From d02eff00d9134e6150cf174cd5f92ad127a7cd5e Mon Sep 17 00:00:00 2001 From: jimmystar Date: Fri, 6 Sep 2013 16:31:21 +0800 Subject: [PATCH 001/557] Update cocos2d_specifics.cpp fix bug about scheduler, if this value is -1, it will work all right in Emulator, but run error in real device, just call one time. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 9edcd1b1c0..09fa749af6 100644 --- a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -cbe012e3979f31ec4001d6a0b65ba46823b497d7 \ No newline at end of file +0850425d8b210a393b8ae220cfd456f4e7907f37 \ No newline at end of file From 357466bab2bb360e4430f29cd7de158def157f78 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Mon, 9 Sep 2013 10:20:32 +0800 Subject: [PATCH 002/557] issue #2768:Add Armature lua binding and releated test samples --- extensions/cocos-ext.h | 7 + .../luaScript/ExtensionTest/ArmatureTest.lua | 815 ++++++++++++++++++ .../luaScript/ExtensionTest/ExtensionTest.lua | 44 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../lua_cocos2dx_extension_manual.cpp | 97 +++ tools/tolua/cocos2dx_extension.ini | 17 +- 6 files changed, 975 insertions(+), 7 deletions(-) create mode 100644 samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua diff --git a/extensions/cocos-ext.h b/extensions/cocos-ext.h index 716f269065..552fe8dc6d 100644 --- a/extensions/cocos-ext.h +++ b/extensions/cocos-ext.h @@ -56,4 +56,11 @@ #include "CCDeprecated-ext.h" +#include "CCArmature/CCArmature.h" +#include "CCArmature/animation/CCArmatureAnimation.h" +#include "CCArmature/display/CCSkin.h" +#include "CCArmature/CCBone.h" +#include "CCArmature/utils/CCArmatureDataManager.h" +#include "CCArmature/datas/CCDatas.h" + #endif /* __COCOS2D_EXT_H__ */ diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua new file mode 100644 index 0000000000..3e7fbaac2e --- /dev/null +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -0,0 +1,815 @@ +local itemTagBasic = 1000 +local winSize = cc.Director:getInstance():getWinSize() +local scheduler = cc.Director:getInstance():getScheduler() +local ArmatureTestIndex = +{ + TEST_COCOSTUDIO_WITH_SKELETON = 1, + TEST_COCOSTUDIO_WITHOUT_SKELETON = 2, + TEST_DRAGON_BONES_2_0 = 3, + TEST_PERFORMANCE = 4, + TEST_CHANGE_ZORDER = 5, + TEST_ANIMATION_EVENT = 6, + TEST_PARTICLE_DISPLAY = 7, + TEST_USE_DIFFERENT_PICTURE = 8, + TEST_BOUDINGBOX = 9, + TEST_ANCHORPOINT = 10, + TEST_ARMATURE_NESTING = 11, +} +local armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON + +local ArmatureTestScene = class("ArmatureTestScene") +ArmatureTestScene.__index = ArmatureTestScene + +function ArmatureTestScene.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, ArmatureTestScene) + return target +end + +function ArmatureTestScene:runThisTest() + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.json") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") + + armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON + self:addChild(restartArmatureTest()) +end + +function ArmatureTestScene.create() + local scene = ArmatureTestScene.extend(cc.Scene:create()) + local bg = cc.Sprite:create("armature/bg.jpg") + bg:setPosition(VisibleRect:center()) + + local scaleX = VisibleRect:getVisibleRect().width / bg:getContentSize().width + local scaleY = VisibleRect:getVisibleRect().height / bg:getContentSize().height + + bg:setScaleX(scaleX) + bg:setScaleY(scaleY) + + scene:addChild(bg) + return scene +end + +function ArmatureTestScene.toMainMenuCallback() + cc.ArmatureDataManager:purgeArmatureSystem() +end + +local ArmatureTestLayer = class("ArmatureTestLayer") +ArmatureTestLayer.__index = ArmatureTestLayer + +function ArmatureTestLayer:onEnter() + +end + +function ArmatureTestLayer.title(idx) + if ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then + return "Test Export From CocoStudio With Skeleton Effect" + elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITHOUT_SKELETON == idx then + return "Test Export From CocoStudio Without Skeleton Effect" + elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then + return "Test Export From DragonBones version 2.0" + elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then + return "Test Performance" + elseif ArmatureTestIndex.TEST_CHANGE_ZORDER == idx then + return "Test Change ZOrder Of Different Armature" + elseif ArmatureTestIndex.TEST_ANIMATION_EVENT == idx then + return "Test Armature Animation Event" + elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then + return "Test Particle Display" + elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then + return "Test One Armature Use Different Picture" + elseif ArmatureTestIndex.TEST_BOUDINGBOX == idx then + return "Test BoundingBox" + elseif ArmatureTestIndex.TEST_ANCHORPOINT == idx then + return "Test Set AnchorPoint" + elseif ArmatureTestIndex.TEST_ARMATURE_NESTING == idx then + return "Test Armature Nesting" + end +end + +function ArmatureTestLayer.subTitle(idx) + if ArmatureTestIndex.TEST_PERFORMANCE == idx then + return "Current Armature Count : " + elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then + return "Touch to change animation" + elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then + return "weapon and armature are in different picture" + else + return "" + end +end + +function ArmatureTestLayer.create() + local layer = ArmatureTestLayer.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +function ArmatureTestLayer.backCallback() + local newScene = ArmatureTestScene.create() + newScene:addChild(backArmatureTest()) + cc.Director:getInstance():replaceScene(newScene) +end + +function ArmatureTestLayer.restartCallback() + local newScene = ArmatureTestScene.create() + newScene:addChild(restartArmatureTest()) + cc.Director:getInstance():replaceScene(newScene) +end + +function ArmatureTestLayer.nextCallback() + local newScene = ArmatureTestScene.create() + newScene:addChild(nextArmatureTest()) + cc.Director:getInstance():replaceScene(newScene) +end + +function ArmatureTestLayer:createMenu() + local menu = cc.Menu:create() + + local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2) + item1:registerScriptTapHandler(self.backCallback) + menu:addChild(item1,itemTagBasic) + local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2) + item2:registerScriptTapHandler(self.restartCallback) + menu:addChild(item2,itemTagBasic) + local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2) + menu:addChild(item3,itemTagBasic) + item3:registerScriptTapHandler(self.nextCallback) + + local size = cc.Director:getInstance():getWinSize() + item1:setPosition(cc.p(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + item2:setPosition(cc.p(size.width / 2, item2:getContentSize().height / 2)) + item3:setPosition(cc.p(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + + menu:setPosition(cc.p(0, 0)) + + self:addChild(menu) +end + +function ArmatureTestLayer.toExtensionMenu() + local scene = ExtensionsTestMain() + if scene ~= nil then + cc.Director:getInstance():replaceScene(scene) + end +end + +function ArmatureTestLayer:createToExtensionMenu() + cc.MenuItemFont:setFontName("Arial") + cc.MenuItemFont:setFontSize(24) + local menuItemFont = cc.MenuItemFont:create("Back") + menuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) + menuItemFont:registerScriptTapHandler(ArmatureTestLayer.toExtensionMenu) + + local backMenu = cc.Menu:create() + backMenu:addChild(menuItemFont) + backMenu:setPosition(cc.p(0, 0)) + self:addChild(backMenu,10) +end + +function ArmatureTestLayer:creatTitleAndSubTitle(idx) + local title = cc.LabelTTF:create(ArmatureTestLayer.title(idx),"Arial",18) + title:setColor(cc.c3b(0,0,0)) + self:addChild(title, 1, 10000) + title:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 30)) + local subTitle = nil + if "" ~= ArmatureTestLayer.subTitle(idx) then + local subTitle = cc.LabelTTF:create(ArmatureTestLayer.subTitle(idx), "Arial", 18) + subTitle:setColor(cc.c3b(0,0,0)) + self:addChild(subTitle, 1, 10001) + subTitle:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 60) ) + end +end + +local TestCSWithSkeleton = class("TestCSWithSkeleton",ArmatureTestLayer) +TestCSWithSkeleton.__index = TestCSWithSkeleton + +function TestCSWithSkeleton.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestCSWithSkeleton) + return target +end + +function TestCSWithSkeleton:onEnter() + local armature = cc.Armature:create("Cowboy") + armature:getAnimation():playByIndex(0) + armature:setScale(0.2) + armature:setAnchorPoint(cc.p(0.5, 0.5)) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) + self:addChild(armature) +end + +function TestCSWithSkeleton.create() + local layer = TestCSWithSkeleton.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) +TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton + +function TestCSWithoutSkeleton.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestCSWithoutSkeleton) + return target +end + +function TestCSWithoutSkeleton:onEnter() + local armature = cc.Armature:create("TestBone") + armature:getAnimation():playByIndex(0) + armature:setScale(0.2) + armature:setAnchorPoint(cc.p(0.5, 0.5)) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) + self:addChild(armature) +end + +function TestCSWithoutSkeleton.create() + local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + return layer +end + +local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer) +TestDragonBones20.__index = TestDragonBones20 + +function TestDragonBones20.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestDragonBones20) + return target +end + +function TestDragonBones20:onEnter() + local armature = cc.Armature:create("Dragon") + armature:getAnimation():playByIndex(1) + armature:getAnimation():setAnimationScale(0.4) + armature:setScale(0.6) + armature:setAnchorPoint(cc.p(0.5, 0.5)) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) + self:addChild(armature) +end + +function TestDragonBones20.create() + local layer = TestDragonBones20.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + return layer +end + +local TestPerformance = class("TestPerformance",ArmatureTestLayer) +TestPerformance.__index = TestPerformance +TestPerformance.armatureCount = 0 +TestPerformance.times = 0 +TestPerformance.testPerformanceEntry = 0 +TestPerformance.selfLayer = nil + +function TestPerformance.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestPerformance) + return target +end + +function TestPerformance.update(delta) + TestPerformance.times = TestPerformance.times + delta + if TestPerformance.times > 0.25 then + TestPerformance.time = 0 + local armature = cc.Armature:create("Knight_f/Knight") + armature:getAnimation():playByIndex(0) + armature:setPosition(cc.p(50 + TestPerformance.armatureCount * 5, winSize.height / 2)) + armature:setScale(0.6) + TestPerformance.armatureCount = TestPerformance.armatureCount + 1 + TestPerformance.selfLayer:addChild(armature,TestPerformance.armatureCount) + + local subTitle = tolua.cast(TestPerformance.selfLayer:getChildByTag(10001),"LabelTTF") + if nil ~= subTitle then + local info = ArmatureTestLayer.subTitle(ArmatureTestIndex.TEST_PERFORMANCE) .. TestPerformance.armatureCount + subTitle:setString(info) + end + end +end + +function TestPerformance.onEnterOrExit(tag) + if tag == "enter" then + TestPerformance.testPerformanceEntry = scheduler:scheduleScriptFunc(TestPerformance.update, 0.0, false) + elseif tag == "exit" then + scheduler:unscheduleScriptEntry(TestPerformance.testPerformanceEntry) + end +end + +function TestPerformance:onEnter() + TestPerformance.armatureCount = 0 + TestPerformance.times = 0 + TestPerformance.selfLayer = nil + self:registerScriptHandler(self.onEnterOrExit) +end + +function TestPerformance.create() + local layer = TestPerformance.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + TestPerformance.selfLayer = layer + end + return layer +end + +local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) +TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton + +function TestCSWithoutSkeleton.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestCSWithoutSkeleton) + return target +end + +function TestCSWithoutSkeleton:onEnter() + local armature = cc.Armature:create("TestBone") + armature:getAnimation():playByIndex(0) + armature:setScale(0.2) + armature:setAnchorPoint(cc.p(0.5, 0.5)) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) + self:addChild(armature) +end + +function TestCSWithoutSkeleton.create() + local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + return layer +end + +local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer) +TestChangeZorder.__index = TestChangeZorder +TestChangeZorder.currentTag = -1 + +function TestChangeZorder.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestChangeZorder) + return target +end + +function TestChangeZorder:onEnter() + self.currentTag = -1 + + local armature = cc.Armature:create("Knight_f/Knight") + armature:getAnimation():playByIndex(0) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 )) + armature:setScale(0.6) + self.currentTag = self.currentTag + 1 + self:addChild(armature, self.currentTag, self.currentTag) + + armature = cc.Armature:create("TestBone") + armature:getAnimation():playByIndex(0) + armature:setScale(0.24) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) + self.currentTag = self.currentTag + 1 + self:addChild(armature, self.currentTag, self.currentTag) + + armature = cc.Armature:create("Dragon") + armature:getAnimation():playByIndex(0) + armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) + armature:setScale(0.6) + self.currentTag = self.currentTag + 1 + self:addChild(armature, self.currentTag, self.currentTag) + + local function changeZorder(dt) + local node = self:getChildByTag(self.currentTag) + node:setZOrder(math.random(0,1) * 3) + self.currentTag = (self.currentTag + 1) % 3 + end + + schedule(self,changeZorder, 1) +end + +function TestChangeZorder.create() + local layer = TestChangeZorder.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + return layer +end + +--UNDO callback +local TestAnimationEvent = class("TestAnimationEvent",ArmatureTestLayer) +TestAnimationEvent.__index = TestAnimationEvent + +function TestAnimationEvent.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestAnimationEvent) + return target +end + +function TestAnimationEvent:onEnter() + local armature = cc.Armature:create("Cowboy") + armature:getAnimation():play("Fire") + armature:setScaleX(-0.24) + armature:setScaleY(0.24) + armature:setPosition(cc.p(VisibleRect:left().x + 50, VisibleRect:left().y)) + --armature:getAnimation()->MovementEventSignal.connect(this, &TestAnimationEvent::animationEvent) + self:addChild(armature) +end + +function TestAnimationEvent.create() + local layer = TestAnimationEvent.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + return layer +end + +local TestParticleDisplay = class("TestParticleDisplay",ArmatureTestLayer) +TestParticleDisplay.__index = TestParticleDisplay +TestParticleDisplay.animationID = 0 +TestParticleDisplay.armature = nil + +function TestParticleDisplay.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestParticleDisplay) + return target +end + +function TestParticleDisplay:onEnter() + self:setTouchEnabled(true) + self.animationID = 0 + + self.armature = cc.Armature:create("robot") + self.armature:getAnimation():playByIndex(0) + self.armature:setPosition(VisibleRect:center()) + self.armature:setScale(0.48) + self:addChild(self.armature) + + local displayData = cc.ParticleDisplayData:create() + displayData:setParam("Particles/SmallSun.plist") + + local bone = cc.Bone:create("p1") + bone:addDisplay(displayData, 0) + bone:changeDisplayByIndex(0, true) + bone:setIgnoreMovementBoneData(true) + bone:setZOrder(100) + bone:setScale(1.2) + self.armature:addBone(bone, "bady-a3") + + bone = cc.Bone:create("p2") + bone:addDisplay(displayData, 0) + bone:changeDisplayByIndex(0, true) + bone:setIgnoreMovementBoneData(true) + bone:setZOrder(100) + bone:setScale(1.2) + self.armature:addBone(bone, "bady-a30") + + local function onTouchBegan(x, y) + self.animationID = (self.animationID + 1) % self.armature:getAnimation():getMovementCount() + self.armature:getAnimation():playByIndex(self.animationID) + return false + end + + local function onTouch(eventType, x, y) + if eventType == "began" then + return onTouchBegan(x,y) + end + end + + self:registerScriptTouchHandler(onTouch) +end + +function TestParticleDisplay.create() + local layer = TestParticleDisplay.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local TestUseMutiplePicture = class("TestUseMutiplePicture",ArmatureTestLayer) +TestUseMutiplePicture.__index = TestUseMutiplePicture +TestUseMutiplePicture.displayIndex = 0 +TestUseMutiplePicture.armature = nil + +function TestUseMutiplePicture.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestUseMutiplePicture) + return target +end + +function TestUseMutiplePicture:onEnter() + self:setTouchEnabled(true) + self.displayIndex = 1 + + self.armature = cc.Armature:create("Knight_f/Knight") + self.armature:getAnimation():playByIndex(0) + self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y)) + self.armature:setScale(1.2) + self:addChild(self.armature) + + local weapon = + { + "weapon_f-sword.png", + "weapon_f-sword2.png", + "weapon_f-sword3.png", + "weapon_f-sword4.png", + "weapon_f-sword5.png", + "weapon_f-knife.png", + "weapon_f-hammer.png", + }; + + local spriteDisplayData = cc.SpriteDisplayData:create() + local i = 1 + for i = 1,table.getn(weapon) do + spriteDisplayData:setParam(weapon[i]) + self.armature:getBone("weapon"):addDisplay(spriteDisplayData, i - 1) + end + + local function onTouchBegan(x, y) + self.displayIndex = (self.displayIndex + 1) % (table.getn(weapon) - 1) + self.armature:getBone("weapon"):changeDisplayByIndex(self.displayIndex, true) + return false + end + + local function onTouch(eventType, x, y) + if eventType == "began" then + return onTouchBegan(x,y) + end + end + + self:registerScriptTouchHandler(onTouch) +end + +function TestUseMutiplePicture.create() + local layer = TestUseMutiplePicture.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local TestBoundingBox = class("TestBoundingBox",ArmatureTestLayer) +TestBoundingBox.__index = TestBoundingBox + +function TestBoundingBox.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestBoundingBox) + return target +end + +function TestBoundingBox:onEnter() + local armature = cc.Armature:create("Cowboy") + armature:getAnimation():playByIndex(0) + armature:setPosition(VisibleRect:center()) + armature:setScale(0.2) + self:addChild(armature) +end + +function TestBoundingBox.create() + local layer = TestBoundingBox.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local TestAnchorPoint = class("TestAnchorPoint",ArmatureTestLayer) +TestAnchorPoint.__index = TestAnchorPoint + +function TestAnchorPoint.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestAnchorPoint) + return target +end + +function TestAnchorPoint:onEnter() + local i = 1 + for i = 1 , 5 do + local armature = cc.Armature:create("Cowboy") + armature:getAnimation():playByIndex(0); + armature:setPosition(VisibleRect:center()) + armature:setScale(0.2) + self:addChild(armature, 0, i - 1) + end + + self:getChildByTag(0):setAnchorPoint(cc.p(0,0)) + self:getChildByTag(1):setAnchorPoint(cc.p(0,1)) + self:getChildByTag(2):setAnchorPoint(cc.p(1,0)) + self:getChildByTag(3):setAnchorPoint(cc.p(1,1)) + self:getChildByTag(4):setAnchorPoint(cc.p(0.5,0.5)) +end + +function TestAnchorPoint.create() + local layer = TestAnchorPoint.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local TestArmatureNesting = class("TestArmatureNesting",ArmatureTestLayer) +TestArmatureNesting.__index = TestArmatureNesting +TestArmatureNesting.weaponIndex = 0 +TestArmatureNesting.armature = nil + +function TestArmatureNesting.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TestArmatureNesting) + return target +end + +function TestArmatureNesting:onEnter() + self:setTouchEnabled(true) + self.weaponIndex = 0 + + self.armature = cc.Armature:create("cyborg") + self.armature:getAnimation():playByIndex(1) + self.armature:setPosition(VisibleRect:center()) + self.armature:setScale(1.2) + self.armature:getAnimation():setAnimationScale(0.4) + self:addChild(self.armature) + + local function onTouchBegan(x, y) + self.weaponIndex = (self.weaponIndex + 1) % 4 + self.armature:getBone("armInside"):getChildArmature():getAnimation():playByIndex(self.weaponIndex) + self.armature:getBone("armOutside"):getChildArmature():getAnimation():playByIndex(self.weaponIndex) + return false + end + + local function onTouch(eventType, x, y) + if eventType == "began" then + return onTouchBegan(x,y) + end + end + + self:registerScriptTouchHandler(onTouch) +end + +function TestArmatureNesting.create() + local layer = TestArmatureNesting.extend(cc.Layer:create()) + + if nil ~= layer then + layer:createMenu() + layer:createToExtensionMenu() + layer:onEnter() + layer:creatTitleAndSubTitle(armatureSceneIdx) + end + + return layer +end + +local armatureSceneArr = +{ + TestCSWithSkeleton.create, + TestCSWithoutSkeleton.create, + TestDragonBones20.create, + TestPerformance.create, + TestChangeZorder.create, + TestAnimationEvent.create, + TestParticleDisplay.create, + TestUseMutiplePicture.create, + TestBoundingBox.create, + TestAnchorPoint.create, + TestArmatureNesting.create, +} + +function nextArmatureTest() + armatureSceneIdx = armatureSceneIdx + 1 + armatureSceneIdx = armatureSceneIdx % table.getn(armatureSceneArr) + if 0 == armatureSceneIdx then + armatureSceneIdx = table.getn(armatureSceneArr) + end + return armatureSceneArr[armatureSceneIdx]() +end + +function backArmatureTest() + armatureSceneIdx = armatureSceneIdx - 1 + if armatureSceneIdx <= 0 then + armatureSceneIdx = armatureSceneIdx + table.getn(armatureSceneArr) + end + + return armatureSceneArr[armatureSceneIdx]() +end + +function restartArmatureTest() + return armatureSceneArr[armatureSceneIdx]() +end + +local function addFileInfo() + +end + +function runArmatureTest() + local newScene = ArmatureTestScene.create() + newScene:runThisTest() + return newScene +end \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua index 0fd38615ee..0197b6ec4e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua @@ -1,5 +1,6 @@ require "luaScript/ExtensionTest/CocosBuilderTest" require "luaScript/ExtensionTest/WebProxyTest" +require "luaScript/ExtensionTest/ArmatureTest" local LINE_SPACE = 40 local kItemTagBasic = 1000 @@ -13,7 +14,8 @@ local ExtensionTestEnum = TEST_EDITBOX = 4, TEST_TABLEVIEW = 5, TEST_SCROLLVIEW = 6, - TEST_MAX_COUNT = 7, + TEST_ARMATURE = 7, + TEST_MAX_COUNT = 8, } local testsName = @@ -25,6 +27,7 @@ local testsName = "EditBoxTest", "TableViewTest", "ScrollViewTest", + "ArmatureTest", } @@ -1190,6 +1193,7 @@ local CreateExtensionsTestTable = runEditBoxTest, runTableViewTest, runScrollViewTest, + runArmatureTest, } @@ -1240,6 +1244,44 @@ local function ExtensionsMainLayer() layer:addChild(menu) + -- handling touch events + local beginPos = {x = 0, y = 0} + local function onTouchBegan(x, y) + beginPos = {x = x, y = y} + return true + end + + local function onTouchMoved(x, y) + local nMoveY = y - beginPos.y + local curPosx, curPosy = menu:getPosition() + local nextPosy = curPosy + nMoveY + local winSize = cc.Director:getInstance():getWinSize() + if nextPosy < 0 then + menu:setPosition(0, 0) + return + end + + if nextPosy > ((ExtensionTestEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height) then + menu:setPosition(0, ((ExtensionTestEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height)) + return + end + + menu:setPosition(curPosx, nextPosy) + beginPos = {x = x, y = y} + end + + local function onTouch(eventType, x, y) + if eventType == "began" then + return onTouchBegan(x, y) + elseif eventType == "moved" then + return onTouchMoved(x, y) + end + end + + layer:setTouchEnabled(true) + + layer:registerScriptTouchHandler(onTouch) + return layer end diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index ef847642e4..b1bce20777 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -a9fdccd58c6cf8ce3cb5d00ea294ef9ff216d439 \ No newline at end of file +2412d119adc08bbb78bebb1bc2e66d0d40b8b146 \ No newline at end of file diff --git a/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp b/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp index 93cf6ce837..fa9416c93e 100644 --- a/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp +++ b/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp @@ -1329,6 +1329,102 @@ static void extendTableView(lua_State* L) } } +static int lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + armature::Bone* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + bool ignore = (bool)tolua_toboolean(L, 2, 0); + self->setIgnoreMovementBoneData(ignore); + return 0; + } + + CCLOG("'setIgnoreMovementBoneData' function of Bone has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setIgnoreMovementBoneData'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + armature::Bone* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + tolua_pushboolean(L, self->getIgnoreMovementBoneData()); + return 1; + } + + CCLOG("'getIgnoreMovementBoneData' function of Bone has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'getIgnoreMovementBoneData'.",&tolua_err); + return 0; +#endif +} + +static void extendBone(lua_State* L) +{ + lua_pushstring(L, "Bone"); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_istable(L,-1)) + { + tolua_function(L, "setIgnoreMovementBoneData", lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData); + tolua_function(L, "getIgnoreMovementBoneData", lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData); + } +} + int register_all_cocos2dx_extension_manual(lua_State* tolua_S) { extendScrollView(tolua_S); @@ -1337,5 +1433,6 @@ int register_all_cocos2dx_extension_manual(lua_State* tolua_S) extendCCBReader(tolua_S); extendCCBAnimationManager(tolua_S); extendTableView(tolua_S); + extendBone(tolua_S); return 0; } diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index 62ccd46dd3..5f35f20cbe 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -26,7 +26,7 @@ headers = %(cocosdir)s/extensions/cocos-ext.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ +classes = CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -45,9 +45,16 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC TableView::[create (g|s)etDataSource$ (g|s)etDelegate], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*] + ControlSwitchSprite::[*], + ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], + Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc], + Skin::[getSkinData setSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent], + Bone::[(s|g)etIgnoreMovementBoneData] -rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] + +rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager], + ArmatureDataManager::[sharedArmatureDataManager=getInstance] rename_classes = CCBReader::_Reader, CCBAnimationManager::AnimationManager @@ -59,11 +66,11 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Object +base_classes_to_skip = Object ProcessBase # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = +abstract_classes = ArmatureDataManager # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no From 567f75c31b49bba84c5c54497c8df268562bcaaa Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Sat, 14 Sep 2013 15:52:41 +0800 Subject: [PATCH 003/557] upload CCArmatureDefine.cpp --- extensions/Android.mk | 4 --- .../Armature/utils/CCArmatureDefine.cpp | 34 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp diff --git a/extensions/Android.mk b/extensions/Android.mk index b0c6196ec7..34af4f3a73 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -69,12 +69,8 @@ CocoStudio/Armature/display/CCBatchNode.cpp \ CocoStudio/Armature/display/CCDecorativeDisplay.cpp \ CocoStudio/Armature/display/CCDisplayFactory.cpp \ CocoStudio/Armature/display/CCDisplayManager.cpp \ -CocoStudio/Armature/display/CCShaderNode.cpp \ CocoStudio/Armature/display/CCSkin.cpp \ -CocoStudio/Armature/external_tool/CCTexture2DMutable.cpp \ -CocoStudio/Armature/external_tool/GLES-Render.cpp \ CocoStudio/Armature/physics/CCColliderDetector.cpp \ -CocoStudio/Armature/physics/CCPhysicsWorld.cpp \ CocoStudio/Armature/utils/CCArmatureDataManager.cpp \ CocoStudio/Armature/utils/CCDataReaderHelper.cpp \ CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.cpp \ diff --git a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp new file mode 100644 index 0000000000..cbd53fe1e0 --- /dev/null +++ b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** +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 "CCArmatureDefine.h" + +NS_CC_EXT_ARMATURE_BEGIN + +const char *armatureVersion() +{ + return "0.4.0.0"; +} + +NS_CC_EXT_ARMATURE_END From 95831eb70f46df1ed75d581f51097f634bcacaa9 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Sat, 14 Sep 2013 20:00:26 +0800 Subject: [PATCH 004/557] issue #2768:Add a newline --- .../TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua index 3e7fbaac2e..7374719740 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -812,4 +812,4 @@ function runArmatureTest() local newScene = ArmatureTestScene.create() newScene:runThisTest() return newScene -end \ No newline at end of file +end From 1e093868c8ff47a9bfefbf6576391a1c1e14e3dd Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Sun, 15 Sep 2013 09:53:08 +0800 Subject: [PATCH 005/557] issue #2768:Modify testlua and hellolua sample's linux mayflies. --- samples/Lua/HelloLua/proj.linux/Makefile | 2 +- samples/Lua/TestLua/proj.linux/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Lua/HelloLua/proj.linux/Makefile b/samples/Lua/HelloLua/proj.linux/Makefile index f0b63ea010..9c80a175dd 100644 --- a/samples/Lua/HelloLua/proj.linux/Makefile +++ b/samples/Lua/HelloLua/proj.linux/Makefile @@ -10,7 +10,7 @@ INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ SOURCES = main.cpp ../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -lextension -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so +COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so $(LIB_DIR)/libbox2d.so include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk diff --git a/samples/Lua/TestLua/proj.linux/Makefile b/samples/Lua/TestLua/proj.linux/Makefile index cb88cc9a93..6d73226774 100644 --- a/samples/Lua/TestLua/proj.linux/Makefile +++ b/samples/Lua/TestLua/proj.linux/Makefile @@ -9,7 +9,7 @@ INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ SOURCES = main.cpp ../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so +COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so $(LIB_DIR)/libbox2d.so include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk From e1acbb6af4098417e4862c9c015088619ba07027 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Sun, 22 Sep 2013 13:53:25 +0800 Subject: [PATCH 006/557] fix setcolor --- extensions/CocoStudio/Armature/CCArmature.cpp | 4 +--- extensions/CocoStudio/Armature/CCBone.cpp | 11 +++++++++++ extensions/CocoStudio/Armature/CCBone.h | 15 +++++++++------ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp index d7817b16b1..8486000dc1 100644 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ b/extensions/CocoStudio/Armature/CCArmature.cpp @@ -128,9 +128,7 @@ bool Armature::init(const char *name) _topBoneList = new Array(); _topBoneList->init(); - - _blendFunc.src = CC_BLEND_SRC; - _blendFunc.dst = CC_BLEND_DST; + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _name = name == NULL ? "" : name; diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp index e6063e51c3..a5f59d7a16 100644 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ b/extensions/CocoStudio/Armature/CCBone.cpp @@ -211,6 +211,17 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } +void Bone::setColor(const Color3B& color) +{ + CCNodeRGBA::setColor(color); + updateColor(); +} +void Bone::setOpacity(GLubyte opacity) +{ + CCNodeRGBA::setOpacity(opacity); + updateColor(); +} + void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); diff --git a/extensions/CocoStudio/Armature/CCBone.h b/extensions/CocoStudio/Armature/CCBone.h index 9f979e616a..1aecfcb099 100644 --- a/extensions/CocoStudio/Armature/CCBone.h +++ b/extensions/CocoStudio/Armature/CCBone.h @@ -122,18 +122,21 @@ public: */ void removeChildBone(Bone *bone, bool recursion); - void update(float delta); + void update(float delta) override; - void updateDisplayedColor(const Color3B &parentColor); - void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void updateDisplayedColor(const Color3B &parentColor) override; + virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; + + virtual void setColor(const Color3B& color) override; + virtual void setOpacity(GLubyte opacity) override; //! Update color to render display - void updateColor(); + virtual void updateColor(); //! Update zorder - void updateZOrder(); + virtual void updateZOrder(); - virtual void setZOrder(int zOrder); + virtual void setZOrder(int zOrder) override; Tween *getTween(); From 90d7abb3ca77d0e927c412098d4a23116380237c Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Mon, 23 Sep 2013 16:48:09 +0800 Subject: [PATCH 007/557] fix add display --- extensions/CocoStudio/Armature/CCArmature.cpp | 26 ++-- extensions/CocoStudio/Armature/CCBone.cpp | 20 ++- .../Armature/display/CCDisplayManager.cpp | 5 +- .../CocoStudio/Armature/display/CCSkin.cpp | 13 +- .../Armature/utils/CCDataReaderHelper.cpp | 114 +++++++++--------- 5 files changed, 95 insertions(+), 83 deletions(-) diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp index 8486000dc1..c5709b0418 100644 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ b/extensions/CocoStudio/Armature/CCArmature.cpp @@ -261,18 +261,12 @@ void Armature::addBone(Bone *bone, const char *parentName) } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } bone->setArmature(this); @@ -338,7 +332,7 @@ Dictionary *Armature::getBoneDic() return _boneDic; } -const AffineTransform& Armature::getNodeToParentTransform() const +const AffineTransform &Armature::getNodeToParentTransform() const { if (_transformDirty) { @@ -387,16 +381,16 @@ const AffineTransform& Armature::getNodeToParentTransform() const // Build Transform Matrix // Adjusted transform calculation for rotational skew _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); + -sx * _scaleY, cx * _scaleY, + x, y ); // XXX: Try to inline skew // If skew is needed, apply skew and then anchor point if (needsSkewMatrix) { AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); + tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, + 0.0f, 0.0f ); _transform = AffineTransformConcat(skewMatrix, _transform); // adjust anchor point @@ -452,7 +446,7 @@ void Armature::update(float dt) Object *object = NULL; CCARRAY_FOREACH(_topBoneList, object) { - static_cast(object)->update(dt); + static_cast(object)->update(dt); } _armatureTransformDirty = false; @@ -523,6 +517,8 @@ void Armature::draw() } } armature->draw(); + + _atlas = armature->getTextureAtlas(); } break; default: @@ -679,7 +675,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) for(int i = length - 1; i >= 0; i--) { - bs = static_cast( _children->getObjectAtIndex(i) ); + bs = static_cast( _children->getObjectAtIndex(i) ); if(bs->getDisplayManager()->containPoint(x, y)) { return bs; diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp index a5f59d7a16..d9ad2bfdc7 100644 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ b/extensions/CocoStudio/Armature/CCBone.cpp @@ -165,6 +165,13 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); + CCBone *armatureParentBone = _armature->getParentBone(); + if (armatureParentBone && !_boneTransformDirty) + { + _boneTransformDirty = armatureParentBone->isTransformDirty(); + } + + if (_boneTransformDirty) { if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) @@ -182,6 +189,13 @@ void Bone::update(float delta) { _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); } + else + { + if (armatureParentBone) + { + _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + } + } } DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); @@ -211,15 +225,15 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } -void Bone::setColor(const Color3B& color) +void Bone::setColor(const Color3B &color) { CCNodeRGBA::setColor(color); - updateColor(); + updateColor(); } void Bone::setOpacity(GLubyte opacity) { CCNodeRGBA::setOpacity(opacity); - updateColor(); + updateColor(); } void Bone::updateColor() diff --git a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp index 01103f392d..ae69ea8230 100644 --- a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp +++ b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp @@ -135,6 +135,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); + ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { @@ -256,8 +257,8 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) if (RGBAProtocol *rgbaProtocaol = dynamic_cast(_displayRenderNode)) { - rgbaProtocaol->setColor(_bone->getDisplayedColor()); - rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); + rgbaProtocaol->setColor(_bone->getDisplayedColor()); + rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); } _displayRenderNode->retain(); diff --git a/extensions/CocoStudio/Armature/display/CCSkin.cpp b/extensions/CocoStudio/Armature/display/CCSkin.cpp index 2fdf2b24af..a35bbffcbe 100644 --- a/extensions/CocoStudio/Armature/display/CCSkin.cpp +++ b/extensions/CocoStudio/Armature/display/CCSkin.cpp @@ -84,10 +84,10 @@ bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) if (ret) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); + TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); - _displayName = pszSpriteFrameName; + _displayName = pszSpriteFrameName; } return ret; @@ -99,10 +99,10 @@ bool Skin::initWithFile(const char *pszFilename) if (ret) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); + TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); - _displayName = pszFilename; + _displayName = pszFilename; } return ret; @@ -118,6 +118,7 @@ void Skin::setSkinData(const BaseData &var) setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); + updateArmatureTransform(); } const BaseData &Skin::getSkinData() const diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp index 76d56a4b8d..a053e4f490 100644 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp @@ -136,7 +136,7 @@ static const char *CONFIG_FILE_PATH = "config_file_path"; NS_CC_EXT_ARMATURE_BEGIN - std::vector s_arrConfigFileList; +std::vector s_arrConfigFileList; float s_PositionReadScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; @@ -169,8 +169,8 @@ void DataReaderHelper::loadData() } else { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); + std::unique_lock lk(_sleepMutex); + _sleepCondition.wait(lk); continue; } } @@ -243,12 +243,12 @@ void DataReaderHelper::clear() } DataReaderHelper::DataReaderHelper() - : _loadingThread(nullptr) - , _asyncStructQueue(nullptr) - , _dataQueue(nullptr) - , need_quit(false) - , _asyncRefCount(0) - , _asyncRefTotalCount(0) + : _loadingThread(nullptr) + , _asyncStructQueue(nullptr) + , _dataQueue(nullptr) + , need_quit(false) + , _asyncRefCount(0) + , _asyncRefTotalCount(0) { } @@ -257,11 +257,11 @@ DataReaderHelper::~DataReaderHelper() { need_quit = true; - _sleepCondition.notify_one(); - if (_loadingThread) _loadingThread->join(); + _sleepCondition.notify_one(); + if (_loadingThread) _loadingThread->join(); - CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; + CC_SAFE_DELETE(_loadingThread); + _dataReaderHelper = NULL; } void DataReaderHelper::addDataFromFile(const char *filePath) @@ -354,15 +354,15 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target _asyncStructQueue = new std::queue(); _dataQueue = new std::queue(); - // create a new thread to load images - _loadingThread = new std::thread(&DataReaderHelper::loadData, this); + // create a new thread to load images + _loadingThread = new std::thread(&DataReaderHelper::loadData, this); need_quit = false; } if (0 == _asyncRefCount) { - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); + Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); } ++_asyncRefCount; @@ -854,26 +854,26 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) + CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; + for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) + { + if (i > 0) + { + float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; + float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } + if (difSkewX < -M_PI || difSkewX > M_PI) + { + frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + } - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } + if (difSkewY < -M_PI || difSkewY > M_PI) + { + frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + } + } + } // @@ -1429,29 +1429,29 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) } - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) - { - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; - for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) + { + //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) + CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; + for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) + { + if (i > 0) + { + float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; + float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } + if (difSkewX < -M_PI || difSkewX > M_PI) + { + frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + } - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - } + if (difSkewY < -M_PI || difSkewY > M_PI) + { + frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + } + } + } + } if (s_CocoStudioVersion < VERSION_COMBINED) { @@ -1478,7 +1478,7 @@ FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); - frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); + frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); const char *event = json.getItemStringValue(A_EVENT); if (event != NULL) @@ -1531,7 +1531,7 @@ TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) { ContourData *contourData = new ContourData(); - contourData->init(); + contourData->init(); int length = json.getArrayItemCount(VERTEX_POINT); for (int i = length - 1; i >= 0; i--) From 6f5e7d540e7039e1ddc818ea997259ac4e2c0b65 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 24 Sep 2013 23:22:07 +0800 Subject: [PATCH 008/557] remove cc --- extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp index a053e4f490..45b63c4db5 100644 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp @@ -855,7 +855,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movBoneData->frameList.data->arr; + FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) { if (i > 0) From dbfd05ef779bab1aa898ab1a7791998430b971e4 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Sun, 29 Sep 2013 09:39:20 +0800 Subject: [PATCH 009/557] issue #2771: add tag and enable functions to physics classes --- .../CCScene.cpp | 2 +- cocos2dx/physics/CCPhysicsBody.cpp | 82 ++++++++++- cocos2dx/physics/CCPhysicsBody.h | 10 ++ cocos2dx/physics/CCPhysicsJoint.cpp | 17 +++ cocos2dx/physics/CCPhysicsJoint.h | 7 + cocos2dx/physics/CCPhysicsShape.cpp | 22 +++ cocos2dx/physics/CCPhysicsShape.h | 6 + cocos2dx/physics/CCPhysicsWorld.cpp | 127 +++++++++++++++--- cocos2dx/physics/CCPhysicsWorld.h | 10 +- .../physics/chipmunk/CCPhysicsShapeInfo.cpp | 8 +- 10 files changed, 260 insertions(+), 31 deletions(-) diff --git a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp index 36f2947dc6..0950fcd0a8 100644 --- a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp +++ b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp @@ -137,7 +137,7 @@ void Scene::addChildToPhysicsWorld(Node* child) if (sp->getPhysicsBody()) { - _physicsWorld->addChild(sp->getPhysicsBody()); + _physicsWorld->addBody(sp->getPhysicsBody()); } } }; diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 3fb5d485b1..2c190eefdd 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -63,12 +63,14 @@ PhysicsBody::PhysicsBody() , _world(nullptr) , _info(nullptr) , _dynamic(false) +, _enable(true) , _massDefault(true) , _angularDampingDefault(true) , _mass(MASS_DEFAULT) , _area(0.0) , _density(DENSITY_DEFAULT) , _angularDamping(ANGULARDAMPING_DEFAULT) +, _tag(0) { } @@ -76,10 +78,7 @@ PhysicsBody::~PhysicsBody() { CC_SAFE_DELETE(_info); - for (auto it = _shapes.begin(); it != _shapes.end(); ++it) - { - delete *it; - } + removeAllShapes(); for (auto it = _joints.begin(); it != _joints.end(); ++it) { @@ -375,6 +374,81 @@ void PhysicsBody::setAngularDamping(float angularDamping) cpBodySetMoment(_info->body, _angularDamping); } +PhysicsShape* PhysicsBody::getShapeByTag(int tag) +{ + for (auto shape : _shapes) + { + if (shape->getTag() == tag) + { + return shape; + } + } + + return nullptr; +} + +void PhysicsBody::removeShapeByTag(int tag) +{ + for (auto shape : _shapes) + { + if (shape->getTag() == tag) + { + removeShape(shape); + return; + } + } +} + +void PhysicsBody::removeShape(PhysicsShape* shape) +{ + auto it = std::find(_shapes.begin(), _shapes.end(), shape); + + if (it != _shapes.end()) + { + if (_world) + { + _world->removeShape(shape); + } + + _shapes.erase(it); + delete shape; + } +} + +void PhysicsBody::removeAllShapes() +{ + for (auto shape : _shapes) + { + if (_world) + { + _world->removeShape(shape); + } + + delete shape; + } + + _shapes.clear(); +} + +void PhysicsBody::setEnable(bool enable) +{ + if (_enable != enable) + { + _enable = enable; + + if (_world) + { + if (enable) + { + _world->addBody(this); + }else + { + _world->removeBody(this); + } + } + } +} + //Clonable* PhysicsBody::clone() const //{ // PhysicsBody* body = new PhysicsBody(); diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 515366e64e..94d30f8b63 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -145,10 +145,12 @@ public: * @brief get the first body shapes. */ inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } + PhysicsShape* getShapeByTag(int tag); /* * @brief remove a shape from body */ void removeShape(PhysicsShape* shape); + void removeShapeByTag(int tag); /* * @brief remove all shapes */ @@ -215,6 +217,12 @@ public: //virtual Clonable* clone() const override; + inline bool isEnable() { return _enable; } + void setEnable(bool enable); + + inline int getTag() { return _tag; } + inline void setTag(int tag) { _tag = tag; } + protected: bool init(); @@ -235,12 +243,14 @@ protected: PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; + bool _enable; bool _massDefault; bool _angularDampingDefault; float _mass; float _area; float _density; float _angularDamping; + int _tag; int _categoryBitmask; int _contactTestBitmask; diff --git a/cocos2dx/physics/CCPhysicsJoint.cpp b/cocos2dx/physics/CCPhysicsJoint.cpp index 3e60d246ab..63b6ac052e 100644 --- a/cocos2dx/physics/CCPhysicsJoint.cpp +++ b/cocos2dx/physics/CCPhysicsJoint.cpp @@ -46,6 +46,8 @@ PhysicsJoint::PhysicsJoint() : _bodyA(nullptr) , _bodyB(nullptr) , _info(nullptr) +, _enable(false) +, _tag(0) { } @@ -79,6 +81,21 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) return false; } +void PhysicsJoint::setEnable(bool enable) +{ + if (_enable != enable) + { + _enable = enable; + + if (enable) + { + + }else + { + + } + } +} PhysicsJointPin::PhysicsJointPin() { diff --git a/cocos2dx/physics/CCPhysicsJoint.h b/cocos2dx/physics/CCPhysicsJoint.h index 854963049d..73383c39b6 100644 --- a/cocos2dx/physics/CCPhysicsJoint.h +++ b/cocos2dx/physics/CCPhysicsJoint.h @@ -49,6 +49,10 @@ protected: public: PhysicsBody* getBodyA() { return _bodyA; } PhysicsBody* getBodyB() { return _bodyB; } + inline int getTag() { return _tag; } + inline void setTag(int tag) { _tag = tag; } + inline bool isEnable() { return _enable; } + void setEnable(bool enable); protected: bool init(PhysicsBody* a, PhysicsBody* b); @@ -62,8 +66,11 @@ protected: PhysicsBody* _bodyA; PhysicsBody* _bodyB; PhysicsJointInfo* _info; + bool _enable; + int _tag; friend class PhysicsBody; + friend class PhysicsWorld; }; /* diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index e98dff0b5c..1ce4cbb3b5 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -32,6 +32,7 @@ #endif #include "CCPhysicsBody.h" +#include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsBodyInfo.h" #include "Box2D/CCPhysicsBodyInfo.h" @@ -45,6 +46,8 @@ PhysicsShape::PhysicsShape() : _body(nullptr) , _info(nullptr) , _type(Type::UNKNOWN) +, _tag(0) +, _enable(true) { } @@ -68,6 +71,25 @@ bool PhysicsShape::init(PhysicsBody* body, Type type) return true; } +void PhysicsShape::setEnable(bool enable) +{ + if (_enable != enable) + { + _enable = enable; + + if (_body->getWorld() && _body->isEnable()) + { + if (enable) + { + _body->getWorld()->addShape(this); + }else + { + _body->getWorld()->removeShape(this); + } + } + } +} + void PhysicsShape::addToBody() { if(_body != nullptr) _body->addShape(this); diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 79cda68e6d..4cc1da148b 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -58,6 +58,10 @@ public: public: inline PhysicsBody* getBody(){ return _body; } inline Type getType() { return _type; } + inline void setTag(int tag) { _tag = tag; } + inline int getTag() { return _tag; } + void setEnable(bool enable); + inline bool isEnable() { return _enable; } protected: bool init(PhysicsBody* body, Type type); @@ -77,6 +81,8 @@ protected: PhysicsBody* _body; PhysicsShapeInfo* _info; Type _type; + int _tag; + bool _enable; friend class PhysicsWorld; friend class PhysicsBody; diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 08857de24b..17b866c6b7 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -34,6 +34,7 @@ #include "CCPhysicsBody.h" #include "CCPhysicsShape.h" #include "CCPhysicsContact.h" +#include "CCPhysicsJoint.h" #include "chipmunk/CCPhysicsWorldInfo.h" #include "Box2D/CCPhysicsWorldInfo.h" @@ -43,6 +44,8 @@ #include "Box2D/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsContactInfo.h" #include "Box2D/CCPhysicsContactInfo.h" +#include "chipmunk/CCPhysicsJointInfo.h" +#include "Box2D/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "draw_nodes/CCDrawNode.h" @@ -110,34 +113,69 @@ bool PhysicsWorld::init() return true; } +void PhysicsWorld::addJoint(PhysicsJoint* joint) +{ + auto it = std::find(_joints.begin(), _joints.end(), joint); + + if (it == _joints.end()) + { + _joints.push_back(joint); + + if (!cpSpaceContainsConstraint(_info->space, joint->_info->joint)) + { + cpSpaceAddConstraint(_info->space, joint->_info->joint); + } + } + +} + +void PhysicsWorld::removeJoint(PhysicsJoint* joint) +{ + +} + +void PhysicsWorld::removeAllJoints() +{ + +} + void PhysicsWorld::addShape(PhysicsShape* shape) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); it++) + for (auto cps : shape->_info->shapes) { + if (cpSpaceContainsShape(_info->space, cps)) + { + continue; + } + if (cpBodyIsStatic(shape->getBody()->_info->body)) { - cpSpaceAddStaticShape(_info->space, *it); + cpSpaceAddStaticShape(_info->space, cps); }else { - cpSpaceAddShape(_info->space, *it); + cpSpaceAddShape(_info->space, cps); } } } -void PhysicsWorld::addChild(PhysicsBody* body) +void PhysicsWorld::addBody(PhysicsBody* body) { - auto shapes = body->getShapes(); - - // add body to space - if (body->isDynamic()) + if (body->isEnable()) { - cpSpaceAddBody(_info->space, body->_info->body); - } - - // add shapes to space - for (auto it = shapes.begin(); it != shapes.end(); it++) - { - addShape(*it); + // add body to space + if (body->isDynamic()) + { + cpSpaceAddBody(_info->space, body->_info->body); + } + + // add shapes to space + for (auto shape : body->getShapes()) + { + if (shape->isEnable()) + { + addShape(shape); + } + } } if (_bodys == nullptr) @@ -150,6 +188,54 @@ void PhysicsWorld::addChild(PhysicsBody* body) } } +void PhysicsWorld::removeBody(PhysicsBody* body) +{ + for (auto shape : body->getShapes()) + { + for (auto cps : shape->_info->shapes) + { + if (cpSpaceContainsShape(_info->space, cps)) + { + cpSpaceRemoveShape(_info->space, cps); + } + } + } + + if (cpSpaceContainsBody(_info->space, body->_info->body)) + { + cpSpaceRemoveBody(_info->space, body->_info->body); + } + + if (_bodys != nullptr) + { + _bodys->removeObject(body); + } +} + +void PhysicsWorld::removeBodyByTag(int tag) +{ + for (Object* obj : *_bodys) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == tag) + { + removeBody(body); + return; + } + } +} + +void PhysicsWorld::removeShape(PhysicsShape* shape) +{ + for (auto cps : shape->_info->shapes) + { + if (cpSpaceContainsShape(_info->space, cps)) + { + cpSpaceRemoveShape(_info->space, cps); + } + } +} + void PhysicsWorld::update(float delta) { cpSpaceStep(_info->space, delta); @@ -171,17 +257,16 @@ void PhysicsWorld::debugDraw() if (_debugDraw && _bodys != nullptr) { _drawNode= DrawNode::create(); - - Object* child = nullptr; - CCARRAY_FOREACH(_bodys, child) + + for (Object* obj : *_bodys) { - PhysicsBody* body = dynamic_cast(child); + PhysicsBody* body = dynamic_cast(obj); std::vector shapes = body->getShapes(); - for (auto it = shapes.begin(); it != shapes.end(); ++it) + for (auto shape : shapes) { - drawWithShape(_drawNode, *it); + drawWithShape(_drawNode, shape); } } diff --git a/cocos2dx/physics/CCPhysicsWorld.h b/cocos2dx/physics/CCPhysicsWorld.h index bd06fdf661..d7a30f37cf 100644 --- a/cocos2dx/physics/CCPhysicsWorld.h +++ b/cocos2dx/physics/CCPhysicsWorld.h @@ -28,6 +28,8 @@ #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include + #include "cocoa/CCObject.h" #include "cocoa/CCGeometry.h" @@ -86,14 +88,18 @@ public: /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } + virtual void removeBody(PhysicsBody* body); + virtual void removeBodyByTag(int tag); + protected: static PhysicsWorld* create(); bool init(); void setScene(Scene* scene); - virtual void addChild(PhysicsBody* body); + virtual void addBody(PhysicsBody* body); virtual void addShape(PhysicsShape* shape); + virtual void removeShape(PhysicsShape* shape); virtual void update(float delta); virtual void debugDraw(); @@ -120,6 +126,7 @@ protected: Array* _bodys; + std::list _joints; Scene* _scene; bool _debugDraw; @@ -132,6 +139,7 @@ protected: friend class Sprite; friend class Scene; friend class PhysicsBody; + friend class PhysicsShape; }; NS_CC_END diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp index 0734bf6e49..0e660792ad 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp @@ -36,12 +36,12 @@ PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) PhysicsShapeInfo::~PhysicsShapeInfo() { - for (auto it = shapes.begin(); it != shapes.end(); it++) + for (auto shape : shapes) { - cpShapeFree(*it); + auto it = map.find(shape); + if (it != map.end()) map.erase(shape); - auto mit = map.find(*it); - if (mit != map.end()) map.erase(*it); + cpShapeFree(shape); } } From 3dbe74db1aafd84bf217a8c496e2782e70d1dac3 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Sun, 29 Sep 2013 15:09:53 +0800 Subject: [PATCH 010/557] issue #2771: refactor PhysicsTest --- .../Classes/PhysicsTest/PhysicsTest.cpp | 267 +++++++++++------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 38 ++- 2 files changed, 200 insertions(+), 105 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 94f63e7f59..00d81cbd0f 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -2,40 +2,172 @@ #include "../testResource.h" USING_NS_CC; -PhysicsTestLayer::PhysicsTestLayer() -: _spriteTexture(nullptr) -, _scene(nullptr) + + +static std::function createFunctions[] = { + + CL(PhysicsDemoClickAdd), +}; + +static int sceneIdx=-1; +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +namespace { + static Layer* next() + { + sceneIdx++; + sceneIdx = sceneIdx % MAX_LAYER; + + auto layer = (createFunctions[sceneIdx])(); + layer->init(); + layer->autorelease(); + + return layer; + } + + static Layer* back() + { + sceneIdx--; + int total = MAX_LAYER; + if( sceneIdx < 0 ) + sceneIdx += total; + + auto layer = (createFunctions[sceneIdx])(); + layer->init(); + layer->autorelease(); + + return layer; + } + + static Layer* restart() + { + auto layer = (createFunctions[sceneIdx])(); + layer->init(); + layer->autorelease(); + + return layer; + } +} + +bool PhysicsTestScene::initTest() +{ +#ifdef CC_USE_PHYSICS + if (TestScene::initWithPhysics()) + { + this->getPhysicsWorld()->setDebugDraw(true); + return true; + } +#else + return TestScene::init(); +#endif + + return false; +} + +void PhysicsTestScene::runThisTest() +{ +#ifdef CC_USE_PHYSICS + sceneIdx = -1; + addChild(next()); + + Director::getInstance()->replaceScene(this); +#else +#endif +} + +PhysicsDemo::PhysicsDemo() +: _scene(nullptr) +{ + +} + +PhysicsDemo::~PhysicsDemo() +{ + +} + +std::string PhysicsDemo::title() +{ + return "PhysicsTest"; +} + +std::string PhysicsDemo::subtitle() +{ + return ""; +} + +void PhysicsDemo::restartCallback(Object* sender) +{ + auto s = new PhysicsTestScene(); + s->addChild( restart() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void PhysicsDemo::nextCallback(Object* sender) +{ + auto s = new PhysicsTestScene(); + s->addChild( next() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void PhysicsDemo::backCallback(Object* sender) +{ + auto s = new PhysicsTestScene(); + s->addChild( back() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void PhysicsDemo::onEnter() +{ + BaseTest::onEnter(); + + _scene = dynamic_cast(this->getParent()); +#ifdef CC_USE_PHYSICS + // menu for debug layer + MenuItemFont::setFontSize(18); + auto item = MenuItemFont::create("Toggle debug", CC_CALLBACK_1(PhysicsDemo::toggleDebugCallback, this)); + + auto menu = Menu::create(item, NULL); + this->addChild(menu); + menu->setPosition(Point(VisibleRect::right().x-50, VisibleRect::top().y-10)); +#else +#endif +} + + +void PhysicsDemo::toggleDebugCallback(Object* sender) +{ +#ifdef CC_USE_PHYSICS + if (_scene != nullptr) + { + _scene->getPhysicsWorld()->setDebugDraw(!_scene->getPhysicsWorld()->isDebugDraw()); + } +#endif +} + +void PhysicsDemoClickAdd::onEnter() +{ + PhysicsDemo::onEnter(); + #ifdef CC_USE_PHYSICS setTouchEnabled(true); setAccelerometerEnabled(true); - // title - auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36); - label->setPosition(Point( VisibleRect::center().x, VisibleRect::top().y - 30)); - this->addChild(label, -1); - - // menu for debug layer - MenuItemFont::setFontSize(18); - auto item = MenuItemFont::create("Toggle debug", CC_CALLBACK_1(PhysicsTestLayer::toggleDebugCallback, this)); - - auto menu = Menu::create(item, NULL); - this->addChild(menu); - menu->setPosition(Point(VisibleRect::right().x-100, VisibleRect::top().y-60)); - auto sp = Sprite::create(); auto body = PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size); sp->setPhysicsBody(body); - this->addChild(sp); sp->setPosition(VisibleRect::center()); + this->addChild(sp); auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); _spriteTexture = parent->getTexture(); addNewSpriteAtPosition(VisibleRect::center()); - createResetButton(); - #else auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", "Arial", @@ -47,41 +179,33 @@ PhysicsTestLayer::PhysicsTestLayer() #endif } -void PhysicsTestLayer::toggleDebugCallback(Object* sender) +void PhysicsDemoClickAdd::addNewSpriteAtPosition(Point p) { #ifdef CC_USE_PHYSICS - if (_scene != nullptr) - { - _scene->getPhysicsWorld()->setDebugDraw(!_scene->getPhysicsWorld()->isDebugDraw()); - } + CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); + + int posx, posy; + + posx = CCRANDOM_0_1() * 200.0f; + posy = CCRANDOM_0_1() * 200.0f; + + posx = (posx % 4) * 85; + posy = (posy % 3) * 121; + + auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); + auto body = PhysicsBody::createBox(Size(48, 108)); + sp->setPhysicsBody(body); + this->addChild(sp); + sp->setPosition(p); #endif } -PhysicsTestLayer::~PhysicsTestLayer() +std::string PhysicsDemoClickAdd::subtitle() { + return "multi touch to add grossini"; } -void PhysicsTestLayer::createResetButton() -{ - auto reset = MenuItemImage::create("Images/r1.png", "Images/r2.png", [](Object *sender) { - auto s = new PhysicsTestScene(); - s->initTest(); - auto child = new PhysicsTestLayer(); - child->setScene(s); - s->addChild(child); - child->release(); - Director::getInstance()->replaceScene(s); - s->release(); - }); - - auto menu = Menu::create(reset, NULL); - - menu->setPosition(Point(VisibleRect::bottom().x, VisibleRect::bottom().y + 30)); - this->addChild(menu, -1); - -} - -void PhysicsTestLayer::onTouchesEnded(const std::vector& touches, Event* event) +void PhysicsDemoClickAdd::onTouchesEnded(const std::vector& touches, Event* event) { //Add a new body/atlas sprite at the touched location @@ -93,8 +217,7 @@ void PhysicsTestLayer::onTouchesEnded(const std::vector& touches, Event* } } - -void PhysicsTestLayer::onAcceleration(Acceleration* acc, Event* event) +void PhysicsDemoClickAdd::onAcceleration(Acceleration* acc, Event* event) { #ifdef CC_USE_PHYSICS static float prevX=0, prevY=0; @@ -115,50 +238,4 @@ void PhysicsTestLayer::onAcceleration(Acceleration* acc, Event* event) _scene->getPhysicsWorld()->setGravity(v); } #endif -} - -void PhysicsTestLayer::addNewSpriteAtPosition(Point p) -{ -#ifdef CC_USE_PHYSICS - CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); - - int posx, posy; - - posx = CCRANDOM_0_1() * 200.0f; - posy = CCRANDOM_0_1() * 200.0f; - - posx = (posx % 4) * 85; - posy = (posy % 3) * 121; - - auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); - auto body = PhysicsBody::createBox(Size(48, 108)); - sp->setPhysicsBody(body); - sp->setPosition(p); - this->addChild(sp); -#endif -} - -bool PhysicsTestScene::initTest() -{ -#ifdef CC_USE_PHYSICS - if (TestScene::initWithPhysics()) - { - this->getPhysicsWorld()->setDebugDraw(true); - return true; - } -#else - return TestScene::init(); -#endif - - return false; -} - -void PhysicsTestScene::runThisTest() -{ - auto layer = new PhysicsTestLayer(); - layer->setScene(this); - addChild(layer); - layer->release(); - - Director::getInstance()->replaceScene(this); -} +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 3c95ed90c8..5acb33e855 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -3,24 +3,42 @@ #include "cocos2d.h" #include "../testBasic.h" +#include "../BaseTest.h" -class PhysicsTestLayer : public Layer + +class PhysicsDemo : public BaseTest { - Texture2D* _spriteTexture; // weak ref +protected: Scene* _scene; public: - PhysicsTestLayer(); - ~PhysicsTestLayer(); - - void createResetButton(); + PhysicsDemo(); + virtual ~PhysicsDemo(); - inline void setScene(Scene* scene) { _scene = scene; } + virtual void onEnter(); + virtual std::string title(); + virtual std::string subtitle(); + + void restartCallback(Object* sender); + void nextCallback(Object* sender); + void backCallback(Object* sender); void toggleDebugCallback(Object* sender); +}; + +class PhysicsDemoClickAdd : public PhysicsDemo +{ +private: + Texture2D* _spriteTexture; // weak ref + +public: + void onEnter(); + std::string subtitle(); + void addNewSpriteAtPosition(Point p); - virtual void onTouchesEnded(const std::vector& touches, Event* event) override; - virtual void onAcceleration(Acceleration* acc, Event* event) override; -} ; + + void onTouchesEnded(const std::vector& touches, Event* event); + void onAcceleration(Acceleration* acc, Event* event); +}; class PhysicsTestScene : public TestScene { From 18a4b18368cd2977f875ead4e4548ebf960b9e5a Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 30 Sep 2013 13:02:17 +0800 Subject: [PATCH 011/557] issue #2771: move _physicsBody from sprite to node --- cocos2dx/base_nodes/CCNode.cpp | 62 +++++++++++++++++++ cocos2dx/base_nodes/CCNode.h | 23 +++++++ .../CCScene.cpp | 10 +-- cocos2dx/physics/CCPhysicsBody.cpp | 13 ++-- cocos2dx/physics/CCPhysicsBody.h | 2 +- cocos2dx/physics/CCPhysicsWorld.cpp | 4 ++ cocos2dx/sprite_nodes/CCSprite.cpp | 47 -------------- cocos2dx/sprite_nodes/CCSprite.h | 18 ------ .../Classes/PhysicsTest/PhysicsTest.cpp | 26 ++++---- 9 files changed, 115 insertions(+), 90 deletions(-) diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp index f4547bb1fa..95f1a94987 100644 --- a/cocos2dx/base_nodes/CCNode.cpp +++ b/cocos2dx/base_nodes/CCNode.cpp @@ -44,6 +44,10 @@ THE SOFTWARE. #include "event_dispatcher/CCEvent.h" #include "event_dispatcher/CCEventTouch.h" +#ifdef CC_USE_PHYSICS +#include "physics/CCPhysicsBody.h" +#endif + // externals #include "kazmath/GL/matrix.h" #include "support/component/CCComponent.h" @@ -128,6 +132,11 @@ Node::Node(void) , _componentContainer(NULL) , _eventPriority(0) , _oldEventPriority(0) +#ifdef CC_USE_PHYSICS +, _physicsBody(nullptr) +, _physicsPositionMark(true) +, _physicsRotationMark(true) +#endif { // set default scheduler and actionManager Director *director = Director::getInstance(); @@ -179,6 +188,10 @@ Node::~Node() CC_SAFE_DELETE(_componentContainer); removeAllEventListeners(); + +#ifdef CC_USE_PHYSICS + CC_SAFE_RELEASE(_physicsBody); +#endif } bool Node::init() @@ -257,6 +270,15 @@ void Node::setRotation(float newRotation) { _rotationX = _rotationY = newRotation; _transformDirty = _inverseDirty = true; + +#ifdef CC_USE_PHYSICS + if (_physicsBody && _physicsRotationMark) + { + _physicsBody->setRotation(newRotation); + } + + _physicsRotationMark = true; +#endif } float Node::getRotationX() const @@ -332,6 +354,15 @@ void Node::setPosition(const Point& newPosition) { _position = newPosition; _transformDirty = _inverseDirty = true; + +#ifdef CC_USE_PHYSICS + if (_physicsBody && _physicsPositionMark) + { + _physicsBody->setPosition(newPosition); + } + + _physicsPositionMark = true; +#endif } void Node::getPosition(float* x, float* y) const @@ -800,6 +831,17 @@ void Node::visit() { return; } + +#ifdef CC_USE_PHYSICS + if (_physicsBody) + { + _physicsPositionMark = false; + _physicsRotationMark = false; + setPosition(_physicsBody->getPosition()); + setRotation(_physicsBody->getRotation()); + } +#endif + kmGLPushMatrix(); if (_grid && _grid->isActive()) @@ -1329,6 +1371,26 @@ void Node::setDirtyForAllEventListeners() } } +#ifdef CC_USE_PHYSICS +void Node::setPhysicsBody(PhysicsBody* body) +{ + if (_physicsBody != nullptr) + { + _physicsBody->release(); + } + + _physicsBody = body; + _physicsBody->retain(); + _physicsBody->setPosition(getPosition()); + _physicsBody->setRotation(getRotation()); +} + +PhysicsBody* Node::getPhysicsBody() const +{ + return _physicsBody; +} +#endif //CC_USE_PHYSICS + // NodeRGBA NodeRGBA::NodeRGBA() : _displayedOpacity(255) diff --git a/cocos2dx/base_nodes/CCNode.h b/cocos2dx/base_nodes/CCNode.h index e335ff11fd..41d16dbcf3 100644 --- a/cocos2dx/base_nodes/CCNode.h +++ b/cocos2dx/base_nodes/CCNode.h @@ -38,6 +38,7 @@ #include "script_support/CCScriptSupport.h" #include "CCProtocols.h" #include "event_dispatcher/CCEventDispatcher.h" +#include "physics/CCPhysicsSetting.h" #include @@ -56,6 +57,9 @@ class Component; class Dictionary; class ComponentContainer; class EventDispatcher; +#ifdef CC_USE_PHYSICS +class PhysicsBody; +#endif /** * @addtogroup base_nodes @@ -1365,6 +1369,19 @@ public: */ virtual void removeAllComponents(); /// @} end of component functions + + +#ifdef CC_USE_PHYSICS + /** + * set the PhysicsBody that let the sprite effect with physics + */ + virtual void setPhysicsBody(PhysicsBody* body); + + /** + * get the PhysicsBody the sprite have + */ + PhysicsBody* getPhysicsBody() const; +#endif private: @@ -1477,6 +1494,12 @@ protected: int _eventPriority; ///< The scene graph based priority of event listener. int _oldEventPriority; ///< The old scene graph based priority of event listener. static int _globalEventPriorityIndex; ///< The index of global event priority. + +#ifdef CC_USE_PHYSICS + PhysicsBody* _physicsBody; ///< the physicsBody the node have + bool _physicsPositionMark; ///< set this mark to false will skip the setRotation to physicsBody one time + bool _physicsRotationMark; ///< set this mark to false will skip the setPosition to physicsBody one time +#endif }; //#pragma mark - NodeRGBA diff --git a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp index 0950fcd0a8..50b67e50e0 100644 --- a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp +++ b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp @@ -129,15 +129,15 @@ void Scene::addChildToPhysicsWorld(Node* child) { if (_physicsWorld) { - auto addToPhysicsWorldFunc = [this](Object* node) -> void + auto addToPhysicsWorldFunc = [this](Object* child) -> void { - if (dynamic_cast(node) != nullptr) + if (dynamic_cast(child) != nullptr) { - Sprite* sp = dynamic_cast(node); + Node* node = dynamic_cast(child); - if (sp->getPhysicsBody()) + if (node->getPhysicsBody()) { - _physicsWorld->addBody(sp->getPhysicsBody()); + _physicsWorld->addBody(node->getPhysicsBody()); } } }; diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 2c190eefdd..32f41fd649 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -273,16 +273,19 @@ bool PhysicsBody::init() void PhysicsBody::setDynamic(bool dynamic) { - _dynamic = dynamic; - if (_world != nullptr && cpBodyIsStatic(_info->body) == (cpBool)_dynamic) + if (dynamic != _dynamic) { if (dynamic) { - cpSpaceConvertBodyToDynamic(_world->_info->space, _info->body, _mass, _angularDamping); + cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_angularDamping)); }else { - cpSpaceConvertBodyToStatic(_world->_info->space, _info->body); + cpBodySetMass(_info->body, INFINITY); + cpBodySetMoment(_info->body, INFINITY); } + + _dynamic = dynamic; } } @@ -293,7 +296,7 @@ bool PhysicsBody::initStatic() _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); - _info->body = cpBodyNewStatic(); + _info->body = cpBodyNew(INFINITY, INFINITY); CC_BREAK_IF(_info->body == nullptr); _dynamic = false; diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 94d30f8b63..9bca83b3c0 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -259,7 +259,7 @@ protected: friend class PhysicsWorld; friend class PhysicsShape; friend class PhysicsJoint; - friend class Sprite; + friend class Node; }; NS_CC_END diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index b67ac5a65a..580fd5fe75 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -186,6 +186,8 @@ void PhysicsWorld::addBody(PhysicsBody* body) { _bodys->addObject(body); } + + body->retain(); } void PhysicsWorld::removeBody(PhysicsBody* body) @@ -210,6 +212,8 @@ void PhysicsWorld::removeBody(PhysicsBody* body) { _bodys->removeObject(body); } + + body->release(); } void PhysicsWorld::removeBodyByTag(int tag) diff --git a/cocos2dx/sprite_nodes/CCSprite.cpp b/cocos2dx/sprite_nodes/CCSprite.cpp index 741a1e1683..e1cfd9b5da 100644 --- a/cocos2dx/sprite_nodes/CCSprite.cpp +++ b/cocos2dx/sprite_nodes/CCSprite.cpp @@ -296,18 +296,12 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) Sprite::Sprite(void) : _shouldBeHidden(false) , _texture(nullptr) -#ifdef CC_USE_PHYSICS -, _physicsBody(nullptr) -#endif { } Sprite::~Sprite(void) { CC_SAFE_RELEASE(_texture); -#ifdef CC_USE_PHYSICS - CC_SAFE_RELEASE(_physicsBody); -#endif } void Sprite::setTextureRect(const Rect& rect) @@ -790,13 +784,6 @@ void Sprite::setPosition(const Point& pos) { Node::setPosition(pos); SET_DIRTY_RECURSIVELY(); - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setPosition(pos); - } -#endif } void Sprite::setRotation(float rotation) @@ -804,13 +791,6 @@ void Sprite::setRotation(float rotation) Node::setRotation(rotation); SET_DIRTY_RECURSIVELY(); - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setRotation(rotation); - } -#endif } void Sprite::setRotationX(float fRotationX) @@ -907,33 +887,6 @@ bool Sprite::isFlippedY(void) const return _flippedY; } -#ifdef CC_USE_PHYSICS -void Sprite::setPhysicsBody(PhysicsBody* body) -{ - _physicsBody = body; - _physicsBody->retain(); - _physicsBody->setPosition(getPosition()); - _physicsBody->setRotation(getRotation()); -} - -PhysicsBody* Sprite::getPhysicsBody() const -{ - return _physicsBody; -} - -void Sprite::visit() -{ - if (_physicsBody) - { - Node::setPosition(_physicsBody->getPosition()); - Node::setRotation(_physicsBody->getRotation()); - SET_DIRTY_RECURSIVELY(); - } - - Node::visit(); -} -#endif //CC_USE_PHYSICS - // // RGBA protocol // diff --git a/cocos2dx/sprite_nodes/CCSprite.h b/cocos2dx/sprite_nodes/CCSprite.h index 815cd67614..d150c55213 100644 --- a/cocos2dx/sprite_nodes/CCSprite.h +++ b/cocos2dx/sprite_nodes/CCSprite.h @@ -461,20 +461,6 @@ public: */ void setFlippedY(bool flippedY); -#ifdef CC_USE_PHYSICS - /** - * set the PhysicsBody that let the sprite effect with physics - */ - virtual void setPhysicsBody(PhysicsBody* body); - - /** - * get the PhysicsBody the sprite have - */ - PhysicsBody* getPhysicsBody() const; - - virtual void visit() override; -#endif - /// @} End of Sprite properties getter/setters /** @deprecated Use isFlippedY() instead */ @@ -590,10 +576,6 @@ protected: // image is flipped bool _flippedX; /// Whether the sprite is flipped horizaontally or not. bool _flippedY; /// Whether the sprite is flipped vertically or not. - -#ifdef CC_USE_PHYSICS - PhysicsBody* _physicsBody; ///< the physicsBody the node have -#endif }; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 00d81cbd0f..db4c3d46ab 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -2,18 +2,16 @@ #include "../testResource.h" USING_NS_CC; - - -static std::function createFunctions[] = { - - CL(PhysicsDemoClickAdd), -}; - -static int sceneIdx=-1; -#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) - namespace { + static std::function createFunctions[] = { + + CL(PhysicsDemoClickAdd), + }; + + static int sceneIdx=-1; +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + static Layer* next() { sceneIdx++; @@ -157,11 +155,11 @@ void PhysicsDemoClickAdd::onEnter() setTouchEnabled(true); setAccelerometerEnabled(true); - auto sp = Sprite::create(); + auto node = Node::create(); auto body = PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size); - sp->setPhysicsBody(body); - sp->setPosition(VisibleRect::center()); - this->addChild(sp); + node->setPhysicsBody(body); + node->setPosition(VisibleRect::center()); + this->addChild(node); auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); _spriteTexture = parent->getTexture(); From 6aa18423e6ed8ab5edb6df0d8a4808f64189dcf7 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Mon, 30 Sep 2013 16:22:55 +0800 Subject: [PATCH 012/557] issue #2792 : Performance Test: Sprite drawing --- cocos2dx/CCDirector.h | 5 + .../PerformanceTest/PerformanceSpriteTest.cpp | 290 +++++++++++++++++- .../PerformanceTest/PerformanceSpriteTest.h | 26 +- 3 files changed, 312 insertions(+), 9 deletions(-) diff --git a/cocos2dx/CCDirector.h b/cocos2dx/CCDirector.h index 8b61b12a96..9cc20393ea 100644 --- a/cocos2dx/CCDirector.h +++ b/cocos2dx/CCDirector.h @@ -353,6 +353,11 @@ public: void setActionManager(ActionManager* actionManager); /* Gets delta time since last tick to main loop */ float getDeltaTime() const; + + /** + * get Frame Rate + */ + float getFrameRate() const { return _frameRate; } protected: void purgeDirector(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 76c423fb82..b00cef317c 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -10,11 +10,10 @@ enum { enum { kTagInfoLayer = 1, kTagMainLayer = 2, + kTagAutoTestMenu = 3, kTagMenuLayer = (kMaxNodes + 1000), }; -static int s_nSpriteCurCase = 0; - //////////////////////////////////////////////////////// // // SubTest @@ -227,6 +226,37 @@ void SubTest::removeByTag(int tag) // SpriteMenuLayer // //////////////////////////////////////////////////////// +void SpriteMenuLayer::restartCallback(Object* sender) +{ + if ( SpriteMainScene::_s_autoTest ) + { + log("It's auto sprite performace testing,so this operation is invalid"); + return; + } + + PerformBasicLayer::restartCallback(sender); +} +void SpriteMenuLayer::nextCallback(Object* sender) +{ + if ( SpriteMainScene::_s_autoTest ) + { + log("It's auto sprite performace testing,so this operation is invalid"); + return; + } + + PerformBasicLayer::nextCallback(sender); +} +void SpriteMenuLayer::backCallback(Object* sender) +{ + if ( SpriteMainScene::_s_autoTest ) + { + log("It's auto sprite performace testing,so this operation is invalid"); + return; + } + + PerformBasicLayer::backCallback(sender); +} + void SpriteMenuLayer::showCurrentTest() { SpriteMainScene* scene = NULL; @@ -258,7 +288,8 @@ void SpriteMenuLayer::showCurrentTest() scene = new SpritePerformTest7; break; } - s_nSpriteCurCase = _curCase; + + SpriteMainScene::_s_nSpriteCurCase = _curCase; if (scene) { @@ -267,12 +298,15 @@ void SpriteMenuLayer::showCurrentTest() scene->release(); } } - //////////////////////////////////////////////////////// // // SpriteMainScene // //////////////////////////////////////////////////////// + +bool SpriteMainScene::_s_autoTest = false; +int SpriteMainScene::_s_nSpriteCurCase = 0; + void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) { //srandom(0); @@ -303,10 +337,33 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) addChild(infoLabel, 1, kTagInfoLayer); // add menu - auto menuLayer = new SpriteMenuLayer(true, TEST_COUNT, s_nSpriteCurCase); + auto menuLayer = new SpriteMenuLayer(true, TEST_COUNT, SpriteMainScene::_s_nSpriteCurCase); addChild(menuLayer, 1, kTagMenuLayer); menuLayer->release(); - + + /** + * auto test menu + */ + + auto menuAutoTest = Menu::create(); + menuAutoTest->setPosition( Point::ZERO ); + MenuItemFont::setFontName("Arial"); + MenuItemFont::setFontSize(24); + + MenuItemFont* autoTestItem = NULL; + if (SpriteMainScene::_s_autoTest) + { + autoTestItem = MenuItemFont::create("Auto Test On",CC_CALLBACK_1(SpriteMainScene::onAutoTest, this)); + } + else + { + autoTestItem = MenuItemFont::create("Auto Test Off",CC_CALLBACK_1(SpriteMainScene::onAutoTest, this)); + } + autoTestItem->setTag(1); + autoTestItem->setPosition(Point( s.width - 90, s.height / 2)); + menuAutoTest->addChild(autoTestItem); + addChild( menuAutoTest, 3, kTagAutoTestMenu ); + // Sub Tests MenuItemFont::setFontSize(32); auto subMenu = Menu::create(); @@ -356,6 +413,12 @@ SpriteMainScene::~SpriteMainScene() void SpriteMainScene::testNCallback(Object* sender) { + if (SpriteMainScene::_s_autoTest) + { + log("It's auto sprite performace testing,so this operation is invalid"); + return; + } + subtestNumber = static_cast(sender)->getTag(); auto menu = static_cast( getChildByTag(kTagMenuLayer) ); menu->restartCallback(sender); @@ -375,7 +438,7 @@ void SpriteMainScene::updateNodes() } void SpriteMainScene::onIncrease(Object* sender) -{ +{ if( quantityNodes >= kMaxNodes) return; @@ -391,6 +454,7 @@ void SpriteMainScene::onIncrease(Object* sender) void SpriteMainScene::onDecrease(Object* sender) { + if( quantityNodes <= 0 ) return; @@ -403,6 +467,216 @@ void SpriteMainScene::onDecrease(Object* sender) updateNodes(); } +void SpriteMainScene::dumpProfilerFPS() +{ + if (_vecFPS.empty()) + { + log("Error: the FPS vector is empty"); + return; + } + + auto iter = _vecFPS.begin(); + float minFPS = *iter; + float maxFPS = *iter; + float totalFPS = 0.0f; + float averagerFPS = 0.0f; + for (; iter != _vecFPS.end(); ++iter) + { + if (minFPS > *iter) + { + minFPS = *iter; + } + + if (maxFPS < *iter) + { + maxFPS = *iter; + } + + totalFPS += *iter; + } + + averagerFPS = totalFPS / _vecFPS.size(); + log("Cur test: %d, cur sub item :%d,cur sprite nums:%d, the min FPS value is %.1f,the max FPS value is %.1f,the averager FPS is %.1f", SpriteMainScene::_s_nSpriteCurCase, subtestNumber, quantityNodes, minFPS, maxFPS, averagerFPS); + +} + +void SpriteMainScene::updateAutoTest(float dt) +{ + if (SpriteMainScene::_s_autoTest) + { + _executeTimes += 1; + _vecFPS.push_back(Director::getInstance()->getFrameRate()); + if ( _executeTimes >= SpriteMainScene::MAX_AUTO_TEST_TIMES ) + { + dumpProfilerFPS(); + nextAutoTest(); + } + } +} + +void SpriteMainScene::onEnter() +{ + Scene::onEnter(); + + if ( SpriteMainScene::_s_autoTest ) + { + _vecFPS.clear(); + _executeTimes = 0; + + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->scheduleSelector(SEL_SCHEDULE(&SpriteMainScene::updateAutoTest), this, 0.2, false); + + } +} + +void SpriteMainScene::onExit() +{ + if ( SpriteMainScene::_s_autoTest ) + { + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(SEL_SCHEDULE(&SpriteMainScene::updateAutoTest), this ); + } + + Scene::onExit(); +} + +void SpriteMainScene::autoShowSpriteTests(int curCase, int subTest,int nodes) +{ + + SpriteMainScene* scene = NULL; + + switch (curCase) + { + case 0: + scene = new SpritePerformTest1; + break; + case 1: + scene = new SpritePerformTest2; + break; + case 2: + scene = new SpritePerformTest3; + break; + case 3: + scene = new SpritePerformTest4; + break; + case 4: + scene = new SpritePerformTest5; + break; + case 5: + scene = new SpritePerformTest6; + break; + case 6: + scene = new SpritePerformTest7; + break; + } + + SpriteMainScene::_s_nSpriteCurCase = curCase; + + if (scene) + { + scene->initWithSubTest(subTest, nodes); + Director::getInstance()->replaceScene(scene); + scene->release(); + } +} + +void SpriteMainScene::beginAutoTest() +{ + if (0 != SpriteMainScene::_s_nSpriteCurCase) + { + SpriteMainScene::_s_nSpriteCurCase = 0; + } + + auto scene = new SpritePerformTest1; + scene->initWithSubTest(1, 500); + Director::getInstance()->replaceScene(scene); + scene->release(); +} + +void SpriteMainScene::endAutoTest() +{ + SpriteMainScene::_s_autoTest = false; + + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector( SEL_SCHEDULE( &SpriteMainScene::updateAutoTest ), this ); +} + +void SpriteMainScene::nextAutoTest() +{ + if ( SpriteMainScene::_s_nSpriteCurCase < SpriteMainScene::MAX_SPRITE_TEST_CASE ) + { + if ( subtestNumber < SpriteMainScene::MAX_SUB_TEST_NUMS ) + { + subtestNumber += 1; + autoShowSpriteTests(SpriteMainScene::_s_nSpriteCurCase, subtestNumber, quantityNodes); + } + else if ( subtestNumber == SpriteMainScene::MAX_SUB_TEST_NUMS ) + { + if (quantityNodes == SpriteMainScene::AUTO_TEST_NODE_NUM1) + { + autoShowSpriteTests(SpriteMainScene::_s_nSpriteCurCase, 1, SpriteMainScene::AUTO_TEST_NODE_NUM2); + } + else + { + if (SpriteMainScene::_s_nSpriteCurCase + 1 < SpriteMainScene::MAX_SPRITE_TEST_CASE) + { + SpriteMainScene::_s_nSpriteCurCase += 1; + autoShowSpriteTests(SpriteMainScene::_s_nSpriteCurCase, 1, SpriteMainScene::AUTO_TEST_NODE_NUM1); + } + else + { + finishAutoTest(); + } + } + } + } +} + +void SpriteMainScene::finishAutoTest() +{ + SpriteMainScene::_s_autoTest = false; + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + sched->unscheduleSelector( SEL_SCHEDULE( &SpriteMainScene::updateAutoTest ), this); + + auto autoTestMenu = dynamic_cast(getChildByTag(kTagAutoTestMenu)); + if (nullptr != autoTestMenu) + { + auto menuItemFont = dynamic_cast(autoTestMenu->getChildByTag(1)); + if (nullptr != menuItemFont) + { + menuItemFont->setString("Auto Test finish"); + } + } + + log("Sprite performance test is finish "); +} + +void SpriteMainScene::onAutoTest(Object* sender) +{ + SpriteMainScene::_s_autoTest = !SpriteMainScene::_s_autoTest; + MenuItemFont* menuItem = dynamic_cast(sender); + if (nullptr != menuItem) + { + if (SpriteMainScene::_s_autoTest) + { + menuItem->setString("Auto Test On"); + beginAutoTest(); + } + else + { + menuItem->setString("Auto Test Off"); + endAutoTest(); + } + } +} + //////////////////////////////////////////////////////// // // For test functions @@ -498,7 +772,6 @@ void SpritePerformTest1::doTest(Sprite* sprite) { performancePosition(sprite); } - //////////////////////////////////////////////////////// // // SpritePerformTest2 @@ -609,6 +882,7 @@ void SpritePerformTest7::doTest(Sprite* sprite) void runSpriteTest() { + SpriteMainScene::_s_autoTest = false; auto scene = new SpritePerformTest1; scene->initWithSubTest(1, 50); Director::getInstance()->replaceScene(scene); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h index da7f009ec3..b9d72a399e 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h @@ -25,6 +25,9 @@ public: { } + virtual void restartCallback(Object* sender); + virtual void nextCallback(Object* sender); + virtual void backCallback(Object* sender); virtual void showCurrentTest(); }; @@ -45,12 +48,33 @@ public: int getSubTestNum() { return subtestNumber; } int getNodesNum() { return quantityNodes; } - + + virtual void onEnter(); + virtual void onExit(); + void updateAutoTest(float dt); + void onAutoTest(Object* sender); +private: + void dumpProfilerFPS(); + void beginAutoTest(); + void endAutoTest(); + void nextAutoTest(); + void finishAutoTest(); + void autoShowSpriteTests(int curCase, int subTest,int nodes); +public: + static bool _s_autoTest; + static int _s_nSpriteCurCase; protected: int lastRenderedCount; int quantityNodes; SubTest *_subTest; int subtestNumber; + std::vector _vecFPS; + int _executeTimes; + const int MAX_AUTO_TEST_TIMES = 25; + const int MAX_SPRITE_TEST_CASE = 7; + const int MAX_SUB_TEST_NUMS = 9; + const int AUTO_TEST_NODE_NUM1 = 500; + const int AUTO_TEST_NODE_NUM2 = 1500; }; class SpritePerformTest1 : public SpriteMainScene From 9c16a45f33aa0072c3587c03082978986cf28e1c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 30 Sep 2013 20:43:19 +0800 Subject: [PATCH 013/557] issue #2771: separate the PhysicsBody and the PhysicsShape. --- cocos2dx/physics/CCPhysicsBody.cpp | 213 ++++++++++-------- cocos2dx/physics/CCPhysicsBody.h | 50 +--- cocos2dx/physics/CCPhysicsShape.cpp | 83 +++++-- cocos2dx/physics/CCPhysicsShape.h | 36 ++- .../Classes/PhysicsTest/PhysicsTest.cpp | 109 ++++++++- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 38 ++-- 6 files changed, 345 insertions(+), 184 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 32f41fd649..b8a961a302 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -62,7 +62,7 @@ PhysicsBody::PhysicsBody() : _owner(nullptr) , _world(nullptr) , _info(nullptr) -, _dynamic(false) +, _dynamic(true) , _enable(true) , _massDefault(true) , _angularDampingDefault(true) @@ -90,12 +90,12 @@ PhysicsBody::~PhysicsBody() } } -PhysicsBody* PhysicsBody::createCircle(float radius) +PhysicsBody* PhysicsBody::createCircle(float radius, float density) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addCircle(radius); + body->addShape(PhysicsShapeCircle::create(body, radius, density)); body->autorelease(); return body; } @@ -104,12 +104,12 @@ PhysicsBody* PhysicsBody::createCircle(float radius) return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size) +PhysicsBody* PhysicsBody::createBox(Size size, float density) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addBox(size); + body->addShape(PhysicsShapeBox::create(body, size, density)); body->autorelease(); return body; } @@ -118,12 +118,12 @@ PhysicsBody* PhysicsBody::createBox(Size size) return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count) +PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, float density) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addPolygon(points, count); + body->addShape(PhysicsShapePolygon::create(body, points, count, density)); body->autorelease(); return body; } @@ -135,9 +135,10 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count) PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); - if (body && body->initStatic()) + if (body && body->init()) { - body->addEdgeSegment(a, b, border); + body->addShape(PhysicsShapeEdgeSegment::create(body, a, b, border)); + body->_dynamic = false; body->autorelease(); return body; } @@ -149,9 +150,10 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, float border/* = 1 PhysicsBody* PhysicsBody::createEdgeBox(Size size, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); - if (body && body->initStatic()) + if (body && body->init()) { - body->addEdgeBox(size, border); + body->addShape(PhysicsShapeEdgeBox::create(body, size, border)); + body->_dynamic = false; body->autorelease(); return body; } @@ -164,9 +166,10 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, float border/* = 1*/) PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); - if (body && body->initStatic()) + if (body && body->init()) { - body->addEdgePolygon(points, count, border); + body->addShape(PhysicsShapePolygon::create(body, points, count, border)); + body->_dynamic = false; body->autorelease(); return body; } @@ -179,9 +182,10 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, float bord PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); - if (body && body->initStatic()) + if (body && body->init()) { - body->addEdgeChain(points, count); + body->addShape(PhysicsShapeEdgeChain::create(body, points, count, border)); + body->_dynamic = false; body->autorelease(); return body; } @@ -191,69 +195,6 @@ PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, float border return nullptr; } -PhysicsShapeCircle* PhysicsBody::addCircle(float radius, Point offset/* = Point(0, 0)*/) -{ - _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); - setMass((_massDefault ? 0 : getMass()) + _area * _density); - - setAngularDamping((_angularDampingDefault ? 0 : getAngularDamping()) - + PhysicsHelper::cpfloat2float(cpMomentForCircle(getMass(), 0, radius, PhysicsHelper::point2cpv(offset)))); - - return PhysicsShapeCircle::create(this, radius, offset); -} - -PhysicsShapeBox* PhysicsBody::addBox(Size size, Point offset/* = Point(0, 0)*/) -{ - cpVect cpOffset = PhysicsHelper::size2cpv(size); - cpVect vec[4] = {}; - vec[0] = cpv(0, 0); - vec[1] = cpv(0, cpOffset.y); - vec[2] = cpv(cpOffset.x, cpOffset.y); - vec[3] = cpv(cpOffset.x, 0); - - _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec)); - setMass((_massDefault ? 0 : getMass()) + _area * _density); - - setAngularDamping((_angularDampingDefault ? 0 : getAngularDamping()) - + PhysicsHelper::cpfloat2float(cpMomentForBox(getMass(), PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)))); - - return PhysicsShapeBox::create(this, size, offset); -} - -PhysicsShapePolygon* PhysicsBody::addPolygon(Point* points, int count, Point offset/* = Point(0, 0)*/) -{ - cpVect* vec = new cpVect[count]; - PhysicsHelper::points2cpvs(points, vec, count); - _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(count, vec)); - - setAngularDamping((_angularDampingDefault ? 0 : getAngularDamping()) - + PhysicsHelper::cpfloat2float(cpMomentForPoly(getMass(), count, vec, PhysicsHelper::point2cpv(offset)))); - - delete[] vec; - - return PhysicsShapePolygon::create(this, points, count, offset); -} - -PhysicsShapeEdgeSegment* PhysicsBody::addEdgeSegment(Point a, Point b, float border/* = 1*/) -{ - return PhysicsShapeEdgeSegment::create(this, a, b, border); -} - -PhysicsShapeEdgeBox* PhysicsBody::addEdgeBox(Size size, float border/* = 1*/, Point offset/* = Point(0, 0)*/) -{ - return PhysicsShapeEdgeBox::create(this, size, border, offset); -} - -PhysicsShapeEdgePolygon* PhysicsBody::addEdgePolygon(Point* points, int count, float border/* = 1*/) -{ - return PhysicsShapeEdgePolygon::create(this, points, count); -} - -PhysicsShapeEdgeChain* PhysicsBody::addEdgeChain(Point* points, int count, float border/* = 1*/) -{ - return PhysicsShapeEdgeChain::create(this, points, count, border); -} - bool PhysicsBody::init() { do @@ -263,7 +204,6 @@ bool PhysicsBody::init() _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_angularDamping)); CC_BREAK_IF(_info->body == nullptr); - _dynamic = true; return true; } while (false); @@ -289,23 +229,6 @@ void PhysicsBody::setDynamic(bool dynamic) } } -bool PhysicsBody::initStatic() -{ - do - { - _info = new PhysicsBodyInfo(); - CC_BREAK_IF(_info == nullptr); - - _info->body = cpBodyNew(INFINITY, INFINITY); - CC_BREAK_IF(_info->body == nullptr); - _dynamic = false; - - return true; - } while (false); - - return false; -} - void PhysicsBody::setPosition(Point position) { cpBodySetPos(_info->body, PhysicsHelper::point2cpv(position)); @@ -331,9 +254,51 @@ void PhysicsBody::addShape(PhysicsShape* shape) { if (shape == nullptr) return; - _shapes.push_back(shape); + if (shape->getBody() != this) CCASSERT(false, ""); - if (_world != nullptr) _world->addShape(shape); + if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) + { + _shapes.push_back(shape); + shape->_isAddToBody = true; + + // calculate the mass, area and desity + _area += shape->getArea(); + if (_mass == INFINITY || shape->getMass() == INFINITY) + { + _mass = INFINITY; + _massDefault = false; + }else + { + if (shape->getMass() > 0) + { + _mass = (_massDefault ? 0 : _mass) + shape->getMass(); + _massDefault = false; + } + } + cpBodySetMass(_info->body, _mass); + + if (!_massDefault) + { + if (_mass == INFINITY) + { + _density = INFINITY; + }else + { + _density = _mass / _area; + } + } + + if (shape->getAngularDumping() > 0) + { + _angularDamping = (_angularDampingDefault ? 0 : _angularDamping) + shape->getAngularDumping(); + _angularDampingDefault = false; + cpBodySetMoment(_info->body, _angularDamping); + } + + if (_world != nullptr) _world->addShape(shape); + + shape->retain(); + } } void PhysicsBody::applyForce(Point force) @@ -369,6 +334,16 @@ void PhysicsBody::setMass(float mass) cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); } +void PhysicsBody::setVelocity(Point velocity) +{ + cpBodySetVel(_info->body, PhysicsHelper::point2cpv(velocity)); +} + +Point PhysicsBody::getVelocity() +{ + return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); +} + void PhysicsBody::setAngularDamping(float angularDamping) { _angularDamping = angularDamping; @@ -414,7 +389,47 @@ void PhysicsBody::removeShape(PhysicsShape* shape) } _shapes.erase(it); - delete shape; + shape->_isAddToBody = false; + + + // deduce the mass, area and angularDamping + if (_mass != INFINITY && shape->getMass() != INFINITY) + { + if (_mass - shape->getMass() <= 0) + { + _mass = MASS_DEFAULT; + _massDefault = true; + }else + { + _mass = _mass = shape->getMass(); + } + + _area -= shape->getArea(); + + if (_mass == INFINITY) + { + _density = INFINITY; + } + else if (_area > 0) + { + _density = _mass / _area; + } + else + { + _density = DENSITY_DEFAULT; + } + + if (_angularDamping - shape->getAngularDumping() > 0) + { + _angularDamping -= shape->getAngularDumping(); + }else + { + _angularDamping = ANGULARDAMPING_DEFAULT; + _angularDampingDefault = true; + } + } + + shape->release(); } } diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 9bca83b3c0..580bec840d 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -37,13 +37,6 @@ class Sprite; class PhysicsWorld; class PhysicsJoint; class PhysicsShape; -class PhysicsShapeCircle; -class PhysicsShapeBox; -class PhysicsShapePolygon; -class PhysicsShapeEdgeSegment; -class PhysicsShapeEdgeBox; -class PhysicsShapeEdgePolygon; -class PhysicsShapeEdgeChain; class PhysicsBodyInfo; /** @@ -56,16 +49,16 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius); + static PhysicsBody* createCircle(float radius, float density = 1); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size); + static PhysicsBody* createBox(Size size, float density = 1); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count); + static PhysicsBody* createPolygon(Point* points, int count, float density = 1); /** * @brief Create a body contains a EdgeSegment shape. @@ -84,37 +77,7 @@ public: */ static PhysicsBody* createEdgeChain(Point* points, int count, float border = 1); - /** - * @brief Attach a circle shape with body - */ - virtual PhysicsShapeCircle* addCircle(float radius, Point offset = Point(0, 0)); - /** - * @brief Attach a box shape with body - */ - virtual PhysicsShapeBox* addBox(Size size, Point offset = Point(0, 0)); - /** - * @brief Attach a polygon shape with body - */ - virtual PhysicsShapePolygon* addPolygon(Point* points, int count, Point offset = Point(0, 0)); - - /** - * @brief Attach a edge segment shape with body - */ - virtual PhysicsShapeEdgeSegment* addEdgeSegment(Point a, Point b, float border = 1); - /** - * @brief Attach a edge box shape with body - */ - virtual PhysicsShapeEdgeBox* addEdgeBox(Size size, float border = 1, Point offset = Point(0, 0)); - /** - * @brief Attach a edge polygon shape with body - * points is an array of Point structs defining a convex hull with a clockwise winding. - */ - virtual PhysicsShapeEdgePolygon* addEdgePolygon(Point* points, int count, float border = 1); - /** - * @brief Attach a edge chain shape with body - * points is an array of Point structs defining a convex hull with a clockwise winding. - */ - virtual PhysicsShapeEdgeChain* addEdgeChain(Point* points, int count, float border = 1); + virtual void addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. @@ -137,6 +100,9 @@ public: */ virtual void applyTorque(float torque); + virtual void setVelocity(Point velocity); + virtual Point getVelocity(); + /* * @brief get the body shapes. */ @@ -226,11 +192,9 @@ public: protected: bool init(); - bool initStatic(); virtual void setPosition(Point position); virtual void setRotation(float rotation); - virtual void addShape(PhysicsShape* shape); protected: PhysicsBody(); diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index 1ce4cbb3b5..8aee1eacf9 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -46,8 +46,13 @@ PhysicsShape::PhysicsShape() : _body(nullptr) , _info(nullptr) , _type(Type::UNKNOWN) +, _area(0) +, _mass(0) +, _angularDamping(0) +, _density(0) , _tag(0) , _enable(true) +, _isAddToBody(false) { } @@ -71,6 +76,11 @@ bool PhysicsShape::init(PhysicsBody* body, Type type) return true; } +void PhysicsShape::setMass(float mass) +{ + +} + void PhysicsShape::setEnable(bool enable) { if (_enable != enable) @@ -173,11 +183,12 @@ PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment() #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(PhysicsBody* body, float radius, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(PhysicsBody* body, float radius, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); - if (shape && shape->init(body, radius, offset)) + if (shape && shape->init(body, radius, density, offset)) { + shape->autorelease(); return shape; } @@ -185,7 +196,7 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(PhysicsBody* body, float radius, return nullptr; } -bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { @@ -195,8 +206,15 @@ bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, Point offset /*= CC_BREAK_IF(shape == nullptr); + _density = density; + _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); + _mass = _density * _area; + if (_mass != 0) + { + _angularDamping = cpMomentForCircle(_density, 0, radius, PhysicsHelper::point2cpv(offset)); + } + _info->add(shape); - addToBody(); return true; } while (false); @@ -210,6 +228,7 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(PhysicsBody* body, Poin PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); if (shape && shape->init(body, a, b, border)) { + shape->autorelease(); return shape; } @@ -230,8 +249,10 @@ bool PhysicsShapeEdgeSegment::init(PhysicsBody* body, Point a, Point b, float bo CC_BREAK_IF(shape == nullptr); + _density = INFINITY; + _angularDamping = INFINITY; + _info->add(shape); - addToBody(); return true; } while (false); @@ -240,11 +261,12 @@ bool PhysicsShapeEdgeSegment::init(PhysicsBody* body, Point a, Point b, float bo } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(PhysicsBody* body, Size size, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(PhysicsBody* body, Size size, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); - if (shape && shape->init(body, size, offset)) + if (shape && shape->init(body, size, density, offset)) { + shape->autorelease(); return shape; } @@ -252,7 +274,7 @@ PhysicsShapeBox* PhysicsShapeBox::create(PhysicsBody* body, Size size, Point off return nullptr; } -bool PhysicsShapeBox::init(PhysicsBody* body, Size size, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(PhysicsBody* body, Size size, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { @@ -262,8 +284,15 @@ bool PhysicsShapeBox::init(PhysicsBody* body, Size size, Point offset /*= Point( CC_BREAK_IF(shape == nullptr); + _density = density; + _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(4, ((cpPolyShape*)shape)->verts)); + _mass = _density * _area; + if (_mass != 0) + { + _angularDamping = cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); + } + _info->add(shape); - addToBody(); return true; } while (false); @@ -272,11 +301,12 @@ bool PhysicsShapeBox::init(PhysicsBody* body, Size size, Point offset /*= Point( } // PhysicsShapeCircle -PhysicsShapePolygon* PhysicsShapePolygon::create(PhysicsBody* body, Point* points, int count, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(PhysicsBody* body, Point* points, int count, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); - if (shape && shape->init(body, points, count, offset)) + if (shape && shape->init(body, points, count, density, offset)) { + shape->autorelease(); return shape; } @@ -284,7 +314,7 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(PhysicsBody* body, Point* point return nullptr; } -bool PhysicsShapePolygon::init(PhysicsBody* body, Point* points, int count, Point offset /*= Point(0, 0)*/) +bool PhysicsShapePolygon::init(PhysicsBody* body, Point* points, int count, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { @@ -293,11 +323,19 @@ bool PhysicsShapePolygon::init(PhysicsBody* body, Point* points, int count, Poin cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); cpShape* shape = cpPolyShapeNew(bodyInfo()->body, count, vecs, PhysicsHelper::point2cpv(offset)); + CC_SAFE_DELETE(vecs); CC_BREAK_IF(shape == nullptr); + _density = density; + _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); + _mass = _density * _area; + if (_mass != 0) + { + _angularDamping = cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); + } + _info->add(shape); - addToBody(); return true; } while (false); @@ -311,6 +349,7 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(PhysicsBody* body, Size size, f PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); if (shape && shape->init(body, size, border, offset)) { + shape->autorelease(); return shape; } @@ -344,7 +383,8 @@ bool PhysicsShapeEdgeBox::init(PhysicsBody* body, Size size, float border/* = 1* } CC_BREAK_IF(i < 4); - addToBody(); + _mass = INFINITY; + _angularDamping = INFINITY; return true; } while (false); @@ -357,7 +397,8 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(PhysicsBody* body, Poin { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); if (shape && shape->init(body, points, count, border)) - { + { + shape->autorelease(); return shape; } @@ -385,11 +426,13 @@ bool PhysicsShapeEdgePolygon::init(PhysicsBody* body, Point* points, int count, cpShapeSetFriction(shape, 1.0f); _info->add(shape); } + CC_SAFE_DELETE(vec); + CC_BREAK_IF(i < count); - addToBody(); + _mass = INFINITY; + _angularDamping = INFINITY; - if (vec != nullptr) delete[] vec; return true; } while (false); @@ -404,6 +447,7 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(PhysicsBody* body, Point* p PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); if (shape && shape->init(body, points, count, border)) { + shape->autorelease(); return shape; } @@ -431,11 +475,12 @@ bool PhysicsShapeEdgeChain::init(PhysicsBody* body, Point* points, int count, fl cpShapeSetFriction(shape, 1.0f); _info->add(shape); } + if (vec != nullptr) delete[] vec; CC_BREAK_IF(i < count); - addToBody(); + _mass = INFINITY; + _angularDamping = INFINITY; - if (vec != nullptr) delete[] vec; return true; } while (false); diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 4cc1da148b..b037eda1dc 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -58,10 +58,17 @@ public: public: inline PhysicsBody* getBody(){ return _body; } inline Type getType() { return _type; } + inline float getMass() { return _mass; } + void setMass(float mass); + inline float getArea() { return _area; } + inline float getDensity() { return _density; } + void setDensity(float density); + inline float getAngularDumping() { return _angularDamping; } inline void setTag(int tag) { _tag = tag; } inline int getTag() { return _tag; } void setEnable(bool enable); inline bool isEnable() { return _enable; } + void addToBody(); protected: bool init(PhysicsBody* body, Type type); @@ -71,8 +78,6 @@ protected: */ PhysicsBodyInfo* bodyInfo() const; - void addToBody(); - protected: PhysicsShape(); virtual ~PhysicsShape() = 0; @@ -81,8 +86,13 @@ protected: PhysicsBody* _body; PhysicsShapeInfo* _info; Type _type; + float _area; + float _mass; + float _angularDamping; + float _density; int _tag; bool _enable; + bool _isAddToBody; friend class PhysicsWorld; friend class PhysicsBody; @@ -91,9 +101,11 @@ protected: /** A circle shape */ class PhysicsShapeCircle : public PhysicsShape { +public: + static PhysicsShapeCircle* create(PhysicsBody* body, float radius, float density = 0, Point offset = Point(0, 0)); + protected: - static PhysicsShapeCircle* create(PhysicsBody* body, float radius, Point offset = Point(0, 0)); - bool init(PhysicsBody* body, float radius, Point offset = Point(0, 0)); + bool init(PhysicsBody* body, float radius, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapeCircle(); @@ -105,9 +117,11 @@ protected: /** A box shape */ class PhysicsShapeBox : public PhysicsShape { +public: + static PhysicsShapeBox* create(PhysicsBody* body, Size size, float density = 0, Point offset = Point(0, 0)); + protected: - static PhysicsShapeBox* create(PhysicsBody* body, Size size, Point offset = Point(0, 0)); - bool init(PhysicsBody* body, Size size, Point offset = Point(0, 0)); + bool init(PhysicsBody* body, Size size, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapeBox(); @@ -119,9 +133,11 @@ protected: /** A polygon shape */ class PhysicsShapePolygon : public PhysicsShape { +public: + static PhysicsShapePolygon* create(PhysicsBody* body, Point* points, int count, float density = 0, Point offset = Point(0, 0)); + protected: - static PhysicsShapePolygon* create(PhysicsBody* body, Point* points, int count, Point offset = Point(0, 0)); - bool init(PhysicsBody* body, Point* points, int count, Point offset = Point(0, 0)); + bool init(PhysicsBody* body, Point* points, int count, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapePolygon(); @@ -133,8 +149,10 @@ protected: /** A segment shape */ class PhysicsShapeEdgeSegment : public PhysicsShape { -protected: +public: static PhysicsShapeEdgeSegment* create(PhysicsBody* body, Point a, Point b, float border = 1); + +protected: bool init(PhysicsBody* body, Point a, Point b, float border = 1); protected: diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index db4c3d46ab..c32219635e 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -5,7 +5,7 @@ USING_NS_CC; namespace { static std::function createFunctions[] = { - + CL(PhysicsDemoLogoSmash), CL(PhysicsDemoClickAdd), }; @@ -236,4 +236,111 @@ void PhysicsDemoClickAdd::onAcceleration(Acceleration* acc, Event* event) _scene->getPhysicsWorld()->setGravity(v); } #endif +} + +namespace +{ + static const int logo_width = 188; + static const int logo_height = 35; + static const int logo_row_length = 24; + static const char logo_image[] = + { + 15,-16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-64,15,63,-32,-2,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,31,-64,15,127,-125,-1,-128,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,127,-64,15,127,15,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-2, + 31,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,0,-4,63,-1,-32,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-8,127,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,-1,-64,0,-8,-15,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-31,-1,-64,15,-8,-32, + -1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-15,-1,-64,9,-15,-32,-1,-32,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,31,-15,-1,-64,0,-15,-32,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,63,-7,-1,-64,9,-29,-32,127,-61,-16,63,15,-61,-1,-8,31,-16,15,-8,126,7,-31, + -8,31,-65,-7,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, + -4,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, + -2,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -2,63,-33,-1,-1,-32,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -1,63,-33,-1,-1,-16,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, + -1,63,-49,-1,-1,-8,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-65,-49,-1,-1,-4,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-65,-57,-1,-1,-2,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, + -1,-1,-57,-1,-1,-1,9,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-61,-1,-1,-1,-119,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-61,-1,-1,-1,-55,-49,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, + -1,-63,-1,-1,-1,-23,-49,-32,127,-57,-1,-1,-97,-25,-1,-1,63,-1,-1,-4,-1,15,-13, + -1,-1,-63,-1,-1,-1,-16,-49,-32,-1,-25,-1,-1,-97,-25,-1,-1,63,-33,-5,-4,-1,15, + -13,-1,-1,-64,-1,-9,-1,-7,-49,-32,-1,-25,-8,127,-97,-25,-1,-1,63,-33,-5,-4,-1, + 15,-13,-1,-1,-64,-1,-13,-1,-32,-49,-32,-1,-25,-8,127,-97,-25,-1,-2,63,-49,-13, + -4,-1,15,-13,-1,-1,-64,127,-7,-1,-119,-17,-15,-1,-25,-8,127,-97,-25,-1,-2,63, + -49,-13,-4,-1,15,-13,-3,-1,-64,127,-8,-2,15,-17,-1,-1,-25,-8,127,-97,-25,-1, + -8,63,-49,-13,-4,-1,15,-13,-3,-1,-64,63,-4,120,0,-17,-1,-1,-25,-8,127,-97,-25, + -8,0,63,-57,-29,-4,-1,15,-13,-4,-1,-64,63,-4,0,15,-17,-1,-1,-25,-8,127,-97, + -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,-1,-64,31,-2,0,0,103,-1,-1,-57,-8,127,-97, + -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127, + -97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8, + 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, + 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0}; + + static inline int + get_pixel(int x, int y) + { + return (logo_image[(x>>3) + y*logo_row_length]>>(~x&0x7)) & 1; + } + +#define RAND_MAX 0x7fffffff + static inline float + frand(void) + { + return rand()/RAND_MAX; + } +} + +Node* PhysicsDemoLogoSmash::makeBall(float x, float y) +{ + Sprite* ball = Sprite::create("Images/ball.png"); + ball->setScale(0.1); + + PhysicsBody* body = PhysicsBody::createCircle(0.95); + body->setDynamic(false); + ball->setPhysicsBody(body); + + ball->setPosition(Point(x, y)); + + return ball; +} + +void PhysicsDemoLogoSmash::onEnter() +{ + PhysicsDemo::onEnter(); + _draw = DrawNode::create(); + + //addChild(makeBall(200, 200)); + for (int y = 0; y < logo_height; ++y) + { + for (int x = 0; x < logo_width; ++x) + { + if (get_pixel(x, y)) + { + float x_jitter = 0.05*frand(); + float y_jitter = 0.05*frand(); + + addChild(makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, + 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2)); + } + } + } + + + Sprite* bullet = Sprite::create("Images/ball.png"); + bullet->setScale(0.2); + + PhysicsBody* body = PhysicsBody::createCircle(3); + body->setDynamic(false); + body->setVelocity(Point(400, 0)); + bullet->setPhysicsBody(body); + + bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); +} + +std::string PhysicsDemoLogoSmash::title() +{ + return "Logo Smash"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 5acb33e855..cf63471998 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -6,6 +6,13 @@ #include "../BaseTest.h" +class PhysicsTestScene : public TestScene +{ +public: + virtual bool initTest() override; + virtual void runThisTest(); +}; + class PhysicsDemo : public BaseTest { protected: @@ -15,9 +22,9 @@ public: PhysicsDemo(); virtual ~PhysicsDemo(); - virtual void onEnter(); - virtual std::string title(); - virtual std::string subtitle(); + virtual void onEnter() override; + virtual std::string title() override; + virtual std::string subtitle() override; void restartCallback(Object* sender); void nextCallback(Object* sender); @@ -27,24 +34,29 @@ public: class PhysicsDemoClickAdd : public PhysicsDemo { -private: - Texture2D* _spriteTexture; // weak ref - public: - void onEnter(); - std::string subtitle(); + void onEnter() override; + std::string subtitle() override; void addNewSpriteAtPosition(Point p); - void onTouchesEnded(const std::vector& touches, Event* event); - void onAcceleration(Acceleration* acc, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event) override; + void onAcceleration(Acceleration* acc, Event* event) override; + +private: + Texture2D* _spriteTexture; // weak ref }; -class PhysicsTestScene : public TestScene +class PhysicsDemoLogoSmash : public PhysicsDemo { public: - virtual bool initTest() override; - virtual void runThisTest(); + void onEnter() override; + std::string title() override; + + Node* makeBall(float x, float y); + +private: + DrawNode* _draw; }; #endif From 35259588a3aff11981e3bece1ee00220961d21d1 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 30 Sep 2013 21:48:25 +0800 Subject: [PATCH 014/557] issue #2771: fix some bugs in PhysicsShape --- cocos2dx/physics/CCPhysicsShape.cpp | 7 ++----- cocos2dx/physics/CCPhysicsShape.h | 1 + .../TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 16 ++++++++-------- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index 8aee1eacf9..35edfb5f1e 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -208,11 +208,8 @@ bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, float density/* = _density = density; _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); - _mass = _density * _area; - if (_mass != 0) - { - _angularDamping = cpMomentForCircle(_density, 0, radius, PhysicsHelper::point2cpv(offset)); - } + _mass = _density == INFINITY ? INFINITY : _density * _area; + _angularDamping = _mass == INFINITY ? INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); _info->add(shape); diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index b037eda1dc..3d431f96e7 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -64,6 +64,7 @@ public: inline float getDensity() { return _density; } void setDensity(float density); inline float getAngularDumping() { return _angularDamping; } + void setAngularDumping(float angularDumping); inline void setTag(int tag) { _tag = tag; } inline int getTag() { return _tag; } void setEnable(bool enable); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index c32219635e..ebab929dec 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -279,15 +279,13 @@ namespace 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0}; - static inline int - get_pixel(int x, int y) + static inline int get_pixel(int x, int y) { return (logo_image[(x>>3) + y*logo_row_length]>>(~x&0x7)) & 1; } #define RAND_MAX 0x7fffffff - static inline float - frand(void) + static inline float frand(void) { return rand()/RAND_MAX; } @@ -299,7 +297,7 @@ Node* PhysicsDemoLogoSmash::makeBall(float x, float y) ball->setScale(0.1); PhysicsBody* body = PhysicsBody::createCircle(0.95); - body->setDynamic(false); + //body->setDynamic(false); ball->setPhysicsBody(body); ball->setPosition(Point(x, y)); @@ -312,6 +310,7 @@ void PhysicsDemoLogoSmash::onEnter() PhysicsDemo::onEnter(); _draw = DrawNode::create(); + _scene->getPhysicsWorld()->setGravity(Point(0, 0)); //addChild(makeBall(200, 200)); for (int y = 0; y < logo_height; ++y) { @@ -330,14 +329,15 @@ void PhysicsDemoLogoSmash::onEnter() Sprite* bullet = Sprite::create("Images/ball.png"); - bullet->setScale(0.2); + bullet->setScale(0.5); - PhysicsBody* body = PhysicsBody::createCircle(3); - body->setDynamic(false); + PhysicsBody* body = PhysicsBody::createCircle(3, INFINITY); body->setVelocity(Point(400, 0)); bullet->setPhysicsBody(body); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); + + addChild(bullet); } std::string PhysicsDemoLogoSmash::title() From 6143c512fa8e105ff9aafb3f5aed958afdfe3ca8 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Thu, 3 Oct 2013 15:41:22 -0700 Subject: [PATCH 015/557] Add AppCode project files to ignorelist --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 321ce706a4..ed3c0b5afa 100644 --- a/.gitignore +++ b/.gitignore @@ -69,6 +69,9 @@ build/ xcuserdata/ DerivedData/ +# Ignore files built by AppCode +.idea/ + # Ignore files built by bada .Simulator-Debug/ .Target-Debug/ From a2c254694202cbe51a0ece8bd610aede39501750 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Fri, 4 Oct 2013 10:07:39 -0700 Subject: [PATCH 016/557] Implement MouseWheel Event, also fix a typo in EventListener interface --- .../project.pbxproj.REMOVED.git-id | 2 +- .../event_dispatcher/CCEventDispatcher.cpp | 4 +- cocos2dx/event_dispatcher/CCEventListener.cpp | 2 +- cocos2dx/event_dispatcher/CCEventListener.h | 2 +- .../CCEventListenerAcceleration.cpp | 2 +- .../CCEventListenerAcceleration.h | 2 +- .../CCEventListenerCustom.cpp | 4 +- .../event_dispatcher/CCEventListenerCustom.h | 2 +- .../CCEventListenerKeyboard.cpp | 2 +- .../CCEventListenerKeyboard.h | 2 +- .../event_dispatcher/CCEventListenerMouse.cpp | 100 ++++++++++++++++++ .../event_dispatcher/CCEventListenerMouse.h | 57 ++++++++++ .../event_dispatcher/CCEventListenerTouch.cpp | 2 +- .../event_dispatcher/CCEventListenerTouch.h | 2 +- cocos2dx/event_dispatcher/CCEventMouse.cpp | 32 ++++++ cocos2dx/event_dispatcher/CCEventMouse.h | 75 +++++++++++++ cocos2dx/include/cocos2d.h | 2 + cocos2dx/platform/mac/CCEGLView.mm | 12 ++- samples/Cpp/TestCpp/Classes/controller.cpp | 28 +++++ samples/Cpp/TestCpp/Classes/controller.h | 2 + 20 files changed, 321 insertions(+), 15 deletions(-) create mode 100644 cocos2dx/event_dispatcher/CCEventListenerMouse.cpp create mode 100644 cocos2dx/event_dispatcher/CCEventListenerMouse.h create mode 100644 cocos2dx/event_dispatcher/CCEventMouse.cpp create mode 100644 cocos2dx/event_dispatcher/CCEventMouse.h diff --git a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 48555d6a5d..3e16069aaa 100644 --- a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3959af89b6bbc8fb982769d22d2591991107d6e5 \ No newline at end of file +a62d231c7569e0d3691fffaeed9f8ed41f11070d \ No newline at end of file diff --git a/cocos2dx/event_dispatcher/CCEventDispatcher.cpp b/cocos2dx/event_dispatcher/CCEventDispatcher.cpp index 468db2f39b..c8901f2b8a 100644 --- a/cocos2dx/event_dispatcher/CCEventDispatcher.cpp +++ b/cocos2dx/event_dispatcher/CCEventDispatcher.cpp @@ -125,7 +125,7 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list CCASSERT(listener && node, "Invalid parameters."); CCASSERT(!listener->_isRegistered, "The listener has been registered."); - if (!listener->checkAvaiable()) + if (!listener->checkAvailable()) return; auto item = new EventListenerItem(); @@ -147,7 +147,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, CCASSERT(!listener->_isRegistered, "The listener has been registered."); CCASSERT(fixedPriority != 0, "0 priority is forbidden for fixed priority since it's used for scene graph based priority."); - if (!listener->checkAvaiable()) + if (!listener->checkAvailable()) return; auto item = new EventListenerItem(); diff --git a/cocos2dx/event_dispatcher/CCEventListener.cpp b/cocos2dx/event_dispatcher/CCEventListener.cpp index ce3c787883..451be9a8c8 100644 --- a/cocos2dx/event_dispatcher/CCEventListener.cpp +++ b/cocos2dx/event_dispatcher/CCEventListener.cpp @@ -44,7 +44,7 @@ bool EventListener::init(const std::string& t, std::function callb return true; } -bool EventListener::checkAvaiable() +bool EventListener::checkAvailable() { return (_onEvent != nullptr); } diff --git a/cocos2dx/event_dispatcher/CCEventListener.h b/cocos2dx/event_dispatcher/CCEventListener.h index 156d644f17..6ef486d8e2 100644 --- a/cocos2dx/event_dispatcher/CCEventListener.h +++ b/cocos2dx/event_dispatcher/CCEventListener.h @@ -54,7 +54,7 @@ public: virtual ~EventListener(); /** Checks whether the listener is available. */ - virtual bool checkAvaiable() = 0; + virtual bool checkAvailable() = 0; /** Clones the listener, its subclasses have to override this method. */ virtual EventListener* clone() = 0; diff --git a/cocos2dx/event_dispatcher/CCEventListenerAcceleration.cpp b/cocos2dx/event_dispatcher/CCEventListenerAcceleration.cpp index e7e1f6055b..d8b01fc4ce 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerAcceleration.cpp +++ b/cocos2dx/event_dispatcher/CCEventListenerAcceleration.cpp @@ -84,7 +84,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone() return ret; } -bool EventListenerAcceleration::checkAvaiable() +bool EventListenerAcceleration::checkAvailable() { CCASSERT(onAccelerationEvent, ""); diff --git a/cocos2dx/event_dispatcher/CCEventListenerAcceleration.h b/cocos2dx/event_dispatcher/CCEventListenerAcceleration.h index 1fb9536be7..2905df9486 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerAcceleration.h +++ b/cocos2dx/event_dispatcher/CCEventListenerAcceleration.h @@ -38,7 +38,7 @@ public: /// Overrides virtual EventListenerAcceleration* clone() override; - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; private: EventListenerAcceleration(); diff --git a/cocos2dx/event_dispatcher/CCEventListenerCustom.cpp b/cocos2dx/event_dispatcher/CCEventListenerCustom.cpp index 7be79b9dcb..abe4153198 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerCustom.cpp +++ b/cocos2dx/event_dispatcher/CCEventListenerCustom.cpp @@ -80,10 +80,10 @@ EventListenerCustom* EventListenerCustom::clone() return ret; } -bool EventListenerCustom::checkAvaiable() +bool EventListenerCustom::checkAvailable() { bool ret = false; - if (EventListener::checkAvaiable() && _onCustomEvent != nullptr) + if (EventListener::checkAvailable() && _onCustomEvent != nullptr) { ret = true; } diff --git a/cocos2dx/event_dispatcher/CCEventListenerCustom.h b/cocos2dx/event_dispatcher/CCEventListenerCustom.h index 190ed63f95..a823d4a4ba 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerCustom.h +++ b/cocos2dx/event_dispatcher/CCEventListenerCustom.h @@ -59,7 +59,7 @@ public: static EventListenerCustom* create(const std::string& eventName, std::function callback); /// Overrides - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; virtual EventListenerCustom* clone() override; protected: diff --git a/cocos2dx/event_dispatcher/CCEventListenerKeyboard.cpp b/cocos2dx/event_dispatcher/CCEventListenerKeyboard.cpp index 80709f8cef..a6e3b617ae 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerKeyboard.cpp +++ b/cocos2dx/event_dispatcher/CCEventListenerKeyboard.cpp @@ -29,7 +29,7 @@ NS_CC_BEGIN -bool EventListenerKeyboard::checkAvaiable() +bool EventListenerKeyboard::checkAvailable() { CCASSERT(onKeyPressed && onKeyReleased, ""); diff --git a/cocos2dx/event_dispatcher/CCEventListenerKeyboard.h b/cocos2dx/event_dispatcher/CCEventListenerKeyboard.h index f7b4c288d9..dd223da533 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerKeyboard.h +++ b/cocos2dx/event_dispatcher/CCEventListenerKeyboard.h @@ -40,7 +40,7 @@ public: /// Overrides virtual EventListenerKeyboard* clone() override; - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; std::function onKeyPressed; std::function onKeyReleased; diff --git a/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp b/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp new file mode 100644 index 0000000000..d747a720b4 --- /dev/null +++ b/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp @@ -0,0 +1,100 @@ +/**************************************************************************** + 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 "CCEventListenerMouse.h" + +NS_CC_BEGIN + +bool EventListenerMouse::checkAvailable() +{ + return true; +} + +EventListenerMouse* EventListenerMouse::create() +{ + auto ret = new EventListenerMouse(); + if (ret && ret->init()) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +EventListenerMouse* EventListenerMouse::clone() +{ + auto ret = new EventListenerMouse(); + if (ret && ret->init()) + { + ret->autorelease(); + ret->onMouseUp = onMouseUp; + ret->onMouseDown = onMouseDown; + ret->onMouseMove = onMouseMove; + ret->onMouseScroll = onMouseScroll; + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +EventListenerMouse::EventListenerMouse() +: onMouseUp(nullptr) +, onMouseDown(nullptr) +, onMouseMove(nullptr) +, onMouseScroll(nullptr) +{ +} + +bool EventListenerMouse::init() +{ + auto listener = [this](Event* event){ + auto mouseEvent = static_cast(event); + switch (mouseEvent->_mouseEventType) + { + case EventMouse::MouseEventType::MOUSE_SCROLL: + { + if(onMouseScroll != nullptr) + onMouseScroll(event); + break; + } + default: + break; + } + }; + + if (EventListener::init(EventMouse::EVENT_TYPE, listener)) + { + return true; + } + + return false; +} + +NS_CC_END \ No newline at end of file diff --git a/cocos2dx/event_dispatcher/CCEventListenerMouse.h b/cocos2dx/event_dispatcher/CCEventListenerMouse.h new file mode 100644 index 0000000000..360d46128a --- /dev/null +++ b/cocos2dx/event_dispatcher/CCEventListenerMouse.h @@ -0,0 +1,57 @@ +/**************************************************************************** + 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 "CCEventListener.h" +#include "CCEventMouse.h" + +#ifndef __cocos2d_libs__CCMouseEventListener__ +#define __cocos2d_libs__CCMouseEventListener__ + +NS_CC_BEGIN + +class Event; + +class EventListenerMouse : public EventListener +{ +public: + static EventListenerMouse* create(); + + /// Overrides + virtual EventListenerMouse* clone() override; + virtual bool checkAvailable() override; + + std::function onMouseDown; + std::function onMouseUp; + std::function onMouseMove; + std::function onMouseScroll; + +private: + EventListenerMouse(); + bool init(); +}; + +NS_CC_END + +#endif /* defined(__cocos2d_libs__CCMouseEventListener__) */ diff --git a/cocos2dx/event_dispatcher/CCEventListenerTouch.cpp b/cocos2dx/event_dispatcher/CCEventListenerTouch.cpp index ec418c2949..80e9f0b011 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerTouch.cpp +++ b/cocos2dx/event_dispatcher/CCEventListenerTouch.cpp @@ -80,7 +80,7 @@ EventListenerTouch* EventListenerTouch::create(Touch::DispatchMode mode) return ret; } -bool EventListenerTouch::checkAvaiable() +bool EventListenerTouch::checkAvailable() { if (_dispatchMode == Touch::DispatchMode::ALL_AT_ONCE) { diff --git a/cocos2dx/event_dispatcher/CCEventListenerTouch.h b/cocos2dx/event_dispatcher/CCEventListenerTouch.h index 62cd4c3e6d..bfe04d9785 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerTouch.h +++ b/cocos2dx/event_dispatcher/CCEventListenerTouch.h @@ -40,7 +40,7 @@ public: /// Overrides virtual EventListenerTouch* clone() override; - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; virtual ~EventListenerTouch(); diff --git a/cocos2dx/event_dispatcher/CCEventMouse.cpp b/cocos2dx/event_dispatcher/CCEventMouse.cpp new file mode 100644 index 0000000000..abb1ce5518 --- /dev/null +++ b/cocos2dx/event_dispatcher/CCEventMouse.cpp @@ -0,0 +1,32 @@ +/**************************************************************************** + 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 "CCEventMouse.h" + +NS_CC_BEGIN + +const char* EventMouse::EVENT_TYPE = "MouseEvent"; + +NS_CC_END \ No newline at end of file diff --git a/cocos2dx/event_dispatcher/CCEventMouse.h b/cocos2dx/event_dispatcher/CCEventMouse.h new file mode 100644 index 0000000000..28df2b409a --- /dev/null +++ b/cocos2dx/event_dispatcher/CCEventMouse.h @@ -0,0 +1,75 @@ +/**************************************************************************** + 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 __cocos2d_libs__CCMouseEvent__ +#define __cocos2d_libs__CCMouseEvent__ + +#include "CCEvent.h" + +NS_CC_BEGIN + +class EventMouse : public Event +{ +public: + /** + * Different types of MouseEvent + */ + enum class MouseEventType + { + MOUSE_NONE, +// todo: support other mouse events +// MOUSE_DOWN, +// MOUSE_UP, +// MOUSE_MOVE, + MOUSE_SCROLL, + }; + + static const char* EVENT_TYPE; + + EventMouse(MouseEventType mouseEventCode) + : Event(EVENT_TYPE) + , _mouseEventType(mouseEventCode) + {}; + + /** Set mouse scroll data */ + inline void setScrollData(float scrollX, float scrollY) { _scrollX = scrollX; _scrollY = scrollY; }; + + inline float getScrollX() { return _scrollX; }; + inline float getScrollY() { return _scrollY; }; + +private: + MouseEventType _mouseEventType; + int _mouseButton; + bool _isPressed; +// Point _position; + float _scrollX; + float _scrollY; + + friend class EventListenerMouse; +}; + +NS_CC_END + +#endif /* defined(__cocos2d_libs__CCMouseEvent__) */ diff --git a/cocos2dx/include/cocos2d.h b/cocos2dx/include/cocos2d.h index 2280067cfc..94301dcf68 100644 --- a/cocos2dx/include/cocos2d.h +++ b/cocos2dx/include/cocos2d.h @@ -269,6 +269,8 @@ THE SOFTWARE. #include "event_dispatcher/CCEventListenerAcceleration.h" #include "event_dispatcher/CCEventCustom.h" #include "event_dispatcher/CCEventListenerCustom.h" +#include "event_dispatcher/CCEventListenerMouse.h" +#include "event_dispatcher/CCEventMouse.h" // root #include "CCCamera.h" diff --git a/cocos2dx/platform/mac/CCEGLView.mm b/cocos2dx/platform/mac/CCEGLView.mm index 3c371b2457..7248877a70 100644 --- a/cocos2dx/platform/mac/CCEGLView.mm +++ b/cocos2dx/platform/mac/CCEGLView.mm @@ -28,6 +28,7 @@ #include "event_dispatcher/CCTouch.h" #include "event_dispatcher/CCEventDispatcher.h" #include "event_dispatcher/CCEventKeyboard.h" +#include "event_dispatcher/CCEventMouse.h" #include "CCIMEDispatcher.h" NS_CC_BEGIN @@ -175,6 +176,7 @@ public: static void OnGLFWError(int errorID, const char* errorDesc); static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); + static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character); static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); @@ -236,6 +238,13 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, } } +void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) +{ + EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); + event.setScrollData((float)x, (float)y); + EventDispatcher::getInstance()->dispatchEvent(&event); +} + void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); @@ -300,10 +309,11 @@ bool EGLView::init(const char *viewName, float width, float height, float frameZ glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack); glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack); + glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback); glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback); glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback); glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback); - + // check OpenGL version at first const GLubyte* glVersion = glGetString(GL_VERSION); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index f78fb2c9af..2f4059469a 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -132,6 +132,10 @@ TestController::TestController() listener->onTouchMoved = CC_CALLBACK_2(TestController::onTouchMoved, this); EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + + auto mouseListener = EventListenerMouse::create(); + mouseListener->onMouseScroll = CC_CALLBACK_1(TestController::onMouseScroll, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(mouseListener, this); } TestController::~TestController() @@ -195,3 +199,27 @@ void TestController::onTouchMoved(Touch* touch, Event *event) _beginPos = touchLocation; s_tCurPos = nextPos; } + +void TestController::onMouseScroll(Event *event) +{ + auto mouseEvent = static_cast(event); + float nMoveY = -mouseEvent->getScrollY(); + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testCount + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testCount + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); + s_tCurPos = nextPos; +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/controller.h b/samples/Cpp/TestCpp/Classes/controller.h index 50126dbceb..19947f20d5 100644 --- a/samples/Cpp/TestCpp/Classes/controller.h +++ b/samples/Cpp/TestCpp/Classes/controller.h @@ -17,6 +17,8 @@ public: bool onTouchBegan(Touch* touches, Event *event); void onTouchMoved(Touch* touches, Event *event); + void onMouseScroll(Event *event); + private: Point _beginPos; Menu* _itemMenu; From e19957136e12a9dd90479e36ea5a896f44136d21 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Fri, 4 Oct 2013 16:14:52 -0700 Subject: [PATCH 017/557] Implement Mouse_up Mouse_down and Mouse_Move --- .../event_dispatcher/CCEventListenerMouse.cpp | 14 +++++++++++-- cocos2dx/event_dispatcher/CCEventMouse.h | 20 ++++++++++++------- cocos2dx/platform/mac/CCEGLView.mm | 14 +++++++++++++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp b/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp index d747a720b4..24f8a167ab 100644 --- a/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp +++ b/cocos2dx/event_dispatcher/CCEventListenerMouse.cpp @@ -78,12 +78,22 @@ bool EventListenerMouse::init() auto mouseEvent = static_cast(event); switch (mouseEvent->_mouseEventType) { + case EventMouse::MouseEventType::MOUSE_DOWN: + if(onMouseDown != nullptr) + onMouseDown(event); + break; + case EventMouse::MouseEventType::MOUSE_UP: + if(onMouseUp != nullptr) + onMouseUp(event); + break; + case EventMouse::MouseEventType::MOUSE_MOVE: + if(onMouseMove != nullptr) + onMouseMove(event); + break; case EventMouse::MouseEventType::MOUSE_SCROLL: - { if(onMouseScroll != nullptr) onMouseScroll(event); break; - } default: break; } diff --git a/cocos2dx/event_dispatcher/CCEventMouse.h b/cocos2dx/event_dispatcher/CCEventMouse.h index 28df2b409a..b44d6d4aca 100644 --- a/cocos2dx/event_dispatcher/CCEventMouse.h +++ b/cocos2dx/event_dispatcher/CCEventMouse.h @@ -39,10 +39,9 @@ public: enum class MouseEventType { MOUSE_NONE, -// todo: support other mouse events -// MOUSE_DOWN, -// MOUSE_UP, -// MOUSE_MOVE, + MOUSE_DOWN, + MOUSE_UP, + MOUSE_MOVE, MOUSE_SCROLL, }; @@ -51,19 +50,26 @@ public: EventMouse(MouseEventType mouseEventCode) : Event(EVENT_TYPE) , _mouseEventType(mouseEventCode) + , _x(0.0f) + , _y(0.0f) + , _scrollX(0.0f) + , _scrollY(0.0f) {}; /** Set mouse scroll data */ inline void setScrollData(float scrollX, float scrollY) { _scrollX = scrollX; _scrollY = scrollY; }; - inline float getScrollX() { return _scrollX; }; inline float getScrollY() { return _scrollY; }; + inline void setCursorPosition(float x, float y) { _x = x; _y = y; }; + inline float getCursorX() { return _x; }; + inline float getCursorY() { return _y; }; + private: MouseEventType _mouseEventType; int _mouseButton; - bool _isPressed; -// Point _position; + float _x; + float _y; float _scrollX; float _scrollY; diff --git a/cocos2dx/platform/mac/CCEGLView.mm b/cocos2dx/platform/mac/CCEGLView.mm index 7248877a70..83d020cef1 100644 --- a/cocos2dx/platform/mac/CCEGLView.mm +++ b/cocos2dx/platform/mac/CCEGLView.mm @@ -195,6 +195,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in { EGLView* eglView = EGLView::getInstance(); if(nullptr == eglView) return; + if(GLFW_MOUSE_BUTTON_LEFT == button) { if(GLFW_PRESS == action) @@ -204,6 +205,10 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in { int id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); + + EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); + event.setCursorPosition(s_mouseX, s_mouseY); + EventDispatcher::getInstance()->dispatchEvent(&event); } } else if(GLFW_RELEASE == action) @@ -213,6 +218,10 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in { int id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); + + EventMouse event(EventMouse::MouseEventType::MOUSE_UP); + event.setCursorPosition(s_mouseX, s_mouseY); + EventDispatcher::getInstance()->dispatchEvent(&event); } } } @@ -236,12 +245,17 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } + + EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); + event.setCursorPosition(s_mouseX, s_mouseY); + EventDispatcher::getInstance()->dispatchEvent(&event); } void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) { EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); event.setScrollData((float)x, (float)y); + event.setCursorPosition(s_mouseX, s_mouseY); EventDispatcher::getInstance()->dispatchEvent(&event); } From 5acac436f90506a023b94421c41c8c3a17f93fbc Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 8 Oct 2013 10:11:52 +0800 Subject: [PATCH 018/557] issues #2677:Use CoreMotion's API to replace UIAccelerometer. --- cocos2dx/platform/ios/CCDevice.mm | 26 +++++++++++-------- .../project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/cocos2dx/platform/ios/CCDevice.mm b/cocos2dx/platform/ios/CCDevice.mm index 6ced352414..f678244da7 100644 --- a/cocos2dx/platform/ios/CCDevice.mm +++ b/cocos2dx/platform/ios/CCDevice.mm @@ -6,13 +6,13 @@ #import // Accelerometer -#import -#import -#import +#include +#import @interface CCAccelerometerDispatcher : NSObject { cocos2d::Acceleration *_acceleration; + CMMotionManager *_motionManager; } + (id) sharedAccelerometerDispather; @@ -38,6 +38,7 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; - (id) init { _acceleration = new cocos2d::Acceleration(); + _motionManager = [[CMMotionManager alloc] init]; return self; } @@ -45,6 +46,7 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; { s_pAccelerometerDispatcher = nullptr; delete _acceleration; + [_motionManager release]; [super dealloc]; } @@ -52,25 +54,27 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; { if (isEnabled) { - [[UIAccelerometer sharedAccelerometer] setDelegate:self]; + [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { + [self accelerometer:accelerometerData]; + }]; } else { - [[UIAccelerometer sharedAccelerometer] setDelegate:nil]; + [_motionManager stopAccelerometerUpdates]; } } -(void) setAccelerometerInterval:(float)interval { - [[UIAccelerometer sharedAccelerometer] setUpdateInterval:interval]; + _motionManager.accelerometerUpdateInterval = interval; } -- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration +- (void)accelerometer:(CMAccelerometerData *)accelerometerData { - _acceleration->x = acceleration.x; - _acceleration->y = acceleration.y; - _acceleration->z = acceleration.z; - _acceleration->timestamp = acceleration.timestamp; + _acceleration->x = accelerometerData.acceleration.x; + _acceleration->y = accelerometerData.acceleration.y; + _acceleration->z = accelerometerData.acceleration.z; + _acceleration->timestamp = accelerometerData.timestamp; double tmp = _acceleration->x; diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index efbf8806ae..dc39ae6bd3 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b759f56a07f242b20e9c96f2a6cd49c4b5c9dc9b \ No newline at end of file +d846dfb9965fecfad1f6fe6190516035158c4d53 \ No newline at end of file From 8dc55b37732e8a2cbe759119063738957627dab7 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 8 Oct 2013 11:08:45 +0800 Subject: [PATCH 019/557] issues #2677:Use CoreMotion's API to replace UIAccelerometer. --- .../proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj | 4 ++++ .../proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj | 4 ++++ .../proj.ios_mac/HelloLua.xcodeproj/project.pbxproj | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj index 7e027bca7a..3cb7edab03 100644 --- a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj +++ b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj @@ -69,6 +69,7 @@ D44C620C132DFF330009C878 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D44C620B132DFF330009C878 /* OpenAL.framework */; }; D44C620E132DFF430009C878 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D44C620D132DFF430009C878 /* AVFoundation.framework */; }; D44C6210132DFF4E0009C878 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D44C620F132DFF4E0009C878 /* AudioToolbox.framework */; }; + D6B0611B1803AB670077942B /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6B0611A1803AB670077942B /* CoreMotion.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -294,6 +295,7 @@ D44C620B132DFF330009C878 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; D44C620D132DFF430009C878 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; D44C620F132DFF4E0009C878 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + D6B0611A1803AB670077942B /* CoreMotion.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMotion.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/CoreMotion.framework; sourceTree = DEVELOPER_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -301,6 +303,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D6B0611B1803AB670077942B /* CoreMotion.framework in Frameworks */, 1AF4C2F417865DCB00122817 /* libbox2d iOS.a in Frameworks */, 1AF4C2F517865DCB00122817 /* libchipmunk iOS.a in Frameworks */, 1AF4C2F617865DCB00122817 /* libcocos2dx iOS.a in Frameworks */, @@ -419,6 +422,7 @@ 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( + D6B0611A1803AB670077942B /* CoreMotion.framework */, 503AE11A17EB9C5A00D1A890 /* IOKit.framework */, 503AE11117EB99EE00D1A890 /* libcurl.dylib */, 5087E78A17EB975400C73F5D /* OpenGL.framework */, diff --git a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index 0601fd183a..9958c7a786 100644 --- a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -95,6 +95,7 @@ A92275501517C094001B78AA /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754F1517C094001B78AA /* CoreGraphics.framework */; }; D454520C156E22BD00887EB5 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D454520B156E22BD00887EB5 /* libz.dylib */; }; D4545227156E28EF00887EB5 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D4545215156E28EF00887EB5 /* AppDelegate.cpp */; }; + D6B061241803AB9F0077942B /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6B061231803AB9F0077942B /* CoreMotion.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -276,6 +277,7 @@ D454520B156E22BD00887EB5 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; D4545215156E28EF00887EB5 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = ""; }; D4545216156E28EF00887EB5 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + D6B061231803AB9F0077942B /* CoreMotion.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMotion.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/CoreMotion.framework; sourceTree = DEVELOPER_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -307,6 +309,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D6B061241803AB9F0077942B /* CoreMotion.framework in Frameworks */, 1AF4C33317865EC500122817 /* libchipmunk iOS.a in Frameworks */, 1AF4C33417865EC500122817 /* libcocos2dx iOS.a in Frameworks */, 1AF4C33517865EC500122817 /* libcocos2dx-extensions iOS.a in Frameworks */, @@ -437,6 +440,7 @@ A92275401517C094001B78AA /* Frameworks */ = { isa = PBXGroup; children = ( + D6B061231803AB9F0077942B /* CoreMotion.framework */, 502380DB17EBB88200990C9B /* libcurl.dylib */, 509D4AEA17EBB82600697056 /* IOKit.framework */, 509D4AE817EBB82000697056 /* AppKit.framework */, diff --git a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj index 2b9b653096..8403e89e8a 100644 --- a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj +++ b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj @@ -101,6 +101,7 @@ 50D7C97417EBBEF7005D0B91 /* libcocos2dx-extensions Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C3CF1786631700122817 /* libcocos2dx-extensions Mac.a */; }; 50D7C97517EBBEF7005D0B91 /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C3D51786631700122817 /* libCocosDenshion Mac.a */; }; 50D7C97617EBBEF7005D0B91 /* libluabindings Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C3D91786631700122817 /* libluabindings Mac.a */; }; + D6B061351803AC000077942B /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6B061341803AC000077942B /* CoreMotion.framework */; }; F293B3CD15EB7BE500256477 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3CC15EB7BE500256477 /* QuartzCore.framework */; }; F293B3D115EB7BE500256477 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D015EB7BE500256477 /* OpenAL.framework */; }; F293B3D315EB7BE500256477 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D215EB7BE500256477 /* AudioToolbox.framework */; }; @@ -285,6 +286,7 @@ 50D7C96B17EBBEDF005D0B91 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; 50D7C96D17EBBEE6005D0B91 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; }; 50D7C96F17EBBEEC005D0B91 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; }; + D6B061341803AC000077942B /* CoreMotion.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMotion.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/CoreMotion.framework; sourceTree = DEVELOPER_DIR; }; F293B3C815EB7BE500256477 /* HelloLua iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "HelloLua iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; F293B3CC15EB7BE500256477 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; F293B3CE15EB7BE500256477 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; @@ -326,6 +328,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D6B061351803AC000077942B /* CoreMotion.framework in Frameworks */, 50D7C96517EBBECA005D0B91 /* libbox2d iOS.a in Frameworks */, 50D7C96617EBBECA005D0B91 /* libchipmunk iOS.a in Frameworks */, 50D7C96717EBBECA005D0B91 /* libcocos2dx iOS.a in Frameworks */, @@ -462,6 +465,7 @@ F293B3CB15EB7BE500256477 /* Frameworks */ = { isa = PBXGroup; children = ( + D6B061341803AC000077942B /* CoreMotion.framework */, 50D7C96F17EBBEEC005D0B91 /* IOKit.framework */, 50D7C96D17EBBEE6005D0B91 /* AppKit.framework */, 50D7C96B17EBBEDF005D0B91 /* OpenGL.framework */, From 44a63bb885ea871c4fc09bd74d85db2ce9105244 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Tue, 8 Oct 2013 11:48:57 +0800 Subject: [PATCH 020/557] closed #2425: fix hole demo test error, we should use GLprogram before we set uniform to them --- cocos2dx/misc_nodes/CCClippingNode.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2dx/misc_nodes/CCClippingNode.cpp b/cocos2dx/misc_nodes/CCClippingNode.cpp index 5d3aeb741e..7b797617cb 100644 --- a/cocos2dx/misc_nodes/CCClippingNode.cpp +++ b/cocos2dx/misc_nodes/CCClippingNode.cpp @@ -311,6 +311,7 @@ void ClippingNode::visit() GLProgram *program = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST); GLint alphaValueLocation = glGetUniformLocation(program->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE); // set our alphaThreshold + program->use(); program->setUniformLocationWith1f(alphaValueLocation, _alphaThreshold); // we need to recursively apply this shader to all the nodes in the stencil node // XXX: we should have a way to apply shader to all nodes without having to do this From 5a5dd2da14be24c7e94b709efb8ce7b4861f0f9d Mon Sep 17 00:00:00 2001 From: LinWenhai Date: Tue, 8 Oct 2013 13:44:35 +0800 Subject: [PATCH 021/557] Update CCDevice.mm --- cocos2dx/platform/ios/CCDevice.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2dx/platform/ios/CCDevice.mm b/cocos2dx/platform/ios/CCDevice.mm index f678244da7..e84eb4196d 100644 --- a/cocos2dx/platform/ios/CCDevice.mm +++ b/cocos2dx/platform/ios/CCDevice.mm @@ -6,7 +6,7 @@ #import // Accelerometer -#include +#import #import @interface CCAccelerometerDispatcher : NSObject From 508654738ad263e652fbf2c06186b1a3f102c623 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Tue, 8 Oct 2013 15:45:13 +0800 Subject: [PATCH 022/557] issue #2768:Modify armature test sample and skip some functions to lua --- .../TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua | 2 +- tools/tolua/cocos2dx_extension.ini | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua index 7374719740..66a224d9e2 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -32,7 +32,7 @@ end function ArmatureTestScene:runThisTest() cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.json") + cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index 5f35f20cbe..ce914cf508 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -47,7 +47,7 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC ControlUtils::[*], ControlSwitchSprite::[*], ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], - Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc], + Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], Skin::[getSkinData setSkinData], ArmatureAnimation::[updateHandler updateFrameData frameEvent], Bone::[(s|g)etIgnoreMovementBoneData] From 20971b0ad2cec75fba2facd4fa5ac8aa249607f1 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 8 Oct 2013 15:57:34 +0800 Subject: [PATCH 023/557] issues #2895:Synchronize JSB from master to developer --- cocos2dx/base_nodes/CCNode.cpp | 8 + cocos2dx/base_nodes/CCNode.h | 9 + .../javascript/bindings/XMLHTTPRequest.cpp | 2 +- .../bindings/js/jsb_cocosbuilder.js | 4 +- .../jsb_cocos2dx_extension_manual.cpp | 216 ++++++++++++++++++ tools/tojs/cocos2dx.ini | 14 +- tools/tojs/cocos2dx_extension.ini | 16 +- 7 files changed, 253 insertions(+), 16 deletions(-) diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp index f4547bb1fa..8169029ebd 100644 --- a/cocos2dx/base_nodes/CCNode.cpp +++ b/cocos2dx/base_nodes/CCNode.cpp @@ -301,6 +301,14 @@ float Node::getScaleX() const return _scaleX; } +/// scale setter +void Node::setScale(float scaleX,float scaleY) +{ + _scaleX = scaleX; + _scaleY = scaleY; + _transformDirty = _inverseDirty = true; +} + /// scaleX setter void Node::setScaleX(float newScaleX) { diff --git a/cocos2dx/base_nodes/CCNode.h b/cocos2dx/base_nodes/CCNode.h index e335ff11fd..b84786126d 100644 --- a/cocos2dx/base_nodes/CCNode.h +++ b/cocos2dx/base_nodes/CCNode.h @@ -288,6 +288,15 @@ public: */ virtual float getScale() const; + /** + * Changes both X and Y scale factor of the node. + * + * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. + * + * @param scaleX The scale factor on X axis. + * @param scaleY The scale factor on Y axis. + */ + virtual void setScale(float scaleX,float scaleY); /** * Changes the position (x,y) of the node in OpenGL coordinates diff --git a/scripting/javascript/bindings/XMLHTTPRequest.cpp b/scripting/javascript/bindings/XMLHTTPRequest.cpp index a096756af5..e334833fa3 100644 --- a/scripting/javascript/bindings/XMLHTTPRequest.cpp +++ b/scripting/javascript/bindings/XMLHTTPRequest.cpp @@ -209,7 +209,7 @@ void MinXmlHttpRequest::handle_requestResponse(cocos2d::extension::HttpClient *s _status = 200; _readyState = DONE; _data << concatenated; - + _dataSize = buffer->size(); } else { diff --git a/scripting/javascript/bindings/js/jsb_cocosbuilder.js b/scripting/javascript/bindings/js/jsb_cocosbuilder.js index f748486286..7e70b8c70e 100644 --- a/scripting/javascript/bindings/js/jsb_cocosbuilder.js +++ b/scripting/javascript/bindings/js/jsb_cocosbuilder.js @@ -148,12 +148,12 @@ cc.BuilderReader.load = function(file, owner, parentSize) if (callbackType == 1) // Document callback { var callfunc = cc.CallFunc.create(controller[callbackName], controller); - animationManager.setCallFuncForJSCallbackNamed(callfunc, keyframeCallbacks[j]); + animationManager.setCallFunc(callfunc, keyframeCallbacks[j]); } else if (callbackType == 2 && owner) // Owner callback { var callfunc = cc.CallFunc.create(owner[callbackName], owner); - animationManager.setCallFuncForJSCallbackNamed(callfunc, keyframeCallbacks[j]); + animationManager.setCallFunc(callfunc, keyframeCallbacks[j]); } } diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index abaf07a2f7..3ec02a7d86 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -12,6 +12,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace extension::armature; class JSB_ScrollViewDelegate : public Object @@ -779,9 +780,218 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon return JS_FALSE; } +class JSArmatureWrapper: public JSCallbackWrapper { +public: + JSArmatureWrapper(); + virtual ~JSArmatureWrapper(); + + virtual void setJSCallbackThis(jsval thisObj); + + void movementCallbackFunc(cocos2d::extension::armature::Armature * pArmature, cocos2d::extension::armature::MovementEventType pMovementEventType, const char *pMovementId); + void frameCallbackFunc(cocos2d::extension::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + void addArmatureFileInfoAsyncCallbackFunc(float percent); + +private: + bool m_bNeedUnroot; +}; + +JSArmatureWrapper::JSArmatureWrapper() + : m_bNeedUnroot(false) +{ + +} + +JSArmatureWrapper::~JSArmatureWrapper() +{ + if (m_bNeedUnroot) + { + JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &thisObj); + } +} + +void JSArmatureWrapper::setJSCallbackThis(jsval _jsThisObj) +{ + JSCallbackWrapper::setJSCallbackThis(_jsThisObj); + + JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); + js_proxy *p = jsb_get_js_proxy(thisObj); + if (!p) + { + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddObjectRoot(cx, &thisObj); + m_bNeedUnroot = true; + } +} + +void JSArmatureWrapper::movementCallbackFunc(cocos2d::extension::armature::Armature *pArmature, cocos2d::extension::armature::MovementEventType pMovementEventType, const char *pMovementId) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + js_proxy_t *proxy = js_get_or_create_proxy(cx, pArmature); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + int movementEventType = (int)pMovementEventType; + jsval movementVal = INT_TO_JSVAL(movementEventType); + + jsval idVal = c_string_to_jsval(cx, pMovementId); + + jsval valArr[3]; + valArr[0] = OBJECT_TO_JSVAL(proxy->obj); + valArr[1] = movementVal; + valArr[2] = idVal; + + JS_AddValueRoot(cx, valArr); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); + JS_RemoveValueRoot(cx, valArr); + } +} + +void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + jsval percentVal = DOUBLE_TO_JSVAL(percent); + + JS_AddValueRoot(cx, &percentVal); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); + JS_RemoveValueRoot(cx, &percentVal); + } +} + + +void JSArmatureWrapper::frameCallbackFunc(cocos2d::extension::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + js_proxy_t *proxy = js_get_or_create_proxy(cx, pBone); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + jsval nameVal = c_string_to_jsval(cx, frameEventName); + jsval originIndexVal = INT_TO_JSVAL(originFrameIndex); + jsval currentIndexVal = INT_TO_JSVAL(currentFrameIndex); + + jsval valArr[4]; + valArr[0] = OBJECT_TO_JSVAL(proxy->obj); + valArr[1] = nameVal; + valArr[2] = originIndexVal; + valArr[3] = currentIndexVal; + + JS_AddValueRoot(cx, valArr); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); + JS_RemoveValueRoot(cx, valArr); + } +} + +static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::armature::ArmatureAnimation* cobj = (cocos2d::extension::armature::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 2) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[0]); + tmpObj->setJSCallbackThis(argv[1]); + + cobj->setMovementEventCallFunc(tmpObj, movementEvent_selector(JSArmatureWrapper::movementCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + +static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::armature::ArmatureAnimation* cobj = (cocos2d::extension::armature::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 2) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[0]); + tmpObj->setJSCallbackThis(argv[1]); + + cobj->setFrameEventCallFunc(tmpObj, frameEvent_selector(JSArmatureWrapper::frameCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + +static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::armature::ArmatureDataManager* cobj = (cocos2d::extension::armature::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 3) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[2]); + tmpObj->setJSCallbackThis(argv[1]); + + std::string ret; + jsval_to_std_string(cx, argv[0], &ret); + + cobj->addArmatureFileInfoAsync(ret.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); + + return JS_TRUE; + } + + if(argc == 5){ + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[4]); + tmpObj->setJSCallbackThis(argv[3]); + + std::string imagePath; + jsval_to_std_string(cx ,argv[0] , &imagePath); + + std::string plistPath; + jsval_to_std_string(cx ,argv[1] , &plistPath); + + std::string configFilePath; + jsval_to_std_string(cx ,argv[2] , &configFilePath); + + cobj->addArmatureFileInfoAsync(imagePath.c_str(), plistPath.c_str(), configFilePath.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + extern JSObject* jsb_ScrollView_prototype; extern JSObject* jsb_TableView_prototype; extern JSObject* jsb_EditBox_prototype; +extern JSObject* jsb_ArmatureAnimation_prototype; +extern JSObject* jsb_ArmatureDataManager_prototype; extern JSObject* jsb_Control_prototype; void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) @@ -793,6 +1003,12 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setMovementEventCallFunc", js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setFrameEventCallFunc", js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, jsb_ArmatureDataManager_prototype, "addArmatureFileInfoAsync", jsb_Animation_addArmatureFileInfoAsyncCallFunc, 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); } \ No newline at end of file diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index 9e2a2399af..7001e2f1f6 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -26,7 +26,7 @@ headers = %(cocosdir)s/cocos2dx/include/cocos2d.h %(cocosdir)s/CocosDenshion/inc # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set Data SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak +classes = Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set Data SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak TextFieldTTF EGLViewProtocol EGLView # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -49,7 +49,8 @@ skip = Node::[^setPosition$ getGrid setGLServerState description getUserObject . Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns], MenuItem.*::[create setCallback initWithCallback], Copying::[*], - .*Protocol::[*], + LabelProtocol::[*], + LabelTextFormatProtocol::[*], .*Delegate::[*], PoolManager::[*], Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData], @@ -67,7 +68,8 @@ skip = Node::[^setPosition$ getGrid setGLServerState description getUserObject . ScriptEngineManager::[*], KeypadHandler::[*], Invocation::[*], - EGLView::[*], + EGLView::[end swapBuffers], + EGLViewProtocol::[(?!setDesignResolutionSize|getVisibleSize|getVisibleOrigin)], SchedulerScriptHandlerEntry::[*], Size::[*], Point::[*], @@ -114,7 +116,7 @@ rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames ge Node::[removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren], LabelAtlas::[create=_create], Sprite::[initWithFile=init], - SpriteBatchNode::[initWithFile=init], + SpriteBatchNode::[initWithFile=init removeAllChildrenWithCleanup=removeAllChildren], Touch::[getID=getId], SimpleAudioEngine::[preloadBackgroundMusic=preloadMusic setBackgroundMusicVolume=setMusicVolume getBackgroundMusicVolume=getMusicVolume playBackgroundMusic=playMusic stopBackgroundMusic=stopMusic pauseBackgroundMusic=pauseMusic resumeBackgroundMusic=resumeMusic rewindBackgroundMusic=rewindMusic isBackgroundMusicPlaying=isMusicPlaying willPlayBackgroundMusic=willPlayMusic], FileUtils::[loadFilenameLookupDictionaryFromFile=loadFilenameLookup] @@ -126,14 +128,14 @@ rename_classes = ParticleSystemQuad::ParticleSystem, remove_prefix = # classes for which there will be no "parent" lookup -classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application +classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application EGLViewProtocol # base classes which will be skipped when their sub-classes found them. base_classes_to_skip = Object Clonable # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label +abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label EGLViewProtocol EGLView # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no diff --git a/tools/tojs/cocos2dx_extension.ini b/tools/tojs/cocos2dx_extension.ini index 41ecc9e5a6..a5170a5d86 100644 --- a/tools/tojs/cocos2dx_extension.ini +++ b/tools/tojs/cocos2dx_extension.ini @@ -26,7 +26,7 @@ headers = %(cocosdir)s/extensions/cocos-ext.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -47,13 +47,15 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*] + ControlSwitchSprite::[*], + Armature::[createBone updateBlendType getBody setBody getShapeList .*BlendFunc], + Skin::[getSkinData setSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent] -rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager], - CCBAnimationManager::[setCallFunc=setCallFuncForJSCallbackNamed] +rename_functions = rename_classes = CCBReader::_Reader, - CCBAnimationManager::AnimationManager + CCBAnimationManager::BuilderAnimationManager # for all class names, should we remove something when registering in the target VM? remove_prefix = @@ -62,11 +64,11 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Object +base_classes_to_skip = Object ProcessBase # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = +abstract_classes = ArmatureDataManager # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no From 98fc2e61d26dfebf9d246ec113229ed07649a5a8 Mon Sep 17 00:00:00 2001 From: rablwupei Date: Tue, 8 Oct 2013 19:50:24 +0800 Subject: [PATCH 024/557] add feature: cc.Sequence.create() and cc.Spawn.create() can pass Array actions. eg: cc.Sequence.create([cc.Show.create(), cc.Delay.create(1), cc.Hide.create()]); --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index ec4aa352c7..9ff7a17801 100644 --- a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -b88df18e2512b5111debda3991f51c2e72a2e5da \ No newline at end of file +db6aaa41d0756117258eebb759cd6420f66071e0 \ No newline at end of file From dee3065dbe8f64045718410db777bd94f75c25dc Mon Sep 17 00:00:00 2001 From: rablwupei Date: Tue, 8 Oct 2013 19:56:03 +0800 Subject: [PATCH 025/557] fix memory leak --- scripting/javascript/bindings/ScriptingCore.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 3a6f4aa4ae..33fd2aee1f 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -521,6 +521,7 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c &length); if (data) { script = JS_DecodeScript(cx, data, length, NULL, NULL); + CC_SAFE_DELETE_ARRAY(data); } // b) no jsc file, check js file From 5ea249a265e6d6f1ee88e94002bf721410a1245f Mon Sep 17 00:00:00 2001 From: rablwupei Date: Tue, 8 Oct 2013 20:03:10 +0800 Subject: [PATCH 026/557] fix memory leak --- extensions/spine/Atlas.cpp | 2 +- extensions/spine/SkeletonJson.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/spine/Atlas.cpp b/extensions/spine/Atlas.cpp index 281e214d77..8b9861463f 100644 --- a/extensions/spine/Atlas.cpp +++ b/extensions/spine/Atlas.cpp @@ -303,7 +303,7 @@ Atlas* Atlas_readAtlasFile (const char* path) { data = _Util_readFile(path, &length); if (data) atlas = Atlas_readAtlas(data, length, dir); - FREE(data); + delete [] data; FREE(dir); return atlas; } diff --git a/extensions/spine/SkeletonJson.cpp b/extensions/spine/SkeletonJson.cpp index 965a43f2a5..35a0daa787 100644 --- a/extensions/spine/SkeletonJson.cpp +++ b/extensions/spine/SkeletonJson.cpp @@ -240,7 +240,7 @@ SkeletonData* SkeletonJson_readSkeletonDataFile (SkeletonJson* self, const char* return 0; } skeletonData = SkeletonJson_readSkeletonData(self, json); - FREE(json); + delete [] json; return skeletonData; } From ce27a4eb141b6c950a4885e92e9406dc7a9cfa8b Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 9 Oct 2013 10:13:59 +0800 Subject: [PATCH 027/557] [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index a87525d295..5d8360eadb 100644 --- a/AUTHORS +++ b/AUTHORS @@ -615,6 +615,9 @@ Retired Core Developers: Project creator: use absolute path for json config files Documentation fixes A better way to locate project creator + + rablwupei + Fixed a memory leak in ScriptingCore::runScript() Cocos2d-x can not grow so fast without the active community. From 938db14bc3ae58cb5ed0157ab2517d9687bd2511 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 9 Oct 2013 02:14:04 +0000 Subject: [PATCH 028/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripting/auto-generated b/scripting/auto-generated index 946a5276fb..62651f8934 160000 --- a/scripting/auto-generated +++ b/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 946a5276fb9b072ee9ceeb8f49c1aeeea66ab9c4 +Subproject commit 62651f8934ba0225136b11d0c23bfd09c3aa2414 From 3548d46b380dd776f9e479cb6e4c7e2bcb03511f Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 9 Oct 2013 10:17:17 +0800 Subject: [PATCH 029/557] [ci skip] --- CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index febeb69cfa..b0f55118b9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -7,6 +7,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [Mac] [FIX] Removed unused CCLOG() from GL initialization +[Javascript binding] + [FIX] Fixed a memory leak in ScriptingCore::runScript() cocos2d-x-3.0alpha0 @Sep.19 2013 [all platforms] From 179eef9d8c617aa53e75352e54f3061a23bd4261 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 9 Oct 2013 11:25:45 +0800 Subject: [PATCH 030/557] [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 5d8360eadb..47e07250c2 100644 --- a/AUTHORS +++ b/AUTHORS @@ -618,6 +618,7 @@ Retired Core Developers: rablwupei Fixed a memory leak in ScriptingCore::runScript() + Fixed a memory leak in Spine Cocos2d-x can not grow so fast without the active community. From cd9689da1a1bae137abe7fd0393168e5cb3fd09a Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 9 Oct 2013 11:27:12 +0800 Subject: [PATCH 031/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index b0f55118b9..40fcdf73f6 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [all platforms] [DOC] Added RELEASE_NOTES and CODING_STYLE.md files [FIX] Texture: use CCLOG to log when a texture is being decoded in software + [FIX] Spine: fix memory leaks [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 4747e37acf176ac56901e2a8c3e2edfecd4bf1c2 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 9 Oct 2013 13:41:19 +0800 Subject: [PATCH 032/557] issue #2771: let PhysicsShape::create doesn't need to pass the PhysicsBody --- cocos2dx/physics/CCPhysicsBody.cpp | 58 +++++--- cocos2dx/physics/CCPhysicsSetting.h | 5 + cocos2dx/physics/CCPhysicsShape.cpp | 133 ++++++++++-------- cocos2dx/physics/CCPhysicsShape.h | 38 ++--- cocos2dx/physics/CCPhysicsWorld.cpp | 2 + .../physics/chipmunk/CCPhysicsShapeInfo.cpp | 7 + .../physics/chipmunk/CCPhysicsShapeInfo.h | 4 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 16 ++- 8 files changed, 162 insertions(+), 101 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index b8a961a302..44acb0c11f 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -42,6 +42,8 @@ #include "Box2D/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsWorldInfo.h" #include "Box2D/CCPhysicsWorldInfo.h" +#include "chipmunk/CCPhysicsShapeInfo.h" +#include "Box2D/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "Box2D/CCPhysicsHelper.h" @@ -95,7 +97,7 @@ PhysicsBody* PhysicsBody::createCircle(float radius, float density) PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeCircle::create(body, radius, density)); + body->addShape(PhysicsShapeCircle::create(radius, density)); body->autorelease(); return body; } @@ -109,7 +111,7 @@ PhysicsBody* PhysicsBody::createBox(Size size, float density) PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeBox::create(body, size, density)); + body->addShape(PhysicsShapeBox::create(size, density)); body->autorelease(); return body; } @@ -123,7 +125,7 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, float density) PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(body, points, count, density)); + body->addShape(PhysicsShapePolygon::create(points, count, density)); body->autorelease(); return body; } @@ -137,7 +139,7 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, float border/* = 1 PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeSegment::create(body, a, b, border)); + body->addShape(PhysicsShapeEdgeSegment::create(a, b, border)); body->_dynamic = false; body->autorelease(); return body; @@ -152,7 +154,7 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, float border/* = 1*/) PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeBox::create(body, size, border)); + body->addShape(PhysicsShapeEdgeBox::create(size, border)); body->_dynamic = false; body->autorelease(); return body; @@ -168,7 +170,7 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, float bord PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(body, points, count, border)); + body->addShape(PhysicsShapePolygon::create(points, count, border)); body->_dynamic = false; body->autorelease(); return body; @@ -184,7 +186,7 @@ PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, float border PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeChain::create(body, points, count, border)); + body->addShape(PhysicsShapeEdgeChain::create(points, count, border)); body->_dynamic = false; body->autorelease(); return body; @@ -221,8 +223,8 @@ void PhysicsBody::setDynamic(bool dynamic) cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_angularDamping)); }else { - cpBodySetMass(_info->body, INFINITY); - cpBodySetMoment(_info->body, INFINITY); + cpBodySetMass(_info->body, PHYSICS_INFINITY); + cpBodySetMoment(_info->body, PHYSICS_INFINITY); } _dynamic = dynamic; @@ -254,18 +256,37 @@ void PhysicsBody::addShape(PhysicsShape* shape) { if (shape == nullptr) return; - if (shape->getBody() != this) CCASSERT(false, ""); + // already added + if (shape->getBody() == this) + { + return; + } + else if (shape->getBody() != nullptr) + { + shape->getBody()->removeShape(shape); + } + // reset the body + if (shape->_info->body != _info->body) + { + for (cpShape* subShape : shape->_info->shapes) + { + cpShapeSetBody(subShape, _info->body); + } + shape->_info->body = _info->body; + } + + // add shape to body if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) { + shape->setBody(this); _shapes.push_back(shape); - shape->_isAddToBody = true; // calculate the mass, area and desity _area += shape->getArea(); - if (_mass == INFINITY || shape->getMass() == INFINITY) + if (_mass == PHYSICS_INFINITY || shape->getMass() == PHYSICS_INFINITY) { - _mass = INFINITY; + _mass = PHYSICS_INFINITY; _massDefault = false; }else { @@ -279,9 +300,9 @@ void PhysicsBody::addShape(PhysicsShape* shape) if (!_massDefault) { - if (_mass == INFINITY) + if (_mass == PHYSICS_INFINITY) { - _density = INFINITY; + _density = PHYSICS_INFINITY; }else { _density = _mass / _area; @@ -389,11 +410,10 @@ void PhysicsBody::removeShape(PhysicsShape* shape) } _shapes.erase(it); - shape->_isAddToBody = false; // deduce the mass, area and angularDamping - if (_mass != INFINITY && shape->getMass() != INFINITY) + if (_mass != PHYSICS_INFINITY && shape->getMass() != PHYSICS_INFINITY) { if (_mass - shape->getMass() <= 0) { @@ -406,9 +426,9 @@ void PhysicsBody::removeShape(PhysicsShape* shape) _area -= shape->getArea(); - if (_mass == INFINITY) + if (_mass == PHYSICS_INFINITY) { - _density = INFINITY; + _density = PHYSICS_INFINITY; } else if (_area > 0) { diff --git a/cocos2dx/physics/CCPhysicsSetting.h b/cocos2dx/physics/CCPhysicsSetting.h index 98b39f8f66..b29b12054d 100644 --- a/cocos2dx/physics/CCPhysicsSetting.h +++ b/cocos2dx/physics/CCPhysicsSetting.h @@ -43,4 +43,9 @@ #define CC_USE_PHYSICS #endif +namespace cocos2d +{ + extern const float PHYSICS_INFINITY; +} + #endif // __CCPHYSICS_SETTING_H__ diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index 35edfb5f1e..0b80d9ae68 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -52,7 +52,6 @@ PhysicsShape::PhysicsShape() , _density(0) , _tag(0) , _enable(true) -, _isAddToBody(false) { } @@ -62,12 +61,8 @@ PhysicsShape::~PhysicsShape() CC_SAFE_DELETE(_info); } -bool PhysicsShape::init(PhysicsBody* body, Type type) +bool PhysicsShape::init(Type type) { - if (body == nullptr) return false; - - _body = body; - _info = new PhysicsShapeInfo(this); if (_info == nullptr) return false; @@ -107,7 +102,13 @@ void PhysicsShape::addToBody() PhysicsBodyInfo* PhysicsShape::bodyInfo() const { - return _body->_info; + if (_body != nullptr) + { + return _body->_info; + }else + { + return nullptr; + } } PhysicsShapeCircle::PhysicsShapeCircle() @@ -182,11 +183,28 @@ PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment() #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + +void PhysicsShape::setElasticity(float elasticity) +{ + for (cpShape* shape : _info->shapes) + { + cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(elasticity)); + } +} + +void PhysicsShape::setFriction(float friction) +{ + for (cpShape* shape : _info->shapes) + { + cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); + } +} + // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(PhysicsBody* body, float radius, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); - if (shape && shape->init(body, radius, density, offset)) + if (shape && shape->init(radius, density, offset)) { shape->autorelease(); return shape; @@ -196,20 +214,20 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(PhysicsBody* body, float radius, return nullptr; } -bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(float radius, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::CIRCLE)); + CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); - cpShape* shape = cpCircleShapeNew(bodyInfo()->body, radius, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); _density = density; _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); - _mass = _density == INFINITY ? INFINITY : _density * _area; - _angularDamping = _mass == INFINITY ? INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); + _mass = _density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _density * _area; + _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); _info->add(shape); @@ -220,10 +238,10 @@ bool PhysicsShapeCircle::init(PhysicsBody* body, float radius, float density/* = } // PhysicsShapeEdgeSegment -PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(PhysicsBody* body, Point a, Point b, float border/* = 1*/) +PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, float border/* = 1*/) { PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); - if (shape && shape->init(body, a, b, border)) + if (shape && shape->init(a, b, border)) { shape->autorelease(); return shape; @@ -233,21 +251,21 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(PhysicsBody* body, Poin return nullptr; } -bool PhysicsShapeEdgeSegment::init(PhysicsBody* body, Point a, Point b, float border/* = 1*/) +bool PhysicsShapeEdgeSegment::init(Point a, Point b, float border/* = 1*/) { do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::EDGESEGMENT)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); - cpShape* shape = cpSegmentShapeNew(bodyInfo()->body, + cpShape* shape = cpSegmentShapeNew(_info->shareBody, PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(b), PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); - _density = INFINITY; - _angularDamping = INFINITY; + _density = PHYSICS_INFINITY; + _angularDamping = PHYSICS_INFINITY; _info->add(shape); @@ -258,10 +276,10 @@ bool PhysicsShapeEdgeSegment::init(PhysicsBody* body, Point a, Point b, float bo } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(PhysicsBody* body, Size size, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(Size size, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); - if (shape && shape->init(body, size, density, offset)) + if (shape && shape->init(size, density, offset)) { shape->autorelease(); return shape; @@ -271,13 +289,13 @@ PhysicsShapeBox* PhysicsShapeBox::create(PhysicsBody* body, Size size, float den return nullptr; } -bool PhysicsShapeBox::init(PhysicsBody* body, Size size, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(Size size, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::BOX)); + CC_BREAK_IF(!PhysicsShape::init(Type::BOX)); - cpShape* shape = cpBoxShapeNew(bodyInfo()->body, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); + cpShape* shape = cpBoxShapeNew(_info->shareBody, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); CC_BREAK_IF(shape == nullptr); @@ -298,10 +316,10 @@ bool PhysicsShapeBox::init(PhysicsBody* body, Size size, float density/* = 0*/, } // PhysicsShapeCircle -PhysicsShapePolygon* PhysicsShapePolygon::create(PhysicsBody* body, Point* points, int count, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, float density/* = 0*/, Point offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); - if (shape && shape->init(body, points, count, density, offset)) + if (shape && shape->init(points, count, density, offset)) { shape->autorelease(); return shape; @@ -311,15 +329,15 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(PhysicsBody* body, Point* point return nullptr; } -bool PhysicsShapePolygon::init(PhysicsBody* body, Point* points, int count, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapePolygon::init(Point* points, int count, float density/* = 0*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::POLYGEN)); + CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN)); cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - cpShape* shape = cpPolyShapeNew(bodyInfo()->body, count, vecs, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->shareBody, count, vecs, PhysicsHelper::point2cpv(offset)); CC_SAFE_DELETE(vecs); CC_BREAK_IF(shape == nullptr); @@ -341,10 +359,10 @@ bool PhysicsShapePolygon::init(PhysicsBody* body, Point* points, int count, floa } // PhysicsShapeEdgeBox -PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(PhysicsBody* body, Size size, float border/* = 1*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, float border/* = 1*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); - if (shape && shape->init(body, size, border, offset)) + if (shape && shape->init(size, border, offset)) { shape->autorelease(); return shape; @@ -354,24 +372,22 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(PhysicsBody* body, Size size, f return nullptr; } -bool PhysicsShapeEdgeBox::init(PhysicsBody* body, Size size, float border/* = 1*/, Point offset/*= Point(0, 0)*/) +bool PhysicsShapeEdgeBox::init(Size size, float border/* = 1*/, Point offset/*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::EDGEBOX)); - - Point bodyPos = body->getPosition(); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX)); cpVect vec[4] = {}; - vec[0] = PhysicsHelper::point2cpv(Point(bodyPos.x-size.width/2+offset.x, bodyPos.y-size.height/2+offset.y)); - vec[1] = PhysicsHelper::point2cpv(Point(bodyPos.x+size.width/2+offset.x, bodyPos.y-size.height/2+offset.y)); - vec[2] = PhysicsHelper::point2cpv(Point(bodyPos.x+size.width/2+offset.x, bodyPos.y+size.height/2+offset.y)); - vec[3] = PhysicsHelper::point2cpv(Point(bodyPos.x-size.width/2+offset.x, bodyPos.y+size.height/2+offset.y)); + vec[0] = PhysicsHelper::point2cpv(Point(-size.width/2+offset.x, -size.height/2+offset.y)); + vec[1] = PhysicsHelper::point2cpv(Point(+size.width/2+offset.x, -size.height/2+offset.y)); + vec[2] = PhysicsHelper::point2cpv(Point(+size.width/2+offset.x, +size.height/2+offset.y)); + vec[3] = PhysicsHelper::point2cpv(Point(-size.width/2+offset.x, +size.height/2+offset.y)); int i = 0; for (; i < 4; ++i) { - cpShape* shape = cpSegmentShapeNew(bodyInfo()->body, vec[i], vec[(i+1)%4], + cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%4], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -380,8 +396,8 @@ bool PhysicsShapeEdgeBox::init(PhysicsBody* body, Size size, float border/* = 1* } CC_BREAK_IF(i < 4); - _mass = INFINITY; - _angularDamping = INFINITY; + _mass = PHYSICS_INFINITY; + _angularDamping = PHYSICS_INFINITY; return true; } while (false); @@ -390,10 +406,10 @@ bool PhysicsShapeEdgeBox::init(PhysicsBody* body, Size size, float border/* = 1* } // PhysicsShapeEdgeBox -PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(PhysicsBody* body, Point* points, int count, float border/* = 1*/) +PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, float border/* = 1*/) { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); - if (shape && shape->init(body, points, count, border)) + if (shape && shape->init(points, count, border)) { shape->autorelease(); return shape; @@ -403,12 +419,12 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(PhysicsBody* body, Poin return nullptr; } -bool PhysicsShapeEdgePolygon::init(PhysicsBody* body, Point* points, int count, float border/* = 1*/) +bool PhysicsShapeEdgePolygon::init(Point* points, int count, float border/* = 1*/) { cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::EDGEPOLYGEN)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); @@ -416,7 +432,7 @@ bool PhysicsShapeEdgePolygon::init(PhysicsBody* body, Point* points, int count, int i = 0; for (; i < count; ++i) { - cpShape* shape = cpSegmentShapeNew(bodyInfo()->body, vec[i], vec[(i+1)%count], + cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%count], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -427,8 +443,8 @@ bool PhysicsShapeEdgePolygon::init(PhysicsBody* body, Point* points, int count, CC_BREAK_IF(i < count); - _mass = INFINITY; - _angularDamping = INFINITY; + _mass = PHYSICS_INFINITY; + _angularDamping = PHYSICS_INFINITY; return true; } while (false); @@ -439,10 +455,10 @@ bool PhysicsShapeEdgePolygon::init(PhysicsBody* body, Point* points, int count, } // PhysicsShapeEdgeChain -PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(PhysicsBody* body, Point* points, int count, float border/* = 1*/) +PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, float border/* = 1*/) { PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); - if (shape && shape->init(body, points, count, border)) + if (shape && shape->init(points, count, border)) { shape->autorelease(); return shape; @@ -452,12 +468,12 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(PhysicsBody* body, Point* p return nullptr; } -bool PhysicsShapeEdgeChain::init(PhysicsBody* body, Point* points, int count, float border/* = 1*/) +bool PhysicsShapeEdgeChain::init(Point* points, int count, float border/* = 1*/) { cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(body, Type::EDGECHAIN)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); @@ -465,7 +481,7 @@ bool PhysicsShapeEdgeChain::init(PhysicsBody* body, Point* points, int count, fl int i = 0; for (; i < count - 1; ++i) { - cpShape* shape = cpSegmentShapeNew(bodyInfo()->body, vec[i], vec[i+1], + cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[i+1], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -475,8 +491,8 @@ bool PhysicsShapeEdgeChain::init(PhysicsBody* body, Point* points, int count, fl if (vec != nullptr) delete[] vec; CC_BREAK_IF(i < count); - _mass = INFINITY; - _angularDamping = INFINITY; + _mass = PHYSICS_INFINITY; + _angularDamping = PHYSICS_INFINITY; return true; } while (false); @@ -486,7 +502,6 @@ bool PhysicsShapeEdgeChain::init(PhysicsBody* body, Point* points, int count, fl return false; } - #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 3d431f96e7..aea4a9e36d 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -71,14 +71,21 @@ public: inline bool isEnable() { return _enable; } void addToBody(); + void setElasticity(float elasticity); + void setFriction(float friction); + + + protected: - bool init(PhysicsBody* body, Type type); + bool init(Type type); /** * @brief PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ PhysicsBodyInfo* bodyInfo() const; + inline void setBody(PhysicsBody* body) { _body = body; } + protected: PhysicsShape(); virtual ~PhysicsShape() = 0; @@ -93,7 +100,6 @@ protected: float _density; int _tag; bool _enable; - bool _isAddToBody; friend class PhysicsWorld; friend class PhysicsBody; @@ -103,10 +109,10 @@ protected: class PhysicsShapeCircle : public PhysicsShape { public: - static PhysicsShapeCircle* create(PhysicsBody* body, float radius, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapeCircle* create(float radius, float density = 0, Point offset = Point(0, 0)); protected: - bool init(PhysicsBody* body, float radius, float density = 0, Point offset = Point(0, 0)); + bool init(float radius, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapeCircle(); @@ -119,10 +125,10 @@ protected: class PhysicsShapeBox : public PhysicsShape { public: - static PhysicsShapeBox* create(PhysicsBody* body, Size size, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapeBox* create(Size size, float density = 0, Point offset = Point(0, 0)); protected: - bool init(PhysicsBody* body, Size size, float density = 0, Point offset = Point(0, 0)); + bool init(Size size, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapeBox(); @@ -135,10 +141,10 @@ protected: class PhysicsShapePolygon : public PhysicsShape { public: - static PhysicsShapePolygon* create(PhysicsBody* body, Point* points, int count, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapePolygon* create(Point* points, int count, float density = 0, Point offset = Point(0, 0)); protected: - bool init(PhysicsBody* body, Point* points, int count, float density = 0, Point offset = Point(0, 0)); + bool init(Point* points, int count, float density = 0, Point offset = Point(0, 0)); protected: PhysicsShapePolygon(); @@ -151,10 +157,10 @@ protected: class PhysicsShapeEdgeSegment : public PhysicsShape { public: - static PhysicsShapeEdgeSegment* create(PhysicsBody* body, Point a, Point b, float border = 1); + static PhysicsShapeEdgeSegment* create(Point a, Point b, float border = 1); protected: - bool init(PhysicsBody* body, Point a, Point b, float border = 1); + bool init(Point a, Point b, float border = 1); protected: PhysicsShapeEdgeSegment(); @@ -167,10 +173,10 @@ protected: class PhysicsShapeEdgeBox : public PhysicsShape { public: - static PhysicsShapeEdgeBox* create(PhysicsBody* body, Size size, float border = 0, Point offset = Point(0, 0)); + static PhysicsShapeEdgeBox* create(Size size, float border = 0, Point offset = Point(0, 0)); protected: - bool init(PhysicsBody* body, Size size, float border = 1, Point offset = Point(0, 0)); + bool init(Size size, float border = 1, Point offset = Point(0, 0)); protected: PhysicsShapeEdgeBox(); @@ -183,10 +189,10 @@ protected: class PhysicsShapeEdgePolygon : public PhysicsShape { public: - static PhysicsShapeEdgePolygon* create(PhysicsBody* body, Point* points, int count, float border = 1); + static PhysicsShapeEdgePolygon* create(Point* points, int count, float border = 1); protected: - bool init(PhysicsBody* body, Point* points, int count, float border = 1); + bool init(Point* points, int count, float border = 1); protected: PhysicsShapeEdgePolygon(); @@ -199,10 +205,10 @@ protected: class PhysicsShapeEdgeChain : public PhysicsShape { public: - static PhysicsShapeEdgeChain* create(PhysicsBody* body, Point* points, int count, float border = 1); + static PhysicsShapeEdgeChain* create(Point* points, int count, float border = 1); protected: - bool init(PhysicsBody* body, Point* points, int count, float border = 1); + bool init(Point* points, int count, float border = 1); protected: PhysicsShapeEdgeChain(); diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 580fd5fe75..6f0fa1295c 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -57,6 +57,8 @@ NS_CC_BEGIN #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +const float PHYSICS_INFINITY = INFINITY; + int PhysicsWorld::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data) { PhysicsWorld* world = static_cast(data); diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp index 0e660792ad..0c048c780b 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp @@ -28,10 +28,17 @@ NS_CC_BEGIN std::map PhysicsShapeInfo::map; +cpBody* PhysicsShapeInfo::shareBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) : shape(shape) { + if (shareBody == nullptr) + { + shareBody = cpBodyNewStatic(); + } + + body = shareBody; } PhysicsShapeInfo::~PhysicsShapeInfo() diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h index 7e0be63747..5e9f2a73e3 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h @@ -46,8 +46,10 @@ public: public: std::vector shapes; - static std::map map; PhysicsShape* shape; + cpBody* body; + static std::map map; + static cpBody* shareBody; private: PhysicsShapeInfo(PhysicsShape* shape); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index ebab929dec..3135e2481a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -51,11 +51,7 @@ namespace bool PhysicsTestScene::initTest() { #ifdef CC_USE_PHYSICS - if (TestScene::initWithPhysics()) - { - this->getPhysicsWorld()->setDebugDraw(true); - return true; - } + return TestScene::initWithPhysics(); #else return TestScene::init(); #endif @@ -297,6 +293,12 @@ Node* PhysicsDemoLogoSmash::makeBall(float x, float y) ball->setScale(0.1); PhysicsBody* body = PhysicsBody::createCircle(0.95); + body->setMass(1.0); + body->setAngularDamping(PHYSICS_INFINITY); + + body->getShape()->setElasticity(0); + body->getShape()->setFriction(0); + //body->setDynamic(false); ball->setPhysicsBody(body); @@ -331,8 +333,10 @@ void PhysicsDemoLogoSmash::onEnter() Sprite* bullet = Sprite::create("Images/ball.png"); bullet->setScale(0.5); - PhysicsBody* body = PhysicsBody::createCircle(3, INFINITY); + PhysicsBody* body = PhysicsBody::createCircle(8, PHYSICS_INFINITY); body->setVelocity(Point(400, 0)); + body->getShape()->setElasticity(0); + body->getShape()->setFriction(0); bullet->setPhysicsBody(body); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); From 5b05731daf678c8349695575acc727a32ec69fd4 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 9 Oct 2013 14:23:36 +0800 Subject: [PATCH 033/557] Update AUTHORS. --- AUTHORS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 47e07250c2..2c056b6364 100644 --- a/AUTHORS +++ b/AUTHORS @@ -618,7 +618,8 @@ Retired Core Developers: rablwupei Fixed a memory leak in ScriptingCore::runScript() - Fixed a memory leak in Spine + Fixed a memory leak in Spine. + Added support of passing array to cc.Sequence.create and cc.Spawn.create. Cocos2d-x can not grow so fast without the active community. From ac16283d8a85ba9a0a91002c8acaf794e768535e Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 9 Oct 2013 06:28:04 +0000 Subject: [PATCH 034/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripting/auto-generated b/scripting/auto-generated index 62651f8934..ec90d1c35d 160000 --- a/scripting/auto-generated +++ b/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 62651f8934ba0225136b11d0c23bfd09c3aa2414 +Subproject commit ec90d1c35d06c1de3cb5079f885c22c45b8f129b From 476c5647be1997efaaaaa86ac2a8a657b53911bc Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 9 Oct 2013 15:55:04 +0800 Subject: [PATCH 035/557] closed #2909, Solve the Chinese string from C++ to JS is messy code in plugin. --- plugin | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin b/plugin index d583b83c58..915a29d230 160000 --- a/plugin +++ b/plugin @@ -1 +1 @@ -Subproject commit d583b83c5806a0d44788095dfc541fb2812c600e +Subproject commit 915a29d230b785bdea4bce39e643ce7ce667f6d0 From d51a04585cf6cd2b65d8e3397704cc51120aa440 Mon Sep 17 00:00:00 2001 From: rablwupei Date: Wed, 9 Oct 2013 16:48:05 +0800 Subject: [PATCH 036/557] fix bug: sys.localStorage.getItem() do not support utf8 in jsb. --- scripting/javascript/bindings/js_bindings_system_functions.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripting/javascript/bindings/js_bindings_system_functions.cpp b/scripting/javascript/bindings/js_bindings_system_functions.cpp index 9960f42b2c..1cb171224b 100644 --- a/scripting/javascript/bindings/js_bindings_system_functions.cpp +++ b/scripting/javascript/bindings/js_bindings_system_functions.cpp @@ -14,6 +14,7 @@ #include "js_bindings_core.h" #include "js_manual_conversions.h" #include "js_bindings_system_functions.h" +#include "ScriptingCore.h" USING_NS_CC; @@ -31,7 +32,7 @@ JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { ret_val = localStorageGetItem((char*)arg0 ); - jsval ret_jsval = charptr_to_jsval( cx, ret_val); + jsval ret_jsval = c_string_to_jsval(cx, ret_val ? ret_val : ""); JS_SET_RVAL(cx, vp, ret_jsval ); return JS_TRUE; From a4053c805ff006bd9c4d60368b270727e8074e1a Mon Sep 17 00:00:00 2001 From: rablwupei Date: Wed, 9 Oct 2013 16:51:37 +0800 Subject: [PATCH 037/557] fix XMLHTTPRequest.cpp memory leak --- scripting/javascript/bindings/XMLHTTPRequest.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripting/javascript/bindings/XMLHTTPRequest.cpp b/scripting/javascript/bindings/XMLHTTPRequest.cpp index e334833fa3..b799f6aacf 100644 --- a/scripting/javascript/bindings/XMLHTTPRequest.cpp +++ b/scripting/javascript/bindings/XMLHTTPRequest.cpp @@ -99,6 +99,8 @@ void MinXmlHttpRequest::_gotHeader(string header) pch = strtok (NULL, " "); } } + + CC_SAFE_DELETE_ARRAY(cstr); } /** From e03dd0714e63e3a920805e682d8306928554180d Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 9 Oct 2013 16:59:36 +0800 Subject: [PATCH 038/557] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 40fcdf73f6..9bc3581f84 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,6 +10,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Removed unused CCLOG() from GL initialization [Javascript binding] [FIX] Fixed a memory leak in ScriptingCore::runScript() + [FIX] sys.localStorage.getItem() does not support non-ascii string. cocos2d-x-3.0alpha0 @Sep.19 2013 [all platforms] From 23d1b4c3c254bb878cf3651917ef0cb019a6126f Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 9 Oct 2013 17:00:46 +0800 Subject: [PATCH 039/557] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 2c056b6364..dfec343959 100644 --- a/AUTHORS +++ b/AUTHORS @@ -620,6 +620,7 @@ Retired Core Developers: Fixed a memory leak in ScriptingCore::runScript() Fixed a memory leak in Spine. Added support of passing array to cc.Sequence.create and cc.Spawn.create. + Fixed a bug that sys.localStorage.getItem() does not support non-ascii string. Cocos2d-x can not grow so fast without the active community. From 6551ef2c169a7f6b63c56b63c8ee18cdebfeccff Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 9 Oct 2013 17:04:43 +0800 Subject: [PATCH 040/557] Update AUTHORS [ci skip] --- AUTHORS | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/AUTHORS b/AUTHORS index dfec343959..c4df157fd3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -587,18 +587,6 @@ Developers: signmotion (Andrey Syrokomsky) Fixed some compiling-warnings (MSVC2012). -Retired Core Developers: - WenSheng Yang - Author of windows port, CCTextField, - Designer of CCApplication/CCEGLView/platform structure. - He's working together with 2dx core team but leading FishingJoy game - - Bin Zhang - core-team member but put himself in FishingJoy game since 2012. - - RongHong Huang (flyingpaper) - Author of cocos2d-xna and spent all his time on wp7. - michaelcontento [Android] use onWindowFocusChanged(bool) instead of onResume()/onPause() Prevent nullptr access in AssetsManager @@ -621,6 +609,20 @@ Retired Core Developers: Fixed a memory leak in Spine. Added support of passing array to cc.Sequence.create and cc.Spawn.create. Fixed a bug that sys.localStorage.getItem() does not support non-ascii string. + Fixed a memory leak in XMLHttpRequest. + +Retired Core Developers: + WenSheng Yang + Author of windows port, CCTextField, + Designer of CCApplication/CCEGLView/platform structure. + He's working together with 2dx core team but leading FishingJoy game + + Bin Zhang + core-team member but put himself in FishingJoy game since 2012. + + RongHong Huang (flyingpaper) + Author of cocos2d-xna and spent all his time on wp7. + Cocos2d-x can not grow so fast without the active community. From e3b30b221b91355273909ef3239499cfd2497466 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 9 Oct 2013 17:06:55 +0800 Subject: [PATCH 041/557] Update CHNAGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 9bc3581f84..81416cfc94 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [DOC] Added RELEASE_NOTES and CODING_STYLE.md files [FIX] Texture: use CCLOG to log when a texture is being decoded in software [FIX] Spine: fix memory leaks + [FIX] fixed a memory leak in XMLHTTPRequest.cpp [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 381f904cd4e96ce2a74ecc799ae01e7fb2203e52 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 9 Oct 2013 17:53:12 +0800 Subject: [PATCH 042/557] issue #2771: add PhysicsMaterial --- .../CCScene.cpp | 1 + cocos2dx/physics/CCPhysicsBody.cpp | 43 +++-- cocos2dx/physics/CCPhysicsBody.h | 22 ++- cocos2dx/physics/CCPhysicsShape.cpp | 104 +++++++----- cocos2dx/physics/CCPhysicsShape.h | 65 ++++--- cocos2dx/physics/CCPhysicsWorld.cpp | 2 - .../Classes/PhysicsTest/PhysicsTest.cpp | 160 +++++++++++------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 34 +++- 8 files changed, 268 insertions(+), 163 deletions(-) diff --git a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp index 50b67e50e0..9081c5c630 100644 --- a/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp +++ b/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp @@ -43,6 +43,7 @@ Scene::Scene() Scene::~Scene() { + CC_SAFE_DELETE(_physicsWorld); } bool Scene::init() diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 44acb0c11f..4c2c1c65d7 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -92,12 +92,12 @@ PhysicsBody::~PhysicsBody() } } -PhysicsBody* PhysicsBody::createCircle(float radius, float density) +PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeCircle::create(radius, density)); + body->addShape(PhysicsShapeCircle::create(radius, material)); body->autorelease(); return body; } @@ -106,12 +106,12 @@ PhysicsBody* PhysicsBody::createCircle(float radius, float density) return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, float density) +PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeBox::create(size, density)); + body->addShape(PhysicsShapeBox::create(size, material)); body->autorelease(); return body; } @@ -120,12 +120,12 @@ PhysicsBody* PhysicsBody::createBox(Size size, float density) return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, float density) +PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(points, count, density)); + body->addShape(PhysicsShapePolygon::create(points, count, material)); body->autorelease(); return body; } @@ -134,12 +134,12 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, float density) return nullptr; } -PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeSegment::create(a, b, border)); + body->addShape(PhysicsShapeEdgeSegment::create(a, b, material, border)); body->_dynamic = false; body->autorelease(); return body; @@ -149,12 +149,12 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, float border/* = 1 return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeBox::create(size, border)); + body->addShape(PhysicsShapeEdgeBox::create(size, material, border)); body->_dynamic = false; body->autorelease(); return body; @@ -165,12 +165,12 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, float border/* = 1*/) return nullptr; } -PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(points, count, border)); + body->addShape(PhysicsShapeEdgePolygon::create(points, count, material, border)); body->_dynamic = false; body->autorelease(); return body; @@ -181,12 +181,12 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, float bord return nullptr; } -PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeChain::create(points, count, border)); + body->addShape(PhysicsShapeEdgeChain::create(points, count, material, border)); body->_dynamic = false; body->autorelease(); return body; @@ -311,9 +311,18 @@ void PhysicsBody::addShape(PhysicsShape* shape) if (shape->getAngularDumping() > 0) { - _angularDamping = (_angularDampingDefault ? 0 : _angularDamping) + shape->getAngularDumping(); - _angularDampingDefault = false; - cpBodySetMoment(_info->body, _angularDamping); + if (shape->getAngularDumping() == INFINITY) + { + _angularDamping = INFINITY; + _angularDampingDefault = false; + cpBodySetMoment(_info->body, _angularDamping); + } + else if (_angularDamping != INFINITY) + { + _angularDamping = (_angularDampingDefault ? 0 : _angularDamping) + shape->getAngularDumping(); + _angularDampingDefault = false; + cpBodySetMoment(_info->body, _angularDamping); + } } if (_world != nullptr) _world->addShape(shape); diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 580bec840d..505235de0a 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -30,15 +30,21 @@ #include "cocoa/CCObject.h" #include "cocoa/CCGeometry.h" + +#include "CCPhysicsShape.h" + #include NS_CC_BEGIN class Sprite; class PhysicsWorld; class PhysicsJoint; -class PhysicsShape; class PhysicsBodyInfo; + + +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; + /** * A body affect by physics. * it can attach one or more shapes. @@ -49,33 +55,33 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, float density = 1); + static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, float density = 1); + static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, float density = 1); + static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); /** * @brief Create a body contains a EdgeSegment shape. */ - static PhysicsBody* createEdgeSegment(Point a, Point b, float border = 1); + static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, float border = 1); + static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgePolygon shape. */ - static PhysicsBody* createEdgePolygon(Point* points, int count, float border = 1); + static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeChain shape. */ - static PhysicsBody* createEdgeChain(Point* points, int count, float border = 1); + static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); virtual void addShape(PhysicsShape* shape); diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index 0b80d9ae68..b373e0710e 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -49,7 +49,6 @@ PhysicsShape::PhysicsShape() , _area(0) , _mass(0) , _angularDamping(0) -, _density(0) , _tag(0) , _enable(true) { @@ -61,12 +60,13 @@ PhysicsShape::~PhysicsShape() CC_SAFE_DELETE(_info); } -bool PhysicsShape::init(Type type) +bool PhysicsShape::init(Type type, PhysicsMaterial material/* = MaterialDefault*/) { _info = new PhysicsShapeInfo(this); if (_info == nullptr) return false; _type = type; + _material = material; return true; } @@ -183,6 +183,14 @@ PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment() #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +void PhysicsShape::initEnd() +{ + for (auto shape : _info->shapes) + { + cpShapeSetElasticity(shape, _material.elasticity); + cpShapeSetFriction(shape, _material.friction); + } +} void PhysicsShape::setElasticity(float elasticity) { @@ -201,10 +209,10 @@ void PhysicsShape::setFriction(float friction) } // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); - if (shape && shape->init(radius, density, offset)) + if (shape && shape->init(radius, material, offset)) { shape->autorelease(); return shape; @@ -214,23 +222,23 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, float density/* = 0 return nullptr; } -bool PhysicsShapeCircle::init(float radius, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); + CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE, material)); cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); - _density = density; _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); - _mass = _density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _density * _area; + _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); _info->add(shape); + initEnd(); return true; } while (false); @@ -238,10 +246,10 @@ bool PhysicsShapeCircle::init(float radius, float density/* = 0*/, Point offset } // PhysicsShapeEdgeSegment -PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, float border/* = 1*/) +PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); - if (shape && shape->init(a, b, border)) + if (shape && shape->init(a, b, material, border)) { shape->autorelease(); return shape; @@ -251,11 +259,11 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, float return nullptr; } -bool PhysicsShapeEdgeSegment::init(Point a, Point b, float border/* = 1*/) +bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT, material)); cpShape* shape = cpSegmentShapeNew(_info->shareBody, PhysicsHelper::point2cpv(a), @@ -264,11 +272,13 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, float border/* = 1*/) CC_BREAK_IF(shape == nullptr); - _density = PHYSICS_INFINITY; + _mass = PHYSICS_INFINITY; _angularDamping = PHYSICS_INFINITY; _info->add(shape); + initEnd(); + return true; } while (false); @@ -276,10 +286,10 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, float border/* = 1*/) } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(Size size, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); - if (shape && shape->init(size, density, offset)) + if (shape && shape->init(size, material, offset)) { shape->autorelease(); return shape; @@ -289,26 +299,24 @@ PhysicsShapeBox* PhysicsShapeBox::create(Size size, float density/* = 0*/, Point return nullptr; } -bool PhysicsShapeBox::init(Size size, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::BOX)); + CC_BREAK_IF(!PhysicsShape::init(Type::BOX, material)); cpShape* shape = cpBoxShapeNew(_info->shareBody, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); CC_BREAK_IF(shape == nullptr); - _density = density; _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(4, ((cpPolyShape*)shape)->verts)); - _mass = _density * _area; - if (_mass != 0) - { - _angularDamping = cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); - } + _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; + _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); _info->add(shape); + initEnd(); + return true; } while (false); @@ -316,10 +324,10 @@ bool PhysicsShapeBox::init(Size size, float density/* = 0*/, Point offset /*= Po } // PhysicsShapeCircle -PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, float density/* = 0*/, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); - if (shape && shape->init(points, count, density, offset)) + if (shape && shape->init(points, count, material, offset)) { shape->autorelease(); return shape; @@ -329,11 +337,11 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, float return nullptr; } -bool PhysicsShapePolygon::init(Point* points, int count, float density/* = 0*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN)); + CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN, material)); cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -342,16 +350,14 @@ bool PhysicsShapePolygon::init(Point* points, int count, float density/* = 0*/, CC_BREAK_IF(shape == nullptr); - _density = density; _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); - _mass = _density * _area; - if (_mass != 0) - { - _angularDamping = cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); - } + _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; + _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); _info->add(shape); + initEnd(); + return true; } while (false); @@ -359,10 +365,10 @@ bool PhysicsShapePolygon::init(Point* points, int count, float density/* = 0*/, } // PhysicsShapeEdgeBox -PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, float border/* = 1*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/* = Point(0, 0)*/) { PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); - if (shape && shape->init(size, border, offset)) + if (shape && shape->init(size, material, border, offset)) { shape->autorelease(); return shape; @@ -372,11 +378,11 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, float border/* = 1*/ return nullptr; } -bool PhysicsShapeEdgeBox::init(Size size, float border/* = 1*/, Point offset/*= Point(0, 0)*/) +bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/*= Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX, material)); cpVect vec[4] = {}; vec[0] = PhysicsHelper::point2cpv(Point(-size.width/2+offset.x, -size.height/2+offset.y)); @@ -390,8 +396,6 @@ bool PhysicsShapeEdgeBox::init(Size size, float border/* = 1*/, Point offset/*= cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%4], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); - cpShapeSetElasticity(shape, 1.0f); - cpShapeSetFriction(shape, 1.0f); _info->add(shape); } CC_BREAK_IF(i < 4); @@ -399,6 +403,8 @@ bool PhysicsShapeEdgeBox::init(Size size, float border/* = 1*/, Point offset/*= _mass = PHYSICS_INFINITY; _angularDamping = PHYSICS_INFINITY; + initEnd(); + return true; } while (false); @@ -406,10 +412,10 @@ bool PhysicsShapeEdgeBox::init(Size size, float border/* = 1*/, Point offset/*= } // PhysicsShapeEdgeBox -PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, float border/* = 1*/) +PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); - if (shape && shape->init(points, count, border)) + if (shape && shape->init(points, count, material, border)) { shape->autorelease(); return shape; @@ -419,12 +425,12 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int coun return nullptr; } -bool PhysicsShapeEdgePolygon::init(Point* points, int count, float border/* = 1*/) +bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN, material)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); @@ -446,6 +452,8 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, float border/* = 1* _mass = PHYSICS_INFINITY; _angularDamping = PHYSICS_INFINITY; + initEnd(); + return true; } while (false); @@ -455,10 +463,10 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, float border/* = 1* } // PhysicsShapeEdgeChain -PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, float border/* = 1*/) +PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); - if (shape && shape->init(points, count, border)) + if (shape && shape->init(points, count, material, border)) { shape->autorelease(); return shape; @@ -468,12 +476,12 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, f return nullptr; } -bool PhysicsShapeEdgeChain::init(Point* points, int count, float border/* = 1*/) +bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN, material)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); @@ -494,6 +502,8 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, float border/* = 1*/) _mass = PHYSICS_INFINITY; _angularDamping = PHYSICS_INFINITY; + initEnd(); + return true; } while (false); diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index aea4a9e36d..d754f6030b 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -37,7 +37,27 @@ class PhysicsShapeInfo; class PhysicsBody; class PhysicsBodyInfo; -/** + +typedef struct PhysicsMaterial +{ + float density; + float elasticity; + float friction; + + PhysicsMaterial() + : density(0.0f) + , elasticity(0.0f) + , friction(0.0f){} + + PhysicsMaterial(float density, float elasticity, float friction) + : density(density) + , elasticity(elasticity) + , friction(friction){} +}PhysicsMaterial; + +const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; + +/** * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. */ class PhysicsShape : public Object @@ -58,11 +78,7 @@ public: public: inline PhysicsBody* getBody(){ return _body; } inline Type getType() { return _type; } - inline float getMass() { return _mass; } - void setMass(float mass); inline float getArea() { return _area; } - inline float getDensity() { return _density; } - void setDensity(float density); inline float getAngularDumping() { return _angularDamping; } void setAngularDumping(float angularDumping); inline void setTag(int tag) { _tag = tag; } @@ -71,13 +87,16 @@ public: inline bool isEnable() { return _enable; } void addToBody(); + inline float getMass() { return _mass; } + void setMass(float mass); + inline float getDensity() { return _material.density; } + void setDensity(float density); void setElasticity(float elasticity); void setFriction(float friction); - - protected: - bool init(Type type); + bool init(Type type, PhysicsMaterial material); + void initEnd(); /** * @brief PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. @@ -97,7 +116,7 @@ protected: float _area; float _mass; float _angularDamping; - float _density; + PhysicsMaterial _material; int _tag; bool _enable; @@ -109,10 +128,10 @@ protected: class PhysicsShapeCircle : public PhysicsShape { public: - static PhysicsShapeCircle* create(float radius, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: - bool init(float radius, float density = 0, Point offset = Point(0, 0)); + bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: PhysicsShapeCircle(); @@ -125,10 +144,10 @@ protected: class PhysicsShapeBox : public PhysicsShape { public: - static PhysicsShapeBox* create(Size size, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: - bool init(Size size, float density = 0, Point offset = Point(0, 0)); + bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: PhysicsShapeBox(); @@ -141,10 +160,10 @@ protected: class PhysicsShapePolygon : public PhysicsShape { public: - static PhysicsShapePolygon* create(Point* points, int count, float density = 0, Point offset = Point(0, 0)); + static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: - bool init(Point* points, int count, float density = 0, Point offset = Point(0, 0)); + bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: PhysicsShapePolygon(); @@ -157,10 +176,10 @@ protected: class PhysicsShapeEdgeSegment : public PhysicsShape { public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, float border = 1); + static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: - bool init(Point a, Point b, float border = 1); + bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeSegment(); @@ -173,10 +192,10 @@ protected: class PhysicsShapeEdgeBox : public PhysicsShape { public: - static PhysicsShapeEdgeBox* create(Size size, float border = 0, Point offset = Point(0, 0)); + static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); protected: - bool init(Size size, float border = 1, Point offset = Point(0, 0)); + bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); protected: PhysicsShapeEdgeBox(); @@ -189,10 +208,10 @@ protected: class PhysicsShapeEdgePolygon : public PhysicsShape { public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, float border = 1); + static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: - bool init(Point* points, int count, float border = 1); + bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgePolygon(); @@ -205,10 +224,10 @@ protected: class PhysicsShapeEdgeChain : public PhysicsShape { public: - static PhysicsShapeEdgeChain* create(Point* points, int count, float border = 1); + static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: - bool init(Point* points, int count, float border = 1); + bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeChain(); diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 6f0fa1295c..fa0c245e5e 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -286,7 +286,6 @@ void PhysicsWorld::debugDraw() void PhysicsWorld::setScene(Scene *scene) { _scene = scene; - scene->retain(); } void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) @@ -413,7 +412,6 @@ PhysicsWorld::~PhysicsWorld() { CC_SAFE_DELETE(_info); CC_SAFE_RELEASE(_bodys); - CC_SAFE_RELEASE(_scene); } NS_CC_END diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 3135e2481a..658cc606da 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -6,6 +6,7 @@ namespace { static std::function createFunctions[] = { CL(PhysicsDemoLogoSmash), + CL(PhysicsDemoPyramidStack), CL(PhysicsDemoClickAdd), }; @@ -48,10 +49,17 @@ namespace } } + +bool PhysicsTestScene::_debugDraw = false; + bool PhysicsTestScene::initTest() { #ifdef CC_USE_PHYSICS - return TestScene::initWithPhysics(); + if(TestScene::initWithPhysics()) + { + this->getPhysicsWorld()->setDebugDraw(_debugDraw); + return true; + } #else return TestScene::init(); #endif @@ -70,6 +78,12 @@ void PhysicsTestScene::runThisTest() #endif } +void PhysicsTestScene::toggleDebug() +{ + _debugDraw = !_debugDraw; + getPhysicsWorld()->setDebugDraw(_debugDraw); +} + PhysicsDemo::PhysicsDemo() : _scene(nullptr) { @@ -94,6 +108,7 @@ std::string PhysicsDemo::subtitle() void PhysicsDemo::restartCallback(Object* sender) { auto s = new PhysicsTestScene(); + s->initTest(); s->addChild( restart() ); Director::getInstance()->replaceScene(s); s->release(); @@ -102,6 +117,7 @@ void PhysicsDemo::restartCallback(Object* sender) void PhysicsDemo::nextCallback(Object* sender) { auto s = new PhysicsTestScene(); + s->initTest(); s->addChild( next() ); Director::getInstance()->replaceScene(s); s->release(); @@ -110,6 +126,7 @@ void PhysicsDemo::nextCallback(Object* sender) void PhysicsDemo::backCallback(Object* sender) { auto s = new PhysicsTestScene(); + s->initTest(); s->addChild( back() ); Director::getInstance()->replaceScene(s); s->release(); @@ -119,7 +136,10 @@ void PhysicsDemo::onEnter() { BaseTest::onEnter(); - _scene = dynamic_cast(this->getParent()); + _scene = dynamic_cast(this->getParent()); + + _spriteTexture = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100)->getTexture(); + #ifdef CC_USE_PHYSICS // menu for debug layer MenuItemFont::setFontSize(18); @@ -132,48 +152,7 @@ void PhysicsDemo::onEnter() #endif } - -void PhysicsDemo::toggleDebugCallback(Object* sender) -{ -#ifdef CC_USE_PHYSICS - if (_scene != nullptr) - { - _scene->getPhysicsWorld()->setDebugDraw(!_scene->getPhysicsWorld()->isDebugDraw()); - } -#endif -} - -void PhysicsDemoClickAdd::onEnter() -{ - PhysicsDemo::onEnter(); - -#ifdef CC_USE_PHYSICS - setTouchEnabled(true); - setAccelerometerEnabled(true); - - auto node = Node::create(); - auto body = PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size); - node->setPhysicsBody(body); - node->setPosition(VisibleRect::center()); - this->addChild(node); - - auto parent = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - _spriteTexture = parent->getTexture(); - - addNewSpriteAtPosition(VisibleRect::center()); - -#else - auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", - "Arial", - 18); - auto size = Director::getInstance()->getWinSize(); - label->setPosition(Point(size.width/2, size.height/2)); - - addChild(label); -#endif -} - -void PhysicsDemoClickAdd::addNewSpriteAtPosition(Point p) +void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { #ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); @@ -187,13 +166,50 @@ void PhysicsDemoClickAdd::addNewSpriteAtPosition(Point p) posy = (posy % 3) * 121; auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); - auto body = PhysicsBody::createBox(Size(48, 108)); - sp->setPhysicsBody(body); + sp->setScale(scale); + sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); #endif } + +void PhysicsDemo::toggleDebugCallback(Object* sender) +{ +#ifdef CC_USE_PHYSICS + if (_scene != nullptr) + { + _scene->toggleDebug(); + } +#endif +} + +void PhysicsDemoClickAdd::onEnter() +{ + PhysicsDemo::onEnter(); + +#ifdef CC_USE_PHYSICS + setTouchEnabled(true); + setAccelerometerEnabled(true); + + auto node = Node::create(); + node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->setPosition(VisibleRect::center()); + this->addChild(node); + + addGrossiniAtPosition(VisibleRect::center()); + +#else + auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", + "Arial", + 18); + auto size = Director::getInstance()->getWinSize(); + label->setPosition(Point(size.width/2, size.height/2)); + + addChild(label); +#endif +} + std::string PhysicsDemoClickAdd::subtitle() { return "multi touch to add grossini"; @@ -207,7 +223,7 @@ void PhysicsDemoClickAdd::onTouchesEnded(const std::vector& touches, Eve { auto location = touch->getLocation(); - addNewSpriteAtPosition( location ); + addGrossiniAtPosition( location ); } } @@ -289,16 +305,13 @@ namespace Node* PhysicsDemoLogoSmash::makeBall(float x, float y) { - Sprite* ball = Sprite::create("Images/ball.png"); + auto ball = Sprite::create("Images/ball.png"); ball->setScale(0.1); - PhysicsBody* body = PhysicsBody::createCircle(0.95); + auto body = PhysicsBody::createCircle(0.95, PhysicsMaterial(1, 0, 0)); body->setMass(1.0); body->setAngularDamping(PHYSICS_INFINITY); - body->getShape()->setElasticity(0); - body->getShape()->setFriction(0); - //body->setDynamic(false); ball->setPhysicsBody(body); @@ -310,7 +323,6 @@ Node* PhysicsDemoLogoSmash::makeBall(float x, float y) void PhysicsDemoLogoSmash::onEnter() { PhysicsDemo::onEnter(); - _draw = DrawNode::create(); _scene->getPhysicsWorld()->setGravity(Point(0, 0)); //addChild(makeBall(200, 200)); @@ -330,13 +342,11 @@ void PhysicsDemoLogoSmash::onEnter() } - Sprite* bullet = Sprite::create("Images/ball.png"); + auto bullet = Sprite::create("Images/ball.png"); bullet->setScale(0.5); - PhysicsBody* body = PhysicsBody::createCircle(8, PHYSICS_INFINITY); + auto body = PhysicsBody::createCircle(8, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); body->setVelocity(Point(400, 0)); - body->getShape()->setElasticity(0); - body->getShape()->setFriction(0); bullet->setPhysicsBody(body); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -347,4 +357,40 @@ void PhysicsDemoLogoSmash::onEnter() std::string PhysicsDemoLogoSmash::title() { return "Logo Smash"; +} + +void PhysicsDemoPyramidStack::onEnter() +{ + PhysicsDemo::onEnter(); + + auto node = Node::create(); + node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(node); + + auto ball = Sprite::create("Images/ball.png"); + ball->setScale(1); + ball->setPhysicsBody(PhysicsBody::createCircle(10)); + ball->setPosition(VisibleRect::bottom() + Point(0, 60)); + this->addChild(ball); + + for(int i=0; i<14; i++){ + for(int j=0; j<=i; j++){ + addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2); + } + } +} +std::string PhysicsDemoPyramidStack::title() +{ + return "Pyramid Stack"; +} + + +void PhysicsDemoPlink::onEnter() +{ + PhysicsDemo::onEnter(); +} + +std::string PhysicsDemoPlink::title() +{ + return "Plink"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index cf63471998..c75431a852 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -11,12 +11,17 @@ class PhysicsTestScene : public TestScene public: virtual bool initTest() override; virtual void runThisTest(); + + void toggleDebug(); + +private: + static bool _debugDraw; }; class PhysicsDemo : public BaseTest { protected: - Scene* _scene; + PhysicsTestScene* _scene; public: PhysicsDemo(); @@ -30,6 +35,11 @@ public: void nextCallback(Object* sender); void backCallback(Object* sender); void toggleDebugCallback(Object* sender); + + void addGrossiniAtPosition(Point p, float scale = 1.0); + +private: + Texture2D* _spriteTexture; // weak ref }; class PhysicsDemoClickAdd : public PhysicsDemo @@ -38,13 +48,8 @@ public: void onEnter() override; std::string subtitle() override; - void addNewSpriteAtPosition(Point p); - void onTouchesEnded(const std::vector& touches, Event* event) override; void onAcceleration(Acceleration* acc, Event* event) override; - -private: - Texture2D* _spriteTexture; // weak ref }; class PhysicsDemoLogoSmash : public PhysicsDemo @@ -54,9 +59,20 @@ public: std::string title() override; Node* makeBall(float x, float y); - -private: - DrawNode* _draw; +}; + +class PhysicsDemoPyramidStack : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; +}; + +class PhysicsDemoPlink : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; }; #endif From 7756c7765100bf0ac8ac25b0c5cda0bf81946ce3 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 9 Oct 2013 18:09:24 +0800 Subject: [PATCH 043/557] issues #2899:Fix application will crash when back to background on Android. --- cocos2dx/platform/android/jni/JniHelper.cpp | 11 ++++++++++- cocos2dx/platform/android/jni/JniHelper.h | 1 + cocos2dx/platform/android/nativeactivity.cpp | 6 +++--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/cocos2dx/platform/android/jni/JniHelper.cpp b/cocos2dx/platform/android/jni/JniHelper.cpp index 852208afc3..22a3807df2 100644 --- a/cocos2dx/platform/android/jni/JniHelper.cpp +++ b/cocos2dx/platform/android/jni/JniHelper.cpp @@ -58,6 +58,8 @@ namespace cocos2d { jobject JniHelper::classloader = NULL; JNIEnv* JniHelper::env = NULL; + static pthread_key_t thread_key; + JavaVM* JniHelper::getJavaVM() { pthread_t thisthread = pthread_self(); LOGD("JniHelper::getJavaVM(), pthread_self() = %X", thisthread); @@ -72,6 +74,10 @@ namespace cocos2d { JniHelper::cacheEnv(javaVM); } + void JniHelper::detach_current_thread (void *env) { + _psJavaVM->DetachCurrentThread(); + } + bool JniHelper::cacheEnv(JavaVM* jvm) { JNIEnv* _env = NULL; // get jni environment @@ -89,7 +95,8 @@ namespace cocos2d { // TODO : If calling AttachCurrentThread() on a native thread // must call DetachCurrentThread() in future. // see: http://developer.android.com/guide/practices/design/jni.html - + + pthread_key_create (&thread_key, JniHelper::detach_current_thread); if (jvm->AttachCurrentThread(&_env, NULL) < 0) { LOGD("Failed to get the environment using AttachCurrentThread()"); @@ -99,6 +106,8 @@ namespace cocos2d { } else { // Success : Attached and obtained JNIEnv! JniHelper::env = _env; + if (pthread_getspecific(thread_key) == NULL) + pthread_setspecific(thread_key, _env); return true; } diff --git a/cocos2dx/platform/android/jni/JniHelper.h b/cocos2dx/platform/android/jni/JniHelper.h index 01405d9559..fe1bf38814 100644 --- a/cocos2dx/platform/android/jni/JniHelper.h +++ b/cocos2dx/platform/android/jni/JniHelper.h @@ -60,6 +60,7 @@ public: static jobject classloader; private: + static void detach_current_thread (void *env); static bool cacheEnv(JavaVM* jvm); static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo, diff --git a/cocos2dx/platform/android/nativeactivity.cpp b/cocos2dx/platform/android/nativeactivity.cpp index c5d387433a..aa0f8f8199 100644 --- a/cocos2dx/platform/android/nativeactivity.cpp +++ b/cocos2dx/platform/android/nativeactivity.cpp @@ -215,10 +215,10 @@ static cocos_dimensions engine_init_display(struct engine* engine) { /** * Invoke the dispatching of the next bunch of Runnables in the Java-Land */ +static bool initialized = false; static void dispatch_pending_runnables() { static cocos2d::JniMethodInfo info; - static bool initialized = false; - + if (!initialized) { initialized = cocos2d::JniHelper::getStaticMethodInfo( info, @@ -652,7 +652,7 @@ void android_main(struct android_app* state) { engine_term_display(&engine); memset(&engine, 0, sizeof(engine)); - + initialized = false; return; } } From a17f141e7dd70ea6e031b3fb5037f76d452b6903 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 10 Oct 2013 10:28:49 +0800 Subject: [PATCH 044/557] issues #2914:removeSpriteFramesFromFile() crashes if file doesn't exist --- cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp b/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp index 945cd30f32..1d19773c60 100644 --- a/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp +++ b/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp @@ -344,7 +344,11 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); - + if (dict == nullptr) + { + CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist); + return; + } removeSpriteFramesFromDictionary((Dictionary*)dict); // remove it from the cache From b5ee16399c0285f0e80ebb3a10575ed4f103e066 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Thu, 10 Oct 2013 11:09:09 +0800 Subject: [PATCH 045/557] =?UTF-8?q?issue=20#2768:Modify=20the=20linux=20ma?= =?UTF-8?q?ke=20files=20of=20the=20liblua=20=E3=80=81the=20testlua=20and?= =?UTF-8?q?=20hellolua=20projects?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- samples/Lua/HelloLua/proj.linux/Makefile | 2 +- samples/Lua/TestLua/proj.linux/Makefile | 2 +- scripting/lua/proj.linux/Makefile | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/samples/Lua/HelloLua/proj.linux/Makefile b/samples/Lua/HelloLua/proj.linux/Makefile index 9c80a175dd..f0b63ea010 100644 --- a/samples/Lua/HelloLua/proj.linux/Makefile +++ b/samples/Lua/HelloLua/proj.linux/Makefile @@ -10,7 +10,7 @@ INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ SOURCES = main.cpp ../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -lextension -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so $(LIB_DIR)/libbox2d.so +COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk diff --git a/samples/Lua/TestLua/proj.linux/Makefile b/samples/Lua/TestLua/proj.linux/Makefile index 6d73226774..cb88cc9a93 100644 --- a/samples/Lua/TestLua/proj.linux/Makefile +++ b/samples/Lua/TestLua/proj.linux/Makefile @@ -9,7 +9,7 @@ INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ SOURCES = main.cpp ../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so $(LIB_DIR)/libbox2d.so +COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk diff --git a/scripting/lua/proj.linux/Makefile b/scripting/lua/proj.linux/Makefile index b718baf883..3e49658d56 100644 --- a/scripting/lua/proj.linux/Makefile +++ b/scripting/lua/proj.linux/Makefile @@ -59,6 +59,7 @@ include ../../../cocos2dx/proj.linux/cocos2dx.mk TARGET := $(LIB_DIR)/$(TARGET) SHAREDLIBS += -lextension +STATICLIBS += $(LIB_DIR)/libbox2d.a all: $(TARGET) From a8f0c99abf82f707c24071f31503fe41f3759d25 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 10 Oct 2013 11:12:33 +0800 Subject: [PATCH 046/557] Fix miss project configuration for CoreMotion. --- samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index dc39ae6bd3..ec33bf839a 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -d846dfb9965fecfad1f6fe6190516035158c4d53 \ No newline at end of file +381c282bed409f4b41a82505460d4d6c84ba70ab \ No newline at end of file From 78e3624b0bd7c4fa1dd1ba8fc49334f184301b77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 10 Oct 2013 11:15:22 +0800 Subject: [PATCH 047/557] Update CHANGELOG[ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 81416cfc94..6a3d593beb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Texture: use CCLOG to log when a texture is being decoded in software [FIX] Spine: fix memory leaks [FIX] fixed a memory leak in XMLHTTPRequest.cpp + [FIX] removeSpriteFramesFromFile() crashes if file doesn't exist. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 6b400dd4eca4c6643562b0fbc85b6706c13fb332 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 10 Oct 2013 11:30:42 +0800 Subject: [PATCH 048/557] rename some variable --- cocos2dx/platform/android/jni/JniHelper.cpp | 8 ++++---- cocos2dx/platform/android/nativeactivity.cpp | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos2dx/platform/android/jni/JniHelper.cpp b/cocos2dx/platform/android/jni/JniHelper.cpp index 22a3807df2..ab3bfc3855 100644 --- a/cocos2dx/platform/android/jni/JniHelper.cpp +++ b/cocos2dx/platform/android/jni/JniHelper.cpp @@ -58,7 +58,7 @@ namespace cocos2d { jobject JniHelper::classloader = NULL; JNIEnv* JniHelper::env = NULL; - static pthread_key_t thread_key; + static pthread_key_t s_threadKey; JavaVM* JniHelper::getJavaVM() { pthread_t thisthread = pthread_self(); @@ -96,7 +96,7 @@ namespace cocos2d { // must call DetachCurrentThread() in future. // see: http://developer.android.com/guide/practices/design/jni.html - pthread_key_create (&thread_key, JniHelper::detach_current_thread); + pthread_key_create (&s_threadKey, JniHelper::detach_current_thread); if (jvm->AttachCurrentThread(&_env, NULL) < 0) { LOGD("Failed to get the environment using AttachCurrentThread()"); @@ -106,8 +106,8 @@ namespace cocos2d { } else { // Success : Attached and obtained JNIEnv! JniHelper::env = _env; - if (pthread_getspecific(thread_key) == NULL) - pthread_setspecific(thread_key, _env); + if (pthread_getspecific(s_threadKey) == NULL) + pthread_setspecific(s_threadKey, _env); return true; } diff --git a/cocos2dx/platform/android/nativeactivity.cpp b/cocos2dx/platform/android/nativeactivity.cpp index aa0f8f8199..b591953fb8 100644 --- a/cocos2dx/platform/android/nativeactivity.cpp +++ b/cocos2dx/platform/android/nativeactivity.cpp @@ -215,19 +215,19 @@ static cocos_dimensions engine_init_display(struct engine* engine) { /** * Invoke the dispatching of the next bunch of Runnables in the Java-Land */ -static bool initialized = false; +static bool s_methodInitialized = false; static void dispatch_pending_runnables() { static cocos2d::JniMethodInfo info; - if (!initialized) { - initialized = cocos2d::JniHelper::getStaticMethodInfo( + if (!s_methodInitialized) { + s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo( info, "org/cocos2dx/lib/Cocos2dxHelper", "dispatchPendingRunnables", "()V" ); - if (!initialized) { + if (!s_methodInitialized) { LOGW("Unable to dispatch pending Runnables!"); return; } @@ -652,7 +652,7 @@ void android_main(struct android_app* state) { engine_term_display(&engine); memset(&engine, 0, sizeof(engine)); - initialized = false; + s_methodInitialized = false; return; } } From a02b2b6834a4cc0b05940956b738edbe6967ee12 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 10 Oct 2013 13:55:22 +0800 Subject: [PATCH 049/557] Update CHANGELOG [ci skip] --- CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 6a3d593beb..b9641d1f71 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [Javascript binding] [FIX] Fixed a memory leak in ScriptingCore::runScript() [FIX] sys.localStorage.getItem() does not support non-ascii string. +[Lua Binding] + [FIX] Added Armature lua binding and added test samples. cocos2d-x-3.0alpha0 @Sep.19 2013 [all platforms] From c46f74b084ad2a9fd41bb3fede7885b11ec568aa Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 10 Oct 2013 14:06:53 +0800 Subject: [PATCH 050/557] issue 2905:SimpleAudioEngine -> audio --- {CocosDenshion => audio}/android/Android.mk | 0 {CocosDenshion => audio}/android/ccdandroidUtils.cpp | 0 {CocosDenshion => audio}/android/ccdandroidUtils.h | 0 {CocosDenshion => audio}/android/cddSimpleAudioEngine.cpp | 0 .../android/jni/cddandroidAndroidJavaEngine.cpp | 0 .../android/jni/cddandroidAndroidJavaEngine.h | 0 {CocosDenshion => audio}/android/opensl/OpenSLEngine.cpp | 0 {CocosDenshion => audio}/android/opensl/OpenSLEngine.h | 0 .../android/opensl/SimpleAudioEngineOpenSL.cpp | 0 {CocosDenshion => audio}/android/opensl/SimpleAudioEngineOpenSL.h | 0 .../android/opensl/cddandroidOpenSLEngine.cpp | 0 {CocosDenshion => audio}/android/opensl/cddandroidOpenSLEngine.h | 0 {CocosDenshion => audio}/emscripten/SimpleAudioEngine.cpp | 0 {CocosDenshion => audio}/include/Export.h | 0 {CocosDenshion => audio}/include/SimpleAudioEngine.h | 0 {CocosDenshion => audio}/ios/CDAudioManager.h | 0 {CocosDenshion => audio}/ios/CDAudioManager.m | 0 {CocosDenshion => audio}/ios/CDConfig.h | 0 {CocosDenshion => audio}/ios/CDOpenALSupport.h | 0 {CocosDenshion => audio}/ios/CDOpenALSupport.m | 0 {CocosDenshion => audio}/ios/CocosDenshion.h | 0 {CocosDenshion => audio}/ios/CocosDenshion.m | 0 {CocosDenshion => audio}/ios/SimpleAudioEngine.mm | 0 {CocosDenshion => audio}/ios/SimpleAudioEngine_objc.h | 0 {CocosDenshion => audio}/ios/SimpleAudioEngine_objc.m | 0 {CocosDenshion => audio}/linux/AudioPlayer.h | 0 {CocosDenshion => audio}/linux/FmodAudioPlayer.cpp | 0 {CocosDenshion => audio}/linux/FmodAudioPlayer.h | 0 {CocosDenshion => audio}/linux/SimpleAudioEngineFMOD.cpp | 0 {CocosDenshion => audio}/mac/CDAudioManager.h | 0 {CocosDenshion => audio}/mac/CDAudioManager.m | 0 {CocosDenshion => audio}/mac/CDConfig.h | 0 {CocosDenshion => audio}/mac/CDOpenALSupport.h | 0 {CocosDenshion => audio}/mac/CDOpenALSupport.m | 0 {CocosDenshion => audio}/mac/CDXMacOSXSupport.h | 0 {CocosDenshion => audio}/mac/CDXMacOSXSupport.mm | 0 {CocosDenshion => audio}/mac/CocosDenshion.h | 0 {CocosDenshion => audio}/mac/CocosDenshion.m | 0 {CocosDenshion => audio}/mac/SimpleAudioEngine.mm | 0 {CocosDenshion => audio}/mac/SimpleAudioEngine_objc.h | 0 {CocosDenshion => audio}/mac/SimpleAudioEngine_objc.m | 0 {CocosDenshion => audio}/openal/OpenALDecoder.cpp | 0 {CocosDenshion => audio}/openal/OpenALDecoder.h | 0 {CocosDenshion => audio}/openal/SimpleAudioEngineOpenAL.cpp | 0 {CocosDenshion => audio}/proj.emscripten/Makefile | 0 .../proj.ios/CocosDenshion.xcodeproj/project.pbxproj | 0 {CocosDenshion => audio}/proj.linux/.cproject | 0 {CocosDenshion => audio}/proj.linux/.project | 0 {CocosDenshion => audio}/proj.linux/CocosDenshion.prf | 0 {CocosDenshion => audio}/proj.linux/Makefile | 0 .../proj.mac/CocosDenshion.xcodeproj/project.pbxproj | 0 {CocosDenshion => audio}/proj.nacl/Makefile | 0 {CocosDenshion => audio}/proj.qt5/cocosdenshion.pro | 0 {CocosDenshion => audio}/proj.tizen/.cproject | 0 {CocosDenshion => audio}/proj.tizen/.project | 0 {CocosDenshion => audio}/proj.tizen/src/placeholder.txt | 0 {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj | 0 {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj.filters | 0 {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj.user | 0 {CocosDenshion => audio}/qt5/SimpleAudioEngineQt5.cpp | 0 {CocosDenshion => audio}/third_party/fmod/Makefile | 0 .../third_party/fmod/api/inc/fmod.h.REMOVED.git-id | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmod.hpp | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_codec.h | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_dsp.h | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_errors.h | 0 .../third_party/fmod/api/inc/fmod_memoryinfo.h | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_output.h | 0 {CocosDenshion => audio}/third_party/fmod/api/inc/fmodlinux.h | 0 .../third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id | 0 .../third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id | 0 .../third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id | 0 .../third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id | 0 {CocosDenshion => audio}/third_party/fmod/lib64/Makefile | 0 .../third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id | 0 {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod.hpp | 0 .../third_party/fmod/lib64/api/inc/fmod_codec.h | 0 .../third_party/fmod/lib64/api/inc/fmod_dsp.h | 0 .../third_party/fmod/lib64/api/inc/fmod_errors.h | 0 .../third_party/fmod/lib64/api/inc/fmod_memoryinfo.h | 0 .../third_party/fmod/lib64/api/inc/fmod_output.h | 0 .../third_party/fmod/lib64/api/inc/fmodlinux.h | 0 .../fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id | 0 .../third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id | 0 .../fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id | 0 .../third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id | 0 {CocosDenshion => audio}/win32/MciPlayer.cpp | 0 {CocosDenshion => audio}/win32/MciPlayer.h | 0 {CocosDenshion => audio}/win32/SimpleAudioEngine.cpp | 0 89 files changed, 0 insertions(+), 0 deletions(-) rename {CocosDenshion => audio}/android/Android.mk (100%) rename {CocosDenshion => audio}/android/ccdandroidUtils.cpp (100%) rename {CocosDenshion => audio}/android/ccdandroidUtils.h (100%) rename {CocosDenshion => audio}/android/cddSimpleAudioEngine.cpp (100%) rename {CocosDenshion => audio}/android/jni/cddandroidAndroidJavaEngine.cpp (100%) rename {CocosDenshion => audio}/android/jni/cddandroidAndroidJavaEngine.h (100%) rename {CocosDenshion => audio}/android/opensl/OpenSLEngine.cpp (100%) rename {CocosDenshion => audio}/android/opensl/OpenSLEngine.h (100%) rename {CocosDenshion => audio}/android/opensl/SimpleAudioEngineOpenSL.cpp (100%) rename {CocosDenshion => audio}/android/opensl/SimpleAudioEngineOpenSL.h (100%) rename {CocosDenshion => audio}/android/opensl/cddandroidOpenSLEngine.cpp (100%) rename {CocosDenshion => audio}/android/opensl/cddandroidOpenSLEngine.h (100%) rename {CocosDenshion => audio}/emscripten/SimpleAudioEngine.cpp (100%) rename {CocosDenshion => audio}/include/Export.h (100%) rename {CocosDenshion => audio}/include/SimpleAudioEngine.h (100%) rename {CocosDenshion => audio}/ios/CDAudioManager.h (100%) rename {CocosDenshion => audio}/ios/CDAudioManager.m (100%) rename {CocosDenshion => audio}/ios/CDConfig.h (100%) rename {CocosDenshion => audio}/ios/CDOpenALSupport.h (100%) rename {CocosDenshion => audio}/ios/CDOpenALSupport.m (100%) rename {CocosDenshion => audio}/ios/CocosDenshion.h (100%) rename {CocosDenshion => audio}/ios/CocosDenshion.m (100%) rename {CocosDenshion => audio}/ios/SimpleAudioEngine.mm (100%) rename {CocosDenshion => audio}/ios/SimpleAudioEngine_objc.h (100%) rename {CocosDenshion => audio}/ios/SimpleAudioEngine_objc.m (100%) rename {CocosDenshion => audio}/linux/AudioPlayer.h (100%) rename {CocosDenshion => audio}/linux/FmodAudioPlayer.cpp (100%) rename {CocosDenshion => audio}/linux/FmodAudioPlayer.h (100%) rename {CocosDenshion => audio}/linux/SimpleAudioEngineFMOD.cpp (100%) rename {CocosDenshion => audio}/mac/CDAudioManager.h (100%) rename {CocosDenshion => audio}/mac/CDAudioManager.m (100%) rename {CocosDenshion => audio}/mac/CDConfig.h (100%) rename {CocosDenshion => audio}/mac/CDOpenALSupport.h (100%) rename {CocosDenshion => audio}/mac/CDOpenALSupport.m (100%) rename {CocosDenshion => audio}/mac/CDXMacOSXSupport.h (100%) rename {CocosDenshion => audio}/mac/CDXMacOSXSupport.mm (100%) rename {CocosDenshion => audio}/mac/CocosDenshion.h (100%) rename {CocosDenshion => audio}/mac/CocosDenshion.m (100%) rename {CocosDenshion => audio}/mac/SimpleAudioEngine.mm (100%) rename {CocosDenshion => audio}/mac/SimpleAudioEngine_objc.h (100%) rename {CocosDenshion => audio}/mac/SimpleAudioEngine_objc.m (100%) rename {CocosDenshion => audio}/openal/OpenALDecoder.cpp (100%) rename {CocosDenshion => audio}/openal/OpenALDecoder.h (100%) rename {CocosDenshion => audio}/openal/SimpleAudioEngineOpenAL.cpp (100%) rename {CocosDenshion => audio}/proj.emscripten/Makefile (100%) rename {CocosDenshion => audio}/proj.ios/CocosDenshion.xcodeproj/project.pbxproj (100%) rename {CocosDenshion => audio}/proj.linux/.cproject (100%) rename {CocosDenshion => audio}/proj.linux/.project (100%) rename {CocosDenshion => audio}/proj.linux/CocosDenshion.prf (100%) rename {CocosDenshion => audio}/proj.linux/Makefile (100%) rename {CocosDenshion => audio}/proj.mac/CocosDenshion.xcodeproj/project.pbxproj (100%) rename {CocosDenshion => audio}/proj.nacl/Makefile (100%) rename {CocosDenshion => audio}/proj.qt5/cocosdenshion.pro (100%) rename {CocosDenshion => audio}/proj.tizen/.cproject (100%) rename {CocosDenshion => audio}/proj.tizen/.project (100%) rename {CocosDenshion => audio}/proj.tizen/src/placeholder.txt (100%) rename {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj (100%) rename {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj.filters (100%) rename {CocosDenshion => audio}/proj.win32/CocosDenshion.vcxproj.user (100%) rename {CocosDenshion => audio}/qt5/SimpleAudioEngineQt5.cpp (100%) rename {CocosDenshion => audio}/third_party/fmod/Makefile (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod.h.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod.hpp (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_codec.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_dsp.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_errors.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_memoryinfo.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmod_output.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/inc/fmodlinux.h (100%) rename {CocosDenshion => audio}/third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/Makefile (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod.hpp (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod_codec.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod_dsp.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod_errors.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod_memoryinfo.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmod_output.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/inc/fmodlinux.h (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id (100%) rename {CocosDenshion => audio}/win32/MciPlayer.cpp (100%) rename {CocosDenshion => audio}/win32/MciPlayer.h (100%) rename {CocosDenshion => audio}/win32/SimpleAudioEngine.cpp (100%) diff --git a/CocosDenshion/android/Android.mk b/audio/android/Android.mk similarity index 100% rename from CocosDenshion/android/Android.mk rename to audio/android/Android.mk diff --git a/CocosDenshion/android/ccdandroidUtils.cpp b/audio/android/ccdandroidUtils.cpp similarity index 100% rename from CocosDenshion/android/ccdandroidUtils.cpp rename to audio/android/ccdandroidUtils.cpp diff --git a/CocosDenshion/android/ccdandroidUtils.h b/audio/android/ccdandroidUtils.h similarity index 100% rename from CocosDenshion/android/ccdandroidUtils.h rename to audio/android/ccdandroidUtils.h diff --git a/CocosDenshion/android/cddSimpleAudioEngine.cpp b/audio/android/cddSimpleAudioEngine.cpp similarity index 100% rename from CocosDenshion/android/cddSimpleAudioEngine.cpp rename to audio/android/cddSimpleAudioEngine.cpp diff --git a/CocosDenshion/android/jni/cddandroidAndroidJavaEngine.cpp b/audio/android/jni/cddandroidAndroidJavaEngine.cpp similarity index 100% rename from CocosDenshion/android/jni/cddandroidAndroidJavaEngine.cpp rename to audio/android/jni/cddandroidAndroidJavaEngine.cpp diff --git a/CocosDenshion/android/jni/cddandroidAndroidJavaEngine.h b/audio/android/jni/cddandroidAndroidJavaEngine.h similarity index 100% rename from CocosDenshion/android/jni/cddandroidAndroidJavaEngine.h rename to audio/android/jni/cddandroidAndroidJavaEngine.h diff --git a/CocosDenshion/android/opensl/OpenSLEngine.cpp b/audio/android/opensl/OpenSLEngine.cpp similarity index 100% rename from CocosDenshion/android/opensl/OpenSLEngine.cpp rename to audio/android/opensl/OpenSLEngine.cpp diff --git a/CocosDenshion/android/opensl/OpenSLEngine.h b/audio/android/opensl/OpenSLEngine.h similarity index 100% rename from CocosDenshion/android/opensl/OpenSLEngine.h rename to audio/android/opensl/OpenSLEngine.h diff --git a/CocosDenshion/android/opensl/SimpleAudioEngineOpenSL.cpp b/audio/android/opensl/SimpleAudioEngineOpenSL.cpp similarity index 100% rename from CocosDenshion/android/opensl/SimpleAudioEngineOpenSL.cpp rename to audio/android/opensl/SimpleAudioEngineOpenSL.cpp diff --git a/CocosDenshion/android/opensl/SimpleAudioEngineOpenSL.h b/audio/android/opensl/SimpleAudioEngineOpenSL.h similarity index 100% rename from CocosDenshion/android/opensl/SimpleAudioEngineOpenSL.h rename to audio/android/opensl/SimpleAudioEngineOpenSL.h diff --git a/CocosDenshion/android/opensl/cddandroidOpenSLEngine.cpp b/audio/android/opensl/cddandroidOpenSLEngine.cpp similarity index 100% rename from CocosDenshion/android/opensl/cddandroidOpenSLEngine.cpp rename to audio/android/opensl/cddandroidOpenSLEngine.cpp diff --git a/CocosDenshion/android/opensl/cddandroidOpenSLEngine.h b/audio/android/opensl/cddandroidOpenSLEngine.h similarity index 100% rename from CocosDenshion/android/opensl/cddandroidOpenSLEngine.h rename to audio/android/opensl/cddandroidOpenSLEngine.h diff --git a/CocosDenshion/emscripten/SimpleAudioEngine.cpp b/audio/emscripten/SimpleAudioEngine.cpp similarity index 100% rename from CocosDenshion/emscripten/SimpleAudioEngine.cpp rename to audio/emscripten/SimpleAudioEngine.cpp diff --git a/CocosDenshion/include/Export.h b/audio/include/Export.h similarity index 100% rename from CocosDenshion/include/Export.h rename to audio/include/Export.h diff --git a/CocosDenshion/include/SimpleAudioEngine.h b/audio/include/SimpleAudioEngine.h similarity index 100% rename from CocosDenshion/include/SimpleAudioEngine.h rename to audio/include/SimpleAudioEngine.h diff --git a/CocosDenshion/ios/CDAudioManager.h b/audio/ios/CDAudioManager.h similarity index 100% rename from CocosDenshion/ios/CDAudioManager.h rename to audio/ios/CDAudioManager.h diff --git a/CocosDenshion/ios/CDAudioManager.m b/audio/ios/CDAudioManager.m similarity index 100% rename from CocosDenshion/ios/CDAudioManager.m rename to audio/ios/CDAudioManager.m diff --git a/CocosDenshion/ios/CDConfig.h b/audio/ios/CDConfig.h similarity index 100% rename from CocosDenshion/ios/CDConfig.h rename to audio/ios/CDConfig.h diff --git a/CocosDenshion/ios/CDOpenALSupport.h b/audio/ios/CDOpenALSupport.h similarity index 100% rename from CocosDenshion/ios/CDOpenALSupport.h rename to audio/ios/CDOpenALSupport.h diff --git a/CocosDenshion/ios/CDOpenALSupport.m b/audio/ios/CDOpenALSupport.m similarity index 100% rename from CocosDenshion/ios/CDOpenALSupport.m rename to audio/ios/CDOpenALSupport.m diff --git a/CocosDenshion/ios/CocosDenshion.h b/audio/ios/CocosDenshion.h similarity index 100% rename from CocosDenshion/ios/CocosDenshion.h rename to audio/ios/CocosDenshion.h diff --git a/CocosDenshion/ios/CocosDenshion.m b/audio/ios/CocosDenshion.m similarity index 100% rename from CocosDenshion/ios/CocosDenshion.m rename to audio/ios/CocosDenshion.m diff --git a/CocosDenshion/ios/SimpleAudioEngine.mm b/audio/ios/SimpleAudioEngine.mm similarity index 100% rename from CocosDenshion/ios/SimpleAudioEngine.mm rename to audio/ios/SimpleAudioEngine.mm diff --git a/CocosDenshion/ios/SimpleAudioEngine_objc.h b/audio/ios/SimpleAudioEngine_objc.h similarity index 100% rename from CocosDenshion/ios/SimpleAudioEngine_objc.h rename to audio/ios/SimpleAudioEngine_objc.h diff --git a/CocosDenshion/ios/SimpleAudioEngine_objc.m b/audio/ios/SimpleAudioEngine_objc.m similarity index 100% rename from CocosDenshion/ios/SimpleAudioEngine_objc.m rename to audio/ios/SimpleAudioEngine_objc.m diff --git a/CocosDenshion/linux/AudioPlayer.h b/audio/linux/AudioPlayer.h similarity index 100% rename from CocosDenshion/linux/AudioPlayer.h rename to audio/linux/AudioPlayer.h diff --git a/CocosDenshion/linux/FmodAudioPlayer.cpp b/audio/linux/FmodAudioPlayer.cpp similarity index 100% rename from CocosDenshion/linux/FmodAudioPlayer.cpp rename to audio/linux/FmodAudioPlayer.cpp diff --git a/CocosDenshion/linux/FmodAudioPlayer.h b/audio/linux/FmodAudioPlayer.h similarity index 100% rename from CocosDenshion/linux/FmodAudioPlayer.h rename to audio/linux/FmodAudioPlayer.h diff --git a/CocosDenshion/linux/SimpleAudioEngineFMOD.cpp b/audio/linux/SimpleAudioEngineFMOD.cpp similarity index 100% rename from CocosDenshion/linux/SimpleAudioEngineFMOD.cpp rename to audio/linux/SimpleAudioEngineFMOD.cpp diff --git a/CocosDenshion/mac/CDAudioManager.h b/audio/mac/CDAudioManager.h similarity index 100% rename from CocosDenshion/mac/CDAudioManager.h rename to audio/mac/CDAudioManager.h diff --git a/CocosDenshion/mac/CDAudioManager.m b/audio/mac/CDAudioManager.m similarity index 100% rename from CocosDenshion/mac/CDAudioManager.m rename to audio/mac/CDAudioManager.m diff --git a/CocosDenshion/mac/CDConfig.h b/audio/mac/CDConfig.h similarity index 100% rename from CocosDenshion/mac/CDConfig.h rename to audio/mac/CDConfig.h diff --git a/CocosDenshion/mac/CDOpenALSupport.h b/audio/mac/CDOpenALSupport.h similarity index 100% rename from CocosDenshion/mac/CDOpenALSupport.h rename to audio/mac/CDOpenALSupport.h diff --git a/CocosDenshion/mac/CDOpenALSupport.m b/audio/mac/CDOpenALSupport.m similarity index 100% rename from CocosDenshion/mac/CDOpenALSupport.m rename to audio/mac/CDOpenALSupport.m diff --git a/CocosDenshion/mac/CDXMacOSXSupport.h b/audio/mac/CDXMacOSXSupport.h similarity index 100% rename from CocosDenshion/mac/CDXMacOSXSupport.h rename to audio/mac/CDXMacOSXSupport.h diff --git a/CocosDenshion/mac/CDXMacOSXSupport.mm b/audio/mac/CDXMacOSXSupport.mm similarity index 100% rename from CocosDenshion/mac/CDXMacOSXSupport.mm rename to audio/mac/CDXMacOSXSupport.mm diff --git a/CocosDenshion/mac/CocosDenshion.h b/audio/mac/CocosDenshion.h similarity index 100% rename from CocosDenshion/mac/CocosDenshion.h rename to audio/mac/CocosDenshion.h diff --git a/CocosDenshion/mac/CocosDenshion.m b/audio/mac/CocosDenshion.m similarity index 100% rename from CocosDenshion/mac/CocosDenshion.m rename to audio/mac/CocosDenshion.m diff --git a/CocosDenshion/mac/SimpleAudioEngine.mm b/audio/mac/SimpleAudioEngine.mm similarity index 100% rename from CocosDenshion/mac/SimpleAudioEngine.mm rename to audio/mac/SimpleAudioEngine.mm diff --git a/CocosDenshion/mac/SimpleAudioEngine_objc.h b/audio/mac/SimpleAudioEngine_objc.h similarity index 100% rename from CocosDenshion/mac/SimpleAudioEngine_objc.h rename to audio/mac/SimpleAudioEngine_objc.h diff --git a/CocosDenshion/mac/SimpleAudioEngine_objc.m b/audio/mac/SimpleAudioEngine_objc.m similarity index 100% rename from CocosDenshion/mac/SimpleAudioEngine_objc.m rename to audio/mac/SimpleAudioEngine_objc.m diff --git a/CocosDenshion/openal/OpenALDecoder.cpp b/audio/openal/OpenALDecoder.cpp similarity index 100% rename from CocosDenshion/openal/OpenALDecoder.cpp rename to audio/openal/OpenALDecoder.cpp diff --git a/CocosDenshion/openal/OpenALDecoder.h b/audio/openal/OpenALDecoder.h similarity index 100% rename from CocosDenshion/openal/OpenALDecoder.h rename to audio/openal/OpenALDecoder.h diff --git a/CocosDenshion/openal/SimpleAudioEngineOpenAL.cpp b/audio/openal/SimpleAudioEngineOpenAL.cpp similarity index 100% rename from CocosDenshion/openal/SimpleAudioEngineOpenAL.cpp rename to audio/openal/SimpleAudioEngineOpenAL.cpp diff --git a/CocosDenshion/proj.emscripten/Makefile b/audio/proj.emscripten/Makefile similarity index 100% rename from CocosDenshion/proj.emscripten/Makefile rename to audio/proj.emscripten/Makefile diff --git a/CocosDenshion/proj.ios/CocosDenshion.xcodeproj/project.pbxproj b/audio/proj.ios/CocosDenshion.xcodeproj/project.pbxproj similarity index 100% rename from CocosDenshion/proj.ios/CocosDenshion.xcodeproj/project.pbxproj rename to audio/proj.ios/CocosDenshion.xcodeproj/project.pbxproj diff --git a/CocosDenshion/proj.linux/.cproject b/audio/proj.linux/.cproject similarity index 100% rename from CocosDenshion/proj.linux/.cproject rename to audio/proj.linux/.cproject diff --git a/CocosDenshion/proj.linux/.project b/audio/proj.linux/.project similarity index 100% rename from CocosDenshion/proj.linux/.project rename to audio/proj.linux/.project diff --git a/CocosDenshion/proj.linux/CocosDenshion.prf b/audio/proj.linux/CocosDenshion.prf similarity index 100% rename from CocosDenshion/proj.linux/CocosDenshion.prf rename to audio/proj.linux/CocosDenshion.prf diff --git a/CocosDenshion/proj.linux/Makefile b/audio/proj.linux/Makefile similarity index 100% rename from CocosDenshion/proj.linux/Makefile rename to audio/proj.linux/Makefile diff --git a/CocosDenshion/proj.mac/CocosDenshion.xcodeproj/project.pbxproj b/audio/proj.mac/CocosDenshion.xcodeproj/project.pbxproj similarity index 100% rename from CocosDenshion/proj.mac/CocosDenshion.xcodeproj/project.pbxproj rename to audio/proj.mac/CocosDenshion.xcodeproj/project.pbxproj diff --git a/CocosDenshion/proj.nacl/Makefile b/audio/proj.nacl/Makefile similarity index 100% rename from CocosDenshion/proj.nacl/Makefile rename to audio/proj.nacl/Makefile diff --git a/CocosDenshion/proj.qt5/cocosdenshion.pro b/audio/proj.qt5/cocosdenshion.pro similarity index 100% rename from CocosDenshion/proj.qt5/cocosdenshion.pro rename to audio/proj.qt5/cocosdenshion.pro diff --git a/CocosDenshion/proj.tizen/.cproject b/audio/proj.tizen/.cproject similarity index 100% rename from CocosDenshion/proj.tizen/.cproject rename to audio/proj.tizen/.cproject diff --git a/CocosDenshion/proj.tizen/.project b/audio/proj.tizen/.project similarity index 100% rename from CocosDenshion/proj.tizen/.project rename to audio/proj.tizen/.project diff --git a/CocosDenshion/proj.tizen/src/placeholder.txt b/audio/proj.tizen/src/placeholder.txt similarity index 100% rename from CocosDenshion/proj.tizen/src/placeholder.txt rename to audio/proj.tizen/src/placeholder.txt diff --git a/CocosDenshion/proj.win32/CocosDenshion.vcxproj b/audio/proj.win32/CocosDenshion.vcxproj similarity index 100% rename from CocosDenshion/proj.win32/CocosDenshion.vcxproj rename to audio/proj.win32/CocosDenshion.vcxproj diff --git a/CocosDenshion/proj.win32/CocosDenshion.vcxproj.filters b/audio/proj.win32/CocosDenshion.vcxproj.filters similarity index 100% rename from CocosDenshion/proj.win32/CocosDenshion.vcxproj.filters rename to audio/proj.win32/CocosDenshion.vcxproj.filters diff --git a/CocosDenshion/proj.win32/CocosDenshion.vcxproj.user b/audio/proj.win32/CocosDenshion.vcxproj.user similarity index 100% rename from CocosDenshion/proj.win32/CocosDenshion.vcxproj.user rename to audio/proj.win32/CocosDenshion.vcxproj.user diff --git a/CocosDenshion/qt5/SimpleAudioEngineQt5.cpp b/audio/qt5/SimpleAudioEngineQt5.cpp similarity index 100% rename from CocosDenshion/qt5/SimpleAudioEngineQt5.cpp rename to audio/qt5/SimpleAudioEngineQt5.cpp diff --git a/CocosDenshion/third_party/fmod/Makefile b/audio/third_party/fmod/Makefile similarity index 100% rename from CocosDenshion/third_party/fmod/Makefile rename to audio/third_party/fmod/Makefile diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod.h.REMOVED.git-id b/audio/third_party/fmod/api/inc/fmod.h.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod.h.REMOVED.git-id rename to audio/third_party/fmod/api/inc/fmod.h.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod.hpp b/audio/third_party/fmod/api/inc/fmod.hpp similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod.hpp rename to audio/third_party/fmod/api/inc/fmod.hpp diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod_codec.h b/audio/third_party/fmod/api/inc/fmod_codec.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod_codec.h rename to audio/third_party/fmod/api/inc/fmod_codec.h diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod_dsp.h b/audio/third_party/fmod/api/inc/fmod_dsp.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod_dsp.h rename to audio/third_party/fmod/api/inc/fmod_dsp.h diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod_errors.h b/audio/third_party/fmod/api/inc/fmod_errors.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod_errors.h rename to audio/third_party/fmod/api/inc/fmod_errors.h diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod_memoryinfo.h b/audio/third_party/fmod/api/inc/fmod_memoryinfo.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod_memoryinfo.h rename to audio/third_party/fmod/api/inc/fmod_memoryinfo.h diff --git a/CocosDenshion/third_party/fmod/api/inc/fmod_output.h b/audio/third_party/fmod/api/inc/fmod_output.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmod_output.h rename to audio/third_party/fmod/api/inc/fmod_output.h diff --git a/CocosDenshion/third_party/fmod/api/inc/fmodlinux.h b/audio/third_party/fmod/api/inc/fmodlinux.h similarity index 100% rename from CocosDenshion/third_party/fmod/api/inc/fmodlinux.h rename to audio/third_party/fmod/api/inc/fmodlinux.h diff --git a/CocosDenshion/third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id b/audio/third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id rename to audio/third_party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id b/audio/third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id rename to audio/third_party/fmod/api/lib/libfmodex.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id b/audio/third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id rename to audio/third_party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id b/audio/third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id rename to audio/third_party/fmod/api/lib/libfmodexL.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/lib64/Makefile b/audio/third_party/fmod/lib64/Makefile similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/Makefile rename to audio/third_party/fmod/lib64/Makefile diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id b/audio/third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id rename to audio/third_party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod.hpp b/audio/third_party/fmod/lib64/api/inc/fmod.hpp similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod.hpp rename to audio/third_party/fmod/lib64/api/inc/fmod.hpp diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod_codec.h b/audio/third_party/fmod/lib64/api/inc/fmod_codec.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod_codec.h rename to audio/third_party/fmod/lib64/api/inc/fmod_codec.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod_dsp.h b/audio/third_party/fmod/lib64/api/inc/fmod_dsp.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod_dsp.h rename to audio/third_party/fmod/lib64/api/inc/fmod_dsp.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod_errors.h b/audio/third_party/fmod/lib64/api/inc/fmod_errors.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod_errors.h rename to audio/third_party/fmod/lib64/api/inc/fmod_errors.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod_memoryinfo.h b/audio/third_party/fmod/lib64/api/inc/fmod_memoryinfo.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod_memoryinfo.h rename to audio/third_party/fmod/lib64/api/inc/fmod_memoryinfo.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmod_output.h b/audio/third_party/fmod/lib64/api/inc/fmod_output.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmod_output.h rename to audio/third_party/fmod/lib64/api/inc/fmod_output.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/inc/fmodlinux.h b/audio/third_party/fmod/lib64/api/inc/fmodlinux.h similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/inc/fmodlinux.h rename to audio/third_party/fmod/lib64/api/inc/fmodlinux.h diff --git a/CocosDenshion/third_party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id b/audio/third_party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id rename to audio/third_party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id b/audio/third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id rename to audio/third_party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id b/audio/third_party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id rename to audio/third_party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id diff --git a/CocosDenshion/third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id b/audio/third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id similarity index 100% rename from CocosDenshion/third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id rename to audio/third_party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id diff --git a/CocosDenshion/win32/MciPlayer.cpp b/audio/win32/MciPlayer.cpp similarity index 100% rename from CocosDenshion/win32/MciPlayer.cpp rename to audio/win32/MciPlayer.cpp diff --git a/CocosDenshion/win32/MciPlayer.h b/audio/win32/MciPlayer.h similarity index 100% rename from CocosDenshion/win32/MciPlayer.h rename to audio/win32/MciPlayer.h diff --git a/CocosDenshion/win32/SimpleAudioEngine.cpp b/audio/win32/SimpleAudioEngine.cpp similarity index 100% rename from CocosDenshion/win32/SimpleAudioEngine.cpp rename to audio/win32/SimpleAudioEngine.cpp From fa51236dee89e5ac40b7e7a5cde7ad0019a70bdc Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 10 Oct 2013 14:40:30 +0800 Subject: [PATCH 051/557] Update CHANGELOG[ci skip] --- CHANGELOG | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index b9641d1f71..33a5c74148 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -8,13 +8,14 @@ cocos2d-x-3.0alpha1 @??? 2013 [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again + [FIX] Fixed application will crash when pause and resume. [Mac] [FIX] Removed unused CCLOG() from GL initialization [Javascript binding] [FIX] Fixed a memory leak in ScriptingCore::runScript() [FIX] sys.localStorage.getItem() does not support non-ascii string. [Lua Binding] - [FIX] Added Armature lua binding and added test samples. + [NEW] Added Armature lua binding and added test samples. cocos2d-x-3.0alpha0 @Sep.19 2013 [all platforms] From 56c945efe62af88680941d1670986979c8390aa2 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 10 Oct 2013 06:43:01 +0000 Subject: [PATCH 052/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripting/auto-generated b/scripting/auto-generated index ec90d1c35d..6f5bc7bbd0 160000 --- a/scripting/auto-generated +++ b/scripting/auto-generated @@ -1 +1 @@ -Subproject commit ec90d1c35d06c1de3cb5079f885c22c45b8f129b +Subproject commit 6f5bc7bbd036c76e7c6be121573662099997a0a4 From 866906fd58f581363754d73ddbcadad95809a430 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 10 Oct 2013 15:40:06 +0800 Subject: [PATCH 053/557] issue #2905:modify project settings to include correct audio path --- Makefile | 4 ++-- cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- extensions/Android.mk | 2 +- samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk | 2 +- samples/Cpp/HelloCpp/proj.android/jni/Android.mk | 2 +- samples/Cpp/SimpleGame/proj.android/jni/Android.mk | 2 +- samples/Cpp/TestCpp/Android.mk | 2 +- samples/Cpp/TestCpp/proj.android/jni/Android.mk | 2 +- samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk | 2 +- samples/Javascript/CrystalCraze/proj.android/jni/Android.mk | 2 +- samples/Javascript/MoonWarriors/proj.android/jni/Android.mk | 2 +- samples/Javascript/TestJavascript/proj.android/jni/Android.mk | 2 +- .../Javascript/WatermelonWithMe/proj.android/jni/Android.mk | 2 +- samples/Lua/HelloLua/proj.android/jni/Android.mk | 2 +- samples/Lua/TestLua/proj.android/jni/Android.mk | 2 +- samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- template/multi-platform-cpp/proj.android/jni/Android.mk | 2 +- .../proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj | 4 ++-- template/multi-platform-js/proj.android/jni/Android.mk | 2 +- .../proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj | 4 ++-- template/multi-platform-lua/proj.android/jni/Android.mk | 2 +- .../proj.ios_mac/HelloLua.xcodeproj/project.pbxproj | 4 ++-- 22 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Makefile b/Makefile index d82b65ec0f..fbea65f3cd 100644 --- a/Makefile +++ b/Makefile @@ -23,9 +23,9 @@ libcocos2dx-clean: $(MAKE) -C cocos2dx/proj.$(PLATFORM) clean cocosdenshion: libcocos2dx - $(MAKE) -C CocosDenshion/proj.$(PLATFORM) + $(MAKE) -C audio/proj.$(PLATFORM) cocosdenshion-clean: - $(MAKE) -C CocosDenshion/proj.$(PLATFORM) clean + $(MAKE) -C audio/proj.$(PLATFORM) clean lua: libextensions $(MAKE) -C scripting/lua/proj.$(PLATFORM) diff --git a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 48555d6a5d..367fc01cf7 100644 --- a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3959af89b6bbc8fb982769d22d2591991107d6e5 \ No newline at end of file +dd4a9b3e507a99df58e814b627efd3983fed2eb9 \ No newline at end of file diff --git a/extensions/Android.mk b/extensions/Android.mk index 4289775bc8..8c0b1e2591 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -161,7 +161,7 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ include $(BUILD_STATIC_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) $(call import-module,external/Box2D) $(call import-module,external/chipmunk) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk index a85ad02ade..42c47b9f80 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk b/samples/Cpp/HelloCpp/proj.android/jni/Android.mk index 13989f3cf1..6ffd7d62ef 100644 --- a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk +++ b/samples/Cpp/HelloCpp/proj.android/jni/Android.mk @@ -17,5 +17,5 @@ LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocos2dxandroid_static cocosdens include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk b/samples/Cpp/SimpleGame/proj.android/jni/Android.mk index e3f5b5c1ef..d0fd9a4eb2 100644 --- a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk +++ b/samples/Cpp/SimpleGame/proj.android/jni/Android.mk @@ -17,7 +17,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocos2dxandroid_static cocosdens include $(BUILD_SHARED_LIBRARY) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,cocos2dx) $(call import-module,extensions) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 87d662be3a..ff687de48a 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -151,7 +151,7 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) include $(BUILD_STATIC_LIBRARY) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,external/Box2D) $(call import-module,external/chipmunk) $(call import-module,cocos2dx) diff --git a/samples/Cpp/TestCpp/proj.android/jni/Android.mk b/samples/Cpp/TestCpp/proj.android/jni/Android.mk index 98de0c8956..d72618a488 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Android.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ include $(BUILD_SHARED_LIBRARY) $(call import-module,samples/Cpp/TestCpp) $(call import-module,cocos2dx) $(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,extensions) $(call import-module,external/Box2D) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk index 0ab251941c..bc55bdaaf5 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk +++ b/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk index 12575cad7a..451b250c37 100644 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk +++ b/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk index 1cdcb62cd6..8f89f72ceb 100644 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk +++ b/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk index 88ce0ac197..5655c291c2 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk @@ -23,7 +23,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,extensions) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk index 76b8e7fd1e..fd7d49998d 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk +++ b/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Lua/HelloLua/proj.android/jni/Android.mk b/samples/Lua/HelloLua/proj.android/jni/Android.mk index 54e142b5d8..e4aa117413 100644 --- a/samples/Lua/HelloLua/proj.android/jni/Android.mk +++ b/samples/Lua/HelloLua/proj.android/jni/Android.mk @@ -20,7 +20,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/lua/proj.android) $(call import-module,extensions) $(call import-module,cocos2dx/platform/android) diff --git a/samples/Lua/TestLua/proj.android/jni/Android.mk b/samples/Lua/TestLua/proj.android/jni/Android.mk index 189dd81468..6f3a99a518 100644 --- a/samples/Lua/TestLua/proj.android/jni/Android.mk +++ b/samples/Lua/TestLua/proj.android/jni/Android.mk @@ -24,7 +24,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/lua/proj.android) $(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) $(call import-module,extensions) diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index ec33bf839a..bc96bbb791 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -381c282bed409f4b41a82505460d4d6c84ba70ab \ No newline at end of file +609e133ab0e4ace89f5ddf8710506b08ff2e952b \ No newline at end of file diff --git a/template/multi-platform-cpp/proj.android/jni/Android.mk b/template/multi-platform-cpp/proj.android/jni/Android.mk index 5430a288ba..97616f1fba 100644 --- a/template/multi-platform-cpp/proj.android/jni/Android.mk +++ b/template/multi-platform-cpp/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) $(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,extensions) $(call import-module,external/Box2D) $(call import-module,cocos2dx/platform/android) diff --git a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj index 3cb7edab03..3f7b3750a3 100644 --- a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj +++ b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj @@ -821,7 +821,7 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", + "$(SRCROOT)/../../../audio/include", "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", "\"$(SRCROOT)/../../../extensions\"", @@ -861,7 +861,7 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", + "$(SRCROOT)/../../../audio/include", "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", "\"$(SRCROOT)/../../../extensions\"", diff --git a/template/multi-platform-js/proj.android/jni/Android.mk b/template/multi-platform-js/proj.android/jni/Android.mk index 09cabaea59..3b09a62b57 100644 --- a/template/multi-platform-js/proj.android/jni/Android.mk +++ b/template/multi-platform-js/proj.android/jni/Android.mk @@ -22,7 +22,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) $(call import-module,cocos2dx/platform/android) diff --git a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index 9958c7a786..dbc340d66f 100644 --- a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -923,7 +923,7 @@ "\"$(SRCROOT)/../../../cocos2dx\"", "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", + "\"$(SRCROOT)/../../../audio/include\"", "$(SRCROOT)/../../../cocos2dx/include", "$(SRCROOT)/../../../cocos2dx/platform/ios", "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", @@ -965,7 +965,7 @@ "\"$(SRCROOT)/../../../cocos2dx\"", "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", + "\"$(SRCROOT)/../../../audio/include\"", "$(SRCROOT)/../../../cocos2dx/include", "$(SRCROOT)/../../../cocos2dx/platform/ios", "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", diff --git a/template/multi-platform-lua/proj.android/jni/Android.mk b/template/multi-platform-lua/proj.android/jni/Android.mk index 05362699b5..af986970fe 100644 --- a/template/multi-platform-lua/proj.android/jni/Android.mk +++ b/template/multi-platform-lua/proj.android/jni/Android.mk @@ -25,7 +25,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static include $(BUILD_SHARED_LIBRARY) $(call import-module,cocos2dx) -$(call import-module,CocosDenshion/android) +$(call import-module,audio/android) $(call import-module,scripting/lua/proj.android) $(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) $(call import-module,extensions) diff --git a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj index 8403e89e8a..67d6e16713 100644 --- a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj +++ b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj @@ -992,7 +992,7 @@ "\"$(SRCROOT)/../../../scripting/lua/cocos2dx_support\"", "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", + "\"$(SRCROOT)/../../../audio/include\"", "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", "\"$(SRCROOT)/../../../external\"", @@ -1035,7 +1035,7 @@ "\"$(SRCROOT)/../../../scripting/lua/cocos2dx_support\"", "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", + "\"$(SRCROOT)/../../../audio/include\"", "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", "\"$(SRCROOT)/../../../external\"", From 2e07b0736b073ff90f985846d9bccf68e4fde101 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 10 Oct 2013 16:13:37 +0800 Subject: [PATCH 054/557] Update .gitmodules, fix wrong reference of auto-generated. --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index eb0c7b5ec4..f7313b3346 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,7 +1,7 @@ [submodule "tools/bindings-generator"] path = tools/bindings-generator url = git://github.com/cocos2d/bindings-generator.git -[submodule "scripting/javascript/bindings/generated"] +[submodule "scripting/auto-generated"] path = scripting/auto-generated url = git://github.com/folecr/cocos2dx-autogen-bindings.git [submodule "samples/Javascript/Shared"] From c381e4ce50f1f83876680c8fb4b090645d6cfb3c Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 5 Oct 2013 10:56:52 +0800 Subject: [PATCH 055/557] issue #2823: firefox remote connection ok. --- .../javascript/bindings/ScriptingCore.cpp | 177 ++++++++++++++++-- .../javascript/bindings/js_bindings_config.h | 2 +- 2 files changed, 167 insertions(+), 12 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 33fd2aee1f..fc21464922 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -1938,7 +1938,8 @@ void ScriptingCore::enableDebugger() { JS_DefineFunction(cx_, debugGlobal_, "_unlockVM", JSBDebug_UnlockExecution, 0, JSPROP_READONLY | JSPROP_PERMANENT); runScript("jsb_debugger.js", debugGlobal_); - + runScript("SysTest/script.js", debugGlobal_); + // prepare the debugger jsval argv = OBJECT_TO_JSVAL(global_); jsval outval; @@ -2166,6 +2167,13 @@ static void clearBuffers() { } } +static int replyToClient(int socket, const std::string& buf) +{ + std::stringstream bufSend; + bufSend << buf.length() << ":" << buf; + return ::send(socket, bufSend.str().c_str(), bufSend.str().length(), 0); +} + static void serverEntryPoint(void) { // start a server, accept the connection and keep reading data from it @@ -2218,25 +2226,172 @@ static void serverEntryPoint(void) listen(s, 1); + int recieveIndex = 0; while (true) { clientSocket = accept(s, NULL, NULL); + if (clientSocket < 0) - { - TRACE_DEBUGGER_SERVER("debug server : error on accept"); - return; - } else { + { + TRACE_DEBUGGER_SERVER("debug server : error on accept"); + return; + } + else + { // read/write data TRACE_DEBUGGER_SERVER("debug server : client connected"); - char buf[256]; - int readBytes; - while ((readBytes = read(clientSocket, buf, 256)) > 0) { + + if (recieveIndex == 0) + { + replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}"); + ++recieveIndex; + } + + + char buf[256] = {0}; + int readBytes = 0; + while ((readBytes = ::recv(clientSocket, buf, sizeof(buf), 0)) > 0) + { buf[readBytes] = '\0'; TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); + + if (recieveIndex == 1) + { + replyToClient(clientSocket, "{ \"from\":\"root\", \"tabs\":[{ \"actor\":\"JSBTabActor\", \"title\":\"Hello cocos2d-x JSB\", \"url\":\"http://www.cocos2d-x.org\" }], \"selected\":0 }"); + } + else if (recieveIndex == 2) + { + replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabAttached\", \"threadActor\":\"tabThreadActor111\" }"); + } + else if (recieveIndex == 3) + { + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"paused\",\ + \"actor\": \"JSBTabActor\",\ + \"poppedFrames\": [],\ + \"why\": {\ + \"type\": \"attached\"\ + }\ + }"); + + + + //replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabNavigated\", \"state\":\"start\", \"url\":\"my_url.js\" }"); + } + else if (recieveIndex == 4) + { +// replyToClient(clientSocket, "{\"from\": \"tabThreadActor111\",\ +// \"type\": \"newSource\",\ +// \"source\": {\ +// \"actor\": \"source_actor2\",\ +// \"url\": \"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\",\ +// \"isBlackBoxed\": false\ +// }}"); + + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"newSource\",\ + \"source\": {\ + \"actor\": \"source_actor1\",\ + \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ + \"isBlackBoxed\": false\ + }\ + }"); + + replyToClient(clientSocket, + "{\ + \"sources\": [\ + {\ + \"actor\": \"source_actor1\",\ + \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ + \"isBlackBoxed\": false\ + }\ + ],\ + \"from\": \"tabThreadActor111\"\ + }"); + } + else if (recieveIndex == 5) + { + replyToClient(clientSocket, "{\ + \"from\": \"source_actor1\",\ + \"source\": {\ + \"type\": \"longString\",\ + \"initial\": \"var cc = cc || {}; cc.Director = {};\",\ + \"length\": 100,\ + \"actor\": \"conn2.longString48\"\ + }\ + }"); + } + else if (recieveIndex == 6) + { + replyToClient(clientSocket, "{\ + \"from\": \"conn2.longString48\",\ + \"substring\": \"var cc = cc || {}; cc.Director = {};\ +\\ncc.Sprite = {};\"\ + }"); + + + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"resumed\"\ + }"); + } + else if (recieveIndex == 7) + { + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"resumed\"\ + }"); + } + else if (recieveIndex == 8) + { + replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); + } + else if (recieveIndex == 9) + { + replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); + } + else if (recieveIndex == 10) + { + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"resumed\"\ + }"); + } + else + { + + + std::string recvBuf = buf; + auto found = recvBuf.find("setBreakpoint"); + if (found != std::string::npos) + { + replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); + } + + found = recvBuf.find("delete"); + if (found != std::string::npos) + { + replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); + } + + found = recvBuf.find("interrupt"); + if (found != std::string::npos) + { + replyToClient(clientSocket, "{\ + \"from\": \"tabThreadActor111\",\ + \"type\": \"resumed\"\ + }"); + } + + } + ++recieveIndex; // no other thread is using this - inData.append(buf); - // process any input, send any output - clearBuffers(); +// inData.append(buf); +// // process any input, send any output +// clearBuffers(); } // while(read) + close(clientSocket); } } // while(true) diff --git a/scripting/javascript/bindings/js_bindings_config.h b/scripting/javascript/bindings/js_bindings_config.h index 2216f2fca2..bfe1d64f96 100644 --- a/scripting/javascript/bindings/js_bindings_config.h +++ b/scripting/javascript/bindings/js_bindings_config.h @@ -141,7 +141,7 @@ Set this to 1 to enable the debugger */ #ifndef JSB_ENABLE_DEBUGGER -#define JSB_ENABLE_DEBUGGER 0 +#define JSB_ENABLE_DEBUGGER 1 #endif // JSB_ENABLE_DEBUGGER #if JSB_ENABLE_DEBUGGER From d033411bbe7946ba601ec43b6053673c60a113b5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 5 Oct 2013 11:24:25 +0800 Subject: [PATCH 056/557] issue #2823: comment some test codes. --- .../javascript/bindings/ScriptingCore.cpp | 258 +++++++++--------- 1 file changed, 125 insertions(+), 133 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index fc21464922..77ba232fc0 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -1938,7 +1938,7 @@ void ScriptingCore::enableDebugger() { JS_DefineFunction(cx_, debugGlobal_, "_unlockVM", JSBDebug_UnlockExecution, 0, JSPROP_READONLY | JSPROP_PERMANENT); runScript("jsb_debugger.js", debugGlobal_); - runScript("SysTest/script.js", debugGlobal_); +// runScript("SysTest/script.js", debugGlobal_); // prepare the debugger jsval argv = OBJECT_TO_JSVAL(global_); @@ -2254,142 +2254,134 @@ static void serverEntryPoint(void) buf[readBytes] = '\0'; TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); - if (recieveIndex == 1) - { - replyToClient(clientSocket, "{ \"from\":\"root\", \"tabs\":[{ \"actor\":\"JSBTabActor\", \"title\":\"Hello cocos2d-x JSB\", \"url\":\"http://www.cocos2d-x.org\" }], \"selected\":0 }"); - } - else if (recieveIndex == 2) - { - replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabAttached\", \"threadActor\":\"tabThreadActor111\" }"); - } - else if (recieveIndex == 3) - { - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"paused\",\ - \"actor\": \"JSBTabActor\",\ - \"poppedFrames\": [],\ - \"why\": {\ - \"type\": \"attached\"\ - }\ - }"); - - - - //replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabNavigated\", \"state\":\"start\", \"url\":\"my_url.js\" }"); - } - else if (recieveIndex == 4) - { -// replyToClient(clientSocket, "{\"from\": \"tabThreadActor111\",\ +// if (recieveIndex == 1) +// { +// replyToClient(clientSocket, "{ \"from\":\"root\", \"tabs\":[{ \"actor\":\"JSBTabActor\", \"title\":\"Hello cocos2d-x JSB\", \"url\":\"http://www.cocos2d-x.org\" }], \"selected\":0 }"); +// } +// else if (recieveIndex == 2) +// { +// replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabAttached\", \"threadActor\":\"tabThreadActor111\" }"); +// } +// else if (recieveIndex == 3) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ +// \"type\": \"paused\",\ +// \"actor\": \"JSBTabActor\",\ +// \"poppedFrames\": [],\ +// \"why\": {\ +// \"type\": \"attached\"\ +// }\ +// }"); +// +// +// +// //replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabNavigated\", \"state\":\"start\", \"url\":\"my_url.js\" }"); +// } +// else if (recieveIndex == 4) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ // \"type\": \"newSource\",\ // \"source\": {\ -// \"actor\": \"source_actor2\",\ -// \"url\": \"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\",\ +// \"actor\": \"source_actor1\",\ +// \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ // \"isBlackBoxed\": false\ -// }}"); - - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"newSource\",\ - \"source\": {\ - \"actor\": \"source_actor1\",\ - \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ - \"isBlackBoxed\": false\ - }\ - }"); - - replyToClient(clientSocket, - "{\ - \"sources\": [\ - {\ - \"actor\": \"source_actor1\",\ - \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ - \"isBlackBoxed\": false\ - }\ - ],\ - \"from\": \"tabThreadActor111\"\ - }"); - } - else if (recieveIndex == 5) - { - replyToClient(clientSocket, "{\ - \"from\": \"source_actor1\",\ - \"source\": {\ - \"type\": \"longString\",\ - \"initial\": \"var cc = cc || {}; cc.Director = {};\",\ - \"length\": 100,\ - \"actor\": \"conn2.longString48\"\ - }\ - }"); - } - else if (recieveIndex == 6) - { - replyToClient(clientSocket, "{\ - \"from\": \"conn2.longString48\",\ - \"substring\": \"var cc = cc || {}; cc.Director = {};\ -\\ncc.Sprite = {};\"\ - }"); - - - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"resumed\"\ - }"); - } - else if (recieveIndex == 7) - { - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"resumed\"\ - }"); - } - else if (recieveIndex == 8) - { - replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); - } - else if (recieveIndex == 9) - { - replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); - } - else if (recieveIndex == 10) - { - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"resumed\"\ - }"); - } - else - { - - - std::string recvBuf = buf; - auto found = recvBuf.find("setBreakpoint"); - if (found != std::string::npos) - { - replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); - } - - found = recvBuf.find("delete"); - if (found != std::string::npos) - { - replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); - } - - found = recvBuf.find("interrupt"); - if (found != std::string::npos) - { - replyToClient(clientSocket, "{\ - \"from\": \"tabThreadActor111\",\ - \"type\": \"resumed\"\ - }"); - } - - } - ++recieveIndex; +// }\ +// }"); +// +// replyToClient(clientSocket, +// "{\ +// \"sources\": [\ +// {\ +// \"actor\": \"source_actor1\",\ +// \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ +// \"isBlackBoxed\": false\ +// }\ +// ],\ +// \"from\": \"tabThreadActor111\"\ +// }"); +// } +// else if (recieveIndex == 5) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"source_actor1\",\ +// \"source\": {\ +// \"type\": \"longString\",\ +// \"initial\": \"var cc = cc || {}; cc.Director = {};\",\ +// \"length\": 100,\ +// \"actor\": \"conn2.longString48\"\ +// }\ +// }"); +// } +// else if (recieveIndex == 6) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"conn2.longString48\",\ +// \"substring\": \"var cc = cc || {}; cc.Director = {};\ +//\\ncc.Sprite = {};\"\ +// }"); +// +// +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ +// \"type\": \"resumed\"\ +// }"); +// } +// else if (recieveIndex == 7) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ +// \"type\": \"resumed\"\ +// }"); +// } +// else if (recieveIndex == 8) +// { +// replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); +// } +// else if (recieveIndex == 9) +// { +// replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); +// } +// else if (recieveIndex == 10) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ +// \"type\": \"resumed\"\ +// }"); +// } +// else +// { +// +// +// std::string recvBuf = buf; +// auto found = recvBuf.find("setBreakpoint"); +// if (found != std::string::npos) +// { +// replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); +// } +// +// found = recvBuf.find("delete"); +// if (found != std::string::npos) +// { +// replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); +// } +// +// found = recvBuf.find("interrupt"); +// if (found != std::string::npos) +// { +// replyToClient(clientSocket, "{\ +// \"from\": \"tabThreadActor111\",\ +// \"type\": \"resumed\"\ +// }"); +// } +// +// } +// ++recieveIndex; // no other thread is using this -// inData.append(buf); -// // process any input, send any output -// clearBuffers(); + inData.append(buf); + // process any input, send any output + clearBuffers(); } // while(read) close(clientSocket); From b5679cbc3a99ee68fc4bc9cc8278e6baa2bea28c Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 7 Oct 2013 10:50:12 +0800 Subject: [PATCH 057/557] issue #2823: load js file in firefox. --- .../javascript/bindings/ScriptingCore.cpp | 92 ++-- scripting/javascript/bindings/ScriptingCore.h | 2 +- .../javascript/bindings/js/jsb_debugger.js | 408 +++++++++++++++++- 3 files changed, 466 insertions(+), 36 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 77ba232fc0..0ed5b8eb68 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -392,7 +392,6 @@ JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char * global = global_; JSScript* script = JS_CompileScript(cx, global, string, strlen(string), filename, 1); if (script) { - // JSAutoCompartment ac(cx, global); JSAutoCompartment ac(cx, global); JSBool evaluatedOK = JS_ExecuteScript(cx, global, script, outVal); if (JS_FALSE == evaluatedOK) { @@ -463,19 +462,23 @@ void ScriptingCore::createGlobalContext() { this->cx_ = JS_NewContext(rt_, 8192); JS_SetOptions(this->cx_, JSOPTION_TYPE_INFERENCE); - JS_SetVersion(this->cx_, JSVERSION_LATEST); + +// JS_SetVersion(this->cx_, JSVERSION_LATEST); // Only disable METHODJIT on iOS. -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT); - JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT_ALWAYS); -#endif +//#if (CC_TARGET_PLATFORM == CC_PLATFORM_ +// JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT); +// JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT_ALWAYS); +//#endif JS_SetErrorReporter(this->cx_, ScriptingCore::reportError); #if defined(JS_GC_ZEAL) && defined(DEBUG) //JS_SetGCZeal(this->cx_, 2, JS_DEFAULT_ZEAL_FREQ); #endif + this->global_ = NewGlobalObject(cx_); + JSAutoCompartment ac(cx_, global_); + #if JSB_ENABLE_DEBUGGER JS_SetDebugMode(cx_, JS_TRUE); #endif @@ -500,6 +503,8 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c if (!path) { return false; } + + cocos2d::FileUtils *futil = cocos2d::FileUtils::getInstance(); std::string fullPath = futil->fullPathForFilename(path); if (global == NULL) { @@ -508,7 +513,12 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c if (cx == NULL) { cx = cx_; } - JSScript *script = NULL; + + JSAutoCompartment ac(cx, global); + + uint32_t oldopts = JS_GetOptions(cx); + JS_SetOptions(cx, oldopts | JSOPTION_COMPILE_N_GO | JSOPTION_NO_SCRIPT_RVAL); + js::RootedObject obj(cx, global); JS::CompileOptions options(cx); options.setUTF8(true).setFileAndLine(fullPath.c_str(), 1); @@ -519,6 +529,8 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c void *data = futil->getFileData(byteCodePath.c_str(), "rb", &length); + + js::RootedScript script(cx); if (data) { script = JS_DecodeScript(cx, data, length, NULL, NULL); CC_SAFE_DELETE_ARRAY(data); @@ -930,15 +942,16 @@ JSBool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, ui do { + JSAutoCompartment ac(cx, obj); + if (JS_HasProperty(cx, obj, name, &hasAction) && hasAction) { if (!JS_GetProperty(cx, obj, name, &temp_retval)) { break; } if (temp_retval == JSVAL_VOID) { break; - } + } - JSAutoCompartment ac(cx, obj); if (retVal) { bRet = JS_CallFunctionName(cx, obj, name, argc, vp, retVal); } @@ -1099,6 +1112,8 @@ int ScriptingCore::sendEvent(ScriptEvent* evt) { if (NULL == evt) return 0; + + JSAutoCompartment ac(cx_, global_); switch (evt->type) { @@ -1199,7 +1214,7 @@ 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 = v.isString() ? JS_ValueToString(cx, v) : NULL; + JSString *tmp = JS_ValueToString(cx, v); JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); JSStringWrapper str(tmp); @@ -1736,14 +1751,24 @@ jsval long_long_to_jsval(JSContext* cx, long long v) { return OBJECT_TO_JSVAL(tmp); } -jsval std_string_to_jsval(JSContext* cx, const std::string& v) { - return c_string_to_jsval(cx, v.c_str()); +jsval std_string_to_jsval(JSContext* cx, const std::string& v) +{ + return c_string_to_jsval(cx, v.c_str(), v.size()); } -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) { - if (v == NULL) { +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) +{ + if (v == NULL) + { return JSVAL_NULL; } + + if (0 == length) + { + auto emptyStr = JS_NewStringCopyZ(cx, ""); + return STRING_TO_JSVAL(emptyStr); + } + jsval ret = JSVAL_NULL; int utf16_size = 0; jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); @@ -1914,6 +1939,8 @@ void SimpleRunLoop::update(float dt) { } void ScriptingCore::debugProcessInput(string str) { + JSAutoCompartment ac(cx_, debugGlobal_); + JSString* jsstr = JS_NewStringCopyZ(cx_, str.c_str()); jsval argv[3] = { STRING_TO_JSVAL(jsstr), @@ -1921,12 +1948,13 @@ void ScriptingCore::debugProcessInput(string str) { script }; jsval outval; - JSAutoCompartment ac(cx_, debugGlobal_); + JS_CallFunctionName(cx_, debugGlobal_, "processInput", 3, argv, &outval); } void ScriptingCore::enableDebugger() { if (debugGlobal_ == NULL) { + JSAutoCompartment ac0(cx_, global_); debugGlobal_ = NewGlobalObject(cx_, true); JS_WrapObject(cx_, &debugGlobal_); JSAutoCompartment ac(cx_, debugGlobal_); @@ -1940,6 +1968,7 @@ void ScriptingCore::enableDebugger() { runScript("jsb_debugger.js", debugGlobal_); // runScript("SysTest/script.js", debugGlobal_); + CCLOG("before _prepareDebugger..."); // prepare the debugger jsval argv = OBJECT_TO_JSVAL(global_); jsval outval; @@ -1947,6 +1976,8 @@ void ScriptingCore::enableDebugger() { if (!ok) { JS_ReportPendingException(cx_); } + + CCLOG("after _prepareDebugger..."); // define the start debugger function JS_DefineFunction(cx_, global_, "startDebugger", JSBDebug_StartDebugger, 3, JSPROP_READONLY | JSPROP_PERMANENT); // start bg thread @@ -1954,6 +1985,7 @@ void ScriptingCore::enableDebugger() { auto t = std::thread(&serverEntryPoint); t.detach(); + CCLOG("after _prepareDebugger...02"); Scheduler* scheduler = Director::getInstance()->getScheduler(); scheduler->scheduleUpdateForTarget(this->runLoop, 0, false); } @@ -1991,15 +2023,23 @@ JSBool jsGetScript(JSContext* cx, unsigned argc, jsval* vp) JSObject* NewGlobalObject(JSContext* cx, bool debug) { - JSObject* glob = JS_NewGlobalObject(cx, &global_class, NULL); - if (!glob) { + JS::CompartmentOptions options; + options.setZone(JS::FreshZone) + .setVersion(JSVERSION_LATEST); + JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, NULL, options)); + + if (!glob) + { return NULL; } + JSAutoCompartment ac(cx, glob); JSBool ok = JS_TRUE; ok = JS_InitStandardClasses(cx, glob); if (ok) - JS_InitReflect(cx, glob); + { + ok = JS_InitReflect(cx, glob) != NULL; + } if (ok && debug) ok = JS_DefineDebuggerObject(cx, glob); if (!ok) @@ -2240,14 +2280,18 @@ static void serverEntryPoint(void) // read/write data TRACE_DEBUGGER_SERVER("debug server : client connected"); - if (recieveIndex == 0) - { - replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}"); - ++recieveIndex; - } + inData = "connected"; + // process any input, send any output + clearBuffers(); + +// if (recieveIndex == 0) +// { +// replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}"); +// ++recieveIndex; +// } - char buf[256] = {0}; + char buf[1024] = {0}; int readBytes = 0; while ((readBytes = ::recv(clientSocket, buf, sizeof(buf), 0)) > 0) { diff --git a/scripting/javascript/bindings/ScriptingCore.h b/scripting/javascript/bindings/ScriptingCore.h index f7b8cb29e1..bea0541b82 100644 --- a/scripting/javascript/bindings/ScriptingCore.h +++ b/scripting/javascript/bindings/ScriptingCore.h @@ -192,7 +192,7 @@ public: void debugProcessInput(string str); void enableDebugger(); JSObject* getDebugGlobal() { return debugGlobal_; } - JSObject* getGlobalObject() { return global_; } + JSObject* getGlobalObject() { return global_ ? global_ : debugGlobal_; } private: void string_report(jsval val); diff --git a/scripting/javascript/bindings/js/jsb_debugger.js b/scripting/javascript/bindings/js/jsb_debugger.js index 20fecc78c2..8d701d22f6 100644 --- a/scripting/javascript/bindings/js/jsb_debugger.js +++ b/scripting/javascript/bindings/js/jsb_debugger.js @@ -1,4 +1,8 @@ -dbg = {}; +dbg = { + LONG_STRING_LENGTH: 10000, + LONG_STRING_INITIAL_LENGTH: 1000, + LONG_STRING_READ_LENGTH: 1000 +}; dbg.log = log; var textCommandProcessor = {}; @@ -299,7 +303,39 @@ jsonResponder.onBreakpoint = function (filename, linenumber) { "data" : {"jsfilename" : filename, "linenumber" : linenumber}}; - this.write(JSON.stringify(response)); + dbg.log("onBreakpoint: " + JSON.stringify(response)); + +var breakInfo = { "from":"tabThreadActor111", "type":"paused", "actor":"pauseActor", + "why":{ "type":"breakpoint", "actors":["breakpointActor1"] }, + "frame":{ "actor":"frameActor", "depth":1, + "type":"call", "where":{ "url":"sample.js", "line":3 }, + "environment":{ "type":"function", "actor":"gFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"gActor" }, + "functionName":"g", + "bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false", + "writable":true, "enumerable":true } } ] }, + "parent":{ "type":"function", "actor":"fFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"fActor" }, + "functionName":"f", + "bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false", + "writable":true, "enumerable":true } } ], + variables: { "z": { "value":"value of z", "configurable":"false", + "writable":true, "enumerable":true } } }, + "parent":{ "type":"object", "actor":"globalCodeActor", + "object":{ "type":"object", "class":"Global", + "actor":"globalObjectActor" } + } + } + }, + "callee":"gActor", "calleeName":"g", + "this":{ "type":"object", "class":"Function", "actor":"gActor" }, + "arguments":["argument to g"] + } + }; + + _RDPWrite(breakInfo); + + //this.write(JSON.stringify(response)); } jsonResponder.onStep = function (filename, linenumber) { @@ -332,10 +368,45 @@ textResponder.write = function (str) { _bufferWrite(String.fromCharCode(23)); } -textResponder.onBreakpoint = function (filename, linenumber) { - var shortFilename = filename.substring(filename.lastIndexOf("/") + 1); - var response = "Breakpoint hit at " + shortFilename + " line number : " + linenumber; - this.write(response); +var breakpointFrame = null; + +textResponder.onBreakpoint = function (frame) {//filename, linenumber) { + // var shortFilename = filename.substring(filename.lastIndexOf("/") + 1); + // var response = "Breakpoint hit at " + shortFilename + " line number : " + linenumber; + // dbg.log("textResponder.onBreakpoint:"+response); + + var breakInfo = { "from":"tabThreadActor111", "type":"paused", "actor":"pauseActor", + "why":{ "type":"breakpoint", "actors":["breakpointActor1"] }, + "frame":{ "actor":"frameActor", "depth":1, + "type":"call", "where":{ "url":"sample.js", "line":3 }, + "environment":{ "type":"function", "actor":"gFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"gActor" }, + "functionName":"g", + "bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false", + "writable":true, "enumerable":true } } ] }, + "parent":{ "type":"function", "actor":"fFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"fActor" }, + "functionName":"f", + "bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false", + "writable":true, "enumerable":true } } ], + variables: { "z": { "value":"value of z", "configurable":"false", + "writable":true, "enumerable":true } } }, + "parent":{ "type":"object", "actor":"globalCodeActor", + "object":{ "type":"object", "class":"Global", + "actor":"globalObjectActor" } + } + } + }, + "callee":"gActor", "calleeName":"g", + "this":{ "type":"object", "class":"Function", "actor":"gActor" }, + "arguments":["argument to g"] + } + }; + + breakpointFrame = frame; + _RDPWrite(breakInfo); + + // this.write(response); } textResponder.onStep = function (filename, linenumber) { @@ -420,8 +491,9 @@ textResponder.commandNotFound = function () { var breakpointHandler = { hit: function (frame) { + dbg.log("breakpointHandler hit"); try { - dbg.responder.onBreakpoint(frame.script.url, frame.script.getOffsetLine(frame.offset)); + dbg.responder.onBreakpoint(frame);//frame.script.url, frame.script.getOffsetLine(frame.offset)); } catch (e) { dbg.log("exception " + e); } @@ -487,6 +559,71 @@ var debugObject = function (r, isNormal) { dbg.breakLine = 0; +dbg.scriptSourceActorMap = {}; + + + +addFiles = function() { + for (var key in dbg.scripts) + { + dbg.log("sources:" + key); + var scripts = dbg.scripts[key]; + for (var i = 0; i < scripts.length; ++i) + { + dbg.log("url:" + scripts[i].source.url); + dbg.log("-----------"); + + dbg.scriptSourceActorMap[key+"_SourceActor"] = scripts[i]; + + _RDPWrite( + { + from: "tabThreadActor111", + type: "newSource", + source: { + actor: key+"_SourceActor", + url: "file://" + scripts[i].source.url, + isBlackBoxed: false + } + }); + } + } +}; + +addInitialSource = function(sourceActor, script) +{ + _RDPWrite( + { + from: sourceActor, + source: { + type: "longString", + initial: script.source.text.substring(0, dbg.LONG_STRING_INITIAL_LENGTH), + length: script.source.text.length, + actor: sourceActor+"_LongString" + } + }); +} + +addSource = function(longStringActor, script) +{ + _RDPWrite( + { + from: longStringActor, + substring: script.source.text + }); +} + +isStringStartWith = function (str, substring) { + var reg = new RegExp("^"+substring); + return reg.test(str); +}; + +isStringEndsWith = function (str, substring) { + var reg = new RegExp(substring + "$"); + return reg.test(str); +}; + +var breakpointActorIndex = 0; + this.processInput = function (inputstr, frame, script) { var command_func; var command_return; @@ -498,6 +635,240 @@ this.processInput = function (inputstr, frame, script) { return; } +// var testStr = "104:{\ +// \"to\": \"tabThreadActor111\",\ +// \"type\": \"resume\",\ +// \"resumeLimit\": null,\ +// \"pauseOnExceptions\": false\ +// }60:{\ +// \"to\": \"ActionsTest.js_SourceActor\",\ +// \"type\": \"source\"\ +// }"; + + // for (var i = 0; i < testArr.length; ++i) + // { + // dbg.log("split: " +"{"+ testArr[i] + ",length= "+testArr.length); + // } + + var inputArr = inputstr.split(/\d+:{/g); + + if (inputArr.length > 1) + { + inputArr.shift(); + for (var i = 0; i < inputArr.length; ++i) { + // dbg.log("---> "+inputArr[i]); + processInput("{"+inputArr[i], frame, script); + } + return; + } + + // dbg.log("inputStr:"+inputstr); + + if (inputstr === "connected") + { + var rootInit = {from:"root",applicationType:"browser",traits:{sources: true}}; + _RDPWrite(rootInit); + return; + } + + // var semi = inputstr.indexOf(":"); + + // if (semi === -1) + // { + // dbg.log("wrong input remote debugger protocol string."); + // return; + // } + + var jsonStr = inputstr;//.substring(semi+1); + dbg.log("jsonStr:" + jsonStr); + var jsonObj = JSON.parse(jsonStr); + // for (var key in jsonObj) + // { + // dbg.log("["+key+"]="+jsonObj[key]); + // } + + if (jsonObj.to === "root" && jsonObj.type === "listTabs") + { + _RDPWrite({ from:"root", tabs:[{ actor:"JSBTabActor", title:"Hello cocos2d-x JSB", url:"http://www.cocos2d-x.org" }], selected:0 }); + } + else if (jsonObj.to === "JSBTabActor" && jsonObj.type === "attach") + { + _RDPWrite({ from:"JSBTabActor", type:"tabAttached", threadActor:"tabThreadActor111" }); + } + else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "attach") + { + _RDPWrite( + { + from: "tabThreadActor111", + type: "paused", + actor: "JSBTabActor", + poppedFrames: [], + why: { + type: "attached" + } + }); + } + else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "sources") + { + addFiles(); + } + else if (jsonObj.to && isStringEndsWith(jsonObj.to, "_SourceActor") && jsonObj.type === "source") + { + dbg.log("require source ...: " + jsonObj.to); + var script = dbg.scriptSourceActorMap[jsonObj.to]; + + if (script) + { + addInitialSource(jsonObj.to, script); + } + } + else if (jsonObj.to && isStringEndsWith(jsonObj.to, "_LongString") && jsonObj.type === "substring") + { + var sourceActor = jsonObj.to.substring(0, jsonObj.to.length-"_LongString".length); + dbg.log("source actor: " + sourceActor); + var script = dbg.scriptSourceActorMap[sourceActor]; + + if (script) + { + addSource(jsonObj.to, script); + } + + _RDPWrite({ + from: "tabThreadActor111", + type: "resumed" + }); + } + else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "resume") + { + dbg.log("resume type to server...."); + _RDPWrite({ + from: "tabThreadActor111", + type: "resumed" + }); + } + else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "setBreakpoint") + { + ++breakpointActorIndex; + + var scripts = dbg.scripts[jsonObj.location.url], + tmpScript = null; + + if (scripts) { + var breakLine = jsonObj.location.line, + off = -1; + for (var n=0; n < scripts.length; n++) { + offsets = scripts[n].getLineOffsets(breakLine); + if (offsets.length > 0) { + off = offsets[0]; + tmpScript = scripts[n]; + break; + } + } + if (off >= 0) { + tmpScript.setBreakpoint(off, breakpointHandler); + // return ({commandname : "break", + // success : true, + // jsfilename : md[2], + // breakpointlinenumber : breakLine}); + } else { + // return ({commandname : "break", + // success : false, + // stringResult : "no valid offsets at that line"}); + } + } else { + // return ({commandname : "break", + // success : false, + // jsfilename : md[2], + // stringResult : "Invalid script name"}); + } + + _RDPWrite({ from: "tabThreadActor111", "actor":"breakpointActor"+breakpointActorIndex}); + // jsonObj.location.url + // jsonObj.location.line + } + else if (isStringStartWith(jsonObj.to, "breakpointActor") && jsonObj.type === "delete") + { + _RDPWrite({ from: jsonObj.to }); + } + else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "frames") + { + dbg.log("sdfsld...."+breakpointFrame.arguments); + + // var arr = breakpointFrame.getOwnPropertyNames(); + // log("names: "+ arr); + + var parentEnv = breakpointFrame.environment.parent; + log("parentEnv:" + parentEnv); + log("parentEnv.type:" + parentEnv.type); + log("parentEnv.actor:" + parentEnv.actor); + log("parentEnv.functionName:" + parentEnv.functionName); + log("parentEnv.object:" + parentEnv.object); + log("parentEnv.object.type:" + parentEnv.object.type); + log("parentEnv.object.class:" + parentEnv.object.class); + var keys = Object.keys(parentEnv.object); + log("keys: " + keys); + + parentEnv = parentEnv.parent; + log("2parentEnv:" + parentEnv); + log("parentEnv.type:" + parentEnv.type); + log("parentEnv.actor:" + parentEnv.actor); + log("parentEnv.functionName:" + parentEnv.functionName); + + var bindings = parentEnv.bindings; + log("bindings:" + bindings); + + var args = bindings.arguments; + log("args:"+args); + + var vars = bindings.variables; + log("vars:" + vars); + + // if (breakpointFrame != null) + { + dbg.log("get frames....."); + var obj = { + "from": "tabThreadActor111", + "frame":{ "actor":"frameActor", "depth":1, + "type":"call", "where":{ "url":"sample.js", "line":3 }, + "environment":{ "type":"function", "actor":"gFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"gActor" }, + "functionName":"g", + "bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false", + "writable":true, "enumerable":true } } ] }, + "parent":{ "type":"function", "actor":"fFrameActor", + "function":{ "type":"object", "class":"Function", "actor":"fActor" }, + "functionName":"f", + "bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false", + "writable":true, "enumerable":true } } ], + variables: { "z": { "value":"value of z", "configurable":"false", + "writable":true, "enumerable":true } } }, + "parent":{ "type":"object", "actor":"globalCodeActor", + "object":{ "type":"object", "class":"Global", + "actor":"globalObjectActor" } + } + } + }, + "callee":"gActor", "calleeName":"g", + "this":{ "type":"object", "class":"Function", "actor":"gActor" }, + "arguments":["argument to g"] + }}; + + _RDPWrite(obj); + + breakpointFrame = null; + } + } + else if (jsonObj.type === "interrupt") + { + _RDPWrite({ + from: "tabThreadActor111", + type: "resumed" + }); + } + + + + return; // remove Carriage Return's inputstr = inputstr.replace(/\r+/, ""); @@ -570,9 +941,15 @@ _printHelp = function() { dbg.scripts = []; +_RDPWrite = function(jsonObj){ + var buf = JSON.stringify(jsonObj); + _bufferWrite("" + buf.length + ":" + buf); +}; + dbg.onNewScript = function (script) { + dbg.log("onNewScript, "+script.url); // skip if the url is this script - var last = script.url.split("/").pop(); + // var last = script.url.split("/").pop(); var children = script.getChildScripts(), arr = [script].concat(children); @@ -584,9 +961,13 @@ dbg.onNewScript = function (script) { var offsets = arr[i].getLineOffsets(j); dbg.log(" off: " + offsets.join(",") + "; line: " + j); } - } - */ - dbg.scripts[last] = arr; + }*/ + + dbg.scripts["file://"+script.url] = arr; + + // dbg.log("source: "+script.source.text); + + }; dbg.onError = function (frame, report) { @@ -596,6 +977,11 @@ dbg.onError = function (frame, report) { dbg.log("!! exception"); }; +dbg.onDebuggerStatement = function(frame) +{ + dbg.log("onDebuggerStatement..."); +}; + this._prepareDebugger = function (global) { var tmp = new Debugger(global); tmp.onNewScript = dbg.onNewScript; From b5d02d8cca1381c25aaa2e670d71ee04a17accae Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 7 Oct 2013 17:19:00 +0800 Subject: [PATCH 058/557] issue #2823: firefox debugger step ok. --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos2dx/platform/CCFileUtils.cpp | 1 - .../TestJavascript/Classes/AppDelegate.cpp | 5 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../javascript/bindings/ScriptingCore.cpp | 145 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/js/debugger/DevToolsUtils.js | 74 + .../bindings/js/debugger/actors/gcli.js | 77 + .../bindings/js/debugger/actors/inspector.js | 2100 ++++++++++++ .../bindings/js/debugger/actors/profiler.js | 218 ++ .../bindings/js/debugger/actors/root.js | 329 ++ .../bindings/js/debugger/actors/script.js | 2946 +++++++++++++++++ .../bindings/js/debugger/actors/string.js | 145 + .../js/debugger/actors/styleeditor.js | 740 +++++ .../bindings/js/debugger/actors/webapps.js | 397 +++ .../bindings/js/debugger/actors/webbrowser.js | 866 +++++ .../bindings/js/debugger/actors/webconsole.js | 1555 +++++++++ .../bindings/js/debugger/core/promise.js | 294 ++ .../js/debugger/jsb-tests/test_dbgglobal.js | 82 + .../js/debugger/jsb-tests/testactors.js | 98 + .../javascript/bindings/js/debugger/main.js | 921 ++++++ .../bindings/js/debugger/protocol.js | 1219 +++++++ .../js/debugger/tests/mochitest/Makefile.in | 31 + .../tests/mochitest/inspector-helpers.js | 293 ++ .../mochitest/inspector-traversal-data.html | 54 + .../js/debugger/tests/mochitest/moz.build | 5 + .../nonchrome_unsafeDereference.html | 8 + .../mochitest/test_inspector-changeattrs.html | 102 + .../mochitest/test_inspector-changevalue.html | 84 + .../test_inspector-mutations-attr.html | 127 + .../test_inspector-mutations-childlist.html | 313 ++ .../test_inspector-mutations-frameload.html | 217 ++ .../test_inspector-mutations-value.html | 151 + .../test_inspector-pseudoclass-lock.html | 177 + .../mochitest/test_inspector-release.html | 94 + .../mochitest/test_inspector-retain.html | 183 + .../mochitest/test_inspector-traversal.html | 332 ++ .../mochitest/test_unsafeDereference.html | 52 + .../bindings/js/debugger/tests/moz.build | 11 + .../js/debugger/tests/unit/head_dbg.js | 328 ++ .../tests/unit/post_init_global_actors.js | 17 + .../tests/unit/post_init_tab_actors.js | 17 + .../tests/unit/pre_init_global_actors.js | 17 + .../tests/unit/pre_init_tab_actors.js | 17 + .../tests/unit/registertestactors-01.js | 15 + .../tests/unit/registertestactors-02.js | 13 + .../unit/source-map-data/sourcemapped.coffee | 6 + .../unit/source-map-data/sourcemapped.map | 10 + .../js/debugger/tests/unit/sourcemapped.js | 16 + .../js/debugger/tests/unit/test_add_actors.js | 87 + .../js/debugger/tests/unit/test_attach.js | 37 + .../tests/unit/test_blackboxing-01.js | 178 + .../tests/unit/test_blackboxing-02.js | 104 + .../tests/unit/test_blackboxing-03.js | 104 + .../tests/unit/test_blackboxing-04.js | 79 + .../tests/unit/test_blackboxing-05.js | 79 + .../debugger/tests/unit/test_breakpoint-01.js | 62 + .../debugger/tests/unit/test_breakpoint-02.js | 50 + .../debugger/tests/unit/test_breakpoint-03.js | 68 + .../debugger/tests/unit/test_breakpoint-04.js | 67 + .../debugger/tests/unit/test_breakpoint-05.js | 70 + .../debugger/tests/unit/test_breakpoint-06.js | 76 + .../debugger/tests/unit/test_breakpoint-07.js | 73 + .../debugger/tests/unit/test_breakpoint-08.js | 71 + .../debugger/tests/unit/test_breakpoint-09.js | 77 + .../debugger/tests/unit/test_breakpoint-10.js | 77 + .../debugger/tests/unit/test_breakpoint-11.js | 76 + .../debugger/tests/unit/test_breakpoint-12.js | 99 + .../tests/unit/test_breakpointstore.js | 21 + .../js/debugger/tests/unit/test_dbgactor.js | 118 + .../unit/test_dbgclient_debuggerstatement.js | 74 + .../js/debugger/tests/unit/test_dbgglobal.js | 65 + .../js/debugger/tests/unit/test_dbgsocket.js | 164 + .../js/debugger/tests/unit/test_eval-01.js | 58 + .../js/debugger/tests/unit/test_eval-02.js | 48 + .../js/debugger/tests/unit/test_eval-03.js | 50 + .../js/debugger/tests/unit/test_eval-04.js | 69 + .../js/debugger/tests/unit/test_eval-05.js | 54 + .../debugger/tests/unit/test_frameactor-01.js | 44 + .../debugger/tests/unit/test_frameactor-02.js | 46 + .../debugger/tests/unit/test_frameactor-03.js | 48 + .../debugger/tests/unit/test_frameactor-04.js | 92 + .../debugger/tests/unit/test_frameactor-05.js | 90 + .../tests/unit/test_framearguments-01.js | 51 + .../tests/unit/test_framebindings-01.js | 77 + .../tests/unit/test_framebindings-02.js | 62 + .../tests/unit/test_framebindings-03.js | 69 + .../tests/unit/test_framebindings-04.js | 84 + .../tests/unit/test_framebindings-05.js | 62 + .../tests/unit/test_framebindings-06.js | 58 + .../tests/unit/test_frameclient-01.js | 54 + .../tests/unit/test_frameclient-02.js | 47 + .../tests/unit/test_functiongrips-01.js | 94 + .../tests/unit/test_getyoungestframe.js | 30 + .../js/debugger/tests/unit/test_interrupt.js | 50 + .../tests/unit/test_listsources-01.js | 58 + .../tests/unit/test_listsources-02.js | 52 + .../tests/unit/test_listsources-03.js | 52 + .../tests/unit/test_longstringactor.js | 107 + .../tests/unit/test_longstringgrips-01.js | 71 + .../tests/unit/test_longstringgrips-02.js | 60 + .../tests/unit/test_nativewrappers.js | 30 + .../debugger/tests/unit/test_new_source-01.js | 40 + .../debugger/tests/unit/test_nsjsinspector.js | 59 + .../tests/unit/test_objectgrips-01.js | 49 + .../tests/unit/test_objectgrips-02.js | 56 + .../tests/unit/test_objectgrips-03.js | 64 + .../tests/unit/test_objectgrips-04.js | 67 + .../tests/unit/test_objectgrips-05.js | 57 + .../tests/unit/test_objectgrips-06.js | 57 + .../tests/unit/test_objectgrips-07.js | 65 + .../tests/unit/test_pause_exceptions-01.js | 51 + .../tests/unit/test_pause_exceptions-02.js | 48 + .../tests/unit/test_pauselifetime-01.js | 55 + .../tests/unit/test_pauselifetime-02.js | 57 + .../tests/unit/test_pauselifetime-03.js | 62 + .../tests/unit/test_pauselifetime-04.js | 49 + .../tests/unit/test_profiler_activation.js | 66 + .../tests/unit/test_profiler_actor.js | 168 + .../tests/unit/test_protocol_children.js | 434 +++ .../tests/unit/test_protocol_longstring.js | 207 ++ .../tests/unit/test_protocol_simple.js | 276 ++ .../tests/unit/test_register_actor.js | 43 + .../js/debugger/tests/unit/test_source-01.js | 72 + .../debugger/tests/unit/test_sourcemaps-01.js | 64 + .../debugger/tests/unit/test_sourcemaps-02.js | 69 + .../debugger/tests/unit/test_sourcemaps-03.js | 149 + .../debugger/tests/unit/test_sourcemaps-04.js | 57 + .../debugger/tests/unit/test_sourcemaps-05.js | 57 + .../debugger/tests/unit/test_sourcemaps-06.js | 86 + .../debugger/tests/unit/test_sourcemaps-07.js | 67 + .../debugger/tests/unit/test_sourcemaps-08.js | 52 + .../unit/test_sources_backwards_compat-01.js | 77 + .../unit/test_sources_backwards_compat-02.js | 54 + .../debugger/tests/unit/test_stepping-01.js | 74 + .../debugger/tests/unit/test_stepping-02.js | 74 + .../debugger/tests/unit/test_stepping-03.js | 53 + .../debugger/tests/unit/test_stepping-04.js | 65 + .../debugger/tests/unit/test_stepping-05.js | 92 + .../debugger/tests/unit/test_stepping-06.js | 85 + .../tests/unit/test_threadlifetime-01.js | 59 + .../tests/unit/test_threadlifetime-02.js | 60 + .../tests/unit/test_threadlifetime-03.js | 82 + .../tests/unit/test_threadlifetime-04.js | 54 + .../tests/unit/test_threadlifetime-05.js | 84 + .../tests/unit/test_threadlifetime-06.js | 72 + .../tests/unit/test_unsafeDereference.js | 134 + .../js/debugger/tests/unit/testactors.js | 98 + .../debugger/tests/unit/testcompatactors.js | 119 + .../js/debugger/tests/unit/xpcshell.ini | 144 + .../bindings/js/debugger/transport.js | 285 ++ .../javascript/bindings/js/jsb_debugger.js | 154 +- 152 files changed, 23120 insertions(+), 153 deletions(-) create mode 100644 scripting/javascript/bindings/js/debugger/DevToolsUtils.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/gcli.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/inspector.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/profiler.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/root.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/script.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/string.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/styleeditor.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/webapps.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/webbrowser.js create mode 100644 scripting/javascript/bindings/js/debugger/actors/webconsole.js create mode 100644 scripting/javascript/bindings/js/debugger/core/promise.js create mode 100644 scripting/javascript/bindings/js/debugger/jsb-tests/test_dbgglobal.js create mode 100644 scripting/javascript/bindings/js/debugger/jsb-tests/testactors.js create mode 100644 scripting/javascript/bindings/js/debugger/main.js create mode 100644 scripting/javascript/bindings/js/debugger/protocol.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/Makefile.in create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/inspector-helpers.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/inspector-traversal-data.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/moz.build create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/nonchrome_unsafeDereference.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-changeattrs.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-changevalue.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-mutations-attr.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-mutations-childlist.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-mutations-frameload.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-mutations-value.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-pseudoclass-lock.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-release.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-retain.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_inspector-traversal.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/mochitest/test_unsafeDereference.html create mode 100644 scripting/javascript/bindings/js/debugger/tests/moz.build create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/head_dbg.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/post_init_global_actors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/post_init_tab_actors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/pre_init_global_actors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/pre_init_tab_actors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/registertestactors-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/registertestactors-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/source-map-data/sourcemapped.coffee create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/source-map-data/sourcemapped.map create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/sourcemapped.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_add_actors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_attach.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_blackboxing-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_blackboxing-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_blackboxing-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_blackboxing-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_blackboxing-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-07.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-08.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-09.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-10.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-11.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpoint-12.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_breakpointstore.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_dbgactor.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_dbgclient_debuggerstatement.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_dbgglobal.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_dbgsocket.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_eval-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_eval-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_eval-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_eval-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_eval-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameactor-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameactor-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameactor-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameactor-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameactor-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framearguments-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_framebindings-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameclient-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_frameclient-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_functiongrips-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_getyoungestframe.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_interrupt.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_listsources-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_listsources-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_listsources-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_longstringactor.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_longstringgrips-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_longstringgrips-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_nativewrappers.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_new_source-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_nsjsinspector.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_objectgrips-07.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pause_exceptions-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pause_exceptions-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pauselifetime-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pauselifetime-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pauselifetime-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_pauselifetime-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_profiler_activation.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_profiler_actor.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_protocol_children.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_protocol_longstring.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_protocol_simple.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_register_actor.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_source-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-07.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sourcemaps-08.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sources_backwards_compat-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_sources_backwards_compat-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_stepping-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-01.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-02.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-03.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-04.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-05.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_threadlifetime-06.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/test_unsafeDereference.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/testactors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/testcompatactors.js create mode 100644 scripting/javascript/bindings/js/debugger/tests/unit/xpcshell.ini create mode 100644 scripting/javascript/bindings/js/debugger/transport.js diff --git a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 48555d6a5d..c1720e39d7 100644 --- a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3959af89b6bbc8fb982769d22d2591991107d6e5 \ No newline at end of file +8ad5afb135018cfa93b3aee4dddbea24f0ef9b9e \ No newline at end of file diff --git a/cocos2dx/platform/CCFileUtils.cpp b/cocos2dx/platform/CCFileUtils.cpp index 6f286607fb..0db8c28f1a 100644 --- a/cocos2dx/platform/CCFileUtils.cpp +++ b/cocos2dx/platform/CCFileUtils.cpp @@ -618,7 +618,6 @@ std::string FileUtils::fullPathForFilename(const std::string &filename) for (auto searchIt = _searchPathArray.begin(); searchIt != _searchPathArray.end(); ++searchIt) { for (auto resolutionIt = _searchResolutionsOrderArray.begin(); resolutionIt != _searchResolutionsOrderArray.end(); ++resolutionIt) { - fullpath = this->getPathForFilename(newFilename, *resolutionIt, *searchIt); if (fullpath.length() > 0) diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp index 4b7b6c87ff..fc44e06b9b 100644 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp +++ b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp @@ -41,6 +41,9 @@ bool AppDelegate::applicationDidFinishLaunching() // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); + FileUtils::getInstance()->addSearchPath("res"); + FileUtils::getInstance()->addSearchPath("js"); + ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_all_cocos2dx_extension); @@ -54,8 +57,6 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_CCBuilderReader); sc->start(); - - FileUtils::getInstance()->addSearchPath("res"); auto pEngine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(pEngine); diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index ec33bf839a..0cf8b5aa58 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -381c282bed409f4b41a82505460d4d6c84ba70ab \ No newline at end of file +0017c1d76ce42fd252ff8245774d5a276e278115 \ No newline at end of file diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 0ed5b8eb68..9c9370e79b 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -662,9 +662,10 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) if (argc == 2 && argv[1].isString()) { JSString* globalName = JSVAL_TO_STRING(argv[1]); JSStringWrapper name(globalName); - js::RootedObject* rootedGlobal = globals[name]; - if (rootedGlobal) { - res = ScriptingCore::getInstance()->runScript(path, rootedGlobal->get()); +// js::RootedObject* rootedGlobal = globals[name]; + JSObject* debugObj = ScriptingCore::getInstance()->getDebugGlobal(); + if (debugObj) { + res = ScriptingCore::getInstance()->runScript(path, debugObj); } else { JS_ReportError(cx, "Invalid global object: %s", (char*)name); return JS_FALSE; @@ -1964,9 +1965,9 @@ void ScriptingCore::enableDebugger() { JS_DefineFunction(cx_, debugGlobal_, "_bufferRead", JSBDebug_BufferRead, 0, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx_, debugGlobal_, "_lockVM", JSBDebug_LockExecution, 2, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx_, debugGlobal_, "_unlockVM", JSBDebug_UnlockExecution, 0, JSPROP_READONLY | JSPROP_PERMANENT); - + + runScript("jsb_debugger.js", debugGlobal_); -// runScript("SysTest/script.js", debugGlobal_); CCLOG("before _prepareDebugger..."); // prepare the debugger @@ -2266,7 +2267,6 @@ static void serverEntryPoint(void) listen(s, 1); - int recieveIndex = 0; while (true) { clientSocket = accept(s, NULL, NULL); @@ -2284,144 +2284,13 @@ static void serverEntryPoint(void) // process any input, send any output clearBuffers(); -// if (recieveIndex == 0) -// { -// replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}"); -// ++recieveIndex; -// } - - char buf[1024] = {0}; int readBytes = 0; while ((readBytes = ::recv(clientSocket, buf, sizeof(buf), 0)) > 0) { buf[readBytes] = '\0'; - TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); +// TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); -// if (recieveIndex == 1) -// { -// replyToClient(clientSocket, "{ \"from\":\"root\", \"tabs\":[{ \"actor\":\"JSBTabActor\", \"title\":\"Hello cocos2d-x JSB\", \"url\":\"http://www.cocos2d-x.org\" }], \"selected\":0 }"); -// } -// else if (recieveIndex == 2) -// { -// replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabAttached\", \"threadActor\":\"tabThreadActor111\" }"); -// } -// else if (recieveIndex == 3) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"paused\",\ -// \"actor\": \"JSBTabActor\",\ -// \"poppedFrames\": [],\ -// \"why\": {\ -// \"type\": \"attached\"\ -// }\ -// }"); -// -// -// -// //replyToClient(clientSocket, "{ \"from\":\"JSBTabActor\", \"type\":\"tabNavigated\", \"state\":\"start\", \"url\":\"my_url.js\" }"); -// } -// else if (recieveIndex == 4) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"newSource\",\ -// \"source\": {\ -// \"actor\": \"source_actor1\",\ -// \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ -// \"isBlackBoxed\": false\ -// }\ -// }"); -// -// replyToClient(clientSocket, -// "{\ -// \"sources\": [\ -// {\ -// \"actor\": \"source_actor1\",\ -// \"url\": \"file://~/Project/cocos2d-html5/cocos2d/CCDirector.js\",\ -// \"isBlackBoxed\": false\ -// }\ -// ],\ -// \"from\": \"tabThreadActor111\"\ -// }"); -// } -// else if (recieveIndex == 5) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"source_actor1\",\ -// \"source\": {\ -// \"type\": \"longString\",\ -// \"initial\": \"var cc = cc || {}; cc.Director = {};\",\ -// \"length\": 100,\ -// \"actor\": \"conn2.longString48\"\ -// }\ -// }"); -// } -// else if (recieveIndex == 6) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"conn2.longString48\",\ -// \"substring\": \"var cc = cc || {}; cc.Director = {};\ -//\\ncc.Sprite = {};\"\ -// }"); -// -// -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"resumed\"\ -// }"); -// } -// else if (recieveIndex == 7) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"resumed\"\ -// }"); -// } -// else if (recieveIndex == 8) -// { -// replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); -// } -// else if (recieveIndex == 9) -// { -// replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); -// } -// else if (recieveIndex == 10) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"resumed\"\ -// }"); -// } -// else -// { -// -// -// std::string recvBuf = buf; -// auto found = recvBuf.find("setBreakpoint"); -// if (found != std::string::npos) -// { -// replyToClient(clientSocket, "{ \"from\":\"tabThreadActor111\", \"actor\":\"breakActor\"}");//, \"actualLocation\":2 }"); -// } -// -// found = recvBuf.find("delete"); -// if (found != std::string::npos) -// { -// replyToClient(clientSocket, "{ \"from\":\"breakActor\" }"); -// } -// -// found = recvBuf.find("interrupt"); -// if (found != std::string::npos) -// { -// replyToClient(clientSocket, "{\ -// \"from\": \"tabThreadActor111\",\ -// \"type\": \"resumed\"\ -// }"); -// } -// -// } -// ++recieveIndex; // no other thread is using this inData.append(buf); // process any input, send any output diff --git a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 9ff7a17801..9aaad3f31f 100644 --- a/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -db6aaa41d0756117258eebb759cd6420f66071e0 \ No newline at end of file +ceb78008acf831592a416d7dfa85a9dfd0ddae75 \ No newline at end of file diff --git a/scripting/javascript/bindings/js/debugger/DevToolsUtils.js b/scripting/javascript/bindings/js/debugger/DevToolsUtils.js new file mode 100644 index 0000000000..8b8fb19feb --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/DevToolsUtils.js @@ -0,0 +1,74 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +var dump = function(msg) { + log(msg); +}; + +/* General utilities used throughout devtools. */ + +/* Turn the error e into a string, without fail. */ +this.safeErrorString = function safeErrorString(aError) { + try { + var s = aError.toString(); + if (typeof s === "string") + return s; + } catch (ee) { } + + return ""; +} + +/** + * Report that |aWho| threw an exception, |aException|. + */ +this.reportException = function reportException(aWho, aException) { + let msg = aWho + " threw an exception: " + safeErrorString(aException); + if (aException.stack) { + msg += "\nCall stack:\n" + aException.stack; + } + + dump(msg + "\n"); + + // if (Components.utils.reportError) { + // /* + // * Note that the xpcshell test harness registers an observer for + // * console messages, so when we're running tests, this will cause + // * the test to quit. + // */ + // Components.utils.reportError(msg); + // } +} + +/** + * Given a handler function that may throw, return an infallible handler + * function that calls the fallible handler, and logs any exceptions it + * throws. + * + * @param aHandler function + * A handler function, which may throw. + * @param aName string + * A name for aHandler, for use in error messages. If omitted, we use + * aHandler.name. + * + * (SpiderMonkey does generate good names for anonymous functions, but we + * don't have a way to get at them from JavaScript at the moment.) + */ +this.makeInfallible = function makeInfallible(aHandler, aName) { + if (!aName) + aName = aHandler.name; + + return function (/* arguments */) { + try { + return aHandler.apply(this, arguments); + } catch (ex) { + let who = "Handler function"; + if (aName) { + who += " " + aName; + } + reportException(who, ex); + } + } +} diff --git a/scripting/javascript/bindings/js/debugger/actors/gcli.js b/scripting/javascript/bindings/js/debugger/actors/gcli.js new file mode 100644 index 0000000000..1f3c914d4e --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/gcli.js @@ -0,0 +1,77 @@ +/* -*- Mode: js2; js2-basic-offset: 2; indent-tabs-mode: nil; -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +let { classes: Cc, interfaces: Ci, utils: Cu } = Components; + +let { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); + +XPCOMUtils.defineLazyModuleGetter(this, "console", + "resource://gre/modules/devtools/Console.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "CommandUtils", + "resource:///modules/devtools/DeveloperToolbar.jsm"); + +XPCOMUtils.defineLazyGetter(this, "require", function() { + let { require } = Cu.import("resource://gre/modules/devtools/Require.jsm", {}); + Cu.import("resource://gre/modules/devtools/gcli.jsm", {}); + return require; +}); + +XPCOMUtils.defineLazyGetter(this, "canon", () => require("gcli/canon")); +XPCOMUtils.defineLazyGetter(this, "Requisition", () => require("gcli/cli").Requisition); +XPCOMUtils.defineLazyGetter(this, "util", () => require("util/util")); + + +/** + * Manage remote connections that want to talk to GCLI + * @constructor + * @param connection The connection to the client, DebuggerServerConnection + * @param parentActor Optional, the parent actor + */ +function GcliActor(connection, parentActor) { + this.connection = connection; +} + +GcliActor.prototype.actorPrefix = "gcli"; + +GcliActor.prototype.disconnect = function() { +}; + +GcliActor.prototype.getCommandSpecs = function(request) { + return { commandSpecs: canon.getCommandSpecs() }; +}; + +GcliActor.prototype.execute = function(request) { + let windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"] + .getService(Ci.nsIWindowMediator); + let chromeWindow = windowMediator.getMostRecentWindow("navigator:browser"); + let contentWindow = chromeWindow.gBrowser.selectedTab.linkedBrowser.contentWindow; + + let environment = CommandUtils.createEnvironment(chromeWindow.document, + contentWindow.document); + + let requisition = new Requisition(environment); + requisition.updateExec(request.typed).then(output => { + return output.promise.then(() => { + this.connection.send({ + from: this.actorID, + requestId: request.requestId, + data: output.data, + type: output.type, + error: output.error + }); + }); + }).then(null, console.error); +}; + +GcliActor.prototype.requestTypes = { + getCommandSpecs: GcliActor.prototype.getCommandSpecs, + execute: GcliActor.prototype.execute, +}; + +addTabActor(GcliActor, "gcliActor"); +addGlobalActor(GcliActor, "gcliActor"); diff --git a/scripting/javascript/bindings/js/debugger/actors/inspector.js b/scripting/javascript/bindings/js/debugger/actors/inspector.js new file mode 100644 index 0000000000..ac07ad103a --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/inspector.js @@ -0,0 +1,2100 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/** + * Here's the server side of the remote inspector. + * + * The WalkerActor is the client's view of the debuggee's DOM. It's gives + * the client a tree of NodeActor objects. + * + * The walker presents the DOM tree mostly unmodified from the source DOM + * tree, but with a few key differences: + * + * - Empty text nodes are ignored. This is pretty typical of developer + * tools, but maybe we should reconsider that on the server side. + * - iframes with documents loaded have the loaded document as the child, + * the walker provides one big tree for the whole document tree. + * + * There are a few ways to get references to NodeActors: + * + * - When you first get a WalkerActor reference, it comes with a free + * reference to the root document's node. + * - Given a node, you can ask for children, siblings, and parents. + * - You can issue querySelector and querySelectorAll requests to find + * other elements. + * - Requests that return arbitrary nodes from the tree (like querySelector + * and querySelectorAll) will also return any nodes the client hasn't + * seen in order to have a complete set of parents. + * + * Once you have a NodeFront, you should be able to answer a few questions + * without further round trips, like the node's name, namespace/tagName, + * attributes, etc. Other questions (like a text node's full nodeValue) + * might require another round trip. + * + * The protocol guarantees that the client will always know the parent of + * any node that is returned by the server. This means that some requests + * (like querySelector) will include the extra nodes needed to satisfy this + * requirement. The client keeps track of this parent relationship, so the + * node fronts form a tree that is a subset of the actual DOM tree. + */ + +const {Cc, Ci, Cu} = require("chrome"); + +const protocol = require("devtools/server/protocol"); +const {Arg, Option, method, RetVal, types} = protocol; +const {LongStringActor, ShortLongString} = require("devtools/server/actors/string"); +const promise = require("sdk/core/promise"); +const object = require("sdk/util/object"); +const events = require("sdk/event/core"); +const { Unknown } = require("sdk/platform/xpcom"); +const { Class } = require("sdk/core/heritage"); + +const PSEUDO_CLASSES = [":hover", ":active", ":focus"]; + +Cu.import("resource://gre/modules/Services.jsm"); + +exports.register = function(handle) { + handle.addTabActor(InspectorActor, "inspectorActor"); +}; + +exports.unregister = function(handle) { + handle.removeTabActor(InspectorActor); +}; + +// XXX: A poor man's makeInfallible until we move it out of transport.js +// Which should be very soon. +function makeInfallible(handler) { + return function(...args) { + try { + return handler.apply(this, args); + } catch(ex) { + console.error(ex); + } + return undefined; + } +} + +// A resolve that hits the main loop first. +function delayedResolve(value) { + let deferred = promise.defer(); + Services.tm.mainThread.dispatch(makeInfallible(function delayedResolveHandler() { + deferred.resolve(value); + }), 0); + return deferred.promise; +} + +/** + * We only send nodeValue up to a certain size by default. This stuff + * controls that size. + */ +exports.DEFAULT_VALUE_SUMMARY_LENGTH = 50; +var gValueSummaryLength = exports.DEFAULT_VALUE_SUMMARY_LENGTH; + +exports.getValueSummaryLength = function() { + return gValueSummaryLength; +}; + +exports.setValueSummaryLength = function(val) { + gValueSummaryLength = val; +}; + +/** + * Server side of the node actor. + */ +var NodeActor = protocol.ActorClass({ + typeName: "domnode", + + initialize: function(walker, node) { + protocol.Actor.prototype.initialize.call(this, null); + this.walker = walker; + this.rawNode = node; + }, + + toString: function() { + return "[NodeActor " + this.actorID + " for " + this.rawNode.toString() + "]"; + }, + + /** + * Instead of storing a connection object, the NodeActor gets its connection + * from its associated walker. + */ + get conn() this.walker.conn, + + // Returns the JSON representation of this object over the wire. + form: function(detail) { + let parentNode = this.walker.parentNode(this); + + // Estimate the number of children. + let numChildren = this.rawNode.childNodes.length; + if (numChildren === 0 && + (this.rawNode.contentDocument || this.rawNode.getSVGDocument)) { + // This might be an iframe with virtual children. + numChildren = 1; + } + + let form = { + actor: this.actorID, + parent: parentNode ? parentNode.actorID : undefined, + nodeType: this.rawNode.nodeType, + namespaceURI: this.namespaceURI, + nodeName: this.rawNode.nodeName, + numChildren: numChildren, + + // doctype attributes + name: this.rawNode.name, + publicId: this.rawNode.publicId, + systemId: this.rawNode.systemId, + + attrs: this.writeAttrs(), + + pseudoClassLocks: this.writePseudoClassLocks(), + }; + + if (this.rawNode.ownerDocument && + this.rawNode.ownerDocument.documentElement === this.rawNode) { + form.isDocumentElement = true; + } + + if (this.rawNode.nodeValue) { + // We only include a short version of the value if it's longer than + // gValueSummaryLength + if (this.rawNode.nodeValue.length > gValueSummaryLength) { + form.shortValue = this.rawNode.nodeValue.substring(0, gValueSummaryLength); + form.incompleteValue = true; + } else { + form.shortValue = this.rawNode.nodeValue; + } + } + + return form; + }, + + writeAttrs: function() { + if (!this.rawNode.attributes) { + return undefined; + } + return [{namespace: attr.namespace, name: attr.name, value: attr.value } + for (attr of this.rawNode.attributes)]; + }, + + writePseudoClassLocks: function() { + if (this.rawNode.nodeType !== Ci.nsIDOMNode.ELEMENT_NODE) { + return undefined; + } + let ret = undefined; + for (let pseudo of PSEUDO_CLASSES) { + if (DOMUtils.hasPseudoClassLock(this.rawNode, pseudo)) { + ret = ret || []; + ret.push(pseudo); + } + } + return ret; + }, + + /** + * Returns a LongStringActor with the node's value. + */ + getNodeValue: method(function() { + return new LongStringActor(this.conn, this.rawNode.nodeValue || ""); + }, { + request: {}, + response: { + value: RetVal("longstring") + } + }), + + /** + * Set the node's value to a given string. + */ + setNodeValue: method(function(value) { + this.rawNode.nodeValue = value; + }, { + request: { value: Arg(0) }, + response: {} + }), + + /** + * Modify a node's attributes. Passed an array of modifications + * similar in format to "attributes" mutations. + * { + * attributeName: + * attributeNamespace: + * newValue: - If null or undefined, the attribute + * will be removed. + * } + * + * Returns when the modifications have been made. Mutations will + * be queued for any changes made. + */ + modifyAttributes: method(function(modifications) { + let rawNode = this.rawNode; + for (let change of modifications) { + if (change.newValue == null) { + if (change.attributeNamespace) { + rawNode.removeAttributeNS(change.attributeNamespace, change.attributeName); + } else { + rawNode.removeAttribute(change.attributeName); + } + } else { + if (change.attributeNamespace) { + rawNode.setAttributeNS(change.attributeNamespace, change.attributeName, change.newValue); + } else { + rawNode.setAttribute(change.attributeName, change.newValue); + } + } + } + }, { + request: { + modifications: Arg(0, "array:json") + }, + response: {} + }), + +}); + +/** + * Client side of the node actor. + * + * Node fronts are strored in a tree that mirrors the DOM tree on the + * server, but with a few key differences: + * - Not all children will be necessary loaded for each node. + * - The order of children isn't guaranteed to be the same as the DOM. + * Children are stored in a doubly-linked list, to make addition/removal + * and traversal quick. + * + * Due to the order/incompleteness of the child list, it is safe to use + * the parent node from clients, but the `children` request should be used + * to traverse children. + */ +let NodeFront = protocol.FrontClass(NodeActor, { + initialize: function(conn, form, detail, ctx) { + this._parent = null; // The parent node + this._child = null; // The first child of this node. + this._next = null; // The next sibling of this node. + this._prev = null; // The previous sibling of this node. + protocol.Front.prototype.initialize.call(this, conn, form, detail, ctx); + }, + + /** + * Destroy a node front. The node must have been removed from the + * ownership tree before this is called, unless the whole walker front + * is being destroyed. + */ + destroy: function() { + // If an observer was added on this node, shut it down. + if (this.observer) { + this._observer.disconnect(); + this._observer = null; + } + + protocol.Front.prototype.destroy.call(this); + }, + + // Update the object given a form representation off the wire. + form: function(form, detail, ctx) { + // Shallow copy of the form. We could just store a reference, but + // eventually we'll want to update some of the data. + this._form = object.merge(form); + this._form.attrs = this._form.attrs ? this._form.attrs.slice() : []; + + if (form.parent) { + // Get the owner actor for this actor (the walker), and find the + // parent node of this actor from it, creating a standin node if + // necessary. + let parentNodeFront = ctx.marshallPool().ensureParentFront(form.parent); + this.reparent(parentNodeFront); + } + }, + + /** + * Returns the parent NodeFront for this NodeFront. + */ + parentNode: function() { + return this._parent; + }, + + /** + * Process a mutation entry as returned from the walker's `getMutations` + * request. Only tries to handle changes of the node's contents + * themselves (character data and attribute changes), the walker itself + * will keep the ownership tree up to date. + */ + updateMutation: function(change) { + if (change.type === "attributes") { + // We'll need to lazily reparse the attributes after this change. + this._attrMap = undefined; + + // Update any already-existing attributes. + let found = false; + for (let i = 0; i < this.attributes.length; i++) { + let attr = this.attributes[i]; + if (attr.name == change.attributeName && + attr.namespace == change.attributeNamespace) { + if (change.newValue !== null) { + attr.value = change.newValue; + } else { + this.attributes.splice(i, 1); + } + found = true; + break; + } + } + // This is a new attribute. + if (!found) { + this.attributes.push({ + name: change.attributeName, + namespace: change.attributeNamespace, + value: change.newValue + }); + } + } else if (change.type === "characterData") { + this._form.shortValue = change.newValue; + this._form.incompleteValue = change.incompleteValue; + } else if (change.type === "pseudoClassLock") { + this._form.pseudoClassLocks = change.pseudoClassLocks; + } + }, + + // Some accessors to make NodeFront feel more like an nsIDOMNode + + get id() this.getAttribute("id"), + + get nodeType() this._form.nodeType, + get namespaceURI() this._form.namespaceURI, + get nodeName() this._form.nodeName, + + get className() { + return this.getAttribute("class") || ''; + }, + + get hasChildren() this._form.numChildren > 0, + get numChildren() this._form.numChildren, + + get tagName() this.nodeType === Ci.nsIDOMNode.ELEMENT_NODE ? this.nodeName : null, + get shortValue() this._form.shortValue, + get incompleteValue() !!this._form.incompleteValue, + + get isDocumentElement() !!this._form.isDocumentElement, + + // doctype properties + get name() this._form.name, + get publicId() this._form.publicId, + get systemId() this._form.systemId, + + getAttribute: function(name) { + let attr = this._getAttribute(name); + return attr ? attr.value : null; + }, + hasAttribute: function(name) { + this._cacheAttributes(); + return (name in this._attrMap); + }, + + get attributes() this._form.attrs, + + get pseudoClassLocks() this._form.pseudoClassLocks || [], + hasPseudoClassLock: function(pseudo) { + return this.pseudoClassLocks.some(locked => locked === pseudo); + }, + + getNodeValue: protocol.custom(function() { + if (!this.incompleteValue) { + return delayedResolve(new ShortLongString(this.shortValue)); + } else { + return this._getNodeValue(); + } + }, { + impl: "_getNodeValue" + }), + + /** + * Return a new AttributeModificationList for this node. + */ + startModifyingAttributes: function() { + return AttributeModificationList(this); + }, + + _cacheAttributes: function() { + if (typeof(this._attrMap) != "undefined") { + return; + } + this._attrMap = {}; + for (let attr of this.attributes) { + this._attrMap[attr.name] = attr; + } + }, + + _getAttribute: function(name) { + this._cacheAttributes(); + return this._attrMap[name] || undefined; + }, + + /** + * Set this node's parent. Note that the children saved in + * this tree are unordered and incomplete, so shouldn't be used + * instead of a `children` request. + */ + reparent: function(parent) { + if (this._parent === parent) { + return; + } + + if (this._parent && this._parent._child === this) { + this._parent._child = this._next; + } + if (this._prev) { + this._prev._next = this._next; + } + if (this._next) { + this._next._prev = this._prev; + } + this._next = null; + this._prev = null; + this._parent = parent; + if (!parent) { + // Subtree is disconnected, we're done + return; + } + this._next = parent._child; + if (this._next) { + this._next._prev = this; + } + parent._child = this; + }, + + /** + * Return all the known children of this node. + */ + treeChildren: function() { + let ret = []; + for (let child = this._child; child != null; child = child._next) { + ret.push(child); + } + return ret; + }, + + /** + * Get an nsIDOMNode for the given node front. This only works locally, + * and is only intended as a stopgap during the transition to the remote + * protocol. If you depend on this you're likely to break soon. + */ + rawNode: function(rawNode) { + if (!this.conn._transport._serverConnection) { + console.warn("Tried to use rawNode on a remote connection."); + return null; + } + let actor = this.conn._transport._serverConnection.getActor(this.actorID); + if (!actor) { + // Can happen if we try to get the raw node for an already-expired + // actor. + return null; + } + return actor.rawNode; + } +}); + +/** + * Returned from any call that might return a node that isn't connected to root by + * nodes the child has seen, such as querySelector. + */ +types.addDictType("disconnectedNode", { + // The actual node to return + node: "domnode", + + // Nodes that are needed to connect the node to a node the client has already seen + newNodes: "array:domnode" +}); + +types.addDictType("disconnectedNodeArray", { + // The actual node list to return + nodes: "array:domnode", + + // Nodes that are needed to connect those nodes to the root. + newNodes: "array:domnode" +}); + +types.addDictType("dommutation", {}); + +/** + * Server side of a node list as returned by querySelectorAll() + */ +var NodeListActor = exports.NodeListActor = protocol.ActorClass({ + typeName: "domnodelist", + + initialize: function(walker, nodeList) { + protocol.Actor.prototype.initialize.call(this); + this.walker = walker; + this.nodeList = nodeList; + }, + + destroy: function() { + protocol.Actor.prototype.destroy.call(this); + }, + + /** + * Instead of storing a connection object, the NodeActor gets its connection + * from its associated walker. + */ + get conn() { + return this.walker.conn; + }, + + /** + * Items returned by this actor should belong to the parent walker. + */ + marshallPool: function() { + return this.walker; + }, + + // Returns the JSON representation of this object over the wire. + form: function() { + return { + actor: this.actorID, + length: this.nodeList.length + } + }, + + /** + * Get a single node from the node list. + */ + item: method(function(index) { + let node = this.walker._ref(this.nodeList[index]); + let newNodes = [node for (node of this.walker.ensurePathToRoot(node))]; + return { + node: node, + newNodes: newNodes + } + }, { + request: { item: Arg(0) }, + response: RetVal("disconnectedNode") + }), + + /** + * Get a range of the items from the node list. + */ + items: method(function(start=0, end=this.nodeList.length) { + let items = [this.walker._ref(item) for (item of Array.prototype.slice.call(this.nodeList, start, end))]; + let newNodes = new Set(); + for (let item of items) { + this.walker.ensurePathToRoot(item, newNodes); + } + return { + nodes: items, + newNodes: [node for (node of newNodes)] + } + }, { + request: { + start: Arg(0, "number", { optional: true }), + end: Arg(1, "number", { optional: true }) + }, + response: { nodes: RetVal("disconnectedNodeArray") } + }), + + release: method(function() {}, { release: true }) +}); + +/** + * Client side of a node list as returned by querySelectorAll() + */ +var NodeListFront = exports.NodeLIstFront = protocol.FrontClass(NodeListActor, { + initialize: function(client, form) { + protocol.Front.prototype.initialize.call(this, client, form); + }, + + destroy: function() { + protocol.Front.prototype.destroy.call(this); + }, + + marshallPool: function() { + return this.parent(); + }, + + // Update the object given a form representation off the wire. + form: function(json) { + this.length = json.length; + }, + + item: protocol.custom(function(index) { + return this._item(index).then(response => { + return response.node; + }); + }, { + impl: "_item" + }), + + items: protocol.custom(function(start, end) { + return this._items(start, end).then(response => { + return response.nodes; + }); + }, { + impl: "_items" + }) +}); + +// Some common request/response templates for the dom walker + +let nodeArrayMethod = { + request: { + node: Arg(0, "domnode"), + maxNodes: Option(1), + center: Option(1, "domnode"), + start: Option(1, "domnode"), + whatToShow: Option(1) + }, + response: RetVal(types.addDictType("domtraversalarray", { + nodes: "array:domnode" + })) +}; + +let traversalMethod = { + request: { + node: Arg(0, "domnode"), + whatToShow: Option(1) + }, + response: { + node: RetVal("domnode", {optional: true}) + } +} + +/** + * We need to know when a document is navigating away so that we can kill + * the nodes underneath it. We also need to know when a document is + * navigated to so that we can send a mutation event for the iframe node. + * + * The nsIWebProgressListener is the easiest/best way to watch these + * loads that works correctly with the bfcache. + * + * See nsIWebProgressListener for details + * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIWebProgressListener + */ +var ProgressListener = Class({ + extends: Unknown, + interfaces: ["nsIWebProgressListener", "nsISupportsWeakReference"], + + initialize: function(webProgress) { + Unknown.prototype.initialize.call(this); + this.webProgress = webProgress; + this.webProgress.addProgressListener(this); + }, + + destroy: function() { + this.webProgress.removeProgressListener(this); + }, + + onStateChange: makeInfallible(function stateChange(progress, request, flag, status) { + let isWindow = flag & Ci.nsIWebProgressListener.STATE_IS_WINDOW; + let isDocument = flag & Ci.nsIWebProgressListener.STATE_IS_DOCUMENT; + if (!(isWindow || isDocument)) { + return; + } + + if (isDocument && (flag & Ci.nsIWebProgressListener.STATE_START)) { + events.emit(this, "windowchange-start", progress.DOMWindow); + } + if (isWindow && (flag & Ci.nsIWebProgressListener.STATE_STOP)) { + events.emit(this, "windowchange-stop", progress.DOMWindow); + } + }), + onProgressChange: function() {}, + onSecurityChange: function() {}, + onStatusChange: function() {}, + onLocationChange: function() {}, +}); + +/** + * Server side of the DOM walker. + */ +var WalkerActor = protocol.ActorClass({ + typeName: "domwalker", + + events: { + "new-mutations" : { + type: "newMutations" + } + }, + + /** + * Create the WalkerActor + * @param DebuggerServerConnection conn + * The server connection. + */ + initialize: function(conn, document, webProgress, options) { + protocol.Actor.prototype.initialize.call(this, conn); + this.rootDoc = document; + this._refMap = new Map(); + this._pendingMutations = []; + this._activePseudoClassLocks = new Set(); + + // Nodes which have been removed from the client's known + // ownership tree are considered "orphaned", and stored in + // this set. + this._orphaned = new Set(); + + // The client can tell the walker that it is interested in a node + // even when it is orphaned with the `retainNode` method. This + // list contains orphaned nodes that were so retained. + this._retainedOrphans = new Set(); + + this.onMutations = this.onMutations.bind(this); + this.onFrameLoad = this.onFrameLoad.bind(this); + this.onFrameUnload = this.onFrameUnload.bind(this); + + this.progressListener = ProgressListener(webProgress); + + events.on(this.progressListener, "windowchange-start", this.onFrameUnload); + events.on(this.progressListener, "windowchange-stop", this.onFrameLoad); + + // Ensure that the root document node actor is ready and + // managed. + this.rootNode = this.document(); + }, + + // Returns the JSON representation of this object over the wire. + form: function() { + return { + actor: this.actorID, + root: this.rootNode.form() + } + }, + + toString: function() { + return "[WalkerActor " + this.actorID + "]"; + }, + + destroy: function() { + this.clearPseudoClassLocks(); + this._activePseudoClassLocks = null; + this.progressListener.destroy(); + this.rootDoc = null; + protocol.Actor.prototype.destroy.call(this); + }, + + release: method(function() {}, { release: true }), + + unmanage: function(actor) { + if (actor instanceof NodeActor) { + if (this._activePseudoClassLocks && + this._activePseudoClassLocks.has(actor)) { + this.clearPsuedoClassLocks(actor); + } + this._refMap.delete(actor.rawNode); + } + protocol.Actor.prototype.unmanage.call(this, actor); + }, + + _ref: function(node) { + let actor = this._refMap.get(node); + if (actor) return actor; + + actor = new NodeActor(this, node); + + // Add the node actor as a child of this walker actor, assigning + // it an actorID. + this.manage(actor); + this._refMap.set(node, actor); + + if (node.nodeType === Ci.nsIDOMNode.DOCUMENT_NODE) { + this._watchDocument(actor); + } + return actor; + }, + + /** + * Watch the given document node for mutations using the DOM observer + * API. + */ + _watchDocument: function(actor) { + let node = actor.rawNode; + // Create the observer on the node's actor. The node will make sure + // the observer is cleaned up when the actor is released. + actor.observer = actor.rawNode.defaultView.MutationObserver(this.onMutations); + actor.observer.observe(node, { + attributes: true, + characterData: true, + childList: true, + subtree: true + }); + }, + + /** + * Return the document node that contains the given node, + * or the root node if no node is specified. + * @param NodeActor node + * The node whose document is needed, or null to + * return the root. + */ + document: method(function(node) { + let doc = node ? nodeDocument(node.rawNode) : this.rootDoc; + return this._ref(doc); + }, { + request: { node: Arg(0, "domnode", {optional: true}) }, + response: { node: RetVal("domnode") }, + }), + + /** + * Return the documentElement for the document containing the + * given node. + * @param NodeActor node + * The node whose documentElement is requested, or null + * to use the root document. + */ + documentElement: method(function(node) { + let elt = node ? nodeDocument(node.rawNode).documentElement : this.rootDoc.documentElement; + return this._ref(elt); + }, { + request: { node: Arg(0, "domnode", {optional: true}) }, + response: { node: RetVal("domnode") }, + }), + + /** + * Return all parents of the given node, ordered from immediate parent + * to root. + * @param NodeActor node + * The node whose parents are requested. + * @param object options + * Named options, including: + * `sameDocument`: If true, parents will be restricted to the same + * document as the node. + */ + parents: method(function(node, options={}) { + let walker = documentWalker(node.rawNode); + let parents = []; + let cur; + while((cur = walker.parentNode())) { + if (options.sameDocument && cur.ownerDocument != node.rawNode.ownerDocument) { + break; + } + parents.push(this._ref(cur)); + } + return parents; + }, { + request: { + node: Arg(0, "domnode"), + sameDocument: Option(1) + }, + response: { + nodes: RetVal("array:domnode") + }, + }), + + parentNode: function(node) { + let walker = documentWalker(node.rawNode); + let parent = walker.parentNode(); + if (parent) { + return this._ref(parent); + } + return null; + }, + + /** + * Mark a node as 'retained'. + * + * A retained node is not released when `releaseNode` is called on its + * parent, or when a parent is released with the `cleanup` option to + * `getMutations`. + * + * When a retained node's parent is released, a retained mode is added to + * the walker's "retained orphans" list. + * + * Retained nodes can be deleted by providing the `force` option to + * `releaseNode`. They will also be released when their document + * has been destroyed. + * + * Retaining a node makes no promise about its children; They can + * still be removed by normal means. + */ + retainNode: method(function(node) { + node.retained = true; + }, { + request: { node: Arg(0, "domnode") }, + response: {} + }), + + /** + * Remove the 'retained' mark from a node. If the node was a + * retained orphan, release it. + */ + unretainNode: method(function(node) { + node.retained = false; + if (this._retainedOrphans.has(node)) { + this._retainedOrphans.delete(node); + this.releaseNode(node); + } + }, { + request: { node: Arg(0, "domnode") }, + response: {}, + }), + + /** + * Release actors for a node and all child nodes. + */ + releaseNode: method(function(node, options={}) { + if (node.retained && !options.force) { + this._retainedOrphans.add(node); + return; + } + + if (node.retained) { + // Forcing a retained node to go away. + this._retainedOrphans.delete(node); + } + + let walker = documentWalker(node.rawNode); + + let child = walker.firstChild(); + while (child) { + let childActor = this._refMap.get(child); + if (childActor) { + this.releaseNode(childActor, options); + } + child = walker.nextSibling(); + } + + node.destroy(); + }, { + request: { + node: Arg(0, "domnode"), + force: Option(1) + } + }), + + /** + * Add any nodes between `node` and the walker's root node that have not + * yet been seen by the client. + */ + ensurePathToRoot: function(node, newParents=new Set()) { + if (!node) { + return newParents; + } + let walker = documentWalker(node.rawNode); + let cur; + while ((cur = walker.parentNode())) { + let parent = this._refMap.get(cur); + if (!parent) { + // This parent didn't exist, so hasn't been seen by the client yet. + newParents.add(this._ref(cur)); + } else { + // This parent did exist, so the client knows about it. + return newParents; + } + } + return newParents; + }, + + /** + * Return children of the given node. By default this method will return + * all children of the node, but there are options that can restrict this + * to a more manageable subset. + * + * @param NodeActor node + * The node whose children you're curious about. + * @param object options + * Named options: + * `maxNodes`: The set of nodes returned by the method will be no longer + * than maxNodes. + * `start`: If a node is specified, the list of nodes will start + * with the given child. Mutally exclusive with `center`. + * `center`: If a node is specified, the given node will be as centered + * as possible in the list, given how close to the ends of the child + * list it is. Mutually exclusive with `start`. + * `whatToShow`: A bitmask of node types that should be included. See + * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter. + * + * @returns an object with three items: + * hasFirst: true if the first child of the node is included in the list. + * hasLast: true if the last child of the node is included in the list. + * nodes: Child nodes returned by the request. + */ + children: method(function(node, options={}) { + if (options.center && options.start) { + throw Error("Can't specify both 'center' and 'start' options."); + } + let maxNodes = options.maxNodes || -1; + if (maxNodes == -1) { + maxNodes = Number.MAX_VALUE; + } + + // We're going to create a few document walkers with the same filter, + // make it easier. + let filteredWalker = function(node) { + return documentWalker(node, options.whatToShow); + } + + // Need to know the first and last child. + let rawNode = node.rawNode; + let firstChild = filteredWalker(rawNode).firstChild(); + let lastChild = filteredWalker(rawNode).lastChild(); + + if (!firstChild) { + // No children, we're done. + return { hasFirst: true, hasLast: true, nodes: [] }; + } + + let start; + if (options.center) { + start = options.center.rawNode; + } else if (options.start) { + start = options.start.rawNode; + } else { + start = firstChild; + } + + let nodes = []; + + // Start by reading backward from the starting point if we're centering... + let backwardWalker = filteredWalker(start); + if (start != firstChild && options.center) { + backwardWalker.previousSibling(); + let backwardCount = Math.floor(maxNodes / 2); + let backwardNodes = this._readBackward(backwardWalker, backwardCount); + nodes = backwardNodes; + } + + // Then read forward by any slack left in the max children... + let forwardWalker = filteredWalker(start); + let forwardCount = maxNodes - nodes.length; + nodes = nodes.concat(this._readForward(forwardWalker, forwardCount)); + + // If there's any room left, it means we've run all the way to the end. + // If we're centering, check if there are more items to read at the front. + let remaining = maxNodes - nodes.length; + if (options.center && remaining > 0 && nodes[0].rawNode != firstChild) { + let firstNodes = this._readBackward(backwardWalker, remaining); + + // Then put it all back together. + nodes = firstNodes.concat(nodes); + } + + return { + hasFirst: nodes[0].rawNode == firstChild, + hasLast: nodes[nodes.length - 1].rawNode == lastChild, + nodes: nodes + }; + }, nodeArrayMethod), + + /** + * Return siblings of the given node. By default this method will return + * all siblings of the node, but there are options that can restrict this + * to a more manageable subset. + * + * If `start` or `center` are not specified, this method will center on the + * node whose siblings are requested. + * + * @param NodeActor node + * The node whose children you're curious about. + * @param object options + * Named options: + * `maxNodes`: The set of nodes returned by the method will be no longer + * than maxNodes. + * `start`: If a node is specified, the list of nodes will start + * with the given child. Mutally exclusive with `center`. + * `center`: If a node is specified, the given node will be as centered + * as possible in the list, given how close to the ends of the child + * list it is. Mutually exclusive with `start`. + * `whatToShow`: A bitmask of node types that should be included. See + * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter. + * + * @returns an object with three items: + * hasFirst: true if the first child of the node is included in the list. + * hasLast: true if the last child of the node is included in the list. + * nodes: Child nodes returned by the request. + */ + siblings: method(function(node, options={}) { + let parentNode = documentWalker(node.rawNode).parentNode(); + if (!parentNode) { + return { + hasFirst: true, + hasLast: true, + nodes: [node] + }; + } + + if (!(options.start || options.center)) { + options.center = node; + } + + return this.children(this._ref(parentNode), options); + }, nodeArrayMethod), + + /** + * Get the next sibling of a given node. Getting nodes one at a time + * might be inefficient, be careful. + * + * @param object options + * Named options: + * `whatToShow`: A bitmask of node types that should be included. See + * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter. + */ + nextSibling: method(function(node, options={}) { + let walker = documentWalker(node.rawNode, options.whatToShow || Ci.nsIDOMNodeFilter.SHOW_ALL); + let sibling = walker.nextSibling(); + return sibling ? this._ref(sibling) : null; + }, traversalMethod), + + /** + * Get the previous sibling of a given node. Getting nodes one at a time + * might be inefficient, be careful. + * + * @param object options + * Named options: + * `whatToShow`: A bitmask of node types that should be included. See + * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter. + */ + previousSibling: method(function(node, options={}) { + let walker = documentWalker(node.rawNode, options.whatToShow || Ci.nsIDOMNodeFilter.SHOW_ALL); + let sibling = walker.previousSibling(); + return sibling ? this._ref(sibling) : null; + }, traversalMethod), + + /** + * Helper function for the `children` method: Read forward in the sibling + * list into an array with `count` items, including the current node. + */ + _readForward: function(walker, count) + { + let ret = []; + let node = walker.currentNode; + do { + ret.push(this._ref(node)); + node = walker.nextSibling(); + } while (node && --count); + return ret; + }, + + /** + * Helper function for the `children` method: Read backward in the sibling + * list into an array with `count` items, including the current node. + */ + _readBackward: function(walker, count) + { + let ret = []; + let node = walker.currentNode; + do { + ret.push(this._ref(node)); + node = walker.previousSibling(); + } while(node && --count); + ret.reverse(); + return ret; + }, + + /** + * Return the first node in the document that matches the given selector. + * See https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelector + * + * @param NodeActor baseNode + * @param string selector + */ + querySelector: method(function(baseNode, selector) { + let node = baseNode.rawNode.querySelector(selector); + + if (!node) { + return { + } + }; + + let node = this._ref(node); + let newParents = this.ensurePathToRoot(node); + return { + node: node, + newNodes: [parent for (parent of newParents)] + } + }, { + request: { + node: Arg(0, "domnode"), + selector: Arg(1) + }, + response: RetVal("disconnectedNode") + }), + + /** + * Return a NodeListActor with all nodes that match the given selector. + * See https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelectorAll + * + * @param NodeActor baseNode + * @param string selector + */ + querySelectorAll: method(function(baseNode, selector) { + return new NodeListActor(this, baseNode.rawNode.querySelectorAll(selector)); + }, { + request: { + node: Arg(0, "domnode"), + selector: Arg(1) + }, + response: { + list: RetVal("domnodelist") + } + }), + + /** + * Add a pseudo-class lock to a node. + * + * @param NodeActor node + * @param string pseudo + * A pseudoclass: ':hover', ':active', ':focus' + * @param options + * Options object: + * `parents`: True if the pseudo-class should be added + * to parent nodes. + * + * @returns An empty packet. A "pseudoClassLock" mutation will + * be queued for any changed nodes. + */ + addPseudoClassLock: method(function(node, pseudo, options={}) { + this._addPseudoClassLock(node, pseudo); + + if (!options.parents) { + return; + } + + let walker = documentWalker(node.rawNode); + let cur; + while ((cur = walker.parentNode())) { + let curNode = this._ref(cur); + this._addPseudoClassLock(curNode, pseudo); + } + }, { + request: { + node: Arg(0, "domnode"), + pseudoClass: Arg(1), + parents: Option(2) + }, + response: {} + }), + + _queuePseudoClassMutation: function(node) { + this.queueMutation({ + target: node.actorID, + type: "pseudoClassLock", + pseudoClassLocks: node.writePseudoClassLocks() + }); + }, + + _addPseudoClassLock: function(node, pseudo) { + if (node.rawNode.nodeType !== Ci.nsIDOMNode.ELEMENT_NODE) { + return false; + } + DOMUtils.addPseudoClassLock(node.rawNode, pseudo); + this._activePseudoClassLocks.add(node); + this._queuePseudoClassMutation(node); + return true; + }, + + /** + * Remove a pseudo-class lock from a node. + * + * @param NodeActor node + * @param string pseudo + * A pseudoclass: ':hover', ':active', ':focus' + * @param options + * Options object: + * `parents`: True if the pseudo-class should be removed + * from parent nodes. + * + * @returns An empty response. "pseudoClassLock" mutations + * will be emitted for any changed nodes. + */ + removePseudoClassLock: method(function(node, pseudo, options={}) { + this._removePseudoClassLock(node, pseudo); + + if (!options.parents) { + return; + } + + let walker = documentWalker(node.rawNode); + let cur; + while ((cur = walker.parentNode())) { + let curNode = this._ref(cur); + this._removePseudoClassLock(curNode, pseudo); + } + }, { + request: { + node: Arg(0, "domnode"), + pseudoClass: Arg(1), + parents: Option(2) + }, + response: {} + }), + + _removePseudoClassLock: function(node, pseudo) { + if (node.rawNode.nodeType != Ci.nsIDOMNode.ELEMENT_NODE) { + return false; + } + DOMUtils.removePseudoClassLock(node.rawNode, pseudo); + if (!node.writePseudoClassLocks()) { + this._activePseudoClassLocks.delete(node); + } + this._queuePseudoClassMutation(node); + return true; + }, + + /** + * Clear all the pseudo-classes on a given node + * or all nodes. + */ + clearPseudoClassLocks: method(function(node) { + if (node) { + DOMUtils.clearPseudoClassLocks(node.rawNode); + this._activePseudoClassLocks.delete(node); + this._queuePseudoClassMutation(node); + } else { + for (let locked of this._activePseudoClassLocks) { + DOMUtils.clearPseudoClassLocks(locked.rawNode); + this._activePseudoClassLocks.delete(locked); + this._queuePseudoClassMutation(locked); + } + } + }, { + request: { + node: Arg(0, "domnode", { optional: true }), + }, + response: {} + }), + + /** + * Get a node's innerHTML property. + */ + innerHTML: method(function(node) { + return LongStringActor(this.conn, node.rawNode.innerHTML); + }, { + request: { + node: Arg(0, "domnode") + }, + response: { + value: RetVal("longstring") + } + }), + + /** + * Get a node's outerHTML property. + */ + outerHTML: method(function(node) { + return LongStringActor(this.conn, node.rawNode.outerHTML); + }, { + request: { + node: Arg(0, "domnode") + }, + response: { + value: RetVal("longstring") + } + }), + + /** + * Get any pending mutation records. Must be called by the client after + * the `new-mutations` notification is received. Returns an array of + * mutation records. + * + * Mutation records have a basic structure: + * + * { + * type: attributes|characterData|childList, + * target: , + * } + * + * And additional attributes based on the mutation type: + * + * `attributes` type: + * attributeName: - the attribute that changed + * attributeNamespace: - the attribute's namespace URI, if any. + * newValue: - The new value of the attribute, if any. + * + * `characterData` type: + * newValue: - the new shortValue for the node + * [incompleteValue: true] - True if the shortValue was truncated. + * + * `childList` type is returned when the set of children for a node + * has changed. Includes extra data, which can be used by the client to + * maintain its ownership subtree. + * + * added: array of - The list of actors *previously + * seen by the client* that were added to the target node. + * removed: array of The list of actors *previously + * seen by the client* that were removed from the target node. + * + * Actors that are included in a MutationRecord's `removed` but + * not in an `added` have been removed from the client's ownership + * tree (either by being moved under a node the client has seen yet + * or by being removed from the tree entirely), and is considered + * 'orphaned'. + * + * Keep in mind that if a node that the client hasn't seen is moved + * into or out of the target node, it will not be included in the + * removedNodes and addedNodes list, so if the client is interested + * in the new set of children it needs to issue a `children` request. + */ + getMutations: method(function(options={}) { + let pending = this._pendingMutations || []; + this._pendingMutations = []; + + if (options.cleanup) { + for (let node of this._orphaned) { + // Release the orphaned node. Nodes or children that have been + // retained will be moved to this._retainedOrphans. + this.releaseNode(node); + } + this._orphaned = new Set(); + } + + return pending; + }, { + request: { + cleanup: Option(0) + }, + response: { + mutations: RetVal("array:dommutation") + } + }), + + queueMutation: function(mutation) { + if (!this.actorID) { + // We've been destroyed, don't bother queueing this mutation. + return; + } + // We only send the `new-mutations` notification once, until the client + // fetches mutations with the `getMutations` packet. + let needEvent = this._pendingMutations.length === 0; + + this._pendingMutations.push(mutation); + + if (needEvent) { + events.emit(this, "new-mutations"); + } + }, + + /** + * Handles mutations from the DOM mutation observer API. + * + * @param array[MutationRecord] mutations + * See https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationRecord + */ + onMutations: function(mutations) { + for (let change of mutations) { + let targetActor = this._refMap.get(change.target); + if (!targetActor) { + continue; + } + let targetNode = change.target; + let mutation = { + type: change.type, + target: targetActor.actorID, + } + + if (mutation.type === "attributes") { + mutation.attributeName = change.attributeName; + mutation.attributeNamespace = change.attributeNamespace || undefined; + mutation.newValue = targetNode.getAttribute(mutation.attributeName); + } else if (mutation.type === "characterData") { + if (targetNode.nodeValue.length > gValueSummaryLength) { + mutation.newValue = targetNode.nodeValue.substring(0, gValueSummaryLength); + mutation.incompleteValue = true; + } else { + mutation.newValue = targetNode.nodeValue; + } + } else if (mutation.type === "childList") { + // Get the list of removed and added actors that the client has seen + // so that it can keep its ownership tree up to date. + let removedActors = []; + let addedActors = []; + for (let removed of change.removedNodes) { + let removedActor = this._refMap.get(removed); + if (!removedActor) { + // If the client never encountered this actor we don't need to + // mention that it was removed. + continue; + } + // While removed from the tree, nodes are saved as orphaned. + this._orphaned.add(removedActor); + removedActors.push(removedActor.actorID); + } + for (let added of change.addedNodes) { + let addedActor = this._refMap.get(added); + if (!addedActor) { + // If the client never encounted this actor we don't need to tell + // it about its addition for ownership tree purposes - if the + // client wants to see the new nodes it can ask for children. + continue; + } + // The actor is reconnected to the ownership tree, unorphan + // it and let the client know so that its ownership tree is up + // to date. + this._orphaned.delete(addedActor); + addedActors.push(addedActor.actorID); + } + mutation.numChildren = change.target.childNodes.length; + mutation.removed = removedActors; + mutation.added = addedActors; + } + this.queueMutation(mutation); + } + }, + + onFrameLoad: function(window) { + let frame = window.frameElement; + let frameActor = this._refMap.get(frame); + if (!frameActor) { + return; + } + + this.queueMutation({ + type: "frameLoad", + target: frameActor.actorID, + }); + + // Send a childList mutation on the frame. + this.queueMutation({ + type: "childList", + target: frameActor.actorID, + added: [], + removed: [] + }) + }, + + // Returns true if domNode is in window or a subframe. + _childOfWindow: function(window, domNode) { + let win = nodeDocument(domNode).defaultView; + while (win) { + if (win === window) { + return true; + } + win = win.frameElement; + } + return false; + }, + + onFrameUnload: function(window) { + // Any retained orphans that belong to this document + // or its children need to be released, and a mutation sent + // to notify of that. + let releasedOrphans = []; + + for (let retained of this._retainedOrphans) { + if (Cu.isDeadWrapper(retained.rawNode) || + this._childOfWindow(window, retained.rawNode)) { + this._retainedOrphans.delete(retained); + releasedOrphans.push(retained.actorID); + this.releaseNode(retained, { force: true }); + } + } + + if (releasedOrphans.length > 0) { + this.queueMutation({ + target: this.rootNode.actorID, + type: "unretained", + nodes: releasedOrphans + }); + } + + let doc = window.document; + let documentActor = this._refMap.get(doc); + if (!documentActor) { + return; + } + + this.queueMutation({ + type: "documentUnload", + target: documentActor.actorID + }); + + let walker = documentWalker(doc); + let parentNode = walker.parentNode(); + if (parentNode) { + // Send a childList mutation on the frame so that clients know + // they should reread the children list. + this.queueMutation({ + type: "childList", + target: this._refMap.get(parentNode).actorID, + added: [], + removed: [] + }); + } + + // Need to force a release of this node, because those nodes can't + // be accessed anymore. + this.releaseNode(documentActor, { force: true }); + } +}); + +/** + * Client side of the DOM walker. + */ +var WalkerFront = exports.WalkerFront = protocol.FrontClass(WalkerActor, { + // Set to true if cleanup should be requested after every mutation list. + autoCleanup: true, + + initialize: function(client, form) { + protocol.Front.prototype.initialize.call(this, client, form); + this._orphaned = new Set(); + this._retainedOrphans = new Set(); + }, + + destroy: function() { + protocol.Front.prototype.destroy.call(this); + }, + + // Update the object given a form representation off the wire. + form: function(json) { + this.actorID = json.actorID; + this.rootNode = types.getType("domnode").read(json.root, this); + }, + + /** + * When reading an actor form off the wire, we want to hook it up to its + * parent front. The protocol guarantees that the parent will be seen + * by the client in either a previous or the current request. + * So if we've already seen this parent return it, otherwise create + * a bare-bones stand-in node. The stand-in node will be updated + * with a real form by the end of the deserialization. + */ + ensureParentFront: function(id) { + let front = this.get(id); + if (front) { + return front; + } + + return types.getType("domnode").read({ actor: id }, this, "standin"); + }, + + /** + * See the documentation for WalkerActor.prototype.retainNode for + * information on retained nodes. + * + * From the client's perspective, `retainNode` can fail if the node in + * question is removed from the ownership tree before the `retainNode` + * request reaches the server. This can only happen if the client has + * asked the server to release nodes but hasn't gotten a response + * yet: Either a `releaseNode` request or a `getMutations` with `cleanup` + * set is outstanding. + * + * If either of those requests is outstanding AND releases the retained + * node, this request will fail with noSuchActor, but the ownership tree + * will stay in a consistent state. + * + * Because the protocol guarantees that requests will be processed and + * responses received in the order they were sent, we get the right + * semantics by setting our local retained flag on the node only AFTER + * a SUCCESSFUL retainNode call. + */ + retainNode: protocol.custom(function(node) { + return this._retainNode(node).then(() => { + node.retained = true; + }); + }, { + impl: "_retainNode", + }), + + unretainNode: protocol.custom(function(node) { + return this._unretainNode(node).then(() => { + node.retained = false; + if (this._retainedOrphans.has(node)) { + this._retainedOrphans.delete(node); + this._releaseFront(node); + } + }); + }, { + impl: "_unretainNode" + }), + + releaseNode: protocol.custom(function(node, options={}) { + // NodeFront.destroy will destroy children in the ownership tree too, + // mimicking what the server will do here. + let actorID = node.actorID; + this._releaseFront(node, !!options.force); + return this._releaseNode({ actorID: actorID }); + }, { + impl: "_releaseNode" + }), + + querySelector: protocol.custom(function(queryNode, selector) { + return this._querySelector(queryNode, selector).then(response => { + return response.node; + }); + }, { + impl: "_querySelector" + }), + + _releaseFront: function(node, force) { + if (node.retained && !force) { + node.reparent(null); + this._retainedOrphans.add(node); + return; + } + + if (node.retained) { + // Forcing a removal. + this._retainedOrphans.delete(node); + } + + // Release any children + for (let child of node.treeChildren()) { + this._releaseFront(child, force); + } + + // All children will have been removed from the node by this point. + node.reparent(null); + node.destroy(); + }, + + /** + * Get any unprocessed mutation records and process them. + */ + getMutations: protocol.custom(function(options={}) { + return this._getMutations(options).then(mutations => { + let emitMutations = []; + for (let change of mutations) { + // The target is only an actorID, get the associated front. + let targetID = change.target; + let targetFront = this.get(targetID); + if (!targetFront) { + console.trace("Got a mutation for an unexpected actor: " + targetID + ", please file a bug on bugzilla.mozilla.org!"); + continue; + } + + let emittedMutation = object.merge(change, { target: targetFront }); + + if (change.type === "childList") { + // Update the ownership tree according to the mutation record. + let addedFronts = []; + let removedFronts = []; + for (let removed of change.removed) { + let removedFront = this.get(removed); + if (!removedFront) { + console.error("Got a removal of an actor we didn't know about: " + removed); + continue; + } + // Remove from the ownership tree + removedFront.reparent(null); + + // This node is orphaned unless we get it in the 'added' list + // eventually. + this._orphaned.add(removedFront); + removedFronts.push(removedFront); + } + for (let added of change.added) { + let addedFront = this.get(added); + if (!addedFront) { + console.error("Got an addition of an actor we didn't know about: " + added); + continue; + } + addedFront.reparent(targetFront) + + // The actor is reconnected to the ownership tree, unorphan + // it. + this._orphaned.delete(addedFront); + addedFronts.push(addedFront); + } + // Before passing to users, replace the added and removed actor + // ids with front in the mutation record. + emittedMutation.added = addedFronts; + emittedMutation.removed = removedFronts; + targetFront._form.numChildren = change.numChildren; + } else if (change.type === "frameLoad") { + // Nothing we need to do here, except verify that we don't have any + // document children, because we should have gotten a documentUnload + // first. + for (let child of targetFront.treeChildren()) { + if (child.nodeType === Ci.nsIDOMNode.DOCUMENT_NODE) { + console.trace("Got an unexpected frameLoad in the inspector, please file a bug on bugzilla.mozilla.org!"); + } + } + } else if (change.type === "documentUnload") { + // We try to give fronts instead of actorIDs, but these fronts need + // to be destroyed now. + emittedMutation.target = targetFront.actorID; + emittedMutation.targetParent = targetFront.parentNode(); + + // Release the document node and all of its children, even retained. + this._releaseFront(targetFront, true); + } else if (change.type === "unretained") { + // Retained orphans were force-released without the intervention of + // client (probably a navigated frame). + for (let released of change.nodes) { + let releasedFront = this.get(released); + this._retainedOrphans.delete(released); + this._releaseFront(releasedFront, true); + } + } else { + targetFront.updateMutation(change); + } + + emitMutations.push(emittedMutation); + } + + if (options.cleanup) { + for (let node of this._orphaned) { + // This will move retained nodes to this._retainedOrphans. + this._releaseFront(node); + } + this._orphaned = new Set(); + } + + events.emit(this, "mutations", emitMutations); + }); + }, { + impl: "_getMutations" + }), + + /** + * Handle the `new-mutations` notification by fetching the + * available mutation records. + */ + onMutations: protocol.preEvent("new-mutations", function() { + // Fetch and process the mutations. + this.getMutations({cleanup: this.autoCleanup}).then(null, console.error); + }), + + isLocal: function() { + return !!this.conn._transport._serverConnection; + }, + + // XXX hack during transition to remote inspector: get a proper NodeFront + // for a given local node. Only works locally. + frontForRawNode: function(rawNode){ + if (!this.isLocal()) { + console.warn("Tried to use frontForRawNode on a remote connection."); + return null; + } + let walkerActor = this.conn._transport._serverConnection.getActor(this.actorID); + if (!walkerActor) { + throw Error("Could not find client side for actor " + this.actorID); + } + let nodeActor = walkerActor._ref(rawNode); + + // Pass the node through a read/write pair to create the client side actor. + let nodeType = types.getType("domnode"); + let returnNode = nodeType.read(nodeType.write(nodeActor, walkerActor), this); + let top = returnNode; + let extras = walkerActor.parents(nodeActor); + for (let extraActor of extras) { + top = nodeType.read(nodeType.write(extraActor, walkerActor), this); + } + + if (top !== this.rootNode) { + // Imported an already-orphaned node. + this._orphaned.add(top); + walkerActor._orphaned.add(this.conn._transport._serverConnection.getActor(top.actorID)); + } + return returnNode; + } +}); + +/** + * Convenience API for building a list of attribute modifications + * for the `modifyAttributes` request. + */ +var AttributeModificationList = Class({ + initialize: function(node) { + this.node = node; + this.modifications = []; + }, + + apply: function() { + let ret = this.node.modifyAttributes(this.modifications); + return ret; + }, + + destroy: function() { + this.node = null; + this.modification = null; + }, + + setAttributeNS: function(ns, name, value) { + this.modifications.push({ + attributeNamespace: ns, + attributeName: name, + newValue: value + }); + }, + + setAttribute: function(name, value) { + this.setAttributeNS(undefined, name, value); + }, + + removeAttributeNS: function(ns, name) { + this.setAttributeNS(ns, name, undefined); + }, + + removeAttribute: function(name) { + this.setAttributeNS(undefined, name, undefined); + } +}) + +/** + * Server side of the inspector actor, which is used to create + * inspector-related actors, including the walker. + */ +var InspectorActor = protocol.ActorClass({ + typeName: "inspector", + initialize: function(conn, tabActor) { + protocol.Actor.prototype.initialize.call(this, conn); + this.tabActor = tabActor; + }, + + get window() { + let tabActor = this.tabActor; + if (tabActor.browser instanceof Ci.nsIDOMWindow) { + return tabActor.browser; + } else if (tabActor.browser instanceof Ci.nsIDOMElement) { + return tabActor.browser.contentWindow; + } + return null; + }, + + getWalker: method(function(options={}) { + let deferred = promise.defer(); + + let window = this.window; + + var domReady = () => { + let tabActor = this.tabActor; + window.removeEventListener("DOMContentLoaded", domReady, true); + deferred.resolve(WalkerActor(this.conn, window.document, tabActor._tabbrowser, options)); + }; + + if (window.document.readyState === "loading") { + window.addEventListener("DOMContentLoaded", domReady, true); + } else { + domReady(); + } + + return deferred.promise; + }, { + request: {}, + response: { + walker: RetVal("domwalker") + } + }) +}); + +/** + * Client side of the inspector actor, which is used to create + * inspector-related actors, including the walker. + */ +var InspectorFront = exports.InspectorFront = protocol.FrontClass(InspectorActor, { + initialize: function(client, tabForm) { + protocol.Front.prototype.initialize.call(this, client); + this.actorID = tabForm.inspectorActor; + + // XXX: This is the first actor type in its hierarchy to use the protocol + // library, so we're going to self-own on the client side for now. + client.addActorPool(this); + this.manage(this); + } +}); + +function documentWalker(node, whatToShow=Ci.nsIDOMNodeFilter.SHOW_ALL) { + return new DocumentWalker(node, whatToShow, whitespaceTextFilter, false); +} + +// Exported for test purposes. +exports._documentWalker = documentWalker; + +function nodeDocument(node) { + return node.ownerDocument || (node.nodeType == Ci.nsIDOMNode.DOCUMENT_NODE ? node : null); +} + +/** + * Similar to a TreeWalker, except will dig in to iframes and it doesn't + * implement the good methods like previousNode and nextNode. + * + * See TreeWalker documentation for explanations of the methods. + */ +function DocumentWalker(aNode, aShow, aFilter, aExpandEntityReferences) +{ + let doc = nodeDocument(aNode); + this.walker = doc.createTreeWalker(nodeDocument(aNode), + aShow, aFilter, aExpandEntityReferences); + this.walker.currentNode = aNode; + this.filter = aFilter; +} + +DocumentWalker.prototype = { + get node() this.walker.node, + get whatToShow() this.walker.whatToShow, + get expandEntityReferences() this.walker.expandEntityReferences, + get currentNode() this.walker.currentNode, + set currentNode(aVal) this.walker.currentNode = aVal, + + /** + * Called when the new node is in a different document than + * the current node, creates a new treewalker for the document we've + * run in to. + */ + _reparentWalker: function DW_reparentWalker(aNewNode) { + if (!aNewNode) { + return null; + } + let doc = nodeDocument(aNewNode); + let walker = doc.createTreeWalker(doc, + this.whatToShow, this.filter, this.expandEntityReferences); + walker.currentNode = aNewNode; + this.walker = walker; + return aNewNode; + }, + + parentNode: function DW_parentNode() + { + let currentNode = this.walker.currentNode; + let parentNode = this.walker.parentNode(); + + if (!parentNode) { + if (currentNode && currentNode.nodeType == Ci.nsIDOMNode.DOCUMENT_NODE + && currentNode.defaultView) { + let embeddingFrame = currentNode.defaultView.frameElement; + if (embeddingFrame) { + return this._reparentWalker(embeddingFrame); + } + } + return null; + } + + return parentNode; + }, + + firstChild: function DW_firstChild() + { + let node = this.walker.currentNode; + if (!node) + return null; + if (node.contentDocument) { + return this._reparentWalker(node.contentDocument); + } else if (node.getSVGDocument) { + return this._reparentWalker(node.getSVGDocument()); + } + return this.walker.firstChild(); + }, + + lastChild: function DW_lastChild() + { + let node = this.walker.currentNode; + if (!node) + return null; + if (node.contentDocument) { + return this._reparentWalker(node.contentDocument); + } else if (node.getSVGDocument) { + return this._reparentWalker(node.getSVGDocument()); + } + return this.walker.lastChild(); + }, + + previousSibling: function DW_previousSibling() this.walker.previousSibling(), + nextSibling: function DW_nextSibling() this.walker.nextSibling() +} + +/** + * A tree walker filter for avoiding empty whitespace text nodes. + */ +function whitespaceTextFilter(aNode) +{ + if (aNode.nodeType == Ci.nsIDOMNode.TEXT_NODE && + !/[^\s]/.exec(aNode.nodeValue)) { + return Ci.nsIDOMNodeFilter.FILTER_SKIP; + } else { + return Ci.nsIDOMNodeFilter.FILTER_ACCEPT; + } +} + +loader.lazyGetter(this, "DOMUtils", function () { + return Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils); +}); diff --git a/scripting/javascript/bindings/js/debugger/actors/profiler.js b/scripting/javascript/bindings/js/debugger/actors/profiler.js new file mode 100644 index 0000000000..bc87f48599 --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/profiler.js @@ -0,0 +1,218 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +var startedProfilers = 0; +var startTime = 0; + +function getCurrentTime() { + return (new Date()).getTime() - startTime; +} + +/** + * Creates a ProfilerActor. ProfilerActor provides remote access to the + * built-in profiler module. + */ +function ProfilerActor(aConnection) +{ + this._profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); + this._started = false; + this._observedEvents = []; +} + +ProfilerActor.prototype = { + actorPrefix: "profiler", + + disconnect: function() { + for (var event of this._observedEvents) { + Services.obs.removeObserver(this, event); + } + + this.stopProfiler(); + this._profiler = null; + }, + + stopProfiler: function() { + // We stop the profiler only after the last client has + // stopped profiling. Otherwise there's a problem where + // we stop the profiler as soon as you close the devtools + // panel in one tab even though there might be other + // profiler instances running in other tabs. + if (!this._started) { + return; + } + this._started = false; + startedProfilers -= 1; + if (startedProfilers <= 0) { + this._profiler.StopProfiler(); + } + }, + + onStartProfiler: function(aRequest) { + this._profiler.StartProfiler(aRequest.entries, aRequest.interval, + aRequest.features, aRequest.features.length); + this._started = true; + startedProfilers += 1; + startTime = (new Date()).getTime(); + return { "msg": "profiler started" } + }, + onStopProfiler: function(aRequest) { + this.stopProfiler(); + return { "msg": "profiler stopped" } + }, + onGetProfileStr: function(aRequest) { + var profileStr = this._profiler.GetProfile(); + return { "profileStr": profileStr } + }, + onGetProfile: function(aRequest) { + var profile = this._profiler.getProfileData(); + return { "profile": profile, "currentTime": getCurrentTime() } + }, + onIsActive: function(aRequest) { + var isActive = this._profiler.IsActive(); + var currentTime = isActive ? getCurrentTime() : null; + return { "isActive": isActive, "currentTime": currentTime } + }, + onGetResponsivenessTimes: function(aRequest) { + var times = this._profiler.GetResponsivenessTimes({}); + return { "responsivenessTimes": times } + }, + onGetFeatures: function(aRequest) { + var features = this._profiler.GetFeatures([]); + return { "features": features } + }, + onGetSharedLibraryInformation: function(aRequest) { + var sharedLibraries = this._profiler.getSharedLibraryInformation(); + return { "sharedLibraryInformation": sharedLibraries } + }, + onRegisterEventNotifications: function(aRequest) { + let registered = []; + for (var event of aRequest.events) { + if (this._observedEvents.indexOf(event) != -1) + continue; + Services.obs.addObserver(this, event, false); + this._observedEvents.push(event); + registered.push(event); + } + return { registered: registered } + }, + onUnregisterEventNotifications: function(aRequest) { + let unregistered = []; + for (var event of aRequest.events) { + let idx = this._observedEvents.indexOf(event); + if (idx == -1) + continue; + Services.obs.removeObserver(this, event); + this._observedEvents.splice(idx, 1); + unregistered.push(event); + } + return { unregistered: unregistered } + }, + observe: makeInfallible(function(aSubject, aTopic, aData) { + /* + * this.conn.send can only transmit acyclic values. However, it is + * idiomatic for wrapped JS objects like aSubject (and possibly aData?) + * to have a 'wrappedJSObject' property pointing to themselves. + * + * this.conn.send also assumes that it can retain the object it is + * passed to be handled on later event ticks; and that it's okay to + * freeze it. Since we don't really know what aSubject and aData are, + * we need to pass this.conn.send a copy of them, not the originals. + * + * We break the cycle and make the copy by JSON.stringifying those + * values with a replacer that omits properties known to introduce + * cycles, and then JSON.parsing the result. This spends processor + * time, but it's simple. + */ + function cycleBreaker(key, value) { + if (key === 'wrappedJSObject') { + return undefined; + } + return value; + } + + /* + * If these values are objects with a non-null 'wrappedJSObject' + * property, use its value. Otherwise, use the value unchanged. + */ + aSubject = (aSubject && aSubject.wrappedJSObject) || aSubject; + aData = (aData && aData.wrappedJSObject) || aData; + + let subj = JSON.parse(JSON.stringify(aSubject, cycleBreaker)); + let data = JSON.parse(JSON.stringify(aData, cycleBreaker)); + + let send = (extra) => { + data = data || {}; + + if (extra) + data.extra = extra; + + this.conn.send({ + from: this.actorID, + type: "eventNotification", + event: aTopic, + subject: subj, + data: data + }); + } + + if (aTopic !== "console-api-profiler") + return void send(); + + // If the event was generated from console.profile or + // console.profileEnd we need to start the profiler + // right away and only then notify our client. Otherwise, + // we'll lose precious samples. + + let name = subj.arguments[0]; + + if (subj.action === "profile") { + let resp = this.onIsActive(); + + if (resp.isActive) { + return void send({ + name: name, + currentTime: resp.currentTime, + action: "profile" + }); + } + + this.onStartProfiler({ + entries: 1000000, + interval: 1, + features: ["js"] + }); + + return void send({ currentTime: 0, action: "profile", name: name }); + } + + if (subj.action === "profileEnd") { + let resp = this.onGetProfile(); + resp.action = "profileEnd"; + resp.name = name; + send(resp); + } + + return undefined; // Otherwise xpcshell tests fail. + }, "ProfilerActor.prototype.observe"), +}; + +/** + * The request types this actor can handle. + */ +ProfilerActor.prototype.requestTypes = { + "startProfiler": ProfilerActor.prototype.onStartProfiler, + "stopProfiler": ProfilerActor.prototype.onStopProfiler, + "getProfileStr": ProfilerActor.prototype.onGetProfileStr, + "getProfile": ProfilerActor.prototype.onGetProfile, + "isActive": ProfilerActor.prototype.onIsActive, + "getResponsivenessTimes": ProfilerActor.prototype.onGetResponsivenessTimes, + "getFeatures": ProfilerActor.prototype.onGetFeatures, + "getSharedLibraryInformation": ProfilerActor.prototype.onGetSharedLibraryInformation, + "registerEventNotifications": ProfilerActor.prototype.onRegisterEventNotifications, + "unregisterEventNotifications": ProfilerActor.prototype.onUnregisterEventNotifications +}; + +DebuggerServer.addGlobalActor(ProfilerActor, "profilerActor"); diff --git a/scripting/javascript/bindings/js/debugger/actors/root.js b/scripting/javascript/bindings/js/debugger/actors/root.js new file mode 100644 index 0000000000..aa0d85342b --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/root.js @@ -0,0 +1,329 @@ +/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* Root actor for the remote debugging protocol. */ + +/** + * Methods shared between RootActor and BrowserTabActor. + */ + +/** + * Populate |this._extraActors| as specified by |aFactories|, reusing whatever + * actors are already there. Add all actors in the final extra actors table to + * |aPool|. + * + * The root actor and the tab actor use this to instantiate actors that other + * parts of the browser have specified with DebuggerServer.addTabActor antd + * DebuggerServer.addGlobalActor. + * + * @param aFactories + * An object whose own property names are the names of properties to add to + * some reply packet (say, a tab actor grip or the "listTabs" response + * form), and whose own property values are actor constructor functions, as + * documented for addTabActor and addGlobalActor. + * + * @param this + * The BrowserRootActor or BrowserTabActor with which the new actors will + * be associated. It should support whatever API the |aFactories| + * constructor functions might be interested in, as it is passed to them. + * For the sake of CommonCreateExtraActors itself, it should have at least + * the following properties: + * + * - _extraActors + * An object whose own property names are factory table (and packet) + * property names, and whose values are no-argument actor constructors, + * of the sort that one can add to an ActorPool. + * + * - conn + * The DebuggerServerConnection in which the new actors will participate. + * + * - actorID + * The actor's name, for use as the new actors' parentID. + */ +function CommonCreateExtraActors(aFactories, aPool) { + // Walk over global actors added by extensions. + for (let name in aFactories) { + let actor = this._extraActors[name]; + if (!actor) { + actor = aFactories[name].bind(null, this.conn, this); + actor.prototype = aFactories[name].prototype; + actor.parentID = this.actorID; + this._extraActors[name] = actor; + } + aPool.addActor(actor); + } +} + +/** + * Append the extra actors in |this._extraActors|, constructed by a prior call + * to CommonCreateExtraActors, to |aObject|. + * + * @param aObject + * The object to which the extra actors should be added, under the + * property names given in the |aFactories| table passed to + * CommonCreateExtraActors. + * + * @param this + * The BrowserRootActor or BrowserTabActor whose |_extraActors| table we + * should use; see above. + */ +function CommonAppendExtraActors(aObject) { + for (let name in this._extraActors) { + let actor = this._extraActors[name]; + aObject[name] = actor.actorID; + } +} + +/** + * Create a remote debugging protocol root actor. + * + * @param aConnection + * The DebuggerServerConnection whose root actor we are constructing. + * + * @param aParameters + * The properties of |aParameters| provide backing objects for the root + * actor's requests; if a given property is omitted from |aParameters|, the + * root actor won't implement the corresponding requests or notifications. + * Supported properties: + * + * - tabList: a live list (see below) of tab actors. If present, the + * new root actor supports the 'listTabs' request, providing the live + * list's elements as its tab actors, and sending 'tabListChanged' + * notifications when the live list's contents change. One actor in + * this list must have a true '.selected' property. + * + * - globalActorFactories: an object |A| describing further actors to + * attach to the 'listTabs' reply. This is the type accumulated by + * DebuggerServer.addGlobalActor. For each own property |P| of |A|, + * the root actor adds a property named |P| to the 'listTabs' + * reply whose value is the name of an actor constructed by + * |A[P]|. + * + * - onShutdown: a function to call when the root actor is disconnected. + * + * Instance properties: + * + * - applicationType: the string the root actor will include as the + * "applicationType" property in the greeting packet. By default, this + * is "browser". + * + * Live lists: + * + * A "live list", as used for the |tabList|, is an object that presents a + * list of actors, and also notifies its clients of changes to the list. A + * live list's interface is two properties: + * + * - iterator: a method that returns an iterator. A for-of loop will call + * this method to obtain an iterator for the loop, so if LL is + * a live list, one can simply write 'for (i of LL) ...'. + * + * - onListChanged: a handler called, with no arguments, when the set of + * values the iterator would produce has changed since the last + * time 'iterator' was called. This may only be set to null or a + * callable value (one for which the typeof operator returns + * 'function'). (Note that the live list will not call the + * onListChanged handler until the list has been iterated over + * once; if nobody's seen the list in the first place, nobody + * should care if its contents have changed!) + * + * When the list changes, the list implementation should ensure that any + * actors yielded in previous iterations whose referents (tabs) still exist + * get yielded again in subsequent iterations. If the underlying referent + * is the same, the same actor should be presented for it. + * + * The root actor registers an 'onListChanged' handler on the appropriate + * list when it may need to send the client 'tabListChanged' notifications, + * and is careful to remove the handler whenever it does not need to send + * such notifications (including when it is disconnected). This means that + * live list implementations can use the state of the handler property (set + * or null) to install and remove observers and event listeners. + * + * Note that, as the only way for the root actor to see the members of the + * live list is to begin an iteration over the list, the live list need not + * actually produce any actors until they are reached in the course of + * iteration: alliterative lazy live lists. + */ +function RootActor(aConnection, aParameters) { + this.conn = aConnection; + this._parameters = aParameters; + this._onTabListChanged = this.onTabListChanged.bind(this); + this._extraActors = {}; +} + +RootActor.prototype = { + constructor: RootActor, + applicationType: "browser", + + /** + * Return a 'hello' packet as specified by the Remote Debugging Protocol. + */ + sayHello: function() { + return { + from: "root", + applicationType: this.applicationType, + /* This is not in the spec, but it's used by tests. */ + testConnectionPrefix: this.conn.prefix, + traits: { + sources: true + } + }; + }, + + /** + * Disconnects the actor from the browser window. + */ + disconnect: function() { + /* Tell the live lists we aren't watching any more. */ + if (this._parameters.tabList) { + this._parameters.tabList.onListChanged = null; + } + if (typeof this._parameters.onShutdown === 'function') { + this._parameters.onShutdown(); + } + this._extraActors = null; + }, + + /* The 'listTabs' request and the 'tabListChanged' notification. */ + + /** + * Handles the listTabs request. The actors will survive until at least + * the next listTabs request. + */ + onListTabs: function() { + + let tabList = this._parameters.tabList; + if (!tabList) { + return { from: "root", error: "noTabs", + message: "This root actor has no browser tabs." }; + } + + /* + * Walk the tab list, accumulating the array of tab actors for the + * reply, and moving all the actors to a new ActorPool. We'll + * replace the old tab actor pool with the one we build here, thus + * retiring any actors that didn't get listed again, and preparing any + * new actors to receive packets. + */ + let newActorPool = new ActorPool(this.conn); + let tabActorList = []; + let selected; + for (let tabActor of tabList) { + if (tabActor.selected) { + selected = tabActorList.length; + } + tabActor.parentID = this.actorID; + newActorPool.addActor(tabActor); + tabActorList.push(tabActor); + } + + /* DebuggerServer.addGlobalActor support: create actors. */ + this._createExtraActors(this._parameters.globalActorFactories, newActorPool); + + /* + * Drop the old actorID -> actor map. Actors that still mattered were + * added to the new map; others will go away. + */ + if (this._tabActorPool) { + this.conn.removeActorPool(this._tabActorPool); + } + this._tabActorPool = newActorPool; + this.conn.addActorPool(this._tabActorPool); + + let reply = { + "from": "root", + "selected": selected || 0, + "tabs": [actor.grip() for (actor of tabActorList)] + }; + + /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ + this._appendExtraActors(reply); + + /* + * Now that we're actually going to report the contents of tabList to + * the client, we're responsible for letting the client know if it + * changes. + */ + tabList.onListChanged = this._onTabListChanged; + + return reply; + }, + + onTabListChanged: function () { + this.conn.send({ from:"root", type:"tabListChanged" }); + /* It's a one-shot notification; no need to watch any more. */ + this._parameters.tabList.onListChanged = null; + }, + + /* This is not in the spec, but it's used by tests. */ + onEcho: (aRequest) => aRequest, + + /* Support for DebuggerServer.addGlobalActor. */ + _createExtraActors: CommonCreateExtraActors, + _appendExtraActors: CommonAppendExtraActors, + + /* ThreadActor hooks. */ + + /** + * Prepare to enter a nested event loop by disabling debuggee events. + */ + preNest: function() { + // Disable events in all open windows. + let e = windowMediator.getEnumerator(null); + while (e.hasMoreElements()) { + let win = e.getNext(); + let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + windowUtils.suppressEventHandling(true); + windowUtils.suspendTimeouts(); + } + }, + + /** + * Prepare to exit a nested event loop by enabling debuggee events. + */ + postNest: function(aNestData) { + // Enable events in all open windows. + let e = windowMediator.getEnumerator(null); + while (e.hasMoreElements()) { + let win = e.getNext(); + let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + windowUtils.resumeTimeouts(); + windowUtils.suppressEventHandling(false); + } + }, + + /* ChromeDebuggerActor hooks. */ + + /** + * Add the specified actor to the default actor pool connection, in order to + * keep it alive as long as the server is. This is used by breakpoints in the + * thread and chrome debugger actors. + * + * @param actor aActor + * The actor object. + */ + addToParentPool: function(aActor) { + this.conn.addActor(aActor); + }, + + /** + * Remove the specified actor from the default actor pool. + * + * @param BreakpointActor aActor + * The actor object. + */ + removeFromParentPool: function(aActor) { + this.conn.removeActor(aActor); + } +} + +RootActor.prototype.requestTypes = { + "listTabs": RootActor.prototype.onListTabs, + "echo": RootActor.prototype.onEcho +}; diff --git a/scripting/javascript/bindings/js/debugger/actors/script.js b/scripting/javascript/bindings/js/debugger/actors/script.js new file mode 100644 index 0000000000..2e65052e29 --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/script.js @@ -0,0 +1,2946 @@ +/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/** + * JSD2 actors. + */ +/** + * Creates a ThreadActor. + * + * ThreadActors manage a JSInspector object and manage execution/inspection + * of debuggees. + * + * @param aHooks object + * An object with preNest and postNest methods for calling when entering + * and exiting a nested event loop, addToParentPool and + * removeFromParentPool methods for handling the lifetime of actors that + * will outlive the thread, like breakpoints. + * @param aGlobal object [optional] + * An optional (for content debugging only) reference to the content + * window. + */ +function ThreadActor(aHooks, aGlobal) +{ + this._state = "detached"; + this._frameActors = []; + this._environmentActors = []; + this._hooks = aHooks; + this.global = aGlobal; + + this.findGlobals = this.globalManager.findGlobals.bind(this); + this.onNewGlobal = this.globalManager.onNewGlobal.bind(this); + this.onNewSource = this.onNewSource.bind(this); + + this._options = { + useSourceMaps: false + }; +} + +/** + * The breakpoint store must be shared across instances of ThreadActor so that + * page reloads don't blow away all of our breakpoints. + */ +ThreadActor._breakpointStore = {}; + +ThreadActor.prototype = { + actorPrefix: "context", + + get state() { return this._state; }, + get attached() this.state == "attached" || + this.state == "running" || + this.state == "paused", + + get _breakpointStore() { return ThreadActor._breakpointStore; }, + + get threadLifetimePool() { + if (!this._threadLifetimePool) { + this._threadLifetimePool = new ActorPool(this.conn); + this.conn.addActorPool(this._threadLifetimePool); + this._threadLifetimePool.objectActors = new WeakMap(); + } + return this._threadLifetimePool; + }, + + get sources() { + if (!this._sources) { + this._sources = new ThreadSources(this, this._options.useSourceMaps, + this._allowSource, this.onNewSource); + } + return this._sources; + }, + + clearDebuggees: function TA_clearDebuggees() { + if (this.dbg) { + this.dbg.removeAllDebuggees(); + } + this.conn.removeActorPool(this._threadLifetimePool || undefined); + this._threadLifetimePool = null; + this._sources = null; + }, + + /** + * Add a debuggee global to the Debugger object. + */ + addDebuggee: function TA_addDebuggee(aGlobal) { + try { + this.dbg.addDebuggee(aGlobal); + } catch (e) { + // Ignore attempts to add the debugger's compartment as a debuggee. + dumpn("Ignoring request to add the debugger's compartment as a debuggee"); + } + }, + + /** + * Initialize the Debugger. + */ + _initDebugger: function TA__initDebugger() { + this.dbg = new Debugger(); + this.dbg.uncaughtExceptionHook = this.uncaughtExceptionHook.bind(this); + this.dbg.onDebuggerStatement = this.onDebuggerStatement.bind(this); + this.dbg.onNewScript = this.onNewScript.bind(this); + this.dbg.onNewGlobalObject = this.globalManager.onNewGlobal.bind(this); + // Keep the debugger disabled until a client attaches. + this.dbg.enabled = this._state != "detached"; + }, + + /** + * Remove a debuggee global from the JSInspector. + */ + removeDebugee: function TA_removeDebuggee(aGlobal) { + try { + this.dbg.removeDebuggee(aGlobal); + } catch(ex) { + // XXX: This debuggee has code currently executing on the stack, + // we need to save this for later. + } + }, + + /** + * Add the provided window and all windows in its frame tree as debuggees. + */ + _addDebuggees: function TA__addDebuggees(aWindow) { + this.addDebuggee(aWindow); + let frames = aWindow.frames; + if (frames) { + for (let i = 0; i < frames.length; i++) { + this._addDebuggees(frames[i]); + } + } + }, + + /** + * An object that will be used by ThreadActors to tailor their behavior + * depending on the debugging context being required (chrome or content). + */ + globalManager: { + findGlobals: function TA_findGlobals() { + this._addDebuggees(this.global); + }, + + /** + * A function that the engine calls when a new global object has been + * created. + * + * @param aGlobal Debugger.Object + * The new global object that was created. + */ + onNewGlobal: function TA_onNewGlobal(aGlobal) { + // Content debugging only cares about new globals in the contant window, + // like iframe children. + if (aGlobal.hostAnnotations && + aGlobal.hostAnnotations.type == "document" && + aGlobal.hostAnnotations.element === this.global) { + this.addDebuggee(aGlobal); + // Notify the client. + this.conn.send({ + from: this.actorID, + type: "newGlobal", + // TODO: after bug 801084 lands see if we need to JSONify this. + hostAnnotations: aGlobal.hostAnnotations + }); + } + } + }, + + disconnect: function TA_disconnect() { + dumpn("in ThreadActor.prototype.disconnect"); + if (this._state == "paused") { + this.onResume(); + } + + this._state = "exited"; + + this.clearDebuggees(); + + if (!this.dbg) { + return; + } + this.dbg.enabled = false; + this.dbg = null; + }, + + /** + * Disconnect the debugger and put the actor in the exited state. + */ + exit: function TA_exit() { + this.disconnect(); + }, + + // Request handlers + onAttach: function TA_onAttach(aRequest) { + if (this.state === "exited") { + return { type: "exited" }; + } + + if (this.state !== "detached") { + return { error: "wrongState" }; + } + + this._state = "attached"; + + update(this._options, aRequest.options || {}); + + if (!this.dbg) { + this._initDebugger(); + } + this.findGlobals(); + this.dbg.enabled = true; + try { + // Put ourselves in the paused state. + let packet = this._paused(); + if (!packet) { + return { error: "notAttached" }; + } + packet.why = { type: "attached" }; + + this._restoreBreakpoints(); + + // Send the response to the attach request now (rather than + // returning it), because we're going to start a nested event loop + // here. + this.conn.send(packet); + + // Start a nested event loop. + this._nest(); + + // We already sent a response to this request, don't send one + // now. + return null; + } catch (e) { + reportError(e); + return { error: "notAttached", message: e.toString() }; + } + }, + + onDetach: function TA_onDetach(aRequest) { + this.disconnect(); + dumpn("ThreadActor.prototype.onDetach: returning 'detached' packet"); + return { + type: "detached" + }; + }, + + onReconfigure: function TA_onReconfigure(aRequest) { + if (this.state == "exited") { + return { error: "wrongState" }; + } + + update(this._options, aRequest.options || {}); + // Clear existing sources, so they can be recreated on next access. + this._sources = null; + + return {}; + }, + + /** + * Pause the debuggee, by entering a nested event loop, and return a 'paused' + * packet to the client. + * + * @param Debugger.Frame aFrame + * The newest debuggee frame in the stack. + * @param object aReason + * An object with a 'type' property containing the reason for the pause. + * @param function onPacket + * Hook to modify the packet before it is sent. Feel free to return a + * promise. + */ + _pauseAndRespond: function TA__pauseAndRespond(aFrame, aReason, + onPacket=function (k) k) { + try { + let packet = this._paused(aFrame); + if (!packet) { + return undefined; + } + packet.why = aReason; + resolve(onPacket(packet)).then(this.conn.send.bind(this.conn)); + _lockVM(aFrame, aFrame.script); + return this._nest(); + } catch(e) { + let msg = "Got an exception during TA__pauseAndRespond: " + e + + ": " + e.stack; + // Cu.reportError(msg); + dumpn(msg); + return undefined; + } + }, + + /** + * Handle a protocol request to resume execution of the debuggee. + */ + onResume: function TA_onResume(aRequest) { + if (this._state !== "paused") { + return { + error: "wrongState", + message: "Can't resume when debuggee isn't paused. Current state is '" + + this._state + "'" + }; + } + + // In case of multiple nested event loops (due to multiple debuggers open in + // different tabs or multiple debugger clients connected to the same tab) + // only allow resumption in a LIFO order. + // if (DebuggerServer.xpcInspector.eventLoopNestLevel > 1) { + // let lastNestRequestor = DebuggerServer.xpcInspector.lastNestRequestor; + // if (lastNestRequestor.connection != this.conn) { + // return { error: "wrongOrder", + // message: "trying to resume in the wrong order.", + // lastPausedUrl: lastNestRequestor.url }; + // } + // } + + if (aRequest && aRequest.forceCompletion) { + // TODO: remove this when Debugger.Frame.prototype.pop is implemented in + // bug 736733. + if (typeof this.frame.pop != "function") { + return { error: "notImplemented", + message: "forced completion is not yet implemented." }; + } + + this.dbg.getNewestFrame().pop(aRequest.completionValue); + let packet = this._resumed(); + // DebuggerServer.xpcInspector.exitNestedEventLoop(); + _unlockVM(); + return { type: "resumeLimit", frameFinished: aRequest.forceCompletion }; + } + + if (aRequest && aRequest.resumeLimit) { + // Bind these methods because some of the hooks are called with 'this' + // set to the current frame. + let pauseAndRespond = (aFrame, onPacket=function (k) k) => { + this._pauseAndRespond(aFrame, { type: "resumeLimit" }, onPacket); + }; + let createValueGrip = this.createValueGrip.bind(this); + + let startFrame = this.youngestFrame; + let startLine; + if (this.youngestFrame.script) { + let offset = this.youngestFrame.offset; + startLine = this.youngestFrame.script.getOffsetLine(offset); + } + + // Define the JS hook functions for stepping. + + let onEnterFrame = aFrame => { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + return pauseAndRespond(aFrame); + }; + + let thread = this; + + let onPop = function TA_onPop(aCompletion) { + // onPop is called with 'this' set to the current frame. + if (thread.sources.isBlackBoxed(this.script.url)) { + return undefined; + } + + // Note that we're popping this frame; we need to watch for + // subsequent step events on its caller. + this.reportedPop = true; + + return pauseAndRespond(this, (aPacket) => { + aPacket.why.frameFinished = {}; + if (!aCompletion) { + aPacket.why.frameFinished.terminated = true; + } else if (aCompletion.hasOwnProperty("return")) { + aPacket.why.frameFinished.return = createValueGrip(aCompletion.return); + } else if (aCompletion.hasOwnProperty("yield")) { + aPacket.why.frameFinished.return = createValueGrip(aCompletion.yield); + } else { + aPacket.why.frameFinished.throw = createValueGrip(aCompletion.throw); + } + return aPacket; + }); + }; + + let onStep = function TA_onStep() { + // onStep is called with 'this' set to the current frame. + + if (thread.sources.isBlackBoxed(this.script.url)) { + return undefined; + } + + // If we've changed frame or line, then report that. + if (this !== startFrame || + (this.script && + this.script.getOffsetLine(this.offset) != startLine)) { + return pauseAndRespond(this); + } + + // Otherwise, let execution continue. + return undefined; + }; + + let steppingType = aRequest.resumeLimit.type; + if (["step", "next", "finish"].indexOf(steppingType) == -1) { + return { error: "badParameterType", + message: "Unknown resumeLimit type" }; + } + // Make sure there is still a frame on the stack if we are to continue + // stepping. + let stepFrame = this._getNextStepFrame(startFrame); + if (stepFrame) { + switch (steppingType) { + case "step": + this.dbg.onEnterFrame = onEnterFrame; + // Fall through. + case "next": + stepFrame.onStep = onStep; + stepFrame.onPop = onPop; + break; + case "finish": + stepFrame.onPop = onPop; + } + } + + } + + if (aRequest && aRequest.pauseOnExceptions) { + this.dbg.onExceptionUnwind = this.onExceptionUnwind.bind(this); + } + let packet = this._resumed(); + _unlockVM(); + // DebuggerServer.xpcInspector.exitNestedEventLoop(); + return packet; + }, + + /** + * Helper method that returns the next frame when stepping. + */ + _getNextStepFrame: function TA__getNextStepFrame(aFrame) { + let stepFrame = aFrame.reportedPop ? aFrame.older : aFrame; + if (!stepFrame || !stepFrame.script) { + stepFrame = null; + } + return stepFrame; + }, + + onClientEvaluate: function TA_onClientEvaluate(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Debuggee must be paused to evaluate code." }; + }; + + let frame = this._requestFrame(aRequest.frame); + if (!frame) { + return { error: "unknownFrame", + message: "Evaluation frame not found" }; + } + + if (!frame.environment) { + return { error: "notDebuggee", + message: "cannot access the environment of this frame." }; + }; + + // We'll clobber the youngest frame if the eval causes a pause, so + // save our frame now to be restored after eval returns. + // XXX: or we could just start using dbg.getNewestFrame() now that it + // works as expected. + let youngest = this.youngestFrame; + + // Put ourselves back in the running state and inform the client. + let resumedPacket = this._resumed(); + this.conn.send(resumedPacket); + + // Run the expression. + // XXX: test syntax errors + let completion = frame.eval(aRequest.expression); + + // Put ourselves back in the pause state. + let packet = this._paused(youngest); + packet.why = { type: "clientEvaluated", + frameFinished: this.createProtocolCompletionValue(completion) }; + + // Return back to our previous pause's event loop. + return packet; + }, + + onFrames: function TA_onFrames(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Stack frames are only available while the debuggee is paused."}; + } + + let start = aRequest.start ? aRequest.start : 0; + let count = aRequest.count; + + // Find the starting frame... + let frame = this.youngestFrame; + let i = 0; + while (frame && (i < start)) { + frame = frame.older; + i++; + } + + // Return request.count frames, or all remaining + // frames if count is not defined. + let frames = []; + let promises = []; + for (; frame && (!count || i < (start + count)); i++, frame=frame.older) { + let form = this._createFrameActor(frame).form(); + form.depth = i; + frames.push(form); + + let promise = this.sources.getOriginalLocation(form.where.url, + form.where.line) + .then(function (aOrigLocation) { + form.where = aOrigLocation; + }); + promises.push(promise); + } + + return all(promises).then(function () { + return { frames: frames }; + }); + }, + + onReleaseMany: function TA_onReleaseMany(aRequest) { + if (!aRequest.actors) { + return { error: "missingParameter", + message: "no actors were specified" }; + } + + let res; + for each (let actorID in aRequest.actors) { + let actor = this.threadLifetimePool.get(actorID); + if (!actor) { + if (!res) { + res = { error: "notReleasable", + message: "Only thread-lifetime actors can be released." }; + } + continue; + } + actor.onRelease(); + } + return res ? res : {}; + }, + + /** + * Handle a protocol request to set a breakpoint. + */ + onSetBreakpoint: function TA_onSetBreakpoint(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Breakpoints can only be set while the debuggee is paused."}; + } + + // XXX: `originalColumn` is never used. See bug 827639. + let { url: originalSource, + line: originalLine, + column: originalColumn } = aRequest.location; + + let locationPromise = this.sources.getGeneratedLocation(originalSource, + originalLine) + return locationPromise.then((aLocation) => { + let line = aLocation.line; + if (this.dbg.findScripts({ url: aLocation.url }).length == 0 || + line < 0 || + line == null) { + return { error: "noScript" }; + } + + // Add the breakpoint to the store for later reuse, in case it belongs to a + // script that hasn't appeared yet. + if (!this._breakpointStore[aLocation.url]) { + this._breakpointStore[aLocation.url] = []; + } + let scriptBreakpoints = this._breakpointStore[aLocation.url]; + scriptBreakpoints[line] = { + url: aLocation.url, + line: line, + column: aLocation.column + }; + + let response = this._setBreakpoint(aLocation); + // If the original location of our generated location is different from + // the original location we attempted to set the breakpoint on, we will + // need to know so that we can set actualLocation on the response. + let originalLocation = this.sources.getOriginalLocation(aLocation.url, + aLocation.line); + + return all([response, originalLocation]) + .then(([aResponse, {url, line}]) => { + if (aResponse.actualLocation) { + let actualOrigLocation = this.sources.getOriginalLocation( + aResponse.actualLocation.url, aResponse.actualLocation.line); + return actualOrigLocation.then(function ({ url, line }) { + if (url !== originalSource || line !== originalLine) { + aResponse.actualLocation = { url: url, line: line }; + } + return aResponse; + }); + } + + if (url !== originalSource || line !== originalLine) { + aResponse.actualLocation = { url: url, line: line }; + } + + return aResponse; + }); + }); + }, + + /** + * Set a breakpoint using the jsdbg2 API. If the line on which the breakpoint + * is being set contains no code, then the breakpoint will slide down to the + * next line that has runnable code. In this case the server breakpoint cache + * will be updated, so callers that iterate over the breakpoint cache should + * take that into account. + * + * @param object aLocation + * The location of the breakpoint as specified in the protocol. + */ + _setBreakpoint: function TA__setBreakpoint(aLocation) { + let breakpoints = this._breakpointStore[aLocation.url]; + + // Get or create the breakpoint actor for the given location + let actor; + if (breakpoints[aLocation.line].actor) { + actor = breakpoints[aLocation.line].actor; + } else { + actor = breakpoints[aLocation.line].actor = new BreakpointActor(this, { + url: aLocation.url, + line: aLocation.line + }); + this._hooks.addToParentPool(actor); + } + + // Find all scripts matching the given location + let scripts = this.dbg.findScripts(aLocation); + if (scripts.length == 0) { + return { + error: "noScript", + actor: actor.actorID + }; + } + + /** + * For each script, if the given line has at least one entry point, set + * breakpoint on the bytecode offet for each of them. + */ + let found = false; + for (let script of scripts) { + let offsets = script.getLineOffsets(aLocation.line); + if (offsets.length > 0) { + for (let offset of offsets) { + script.setBreakpoint(offset, actor); + } + actor.addScript(script, this); + found = true; + } + } + if (found) { + return { + actor: actor.actorID + }; + } + + /** + * If we get here, no breakpoint was set. This is because the given line + * has no entry points, for example because it is empty. As a fallback + * strategy, we try to set the breakpoint on the smallest line greater + * than or equal to the given line that as at least one entry point. + */ + + // Find all innermost scripts matching the given location + let scripts = this.dbg.findScripts({ + url: aLocation.url, + line: aLocation.line, + innermost: true + }); + + /** + * For each innermost script, look for the smallest line greater than or + * equal to the given line that has one or more entry points. If found, set + * a breakpoint on the bytecode offset for each of its entry points. + */ + let actualLocation; + let found = false; + for (let script of scripts) { + let offsets = script.getAllOffsets(); + for (let line = aLocation.line; line < offsets.length; ++line) { + if (offsets[line]) { + for (let offset of offsets[line]) { + script.setBreakpoint(offset, actor); + } + actor.addScript(script, this); + if (!actualLocation) { + actualLocation = { + url: aLocation.url, + line: line, + column: 0 + }; + } + found = true; + break; + } + } + } + if (found) { + if (breakpoints[actualLocation.line] && + breakpoints[actualLocation.line].actor) { + /** + * We already have a breakpoint actor for the actual location, so + * actor we created earlier is now redundant. Delete it, update the + * breakpoint store, and return the actor for the actual location. + */ + actor.onDelete(); + delete breakpoints[aLocation.line]; + return { + actor: breakpoints[actualLocation.line].actor.actorID, + actualLocation: actualLocation + }; + } else { + /** + * We don't have a breakpoint actor for the actual location yet. + * Instead or creating a new actor, reuse the actor we created earlier, + * and update the breakpoint store. + */ + actor.location = actualLocation; + breakpoints[actualLocation.line] = breakpoints[aLocation.line]; + delete breakpoints[aLocation.line]; + // WARNING: This overwrites aLocation.line + breakpoints[actualLocation.line].line = actualLocation.line; + return { + actor: actor.actorID, + actualLocation: actualLocation + }; + } + } + + /** + * If we get here, no line matching the given line was found, so just + * epically. + */ + return { + error: "noCodeAtLineColumn", + actor: actor.actorID + }; + }, + + /** + * Get the script and source lists from the debugger. + * + * TODO bug 637572: we should be dealing with sources directly, not inferring + * them through scripts. + */ + _discoverSources: function TA__discoverSources() { + // Only get one script per url. + let scriptsByUrl = {}; + for (let s of this.dbg.findScripts()) { + scriptsByUrl[s.url] = s; + } + + return all([this.sources.sourcesForScript(scriptsByUrl[s]) + for (s of Object.keys(scriptsByUrl))]); + }, + + onSources: function TA_onSources(aRequest) { + return this._discoverSources().then(() => { + return { + sources: [s.form() for (s of this.sources.iter())] + }; + }); + }, + + /** + * Disassociate all breakpoint actors from their scripts and clear the + * breakpoint handlers. This method can be used when the thread actor intends + * to keep the breakpoint store, but needs to clear any actual breakpoints, + * e.g. due to a page navigation. This way the breakpoint actors' script + * caches won't hold on to the Debugger.Script objects leaking memory. + */ + disableAllBreakpoints: function () { + for (let url in this._breakpointStore) { + for (let line in this._breakpointStore[url]) { + let bp = this._breakpointStore[url][line]; + bp.actor.removeScripts(); + } + } + }, + + /** + * Handle a protocol request to pause the debuggee. + */ + onInterrupt: function TA_onInterrupt(aRequest) { + if (this.state == "exited") { + return { type: "exited" }; + } else if (this.state == "paused") { + // TODO: return the actual reason for the existing pause. + return { type: "paused", why: { type: "alreadyPaused" } }; + } else if (this.state != "running") { + return { error: "wrongState", + message: "Received interrupt request in " + this.state + + " state." }; + } + + try { + // Put ourselves in the paused state. + let packet = this._paused(); + if (!packet) { + return { error: "notInterrupted" }; + } + packet.why = { type: "interrupted" }; + + // Send the response to the interrupt request now (rather than + // returning it), because we're going to start a nested event loop + // here. + this.conn.send(packet); + + // Start a nested event loop. + this._nest(); + + // We already sent a response to this request, don't send one + // now. + return null; + } catch (e) { + reportError(e); + return { error: "notInterrupted", message: e.toString() }; + } + }, + + /** + * Return the Debug.Frame for a frame mentioned by the protocol. + */ + _requestFrame: function TA_requestFrame(aFrameID) { + if (!aFrameID) { + return this.youngestFrame; + } + + if (this._framePool.has(aFrameID)) { + return this._framePool.get(aFrameID).frame; + } + + return undefined; + }, + + _paused: function TA_paused(aFrame) { + // We don't handle nested pauses correctly. Don't try - if we're + // paused, just continue running whatever code triggered the pause. + // We don't want to actually have nested pauses (although we + // have nested event loops). If code runs in the debuggee during + // a pause, it should cause the actor to resume (dropping + // pause-lifetime actors etc) and then repause when complete. + + if (this.state === "paused") { + return undefined; + } + + // Clear stepping hooks. + this.dbg.onEnterFrame = undefined; + this.dbg.onExceptionUnwind = undefined; + if (aFrame) { + aFrame.onStep = undefined; + aFrame.onPop = undefined; + } + + this._state = "paused"; + + // Save the pause frame (if any) as the youngest frame for + // stack viewing. + this.youngestFrame = aFrame; + + // Create the actor pool that will hold the pause actor and its + // children. + dbg_assert(!this._pausePool); + this._pausePool = new ActorPool(this.conn); + this.conn.addActorPool(this._pausePool); + + // Give children of the pause pool a quick link back to the + // thread... + this._pausePool.threadActor = this; + + // Create the pause actor itself... + dbg_assert(!this._pauseActor); + this._pauseActor = new PauseActor(this._pausePool); + this._pausePool.addActor(this._pauseActor); + + // Update the list of frames. + let poppedFrames = this._updateFrames(); + + // Send off the paused packet and spin an event loop. + let packet = { from: this.actorID, + type: "paused", + actor: this._pauseActor.actorID }; + if (aFrame) { + packet.frame = this._createFrameActor(aFrame).form(); + } + + if (poppedFrames) { + packet.poppedFrames = poppedFrames; + } + + return packet; + }, + + _nest: function TA_nest() { + if (this._hooks.preNest) { + var nestData = this._hooks.preNest(); + } + + let requestor = Object.create(null); + requestor.url = this._hooks.url; + requestor.connection = this.conn; + // DebuggerServer.xpcInspector.enterNestedEventLoop(requestor); + + dbg_assert(this.state === "running"); + + if (this._hooks.postNest) { + this._hooks.postNest(nestData) + } + + // "continue" resumption value. + return undefined; + }, + + _resumed: function TA_resumed() { + this._state = "running"; + + // Drop the actors in the pause actor pool. + this.conn.removeActorPool(this._pausePool); + + this._pausePool = null; + this._pauseActor = null; + this.youngestFrame = null; + + return { from: this.actorID, type: "resumed" }; + }, + + /** + * Expire frame actors for frames that have been popped. + * + * @returns A list of actor IDs whose frames have been popped. + */ + _updateFrames: function TA_updateFrames() { + let popped = []; + + // Create the actor pool that will hold the still-living frames. + let framePool = new ActorPool(this.conn); + let frameList = []; + + for each (let frameActor in this._frameActors) { + if (frameActor.frame.live) { + framePool.addActor(frameActor); + frameList.push(frameActor); + } else { + popped.push(frameActor.actorID); + } + } + + // Remove the old frame actor pool, this will expire + // any actors that weren't added to the new pool. + if (this._framePool) { + this.conn.removeActorPool(this._framePool); + } + + this._frameActors = frameList; + this._framePool = framePool; + this.conn.addActorPool(framePool); + + return popped; + }, + + _createFrameActor: function TA_createFrameActor(aFrame) { + if (aFrame.actor) { + return aFrame.actor; + } + + let actor = new FrameActor(aFrame, this); + this._frameActors.push(actor); + this._framePool.addActor(actor); + aFrame.actor = actor; + + return actor; + }, + + /** + * Create and return an environment actor that corresponds to the provided + * Debugger.Environment. + * @param Debugger.Environment aEnvironment + * The lexical environment we want to extract. + * @param object aPool + * The pool where the newly-created actor will be placed. + * @return The EnvironmentActor for aEnvironment or undefined for host + * functions or functions scoped to a non-debuggee global. + */ + createEnvironmentActor: + function TA_createEnvironmentActor(aEnvironment, aPool) { + if (!aEnvironment) { + return undefined; + } + + if (aEnvironment.actor) { + return aEnvironment.actor; + } + + let actor = new EnvironmentActor(aEnvironment, this); + this._environmentActors.push(actor); + aPool.addActor(actor); + aEnvironment.actor = actor; + + return actor; + }, + + /** + * Create a grip for the given debuggee value. If the value is an + * object, will create an actor with the given lifetime. + */ + createValueGrip: function TA_createValueGrip(aValue, aPool=false) { + if (!aPool) { + aPool = this._pausePool; + } + let type = typeof(aValue); + + if (type === "string" && this._stringIsLong(aValue)) { + return this.longStringGrip(aValue, aPool); + } + + if (type === "boolean" || type === "string" || type === "number") { + return aValue; + } + + if (aValue === null) { + return { type: "null" }; + } + + if (aValue === undefined) { + return { type: "undefined" } + } + + if (typeof(aValue) === "object") { + return this.objectGrip(aValue, aPool); + } + + dbg_assert(false, "Failed to provide a grip for: " + aValue); + return null; + }, + + /** + * Return a protocol completion value representing the given + * Debugger-provided completion value. + */ + createProtocolCompletionValue: + function TA_createProtocolCompletionValue(aCompletion) { + let protoValue = {}; + if ("return" in aCompletion) { + protoValue.return = this.createValueGrip(aCompletion.return); + } else if ("yield" in aCompletion) { + protoValue.return = this.createValueGrip(aCompletion.yield); + } else if ("throw" in aCompletion) { + protoValue.throw = this.createValueGrip(aCompletion.throw); + } else { + protoValue.terminated = true; + } + return protoValue; + }, + + /** + * Create a grip for the given debuggee object. + * + * @param aValue Debugger.Object + * The debuggee object value. + * @param aPool ActorPool + * The actor pool where the new object actor will be added. + */ + objectGrip: function TA_objectGrip(aValue, aPool) { + if (!aPool.objectActors) { + aPool.objectActors = new WeakMap(); + } + + if (aPool.objectActors.has(aValue)) { + return aPool.objectActors.get(aValue).grip(); + } else if (this.threadLifetimePool.objectActors.has(aValue)) { + return this.threadLifetimePool.objectActors.get(aValue).grip(); + } + + let actor = new PauseScopedObjectActor(aValue, this); + aPool.addActor(actor); + aPool.objectActors.set(aValue, actor); + return actor.grip(); + }, + + /** + * Create a grip for the given debuggee object with a pause lifetime. + * + * @param aValue Debugger.Object + * The debuggee object value. + */ + pauseObjectGrip: function TA_pauseObjectGrip(aValue) { + if (!this._pausePool) { + throw "Object grip requested while not paused."; + } + + return this.objectGrip(aValue, this._pausePool); + }, + + /** + * Extend the lifetime of the provided object actor to thread lifetime. + * + * @param aActor object + * The object actor. + */ + threadObjectGrip: function TA_threadObjectGrip(aActor) { + // We want to reuse the existing actor ID, so we just remove it from the + // current pool's weak map and then let pool.addActor do the rest. + aActor.registeredPool.objectActors.delete(aActor.obj); + this.threadLifetimePool.addActor(aActor); + this.threadLifetimePool.objectActors.set(aActor.obj, aActor); + }, + + /** + * Handle a protocol request to promote multiple pause-lifetime grips to + * thread-lifetime grips. + * + * @param aRequest object + * The protocol request object. + */ + onThreadGrips: function OA_onThreadGrips(aRequest) { + if (this.state != "paused") { + return { error: "wrongState" }; + } + + if (!aRequest.actors) { + return { error: "missingParameter", + message: "no actors were specified" }; + } + + for (let actorID of aRequest.actors) { + let actor = this._pausePool.get(actorID); + if (actor) { + this.threadObjectGrip(actor); + } + } + return {}; + }, + + /** + * Create a grip for the given string. + * + * @param aString String + * The string we are creating a grip for. + * @param aPool ActorPool + * The actor pool where the new actor will be added. + */ + longStringGrip: function TA_longStringGrip(aString, aPool) { + if (!aPool.longStringActors) { + aPool.longStringActors = {}; + } + + if (aPool.longStringActors.hasOwnProperty(aString)) { + return aPool.longStringActors[aString].grip(); + } + + let actor = new LongStringActor(aString, this); + aPool.addActor(actor); + aPool.longStringActors[aString] = actor; + return actor.grip(); + }, + + /** + * Create a long string grip that is scoped to a pause. + * + * @param aString String + * The string we are creating a grip for. + */ + pauseLongStringGrip: function TA_pauseLongStringGrip (aString) { + return this.longStringGrip(aString, this._pausePool); + }, + + /** + * Create a long string grip that is scoped to a thread. + * + * @param aString String + * The string we are creating a grip for. + */ + threadLongStringGrip: function TA_pauseLongStringGrip (aString) { + return this.longStringGrip(aString, this._threadLifetimePool); + }, + + /** + * Returns true if the string is long enough to use a LongStringActor instead + * of passing the value directly over the protocol. + * + * @param aString String + * The string we are checking the length of. + */ + _stringIsLong: function TA__stringIsLong(aString) { + return aString.length >= DebuggerServer.LONG_STRING_LENGTH; + }, + + // JS Debugger API hooks. + + /** + * A function that the engine calls when a call to a debug event hook, + * breakpoint handler, watchpoint handler, or similar function throws some + * exception. + * + * @param aException exception + * The exception that was thrown in the debugger code. + */ + uncaughtExceptionHook: function TA_uncaughtExceptionHook(aException) { + dumpn("Got an exception: " + aException.message + "\n" + aException.stack); + }, + + /** + * A function that the engine calls when a debugger statement has been + * executed in the specified frame. + * + * @param aFrame Debugger.Frame + * The stack frame that contained the debugger statement. + */ + onDebuggerStatement: function TA_onDebuggerStatement(aFrame) { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + return this._pauseAndRespond(aFrame, { type: "debuggerStatement" }); + }, + + /** + * A function that the engine calls when an exception has been thrown and has + * propagated to the specified frame. + * + * @param aFrame Debugger.Frame + * The youngest remaining stack frame. + * @param aValue object + * The exception that was thrown. + */ + onExceptionUnwind: function TA_onExceptionUnwind(aFrame, aValue) { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + try { + let packet = this._paused(aFrame); + if (!packet) { + return undefined; + } + + packet.why = { type: "exception", + exception: this.createValueGrip(aValue) }; + this.conn.send(packet); + return this._nest(); + } catch(e) { + log("Got an exception during TA_onExceptionUnwind: " + e + + ": " + e.stack); + return undefined; + } + }, + + /** + * A function that the engine calls when a new script has been loaded into the + * scope of the specified debuggee global. + * + * @param aScript Debugger.Script + * The source script that has been loaded into a debuggee compartment. + * @param aGlobal Debugger.Object + * A Debugger.Object instance whose referent is the global object. + */ + onNewScript: function TA_onNewScript(aScript, aGlobal) { + this._addScript(aScript); + this.sources.sourcesForScript(aScript); + }, + + onNewSource: function TA_onNewSource(aSource) { + this.conn.send({ + from: this.actorID, + type: "newSource", + source: aSource.form() + }); + }, + + /** + * Check if scripts from the provided source URL are allowed to be stored in + * the cache. + * + * @param aSourceUrl String + * The url of the script's source that will be stored. + * @returns true, if the script can be added, false otherwise. + */ + _allowSource: function TA__allowSource(aSourceUrl) { + // Ignore anything we don't have a URL for (eval scripts, for example). + if (!aSourceUrl) + return false; + // Ignore XBL bindings for content debugging. + if (aSourceUrl.indexOf("chrome://") == 0) { + return false; + } + // Ignore about:* pages for content debugging. + if (aSourceUrl.indexOf("about:") == 0) { + return false; + } + return true; + }, + + /** + * Restore any pre-existing breakpoints to the scripts that we have access to. + */ + _restoreBreakpoints: function TA__restoreBreakpoints() { + for (let s of this.dbg.findScripts()) { + this._addScript(s); + } + }, + + /** + * Add the provided script to the server cache. + * + * @param aScript Debugger.Script + * The source script that will be stored. + * @returns true, if the script was added; false otherwise. + */ + _addScript: function TA__addScript(aScript) { + if (!this._allowSource(aScript.url)) { + return false; + } + + // Set any stored breakpoints. + let existing = this._breakpointStore[aScript.url]; + if (existing) { + let endLine = aScript.startLine + aScript.lineCount - 1; + // Iterate over the lines backwards, so that sliding breakpoints don't + // affect the loop. + for (let line = existing.length - 1; line >= aScript.startLine; line--) { + let bp = existing[line]; + // Only consider breakpoints that are not already associated with + // scripts, and limit search to the line numbers contained in the new + // script. + if (bp && !bp.actor.scripts.length && line <= endLine) { + this._setBreakpoint(bp); + } + } + } + return true; + }, + +}; + +ThreadActor.prototype.requestTypes = { + "attach": ThreadActor.prototype.onAttach, + "detach": ThreadActor.prototype.onDetach, + "reconfigure": ThreadActor.prototype.onReconfigure, + "resume": ThreadActor.prototype.onResume, + "clientEvaluate": ThreadActor.prototype.onClientEvaluate, + "frames": ThreadActor.prototype.onFrames, + "interrupt": ThreadActor.prototype.onInterrupt, + "releaseMany": ThreadActor.prototype.onReleaseMany, + "setBreakpoint": ThreadActor.prototype.onSetBreakpoint, + "sources": ThreadActor.prototype.onSources, + "threadGrips": ThreadActor.prototype.onThreadGrips +}; + + +/** + * Creates a PauseActor. + * + * PauseActors exist for the lifetime of a given debuggee pause. Used to + * scope pause-lifetime grips. + * + * @param ActorPool aPool + * The actor pool created for this pause. + */ +function PauseActor(aPool) +{ + this.pool = aPool; +} + +PauseActor.prototype = { + actorPrefix: "pause" +}; + + +/** + * A base actor for any actors that should only respond receive messages in the + * paused state. Subclasses may expose a `threadActor` which is used to help + * determine when we are in a paused state. Subclasses should set their own + * "constructor" property if they want better error messages. You should never + * instantiate a PauseScopedActor directly, only through subclasses. + */ +function PauseScopedActor() +{ +} + +/** + * A function decorator for creating methods to handle protocol messages that + * should only be received while in the paused state. + * + * @param aMethod Function + * The function we are decorating. + */ +PauseScopedActor.withPaused = function PSA_withPaused(aMethod) { + return function () { + if (this.isPaused()) { + return aMethod.apply(this, arguments); + } else { + return this._wrongState(); + } + }; +}; + +PauseScopedActor.prototype = { + + /** + * Returns true if we are in the paused state. + */ + isPaused: function PSA_isPaused() { + // When there is not a ThreadActor available (like in the webconsole) we + // have to be optimistic and assume that we are paused so that we can + // respond to requests. + return this.threadActor ? this.threadActor.state === "paused" : true; + }, + + /** + * Returns the wrongState response packet for this actor. + */ + _wrongState: function PSA_wrongState() { + return { + error: "wrongState", + message: this.constructor.name + + " actors can only be accessed while the thread is paused." + }; + } +}; + + +/** + * A SourceActor provides information about the source of a script. + * + * @param aUrl String + * The url of the source we are representing. + * @param aThreadActor ThreadActor + * The current thread actor. + * @param aSourceMap SourceMapConsumer + * Optional. The source map that introduced this source, if available. + */ +function SourceActor(aUrl, aThreadActor, aSourceMap=null) { + this._threadActor = aThreadActor; + this._url = aUrl; + this._sourceMap = aSourceMap; +} + +SourceActor.prototype = { + constructor: SourceActor, + actorPrefix: "source", + + get threadActor() this._threadActor, + get url() this._url, + + form: function SA_form() { + return { + actor: this.actorID, + url: this._url, + isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url) + // TODO bug 637572: introductionScript + }; + }, + + disconnect: function LSA_disconnect() { + if (this.registeredPool && this.registeredPool.sourceActors) { + delete this.registeredPool.sourceActors[this.actorID]; + } + }, + + /** + * Handler for the "source" packet. + */ + onSource: function SA_onSource(aRequest) { + let sourceContent = null; + if (this._sourceMap) { + sourceContent = this._sourceMap.sourceContentFor(this._url); + } + + if (sourceContent) { + return { + from: this.actorID, + source: this.threadActor.createValueGrip( + sourceContent, this.threadActor.threadLifetimePool) + }; + } + + // XXX bug 865252: Don't load from the cache if this is a source mapped + // source because we can't guarantee that the cache has the most up to date + // content for this source like we can if it isn't source mapped. + return fetch(this._url, { loadFromCache: !this._sourceMap }) + .then((aSource) => { + return this.threadActor.createValueGrip( + aSource, this.threadActor.threadLifetimePool); + }) + .then((aSourceGrip) => { + return { + from: this.actorID, + source: aSourceGrip + }; + }, (aError) => { + let msg = "Got an exception during SA_onSource: " + aError + + "\n" + aError.stack; + // Cu.reportError(msg); + dumpn(msg); + return { + "from": this.actorID, + "error": "loadSourceError", + "message": "Could not load the source for " + this._url + "." + }; + }); + }, + + /** + * Handler for the "blackbox" packet. + */ + onBlackBox: function SA_onBlackBox(aRequest) { + this.threadActor.sources.blackBox(this.url); + let packet = { + from: this.actorID + }; + if (this.threadActor.state == "paused" + && this.threadActor.youngestFrame + && this.threadActor.youngestFrame.script.url == this.url) { + packet.pausedInSource = true; + } + return packet; + }, + + /** + * Handler for the "unblackbox" packet. + */ + onUnblackBox: function SA_onUnblackBox(aRequest) { + this.threadActor.sources.unblackBox(this.url); + return { + from: this.actorID + }; + } +}; + +SourceActor.prototype.requestTypes = { + "source": SourceActor.prototype.onSource, + "blackbox": SourceActor.prototype.onBlackBox, + "unblackbox": SourceActor.prototype.onUnblackBox +}; + + +/** + * Creates an actor for the specified object. + * + * @param aObj Debugger.Object + * The debuggee object. + * @param aThreadActor ThreadActor + * The parent thread actor for this object. + */ +function ObjectActor(aObj, aThreadActor) +{ + this.obj = aObj; + this.threadActor = aThreadActor; +} + +ObjectActor.prototype = { + actorPrefix: "obj", + + /** + * Returns a grip for this actor for returning in a protocol message. + */ + grip: function OA_grip() { + let g = { + "type": "object", + "class": this.obj.class, + "actor": this.actorID, + "extensible": this.obj.isExtensible(), + "frozen": this.obj.isFrozen(), + "sealed": this.obj.isSealed() + }; + + // Add additional properties for functions. + if (this.obj.class === "Function") { + if (this.obj.name) { + g.name = this.obj.name; + } else if (this.obj.displayName) { + g.displayName = this.obj.displayName; + } + + // Check if the developer has added a de-facto standard displayName + // property for us to use. + let desc = this.obj.getOwnPropertyDescriptor("displayName"); + if (desc && desc.value && typeof desc.value == "string") { + g.userDisplayName = this.threadActor.createValueGrip(desc.value); + } + } + + return g; + }, + + /** + * Releases this actor from the pool. + */ + release: function OA_release() { + if (this.registeredPool.objectActors) { + this.registeredPool.objectActors.delete(this.obj); + } + this.registeredPool.removeActor(this); + }, + + /** + * Handle a protocol request to provide the names of the properties defined on + * the object and not its prototype. + * + * @param aRequest object + * The protocol request object. + */ + onOwnPropertyNames: function OA_onOwnPropertyNames(aRequest) { + return { from: this.actorID, + ownPropertyNames: this.obj.getOwnPropertyNames() }; + }, + + /** + * Handle a protocol request to provide the prototype and own properties of + * the object. + * + * @param aRequest object + * The protocol request object. + */ + onPrototypeAndProperties: function OA_onPrototypeAndProperties(aRequest) { + let ownProperties = Object.create(null); + let names; + try { + names = this.obj.getOwnPropertyNames(); + } catch (ex) { + // The above can throw if this.obj points to a dead object. + // TODO: we should use Cu.isDeadWrapper() - see bug 885800. + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(null), + ownProperties: ownProperties, + safeGetterValues: Object.create(null) }; + } + for (let name of names) { + ownProperties[name] = this._propertyDescriptor(name); + } + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(this.obj.proto), + ownProperties: ownProperties, + safeGetterValues: this._findSafeGetterValues(ownProperties) }; + }, + + /** + * Find the safe getter values for the current Debugger.Object, |this.obj|. + * + * @private + * @param object aOwnProperties + * The object that holds the list of known ownProperties for + * |this.obj|. + * @return object + * An object that maps property names to safe getter descriptors as + * defined by the remote debugging protocol. + */ + _findSafeGetterValues: function OA__findSafeGetterValues(aOwnProperties) + { + let safeGetterValues = Object.create(null); + let obj = this.obj; + let level = 0; + + while (obj) { + let getters = this._findSafeGetters(obj); + for (let name of getters) { + // Avoid overwriting properties from prototypes closer to this.obj. Also + // avoid providing safeGetterValues from prototypes if property |name| + // is already defined as an own property. + if (name in safeGetterValues || + (obj != this.obj && name in aOwnProperties)) { + continue; + } + + let desc = null, getter = null; + try { + desc = obj.getOwnPropertyDescriptor(name); + getter = desc.get; + } catch (ex) { + // The above can throw if the cache becomes stale. + } + if (!getter) { + obj._safeGetters = null; + continue; + } + + let result = getter.call(this.obj); + if (result && !("throw" in result)) { + let getterValue = undefined; + if ("return" in result) { + getterValue = result.return; + } else if ("yield" in result) { + getterValue = result.yield; + } + // WebIDL attributes specified with the LenientThis extended attribute + // return undefined and should be ignored. + if (getterValue !== undefined) { + safeGetterValues[name] = { + getterValue: this.threadActor.createValueGrip(getterValue), + getterPrototypeLevel: level, + enumerable: desc.enumerable, + writable: level == 0 ? desc.writable : true, + }; + } + } + } + + obj = obj.proto; + level++; + } + + return safeGetterValues; + }, + + /** + * Find the safe getters for a given Debugger.Object. Safe getters are native + * getters which are safe to execute. + * + * @private + * @param Debugger.Object aObject + * The Debugger.Object where you want to find safe getters. + * @return Set + * A Set of names of safe getters. This result is cached for each + * Debugger.Object. + */ + _findSafeGetters: function OA__findSafeGetters(aObject) + { + if (aObject._safeGetters) { + return aObject._safeGetters; + } + + let getters = new Set(); + for (let name of aObject.getOwnPropertyNames()) { + let desc = null; + try { + desc = aObject.getOwnPropertyDescriptor(name); + } catch (e) { + // Calling getOwnPropertyDescriptor on wrapped native prototypes is not + // allowed (bug 560072). + } + if (!desc || desc.value !== undefined || !("get" in desc)) { + continue; + } + + let fn = desc.get; + if (fn && fn.callable && fn.class == "Function" && + fn.script === undefined) { + getters.add(name); + } + } + + aObject._safeGetters = getters; + return getters; + }, + + /** + * Handle a protocol request to provide the prototype of the object. + * + * @param aRequest object + * The protocol request object. + */ + onPrototype: function OA_onPrototype(aRequest) { + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(this.obj.proto) }; + }, + + /** + * Handle a protocol request to provide the property descriptor of the + * object's specified property. + * + * @param aRequest object + * The protocol request object. + */ + onProperty: function OA_onProperty(aRequest) { + if (!aRequest.name) { + return { error: "missingParameter", + message: "no property name was specified" }; + } + + return { from: this.actorID, + descriptor: this._propertyDescriptor(aRequest.name) }; + }, + + /** + * A helper method that creates a property descriptor for the provided object, + * properly formatted for sending in a protocol response. + * + * @param string aName + * The property that the descriptor is generated for. + */ + _propertyDescriptor: function OA_propertyDescriptor(aName) { + let desc; + try { + desc = this.obj.getOwnPropertyDescriptor(aName); + } catch (e) { + // Calling getOwnPropertyDescriptor on wrapped native prototypes is not + // allowed (bug 560072). Inform the user with a bogus, but hopefully + // explanatory, descriptor. + return { + configurable: false, + writable: false, + enumerable: false, + value: e.name + }; + } + + let retval = { + configurable: desc.configurable, + enumerable: desc.enumerable + }; + + if ("value" in desc) { + retval.writable = desc.writable; + retval.value = this.threadActor.createValueGrip(desc.value); + } else { + if ("get" in desc) { + retval.get = this.threadActor.createValueGrip(desc.get); + } + if ("set" in desc) { + retval.set = this.threadActor.createValueGrip(desc.set); + } + } + return retval; + }, + + /** + * Handle a protocol request to provide the source code of a function. + * + * @param aRequest object + * The protocol request object. + */ + onDecompile: function OA_onDecompile(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "decompile request is only valid for object grips " + + "with a 'Function' class." }; + } + + return { from: this.actorID, + decompiledCode: this.obj.decompile(!!aRequest.pretty) }; + }, + + /** + * Handle a protocol request to provide the parameters of a function. + * + * @param aRequest object + * The protocol request object. + */ + onParameterNames: function OA_onParameterNames(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "'parameterNames' request is only valid for object " + + "grips with a 'Function' class." }; + } + + return { parameterNames: this.obj.parameterNames }; + }, + + /** + * Handle a protocol request to release a thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onRelease: function OA_onRelease(aRequest) { + this.release(); + return {}; + }, +}; + +ObjectActor.prototype.requestTypes = { + "parameterNames": ObjectActor.prototype.onParameterNames, + "prototypeAndProperties": ObjectActor.prototype.onPrototypeAndProperties, + "prototype": ObjectActor.prototype.onPrototype, + "property": ObjectActor.prototype.onProperty, + "ownPropertyNames": ObjectActor.prototype.onOwnPropertyNames, + "decompile": ObjectActor.prototype.onDecompile, + "release": ObjectActor.prototype.onRelease, +}; + + +/** + * Creates a pause-scoped actor for the specified object. + * @see ObjectActor + */ +function PauseScopedObjectActor() +{ + ObjectActor.apply(this, arguments); +} + +PauseScopedObjectActor.prototype = Object.create(PauseScopedActor.prototype); + +update(PauseScopedObjectActor.prototype, ObjectActor.prototype); + +update(PauseScopedObjectActor.prototype, { + constructor: PauseScopedObjectActor, + + onOwnPropertyNames: + PauseScopedActor.withPaused(ObjectActor.prototype.onOwnPropertyNames), + + onPrototypeAndProperties: + PauseScopedActor.withPaused(ObjectActor.prototype.onPrototypeAndProperties), + + onPrototype: PauseScopedActor.withPaused(ObjectActor.prototype.onPrototype), + onProperty: PauseScopedActor.withPaused(ObjectActor.prototype.onProperty), + onDecompile: PauseScopedActor.withPaused(ObjectActor.prototype.onDecompile), + + onParameterNames: + PauseScopedActor.withPaused(ObjectActor.prototype.onParameterNames), + + /** + * Handle a protocol request to provide the lexical scope of a function. + * + * @param aRequest object + * The protocol request object. + */ + onScope: PauseScopedActor.withPaused(function OA_onScope(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "scope request is only valid for object grips with a" + + " 'Function' class." }; + } + + let envActor = this.threadActor.createEnvironmentActor(this.obj.environment, + this.registeredPool); + if (!envActor) { + return { error: "notDebuggee", + message: "cannot access the environment of this function." }; + } + + return { from: this.actorID, scope: envActor.form() }; + }), + + /** + * Handle a protocol request to promote a pause-lifetime grip to a + * thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onThreadGrip: PauseScopedActor.withPaused(function OA_onThreadGrip(aRequest) { + this.threadActor.threadObjectGrip(this); + return {}; + }), + + /** + * Handle a protocol request to release a thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onRelease: PauseScopedActor.withPaused(function OA_onRelease(aRequest) { + if (this.registeredPool !== this.threadActor.threadLifetimePool) { + return { error: "notReleasable", + message: "Only thread-lifetime actors can be released." }; + } + + this.release(); + return {}; + }), +}); + +update(PauseScopedObjectActor.prototype.requestTypes, { + "scope": PauseScopedObjectActor.prototype.onScope, + "threadGrip": PauseScopedObjectActor.prototype.onThreadGrip, +}); + + +/** + * Creates an actor for the specied "very long" string. "Very long" is specified + * at the server's discretion. + * + * @param aString String + * The string. + */ +function LongStringActor(aString) +{ + this.string = aString; + this.stringLength = aString.length; +} + +LongStringActor.prototype = { + + actorPrefix: "longString", + + disconnect: function LSA_disconnect() { + // Because longStringActors is not a weak map, we won't automatically leave + // it so we need to manually leave on disconnect so that we don't leak + // memory. + if (this.registeredPool && this.registeredPool.longStringActors) { + delete this.registeredPool.longStringActors[this.actorID]; + } + }, + + /** + * Returns a grip for this actor for returning in a protocol message. + */ + grip: function LSA_grip() { + return { + "type": "longString", + "initial": this.string.substring( + 0, DebuggerServer.LONG_STRING_INITIAL_LENGTH), + "length": this.stringLength, + "actor": this.actorID + }; + }, + + /** + * Handle a request to extract part of this actor's string. + * + * @param aRequest object + * The protocol request object. + */ + onSubstring: function LSA_onSubString(aRequest) { + return { + "from": this.actorID, + "substring": this.string.substring(aRequest.start, aRequest.end) + }; + }, + + /** + * Handle a request to release this LongStringActor instance. + */ + onRelease: function LSA_onRelease() { + // TODO: also check if registeredPool === threadActor.threadLifetimePool + // when the web console moves aray from manually releasing pause-scoped + // actors. + if (this.registeredPool.longStringActors) { + delete this.registeredPool.longStringActors[this.actorID]; + } + this.registeredPool.removeActor(this); + return {}; + }, +}; + +LongStringActor.prototype.requestTypes = { + "substring": LongStringActor.prototype.onSubstring, + "release": LongStringActor.prototype.onRelease +}; + + +/** + * Creates an actor for the specified stack frame. + * + * @param aFrame Debugger.Frame + * The debuggee frame. + * @param aThreadActor ThreadActor + * The parent thread actor for this frame. + */ +function FrameActor(aFrame, aThreadActor) +{ + this.frame = aFrame; + this.threadActor = aThreadActor; +} + +FrameActor.prototype = { + actorPrefix: "frame", + + /** + * A pool that contains frame-lifetime objects, like the environment. + */ + _frameLifetimePool: null, + get frameLifetimePool() { + if (!this._frameLifetimePool) { + this._frameLifetimePool = new ActorPool(this.conn); + this.conn.addActorPool(this._frameLifetimePool); + } + return this._frameLifetimePool; + }, + + /** + * Finalization handler that is called when the actor is being evicted from + * the pool. + */ + disconnect: function FA_disconnect() { + this.conn.removeActorPool(this._frameLifetimePool); + this._frameLifetimePool = null; + }, + + /** + * Returns a frame form for use in a protocol message. + */ + form: function FA_form() { + let form = { actor: this.actorID, + type: this.frame.type }; + if (this.frame.type === "call") { + form.callee = this.threadActor.createValueGrip(this.frame.callee); + } + + if (this.frame.environment) { + let envActor = this.threadActor + .createEnvironmentActor(this.frame.environment, + this.frameLifetimePool); + form.environment = envActor.form(); + } + form.this = this.threadActor.createValueGrip(this.frame.this); + form.arguments = this._args(); + if (this.frame.script) { + form.where = { url: this.frame.script.url, + line: this.frame.script.getOffsetLine(this.frame.offset) }; + form.isBlackBoxed = this.threadActor.sources.isBlackBoxed(this.frame.script.url) + } + + if (!this.frame.older) { + form.oldest = true; + } + + return form; + }, + + _args: function FA__args() { + if (!this.frame.arguments) { + return []; + } + + return [this.threadActor.createValueGrip(arg) + for each (arg in this.frame.arguments)]; + }, + + /** + * Handle a protocol request to pop this frame from the stack. + * + * @param aRequest object + * The protocol request object. + */ + onPop: function FA_onPop(aRequest) { + // TODO: remove this when Debugger.Frame.prototype.pop is implemented + if (typeof this.frame.pop != "function") { + return { error: "notImplemented", + message: "Popping frames is not yet implemented." }; + } + + while (this.frame != this.threadActor.dbg.getNewestFrame()) { + this.threadActor.dbg.getNewestFrame().pop(); + } + this.frame.pop(aRequest.completionValue); + + // TODO: return the watches property when frame pop watch actors are + // implemented. + return { from: this.actorID }; + } +}; + +FrameActor.prototype.requestTypes = { + "pop": FrameActor.prototype.onPop, +}; + + +/** + * Creates a BreakpointActor. BreakpointActors exist for the lifetime of their + * containing thread and are responsible for deleting breakpoints, handling + * breakpoint hits and associating breakpoints with scripts. + * + * @param ThreadActor aThreadActor + * The parent thread actor that contains this breakpoint. + * @param object aLocation + * The location of the breakpoint as specified in the protocol. + */ +function BreakpointActor(aThreadActor, aLocation) +{ + this.scripts = []; + this.threadActor = aThreadActor; + this.location = aLocation; +} + +BreakpointActor.prototype = { + actorPrefix: "breakpoint", + + /** + * Called when this same breakpoint is added to another Debugger.Script + * instance, in the case of a page reload. + * + * @param aScript Debugger.Script + * The new source script on which the breakpoint has been set. + * @param ThreadActor aThreadActor + * The parent thread actor that contains this breakpoint. + */ + addScript: function BA_addScript(aScript, aThreadActor) { + this.threadActor = aThreadActor; + this.scripts.push(aScript); + }, + + /** + * Remove the breakpoints from associated scripts and clear the script cache. + */ + removeScripts: function () { + for (let script of this.scripts) { + script.clearBreakpoint(this); + } + this.scripts = []; + }, + + /** + * A function that the engine calls when a breakpoint has been hit. + * + * @param aFrame Debugger.Frame + * The stack frame that contained the breakpoint. + */ + hit: function BA_hit(aFrame) { + if (this.threadActor.sources.isBlackBoxed(this.location.url)) { + return undefined; + } + + // TODO: add the rest of the breakpoints on that line (bug 676602). + let reason = { type: "breakpoint", actors: [ this.actorID ] }; + return this.threadActor._pauseAndRespond(aFrame, reason, (aPacket) => { + log("pause callback ..."); + + let { url, line } = aPacket.frame.where; + return this.threadActor.sources.getOriginalLocation(url, line) + .then(function (aOrigPosition) { + aPacket.frame.where = aOrigPosition; + return aPacket; + }); + }); + }, + + /** + * Handle a protocol request to remove this breakpoint. + * + * @param aRequest object + * The protocol request object. + */ + onDelete: function BA_onDelete(aRequest) { + // Remove from the breakpoint store. + let scriptBreakpoints = this.threadActor._breakpointStore[this.location.url]; + delete scriptBreakpoints[this.location.line]; + this.threadActor._hooks.removeFromParentPool(this); + // Remove the actual breakpoint from the associated scripts. + this.removeScripts(); + + return { from: this.actorID }; + } +}; + +BreakpointActor.prototype.requestTypes = { + "delete": BreakpointActor.prototype.onDelete +}; + + +/** + * Creates an EnvironmentActor. EnvironmentActors are responsible for listing + * the bindings introduced by a lexical environment and assigning new values to + * those identifier bindings. + * + * @param Debugger.Environment aEnvironment + * The lexical environment that will be used to create the actor. + * @param ThreadActor aThreadActor + * The parent thread actor that contains this environment. + */ +function EnvironmentActor(aEnvironment, aThreadActor) +{ + this.obj = aEnvironment; + this.threadActor = aThreadActor; +} + +EnvironmentActor.prototype = { + actorPrefix: "environment", + + /** + * Return an environment form for use in a protocol message. + */ + form: function EA_form() { + let form = { actor: this.actorID }; + + // What is this environment's type? + if (this.obj.type == "declarative") { + form.type = this.obj.callee ? "function" : "block"; + } else { + form.type = this.obj.type; + } + + // Does this environment have a parent? + if (this.obj.parent) { + form.parent = (this.threadActor + .createEnvironmentActor(this.obj.parent, + this.registeredPool) + .form()); + } + + // Does this environment reflect the properties of an object as variables? + if (this.obj.type == "object" || this.obj.type == "with") { + form.object = this.threadActor.createValueGrip(this.obj.object); + } + + // Is this the environment created for a function call? + if (this.obj.callee) { + form.function = this.threadActor.createValueGrip(this.obj.callee); + } + + // Shall we list this environment's bindings? + if (this.obj.type == "declarative") { + form.bindings = this._bindings(); + } + + return form; + }, + + /** + * Return the identifier bindings object as required by the remote protocol + * specification. + */ + _bindings: function EA_bindings() { + let bindings = { arguments: [], variables: {} }; + + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands (bug 725815). + if (typeof this.obj.getVariable != "function") { + //if (typeof this.obj.getVariableDescriptor != "function") { + return bindings; + } + + let parameterNames; + if (this.obj.callee) { + parameterNames = this.obj.callee.parameterNames; + } + for each (let name in parameterNames) { + let arg = {}; + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands (bug 725815). + let desc = { + value: this.obj.getVariable(name), + configurable: false, + writable: true, + enumerable: true + }; + + // let desc = this.obj.getVariableDescriptor(name); + let descForm = { + enumerable: true, + configurable: desc.configurable + }; + if ("value" in desc) { + descForm.value = this.threadActor.createValueGrip(desc.value); + descForm.writable = desc.writable; + } else { + descForm.get = this.threadActor.createValueGrip(desc.get); + descForm.set = this.threadActor.createValueGrip(desc.set); + } + arg[name] = descForm; + bindings.arguments.push(arg); + } + + for each (let name in this.obj.names()) { + if (bindings.arguments.some(function exists(element) { + return !!element[name]; + })) { + continue; + } + + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands. + let desc = { + configurable: false, + writable: true, + enumerable: true + }; + try { + desc.value = this.obj.getVariable(name); + } catch (e) { + // Avoid "Debugger scope is not live" errors for |arguments|, introduced + // in bug 746601. + if (name != "arguments") { + throw e; + } + } + //let desc = this.obj.getVariableDescriptor(name); + let descForm = { + enumerable: true, + configurable: desc.configurable + }; + if ("value" in desc) { + descForm.value = this.threadActor.createValueGrip(desc.value); + descForm.writable = desc.writable; + } else { + descForm.get = this.threadActor.createValueGrip(desc.get); + descForm.set = this.threadActor.createValueGrip(desc.set); + } + bindings.variables[name] = descForm; + } + + return bindings; + }, + + /** + * Handle a protocol request to change the value of a variable bound in this + * lexical environment. + * + * @param aRequest object + * The protocol request object. + */ + onAssign: function EA_onAssign(aRequest) { + // TODO: enable the commented-out part when getVariableDescriptor lands + // (bug 725815). + /*let desc = this.obj.getVariableDescriptor(aRequest.name); + + if (!desc.writable) { + return { error: "immutableBinding", + message: "Changing the value of an immutable binding is not " + + "allowed" }; + }*/ + + try { + this.obj.setVariable(aRequest.name, aRequest.value); + } catch (e) { + if (e instanceof Debugger.DebuggeeWouldRun) { + return { error: "threadWouldRun", + cause: e.cause ? e.cause : "setter", + message: "Assigning a value would cause the debuggee to run" }; + } + // This should never happen, so let it complain loudly if it does. + throw e; + } + return { from: this.actorID }; + }, + + /** + * Handle a protocol request to fully enumerate the bindings introduced by the + * lexical environment. + * + * @param aRequest object + * The protocol request object. + */ + onBindings: function EA_onBindings(aRequest) { + return { from: this.actorID, + bindings: this._bindings() }; + } +}; + +EnvironmentActor.prototype.requestTypes = { + "assign": EnvironmentActor.prototype.onAssign, + "bindings": EnvironmentActor.prototype.onBindings +}; + +/** + * Override the toString method in order to get more meaningful script output + * for debugging the debugger. + */ +Debugger.Script.prototype.toString = function() { + let output = ""; + if (this.url) { + output += this.url; + } + if (typeof this.startLine != "undefined") { + output += ":" + this.startLine; + if (this.lineCount && this.lineCount > 1) { + output += "-" + (this.startLine + this.lineCount - 1); + } + } + if (this.strictMode) { + output += ":strict"; + } + return output; +}; + +/** + * Helper property for quickly getting to the line number a stack frame is + * currently paused at. + */ +Object.defineProperty(Debugger.Frame.prototype, "line", { + configurable: true, + get: function() { + if (this.script) { + return this.script.getOffsetLine(this.offset); + } else { + return null; + } + } +}); + + +/** + * Creates an actor for handling chrome debugging. ChromeDebuggerActor is a + * thin wrapper over ThreadActor, slightly changing some of its behavior. + * + * @param aConnection object + * The DebuggerServerConnection with which this ChromeDebuggerActor + * is associated. (Currently unused, but required to make this + * constructor usable with addGlobalActor.) + * + * @param aHooks object + * An object with preNest and postNest methods for calling when entering + * and exiting a nested event loop and also addToParentPool and + * removeFromParentPool methods for handling the lifetime of actors that + * will outlive the thread, like breakpoints. + */ +function ChromeDebuggerActor(aConnection, aHooks) +{ + ThreadActor.call(this, aHooks); +} + +ChromeDebuggerActor.prototype = Object.create(ThreadActor.prototype); + +update(ChromeDebuggerActor.prototype, { + constructor: ChromeDebuggerActor, + + // A constant prefix that will be used to form the actor ID by the server. + actorPrefix: "chromeDebugger", + + /** + * Override the eligibility check for scripts and sources to make sure every + * script and source with a URL is stored when debugging chrome. + */ + _allowSource: function(aSourceURL) !!aSourceURL, + + /** + * An object that will be used by ThreadActors to tailor their behavior + * depending on the debugging context being required (chrome or content). + * The methods that this object provides must be bound to the ThreadActor + * before use. + */ + globalManager: { + findGlobals: function CDA_findGlobals() { + // Add every global known to the debugger as debuggee. + this.dbg.addAllGlobalsAsDebuggees(); + }, + + /** + * A function that the engine calls when a new global object has been + * created. + * + * @param aGlobal Debugger.Object + * The new global object that was created. + */ + onNewGlobal: function CDA_onNewGlobal(aGlobal) { + this.addDebuggee(aGlobal); + // Notify the client. + this.conn.send({ + from: this.actorID, + type: "newGlobal", + // TODO: after bug 801084 lands see if we need to JSONify this. + hostAnnotations: aGlobal.hostAnnotations + }); + } + } +}); + + +/** + * Manages the sources for a thread. Handles source maps, locations in the + * sources, etc for ThreadActors. + */ +function ThreadSources(aThreadActor, aUseSourceMaps, aAllowPredicate, + aOnNewSource) { + this._thread = aThreadActor; + this._useSourceMaps = aUseSourceMaps; + this._allow = aAllowPredicate; + this._onNewSource = aOnNewSource; + + // source map URL --> promise of SourceMapConsumer + this._sourceMaps = Object.create(null); + // generated source url --> promise of SourceMapConsumer + this._sourceMapsByGeneratedSource = Object.create(null); + // original source url --> promise of SourceMapConsumer + this._sourceMapsByOriginalSource = Object.create(null); + // source url --> SourceActor + this._sourceActors = Object.create(null); + // original url --> generated url + this._generatedUrlsByOriginalUrl = Object.create(null); +} + +/** + * Must be a class property because it needs to persist across reloads, same as + * the breakpoint store. + */ +ThreadSources._blackBoxedSources = new Set(); + +ThreadSources.prototype = { + /** + * Return the source actor representing |aURL|, creating one if none + * exists already. Returns null if |aURL| is not allowed by the 'allow' + * predicate. + * + * Right now this takes a URL, but in the future it should + * take a Debugger.Source. See bug 637572. + * + * @param String aURL + * The source URL. + * @param optional SourceMapConsumer aSourceMap + * The source map that introduced this source, if any. + * @returns a SourceActor representing the source at aURL or null. + */ + source: function TS_source(aURL, aSourceMap=null) { + if (!this._allow(aURL)) { + return null; + } + + if (aURL in this._sourceActors) { + return this._sourceActors[aURL]; + } + + let actor = new SourceActor(aURL, this._thread, aSourceMap); + this._thread.threadLifetimePool.addActor(actor); + this._sourceActors[aURL] = actor; + try { + this._onNewSource(actor); + } catch (e) { + reportError(e); + } + return actor; + }, + + /** + * Return a promise of an array of source actors representing all the + * sources of |aScript|. + * + * If source map handling is enabled and |aScript| has a source map, then + * use it to find all of |aScript|'s *original* sources; return a promise + * of an array of source actors for those. + */ + sourcesForScript: function TS_sourcesForScript(aScript) { + if (!this._useSourceMaps || !aScript.sourceMapURL) { + return resolve([this.source(aScript.url)].filter(isNotNull)); + } + + return this.sourceMap(aScript) + .then((aSourceMap) => { + return [ + this.source(s, aSourceMap) for (s of aSourceMap.sources) + ]; + }) + .then(null, (e) => { + reportError(e); + delete this._sourceMaps[this._normalize(aScript.sourceMapURL, aScript.url)]; + delete this._sourceMapsByGeneratedSource[aScript.url]; + return [this.source(aScript.url)]; + }) + .then(function (aSources) { + return aSources.filter(isNotNull); + }); + }, + + /** + * Return a promise of a SourceMapConsumer for the source map for + * |aScript|; if we already have such a promise extant, return that. + * |aScript| must have a non-null sourceMapURL. + */ + sourceMap: function TS_sourceMap(aScript) { + if (aScript.url in this._sourceMapsByGeneratedSource) { + return this._sourceMapsByGeneratedSource[aScript.url]; + } + dbg_assert(aScript.sourceMapURL); + let sourceMapURL = this._normalize(aScript.sourceMapURL, aScript.url); + let map = this._fetchSourceMap(sourceMapURL) + .then((aSourceMap) => { + for (let s of aSourceMap.sources) { + this._generatedUrlsByOriginalUrl[s] = aScript.url; + this._sourceMapsByOriginalSource[s] = resolve(aSourceMap); + } + return aSourceMap; + }); + this._sourceMapsByGeneratedSource[aScript.url] = map; + return map; + }, + + /** + * Return a promise of a SourceMapConsumer for the source map located at + * |aAbsSourceMapURL|, which must be absolute. If there is already such a + * promise extant, return it. + */ + _fetchSourceMap: function TS__fetchSourceMap(aAbsSourceMapURL) { + if (aAbsSourceMapURL in this._sourceMaps) { + return this._sourceMaps[aAbsSourceMapURL]; + } else { + let promise = fetch(aAbsSourceMapURL).then((rawSourceMap) => { + let map = new SourceMapConsumer(rawSourceMap); + let base = aAbsSourceMapURL.replace(/\/[^\/]+$/, '/'); + if (base.indexOf("data:") !== 0) { + map.sourceRoot = map.sourceRoot + ? this._normalize(map.sourceRoot, base) + : base; + } + return map; + }); + this._sourceMaps[aAbsSourceMapURL] = promise; + return promise; + } + }, + + /** + * Returns a promise of the location in the original source if the source is + * source mapped, otherwise a promise of the same location. + * + * TODO bug 637572: take/return a column + */ + getOriginalLocation: function TS_getOriginalLocation(aSourceUrl, aLine) { + if (aSourceUrl in this._sourceMapsByGeneratedSource) { + return this._sourceMapsByGeneratedSource[aSourceUrl] + .then(function (aSourceMap) { + let { source, line } = aSourceMap.originalPositionFor({ + source: aSourceUrl, + line: aLine, + column: Infinity + }); + return { + url: source, + line: line + }; + }); + } + + // No source map + return resolve({ + url: aSourceUrl, + line: aLine + }); + }, + + /** + * Returns a promise of the location in the generated source corresponding to + * the original source and line given. + * + * When we pass a script S representing generated code to |sourceMap|, + * above, that returns a promise P. The process of resolving P populates + * the tables this function uses; thus, it won't know that S's original + * source URLs map to S until P is resolved. + * + * TODO bug 637572: take/return a column + */ + getGeneratedLocation: function TS_getGeneratedLocation(aSourceUrl, aLine) { + if (aSourceUrl in this._sourceMapsByOriginalSource) { + return this._sourceMapsByOriginalSource[aSourceUrl] + .then((aSourceMap) => { + let { line } = aSourceMap.generatedPositionFor({ + source: aSourceUrl, + line: aLine, + column: Infinity + }); + return { + url: this._generatedUrlsByOriginalUrl[aSourceUrl], + line: line + }; + }); + } + + // No source map + return resolve({ + url: aSourceUrl, + line: aLine + }); + }, + + /** + * Returns true if URL for the given source is black boxed. + * + * @param aURL String + * The URL of the source which we are checking whether it is black + * boxed or not. + */ + isBlackBoxed: function TS_isBlackBoxed(aURL) { + return ThreadSources._blackBoxedSources.has(aURL); + }, + + /** + * Add the given source URL to the set of sources that are black boxed. If the + * thread is currently paused and we are black boxing the yougest frame's + * source, this will force a step. + * + * @param aURL String + * The URL of the source which we are black boxing. + */ + blackBox: function TS_blackBox(aURL) { + ThreadSources._blackBoxedSources.add(aURL); + }, + + /** + * Remove the given source URL to the set of sources that are black boxed. + * + * @param aURL String + * The URL of the source which we are no longer black boxing. + */ + unblackBox: function TS_unblackBox(aURL) { + ThreadSources._blackBoxedSources.delete(aURL); + }, + + /** + * Normalize multiple relative paths towards the base paths on the right. + */ + _normalize: function TS__normalize(...aURLs) { + dbg_assert(aURLs.length > 1); + let base = Services.io.newURI(aURLs.pop(), null, null); + let url; + while ((url = aURLs.pop())) { + base = Services.io.newURI(url, null, base); + } + return base.spec; + }, + + iter: function TS_iter() { + for (let url in this._sourceActors) { + yield this._sourceActors[url]; + } + } +}; + +// Utility functions. + +/** + * Utility function for updating an object with the properties of another + * object. + * + * @param aTarget Object + * The object being updated. + * @param aNewAttrs Object + * The new attributes being set on the target. + */ +function update(aTarget, aNewAttrs) { + for (let key in aNewAttrs) { + let desc = Object.getOwnPropertyDescriptor(aNewAttrs, key); + + if (desc) { + Object.defineProperty(aTarget, key, desc); + } + } +} + +/** + * Returns true if its argument is not null. + */ +function isNotNull(aThing) { + return aThing !== null; +} + +/** + * Performs a request to load the desired URL and returns a promise. + * + * @param aURL String + * The URL we will request. + * @returns Promise + * A promise of the document at that URL, as a string. + * + * XXX: It may be better to use nsITraceableChannel to get to the sources + * without relying on caching when we can (not for eval, etc.): + * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ + */ +function fetch(aURL, aOptions={ loadFromCache: true }) { + let deferred = defer(); + let scheme; + let url = aURL.split(" -> ").pop(); + let charset; + let filePath = url; + // try { + // scheme = Services.io.extractScheme(url); + // } catch (e) { + // In the xpcshell tests, the script url is the absolute path of the test + // file, which will make a malformed URI error be thrown. Add the file + // scheme prefix ourselves. + url = "file://" + url; + // scheme = Services.io.extractScheme(url); + // } + scheme = "file"; + + switch (scheme) { + case "file": + case "chrome": + case "resource": + try { + // NetUtil.asyncFetch(url, function onFetch(aStream, aStatus) { + // if (!Components.isSuccessCode(aStatus)) { + // deferred.reject("Request failed: " + url); + // return; + // } + let cc = globalDebuggee.cc; + let fileUtils = cc.FileUtils.getInstance(); + let source = fileUtils.getStringFromFile(filePath);//NetUtil.readInputStreamToString(aStream, aStream.available()); + if (!source) + { + deferred.reject("Request failed: " + url); + } + else + { + deferred.resolve(source); + } + // aStream.close(); + // }); + } catch (ex) { + deferred.reject("Request failed: " + url); + } + break; + + default: + let channel; + try { + channel = Services.io.newChannel(url, null, null); + } catch (e if e.name == "NS_ERROR_UNKNOWN_PROTOCOL") { + // On Windows xpcshell tests, c:/foo/bar can pass as a valid URL, but + // newChannel won't be able to handle it. + url = "file:///" + url; + channel = Services.io.newChannel(url, null, null); + } + let chunks = []; + let streamListener = { + onStartRequest: function(aRequest, aContext, aStatusCode) { + if (!Components.isSuccessCode(aStatusCode)) { + deferred.reject("Request failed: " + url); + } + }, + onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount) { + chunks.push(NetUtil.readInputStreamToString(aStream, aCount)); + }, + onStopRequest: function(aRequest, aContext, aStatusCode) { + if (!Components.isSuccessCode(aStatusCode)) { + deferred.reject("Request failed: " + url); + return; + } + + charset = channel.contentCharset; + deferred.resolve(chunks.join("")); + } + }; + + channel.loadFlags = aOptions.loadFromCache + ? channel.LOAD_FROM_CACHE + : channel.LOAD_BYPASS_CACHE; + channel.asyncOpen(streamListener, null); + break; + } + + return deferred.promise.then(function (source) { + return convertToUnicode(source, charset); + }); +} + +/** + * Convert a given string, encoded in a given character set, to unicode. + * + * @param string aString + * A string. + * @param string aCharset + * A character set. + */ +function convertToUnicode(aString, aCharset=null) { + // Decoding primitives. + // let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + // .createInstance(Ci.nsIScriptableUnicodeConverter); + // try { + // converter.charset = aCharset || "UTF-8"; + // return converter.ConvertToUnicode(aString); + // } catch(e) { + return aString; + // } +} + +/** + * Report the given error in the error console and to stdout. + */ +function reportError(aError) { + // Cu.reportError(aError); + dumpn(aError.message + ":\n" + aError.stack); +} diff --git a/scripting/javascript/bindings/js/debugger/actors/string.js b/scripting/javascript/bindings/js/debugger/actors/string.js new file mode 100644 index 0000000000..8fc1eda94e --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/string.js @@ -0,0 +1,145 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +let {Cu} = require("chrome"); +let {DebuggerServer} = Cu.import("resource://gre/modules/devtools/dbg-server.jsm", {}); + +let promise = require("sdk/core/promise"); +let {Class} = require("sdk/core/heritage"); + +let protocol = require("devtools/server/protocol"); +let {method, Arg, Option, RetVal} = protocol; + +exports.LongStringActor = protocol.ActorClass({ + typeName: "longstractor", + + initialize: function(conn, str) { + protocol.Actor.prototype.initialize.call(this, conn); + this.str = str; + this.short = (this.str.length < DebuggerServer.LONG_STRING_LENGTH); + }, + + destroy: function() { + this.str = null; + protocol.Actor.prototype.destroy.call(this); + }, + + form: function() { + if (this.short) { + return this.str; + } + return { + type: "longString", + actor: this.actorID, + length: this.str.length, + initial: this.str.substring(0, DebuggerServer.LONG_STRING_INITIAL_LENGTH) + } + }, + + substring: method(function(start, end) { + return promise.resolve(this.str.substring(start, end)); + }, { + request: { + start: Arg(0), + end: Arg(1) + }, + response: { substring: RetVal() }, + }), + + release: method(function() { }, { release: true }) +}); + +/** + * When a LongString on the server is short enough to be passed + * as a full string, the client will get a ShortLongString instead of + * a LongStringFront. Its API should match. + * + * I'm very proud of this name. + */ +exports.ShortLongString = Class({ + initialize: function(str) { + this.str = str; + }, + + get length() { return this.str.length; }, + get initial() { return this.str; }, + string: function() { return promise.resolve(this.str) }, + + substring: function(start, end) { + return promise.resolve(this.str.substring(start, end)); + }, + + release: function() { + this.str = null; + return promise.resolve(undefined); + } +}) + +exports.LongStringFront = protocol.FrontClass(exports.LongStringActor, { + initialize: function(client, form) { + // Don't give the form by default, because we're being tricky and it might just + // be a string. + protocol.Front.prototype.initialize.call(this, client, null); + this.form(form); + }, + + destroy: function() { + this.initial = null; + this.length = null; + this.strPromise = null; + protocol.Front.prototype.destroy.call(this); + }, + + form: function(form) { + this.actorID = form.actorID; + this.initial = form.initial; + this.length = form.length; + }, + + string: function() { + if (!this.strPromise) { + let promiseRest = (thusFar) => { + if (thusFar.length === this.length) + return promise.resolve(thusFar); + else { + return this.substring(thusFar.length, + thusFar.length + DebuggerServer.LONG_STRING_READ_LENGTH) + .then((next) => promiseRest(thusFar + next)); + } + } + + this.strPromise = promiseRest(this.initial); + } + return this.strPromise; + } +}); + +// The long string actor needs some custom marshalling, because it is sometimes +// returned as a primitive rather than a complete form. + +let stringActorType = protocol.types.getType("longstractor"); +protocol.types.addType("longstring", { + _actor: true, + write: (value, context, detail) => { + if (!(context instanceof protocol.Actor)) { + throw Error("Passing a longstring as an argument isn't supported."); + } + if (value.short) { + return value.str; + } else { + return stringActorType.write(value, context, detail); + } + }, + read: (value, context, detail) => { + if (context instanceof protocol.Actor) { + throw Error("Passing a longstring as an argument isn't supported."); + } + if (typeof(value) === "string") { + return exports.ShortLongString(value); + } + return stringActorType.read(value, context, detail); + } +}); diff --git a/scripting/javascript/bindings/js/debugger/actors/styleeditor.js b/scripting/javascript/bindings/js/debugger/actors/styleeditor.js new file mode 100644 index 0000000000..d4ef50186d --- /dev/null +++ b/scripting/javascript/bindings/js/debugger/actors/styleeditor.js @@ -0,0 +1,740 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +let Cc = Components.classes; +let Ci = Components.interfaces; +let Cu = Components.utils; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource://gre/modules/FileUtils.jsm"); + +let TRANSITION_CLASS = "moz-styleeditor-transitioning"; +let TRANSITION_DURATION_MS = 500; +let TRANSITION_RULE = "\ +:root.moz-styleeditor-transitioning, :root.moz-styleeditor-transitioning * {\ +transition-duration: " + TRANSITION_DURATION_MS + "ms !important; \ +transition-delay: 0ms !important;\ +transition-timing-function: ease-out !important;\ +transition-property: all !important;\ +}"; + +let LOAD_ERROR = "error-load"; + +/** + * Creates a StyleEditorActor. StyleEditorActor provides remote access to the + * built-in style editor module. + */ +function StyleEditorActor(aConnection, aParentActor) +{ + this.conn = aConnection; + this._onDocumentLoaded = this._onDocumentLoaded.bind(this); + this._onSheetLoaded = this._onSheetLoaded.bind(this); + + if (aParentActor instanceof BrowserTabActor && + aParentActor.browser instanceof Ci.nsIDOMWindow) { + this._window = aParentActor.browser; + } + else if (aParentActor instanceof BrowserTabActor && + aParentActor.browser instanceof Ci.nsIDOMElement) { + this._window = aParentActor.browser.contentWindow; + } + else { + this._window = Services.wm.getMostRecentWindow("navigator:browser"); + } + + // keep a map of sheets-to-actors so we don't create two actors for one sheet + this._sheets = new Map(); + + this._actorPool = new ActorPool(this.conn); + this.conn.addActorPool(this._actorPool); +} + +StyleEditorActor.prototype = { + /** + * Actor pool for all of the actors we send to the client. + */ + _actorPool: null, + + /** + * The debugger server connection instance. + */ + conn: null, + + /** + * The content window we work with. + */ + get win() this._window, + + /** + * The current content document of the window we work with. + */ + get doc() this._window.document, + + /** + * A window object, usually the browser window + */ + _window: null, + + actorPrefix: "styleEditor", + + form: function() + { + return { actor: this.actorID }; + }, + + /** + * Destroy the current StyleEditorActor instance. + */ + disconnect: function() + { + if (this._observer) { + this._observer.disconnect(); + delete this._observer; + } + + this._sheets.clear(); + + this.conn.removeActorPool(this._actorPool); + this._actorPool = null; + this.conn = this._window = null; + }, + + /** + * Release an actor from our actor pool. + */ + releaseActor: function(actor) + { + if (this._actorPool) { + this._actorPool.removeActor(actor.actorID); + } + }, + + /** + * Get the BaseURI for the document. + * + * @return {object} JSON message to with BaseURI + */ + onGetBaseURI: function() { + return { baseURI: this.doc.baseURIObject }; + }, + + /** + * Called when target navigates to a new document. + * Adds load listeners to document. + */ + onNewDocument: function() { + // delete previous document's actors + this._clearStyleSheetActors(); + + // Note: listening for load won't be necessary once + // https://bugzilla.mozilla.org/show_bug.cgi?id=839103 is fixed + if (this.doc.readyState == "complete") { + this._onDocumentLoaded(); + } + else { + this.win.addEventListener("load", this._onDocumentLoaded, false); + } + return {}; + }, + + /** + * Event handler for document loaded event. Add actor for each stylesheet + * and send an event notifying of the load + */ + _onDocumentLoaded: function(event) { + if (event) { + this.win.removeEventListener("load", this._onDocumentLoaded, false); + } + + let documents = [this.doc]; + var forms = []; + for (let doc of documents) { + let sheetForms = this._addStyleSheets(doc.styleSheets); + forms = forms.concat(sheetForms); + // Recursively handle style sheets of the documents in iframes. + for (let iframe of doc.getElementsByTagName("iframe")) { + documents.push(iframe.contentDocument); + } + } + + this.conn.send({ + from: this.actorID, + type: "documentLoad", + styleSheets: forms + }); + }, + + /** + * Add all the stylesheets to the map and create an actor + * for each one if not already created. Send event that there + * are new stylesheets. + * + * @param {[DOMStyleSheet]} styleSheets + * Stylesheets to add + * @return {[object]} + * Array of forms for each StyleSheetActor created + */ + _addStyleSheets: function(styleSheets) + { + let sheets = []; + for (let i = 0; i < styleSheets.length; i++) { + let styleSheet = styleSheets[i]; + sheets.push(styleSheet); + + // Get all sheets, including imported ones + let imports = this._getImported(styleSheet); + sheets = sheets.concat(imports); + } + + let forms = sheets.map((sheet) => { + let actor = this._createStyleSheetActor(sheet); + return actor.form(); + }); + + return forms; + }, + + /** + * Get all the stylesheets @imported from a stylesheet. + * + * @param {DOMStyleSheet} styleSheet + * Style sheet to search + * @return {array} + * All the imported stylesheets + */ + _getImported: function(styleSheet) { + let imported = []; + + for (let i = 0; i < styleSheet.cssRules.length; i++) { + let rule = styleSheet.cssRules[i]; + if (rule.type == Ci.nsIDOMCSSRule.IMPORT_RULE) { + // Associated styleSheet may be null if it has already been seen due to + // duplicate @imports for the same URL. + if (!rule.styleSheet) { + continue; + } + imported.push(rule.styleSheet); + + // recurse imports in this stylesheet as well + imported = imported.concat(this._getImported(rule.styleSheet)); + } + else if (rule.type != Ci.nsIDOMCSSRule.CHARSET_RULE) { + // @import rules must precede all others except @charset + break; + } + } + return imported; + }, + + /** + * Create a new actor for a style sheet, if it hasn't + * already been created, and return it. + * + * @param {DOMStyleSheet} aStyleSheet + * The style sheet to create an actor for. + * @return {StyleSheetActor} + * The actor for this style sheet + */ + _createStyleSheetActor: function(aStyleSheet) + { + if (this._sheets.has(aStyleSheet)) { + return this._sheets.get(aStyleSheet); + } + let actor = new StyleSheetActor(aStyleSheet, this); + this._actorPool.addActor(actor); + this._sheets.set(aStyleSheet, actor); + return actor; + }, + + /** + * Clear all the current stylesheet actors in map. + */ + _clearStyleSheetActors: function() { + for (let actor in this._sheets) { + this.releaseActor(this._sheets[actor]); + } + this._sheets.clear(); + }, + + /** + * Get the actors of all the stylesheets in the current document. + * + * @return {object} JSON message with the stylesheet actors' forms + */ + onGetStyleSheets: function() { + let forms = this._addStyleSheets(this.doc.styleSheets); + return { "styleSheets": forms }; + }, + + /** + * Handler for style sheet loading event. Add + * a new actor for the sheet and notify. + * + * @param {Event} event + */ + _onSheetLoaded: function(event) { + let style = event.target; + style.removeEventListener("load", this._onSheetLoaded, false); + + let actor = this._createStyleSheetActor(style.sheet); + this._notifyStyleSheetsAdded([actor.form()]); + }, + + /** + * Create a new style sheet in the document with the given text. + * Return an actor for it. + * + * @param {object} request + * Debugging protocol request object, with 'text property' + * @return {object} + * Object with 'styelSheet' property for form on new actor. + */ + onNewStyleSheet: function(request) { + let parent = this.doc.documentElement; + let style = this.doc.createElementNS("http://www.w3.org/1999/xhtml", "style"); + style.setAttribute("type", "text/css"); + + if (request.text) { + style.appendChild(this.doc.createTextNode(request.text)); + } + parent.appendChild(style); + + let actor = this._createStyleSheetActor(style.sheet); + return { styleSheet: actor.form() }; + } +}; + +/** + * The request types this actor can handle. + */ +StyleEditorActor.prototype.requestTypes = { + "getStyleSheets": StyleEditorActor.prototype.onGetStyleSheets, + "newStyleSheet": StyleEditorActor.prototype.onNewStyleSheet, + "getBaseURI": StyleEditorActor.prototype.onGetBaseURI, + "newDocument": StyleEditorActor.prototype.onNewDocument +}; + + +function StyleSheetActor(aStyleSheet, aParentActor) { + this.styleSheet = aStyleSheet; + this.parentActor = aParentActor; + + // text and index are unknown until source load + this.text = null; + this._styleSheetIndex = -1; + + this._transitionRefCount = 0; + + this._onSourceLoad = this._onSourceLoad.bind(this); + this._notifyError = this._notifyError.bind(this); + + // if this sheet has an @import, then it's rules are loaded async + let ownerNode = this.styleSheet.ownerNode; + if (ownerNode) { + let onSheetLoaded = function(event) { + ownerNode.removeEventListener("load", onSheetLoaded, false); + this._notifyPropertyChanged("ruleCount"); + }.bind(this); + + ownerNode.addEventListener("load", onSheetLoaded, false); + } +} + +StyleSheetActor.prototype = { + actorPrefix: "stylesheet", + + toString: function() { + return "[StyleSheetActor " + this.actorID + "]"; + }, + + disconnect: function() { + this.parentActor.releaseActor(this); + }, + + /** + * Window of target + */ + get win() { + return this.parentActor._window; + }, + + /** + * Document of target. + */ + get doc() { + return this.win.document; + }, + + /** + * Retrieve the index (order) of stylesheet in the document. + * + * @return number + */ + get styleSheetIndex() + { + if (this._styleSheetIndex == -1) { + for (let i = 0; i < this.doc.styleSheets.length; i++) { + if (this.doc.styleSheets[i] == this.styleSheet) { + this._styleSheetIndex = i; + break; + } + } + } + return this._styleSheetIndex; + }, + + /** + * Get the current state of the actor + * + * @return {object} + * With properties of the underlying stylesheet, plus 'text', + * 'styleSheetIndex' and 'parentActor' if it's @imported + */ + form: function() { + let form = { + actor: this.actorID, // actorID is set when this actor is added to a pool + href: this.styleSheet.href, + disabled: this.styleSheet.disabled, + title: this.styleSheet.title, + styleSheetIndex: this.styleSheetIndex, + text: this.text + } + + // get parent actor if this sheet was @imported + let parent = this.styleSheet.parentStyleSheet; + if (parent) { + form.parentActor = this.parentActor._sheets.get(parent); + } + + try { + form.ruleCount = this.styleSheet.cssRules.length; + } + catch(e) { + // stylesheet had an @import rule that wasn't loaded yet + } + + return form; + }, + + /** + * Toggle the disabled property of the style sheet + * + * @return {object} + * 'disabled' - the disabled state after toggling. + */ + onToggleDisabled: function() { + this.styleSheet.disabled = !this.styleSheet.disabled; + this._notifyPropertyChanged("disabled"); + + return { disabled: this.styleSheet.disabled }; + }, + + /** + * Send an event notifying that a property of the stylesheet + * has changed. + * + * @param {string} property + * Name of the changed property + */ + _notifyPropertyChanged: function(property) { + this.conn.send({ + from: this.actorID, + type: "propertyChange-" + this.actorID, + property: property, + value: this.form()[property] + }) + }, + + /** + * Send an event notifying that an error has occured + * + * @param {string} message + * Error message + */ + _notifyError: function(message) { + this.conn.send({ + from: this.actorID, + type: "error-" + this.actorID, + errorMessage: message + }); + }, + + /** + * Handler for event when the style sheet's full text has been + * loaded from its source. + * + * @param {string} source + * Text of the style sheet + * @param {[type]} charset + * Optional charset of the source + */ + _onSourceLoad: function(source, charset) { + this.text = this._decodeCSSCharset(source, charset || ""); + + this.conn.send({ + from: this.actorID, + type: "sourceLoad-" + this.actorID, + source: this.text + }); + }, + + /** + * Fetch the source of the style sheet from its URL + */ + onFetchSource: function() { + if (!this.styleSheet.href) { + // this is an inline - - -
- -
- - diff --git a/samples/Cpp/TestCpp/proj.qt5/TestCpp.pro b/samples/Cpp/TestCpp/proj.qt5/TestCpp.pro deleted file mode 100644 index 1678596819..0000000000 --- a/samples/Cpp/TestCpp/proj.qt5/TestCpp.pro +++ /dev/null @@ -1,128 +0,0 @@ - -include(../../../../cocos2dx/proj.qt5/common.pri) - -TARGET = cocos2dx_TestCpp - -INCLUDEPATH += .. -INCLUDEPATH += ../Classes - -SOURCES += main.cpp -SOURCES += ../Classes/AccelerometerTest/AccelerometerTest.cpp \ - ../Classes/ActionManagerTest/ActionManagerTest.cpp \ - ../Classes/ActionsEaseTest/ActionsEaseTest.cpp \ - ../Classes/ActionsProgressTest/ActionsProgressTest.cpp \ - ../Classes/ActionsTest/ActionsTest.cpp \ - ../Classes/Box2DTest/Box2dTest.cpp \ - ../Classes/Box2DTestBed/Box2dView.cpp \ - ../Classes/Box2DTestBed/GLES-Render.cpp \ - ../Classes/Box2DTestBed/Test.cpp \ - ../Classes/Box2DTestBed/TestEntries.cpp \ - ../Classes/BugsTest/Bug-1159.cpp \ - ../Classes/BugsTest/Bug-1174.cpp \ - ../Classes/BugsTest/Bug-350.cpp \ - ../Classes/BugsTest/Bug-422.cpp \ - ../Classes/BugsTest/Bug-458/Bug-458.cpp \ - ../Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ - ../Classes/BugsTest/Bug-624.cpp \ - ../Classes/BugsTest/Bug-886.cpp \ - ../Classes/BugsTest/Bug-899.cpp \ - ../Classes/BugsTest/Bug-914.cpp \ - ../Classes/BugsTest/BugsTest.cpp \ - ../Classes/ChipmunkTest/ChipmunkTest.cpp \ - ../Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ - ../Classes/ClippingNodeTest/ClippingNodeTest.cpp \ - ../Classes/CocosDenshionTest/CocosDenshionTest.cpp \ - ../Classes/CurlTest/CurlTest.cpp \ - ../Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ - ../Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ - ../Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ - ../Classes/EffectsTest/EffectsTest.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ - ../Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ - ../Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ - ../Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ - ../Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ - ../Classes/ExtensionsTest/ExtensionsTest.cpp \ - ../Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ - ../Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/ComponentsTestScene.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/EnemyController.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/GameOverScene.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/PlayerController.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/ProjectileController.cpp \ - ../Classes/ExtensionsTest/ComponentsTest/SceneController.cpp \ - ../Classes/ExtensionsTest/ArmatureTest/ArmatureScene.cpp \ - ../Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ - ../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ - ../Classes/FontTest/FontTest.cpp \ - ../Classes/IntervalTest/IntervalTest.cpp \ - ../Classes/KeyboardTest/KeyboardTest.cpp \ - ../Classes/KeypadTest/KeypadTest.cpp \ - ../Classes/LabelTest/LabelTest.cpp \ - ../Classes/LayerTest/LayerTest.cpp \ - ../Classes/MenuTest/MenuTest.cpp \ - ../Classes/MotionStreakTest/MotionStreakTest.cpp \ - ../Classes/MutiTouchTest/MutiTouchTest.cpp \ - ../Classes/NodeTest/NodeTest.cpp \ - ../Classes/ParallaxTest/ParallaxTest.cpp \ - ../Classes/ParticleTest/ParticleTest.cpp \ - ../Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ - ../Classes/PerformanceTest/PerformanceParticleTest.cpp \ - ../Classes/PerformanceTest/PerformanceSpriteTest.cpp \ - ../Classes/PerformanceTest/PerformanceTest.cpp \ - ../Classes/PerformanceTest/PerformanceTextureTest.cpp \ - ../Classes/PerformanceTest/PerformanceTouchesTest.cpp \ - ../Classes/RenderTextureTest/RenderTextureTest.cpp \ - ../Classes/RotateWorldTest/RotateWorldTest.cpp \ - ../Classes/SceneTest/SceneTest.cpp \ - ../Classes/SchedulerTest/SchedulerTest.cpp \ - ../Classes/ShaderTest/ShaderTest.cpp \ - ../Classes/SpriteTest/SpriteTest.cpp \ - ../Classes/TextInputTest/TextInputTest.cpp \ - ../Classes/Texture2dTest/Texture2dTest.cpp \ - ../Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ - ../Classes/TextureCacheTest/TextureCacheTest.cpp \ - ../Classes/TileMapTest/TileMapTest.cpp \ - ../Classes/TouchesTest/Ball.cpp \ - ../Classes/TouchesTest/Paddle.cpp \ - ../Classes/TouchesTest/TouchesTest.cpp \ - ../Classes/TransitionsTest/TransitionsTest.cpp \ - ../Classes/UserDefaultTest/UserDefaultTest.cpp \ - ../Classes/ZwoptexTest/ZwoptexTest.cpp \ - ../Classes/FileUtilsTest/FileUtilsTest.cpp \ - ../Classes/SpineTest/SpineTest.cpp \ - ../Classes/DataVisitorTest/DataVisitorTest.cpp \ - ../Classes/ConfigurationTest/ConfigurationTest.cpp \ - ../Classes/controller.cpp \ - ../Classes/testBasic.cpp \ - ../Classes/AppDelegate.cpp \ - ../Classes/BaseTest.cpp \ - ../Classes/VisibleRect.cpp - -LIBS += $${LINK_AGAINST_COCOS2DX} -LIBS += $${LINK_AGAINST_COCOSDENSHION} -LIBS += $${LINK_AGAINST_COCOSEXTENSION} - -INSTALLS += target -target.path = /opt/$${TARGET} - -INSTALLS += desktop -desktop.files = $${TARGET}.desktop -desktop.path = $${DESKTOP_INSTALL_DIR} - -INSTALLS += resources -resources.files = icon.png ../Resources -resources.path = /opt/$${TARGET} - diff --git a/samples/Cpp/TestCpp/proj.qt5/cocos2dx_TestCpp.desktop b/samples/Cpp/TestCpp/proj.qt5/cocos2dx_TestCpp.desktop deleted file mode 100644 index 8447988c7f..0000000000 --- a/samples/Cpp/TestCpp/proj.qt5/cocos2dx_TestCpp.desktop +++ /dev/null @@ -1,5 +0,0 @@ -[Desktop Entry] -Type=Application -Name=Cocos2D-X -Icon=/opt/cocos2dx_TestCpp/icon.png -Exec=/opt/cocos2dx_TestCpp/cocos2dx_TestCpp diff --git a/samples/Cpp/TestCpp/proj.qt5/main.cpp b/samples/Cpp/TestCpp/proj.qt5/main.cpp deleted file mode 100644 index 87fe8873df..0000000000 --- a/samples/Cpp/TestCpp/proj.qt5/main.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - auto eglView = CCEGLView::sharedOpenGLView(); - eglView->setFrameSize(800, 480); - return CCApplication::sharedApplication()->run(); -} diff --git a/samples/Cpp/TestCpp/proj.tizen/.cproject b/samples/Cpp/TestCpp/proj.tizen/.cproject deleted file mode 100644 index 9cb31d8072..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/.cproject +++ /dev/null @@ -1,701 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/TestCpp/proj.tizen/.project b/samples/Cpp/TestCpp/proj.tizen/.project deleted file mode 100644 index ad264e16ca..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/.project +++ /dev/null @@ -1,106 +0,0 @@ - - - proj.tizen - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - sbi-make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/${ProjName}/Debug-Tizen-Emulator} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - true - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - org.tizen.nativecpp.apichecker.core.builder - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.tizen.nativecpp.apichecker.core.tizenCppNature - - - - src/Classes - 2 - PARENT-1-PROJECT_LOC/Classes - - - - - 1372993495655 - - 26 - - org.eclipse.ui.ide.multiFilter - 1.0-projectRelativePath-matches-false-false-*/.tpk - - - - diff --git a/samples/Cpp/TestCpp/proj.tizen/README.mdown b/samples/Cpp/TestCpp/proj.tizen/README.mdown deleted file mode 100644 index 68e93e99e0..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/README.mdown +++ /dev/null @@ -1,6 +0,0 @@ -TestCpp for Tizen -================== - - * Create Tizen IDE workspace in cocos2d-x/samples/Cpp/TestCpp - * Import proj.tizen - * Copy cocos2d-x/samples/Cpp/TestCpp/Resources/*.* to cocos2d-x/samples/Cpp/TestCpp/proj.tizen/res diff --git a/samples/Cpp/TestCpp/proj.tizen/data/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/inc/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/inc/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/lib/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/lib/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/manifest.xml b/samples/Cpp/TestCpp/proj.tizen/manifest.xml deleted file mode 100644 index 32976beeb6..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/manifest.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - WMrZqguX0B - 1.0.0 - C++App - - true - - - 2.2 - - - - - - TestCpp - - - mainmenu.png - - - - - diff --git a/samples/Cpp/TestCpp/proj.tizen/res/.gitignore b/samples/Cpp/TestCpp/proj.tizen/res/.gitignore deleted file mode 100644 index 1d65afe366..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/res/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -#Do now ignore Marmalade icf files -!*.icf diff --git a/samples/Cpp/TestCpp/proj.tizen/res/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/res/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/shared/data/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/shared/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/shared/trusted/.gitkeep b/samples/Cpp/TestCpp/proj.tizen/shared/trusted/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Cpp/TestCpp/proj.tizen/src/TestCppEntry.cpp b/samples/Cpp/TestCpp/proj.tizen/src/TestCppEntry.cpp deleted file mode 100644 index 3ec1b2ae63..0000000000 --- a/samples/Cpp/TestCpp/proj.tizen/src/TestCppEntry.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org -Copyright (c) 2013 Lee, Jae-Hong - -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. -****************************************************************************/ - -// -// This file contains the Tizen application entry point. -// -#include "../../Classes/AppDelegate.h" -#include "cocos2d.h" - -USING_NS_CC; -using namespace Tizen::Base; -using namespace Tizen::Base::Collection; - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -void -ApplicationInitialized(void) -{ - AppDelegate* pAppDelegate = new AppDelegate; - - auto eglView = EGLView::getInstance(); - eglView->setFrameSize(1280, 720); - - Application::getInstance()->run(); -} - -// -// The entry function of Tizen application called by the operating system. -// -_EXPORT_ int -OspMain(int argc, char *pArgv[]) -{ - AppLog("Application started."); - ArrayList args(SingleObjectDeleter); - args.Construct(); - for (int i = 0; i < argc; i++) - { - args.Add(new (std::nothrow) Tizen::Base::String(pArgv[i])); - } - - OspApplication::SetApplicationInitializedCallback(ApplicationInitialized); - OspApplication::SetScreenOrientation(Tizen::Ui::ORIENTATION_LANDSCAPE); - result r = Tizen::App::Application::Execute(OspApplication::CreateInstance, &args); - TryLog(r == E_SUCCESS, "[%s] Application execution failed", GetErrorMessage(r)); - AppLog("Application finished."); - - return static_cast(r); -} -#ifdef __cplusplus -} -#endif // __cplusplus diff --git a/samples/Lua/HelloLua/proj.emscripten/Makefile b/samples/Lua/HelloLua/proj.emscripten/Makefile deleted file mode 100644 index 3cb02a4db5..0000000000 --- a/samples/Lua/HelloLua/proj.emscripten/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -EXECUTABLE = HelloLua - -COCOS_ROOT = ../../../.. -INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support \ - -I$(COCOS_ROOT)/extensions \ - -SOURCES = main.cpp ../Classes/AppDelegate.cpp - -SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so - -include $(COCOS_ROOT)/cocos2dx/proj.emscripten/cocos2dx.mk - -$(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - cp -r ../../../../scripting/lua/script/ ../../../../samples/Lua/HelloLua/Resources - $(CXX) $(CXXFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/samples/Lua/HelloLua/proj.emscripten/main.cpp b/samples/Lua/HelloLua/proj.emscripten/main.cpp deleted file mode 100644 index 92b65bdca4..0000000000 --- a/samples/Lua/HelloLua/proj.emscripten/main.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - auto eglView = EGLView::getInstance(); - eglView->setFrameSize(960, 640); - return Application::getInstance()->run(); -} diff --git a/samples/Lua/HelloLua/proj.nacl/Makefile b/samples/Lua/HelloLua/proj.nacl/Makefile deleted file mode 100644 index 64ee13248e..0000000000 --- a/samples/Lua/HelloLua/proj.nacl/Makefile +++ /dev/null @@ -1,67 +0,0 @@ -COCOS_ROOT = ../../../.. -COCOS2DX_PATH = $(COCOS_ROOT)/cocos2dx - -INCLUDES = -I.. \ - -I../Classes \ - -I$(COCOS_ROOT)/CocosDenshion/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support \ - -I$(NACL_SDK_ROOT)/include \ - -I$(COCOS_ROOT)/external \ - -I$(COCOS_ROOT)/external/chipmunk/include/chipmunk \ - -I$(COCOS_ROOT)/extensions \ - -I$(COCOS_ROOT)/extensions/Components - -SOURCES = main.cpp \ - ../Classes/AppDelegate.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaEngine.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaStack.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaValue.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/LuaCocos2d.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/tolua_fix.c \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCBProxy.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/Lua_extensions_CCB.cpp - -include $(COCOS2DX_PATH)/../extensions/proj.nacl/Makefile -SOURCES += $(addprefix $(COCOS_ROOT)/extensions/, $(EXTENSIONS_SOURCES)) - -include $(COCOS_ROOT)/cocos2dx/proj.nacl/cocos2dx.mk - -CXXFLAGS += -Wno-multichar -STATICLIBS += -llua -lnosys -SHAREDLIBS += -lbox2d - -APP_NAME = HelloLua -TARGET = $(BIN_DIR)/$(APP_NAME)_$(NACL_ARCH).nexe -NMF = $(BIN_DIR)/$(APP_NAME).nmf - -all: $(NMF) - -$(TARGET): $(OBJECTS) $(LIB_DIR)/libcocos2d.a - @mkdir -p $(@D) - $(LOG_LINK)$(NACL_CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: ../%.cpp - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.cpp - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: $(COCOS_ROOT)/%.cpp - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: $(COCOS_ROOT)/%.c - @mkdir -p $(@D) - $(LOG_CC)$(NACL_CC) -MMD $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(NMF): $(TARGET) - $(NACL_SDK_ROOT)/tools/create_nmf.py -o $@ $(BIN_DIR)/*.nexe $(NMF_FLAGS) -s $(BIN_DIR) - -run: all - /bin/cp -ar ../Resources/ . - $(NACL_SDK_ROOT)/tools/httpd.py --no_dir_check diff --git a/samples/Lua/HelloLua/proj.nacl/index.html b/samples/Lua/HelloLua/proj.nacl/index.html deleted file mode 100644 index cd401f1626..0000000000 --- a/samples/Lua/HelloLua/proj.nacl/index.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - cocos2dx HelloLua - - -

cocos2dx HelloLua

- - - -

-

- - diff --git a/samples/Lua/HelloLua/proj.nacl/main.cpp b/samples/Lua/HelloLua/proj.nacl/main.cpp deleted file mode 100644 index e4bce8fc75..0000000000 --- a/samples/Lua/HelloLua/proj.nacl/main.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "main.h" -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCInstance.h" -#include "CCModule.h" - -#include -#include -#include -#include -#include - -#include "fcntl.h" -#include "sys/stat.h" - -USING_NS_CC; - -AppDelegate g_app; - -void* cocos_main(void* arg) -{ - fprintf(stderr, "in cocos_main\n"); - CocosPepperInstance* instance = (CocosPepperInstance*)arg; - alSetPpapiInfo(instance->pp_instance(), pp::Module::Get()->get_browser_interface()); - fprintf(stderr, "calling application->run\n"); - int rtn = Application::getInstance()->run(); - fprintf(stderr, "app run returned: %d\n", rtn); - return NULL; -} - -namespace pp -{ - -Module* CreateModule() -{ - return new CocosPepperModule(); -} - -} diff --git a/samples/Lua/HelloLua/proj.nacl/main.h b/samples/Lua/HelloLua/proj.nacl/main.h deleted file mode 100644 index 7ad9d5c9e4..0000000000 --- a/samples/Lua/HelloLua/proj.nacl/main.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __MAIN_H__ diff --git a/samples/Lua/HelloLua/proj.tizen/.cproject b/samples/Lua/HelloLua/proj.tizen/.cproject deleted file mode 100644 index 082b16066d..0000000000 --- a/samples/Lua/HelloLua/proj.tizen/.cproject +++ /dev/null @@ -1,760 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.tizen/.project b/samples/Lua/HelloLua/proj.tizen/.project deleted file mode 100644 index 06b6c44cf6..0000000000 --- a/samples/Lua/HelloLua/proj.tizen/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - proj.tizen - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - - - ?children? - ?name?=outputEntries\|?children?=?name?=entry\\\\\\\|\\\|?name?=entry\\\\\\\|\\\|?name?=entry\\\\\\\|\\\|\|| - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - sbi-make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/${ProjName}/Debug-Tizen-Emulator} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - true - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - org.tizen.nativecpp.apichecker.core.builder - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.tizen.nativecpp.apichecker.core.tizenCppNature - - - - src/Classes - 2 - PARENT-1-PROJECT_LOC/Classes - - - - - 1373007589779 - - 26 - - org.eclipse.ui.ide.multiFilter - 1.0-projectRelativePath-matches-false-false-*/.tpk - - - - diff --git a/samples/Lua/HelloLua/proj.tizen/data/.gitkeep b/samples/Lua/HelloLua/proj.tizen/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/HelloLua/proj.tizen/lib/.gitkeep b/samples/Lua/HelloLua/proj.tizen/lib/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/HelloLua/proj.tizen/manifest.xml b/samples/Lua/HelloLua/proj.tizen/manifest.xml deleted file mode 100644 index 2518a97d98..0000000000 --- a/samples/Lua/HelloLua/proj.tizen/manifest.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - qc0zxC9NQi - 1.0.0 - C++App - - true - - - 2.2 - - - - - - HelloLua - - - mainmenu.png - - - - - diff --git a/samples/Lua/HelloLua/proj.tizen/res/.gitkeep b/samples/Lua/HelloLua/proj.tizen/res/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/HelloLua/proj.tizen/shared/data/.gitkeep b/samples/Lua/HelloLua/proj.tizen/shared/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/HelloLua/proj.tizen/shared/trusted/.gitkeep b/samples/Lua/HelloLua/proj.tizen/shared/trusted/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/HelloLua/proj.tizen/src/HelloLuaEntry.cpp b/samples/Lua/HelloLua/proj.tizen/src/HelloLuaEntry.cpp deleted file mode 100644 index 3ec1b2ae63..0000000000 --- a/samples/Lua/HelloLua/proj.tizen/src/HelloLuaEntry.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org -Copyright (c) 2013 Lee, Jae-Hong - -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. -****************************************************************************/ - -// -// This file contains the Tizen application entry point. -// -#include "../../Classes/AppDelegate.h" -#include "cocos2d.h" - -USING_NS_CC; -using namespace Tizen::Base; -using namespace Tizen::Base::Collection; - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -void -ApplicationInitialized(void) -{ - AppDelegate* pAppDelegate = new AppDelegate; - - auto eglView = EGLView::getInstance(); - eglView->setFrameSize(1280, 720); - - Application::getInstance()->run(); -} - -// -// The entry function of Tizen application called by the operating system. -// -_EXPORT_ int -OspMain(int argc, char *pArgv[]) -{ - AppLog("Application started."); - ArrayList args(SingleObjectDeleter); - args.Construct(); - for (int i = 0; i < argc; i++) - { - args.Add(new (std::nothrow) Tizen::Base::String(pArgv[i])); - } - - OspApplication::SetApplicationInitializedCallback(ApplicationInitialized); - OspApplication::SetScreenOrientation(Tizen::Ui::ORIENTATION_LANDSCAPE); - result r = Tizen::App::Application::Execute(OspApplication::CreateInstance, &args); - TryLog(r == E_SUCCESS, "[%s] Application execution failed", GetErrorMessage(r)); - AppLog("Application finished."); - - return static_cast(r); -} -#ifdef __cplusplus -} -#endif // __cplusplus diff --git a/samples/Lua/TestLua/proj.emscripten/Makefile b/samples/Lua/TestLua/proj.emscripten/Makefile deleted file mode 100644 index 89fbdf9a12..0000000000 --- a/samples/Lua/TestLua/proj.emscripten/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -EXECUTABLE = TestLua - -COCOS_ROOT = ../../../.. -INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/CocosDenshion/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support - -SOURCES = main.cpp ../Classes/AppDelegate.cpp - -SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so - -include $(COCOS_ROOT)/cocos2dx/proj.emscripten/cocos2dx.mk - -$(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - cp -a ../../../../samples/Cpp/TestCpp/Resources ../../../../samples/Lua/TestLua - cp -r ../../../../scripting/lua/script/ ../../../../samples/Lua/TestLua/Resources - $(CXX) $(CXXFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/samples/Lua/TestLua/proj.emscripten/main.cpp b/samples/Lua/TestLua/proj.emscripten/main.cpp deleted file mode 100644 index f114dbc8b7..0000000000 --- a/samples/Lua/TestLua/proj.emscripten/main.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - auto eglView = EGLView::getInstance(); - eglView->setFrameSize(800, 480); - return Application::getInstance()->run(); -} diff --git a/samples/Lua/TestLua/proj.nacl/Makefile b/samples/Lua/TestLua/proj.nacl/Makefile deleted file mode 100644 index 2895ab652c..0000000000 --- a/samples/Lua/TestLua/proj.nacl/Makefile +++ /dev/null @@ -1,69 +0,0 @@ -COCOS_ROOT = ../../../../ -COCOS2DX_PATH = $(COCOS_ROOT)/cocos2dx - -INCLUDES = -I.. \ - -I../Classes \ - -I$(COCOS_ROOT)/CocosDenshion/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support \ - -I$(NACL_SDK_ROOT)/include \ - -I$(COCOS_ROOT)/external \ - -I$(COCOS_ROOT)/external/chipmunk/include/chipmunk \ - -I$(COCOS_ROOT)/extensions \ - -I$(COCOS_ROOT)/extensions/Components - -SOURCES = main.cpp \ - ../Classes/AppDelegate.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaEngine.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaStack.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCLuaValue.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/LuaCocos2d.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/tolua_fix.c \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/CCBProxy.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/Lua_extensions_CCB.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/LuaOpengl.cpp \ - $(COCOS_ROOT)/scripting/lua/cocos2dx_support/LuaScrollView.cpp - -include $(COCOS2DX_PATH)/../extensions/proj.nacl/Makefile -SOURCES += $(addprefix $(COCOS_ROOT)/extensions/, $(EXTENSIONS_SOURCES)) - -include $(COCOS_ROOT)/cocos2dx/proj.nacl/cocos2dx.mk - -CXXFLAGS += -Wno-multichar -STATICLIBS += -llua -SHAREDLIBS += -lbox2d - -APP_NAME = TestLua -TARGET = $(BIN_DIR)/$(APP_NAME)_$(NACL_ARCH).nexe -NMF = $(BIN_DIR)/$(APP_NAME).nmf - -all: $(NMF) - -$(TARGET): $(OBJECTS) $(LIB_DIR)/libcocos2d.a $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(NACL_CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: $(COCOS_ROOT)/%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: $(COCOS_ROOT)/%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(NACL_CC) -MMD $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(NMF): $(TARGET) - $(NACL_SDK_ROOT)/tools/create_nmf.py -o $@ $(BIN_DIR)/*.nexe $(NMF_FLAGS) -s $(BIN_DIR) - -run: all - /bin/cp -ar ../Resources/ . - $(NACL_SDK_ROOT)/tools/httpd.py --no_dir_check diff --git a/samples/Lua/TestLua/proj.nacl/index.html b/samples/Lua/TestLua/proj.nacl/index.html deleted file mode 100644 index 1c999373ca..0000000000 --- a/samples/Lua/TestLua/proj.nacl/index.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - cocos2dx TestLua - - -

cocos2dx TestLua

- - - -

-

- - diff --git a/samples/Lua/TestLua/proj.nacl/main.cpp b/samples/Lua/TestLua/proj.nacl/main.cpp deleted file mode 100644 index e8571e92c5..0000000000 --- a/samples/Lua/TestLua/proj.nacl/main.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "main.h" -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCInstance.h" -#include "CCModule.h" - -#include -#include -#include -#include -#include - -USING_NS_CC; - -AppDelegate g_app; - -void* cocos_main(void* arg) -{ - fprintf(stderr, "in cocos_main\n"); - CocosPepperInstance* instance = (CocosPepperInstance*)arg; - alSetPpapiInfo(instance->pp_instance(), pp::Module::Get()->get_browser_interface()); - fprintf(stderr, "calling application->run\n"); - int rtn = Application::getInstance()->run(); - fprintf(stderr, "app run returned: %d\n", rtn); - return NULL; -} - -namespace pp -{ - -Module* CreateModule() -{ - return new CocosPepperModule(); -} - -} diff --git a/samples/Lua/TestLua/proj.nacl/main.h b/samples/Lua/TestLua/proj.nacl/main.h deleted file mode 100644 index 7ad9d5c9e4..0000000000 --- a/samples/Lua/TestLua/proj.nacl/main.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __MAIN_H__ diff --git a/samples/Lua/TestLua/proj.tizen/.cproject b/samples/Lua/TestLua/proj.tizen/.cproject deleted file mode 100644 index 173493f4c3..0000000000 --- a/samples/Lua/TestLua/proj.tizen/.cproject +++ /dev/null @@ -1,692 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/TestLua/proj.tizen/.project b/samples/Lua/TestLua/proj.tizen/.project deleted file mode 100644 index 93037cf80e..0000000000 --- a/samples/Lua/TestLua/proj.tizen/.project +++ /dev/null @@ -1,106 +0,0 @@ - - - proj.tizen - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - sbi-make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/${ProjName}/Debug-Tizen-Emulator} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - true - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - org.tizen.nativecpp.apichecker.core.builder - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.tizen.nativecpp.apichecker.core.tizenCppNature - - - - src/Classes - 2 - PARENT-2-PROJECT_LOC/HelloLua/Classes - - - - - 1373009863403 - - 26 - - org.eclipse.ui.ide.multiFilter - 1.0-projectRelativePath-matches-false-false-*/.tpk - - - - diff --git a/samples/Lua/TestLua/proj.tizen/data/.gitkeep b/samples/Lua/TestLua/proj.tizen/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/inc/.gitkeep b/samples/Lua/TestLua/proj.tizen/inc/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/lib/.gitkeep b/samples/Lua/TestLua/proj.tizen/lib/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/manifest.xml b/samples/Lua/TestLua/proj.tizen/manifest.xml deleted file mode 100644 index 689fd8cfa4..0000000000 --- a/samples/Lua/TestLua/proj.tizen/manifest.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - PHG8MiVSLl - 1.0.0 - C++App - - true - - - 2.2 - - - - - - TestLua - - - mainmenu.png - - - - - diff --git a/samples/Lua/TestLua/proj.tizen/res/.gitkeep b/samples/Lua/TestLua/proj.tizen/res/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/shared/data/.gitkeep b/samples/Lua/TestLua/proj.tizen/shared/data/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/shared/trusted/.gitkeep b/samples/Lua/TestLua/proj.tizen/shared/trusted/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/samples/Lua/TestLua/proj.tizen/src/TestLuaEntry.cpp b/samples/Lua/TestLua/proj.tizen/src/TestLuaEntry.cpp deleted file mode 100644 index 3ec1b2ae63..0000000000 --- a/samples/Lua/TestLua/proj.tizen/src/TestLuaEntry.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org -Copyright (c) 2013 Lee, Jae-Hong - -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. -****************************************************************************/ - -// -// This file contains the Tizen application entry point. -// -#include "../../Classes/AppDelegate.h" -#include "cocos2d.h" - -USING_NS_CC; -using namespace Tizen::Base; -using namespace Tizen::Base::Collection; - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -void -ApplicationInitialized(void) -{ - AppDelegate* pAppDelegate = new AppDelegate; - - auto eglView = EGLView::getInstance(); - eglView->setFrameSize(1280, 720); - - Application::getInstance()->run(); -} - -// -// The entry function of Tizen application called by the operating system. -// -_EXPORT_ int -OspMain(int argc, char *pArgv[]) -{ - AppLog("Application started."); - ArrayList args(SingleObjectDeleter); - args.Construct(); - for (int i = 0; i < argc; i++) - { - args.Add(new (std::nothrow) Tizen::Base::String(pArgv[i])); - } - - OspApplication::SetApplicationInitializedCallback(ApplicationInitialized); - OspApplication::SetScreenOrientation(Tizen::Ui::ORIENTATION_LANDSCAPE); - result r = Tizen::App::Application::Execute(OspApplication::CreateInstance, &args); - TryLog(r == E_SUCCESS, "[%s] Application execution failed", GetErrorMessage(r)); - AppLog("Application finished."); - - return static_cast(r); -} -#ifdef __cplusplus -} -#endif // __cplusplus diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 131372c79f..0000000000 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -0243fae13fc45728b6dfe8d61ab64782e34c145f \ No newline at end of file diff --git a/scripting/auto-generated b/scripting/auto-generated deleted file mode 160000 index 6f5bc7bbd0..0000000000 --- a/scripting/auto-generated +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6f5bc7bbd036c76e7c6be121573662099997a0a4 diff --git a/scripting/javascript/bindings/js/debugger/DevToolsUtils.js b/scripting/javascript/bindings/js/debugger/DevToolsUtils.js deleted file mode 100644 index 26d0597644..0000000000 --- a/scripting/javascript/bindings/js/debugger/DevToolsUtils.js +++ /dev/null @@ -1,133 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -function utf16to8(str) { - var out, i, len, c; - - out = ""; - len = str.length; - for(i = 0; i < len; i++) - { - c = str.charCodeAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - out += str.charAt(i); - } - else if (c > 0x07FF) - { - out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); - out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); - out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); - } - else - { - out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); - out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); - } - } - return out; -} - -function utf8to16(str) { - var out, i, len, c; - var char2, char3; - - out = ""; - len = str.length; - i = 0; - while(i < len) { c = str.charCodeAt(i++); switch(c >> 4) - { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - // 0xxxxxxx - out += str.charAt(i-1); - break; - case 12: case 13: - // 110x xxxx 10xx xxxx - char2 = str.charCodeAt(i++); - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = str.charCodeAt(i++); - char3 = str.charCodeAt(i++); - out += String.fromCharCode(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; - } - } - - return out; - } - -var dump = function(msg) { - log(msg); -}; - -/* General utilities used throughout devtools. */ - -/* Turn the error e into a string, without fail. */ -this.safeErrorString = function safeErrorString(aError) { - try { - var s = aError.toString(); - if (typeof s === "string") - return s; - } catch (ee) { } - - return ""; -} - -/** - * Report that |aWho| threw an exception, |aException|. - */ -this.reportException = function reportException(aWho, aException) { - let msg = aWho + " threw an exception: " + safeErrorString(aException); - if (aException.stack) { - msg += "\nCall stack:\n" + aException.stack; - } - - dump(msg + "\n"); - - // if (Components.utils.reportError) { - // /* - // * Note that the xpcshell test harness registers an observer for - // * console messages, so when we're running tests, this will cause - // * the test to quit. - // */ - // Components.utils.reportError(msg); - // } -} - -/** - * Given a handler function that may throw, return an infallible handler - * function that calls the fallible handler, and logs any exceptions it - * throws. - * - * @param aHandler function - * A handler function, which may throw. - * @param aName string - * A name for aHandler, for use in error messages. If omitted, we use - * aHandler.name. - * - * (SpiderMonkey does generate good names for anonymous functions, but we - * don't have a way to get at them from JavaScript at the moment.) - */ -this.makeInfallible = function makeInfallible(aHandler, aName) { - if (!aName) - aName = aHandler.name; - - return function (/* arguments */) { - try { - return aHandler.apply(this, arguments); - } catch (ex) { - let who = "Handler function"; - if (aName) { - who += " " + aName; - } - reportException(who, ex); - } - } -} diff --git a/scripting/javascript/bindings/js/debugger/README.md b/scripting/javascript/bindings/js/debugger/README.md deleted file mode 100644 index 9e1d7bebd0..0000000000 --- a/scripting/javascript/bindings/js/debugger/README.md +++ /dev/null @@ -1,54 +0,0 @@ -Remote Debugging By Using FireFox -================================= - -Requirement ------------ - -* Firefox: From v24 - -How To Use ----------- - -### Prepare ### - -Please refer to https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging . - -### Enable Debugger Support For Your JSB Project ### - -``` -bool AppDelegate::applicationDidFinishLaunching() -{ - ... - - ScriptingCore* sc = ScriptingCore::getInstance(); - sc->addRegisterCallback(register_all_cocos2dx); - sc->addRegisterCallback(register_all_cocos2dx_extension); - sc->addRegisterCallback(register_cocos2dx_js_extensions); - sc->addRegisterCallback(jsb_register_chipmunk); - sc->addRegisterCallback(register_all_cocos2dx_extension_manual); - sc->addRegisterCallback(register_CCBuilderReader); - sc->addRegisterCallback(jsb_register_system); - sc->addRegisterCallback(JSB_register_opengl); - - sc->start(); - -#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) - sc->enableDebugger(); // Enable debugger here -#endif - - ... -} -``` - -Run your game. - -### Open Firefox And Follow The Step As Follows ### - - -![pic 1](https://lh5.googleusercontent.com/-HoxLGBdV2J0/UlZ7ZoFUjyI/AAAAAAAAADM/68GDaCQ1vP0/s0-I/Firefox-Remote-Debug01.jpg) -![pic 2](https://lh6.googleusercontent.com/-7FDIHAYsKAY/UlZ7Yf8W-pI/AAAAAAAAAFQ/joG0AymnuBk/s0-I/Firefox-Remote-Debug02.jpg) -![pic 3](https://lh4.googleusercontent.com/-idvnMRGcGy8/UlZ7Wj6DDuI/AAAAAAAAAC0/L9IVyHLNqeQ/s0-I/Firefox-Remote-Debug04.jpg) -![pic 4](https://lh6.googleusercontent.com/-YuZj7JGAtFE/UlZ9DDGDczI/AAAAAAAAAEQ/D2qIedjP5FU/s0-I/Firefox-Remote-Debug04.png.png) -![pic 5](https://lh3.googleusercontent.com/-cdIcNa3jT5c/UlZ9uapf3OI/AAAAAAAAAEg/MGq3vLHsauw/s0-I/Firefox-Remote-Debug05.png) -![pic 6](https://lh5.googleusercontent.com/-T79-o5ylJKI/UlZ_JJQe3MI/AAAAAAAAAE8/F63fSVxlJKs/s0-I/Firefox-Remote-Debug06.png) - diff --git a/scripting/javascript/bindings/js/debugger/actors/root.js b/scripting/javascript/bindings/js/debugger/actors/root.js deleted file mode 100644 index aa0d85342b..0000000000 --- a/scripting/javascript/bindings/js/debugger/actors/root.js +++ /dev/null @@ -1,329 +0,0 @@ -/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -/* Root actor for the remote debugging protocol. */ - -/** - * Methods shared between RootActor and BrowserTabActor. - */ - -/** - * Populate |this._extraActors| as specified by |aFactories|, reusing whatever - * actors are already there. Add all actors in the final extra actors table to - * |aPool|. - * - * The root actor and the tab actor use this to instantiate actors that other - * parts of the browser have specified with DebuggerServer.addTabActor antd - * DebuggerServer.addGlobalActor. - * - * @param aFactories - * An object whose own property names are the names of properties to add to - * some reply packet (say, a tab actor grip or the "listTabs" response - * form), and whose own property values are actor constructor functions, as - * documented for addTabActor and addGlobalActor. - * - * @param this - * The BrowserRootActor or BrowserTabActor with which the new actors will - * be associated. It should support whatever API the |aFactories| - * constructor functions might be interested in, as it is passed to them. - * For the sake of CommonCreateExtraActors itself, it should have at least - * the following properties: - * - * - _extraActors - * An object whose own property names are factory table (and packet) - * property names, and whose values are no-argument actor constructors, - * of the sort that one can add to an ActorPool. - * - * - conn - * The DebuggerServerConnection in which the new actors will participate. - * - * - actorID - * The actor's name, for use as the new actors' parentID. - */ -function CommonCreateExtraActors(aFactories, aPool) { - // Walk over global actors added by extensions. - for (let name in aFactories) { - let actor = this._extraActors[name]; - if (!actor) { - actor = aFactories[name].bind(null, this.conn, this); - actor.prototype = aFactories[name].prototype; - actor.parentID = this.actorID; - this._extraActors[name] = actor; - } - aPool.addActor(actor); - } -} - -/** - * Append the extra actors in |this._extraActors|, constructed by a prior call - * to CommonCreateExtraActors, to |aObject|. - * - * @param aObject - * The object to which the extra actors should be added, under the - * property names given in the |aFactories| table passed to - * CommonCreateExtraActors. - * - * @param this - * The BrowserRootActor or BrowserTabActor whose |_extraActors| table we - * should use; see above. - */ -function CommonAppendExtraActors(aObject) { - for (let name in this._extraActors) { - let actor = this._extraActors[name]; - aObject[name] = actor.actorID; - } -} - -/** - * Create a remote debugging protocol root actor. - * - * @param aConnection - * The DebuggerServerConnection whose root actor we are constructing. - * - * @param aParameters - * The properties of |aParameters| provide backing objects for the root - * actor's requests; if a given property is omitted from |aParameters|, the - * root actor won't implement the corresponding requests or notifications. - * Supported properties: - * - * - tabList: a live list (see below) of tab actors. If present, the - * new root actor supports the 'listTabs' request, providing the live - * list's elements as its tab actors, and sending 'tabListChanged' - * notifications when the live list's contents change. One actor in - * this list must have a true '.selected' property. - * - * - globalActorFactories: an object |A| describing further actors to - * attach to the 'listTabs' reply. This is the type accumulated by - * DebuggerServer.addGlobalActor. For each own property |P| of |A|, - * the root actor adds a property named |P| to the 'listTabs' - * reply whose value is the name of an actor constructed by - * |A[P]|. - * - * - onShutdown: a function to call when the root actor is disconnected. - * - * Instance properties: - * - * - applicationType: the string the root actor will include as the - * "applicationType" property in the greeting packet. By default, this - * is "browser". - * - * Live lists: - * - * A "live list", as used for the |tabList|, is an object that presents a - * list of actors, and also notifies its clients of changes to the list. A - * live list's interface is two properties: - * - * - iterator: a method that returns an iterator. A for-of loop will call - * this method to obtain an iterator for the loop, so if LL is - * a live list, one can simply write 'for (i of LL) ...'. - * - * - onListChanged: a handler called, with no arguments, when the set of - * values the iterator would produce has changed since the last - * time 'iterator' was called. This may only be set to null or a - * callable value (one for which the typeof operator returns - * 'function'). (Note that the live list will not call the - * onListChanged handler until the list has been iterated over - * once; if nobody's seen the list in the first place, nobody - * should care if its contents have changed!) - * - * When the list changes, the list implementation should ensure that any - * actors yielded in previous iterations whose referents (tabs) still exist - * get yielded again in subsequent iterations. If the underlying referent - * is the same, the same actor should be presented for it. - * - * The root actor registers an 'onListChanged' handler on the appropriate - * list when it may need to send the client 'tabListChanged' notifications, - * and is careful to remove the handler whenever it does not need to send - * such notifications (including when it is disconnected). This means that - * live list implementations can use the state of the handler property (set - * or null) to install and remove observers and event listeners. - * - * Note that, as the only way for the root actor to see the members of the - * live list is to begin an iteration over the list, the live list need not - * actually produce any actors until they are reached in the course of - * iteration: alliterative lazy live lists. - */ -function RootActor(aConnection, aParameters) { - this.conn = aConnection; - this._parameters = aParameters; - this._onTabListChanged = this.onTabListChanged.bind(this); - this._extraActors = {}; -} - -RootActor.prototype = { - constructor: RootActor, - applicationType: "browser", - - /** - * Return a 'hello' packet as specified by the Remote Debugging Protocol. - */ - sayHello: function() { - return { - from: "root", - applicationType: this.applicationType, - /* This is not in the spec, but it's used by tests. */ - testConnectionPrefix: this.conn.prefix, - traits: { - sources: true - } - }; - }, - - /** - * Disconnects the actor from the browser window. - */ - disconnect: function() { - /* Tell the live lists we aren't watching any more. */ - if (this._parameters.tabList) { - this._parameters.tabList.onListChanged = null; - } - if (typeof this._parameters.onShutdown === 'function') { - this._parameters.onShutdown(); - } - this._extraActors = null; - }, - - /* The 'listTabs' request and the 'tabListChanged' notification. */ - - /** - * Handles the listTabs request. The actors will survive until at least - * the next listTabs request. - */ - onListTabs: function() { - - let tabList = this._parameters.tabList; - if (!tabList) { - return { from: "root", error: "noTabs", - message: "This root actor has no browser tabs." }; - } - - /* - * Walk the tab list, accumulating the array of tab actors for the - * reply, and moving all the actors to a new ActorPool. We'll - * replace the old tab actor pool with the one we build here, thus - * retiring any actors that didn't get listed again, and preparing any - * new actors to receive packets. - */ - let newActorPool = new ActorPool(this.conn); - let tabActorList = []; - let selected; - for (let tabActor of tabList) { - if (tabActor.selected) { - selected = tabActorList.length; - } - tabActor.parentID = this.actorID; - newActorPool.addActor(tabActor); - tabActorList.push(tabActor); - } - - /* DebuggerServer.addGlobalActor support: create actors. */ - this._createExtraActors(this._parameters.globalActorFactories, newActorPool); - - /* - * Drop the old actorID -> actor map. Actors that still mattered were - * added to the new map; others will go away. - */ - if (this._tabActorPool) { - this.conn.removeActorPool(this._tabActorPool); - } - this._tabActorPool = newActorPool; - this.conn.addActorPool(this._tabActorPool); - - let reply = { - "from": "root", - "selected": selected || 0, - "tabs": [actor.grip() for (actor of tabActorList)] - }; - - /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ - this._appendExtraActors(reply); - - /* - * Now that we're actually going to report the contents of tabList to - * the client, we're responsible for letting the client know if it - * changes. - */ - tabList.onListChanged = this._onTabListChanged; - - return reply; - }, - - onTabListChanged: function () { - this.conn.send({ from:"root", type:"tabListChanged" }); - /* It's a one-shot notification; no need to watch any more. */ - this._parameters.tabList.onListChanged = null; - }, - - /* This is not in the spec, but it's used by tests. */ - onEcho: (aRequest) => aRequest, - - /* Support for DebuggerServer.addGlobalActor. */ - _createExtraActors: CommonCreateExtraActors, - _appendExtraActors: CommonAppendExtraActors, - - /* ThreadActor hooks. */ - - /** - * Prepare to enter a nested event loop by disabling debuggee events. - */ - preNest: function() { - // Disable events in all open windows. - let e = windowMediator.getEnumerator(null); - while (e.hasMoreElements()) { - let win = e.getNext(); - let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); - windowUtils.suppressEventHandling(true); - windowUtils.suspendTimeouts(); - } - }, - - /** - * Prepare to exit a nested event loop by enabling debuggee events. - */ - postNest: function(aNestData) { - // Enable events in all open windows. - let e = windowMediator.getEnumerator(null); - while (e.hasMoreElements()) { - let win = e.getNext(); - let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); - windowUtils.resumeTimeouts(); - windowUtils.suppressEventHandling(false); - } - }, - - /* ChromeDebuggerActor hooks. */ - - /** - * Add the specified actor to the default actor pool connection, in order to - * keep it alive as long as the server is. This is used by breakpoints in the - * thread and chrome debugger actors. - * - * @param actor aActor - * The actor object. - */ - addToParentPool: function(aActor) { - this.conn.addActor(aActor); - }, - - /** - * Remove the specified actor from the default actor pool. - * - * @param BreakpointActor aActor - * The actor object. - */ - removeFromParentPool: function(aActor) { - this.conn.removeActor(aActor); - } -} - -RootActor.prototype.requestTypes = { - "listTabs": RootActor.prototype.onListTabs, - "echo": RootActor.prototype.onEcho -}; diff --git a/scripting/javascript/bindings/js/debugger/actors/script.js b/scripting/javascript/bindings/js/debugger/actors/script.js deleted file mode 100644 index 7ddade2b54..0000000000 --- a/scripting/javascript/bindings/js/debugger/actors/script.js +++ /dev/null @@ -1,2948 +0,0 @@ -/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -/** - * JSD2 actors. - */ -/** - * Creates a ThreadActor. - * - * ThreadActors manage a JSInspector object and manage execution/inspection - * of debuggees. - * - * @param aHooks object - * An object with preNest and postNest methods for calling when entering - * and exiting a nested event loop, addToParentPool and - * removeFromParentPool methods for handling the lifetime of actors that - * will outlive the thread, like breakpoints. - * @param aGlobal object [optional] - * An optional (for content debugging only) reference to the content - * window. - */ -function ThreadActor(aHooks, aGlobal) -{ - this._state = "detached"; - this._frameActors = []; - this._environmentActors = []; - this._hooks = aHooks; - this.global = aGlobal; - - this.findGlobals = this.globalManager.findGlobals.bind(this); - this.onNewGlobal = this.globalManager.onNewGlobal.bind(this); - this.onNewSource = this.onNewSource.bind(this); - - this._options = { - useSourceMaps: false - }; -} - -/** - * The breakpoint store must be shared across instances of ThreadActor so that - * page reloads don't blow away all of our breakpoints. - */ -ThreadActor._breakpointStore = {}; - -ThreadActor.prototype = { - actorPrefix: "context", - - get state() { return this._state; }, - get attached() this.state == "attached" || - this.state == "running" || - this.state == "paused", - - get _breakpointStore() { return ThreadActor._breakpointStore; }, - - get threadLifetimePool() { - if (!this._threadLifetimePool) { - this._threadLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._threadLifetimePool); - this._threadLifetimePool.objectActors = new WeakMap(); - } - return this._threadLifetimePool; - }, - - get sources() { - if (!this._sources) { - this._sources = new ThreadSources(this, this._options.useSourceMaps, - this._allowSource, this.onNewSource); - } - return this._sources; - }, - - clearDebuggees: function TA_clearDebuggees() { - if (this.dbg) { - this.dbg.removeAllDebuggees(); - } - this.conn.removeActorPool(this._threadLifetimePool || undefined); - this._threadLifetimePool = null; - this._sources = null; - }, - - /** - * Add a debuggee global to the Debugger object. - */ - addDebuggee: function TA_addDebuggee(aGlobal) { - try { - this.dbg.addDebuggee(aGlobal); - } catch (e) { - // Ignore attempts to add the debugger's compartment as a debuggee. - dumpn("Ignoring request to add the debugger's compartment as a debuggee"); - } - }, - - /** - * Initialize the Debugger. - */ - _initDebugger: function TA__initDebugger() { - this.dbg = new Debugger(); - this.dbg.uncaughtExceptionHook = this.uncaughtExceptionHook.bind(this); - this.dbg.onDebuggerStatement = this.onDebuggerStatement.bind(this); - this.dbg.onNewScript = this.onNewScript.bind(this); - this.dbg.onNewGlobalObject = this.globalManager.onNewGlobal.bind(this); - // Keep the debugger disabled until a client attaches. - this.dbg.enabled = this._state != "detached"; - }, - - /** - * Remove a debuggee global from the JSInspector. - */ - removeDebugee: function TA_removeDebuggee(aGlobal) { - try { - this.dbg.removeDebuggee(aGlobal); - } catch(ex) { - // XXX: This debuggee has code currently executing on the stack, - // we need to save this for later. - } - }, - - /** - * Add the provided window and all windows in its frame tree as debuggees. - */ - _addDebuggees: function TA__addDebuggees(aWindow) { - this.addDebuggee(aWindow); - let frames = aWindow.frames; - if (frames) { - for (let i = 0; i < frames.length; i++) { - this._addDebuggees(frames[i]); - } - } - }, - - /** - * An object that will be used by ThreadActors to tailor their behavior - * depending on the debugging context being required (chrome or content). - */ - globalManager: { - findGlobals: function TA_findGlobals() { - this._addDebuggees(this.global); - }, - - /** - * A function that the engine calls when a new global object has been - * created. - * - * @param aGlobal Debugger.Object - * The new global object that was created. - */ - onNewGlobal: function TA_onNewGlobal(aGlobal) { - // Content debugging only cares about new globals in the contant window, - // like iframe children. - if (aGlobal.hostAnnotations && - aGlobal.hostAnnotations.type == "document" && - aGlobal.hostAnnotations.element === this.global) { - this.addDebuggee(aGlobal); - // Notify the client. - this.conn.send({ - from: this.actorID, - type: "newGlobal", - // TODO: after bug 801084 lands see if we need to JSONify this. - hostAnnotations: aGlobal.hostAnnotations - }); - } - } - }, - - disconnect: function TA_disconnect() { - dumpn("in ThreadActor.prototype.disconnect"); - if (this._state == "paused") { - this.onResume(); - } - - this._state = "exited"; - - this.clearDebuggees(); - - if (!this.dbg) { - return; - } - this.dbg.enabled = false; - this.dbg = null; - }, - - /** - * Disconnect the debugger and put the actor in the exited state. - */ - exit: function TA_exit() { - this.disconnect(); - }, - - // Request handlers - onAttach: function TA_onAttach(aRequest) { - if (this.state === "exited") { - return { type: "exited" }; - } - - if (this.state !== "detached") { - return { error: "wrongState" }; - } - - this._state = "attached"; - - update(this._options, aRequest.options || {}); - - if (!this.dbg) { - this._initDebugger(); - } - this.findGlobals(); - this.dbg.enabled = true; - try { - // Put ourselves in the paused state. - let packet = this._paused(); - if (!packet) { - return { error: "notAttached" }; - } - packet.why = { type: "attached" }; - - this._restoreBreakpoints(); - - // Send the response to the attach request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._nest(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notAttached", message: e.toString() }; - } - }, - - onDetach: function TA_onDetach(aRequest) { - this.disconnect(); - dumpn("ThreadActor.prototype.onDetach: returning 'detached' packet"); - return { - type: "detached" - }; - }, - - onReconfigure: function TA_onReconfigure(aRequest) { - if (this.state == "exited") { - return { error: "wrongState" }; - } - - update(this._options, aRequest.options || {}); - // Clear existing sources, so they can be recreated on next access. - this._sources = null; - - return {}; - }, - - /** - * Pause the debuggee, by entering a nested event loop, and return a 'paused' - * packet to the client. - * - * @param Debugger.Frame aFrame - * The newest debuggee frame in the stack. - * @param object aReason - * An object with a 'type' property containing the reason for the pause. - * @param function onPacket - * Hook to modify the packet before it is sent. Feel free to return a - * promise. - */ - _pauseAndRespond: function TA__pauseAndRespond(aFrame, aReason, - onPacket=function (k) k) { - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - packet.why = aReason; - resolve(onPacket(packet)).then(this.conn.send.bind(this.conn)); - return this._nest(); - } catch(e) { - let msg = "Got an exception during TA__pauseAndRespond: " + e + - ": " + e.stack; - // Cu.reportError(msg); - dumpn(msg); - return undefined; - } - }, - - /** - * Handle a protocol request to resume execution of the debuggee. - */ - onResume: function TA_onResume(aRequest) { - if (this._state !== "paused") { - return { - error: "wrongState", - message: "Can't resume when debuggee isn't paused. Current state is '" - + this._state + "'" - }; - } - - // In case of multiple nested event loops (due to multiple debuggers open in - // different tabs or multiple debugger clients connected to the same tab) - // only allow resumption in a LIFO order. - if (DebuggerServer.xpcInspector.eventLoopNestLevel() > 1) { - log("DebuggerServer.xpcInspector.eventLoopNestLevel: "+DebuggerServer.xpcInspector.eventLoopNestLevel()); - // let lastNestRequestor = DebuggerServer.xpcInspector.lastNestRequestor; - // if (lastNestRequestor.connection != this.conn) { - // return { error: "wrongOrder", - // message: "trying to resume in the wrong order.", - // lastPausedUrl: lastNestRequestor.url }; - // } - } - - if (aRequest && aRequest.forceCompletion) { - // TODO: remove this when Debugger.Frame.prototype.pop is implemented in - // bug 736733. - if (typeof this.frame.pop != "function") { - return { error: "notImplemented", - message: "forced completion is not yet implemented." }; - } - - this.dbg.getNewestFrame().pop(aRequest.completionValue); - let packet = this._resumed(); - DebuggerServer.xpcInspector.exitNestedEventLoop(); - return { type: "resumeLimit", frameFinished: aRequest.forceCompletion }; - } - - if (aRequest && aRequest.resumeLimit) { - log("resumeLimit..."); - // Bind these methods because some of the hooks are called with 'this' - // set to the current frame. - let pauseAndRespond = (aFrame, onPacket=function (k) k) => { - this._pauseAndRespond(aFrame, { type: "resumeLimit" }, onPacket); - }; - let createValueGrip = this.createValueGrip.bind(this); - - let startFrame = this.youngestFrame; - let startLine; - if (this.youngestFrame.script) { - let offset = this.youngestFrame.offset; - startLine = this.youngestFrame.script.getOffsetLine(offset); - } - - // Define the JS hook functions for stepping. - - let onEnterFrame = aFrame => { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - return pauseAndRespond(aFrame); - }; - - let thread = this; - - let onPop = function TA_onPop(aCompletion) { - // onPop is called with 'this' set to the current frame. - if (thread.sources.isBlackBoxed(this.script.url)) { - return undefined; - } - - // Note that we're popping this frame; we need to watch for - // subsequent step events on its caller. - this.reportedPop = true; - - return pauseAndRespond(this, (aPacket) => { - aPacket.why.frameFinished = {}; - if (!aCompletion) { - aPacket.why.frameFinished.terminated = true; - } else if (aCompletion.hasOwnProperty("return")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.return); - } else if (aCompletion.hasOwnProperty("yield")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.yield); - } else { - aPacket.why.frameFinished.throw = createValueGrip(aCompletion.throw); - } - return aPacket; - }); - }; - - let onStep = function TA_onStep() { - // onStep is called with 'this' set to the current frame. - - if (thread.sources.isBlackBoxed(this.script.url)) { - return undefined; - } - - // If we've changed frame or line, then report that. - if (this !== startFrame || - (this.script && - this.script.getOffsetLine(this.offset) != startLine)) { - return pauseAndRespond(this); - } - - // Otherwise, let execution continue. - return undefined; - }; - - let steppingType = aRequest.resumeLimit.type; - if (["step", "next", "finish"].indexOf(steppingType) == -1) { - return { error: "badParameterType", - message: "Unknown resumeLimit type" }; - } - // Make sure there is still a frame on the stack if we are to continue - // stepping. - let stepFrame = this._getNextStepFrame(startFrame); - if (stepFrame) { - switch (steppingType) { - case "step": - log("--> step..."); - this.dbg.onEnterFrame = onEnterFrame; - // Fall through. - case "next": - log("--> next..."); - stepFrame.onStep = onStep; - stepFrame.onPop = onPop; - break; - case "finish": - log("--> finish..."); - stepFrame.onPop = onPop; - } - } - - } - - if (aRequest && aRequest.pauseOnExceptions) { - this.dbg.onExceptionUnwind = this.onExceptionUnwind.bind(this); - } - let packet = this._resumed(); - DebuggerServer.xpcInspector.exitNestedEventLoop(); - return packet; - }, - - /** - * Helper method that returns the next frame when stepping. - */ - _getNextStepFrame: function TA__getNextStepFrame(aFrame) { - let stepFrame = aFrame.reportedPop ? aFrame.older : aFrame; - if (!stepFrame || !stepFrame.script) { - stepFrame = null; - } - return stepFrame; - }, - - onClientEvaluate: function TA_onClientEvaluate(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Debuggee must be paused to evaluate code." }; - }; - - let frame = this._requestFrame(aRequest.frame); - if (!frame) { - return { error: "unknownFrame", - message: "Evaluation frame not found" }; - } - - if (!frame.environment) { - return { error: "notDebuggee", - message: "cannot access the environment of this frame." }; - }; - - // We'll clobber the youngest frame if the eval causes a pause, so - // save our frame now to be restored after eval returns. - // XXX: or we could just start using dbg.getNewestFrame() now that it - // works as expected. - let youngest = this.youngestFrame; - - // Put ourselves back in the running state and inform the client. - let resumedPacket = this._resumed(); - this.conn.send(resumedPacket); - - // Run the expression. - // XXX: test syntax errors - let completion = frame.eval(aRequest.expression); - - // Put ourselves back in the pause state. - let packet = this._paused(youngest); - packet.why = { type: "clientEvaluated", - frameFinished: this.createProtocolCompletionValue(completion) }; - - // Return back to our previous pause's event loop. - return packet; - }, - - onFrames: function TA_onFrames(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Stack frames are only available while the debuggee is paused."}; - } - - let start = aRequest.start ? aRequest.start : 0; - let count = aRequest.count; - - // Find the starting frame... - let frame = this.youngestFrame; - let i = 0; - while (frame && (i < start)) { - frame = frame.older; - i++; - } - - // Return request.count frames, or all remaining - // frames if count is not defined. - let frames = []; - let promises = []; - for (; frame && (!count || i < (start + count)); i++, frame=frame.older) { - let form = this._createFrameActor(frame).form(); - form.depth = i; - frames.push(form); - - let promise = this.sources.getOriginalLocation(form.where.url, - form.where.line) - .then(function (aOrigLocation) { - form.where = aOrigLocation; - }); - promises.push(promise); - } - - return all(promises).then(function () { - return { frames: frames }; - }); - }, - - onReleaseMany: function TA_onReleaseMany(aRequest) { - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - let res; - for each (let actorID in aRequest.actors) { - let actor = this.threadLifetimePool.get(actorID); - if (!actor) { - if (!res) { - res = { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - continue; - } - actor.onRelease(); - } - return res ? res : {}; - }, - - /** - * Handle a protocol request to set a breakpoint. - */ - onSetBreakpoint: function TA_onSetBreakpoint(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Breakpoints can only be set while the debuggee is paused."}; - } - - // XXX: `originalColumn` is never used. See bug 827639. - let { url: originalSource, - line: originalLine, - column: originalColumn } = aRequest.location; - - let locationPromise = this.sources.getGeneratedLocation(originalSource, - originalLine) - return locationPromise.then((aLocation) => { - let line = aLocation.line; - if (this.dbg.findScripts({ url: aLocation.url }).length == 0 || - line < 0 || - line == null) { - return { error: "noScript" }; - } - - // Add the breakpoint to the store for later reuse, in case it belongs to a - // script that hasn't appeared yet. - if (!this._breakpointStore[aLocation.url]) { - this._breakpointStore[aLocation.url] = []; - } - let scriptBreakpoints = this._breakpointStore[aLocation.url]; - scriptBreakpoints[line] = { - url: aLocation.url, - line: line, - column: aLocation.column - }; - - let response = this._setBreakpoint(aLocation); - // If the original location of our generated location is different from - // the original location we attempted to set the breakpoint on, we will - // need to know so that we can set actualLocation on the response. - let originalLocation = this.sources.getOriginalLocation(aLocation.url, - aLocation.line); - - return all([response, originalLocation]) - .then(([aResponse, {url, line}]) => { - if (aResponse.actualLocation) { - let actualOrigLocation = this.sources.getOriginalLocation( - aResponse.actualLocation.url, aResponse.actualLocation.line); - return actualOrigLocation.then(function ({ url, line }) { - if (url !== originalSource || line !== originalLine) { - aResponse.actualLocation = { url: url, line: line }; - } - return aResponse; - }); - } - - if (url !== originalSource || line !== originalLine) { - aResponse.actualLocation = { url: url, line: line }; - } - - return aResponse; - }); - }); - }, - - /** - * Set a breakpoint using the jsdbg2 API. If the line on which the breakpoint - * is being set contains no code, then the breakpoint will slide down to the - * next line that has runnable code. In this case the server breakpoint cache - * will be updated, so callers that iterate over the breakpoint cache should - * take that into account. - * - * @param object aLocation - * The location of the breakpoint as specified in the protocol. - */ - _setBreakpoint: function TA__setBreakpoint(aLocation) { - let breakpoints = this._breakpointStore[aLocation.url]; - - // Get or create the breakpoint actor for the given location - let actor; - if (breakpoints[aLocation.line].actor) { - actor = breakpoints[aLocation.line].actor; - } else { - actor = breakpoints[aLocation.line].actor = new BreakpointActor(this, { - url: aLocation.url, - line: aLocation.line - }); - this._hooks.addToParentPool(actor); - } - - // Find all scripts matching the given location - let scripts = this.dbg.findScripts(aLocation); - if (scripts.length == 0) { - return { - error: "noScript", - actor: actor.actorID - }; - } - - /** - * For each script, if the given line has at least one entry point, set - * breakpoint on the bytecode offet for each of them. - */ - let found = false; - for (let script of scripts) { - let offsets = script.getLineOffsets(aLocation.line); - if (offsets.length > 0) { - for (let offset of offsets) { - script.setBreakpoint(offset, actor); - } - actor.addScript(script, this); - found = true; - } - } - if (found) { - return { - actor: actor.actorID - }; - } - - /** - * If we get here, no breakpoint was set. This is because the given line - * has no entry points, for example because it is empty. As a fallback - * strategy, we try to set the breakpoint on the smallest line greater - * than or equal to the given line that as at least one entry point. - */ - - // Find all innermost scripts matching the given location - let scripts = this.dbg.findScripts({ - url: aLocation.url, - line: aLocation.line, - innermost: true - }); - - /** - * For each innermost script, look for the smallest line greater than or - * equal to the given line that has one or more entry points. If found, set - * a breakpoint on the bytecode offset for each of its entry points. - */ - let actualLocation; - let found = false; - for (let script of scripts) { - let offsets = script.getAllOffsets(); - for (let line = aLocation.line; line < offsets.length; ++line) { - if (offsets[line]) { - for (let offset of offsets[line]) { - script.setBreakpoint(offset, actor); - } - actor.addScript(script, this); - if (!actualLocation) { - actualLocation = { - url: aLocation.url, - line: line, - column: 0 - }; - } - found = true; - break; - } - } - } - if (found) { - if (breakpoints[actualLocation.line] && - breakpoints[actualLocation.line].actor) { - /** - * We already have a breakpoint actor for the actual location, so - * actor we created earlier is now redundant. Delete it, update the - * breakpoint store, and return the actor for the actual location. - */ - actor.onDelete(); - delete breakpoints[aLocation.line]; - return { - actor: breakpoints[actualLocation.line].actor.actorID, - actualLocation: actualLocation - }; - } else { - /** - * We don't have a breakpoint actor for the actual location yet. - * Instead or creating a new actor, reuse the actor we created earlier, - * and update the breakpoint store. - */ - actor.location = actualLocation; - breakpoints[actualLocation.line] = breakpoints[aLocation.line]; - delete breakpoints[aLocation.line]; - // WARNING: This overwrites aLocation.line - breakpoints[actualLocation.line].line = actualLocation.line; - return { - actor: actor.actorID, - actualLocation: actualLocation - }; - } - } - - /** - * If we get here, no line matching the given line was found, so just - * epically. - */ - return { - error: "noCodeAtLineColumn", - actor: actor.actorID - }; - }, - - /** - * Get the script and source lists from the debugger. - * - * TODO bug 637572: we should be dealing with sources directly, not inferring - * them through scripts. - */ - _discoverSources: function TA__discoverSources() { - // Only get one script per url. - let scriptsByUrl = {}; - for (let s of this.dbg.findScripts()) { - scriptsByUrl[s.url] = s; - } - - return all([this.sources.sourcesForScript(scriptsByUrl[s]) - for (s of Object.keys(scriptsByUrl))]); - }, - - onSources: function TA_onSources(aRequest) { - return this._discoverSources().then(() => { - return { - sources: [s.form() for (s of this.sources.iter())] - }; - }); - }, - - /** - * Disassociate all breakpoint actors from their scripts and clear the - * breakpoint handlers. This method can be used when the thread actor intends - * to keep the breakpoint store, but needs to clear any actual breakpoints, - * e.g. due to a page navigation. This way the breakpoint actors' script - * caches won't hold on to the Debugger.Script objects leaking memory. - */ - disableAllBreakpoints: function () { - for (let url in this._breakpointStore) { - for (let line in this._breakpointStore[url]) { - let bp = this._breakpointStore[url][line]; - bp.actor.removeScripts(); - } - } - }, - - /** - * Handle a protocol request to pause the debuggee. - */ - onInterrupt: function TA_onInterrupt(aRequest) { - if (this.state == "exited") { - return { type: "exited" }; - } else if (this.state == "paused") { - // TODO: return the actual reason for the existing pause. - return { type: "paused", why: { type: "alreadyPaused" } }; - } else if (this.state != "running") { - return { error: "wrongState", - message: "Received interrupt request in " + this.state + - " state." }; - } - - try { - // Put ourselves in the paused state. - let packet = this._paused(); - if (!packet) { - return { error: "notInterrupted" }; - } - packet.why = { type: "interrupted" }; - - // Send the response to the interrupt request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._nest(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notInterrupted", message: e.toString() }; - } - }, - - /** - * Return the Debug.Frame for a frame mentioned by the protocol. - */ - _requestFrame: function TA_requestFrame(aFrameID) { - if (!aFrameID) { - return this.youngestFrame; - } - - if (this._framePool.has(aFrameID)) { - return this._framePool.get(aFrameID).frame; - } - - return undefined; - }, - - _paused: function TA_paused(aFrame) { - // We don't handle nested pauses correctly. Don't try - if we're - // paused, just continue running whatever code triggered the pause. - // We don't want to actually have nested pauses (although we - // have nested event loops). If code runs in the debuggee during - // a pause, it should cause the actor to resume (dropping - // pause-lifetime actors etc) and then repause when complete. - - if (this.state === "paused") { - return undefined; - } - - // Clear stepping hooks. - this.dbg.onEnterFrame = undefined; - this.dbg.onExceptionUnwind = undefined; - if (aFrame) { - aFrame.onStep = undefined; - aFrame.onPop = undefined; - } - - this._state = "paused"; - - // Save the pause frame (if any) as the youngest frame for - // stack viewing. - this.youngestFrame = aFrame; - - // Create the actor pool that will hold the pause actor and its - // children. - dbg_assert(!this._pausePool); - this._pausePool = new ActorPool(this.conn); - this.conn.addActorPool(this._pausePool); - - // Give children of the pause pool a quick link back to the - // thread... - this._pausePool.threadActor = this; - - // Create the pause actor itself... - dbg_assert(!this._pauseActor); - this._pauseActor = new PauseActor(this._pausePool); - this._pausePool.addActor(this._pauseActor); - - // Update the list of frames. - let poppedFrames = this._updateFrames(); - - // Send off the paused packet and spin an event loop. - let packet = { from: this.actorID, - type: "paused", - actor: this._pauseActor.actorID }; - if (aFrame) { - packet.frame = this._createFrameActor(aFrame).form(); - } - - if (poppedFrames) { - packet.poppedFrames = poppedFrames; - } - - return packet; - }, - - _nest: function TA_nest() { - if (this._hooks.preNest) { - var nestData = this._hooks.preNest(); - } - - let requestor = Object.create(null); - requestor.url = this._hooks.url; - requestor.connection = this.conn; - DebuggerServer.xpcInspector.enterNestedEventLoop(requestor); - - dbg_assert(this.state === "running"); - - if (this._hooks.postNest) { - this._hooks.postNest(nestData) - } - - // "continue" resumption value. - return undefined; - }, - - _resumed: function TA_resumed() { - this._state = "running"; - - // Drop the actors in the pause actor pool. - this.conn.removeActorPool(this._pausePool); - - this._pausePool = null; - this._pauseActor = null; - this.youngestFrame = null; - - return { from: this.actorID, type: "resumed" }; - }, - - /** - * Expire frame actors for frames that have been popped. - * - * @returns A list of actor IDs whose frames have been popped. - */ - _updateFrames: function TA_updateFrames() { - let popped = []; - - // Create the actor pool that will hold the still-living frames. - let framePool = new ActorPool(this.conn); - let frameList = []; - - for each (let frameActor in this._frameActors) { - if (frameActor.frame.live) { - framePool.addActor(frameActor); - frameList.push(frameActor); - } else { - popped.push(frameActor.actorID); - } - } - - // Remove the old frame actor pool, this will expire - // any actors that weren't added to the new pool. - if (this._framePool) { - this.conn.removeActorPool(this._framePool); - } - - this._frameActors = frameList; - this._framePool = framePool; - this.conn.addActorPool(framePool); - - return popped; - }, - - _createFrameActor: function TA_createFrameActor(aFrame) { - if (aFrame.actor) { - return aFrame.actor; - } - - let actor = new FrameActor(aFrame, this); - this._frameActors.push(actor); - this._framePool.addActor(actor); - aFrame.actor = actor; - - return actor; - }, - - /** - * Create and return an environment actor that corresponds to the provided - * Debugger.Environment. - * @param Debugger.Environment aEnvironment - * The lexical environment we want to extract. - * @param object aPool - * The pool where the newly-created actor will be placed. - * @return The EnvironmentActor for aEnvironment or undefined for host - * functions or functions scoped to a non-debuggee global. - */ - createEnvironmentActor: - function TA_createEnvironmentActor(aEnvironment, aPool) { - if (!aEnvironment) { - return undefined; - } - - if (aEnvironment.actor) { - return aEnvironment.actor; - } - - let actor = new EnvironmentActor(aEnvironment, this); - this._environmentActors.push(actor); - aPool.addActor(actor); - aEnvironment.actor = actor; - - return actor; - }, - - /** - * Create a grip for the given debuggee value. If the value is an - * object, will create an actor with the given lifetime. - */ - createValueGrip: function TA_createValueGrip(aValue, aPool=false) { - if (!aPool) { - aPool = this._pausePool; - } - let type = typeof(aValue); - - if (type === "string" && this._stringIsLong(aValue)) { - return this.longStringGrip(aValue, aPool); - } - - if (type === "boolean" || type === "string" || type === "number") { - return aValue; - } - - if (aValue === null) { - return { type: "null" }; - } - - if (aValue === undefined) { - return { type: "undefined" } - } - - if (typeof(aValue) === "object") { - return this.objectGrip(aValue, aPool); - } - - dbg_assert(false, "Failed to provide a grip for: " + aValue); - return null; - }, - - /** - * Return a protocol completion value representing the given - * Debugger-provided completion value. - */ - createProtocolCompletionValue: - function TA_createProtocolCompletionValue(aCompletion) { - let protoValue = {}; - if ("return" in aCompletion) { - protoValue.return = this.createValueGrip(aCompletion.return); - } else if ("yield" in aCompletion) { - protoValue.return = this.createValueGrip(aCompletion.yield); - } else if ("throw" in aCompletion) { - protoValue.throw = this.createValueGrip(aCompletion.throw); - } else { - protoValue.terminated = true; - } - return protoValue; - }, - - /** - * Create a grip for the given debuggee object. - * - * @param aValue Debugger.Object - * The debuggee object value. - * @param aPool ActorPool - * The actor pool where the new object actor will be added. - */ - objectGrip: function TA_objectGrip(aValue, aPool) { - if (!aPool.objectActors) { - aPool.objectActors = new WeakMap(); - } - - if (aPool.objectActors.has(aValue)) { - return aPool.objectActors.get(aValue).grip(); - } else if (this.threadLifetimePool.objectActors.has(aValue)) { - return this.threadLifetimePool.objectActors.get(aValue).grip(); - } - - let actor = new PauseScopedObjectActor(aValue, this); - aPool.addActor(actor); - aPool.objectActors.set(aValue, actor); - return actor.grip(); - }, - - /** - * Create a grip for the given debuggee object with a pause lifetime. - * - * @param aValue Debugger.Object - * The debuggee object value. - */ - pauseObjectGrip: function TA_pauseObjectGrip(aValue) { - if (!this._pausePool) { - throw "Object grip requested while not paused."; - } - - return this.objectGrip(aValue, this._pausePool); - }, - - /** - * Extend the lifetime of the provided object actor to thread lifetime. - * - * @param aActor object - * The object actor. - */ - threadObjectGrip: function TA_threadObjectGrip(aActor) { - // We want to reuse the existing actor ID, so we just remove it from the - // current pool's weak map and then let pool.addActor do the rest. - aActor.registeredPool.objectActors.delete(aActor.obj); - this.threadLifetimePool.addActor(aActor); - this.threadLifetimePool.objectActors.set(aActor.obj, aActor); - }, - - /** - * Handle a protocol request to promote multiple pause-lifetime grips to - * thread-lifetime grips. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrips: function OA_onThreadGrips(aRequest) { - if (this.state != "paused") { - return { error: "wrongState" }; - } - - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - for (let actorID of aRequest.actors) { - let actor = this._pausePool.get(actorID); - if (actor) { - this.threadObjectGrip(actor); - } - } - return {}; - }, - - /** - * Create a grip for the given string. - * - * @param aString String - * The string we are creating a grip for. - * @param aPool ActorPool - * The actor pool where the new actor will be added. - */ - longStringGrip: function TA_longStringGrip(aString, aPool) { - if (!aPool.longStringActors) { - aPool.longStringActors = {}; - } - - if (aPool.longStringActors.hasOwnProperty(aString)) { - return aPool.longStringActors[aString].grip(); - } - - let actor = new LongStringActor(aString, this); - aPool.addActor(actor); - aPool.longStringActors[aString] = actor; - return actor.grip(); - }, - - /** - * Create a long string grip that is scoped to a pause. - * - * @param aString String - * The string we are creating a grip for. - */ - pauseLongStringGrip: function TA_pauseLongStringGrip (aString) { - return this.longStringGrip(aString, this._pausePool); - }, - - /** - * Create a long string grip that is scoped to a thread. - * - * @param aString String - * The string we are creating a grip for. - */ - threadLongStringGrip: function TA_pauseLongStringGrip (aString) { - return this.longStringGrip(aString, this._threadLifetimePool); - }, - - /** - * Returns true if the string is long enough to use a LongStringActor instead - * of passing the value directly over the protocol. - * - * @param aString String - * The string we are checking the length of. - */ - _stringIsLong: function TA__stringIsLong(aString) { - return aString.length >= DebuggerServer.LONG_STRING_LENGTH; - }, - - // JS Debugger API hooks. - - /** - * A function that the engine calls when a call to a debug event hook, - * breakpoint handler, watchpoint handler, or similar function throws some - * exception. - * - * @param aException exception - * The exception that was thrown in the debugger code. - */ - uncaughtExceptionHook: function TA_uncaughtExceptionHook(aException) { - dumpn("Got an exception: " + aException.message + "\n" + aException.stack); - }, - - /** - * A function that the engine calls when a debugger statement has been - * executed in the specified frame. - * - * @param aFrame Debugger.Frame - * The stack frame that contained the debugger statement. - */ - onDebuggerStatement: function TA_onDebuggerStatement(aFrame) { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - return this._pauseAndRespond(aFrame, { type: "debuggerStatement" }); - }, - - /** - * A function that the engine calls when an exception has been thrown and has - * propagated to the specified frame. - * - * @param aFrame Debugger.Frame - * The youngest remaining stack frame. - * @param aValue object - * The exception that was thrown. - */ - onExceptionUnwind: function TA_onExceptionUnwind(aFrame, aValue) { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - - packet.why = { type: "exception", - exception: this.createValueGrip(aValue) }; - this.conn.send(packet); - return this._nest(); - } catch(e) { - log("Got an exception during TA_onExceptionUnwind: " + e + - ": " + e.stack); - return undefined; - } - }, - - /** - * A function that the engine calls when a new script has been loaded into the - * scope of the specified debuggee global. - * - * @param aScript Debugger.Script - * The source script that has been loaded into a debuggee compartment. - * @param aGlobal Debugger.Object - * A Debugger.Object instance whose referent is the global object. - */ - onNewScript: function TA_onNewScript(aScript, aGlobal) { - this._addScript(aScript); - this.sources.sourcesForScript(aScript); - }, - - onNewSource: function TA_onNewSource(aSource) { - this.conn.send({ - from: this.actorID, - type: "newSource", - source: aSource.form() - }); - }, - - /** - * Check if scripts from the provided source URL are allowed to be stored in - * the cache. - * - * @param aSourceUrl String - * The url of the script's source that will be stored. - * @returns true, if the script can be added, false otherwise. - */ - _allowSource: function TA__allowSource(aSourceUrl) { - // Ignore anything we don't have a URL for (eval scripts, for example). - if (!aSourceUrl) - return false; - // Ignore XBL bindings for content debugging. - if (aSourceUrl.indexOf("chrome://") == 0) { - return false; - } - // Ignore about:* pages for content debugging. - if (aSourceUrl.indexOf("about:") == 0) { - return false; - } - return true; - }, - - /** - * Restore any pre-existing breakpoints to the scripts that we have access to. - */ - _restoreBreakpoints: function TA__restoreBreakpoints() { - for (let s of this.dbg.findScripts()) { - this._addScript(s); - } - }, - - /** - * Add the provided script to the server cache. - * - * @param aScript Debugger.Script - * The source script that will be stored. - * @returns true, if the script was added; false otherwise. - */ - _addScript: function TA__addScript(aScript) { - if (!this._allowSource(aScript.url)) { - return false; - } - - // Set any stored breakpoints. - let existing = this._breakpointStore[aScript.url]; - if (existing) { - let endLine = aScript.startLine + aScript.lineCount - 1; - // Iterate over the lines backwards, so that sliding breakpoints don't - // affect the loop. - for (let line = existing.length - 1; line >= aScript.startLine; line--) { - let bp = existing[line]; - // Only consider breakpoints that are not already associated with - // scripts, and limit search to the line numbers contained in the new - // script. - if (bp && !bp.actor.scripts.length && line <= endLine) { - this._setBreakpoint(bp); - } - } - } - return true; - }, - -}; - -ThreadActor.prototype.requestTypes = { - "attach": ThreadActor.prototype.onAttach, - "detach": ThreadActor.prototype.onDetach, - "reconfigure": ThreadActor.prototype.onReconfigure, - "resume": ThreadActor.prototype.onResume, - "clientEvaluate": ThreadActor.prototype.onClientEvaluate, - "frames": ThreadActor.prototype.onFrames, - "interrupt": ThreadActor.prototype.onInterrupt, - "releaseMany": ThreadActor.prototype.onReleaseMany, - "setBreakpoint": ThreadActor.prototype.onSetBreakpoint, - "sources": ThreadActor.prototype.onSources, - "threadGrips": ThreadActor.prototype.onThreadGrips -}; - - -/** - * Creates a PauseActor. - * - * PauseActors exist for the lifetime of a given debuggee pause. Used to - * scope pause-lifetime grips. - * - * @param ActorPool aPool - * The actor pool created for this pause. - */ -function PauseActor(aPool) -{ - this.pool = aPool; -} - -PauseActor.prototype = { - actorPrefix: "pause" -}; - - -/** - * A base actor for any actors that should only respond receive messages in the - * paused state. Subclasses may expose a `threadActor` which is used to help - * determine when we are in a paused state. Subclasses should set their own - * "constructor" property if they want better error messages. You should never - * instantiate a PauseScopedActor directly, only through subclasses. - */ -function PauseScopedActor() -{ -} - -/** - * A function decorator for creating methods to handle protocol messages that - * should only be received while in the paused state. - * - * @param aMethod Function - * The function we are decorating. - */ -PauseScopedActor.withPaused = function PSA_withPaused(aMethod) { - return function () { - if (this.isPaused()) { - return aMethod.apply(this, arguments); - } else { - return this._wrongState(); - } - }; -}; - -PauseScopedActor.prototype = { - - /** - * Returns true if we are in the paused state. - */ - isPaused: function PSA_isPaused() { - // When there is not a ThreadActor available (like in the webconsole) we - // have to be optimistic and assume that we are paused so that we can - // respond to requests. - return this.threadActor ? this.threadActor.state === "paused" : true; - }, - - /** - * Returns the wrongState response packet for this actor. - */ - _wrongState: function PSA_wrongState() { - return { - error: "wrongState", - message: this.constructor.name + - " actors can only be accessed while the thread is paused." - }; - } -}; - - -/** - * A SourceActor provides information about the source of a script. - * - * @param aUrl String - * The url of the source we are representing. - * @param aThreadActor ThreadActor - * The current thread actor. - * @param aSourceMap SourceMapConsumer - * Optional. The source map that introduced this source, if available. - */ -function SourceActor(aUrl, aThreadActor, aSourceMap=null) { - this._threadActor = aThreadActor; - this._url = aUrl; - this._sourceMap = aSourceMap; -} - -SourceActor.prototype = { - constructor: SourceActor, - actorPrefix: "source", - - get threadActor() this._threadActor, - get url() this._url, - - form: function SA_form() { - return { - actor: this.actorID, - url: this._url, - isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url) - // TODO bug 637572: introductionScript - }; - }, - - disconnect: function LSA_disconnect() { - if (this.registeredPool && this.registeredPool.sourceActors) { - delete this.registeredPool.sourceActors[this.actorID]; - } - }, - - /** - * Handler for the "source" packet. - */ - onSource: function SA_onSource(aRequest) { - let sourceContent = null; - if (this._sourceMap) { - sourceContent = this._sourceMap.sourceContentFor(this._url); - } - - if (sourceContent) { - return { - from: this.actorID, - source: this.threadActor.createValueGrip( - sourceContent, this.threadActor.threadLifetimePool) - }; - } - - // XXX bug 865252: Don't load from the cache if this is a source mapped - // source because we can't guarantee that the cache has the most up to date - // content for this source like we can if it isn't source mapped. - return fetch(this._url, { loadFromCache: !this._sourceMap }) - .then((aSource) => { - return this.threadActor.createValueGrip( - aSource, this.threadActor.threadLifetimePool); - }) - .then((aSourceGrip) => { - return { - from: this.actorID, - source: aSourceGrip - }; - }, (aError) => { - let msg = "Got an exception during SA_onSource: " + aError + - "\n" + aError.stack; - // Cu.reportError(msg); - dumpn(msg); - return { - "from": this.actorID, - "error": "loadSourceError", - "message": "Could not load the source for " + this._url + "." - }; - }); - }, - - /** - * Handler for the "blackbox" packet. - */ - onBlackBox: function SA_onBlackBox(aRequest) { - this.threadActor.sources.blackBox(this.url); - let packet = { - from: this.actorID - }; - if (this.threadActor.state == "paused" - && this.threadActor.youngestFrame - && this.threadActor.youngestFrame.script.url == this.url) { - packet.pausedInSource = true; - } - return packet; - }, - - /** - * Handler for the "unblackbox" packet. - */ - onUnblackBox: function SA_onUnblackBox(aRequest) { - this.threadActor.sources.unblackBox(this.url); - return { - from: this.actorID - }; - } -}; - -SourceActor.prototype.requestTypes = { - "source": SourceActor.prototype.onSource, - "blackbox": SourceActor.prototype.onBlackBox, - "unblackbox": SourceActor.prototype.onUnblackBox -}; - - -/** - * Creates an actor for the specified object. - * - * @param aObj Debugger.Object - * The debuggee object. - * @param aThreadActor ThreadActor - * The parent thread actor for this object. - */ -function ObjectActor(aObj, aThreadActor) -{ - this.obj = aObj; - this.threadActor = aThreadActor; -} - -ObjectActor.prototype = { - actorPrefix: "obj", - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function OA_grip() { - let g = { - "type": "object", - "class": this.obj.class, - "actor": this.actorID, - "extensible": this.obj.isExtensible(), - "frozen": this.obj.isFrozen(), - "sealed": this.obj.isSealed() - }; - - // Add additional properties for functions. - if (this.obj.class === "Function") { - if (this.obj.name) { - g.name = this.obj.name; - } else if (this.obj.displayName) { - g.displayName = this.obj.displayName; - } - - // Check if the developer has added a de-facto standard displayName - // property for us to use. - let desc = this.obj.getOwnPropertyDescriptor("displayName"); - if (desc && desc.value && typeof desc.value == "string") { - g.userDisplayName = this.threadActor.createValueGrip(desc.value); - } - } - - return g; - }, - - /** - * Releases this actor from the pool. - */ - release: function OA_release() { - if (this.registeredPool.objectActors) { - this.registeredPool.objectActors.delete(this.obj); - } - this.registeredPool.removeActor(this); - }, - - /** - * Handle a protocol request to provide the names of the properties defined on - * the object and not its prototype. - * - * @param aRequest object - * The protocol request object. - */ - onOwnPropertyNames: function OA_onOwnPropertyNames(aRequest) { - return { from: this.actorID, - ownPropertyNames: this.obj.getOwnPropertyNames() }; - }, - - /** - * Handle a protocol request to provide the prototype and own properties of - * the object. - * - * @param aRequest object - * The protocol request object. - */ - onPrototypeAndProperties: function OA_onPrototypeAndProperties(aRequest) { - let ownProperties = Object.create(null); - let names; - try { - names = this.obj.getOwnPropertyNames(); - } catch (ex) { - // The above can throw if this.obj points to a dead object. - // TODO: we should use Cu.isDeadWrapper() - see bug 885800. - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(null), - ownProperties: ownProperties, - safeGetterValues: Object.create(null) }; - } - for (let name of names) { - ownProperties[name] = this._propertyDescriptor(name); - } - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(this.obj.proto), - ownProperties: ownProperties, - safeGetterValues: this._findSafeGetterValues(ownProperties) }; - }, - - /** - * Find the safe getter values for the current Debugger.Object, |this.obj|. - * - * @private - * @param object aOwnProperties - * The object that holds the list of known ownProperties for - * |this.obj|. - * @return object - * An object that maps property names to safe getter descriptors as - * defined by the remote debugging protocol. - */ - _findSafeGetterValues: function OA__findSafeGetterValues(aOwnProperties) - { - let safeGetterValues = Object.create(null); - let obj = this.obj; - let level = 0; - - while (obj) { - let getters = this._findSafeGetters(obj); - for (let name of getters) { - // Avoid overwriting properties from prototypes closer to this.obj. Also - // avoid providing safeGetterValues from prototypes if property |name| - // is already defined as an own property. - if (name in safeGetterValues || - (obj != this.obj && name in aOwnProperties)) { - continue; - } - - let desc = null, getter = null; - try { - desc = obj.getOwnPropertyDescriptor(name); - getter = desc.get; - } catch (ex) { - // The above can throw if the cache becomes stale. - } - if (!getter) { - obj._safeGetters = null; - continue; - } - - let result = getter.call(this.obj); - if (result && !("throw" in result)) { - let getterValue = undefined; - if ("return" in result) { - getterValue = result.return; - } else if ("yield" in result) { - getterValue = result.yield; - } - // WebIDL attributes specified with the LenientThis extended attribute - // return undefined and should be ignored. - if (getterValue !== undefined) { - safeGetterValues[name] = { - getterValue: this.threadActor.createValueGrip(getterValue), - getterPrototypeLevel: level, - enumerable: desc.enumerable, - writable: level == 0 ? desc.writable : true, - }; - } - } - } - - obj = obj.proto; - level++; - } - - return safeGetterValues; - }, - - /** - * Find the safe getters for a given Debugger.Object. Safe getters are native - * getters which are safe to execute. - * - * @private - * @param Debugger.Object aObject - * The Debugger.Object where you want to find safe getters. - * @return Set - * A Set of names of safe getters. This result is cached for each - * Debugger.Object. - */ - _findSafeGetters: function OA__findSafeGetters(aObject) - { - if (aObject._safeGetters) { - return aObject._safeGetters; - } - - let getters = new Set(); - for (let name of aObject.getOwnPropertyNames()) { - let desc = null; - try { - desc = aObject.getOwnPropertyDescriptor(name); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). - } - if (!desc || desc.value !== undefined || !("get" in desc)) { - continue; - } - - let fn = desc.get; - if (fn && fn.callable && fn.class == "Function" && - fn.script === undefined) { - getters.add(name); - } - } - - aObject._safeGetters = getters; - return getters; - }, - - /** - * Handle a protocol request to provide the prototype of the object. - * - * @param aRequest object - * The protocol request object. - */ - onPrototype: function OA_onPrototype(aRequest) { - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(this.obj.proto) }; - }, - - /** - * Handle a protocol request to provide the property descriptor of the - * object's specified property. - * - * @param aRequest object - * The protocol request object. - */ - onProperty: function OA_onProperty(aRequest) { - if (!aRequest.name) { - return { error: "missingParameter", - message: "no property name was specified" }; - } - - return { from: this.actorID, - descriptor: this._propertyDescriptor(aRequest.name) }; - }, - - /** - * A helper method that creates a property descriptor for the provided object, - * properly formatted for sending in a protocol response. - * - * @param string aName - * The property that the descriptor is generated for. - */ - _propertyDescriptor: function OA_propertyDescriptor(aName) { - let desc; - try { - desc = this.obj.getOwnPropertyDescriptor(aName); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). Inform the user with a bogus, but hopefully - // explanatory, descriptor. - return { - configurable: false, - writable: false, - enumerable: false, - value: e.name - }; - } - - let retval = { - configurable: desc.configurable, - enumerable: desc.enumerable - }; - - if ("value" in desc) { - retval.writable = desc.writable; - retval.value = this.threadActor.createValueGrip(desc.value); - } else { - if ("get" in desc) { - retval.get = this.threadActor.createValueGrip(desc.get); - } - if ("set" in desc) { - retval.set = this.threadActor.createValueGrip(desc.set); - } - } - return retval; - }, - - /** - * Handle a protocol request to provide the source code of a function. - * - * @param aRequest object - * The protocol request object. - */ - onDecompile: function OA_onDecompile(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "decompile request is only valid for object grips " + - "with a 'Function' class." }; - } - - return { from: this.actorID, - decompiledCode: this.obj.decompile(!!aRequest.pretty) }; - }, - - /** - * Handle a protocol request to provide the parameters of a function. - * - * @param aRequest object - * The protocol request object. - */ - onParameterNames: function OA_onParameterNames(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "'parameterNames' request is only valid for object " + - "grips with a 'Function' class." }; - } - - return { parameterNames: this.obj.parameterNames }; - }, - - /** - * Handle a protocol request to release a thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onRelease: function OA_onRelease(aRequest) { - this.release(); - return {}; - }, -}; - -ObjectActor.prototype.requestTypes = { - "parameterNames": ObjectActor.prototype.onParameterNames, - "prototypeAndProperties": ObjectActor.prototype.onPrototypeAndProperties, - "prototype": ObjectActor.prototype.onPrototype, - "property": ObjectActor.prototype.onProperty, - "ownPropertyNames": ObjectActor.prototype.onOwnPropertyNames, - "decompile": ObjectActor.prototype.onDecompile, - "release": ObjectActor.prototype.onRelease, -}; - - -/** - * Creates a pause-scoped actor for the specified object. - * @see ObjectActor - */ -function PauseScopedObjectActor() -{ - ObjectActor.apply(this, arguments); -} - -PauseScopedObjectActor.prototype = Object.create(PauseScopedActor.prototype); - -update(PauseScopedObjectActor.prototype, ObjectActor.prototype); - -update(PauseScopedObjectActor.prototype, { - constructor: PauseScopedObjectActor, - - onOwnPropertyNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onOwnPropertyNames), - - onPrototypeAndProperties: - PauseScopedActor.withPaused(ObjectActor.prototype.onPrototypeAndProperties), - - onPrototype: PauseScopedActor.withPaused(ObjectActor.prototype.onPrototype), - onProperty: PauseScopedActor.withPaused(ObjectActor.prototype.onProperty), - onDecompile: PauseScopedActor.withPaused(ObjectActor.prototype.onDecompile), - - onParameterNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onParameterNames), - - /** - * Handle a protocol request to provide the lexical scope of a function. - * - * @param aRequest object - * The protocol request object. - */ - onScope: PauseScopedActor.withPaused(function OA_onScope(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "scope request is only valid for object grips with a" + - " 'Function' class." }; - } - - let envActor = this.threadActor.createEnvironmentActor(this.obj.environment, - this.registeredPool); - if (!envActor) { - return { error: "notDebuggee", - message: "cannot access the environment of this function." }; - } - - return { from: this.actorID, scope: envActor.form() }; - }), - - /** - * Handle a protocol request to promote a pause-lifetime grip to a - * thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrip: PauseScopedActor.withPaused(function OA_onThreadGrip(aRequest) { - this.threadActor.threadObjectGrip(this); - return {}; - }), - - /** - * Handle a protocol request to release a thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onRelease: PauseScopedActor.withPaused(function OA_onRelease(aRequest) { - if (this.registeredPool !== this.threadActor.threadLifetimePool) { - return { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - - this.release(); - return {}; - }), -}); - -update(PauseScopedObjectActor.prototype.requestTypes, { - "scope": PauseScopedObjectActor.prototype.onScope, - "threadGrip": PauseScopedObjectActor.prototype.onThreadGrip, -}); - - -/** - * Creates an actor for the specied "very long" string. "Very long" is specified - * at the server's discretion. - * - * @param aString String - * The string. - */ -function LongStringActor(aString) -{ - this.string = aString; - this.stringLength = aString.length; -} - -LongStringActor.prototype = { - - actorPrefix: "longString", - - disconnect: function LSA_disconnect() { - // Because longStringActors is not a weak map, we won't automatically leave - // it so we need to manually leave on disconnect so that we don't leak - // memory. - if (this.registeredPool && this.registeredPool.longStringActors) { - delete this.registeredPool.longStringActors[this.actorID]; - } - }, - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function LSA_grip() { - return { - "type": "longString", - "initial": this.string.substring( - 0, DebuggerServer.LONG_STRING_INITIAL_LENGTH), - "length": this.stringLength, - "actor": this.actorID - }; - }, - - /** - * Handle a request to extract part of this actor's string. - * - * @param aRequest object - * The protocol request object. - */ - onSubstring: function LSA_onSubString(aRequest) { - return { - "from": this.actorID, - "substring": this.string.substring(aRequest.start, aRequest.end) - }; - }, - - /** - * Handle a request to release this LongStringActor instance. - */ - onRelease: function LSA_onRelease() { - // TODO: also check if registeredPool === threadActor.threadLifetimePool - // when the web console moves aray from manually releasing pause-scoped - // actors. - if (this.registeredPool.longStringActors) { - delete this.registeredPool.longStringActors[this.actorID]; - } - this.registeredPool.removeActor(this); - return {}; - }, -}; - -LongStringActor.prototype.requestTypes = { - "substring": LongStringActor.prototype.onSubstring, - "release": LongStringActor.prototype.onRelease -}; - - -/** - * Creates an actor for the specified stack frame. - * - * @param aFrame Debugger.Frame - * The debuggee frame. - * @param aThreadActor ThreadActor - * The parent thread actor for this frame. - */ -function FrameActor(aFrame, aThreadActor) -{ - this.frame = aFrame; - this.threadActor = aThreadActor; -} - -FrameActor.prototype = { - actorPrefix: "frame", - - /** - * A pool that contains frame-lifetime objects, like the environment. - */ - _frameLifetimePool: null, - get frameLifetimePool() { - if (!this._frameLifetimePool) { - this._frameLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._frameLifetimePool); - } - return this._frameLifetimePool; - }, - - /** - * Finalization handler that is called when the actor is being evicted from - * the pool. - */ - disconnect: function FA_disconnect() { - this.conn.removeActorPool(this._frameLifetimePool); - this._frameLifetimePool = null; - }, - - /** - * Returns a frame form for use in a protocol message. - */ - form: function FA_form() { - let form = { actor: this.actorID, - type: this.frame.type }; - if (this.frame.type === "call") { - form.callee = this.threadActor.createValueGrip(this.frame.callee); - } - - if (this.frame.environment) { - let envActor = this.threadActor - .createEnvironmentActor(this.frame.environment, - this.frameLifetimePool); - form.environment = envActor.form(); - } - form.this = this.threadActor.createValueGrip(this.frame.this); - form.arguments = this._args(); - if (this.frame.script) { - form.where = { url: this.frame.script.url, - line: this.frame.script.getOffsetLine(this.frame.offset) }; - form.isBlackBoxed = this.threadActor.sources.isBlackBoxed(this.frame.script.url) - } - - if (!this.frame.older) { - form.oldest = true; - } - - return form; - }, - - _args: function FA__args() { - if (!this.frame.arguments) { - return []; - } - - return [this.threadActor.createValueGrip(arg) - for each (arg in this.frame.arguments)]; - }, - - /** - * Handle a protocol request to pop this frame from the stack. - * - * @param aRequest object - * The protocol request object. - */ - onPop: function FA_onPop(aRequest) { - // TODO: remove this when Debugger.Frame.prototype.pop is implemented - if (typeof this.frame.pop != "function") { - return { error: "notImplemented", - message: "Popping frames is not yet implemented." }; - } - - while (this.frame != this.threadActor.dbg.getNewestFrame()) { - this.threadActor.dbg.getNewestFrame().pop(); - } - this.frame.pop(aRequest.completionValue); - - // TODO: return the watches property when frame pop watch actors are - // implemented. - return { from: this.actorID }; - } -}; - -FrameActor.prototype.requestTypes = { - "pop": FrameActor.prototype.onPop, -}; - - -/** - * Creates a BreakpointActor. BreakpointActors exist for the lifetime of their - * containing thread and are responsible for deleting breakpoints, handling - * breakpoint hits and associating breakpoints with scripts. - * - * @param ThreadActor aThreadActor - * The parent thread actor that contains this breakpoint. - * @param object aLocation - * The location of the breakpoint as specified in the protocol. - */ -function BreakpointActor(aThreadActor, aLocation) -{ - this.scripts = []; - this.threadActor = aThreadActor; - this.location = aLocation; -} - -BreakpointActor.prototype = { - actorPrefix: "breakpoint", - - /** - * Called when this same breakpoint is added to another Debugger.Script - * instance, in the case of a page reload. - * - * @param aScript Debugger.Script - * The new source script on which the breakpoint has been set. - * @param ThreadActor aThreadActor - * The parent thread actor that contains this breakpoint. - */ - addScript: function BA_addScript(aScript, aThreadActor) { - this.threadActor = aThreadActor; - this.scripts.push(aScript); - }, - - /** - * Remove the breakpoints from associated scripts and clear the script cache. - */ - removeScripts: function () { - for (let script of this.scripts) { - script.clearBreakpoint(this); - } - this.scripts = []; - }, - - /** - * A function that the engine calls when a breakpoint has been hit. - * - * @param aFrame Debugger.Frame - * The stack frame that contained the breakpoint. - */ - hit: function BA_hit(aFrame) { - if (this.threadActor.sources.isBlackBoxed(this.location.url)) { - return undefined; - } - - // TODO: add the rest of the breakpoints on that line (bug 676602). - let reason = { type: "breakpoint", actors: [ this.actorID ] }; - return this.threadActor._pauseAndRespond(aFrame, reason, (aPacket) => { - log("pause callback ..."); - - let { url, line } = aPacket.frame.where; - return this.threadActor.sources.getOriginalLocation(url, line) - .then(function (aOrigPosition) { - aPacket.frame.where = aOrigPosition; - return aPacket; - }); - }); - }, - - /** - * Handle a protocol request to remove this breakpoint. - * - * @param aRequest object - * The protocol request object. - */ - onDelete: function BA_onDelete(aRequest) { - // Remove from the breakpoint store. - let scriptBreakpoints = this.threadActor._breakpointStore[this.location.url]; - delete scriptBreakpoints[this.location.line]; - this.threadActor._hooks.removeFromParentPool(this); - // Remove the actual breakpoint from the associated scripts. - this.removeScripts(); - - return { from: this.actorID }; - } -}; - -BreakpointActor.prototype.requestTypes = { - "delete": BreakpointActor.prototype.onDelete -}; - - -/** - * Creates an EnvironmentActor. EnvironmentActors are responsible for listing - * the bindings introduced by a lexical environment and assigning new values to - * those identifier bindings. - * - * @param Debugger.Environment aEnvironment - * The lexical environment that will be used to create the actor. - * @param ThreadActor aThreadActor - * The parent thread actor that contains this environment. - */ -function EnvironmentActor(aEnvironment, aThreadActor) -{ - this.obj = aEnvironment; - this.threadActor = aThreadActor; -} - -EnvironmentActor.prototype = { - actorPrefix: "environment", - - /** - * Return an environment form for use in a protocol message. - */ - form: function EA_form() { - let form = { actor: this.actorID }; - - // What is this environment's type? - if (this.obj.type == "declarative") { - form.type = this.obj.callee ? "function" : "block"; - } else { - form.type = this.obj.type; - } - - // Does this environment have a parent? - if (this.obj.parent) { - form.parent = (this.threadActor - .createEnvironmentActor(this.obj.parent, - this.registeredPool) - .form()); - } - - // Does this environment reflect the properties of an object as variables? - if (this.obj.type == "object" || this.obj.type == "with") { - form.object = this.threadActor.createValueGrip(this.obj.object); - } - - // Is this the environment created for a function call? - if (this.obj.callee) { - form.function = this.threadActor.createValueGrip(this.obj.callee); - } - - // Shall we list this environment's bindings? - if (this.obj.type == "declarative") { - form.bindings = this._bindings(); - } - - return form; - }, - - /** - * Return the identifier bindings object as required by the remote protocol - * specification. - */ - _bindings: function EA_bindings() { - let bindings = { arguments: [], variables: {} }; - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - if (typeof this.obj.getVariable != "function") { - //if (typeof this.obj.getVariableDescriptor != "function") { - return bindings; - } - - let parameterNames; - if (this.obj.callee) { - parameterNames = this.obj.callee.parameterNames; - } - for each (let name in parameterNames) { - let arg = {}; - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - let desc = { - value: this.obj.getVariable(name), - configurable: false, - writable: true, - enumerable: true - }; - - // let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = this.threadActor.createValueGrip(desc.value); - descForm.writable = desc.writable; - } else { - descForm.get = this.threadActor.createValueGrip(desc.get); - descForm.set = this.threadActor.createValueGrip(desc.set); - } - arg[name] = descForm; - bindings.arguments.push(arg); - } - - for each (let name in this.obj.names()) { - if (bindings.arguments.some(function exists(element) { - return !!element[name]; - })) { - continue; - } - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands. - let desc = { - configurable: false, - writable: true, - enumerable: true - }; - try { - desc.value = this.obj.getVariable(name); - } catch (e) { - // Avoid "Debugger scope is not live" errors for |arguments|, introduced - // in bug 746601. - if (name != "arguments") { - throw e; - } - } - //let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = this.threadActor.createValueGrip(desc.value); - descForm.writable = desc.writable; - } else { - descForm.get = this.threadActor.createValueGrip(desc.get); - descForm.set = this.threadActor.createValueGrip(desc.set); - } - bindings.variables[name] = descForm; - } - - return bindings; - }, - - /** - * Handle a protocol request to change the value of a variable bound in this - * lexical environment. - * - * @param aRequest object - * The protocol request object. - */ - onAssign: function EA_onAssign(aRequest) { - // TODO: enable the commented-out part when getVariableDescriptor lands - // (bug 725815). - /*let desc = this.obj.getVariableDescriptor(aRequest.name); - - if (!desc.writable) { - return { error: "immutableBinding", - message: "Changing the value of an immutable binding is not " + - "allowed" }; - }*/ - - try { - this.obj.setVariable(aRequest.name, aRequest.value); - } catch (e) { - if (e instanceof Debugger.DebuggeeWouldRun) { - return { error: "threadWouldRun", - cause: e.cause ? e.cause : "setter", - message: "Assigning a value would cause the debuggee to run" }; - } - // This should never happen, so let it complain loudly if it does. - throw e; - } - return { from: this.actorID }; - }, - - /** - * Handle a protocol request to fully enumerate the bindings introduced by the - * lexical environment. - * - * @param aRequest object - * The protocol request object. - */ - onBindings: function EA_onBindings(aRequest) { - return { from: this.actorID, - bindings: this._bindings() }; - } -}; - -EnvironmentActor.prototype.requestTypes = { - "assign": EnvironmentActor.prototype.onAssign, - "bindings": EnvironmentActor.prototype.onBindings -}; - -/** - * Override the toString method in order to get more meaningful script output - * for debugging the debugger. - */ -Debugger.Script.prototype.toString = function() { - let output = ""; - if (this.url) { - output += this.url; - } - if (typeof this.startLine != "undefined") { - output += ":" + this.startLine; - if (this.lineCount && this.lineCount > 1) { - output += "-" + (this.startLine + this.lineCount - 1); - } - } - if (this.strictMode) { - output += ":strict"; - } - return output; -}; - -/** - * Helper property for quickly getting to the line number a stack frame is - * currently paused at. - */ -Object.defineProperty(Debugger.Frame.prototype, "line", { - configurable: true, - get: function() { - if (this.script) { - return this.script.getOffsetLine(this.offset); - } else { - return null; - } - } -}); - - -/** - * Creates an actor for handling chrome debugging. ChromeDebuggerActor is a - * thin wrapper over ThreadActor, slightly changing some of its behavior. - * - * @param aConnection object - * The DebuggerServerConnection with which this ChromeDebuggerActor - * is associated. (Currently unused, but required to make this - * constructor usable with addGlobalActor.) - * - * @param aHooks object - * An object with preNest and postNest methods for calling when entering - * and exiting a nested event loop and also addToParentPool and - * removeFromParentPool methods for handling the lifetime of actors that - * will outlive the thread, like breakpoints. - */ -function ChromeDebuggerActor(aConnection, aHooks) -{ - ThreadActor.call(this, aHooks); -} - -ChromeDebuggerActor.prototype = Object.create(ThreadActor.prototype); - -update(ChromeDebuggerActor.prototype, { - constructor: ChromeDebuggerActor, - - // A constant prefix that will be used to form the actor ID by the server. - actorPrefix: "chromeDebugger", - - /** - * Override the eligibility check for scripts and sources to make sure every - * script and source with a URL is stored when debugging chrome. - */ - _allowSource: function(aSourceURL) !!aSourceURL, - - /** - * An object that will be used by ThreadActors to tailor their behavior - * depending on the debugging context being required (chrome or content). - * The methods that this object provides must be bound to the ThreadActor - * before use. - */ - globalManager: { - findGlobals: function CDA_findGlobals() { - // Add every global known to the debugger as debuggee. - this.dbg.addAllGlobalsAsDebuggees(); - }, - - /** - * A function that the engine calls when a new global object has been - * created. - * - * @param aGlobal Debugger.Object - * The new global object that was created. - */ - onNewGlobal: function CDA_onNewGlobal(aGlobal) { - this.addDebuggee(aGlobal); - // Notify the client. - this.conn.send({ - from: this.actorID, - type: "newGlobal", - // TODO: after bug 801084 lands see if we need to JSONify this. - hostAnnotations: aGlobal.hostAnnotations - }); - } - } -}); - - -/** - * Manages the sources for a thread. Handles source maps, locations in the - * sources, etc for ThreadActors. - */ -function ThreadSources(aThreadActor, aUseSourceMaps, aAllowPredicate, - aOnNewSource) { - this._thread = aThreadActor; - this._useSourceMaps = aUseSourceMaps; - this._allow = aAllowPredicate; - this._onNewSource = aOnNewSource; - - // source map URL --> promise of SourceMapConsumer - this._sourceMaps = Object.create(null); - // generated source url --> promise of SourceMapConsumer - this._sourceMapsByGeneratedSource = Object.create(null); - // original source url --> promise of SourceMapConsumer - this._sourceMapsByOriginalSource = Object.create(null); - // source url --> SourceActor - this._sourceActors = Object.create(null); - // original url --> generated url - this._generatedUrlsByOriginalUrl = Object.create(null); -} - -/** - * Must be a class property because it needs to persist across reloads, same as - * the breakpoint store. - */ -ThreadSources._blackBoxedSources = new Set(); - -ThreadSources.prototype = { - /** - * Return the source actor representing |aURL|, creating one if none - * exists already. Returns null if |aURL| is not allowed by the 'allow' - * predicate. - * - * Right now this takes a URL, but in the future it should - * take a Debugger.Source. See bug 637572. - * - * @param String aURL - * The source URL. - * @param optional SourceMapConsumer aSourceMap - * The source map that introduced this source, if any. - * @returns a SourceActor representing the source at aURL or null. - */ - source: function TS_source(aURL, aSourceMap=null) { - if (!this._allow(aURL)) { - return null; - } - - if (aURL in this._sourceActors) { - return this._sourceActors[aURL]; - } - - let actor = new SourceActor(aURL, this._thread, aSourceMap); - this._thread.threadLifetimePool.addActor(actor); - this._sourceActors[aURL] = actor; - try { - this._onNewSource(actor); - } catch (e) { - reportError(e); - } - return actor; - }, - - /** - * Return a promise of an array of source actors representing all the - * sources of |aScript|. - * - * If source map handling is enabled and |aScript| has a source map, then - * use it to find all of |aScript|'s *original* sources; return a promise - * of an array of source actors for those. - */ - sourcesForScript: function TS_sourcesForScript(aScript) { - if (!this._useSourceMaps || !aScript.sourceMapURL) { - return resolve([this.source(aScript.url)].filter(isNotNull)); - } - - return this.sourceMap(aScript) - .then((aSourceMap) => { - return [ - this.source(s, aSourceMap) for (s of aSourceMap.sources) - ]; - }) - .then(null, (e) => { - reportError(e); - delete this._sourceMaps[this._normalize(aScript.sourceMapURL, aScript.url)]; - delete this._sourceMapsByGeneratedSource[aScript.url]; - return [this.source(aScript.url)]; - }) - .then(function (aSources) { - return aSources.filter(isNotNull); - }); - }, - - /** - * Return a promise of a SourceMapConsumer for the source map for - * |aScript|; if we already have such a promise extant, return that. - * |aScript| must have a non-null sourceMapURL. - */ - sourceMap: function TS_sourceMap(aScript) { - if (aScript.url in this._sourceMapsByGeneratedSource) { - return this._sourceMapsByGeneratedSource[aScript.url]; - } - dbg_assert(aScript.sourceMapURL); - let sourceMapURL = this._normalize(aScript.sourceMapURL, aScript.url); - let map = this._fetchSourceMap(sourceMapURL) - .then((aSourceMap) => { - for (let s of aSourceMap.sources) { - this._generatedUrlsByOriginalUrl[s] = aScript.url; - this._sourceMapsByOriginalSource[s] = resolve(aSourceMap); - } - return aSourceMap; - }); - this._sourceMapsByGeneratedSource[aScript.url] = map; - return map; - }, - - /** - * Return a promise of a SourceMapConsumer for the source map located at - * |aAbsSourceMapURL|, which must be absolute. If there is already such a - * promise extant, return it. - */ - _fetchSourceMap: function TS__fetchSourceMap(aAbsSourceMapURL) { - if (aAbsSourceMapURL in this._sourceMaps) { - return this._sourceMaps[aAbsSourceMapURL]; - } else { - let promise = fetch(aAbsSourceMapURL).then((rawSourceMap) => { - let map = new SourceMapConsumer(rawSourceMap); - let base = aAbsSourceMapURL.replace(/\/[^\/]+$/, '/'); - if (base.indexOf("data:") !== 0) { - map.sourceRoot = map.sourceRoot - ? this._normalize(map.sourceRoot, base) - : base; - } - return map; - }); - this._sourceMaps[aAbsSourceMapURL] = promise; - return promise; - } - }, - - /** - * Returns a promise of the location in the original source if the source is - * source mapped, otherwise a promise of the same location. - * - * TODO bug 637572: take/return a column - */ - getOriginalLocation: function TS_getOriginalLocation(aSourceUrl, aLine) { - if (aSourceUrl in this._sourceMapsByGeneratedSource) { - return this._sourceMapsByGeneratedSource[aSourceUrl] - .then(function (aSourceMap) { - let { source, line } = aSourceMap.originalPositionFor({ - source: aSourceUrl, - line: aLine, - column: Infinity - }); - return { - url: source, - line: line - }; - }); - } - - // No source map - return resolve({ - url: aSourceUrl, - line: aLine - }); - }, - - /** - * Returns a promise of the location in the generated source corresponding to - * the original source and line given. - * - * When we pass a script S representing generated code to |sourceMap|, - * above, that returns a promise P. The process of resolving P populates - * the tables this function uses; thus, it won't know that S's original - * source URLs map to S until P is resolved. - * - * TODO bug 637572: take/return a column - */ - getGeneratedLocation: function TS_getGeneratedLocation(aSourceUrl, aLine) { - if (aSourceUrl in this._sourceMapsByOriginalSource) { - return this._sourceMapsByOriginalSource[aSourceUrl] - .then((aSourceMap) => { - let { line } = aSourceMap.generatedPositionFor({ - source: aSourceUrl, - line: aLine, - column: Infinity - }); - return { - url: this._generatedUrlsByOriginalUrl[aSourceUrl], - line: line - }; - }); - } - - // No source map - return resolve({ - url: aSourceUrl, - line: aLine - }); - }, - - /** - * Returns true if URL for the given source is black boxed. - * - * @param aURL String - * The URL of the source which we are checking whether it is black - * boxed or not. - */ - isBlackBoxed: function TS_isBlackBoxed(aURL) { - return ThreadSources._blackBoxedSources.has(aURL); - }, - - /** - * Add the given source URL to the set of sources that are black boxed. If the - * thread is currently paused and we are black boxing the yougest frame's - * source, this will force a step. - * - * @param aURL String - * The URL of the source which we are black boxing. - */ - blackBox: function TS_blackBox(aURL) { - ThreadSources._blackBoxedSources.add(aURL); - }, - - /** - * Remove the given source URL to the set of sources that are black boxed. - * - * @param aURL String - * The URL of the source which we are no longer black boxing. - */ - unblackBox: function TS_unblackBox(aURL) { - ThreadSources._blackBoxedSources.delete(aURL); - }, - - /** - * Normalize multiple relative paths towards the base paths on the right. - */ - _normalize: function TS__normalize(...aURLs) { - dbg_assert(aURLs.length > 1); - let base = Services.io.newURI(aURLs.pop(), null, null); - let url; - while ((url = aURLs.pop())) { - base = Services.io.newURI(url, null, base); - } - return base.spec; - }, - - iter: function TS_iter() { - for (let url in this._sourceActors) { - yield this._sourceActors[url]; - } - } -}; - -// Utility functions. - -/** - * Utility function for updating an object with the properties of another - * object. - * - * @param aTarget Object - * The object being updated. - * @param aNewAttrs Object - * The new attributes being set on the target. - */ -function update(aTarget, aNewAttrs) { - for (let key in aNewAttrs) { - let desc = Object.getOwnPropertyDescriptor(aNewAttrs, key); - - if (desc) { - Object.defineProperty(aTarget, key, desc); - } - } -} - -/** - * Returns true if its argument is not null. - */ -function isNotNull(aThing) { - return aThing !== null; -} - -/** - * Performs a request to load the desired URL and returns a promise. - * - * @param aURL String - * The URL we will request. - * @returns Promise - * A promise of the document at that URL, as a string. - * - * XXX: It may be better to use nsITraceableChannel to get to the sources - * without relying on caching when we can (not for eval, etc.): - * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ - */ -function fetch(aURL, aOptions={ loadFromCache: true }) { - let deferred = defer(); - let scheme; - let url = aURL.split(" -> ").pop(); - let charset; - let filePath = url; - // try { - // scheme = Services.io.extractScheme(url); - // } catch (e) { - // In the xpcshell tests, the script url is the absolute path of the test - // file, which will make a malformed URI error be thrown. Add the file - // scheme prefix ourselves. - url = "file://" + url; - // scheme = Services.io.extractScheme(url); - // } - scheme = "file"; - - switch (scheme) { - case "file": - case "chrome": - case "resource": - try { - // NetUtil.asyncFetch(url, function onFetch(aStream, aStatus) { - // if (!Components.isSuccessCode(aStatus)) { - // deferred.reject("Request failed: " + url); - // return; - // } - let cc = globalDebuggee.cc; - let fileUtils = cc.FileUtils.getInstance(); - let source = fileUtils.getStringFromFile(filePath);//NetUtil.readInputStreamToString(aStream, aStream.available()); - if (!source) - { - deferred.reject("Request failed: " + url); - } - else - { - deferred.resolve(source); - } - // aStream.close(); - // }); - } catch (ex) { - deferred.reject("Request failed: " + url); - } - break; - - default: - let channel; - try { - channel = Services.io.newChannel(url, null, null); - } catch (e if e.name == "NS_ERROR_UNKNOWN_PROTOCOL") { - // On Windows xpcshell tests, c:/foo/bar can pass as a valid URL, but - // newChannel won't be able to handle it. - url = "file:///" + url; - channel = Services.io.newChannel(url, null, null); - } - let chunks = []; - let streamListener = { - onStartRequest: function(aRequest, aContext, aStatusCode) { - if (!Components.isSuccessCode(aStatusCode)) { - deferred.reject("Request failed: " + url); - } - }, - onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount) { - chunks.push(NetUtil.readInputStreamToString(aStream, aCount)); - }, - onStopRequest: function(aRequest, aContext, aStatusCode) { - if (!Components.isSuccessCode(aStatusCode)) { - deferred.reject("Request failed: " + url); - return; - } - - charset = channel.contentCharset; - deferred.resolve(chunks.join("")); - } - }; - - channel.loadFlags = aOptions.loadFromCache - ? channel.LOAD_FROM_CACHE - : channel.LOAD_BYPASS_CACHE; - channel.asyncOpen(streamListener, null); - break; - } - - return deferred.promise.then(function (source) { - return convertToUnicode(source, charset); - }); -} - -/** - * Convert a given string, encoded in a given character set, to unicode. - * - * @param string aString - * A string. - * @param string aCharset - * A character set. - */ -function convertToUnicode(aString, aCharset=null) { - // Decoding primitives. - // let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - // .createInstance(Ci.nsIScriptableUnicodeConverter); - // try { - // converter.charset = aCharset || "UTF-8"; - // return converter.ConvertToUnicode(aString); - // } catch(e) { - return aString; - // } -} - -/** - * Report the given error in the error console and to stdout. - */ -function reportError(aError) { - // Cu.reportError(aError); - dumpn(aError.message + ":\n" + aError.stack); -} diff --git a/scripting/javascript/bindings/js/debugger/core/promise.js b/scripting/javascript/bindings/js/debugger/core/promise.js deleted file mode 100644 index a695f5a3ad..0000000000 --- a/scripting/javascript/bindings/js/debugger/core/promise.js +++ /dev/null @@ -1,294 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/*jshint undef: true es5: true node: true browser: true devel: true - forin: true latedef: false */ -/*global define: true, Cu: true, __URI__: true */ -//;(function(id, factory) { // Module boilerplate :( -// if (typeof(define) === 'function') { // RequireJS -// define(factory); -// } else if (typeof(require) === 'function') { // CommonJS -// factory.call(this, require, exports, module); -// } else if (String(this).indexOf('BackstagePass') >= 0) { // JSM -// this[factory.name] = {}; -// try { -// this.console = this['Components'].utils -// .import('resource://gre/modules/devtools/Console.jsm', {}).console; -// } -// catch (ex) { -// // Avoid failures on different toolkit configurations. -// } -// factory(function require(uri) { -// var imports = {}; -// this['Components'].utils.import(uri, imports); -// return imports; -// }, this[factory.name], { uri: __URI__, id: id }); -// this.EXPORTED_SYMBOLS = [factory.name]; -// } else { // Browser or alike -// var globals = this; -// factory(function require(id) { -// return globals[id]; -// }, (globals[id] = {}), { uri: document.location.href + '#' + id, id: id }); -// } -//}).call(this, 'promise/core', function Promise(require, exports, module) { - -'use strict'; - -var exports = exports || {}; - -//module.metadata = { -// "stability": "unstable" -//}; - -/** - * Internal utility: Wraps given `value` into simplified promise, successfully - * fulfilled to a given `value`. Note the result is not a complete promise - * implementation, as its method `then` does not returns anything. - */ -function fulfilled(value) { - return { then: function then(fulfill) { fulfill(value); } }; -} - -/** - * Internal utility: Wraps given input into simplified promise, pre-rejected - * with a given `reason`. Note the result is not a complete promise - * implementation, as its method `then` does not returns anything. - */ -function rejected(reason) { - return { then: function then(fulfill, reject) { reject(reason); } }; -} - -/** - * Internal utility: Returns `true` if given `value` is a promise. Value is - * assumed to be a promise if it implements method `then`. - */ -function isPromise(value) { - return value && typeof(value.then) === 'function'; -} - -/** - * Creates deferred object containing fresh promise & methods to either resolve - * or reject it. The result is an object with the following properties: - * - `promise` Eventual value representation implementing CommonJS [Promises/A] - * (http://wiki.commonjs.org/wiki/Promises/A) API. - * - `resolve` Single shot function that resolves enclosed `promise` with a - * given `value`. - * - `reject` Single shot function that rejects enclosed `promise` with a given - * `reason`. - * - * An optional `prototype` argument is used as a prototype of the returned - * `promise` allowing one to implement additional API. If prototype is not - * passed then it falls back to `Object.prototype`. - * - * ## Example - * - * function fetchURI(uri, type) { - * var deferred = defer(); - * var request = new XMLHttpRequest(); - * request.open("GET", uri, true); - * request.responseType = type; - * request.onload = function onload() { - * deferred.resolve(request.response); - * } - * request.onerror = function(event) { - * deferred.reject(event); - * } - * request.send(); - * - * return deferred.promise; - * } - */ -function defer(prototype) { - // Define FIFO queue of observer pairs. Once promise is resolved & all queued - // observers are forwarded to `result` and variable is set to `null`. - var observers = []; - - // Promise `result`, which will be assigned a resolution value once promise - // is resolved. Note that result will always be assigned promise (or alike) - // object to take care of propagation through promise chains. If result is - // `null` promise is not resolved yet. - var result = null; - - prototype = (prototype || prototype === null) ? prototype : Object.prototype; - - // Create an object implementing promise API. - var promise = Object.create(prototype, { - then: { value: function then(onFulfill, onError) { - var deferred = defer(prototype); - - function resolve(value) { - // If `onFulfill` handler is provided resolve `deferred.promise` with - // result of invoking it with a resolution value. If handler is not - // provided propagate value through. - try { - deferred.resolve(onFulfill ? onFulfill(value) : value); - } - // `onFulfill` may throw exception in which case resulting promise - // is rejected with thrown exception. - catch(error) { - if (exports._reportErrors && typeof(console) === 'object') - console.error(error); - // Note: Following is equivalent of `deferred.reject(error)`, - // we use this shortcut to reduce a stack. - deferred.resolve(rejected(error)); - } - } - - function reject(reason) { - try { - if (onError) deferred.resolve(onError(reason)); - else deferred.resolve(rejected(reason)); - } - catch(error) { - if (exports._reportErrors && typeof(console) === 'object') - console.error(error); - deferred.resolve(rejected(error)); - } - } - - // If enclosed promise (`this.promise`) observers queue is still alive - // enqueue a new observer pair into it. Note that this does not - // necessary means that promise is pending, it may already be resolved, - // but we still have to queue observers to guarantee an order of - // propagation. - if (observers) { - observers.push({ resolve: resolve, reject: reject }); - } - // Otherwise just forward observer pair right to a `result` promise. - else { - result.then(resolve, reject); - } - - return deferred.promise; - }} - }) - - var deferred = { - promise: promise, - /** - * Resolves associated `promise` to a given `value`, unless it's already - * resolved or rejected. Note that resolved promise is not necessary a - * successfully fulfilled. Promise may be resolved with a promise `value` - * in which case `value` promise's fulfillment / rejection will propagate - * up to a promise resolved with `value`. - */ - resolve: function resolve(value) { - if (!result) { - // Store resolution `value` in a `result` as a promise, so that all - // the subsequent handlers can be simply forwarded to it. Since - // `result` will be a promise all the value / error propagation will - // be uniformly taken care of. - result = isPromise(value) ? value : fulfilled(value); - - // Forward already registered observers to a `result` promise in the - // order they were registered. Note that we intentionally dequeue - // observer at a time until queue is exhausted. This makes sure that - // handlers registered as side effect of observer forwarding are - // queued instead of being invoked immediately, guaranteeing FIFO - // order. - while (observers.length) { - var observer = observers.shift(); - result.then(observer.resolve, observer.reject); - } - - // Once `observers` queue is exhausted we `null`-ify it, so that - // new handlers are forwarded straight to the `result`. - observers = null; - } - }, - /** - * Rejects associated `promise` with a given `reason`, unless it's already - * resolved / rejected. This is just a (better performing) convenience - * shortcut for `deferred.resolve(reject(reason))`. - */ - reject: function reject(reason) { - // Note that if promise is resolved that does not necessary means that it - // is successfully fulfilled. Resolution value may be a promise in which - // case its result propagates. In other words if promise `a` is resolved - // with promise `b`, `a` is either fulfilled or rejected depending - // on weather `b` is fulfilled or rejected. Here `deferred.promise` is - // resolved with a promise pre-rejected with a given `reason`, there for - // `deferred.promise` is rejected with a given `reason`. This may feel - // little awkward first, but doing it this way greatly simplifies - // propagation through promise chains. - deferred.resolve(rejected(reason)); - } - }; - - return deferred; -} -exports.defer = defer; - -/** - * Returns a promise resolved to a given `value`. Optionally a second - * `prototype` argument may be provided to be used as a prototype for the - * returned promise. - */ -function resolve(value, prototype) { - var deferred = defer(prototype); - deferred.resolve(value); - return deferred.promise; -} -exports.resolve = resolve; - -/** - * Returns a promise rejected with a given `reason`. Optionally a second - * `prototype` argument may be provided to be used as a prototype for the - * returned promise. - */ -function reject(reason, prototype) { - var deferred = defer(prototype); - deferred.reject(reason); - return deferred.promise; -} -exports.reject = reject; - -var promised = (function() { - // Note: Define shortcuts and utility functions here in order to avoid - // slower property accesses and unnecessary closure creations on each - // call of this popular function. - - var call = Function.call; - var concat = Array.prototype.concat; - - // Utility function that does following: - // execute([ f, self, args...]) => f.apply(self, args) - function execute(args) { return call.apply(call, args) } - - // Utility function that takes promise of `a` array and maybe promise `b` - // as arguments and returns promise for `a.concat(b)`. - function promisedConcat(promises, unknown) { - return promises.then(function(values) { - return resolve(unknown).then(function(value) { - return values.concat([ value ]); - }); - }); - } - - return function promised(f, prototype) { - /** - Returns a wrapped `f`, which when called returns a promise that resolves to - `f(...)` passing all the given arguments to it, which by the way may be - promises. Optionally second `prototype` argument may be provided to be used - a prototype for a returned promise. - - ## Example - - var promise = promised(Array)(1, promise(2), promise(3)) - promise.then(console.log) // => [ 1, 2, 3 ] - **/ - - return function promised() { - // create array of [ f, this, args... ] - return concat.apply([ f, this ], arguments). - // reduce it via `promisedConcat` to get promised array of fulfillments - reduce(promisedConcat, resolve([], prototype)). - // finally map that to promise of `f.apply(this, args...)` - then(execute); - }; - } -})(); -exports.promised = promised; -// -var all = promised(Array); -exports.all = all; -// -//}); diff --git a/scripting/javascript/bindings/js/debugger/main.js b/scripting/javascript/bindings/js/debugger/main.js deleted file mode 100644 index f08009ade6..0000000000 --- a/scripting/javascript/bindings/js/debugger/main.js +++ /dev/null @@ -1,928 +0,0 @@ -/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; -/** - * Toolkit glue for the remote debugging protocol, loaded into the - * debugging global. - */ - -//const Ci = Components.interfaces; -//const Cc = Components.classes; -//const CC = Components.Constructor; -//const Cu = Components.utils; -//const Cr = Components.results; -//const DBG_STRINGS_URI = "chrome://global/locale/devtools/debugger.properties"; -// -//Cu.import("resource://gre/modules/Services.jsm"); -//Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -//let wantLogging = Services.prefs.getBoolPref("devtools.debugger.log"); -// -//Cu.import("resource://gre/modules/jsdebugger.jsm"); -//addDebuggerToGlobal(this); -// -//Cu.import("resource://gre/modules/commonjs/sdk/core/promise.js"); -//const { defer, resolve, reject, all } = Promise; -// -//Cu.import("resource://gre/modules/devtools/SourceMap.jsm"); -// -//loadSubScript.call(this, "resource://gre/modules/devtools/DevToolsUtils.js"); - -let wantLogging = true; -let debuggerServer = null; - -function dumpn(str) { - if (wantLogging) { - log("DBG-SERVER: " + str + "\n"); - } -} - -function dbg_assert(cond, e) { - if (!cond) { - log("assert >>>> " + cond.toString()); - return e; - } -} - -function XPCInspector() { - this.exitNestedEventLoop = _exitNestedEventLoop; - this.enterNestedEventLoop = _enterNestedEventLoop; - this.eventLoopNestLevel = _getEventLoopNestLevel; -} - -//loadSubScript.call(this, "resource://gre/modules/devtools/server/transport.js"); - -// XPCOM constructors -// const ServerSocket = CC("@mozilla.org/network/server-socket;1", -// "nsIServerSocket", -// "initSpecialConnection"); - -function ServerSocket(aPort, flags, c){ - this.asyncListen = function(server){ - log("asyncListen...."); - debuggerServer = server; - }; -}; - -var gRegisteredModules = Object.create(null); - -/** - * The ModuleAPI object is passed to modules loaded using the - * DebuggerServer.registerModule() API. Modules can use this - * object to register actor factories. - * Factories registered through the module API will be removed - * when the module is unregistered or when the server is - * destroyed. - */ -function ModuleAPI() { - let activeTabActors = new Set(); - let activeGlobalActors = new Set(); - - return { - // See DebuggerServer.addGlobalActor for a description. - addGlobalActor: function(factory, name) { - DebuggerServer.addGlobalActor(factory, name); - activeGlobalActors.add(factory); - }, - // See DebuggerServer.removeGlobalActor for a description. - removeGlobalActor: function(factory) { - DebuggerServer.removeGlobalActor(factory); - activeGlobalActors.delete(factory); - }, - - // See DebuggerServer.addTabActor for a description. - addTabActor: function(factory, name) { - DebuggerServer.addTabActor(factory, name); - activeTabActors.add(factory); - }, - // See DebuggerServer.removeTabActor for a description. - removeTabActor: function(factory) { - DebuggerServer.removeTabActor(factory); - activeTabActors.delete(factory); - }, - - // Destroy the module API object, unregistering any - // factories registered by the module. - destroy: function() { - for (let factory of activeTabActors) { - DebuggerServer.removeTabActor(factory); - } - activeTabActors = null; - for (let factory of activeGlobalActors) { - DebuggerServer.removeGlobalActor(factory); - } - activeGlobalActors = null; - } - } -}; - -/*** - * Public API - */ -var DebuggerServer = { - _listener: null, - _initialized: false, - _transportInitialized: false, - xpcInspector: null, - _transport: null, - // Number of currently open TCP connections. - _socketConnections: 0, - // Map of global actor names to actor constructors provided by extensions. - globalActorFactories: {}, - // Map of tab actor names to actor constructors provided by extensions. - tabActorFactories: {}, - - LONG_STRING_LENGTH: 10000, - LONG_STRING_INITIAL_LENGTH: 1000, - LONG_STRING_READ_LENGTH: 1000, - - /** - * A handler function that prompts the user to accept or decline the incoming - * connection. - */ - _allowConnection: null, - - /** - * Prompt the user to accept or decline the incoming connection. This is the - * default implementation that products embedding the debugger server may - * choose to override. - * - * @return true if the connection should be permitted, false otherwise - */ - _defaultAllowConnection: function DS__defaultAllowConnection() { - // let title = L10N.getStr("remoteIncomingPromptTitle"); - // let msg = L10N.getStr("remoteIncomingPromptMessage"); - // let disableButton = L10N.getStr("remoteIncomingPromptDisable"); - // let prompt = Services.prompt; - // let flags = prompt.BUTTON_POS_0 * prompt.BUTTON_TITLE_OK + - // prompt.BUTTON_POS_1 * prompt.BUTTON_TITLE_CANCEL + - // prompt.BUTTON_POS_2 * prompt.BUTTON_TITLE_IS_STRING + - // prompt.BUTTON_POS_1_DEFAULT; - // let result = prompt.confirmEx(null, title, msg, flags, null, null, - // disableButton, null, { value: false }); - // if (result == 0) { - // return true; - // } - // if (result == 2) { - // DebuggerServer.closeListener(true); - // Services.prefs.setBoolPref("devtools.debugger.remote-enabled", false); - // } - // return false; - return true; - }, - - /** - * Initialize the debugger server. - * - * @param function aAllowConnectionCallback - * The embedder-provider callback, that decides whether an incoming - * remote protocol conection should be allowed or refused. - */ - init: function DS_init(aAllowConnectionCallback) { - if (this.initialized) { - return; - } - - this.xpcInspector = new XPCInspector();//Cc["@mozilla.org/jsinspector;1"].getService(Ci.nsIJSInspector); - this.initTransport(aAllowConnectionCallback); - this.addActors("resource://gre/modules/devtools/server/actors/root.js"); - - this._initialized = true; - }, - - /** - * Initialize the debugger server's transport variables. This can be - * in place of init() for cases where the jsdebugger isn't needed. - * - * @param function aAllowConnectionCallback - * The embedder-provider callback, that decides whether an incoming - * remote protocol conection should be allowed or refused. - */ - initTransport: function DS_initTransport(aAllowConnectionCallback) { - if (this._transportInitialized) { - return; - } - - this._connections = {}; - this._nextConnID = 0; - this._transportInitialized = true; - this._allowConnection = aAllowConnectionCallback ? - aAllowConnectionCallback : - this._defaultAllowConnection; - }, - - get initialized() this._initialized, - - /** - * Performs cleanup tasks before shutting down the debugger server, if no - * connections are currently open. Such tasks include clearing any actor - * constructors added at runtime. This method should be called whenever a - * debugger server is no longer useful, to avoid memory leaks. After this - * method returns, the debugger server must be initialized again before use. - */ - destroy: function DS_destroy() { - if (!this._initialized) { - return; - } - - for (let connID of Object.getOwnPropertyNames(this._connections)) { - this._connections[connID].close(); - } - - for (let id of Object.getOwnPropertyNames(gRegisteredModules)) { - let mod = gRegisteredModules[id]; - mod.module.unregister(mod.api); - } - gRegisteredModules = {}; - - this.closeListener(); - this.globalActorFactories = {}; - this.tabActorFactories = {}; - delete this._allowConnection; - this._transportInitialized = false; - this._initialized = false; - dumpn("Debugger server is shut down."); - }, - - /** - * Load a subscript into the debugging global. - * - * @param aURL string A url that will be loaded as a subscript into the - * debugging global. The user must load at least one script - * that implements a createRootActor() function to create the - * server's root actor. - */ - addActors: function DS_addActors(aURL) { - //loadSubScript.call(this, aURL); - }, - - /** - * Register a CommonJS module with the debugger server. - * @param id string - * The ID of a CommonJS module. This module must export - * 'register' and 'unregister' functions. - */ - registerModule: function(id) { - if (id in gRegisteredModules) { - throw new Error("Tried to register a module twice: " + id + "\n"); - } - - let moduleAPI = ModuleAPI(); - - let {devtools} = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); - let mod = devtools.require(id); - mod.register(moduleAPI); - gRegisteredModules[id] = { module: mod, api: moduleAPI }; - }, - - /** - * Returns true if a module id has been registered. - */ - isModuleRegistered: function(id) { - return (id in gRegisteredModules); - }, - - /** - * Unregister a previously-loaded CommonJS module from the debugger server. - */ - unregisterModule: function(id) { - let mod = gRegisteredModules[id]; - if (!mod) { - throw new Error("Tried to unregister a module that was not previously registered."); - } - mod.module.unregister(mod.api); - mod.api.destroy(); - delete gRegisteredModules[id]; - }, - - /** - * Install Firefox-specific actors. - */ - addBrowserActors: function DS_addBrowserActors() { - this.addActors("resource://gre/modules/devtools/server/actors/webbrowser.js"); - this.addActors("resource://gre/modules/devtools/server/actors/script.js"); - this.addGlobalActor(this.ChromeDebuggerActor, "chromeDebugger"); - this.addActors("resource://gre/modules/devtools/server/actors/webconsole.js"); - this.addActors("resource://gre/modules/devtools/server/actors/gcli.js"); - if ("nsIProfiler" in Ci) - this.addActors("resource://gre/modules/devtools/server/actors/profiler.js"); - - this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); - this.addActors("resource://gre/modules/devtools/server/actors/webapps.js"); - this.registerModule("devtools/server/actors/inspector"); - }, - - /** - * Listens on the given port for remote debugger connections. - * - * @param aPort int - * The port to listen on. - */ - openListener: function DS_openListener(aPort) { - // if (!Services.prefs.getBoolPref("devtools.debugger.remote-enabled")) { - // return false; - // } - this._checkInit(); - - // Return early if the server is already listening. - if (this._listener) { - return true; - } - - // let flags = Ci.nsIServerSocket.KeepWhenOffline; - // A preference setting can force binding on the loopback interface. - // if (Services.prefs.getBoolPref("devtools.debugger.force-local")) { - // flags |= Ci.nsIServerSocket.LoopbackOnly; - // } - - let flags = 0; - - try { - let socket = new ServerSocket(aPort, flags, 4); - socket.asyncListen(this); - this._listener = socket; - } catch (e) { - dumpn("Could not start debugging listener on port " + aPort + ": " + e); - throw "Cr.NS_ERROR_NOT_AVAILABLE"; - } - this._socketConnections++; - - return true; - }, - - /** - * Close a previously-opened TCP listener. - * - * @param aForce boolean [optional] - * If set to true, then the socket will be closed, regardless of the - * number of open connections. - */ - closeListener: function DS_closeListener(aForce) { - if (!this._listener || this._socketConnections == 0) { - return false; - } - - // Only close the listener when the last connection is closed, or if the - // aForce flag is passed. - if (--this._socketConnections == 0 || aForce) { - this._listener.close(); - this._listener = null; - this._socketConnections = 0; - } - - return true; - }, - - /** - * Creates a new connection to the local debugger speaking over a fake - * transport. This connection results in straightforward calls to the onPacket - * handlers of each side. - * - * @returns a client-side DebuggerTransport for communicating with - * the newly-created connection. - */ - connectPipe: function DS_connectPipe() { - this._checkInit(); - - let serverTransport = new LocalDebuggerTransport; - let clientTransport = new LocalDebuggerTransport(serverTransport); - serverTransport.other = clientTransport; - let connection = this._onConnection(serverTransport); - - // I'm putting this here because I trust you. - // - // There are times, when using a local connection, when you're going - // to be tempted to just get direct access to the server. Resist that - // temptation! If you succumb to that temptation, you will make the - // fine developers that work on Fennec and Firefox OS sad. They're - // professionals, they'll try to act like they understand, but deep - // down you'll know that you hurt them. - // - // This reference allows you to give in to that temptation. There are - // times this makes sense: tests, for example, and while porting a - // previously local-only codebase to the remote protocol. - // - // But every time you use this, you will feel the shame of having - // used a property that starts with a '_'. - clientTransport._serverConnection = connection; - - return clientTransport; - }, - - - // nsIServerSocketListener implementation - - onSocketAccepted: - makeInfallible(function DS_onSocketAccepted(aSocket, aTransport) { - if (!this._allowConnection()) { - return; - } - dumpn("New debugging connection on " + aTransport.host + ":" + aTransport.port); - - let input = aTransport.openInputStream(0, 0, 0); - let output = aTransport.openOutputStream(0, 0, 0); - let transport = new DebuggerTransport(input, output); - DebuggerServer._onConnection(transport); - }, "DebuggerServer.onSocketAccepted"), - - onStopListening: function DS_onStopListening(aSocket, status) { - dumpn("onStopListening, status: " + status); - }, - - /** - * Raises an exception if the server has not been properly initialized. - */ - _checkInit: function DS_checkInit() { - if (!this._transportInitialized) { - throw "DebuggerServer has not been initialized."; - } - - if (!this.createRootActor) { - throw "Use DebuggerServer.addActors() to add a root actor implementation."; - } - }, - - /** - * Create a new debugger connection for the given transport. Called - * after connectPipe() or after an incoming socket connection. - */ - _onConnection: function DS_onConnection(aTransport) { - log("DebuggerServer._onConnection...."); - - this._transport = aTransport; - - let connID = "conn" + this._nextConnID++ + '.'; - let conn = new DebuggerServerConnection(connID, aTransport); - this._connections[connID] = conn; - - // Create a root actor for the connection and send the hello packet. - conn.rootActor = this.createRootActor(conn); - conn.addActor(conn.rootActor); - - aTransport.send(conn.rootActor.sayHello()); - aTransport.ready(); - - return conn; - }, - - /** - * Remove the connection from the debugging server. - */ - _connectionClosed: function DS_connectionClosed(aConnection) { - delete this._connections[aConnection.prefix]; - }, - - // DebuggerServer extension API. - - /** - * Registers handlers for new tab-scoped request types defined dynamically. - * This is used for example by add-ons to augment the functionality of the tab - * actor. Note that the name or actorPrefix of the request type is not allowed - * to clash with existing protocol packet properties, like 'title', 'url' or - * 'actor', since that would break the protocol. - * - * @param aFunction function - * The constructor function for this request type. This expects to be - * called as a constructor (i.e. with 'new'), and passed two - * arguments: the DebuggerServerConnection, and the BrowserTabActor - * with which it will be associated. - * - * @param aName string [optional] - * The name of the new request type. If this is not present, the - * actorPrefix property of the constructor prototype is used. - */ - addTabActor: function DS_addTabActor(aFunction, aName) { - let name = aName ? aName : aFunction.prototype.actorPrefix; - if (["title", "url", "actor"].indexOf(name) != -1) { - throw Error(name + " is not allowed"); - } - if (DebuggerServer.tabActorFactories.hasOwnProperty(name)) { - throw Error(name + " already exists"); - } - DebuggerServer.tabActorFactories[name] = aFunction; - }, - - /** - * Unregisters the handler for the specified tab-scoped request type. - * This may be used for example by add-ons when shutting down or upgrading. - * - * @param aFunction function - * The constructor function for this request type. - */ - removeTabActor: function DS_removeTabActor(aFunction) { - for (let name in DebuggerServer.tabActorFactories) { - let handler = DebuggerServer.tabActorFactories[name]; - if (handler.name == aFunction.name) { - delete DebuggerServer.tabActorFactories[name]; - } - } - }, - - /** - * Registers handlers for new browser-scoped request types defined - * dynamically. This is used for example by add-ons to augment the - * functionality of the root actor. Note that the name or actorPrefix of the - * request type is not allowed to clash with existing protocol packet - * properties, like 'from', 'tabs' or 'selected', since that would break the - * protocol. - * - * @param aFunction function - * The constructor function for this request type. This expects to be - * called as a constructor (i.e. with 'new'), and passed two - * arguments: the DebuggerServerConnection, and the BrowserRootActor - * with which it will be associated. - * - * @param aName string [optional] - * The name of the new request type. If this is not present, the - * actorPrefix property of the constructor prototype is used. - */ - addGlobalActor: function DS_addGlobalActor(aFunction, aName) { - let name = aName ? aName : aFunction.prototype.actorPrefix; - if (["from", "tabs", "selected"].indexOf(name) != -1) { - throw Error(name + " is not allowed"); - } - if (DebuggerServer.globalActorFactories.hasOwnProperty(name)) { - throw Error(name + " already exists"); - } - DebuggerServer.globalActorFactories[name] = aFunction; - }, - - /** - * Unregisters the handler for the specified browser-scoped request type. - * This may be used for example by add-ons when shutting down or upgrading. - * - * @param aFunction function - * The constructor function for this request type. - */ - removeGlobalActor: function DS_removeGlobalActor(aFunction) { - for (let name in DebuggerServer.globalActorFactories) { - let handler = DebuggerServer.globalActorFactories[name]; - if (handler.name == aFunction.name) { - delete DebuggerServer.globalActorFactories[name]; - } - } - } -}; - - -/** - * Construct an ActorPool. - * - * ActorPools are actorID -> actor mapping and storage. These are - * used to accumulate and quickly dispose of groups of actors that - * share a lifetime. - */ -function ActorPool(aConnection) -{ - this.conn = aConnection; - this._cleanups = {}; - this._actors = {}; -} - -ActorPool.prototype = { - /** - * Add an actor to the actor pool. If the actor doesn't have an ID, - * allocate one from the connection. - * - * @param aActor object - * The actor implementation. If the object has a - * 'disconnect' property, it will be called when the actor - * pool is cleaned up. - */ - addActor: function AP_addActor(aActor) { - aActor.conn = this.conn; - if (!aActor.actorID) { - let prefix = aActor.actorPrefix; - if (typeof aActor == "function") { - prefix = aActor.prototype.actorPrefix; - } - aActor.actorID = this.conn.allocID(prefix || undefined); - } - - if (aActor.registeredPool) { - aActor.registeredPool.removeActor(aActor); - } - aActor.registeredPool = this; - - this._actors[aActor.actorID] = aActor; - if (aActor.disconnect) { - this._cleanups[aActor.actorID] = aActor; - } - }, - - get: function AP_get(aActorID) { - return this._actors[aActorID]; - }, - - has: function AP_has(aActorID) { - return aActorID in this._actors; - }, - - /** - * Returns true if the pool is empty. - */ - isEmpty: function AP_isEmpty() { - return Object.keys(this._actors).length == 0; - }, - - /** - * Remove an actor from the actor pool. - */ - removeActor: function AP_remove(aActor) { - delete this._actors[aActor.actorID]; - delete this._cleanups[aActor.actorID]; - }, - - /** - * Match the api expected by the protocol library. - */ - unmanage: function(aActor) { - return this.removeActor(aActor); - }, - - /** - * Run all actor cleanups. - */ - cleanup: function AP_cleanup() { - for each (let actor in this._cleanups) { - actor.disconnect(); - } - this._cleanups = {}; - } -} - -/** - * Creates a DebuggerServerConnection. - * - * Represents a connection to this debugging global from a client. - * Manages a set of actors and actor pools, allocates actor ids, and - * handles incoming requests. - * - * @param aPrefix string - * All actor IDs created by this connection should be prefixed - * with aPrefix. - * @param aTransport transport - * Packet transport for the debugging protocol. - */ -function DebuggerServerConnection(aPrefix, aTransport) -{ - this._prefix = aPrefix; - this._transport = aTransport; - this._transport.hooks = this; - this._nextID = 1; - - this._actorPool = new ActorPool(this); - this._extraPools = []; -} - -DebuggerServerConnection.prototype = { - _prefix: null, - get prefix() { return this._prefix }, - - _transport: null, - get transport() { return this._transport }, - - close: function() { - this._transport.close(); - }, - - send: function DSC_send(aPacket) { - this.transport.send(aPacket); - }, - - allocID: function DSC_allocID(aPrefix) { - return this.prefix + (aPrefix || '') + this._nextID++; - }, - - /** - * Add a map of actor IDs to the connection. - */ - addActorPool: function DSC_addActorPool(aActorPool) { - this._extraPools.push(aActorPool); - }, - - /** - * Remove a previously-added pool of actors to the connection. - * - * @param ActorPool aActorPool - * The ActorPool instance you want to remove. - * @param boolean aCleanup - * True if you want to disconnect each actor from the pool, false - * otherwise. - */ - removeActorPool: function DSC_removeActorPool(aActorPool, aCleanup) { - let index = this._extraPools.lastIndexOf(aActorPool); - if (index > -1) { - let pool = this._extraPools.splice(index, 1); - if (aCleanup) { - pool.map(function(p) { p.cleanup(); }); - } - } - }, - - /** - * Add an actor to the default actor pool for this connection. - */ - addActor: function DSC_addActor(aActor) { - this._actorPool.addActor(aActor); - }, - - /** - * Remove an actor to the default actor pool for this connection. - */ - removeActor: function DSC_removeActor(aActor) { - this._actorPool.removeActor(aActor); - }, - - /** - * Match the api expected by the protocol library. - */ - unmanage: function(aActor) { - return this.removeActor(aActor); - }, - - /** - * Look up an actor implementation for an actorID. Will search - * all the actor pools registered with the connection. - * - * @param aActorID string - * Actor ID to look up. - */ - getActor: function DSC_getActor(aActorID) { - let pool = this.poolFor(aActorID); - if (pool) { - return pool.get(aActorID); - } - - if (aActorID === "root") { - return this.rootActor; - } - - return null; - }, - - poolFor: function DSC_actorPool(aActorID) { - if (this._actorPool && this._actorPool.has(aActorID)) { - return this._actorPool; - } - - for (let pool of this._extraPools) { - if (pool.has(aActorID)) { - return pool; - } - } - return null; - }, - - _unknownError: function DSC__unknownError(aPrefix, aError) { - let errorString = safeErrorString(aError); - errorString += "\n" + aError.stack; - // Cu.reportError(errorString); - dumpn(errorString); - return { - error: "unknownError", - message: (aPrefix + "': " + errorString) - }; - }, - - // Transport hooks. - - /** - * Called by DebuggerTransport to dispatch incoming packets as appropriate. - * - * @param aPacket object - * The incoming packet. - */ - onPacket: function DSC_onPacket(aPacket) { - let actor = this.getActor(aPacket.to); - if (!actor) { - this.transport.send({ from: aPacket.to ? aPacket.to : "root", - error: "noSuchActor" }); - return; - } - - // Dyamically-loaded actors have to be created lazily. - if (typeof actor == "function") { - let instance; - try { - instance = new actor(); - } catch (e) { - this.transport.send(this._unknownError( - "Error occurred while creating actor '" + actor.name, - e)); - } - instance.parentID = actor.parentID; - // We want the newly-constructed actor to completely replace the factory - // actor. Reusing the existing actor ID will make sure ActorPool.addActor - // does the right thing. - instance.actorID = actor.actorID; - actor.registeredPool.addActor(instance); - actor = instance; - } - - var ret = null; - // log("actor.requestTypes: "+actor.requestTypes+", cb: "+actor.requestTypes[aPacket.type]); - // Dispatch the request to the actor. - if (actor.requestTypes && actor.requestTypes[aPacket.type]) { - try { - this.currentPacket = aPacket; - ret = actor.requestTypes[aPacket.type].bind(actor)(aPacket, this); - } catch(e) { - this.transport.send(this._unknownError( - "error occurred while processing '" + aPacket.type, - e)); - } finally { - delete this.currentPacket; - } - } else { - ret = { error: "unrecognizedPacketType", - message: ('Actor "' + actor.actorID + - '" does not recognize the packet type "' + - aPacket.type + '"') }; - } - - if (!ret) { - // This should become an error once we've converted every user - // of this to promises in bug 794078. - return; - } - - resolve(ret) - .then(null, (e) => { - return this._unknownError( - "error occurred while processing '" + aPacket.type, - e); - }) - .then(function (aResponse) { - if (!aResponse.from) { - aResponse.from = aPacket.to; - } - return aResponse; - }) - .then(this.transport.send.bind(this.transport)); - }, - - /** - * Called by DebuggerTransport when the underlying stream is closed. - * - * @param aStatus nsresult - * The status code that corresponds to the reason for closing - * the stream. - */ - onClosed: function DSC_onClosed(aStatus) { - dumpn("Cleaning up connection."); - - this._actorPool.cleanup(); - this._actorPool = null; - this._extraPools.map(function(p) { p.cleanup(); }); - this._extraPools = null; - - DebuggerServer._connectionClosed(this); - }, - - /* - * Debugging helper for inspecting the state of the actor pools. - */ - _dumpPools: function DSC_dumpPools() { - dumpn("/-------------------- dumping pools:"); - if (this._actorPool) { - dumpn("--------------------- actorPool actors: " + - uneval(Object.keys(this._actorPool._actors))); - } - for each (let pool in this._extraPools) - dumpn("--------------------- extraPool actors: " + - uneval(Object.keys(pool._actors))); - }, - - /* - * Debugging helper for inspecting the state of an actor pool. - */ - _dumpPool: function DSC_dumpPools(aPool) { - dumpn("/-------------------- dumping pool:"); - dumpn("--------------------- actorPool actors: " + - uneval(Object.keys(aPool._actors))); - } -}; - -/** - * Localization convenience methods. - */ -// let L10N = { - -// /** -// * L10N shortcut function. -// * -// * @param string aName -// * @return string -// */ -// getStr: function L10N_getStr(aName) { -// return this.stringBundle.GetStringFromName(aName); -// } -// }; - -// XPCOMUtils.defineLazyGetter(L10N, "stringBundle", function() { -// return Services.strings.createBundle(DBG_STRINGS_URI); -// }); diff --git a/scripting/javascript/bindings/js/debugger/transport.js b/scripting/javascript/bindings/js/debugger/transport.js deleted file mode 100644 index 8676e367a8..0000000000 --- a/scripting/javascript/bindings/js/debugger/transport.js +++ /dev/null @@ -1,288 +0,0 @@ -/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; -// Components.utils.import("resource://gre/modules/NetUtil.jsm"); - -/** - * An adapter that handles data transfers between the debugger client and - * server. It can work with both nsIPipe and nsIServerSocket transports so - * long as the properly created input and output streams are specified. - * - * @param aInput nsIInputStream - * The input stream. - * @param aOutput nsIAsyncOutputStream - * The output stream. - * - * Given a DebuggerTransport instance dt: - * 1) Set dt.hooks to a packet handler object (described below). - * 2) Call dt.ready() to begin watching for input packets. - * 3) Send packets as you please, and handle incoming packets passed to - * hook.onPacket. - * 4) Call dt.close() to close the connection, and disengage from the event - * loop. - * - * A packet handler object is an object with two methods: - * - * - onPacket(packet) - called when we have received a complete packet. - * |Packet| is the parsed form of the packet --- a JavaScript value, not - * a JSON-syntax string. - * - * - onClosed(status) - called when the connection is closed. |Status| is - * an nsresult, of the sort passed to nsIRequestObserver. - * - * Data is transferred as a JSON packet serialized into a string, with the - * string length prepended to the packet, followed by a colon - * ([length]:[packet]). The contents of the JSON packet are specified in - * the Remote Debugging Protocol specification. - */ -this.DebuggerTransport = function DebuggerTransport(aInput, aOutput) -{ - this._input = aInput; - this._output = aOutput; - - this._converter = null;//Cc["@mozilla.org/intl/scriptableunicodeconverter"] - // .createInstance(Ci.nsIScriptableUnicodeConverter); - // this._converter.charset = "UTF-8"; - - this._outgoing = ""; - this._incoming = ""; - - this.hooks = null; -} - -DebuggerTransport.prototype = { - /** - * Transmit a packet. - * - * This method returns immediately, without waiting for the entire - * packet to be transmitted, registering event handlers as needed to - * transmit the entire packet. Packets are transmitted in the order - * they are passed to this method. - */ - send: function DT_send(aPacket) { - // TODO (bug 709088): remove pretty printing when the protocol is done. - let data = JSON.stringify(aPacket, null, 2); - // data = this._converter.ConvertFromUnicode(data); - - let data_for_len = utf16to8(data); - - this._outgoing = data_for_len.length + ':' + data; - - this._flushOutgoing(); - }, - - /** - * Close the transport. - */ - close: function DT_close() { - this._input.close(); - this._output.close(); - }, - - /** - * Flush the outgoing stream. - */ - _flushOutgoing: function DT_flushOutgoing() { - if (this._outgoing.length > 0) { - // var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - // this._output.asyncWait(this, 0, 0, threadManager.currentThread); - log("outgoing: " + this._outgoing);//.substring(0, 200)); - _bufferWrite(this._outgoing); - } - }, - - onOutputStreamReady: - makeInfallible(function DT_onOutputStreamReady(aStream) { - let written = 0; - try { - written = aStream.write(this._outgoing, this._outgoing.length); - } catch(e if e.result == Components.results.NS_BASE_STREAM_CLOSED) { - dumpn("Connection closed."); - this.close(); - return; - } - this._outgoing = this._outgoing.slice(written); - this._flushOutgoing(); - }, "DebuggerTransport.prototype.onOutputStreamReady"), - - /** - * Initialize the input stream for reading. Once this method has been - * called, we watch for packets on the input stream, and pass them to - * this.hook.onPacket. - */ - ready: function DT_ready() { - // let pump = Cc["@mozilla.org/network/input-stream-pump;1"] - // .createInstance(Ci.nsIInputStreamPump); - // pump.init(this._input, -1, -1, 0, 0, false); - // pump.asyncRead(this, null); - }, - - // nsIStreamListener - onStartRequest: - makeInfallible(function DT_onStartRequest(aRequest, aContext) {}, - "DebuggerTransport.prototype.onStartRequest"), - - onStopRequest: - makeInfallible(function DT_onStopRequest(aRequest, aContext, aStatus) { - this.close(); - if (this.hooks) { - this.hooks.onClosed(aStatus); - this.hooks = null; - } - }, "DebuggerTransport.prototype.onStopRequest"), - - onDataAvailable: makeInfallible(function DT_onDataAvailable (incoming) -// makeInfallible(function DT_onDataAvailable(aRequest, aContext, -// aStream, aOffset, aCount) - { - this._incoming = incoming;//+= NetUtil.readInputStreamToString(aStream, - // aStream.available()); - while (this._processIncoming()) {}; - }, "DebuggerTransport.prototype.onDataAvailable"), - - /** - * Process incoming packets. Returns true if a packet has been received, either - * if it was properly parsed or not. Returns false if the incoming stream does - * not contain a full packet yet. After a proper packet is parsed, the dispatch - * handler DebuggerTransport.hooks.onPacket is called with the packet as a - * parameter. - */ - _processIncoming: function DT__processIncoming() { - // Well this is ugly. - let sep = this._incoming.indexOf(':'); - if (sep < 0) { - return false; - } - - let count = parseInt(this._incoming.substring(0, sep)); - if (this._incoming.length - (sep + 1) < count) { - // Don't have a complete request yet. - return false; - } - - // We have a complete request, pluck it out of the data and parse it. - this._incoming = this._incoming.substring(sep + 1); - let packet = this._incoming.substring(0, count); - this._incoming = this._incoming.substring(count); - - try { - // packet = this._converter.ConvertToUnicode(packet); - packet = utf8to16(packet); - var parsed = JSON.parse(packet); - } catch(e) { - let msg = "Error parsing incoming packet: " + packet + " (" + e + " - " + e.stack + ")"; - // if (Cu.reportError) { - // Cu.reportError(msg); - // } - dump(msg + "\n"); - return true; - } - - dumpn("Got: " + packet); - let self = this; - - // Services.tm.currentThread.dispatch(makeInfallible(function() { - self.hooks.onPacket(parsed); - // }, "DebuggerTransport instance's this.hooks.onPacket"), 0); - - return true; - } -} - - -/** - * An adapter that handles data transfers between the debugger client and - * server when they both run in the same process. It presents the same API as - * DebuggerTransport, but instead of transmitting serialized messages across a - * connection it merely calls the packet dispatcher of the other side. - * - * @param aOther LocalDebuggerTransport - * The other endpoint for this debugger connection. - * - * @see DebuggerTransport - */ -this.LocalDebuggerTransport = function LocalDebuggerTransport(aOther) -{ - this.other = aOther; - this.hooks = null; - - /* - * A packet number, shared between this and this.other. This isn't used - * by the protocol at all, but it makes the packet traces a lot easier to - * follow. - */ - this._serial = this.other ? this.other._serial : { count: 0 }; -} - -LocalDebuggerTransport.prototype = { - /** - * Transmit a message by directly calling the onPacket handler of the other - * endpoint. - */ - send: function LDT_send(aPacket) { - let serial = this._serial.count++; - if (wantLogging) { - if (aPacket.to) { - dumpn("Packet " + serial + " sent to " + uneval(aPacket.to)); - } else if (aPacket.from) { - dumpn("Packet " + serial + " sent from " + uneval(aPacket.from)); - } - } - this._deepFreeze(aPacket); - let other = this.other; - if (other) { - Services.tm.currentThread.dispatch(makeInfallible(function() { - // Avoid the cost of JSON.stringify() when logging is disabled. - if (wantLogging) { - dumpn("Received packet " + serial + ": " + JSON.stringify(aPacket, null, 2)); - } - if (other.hooks) { - other.hooks.onPacket(aPacket); - } - }, "LocalDebuggerTransport instance's this.other.hooks.onPacket"), 0); - } - }, - - /** - * Close the transport. - */ - close: function LDT_close() { - if (this.other) { - // Remove the reference to the other endpoint before calling close(), to - // avoid infinite recursion. - let other = this.other; - delete this.other; - other.close(); - } - if (this.hooks) { - this.hooks.onClosed(); - this.hooks = null; - } - }, - - /** - * An empty method for emulating the DebuggerTransport API. - */ - ready: function LDT_ready() {}, - - /** - * Helper function that makes an object fully immutable. - */ - _deepFreeze: function LDT_deepFreeze(aObject) { - Object.freeze(aObject); - for (let prop in aObject) { - // Freeze the properties that are objects, not on the prototype, and not - // already frozen. Note that this might leave an unfrozen reference - // somewhere in the object if there is an already frozen object containing - // an unfrozen object. - if (aObject.hasOwnProperty(prop) && typeof aObject === "object" && - !Object.isFrozen(aObject)) { - this._deepFreeze(o[prop]); - } - } - } -}; diff --git a/scripting/lua/proj.emscripten/Makefile b/scripting/lua/proj.emscripten/Makefile deleted file mode 100644 index 5c978d7a0f..0000000000 --- a/scripting/lua/proj.emscripten/Makefile +++ /dev/null @@ -1,77 +0,0 @@ -TARGET = liblua.so - -INCLUDES += -I.. -I../lua -I../tolua -I../cocos2dx_support -I../../auto-generated/lua-bindings \ - -I../Classes -I../../../CocosDenshion/include -I../../../extensions - -SOURCES = ../lua/lapi.c \ - ../lua/lauxlib.c \ - ../lua/lbaselib.c \ - ../lua/lcode.c \ - ../lua/ldblib.c \ - ../lua/ldebug.c \ - ../lua/ldo.c \ - ../lua/ldump.c \ - ../lua/lfunc.c \ - ../lua/lgc.c \ - ../lua/linit.c \ - ../lua/liolib.c \ - ../lua/llex.c \ - ../lua/lmathlib.c \ - ../lua/lmem.c \ - ../lua/loadlib.c \ - ../lua/lobject.c \ - ../lua/lopcodes.c \ - ../lua/loslib.c \ - ../lua/lparser.c \ - ../lua/lstate.c \ - ../lua/lstring.c \ - ../lua/lstrlib.c \ - ../lua/ltable.c \ - ../lua/ltablib.c \ - ../lua/ltm.c \ - ../lua/lundump.c \ - ../lua/lvm.c \ - ../lua/lzio.c \ - ../lua/print.c \ - ../tolua/tolua_event.c \ - ../tolua/tolua_is.c \ - ../tolua/tolua_map.c \ - ../tolua/tolua_push.c \ - ../tolua/tolua_to.c \ - ../cocos2dx_support/tolua_fix.c \ - ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - ../cocos2dx_support/CCLuaBridge.cpp \ - ../cocos2dx_support/CCLuaEngine.cpp \ - ../cocos2dx_support/CCLuaStack.cpp \ - ../cocos2dx_support/CCLuaValue.cpp \ - ../cocos2dx_support/Cocos2dxLuaLoader.cpp \ - ../cocos2dx_support/CCBProxy.cpp \ - ../cocos2dx_support/LuaOpengl.cpp \ - ../cocos2dx_support/LuaScriptHandlerMgr.cpp \ - ../cocos2dx_support/LuaBasicConversions.cpp \ - ../cocos2dx_support/lua_cocos2dx_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_extension_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_deprecated.cpp - -include ../../../cocos2dx/proj.emscripten/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/scripting/lua/proj.nacl/Makefile b/scripting/lua/proj.nacl/Makefile deleted file mode 100644 index 2a5c081487..0000000000 --- a/scripting/lua/proj.nacl/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -INCLUDES = -I.. -I../lua -I../../../extensions -I../../../external/chipmunk/include/chipmunk - -SOURCES = ../lua/lapi.c \ - ../lua/lauxlib.c \ - ../lua/lbaselib.c \ - ../lua/lcode.c \ - ../lua/ldblib.c \ - ../lua/ldebug.c \ - ../lua/ldo.c \ - ../lua/ldump.c \ - ../lua/lfunc.c \ - ../lua/lgc.c \ - ../lua/linit.c \ - ../lua/liolib.c \ - ../lua/llex.c \ - ../lua/lmathlib.c \ - ../lua/lmem.c \ - ../lua/loadlib.c \ - ../lua/lobject.c \ - ../lua/lopcodes.c \ - ../lua/loslib.c \ - ../lua/lparser.c \ - ../lua/lstate.c \ - ../lua/lstring.c \ - ../lua/lstrlib.c \ - ../lua/ltable.c \ - ../lua/ltablib.c \ - ../lua/ltm.c \ - ../lua/lundump.c \ - ../lua/lvm.c \ - ../lua/lzio.c \ - ../lua/print.c \ - ../tolua/tolua_event.c \ - ../tolua/tolua_is.c \ - ../tolua/tolua_map.c \ - ../tolua/tolua_push.c \ - ../tolua/tolua_to.c - -COCOS_ROOT = ../../.. - -include $(COCOS_ROOT)/cocos2dx/proj.nacl/cocos2dx.mk - -CCFLAGS = -Wno-uninitialized - -TARGET = $(LIB_DIR)/liblua.a -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - $(LOG_AR)$(NACL_AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(NACL_CC) -MMD $(CCFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(NACL_CXX) -MMD $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/scripting/lua/proj.qt5/lua.pro b/scripting/lua/proj.qt5/lua.pro deleted file mode 100644 index c6a146d36e..0000000000 --- a/scripting/lua/proj.qt5/lua.pro +++ /dev/null @@ -1,33 +0,0 @@ - -include(../../../cocos2dx/proj.qt5/common.pri) - -TEMPLATE = lib -CONFIG += static -CONFIG += c++11 - -SOURCES += $$files(../lua/*.c) -SOURCES += $$files(../tolua/*.c) -SOURCES += $$files(../cocos2dx_support/*.c) -SOURCES += $$files(../cocos2dx_support/*.cpp) -SOURCES += $$files(../cocos2dx_support/generated/*.cpp) - -DEFINES += CC_TARGET_OS_MAC - -INCLUDEPATH += .. -INCLUDEPATH += ../lua -INCLUDEPATH += ../tolua -INCLUDEPATH += ../Classes -INCLUDEPATH += ../../../CocosDenshion/include -INCLUDEPATH += ../../../extensions -INCLUDEPATH += ../../../external/chipmunk/include/chipmunk -INCLUDEPATH += ../../../cocos2dx/include -INCLUDEPATH += ../../../cocos2dx -INCLUDEPATH += ../../../cocos2dx/platform/qt5 -INCLUDEPATH += ../../../cocos2dx/kazmath/include -INCLUDEPATH += ../cocos2dx_support -INCLUDEPATH += ../cocos2dx_support/generated - -# XXX SHAREDLIBS += -lextension - -TARGET = $${LIB_OUTPUT_DIR}/lua - diff --git a/scripting/lua/proj.tizen/.cproject b/scripting/lua/proj.tizen/.cproject deleted file mode 100644 index 115700b2ea..0000000000 --- a/scripting/lua/proj.tizen/.cproject +++ /dev/null @@ -1,349 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/scripting/lua/proj.tizen/.project b/scripting/lua/proj.tizen/.project deleted file mode 100644 index 63ebdf667e..0000000000 --- a/scripting/lua/proj.tizen/.project +++ /dev/null @@ -1,106 +0,0 @@ - - - lua - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - sbi-make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/${ProjName}/Debug-Tizen-Emulator} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - org.tizen.nativecpp.apichecker.core.builder - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.tizen.nativecpp.apichecker.core.tizenCppNature - - - - src/cocos2dx_support - 2 - PARENT-1-PROJECT_LOC/cocos2dx_support - - - src/lua - 2 - PARENT-1-PROJECT_LOC/lua - - - src/tolua - 2 - PARENT-1-PROJECT_LOC/tolua - - - diff --git a/scripting/lua/proj.tizen/src/placeholder.txt b/scripting/lua/proj.tizen/src/placeholder.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tools/android-buildsetup.sh b/tools/android-buildsetup.sh deleted file mode 100755 index 1854d99b4d..0000000000 --- a/tools/android-buildsetup.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash - -# Set up this cocos2d-x directory to build the Android port -# -# 1. Generate local.properties where necessary -# The END - -# exit this script if any commmand fails -set -e - -# read user.cfg if it exists and is readable - -_CFG_FILE=$(dirname "$0")"/user.cfg" -if [ -f "$_CFG_FILE" ] -then - [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable" - . "$_CFG_FILE" -fi - -# paths - -if [ -z "${ANDROID_SDK_ROOT+aaa}" ]; then -# ... if ANDROID_SDK_ROOT is not set, use "$HOME/bin/android-sdk" - ANDROID_SDK_ROOT="$HOME/bin/android-sdk" -fi - -if [ -z "${ANDROID_NDK_ROOT+aaa}" ]; then -# ... if ANDROID_NDK_ROOT is not set, use "$HOME/bin/android-ndk" - ANDROID_NDK_ROOT="$HOME/bin/android-ndk" -fi - -# find current dir -SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -# find working dir -WORKINGDIR="$(pwd)" - -# paths with defaults hardcoded to relative paths - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then - COCOS2DX_ROOT="$WORKINGDIR" -fi - -if [ ! -f "$COCOS2DX_ROOT/tools/android-buildsetup.sh" ] -then - echo "Run..." - echo "> ./tools/android-buildsetup.sh" - echo "... from the top level of the cocos2d-x source tree" - echo "OR" - echo "Run..." - echo "> COCOS2DX_ROOT= /build/setupandroid.sh" - exit -1 -fi - -echo "Paths :" -echo " ANDROID_SDK_ROOT: $ANDROID_SDK_ROOT" -echo " ANDROID_NDK_ROOT: $ANDROID_NDK_ROOT" -echo " COCOS2DX_ROOT : $COCOS2DX_ROOT" -echo " WORKINGDIR : $WORKINGDIR" -echo " SCRIPTDIR : $SCRIPTDIR" - -_CONTENTS="" -_CONTENTS+="sdk.dir=$ANDROID_SDK_ROOT"'\n' -_CONTENTS+="NDK_ROOT=$ANDROID_NDK_ROOT"'\n' -echo -echo "--- local.properties" -echo "---" -echo -e "$_CONTENTS" -echo "---" - -_ANDROIDMANIFESTS=(`find "$COCOS2DX_ROOT/cocos2dx" -type f -name "AndroidManifest.xml"`) -_ANDROIDMANIFESTS+=(`find "$COCOS2DX_ROOT/samples" -type f -name "AndroidManifest.xml"`) - -for a in "${_ANDROIDMANIFESTS[@]}"; do - _LOCAL_PROPERTIES_FILE=${a/AndroidManifest\.xml/local\.properties} - -# write local.properties if it doesn't already exist - if [ -f "$_LOCAL_PROPERTIES_FILE" ] - then - echo "$_LOCAL_PROPERTIES_FILE exists. skipping overwrite" - else - echo "writing $_LOCAL_PROPERTIES_FILE" - echo -e "$_CONTENTS" > "$_LOCAL_PROPERTIES_FILE" - fi -done diff --git a/tools/android_mk_generator/android_mk_generator.py b/tools/android-mk-generator/android_mk_generator.py similarity index 100% rename from tools/android_mk_generator/android_mk_generator.py rename to tools/android-mk-generator/android_mk_generator.py diff --git a/tools/android_mk_generator/config.py b/tools/android-mk-generator/config.py similarity index 100% rename from tools/android_mk_generator/config.py rename to tools/android-mk-generator/config.py diff --git a/tools/emscripten-templates/basic/index.html b/tools/emscripten-templates/basic/index.html deleted file mode 100644 index 2a30217165..0000000000 --- a/tools/emscripten-templates/basic/index.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - JS_APPLICATION generated by emscripten - - - -
- Cocos2d-x -

JS_APPLICATION

-
-
- Downloading... -
-
-

WebGL Error

-

WebGL is not supported by your browser.

-
-
-

Default quality

- Not ready yet - GO! -
-
-
- -
-
- Resize canvas - Lock/hide mouse pointer -     - -
- - - - - diff --git a/tools/emscripten-templates/iphone-ipad-ipadhd/index.html b/tools/emscripten-templates/iphone-ipad-ipadhd/index.html deleted file mode 100644 index b19939e956..0000000000 --- a/tools/emscripten-templates/iphone-ipad-ipadhd/index.html +++ /dev/null @@ -1,181 +0,0 @@ - - - - - - JS_APPLICATION generated by emscripten - - - -
- Cocos2d-x -

JS_APPLICATION

-
-
- Downloading... -
-
-

WebGL Error

-

WebGL is not supported by your browser.

-
-
-

IPad HD quality

-

2048×1536px

- Not ready yet - GO! -
-
-

IPad quality

-

1024×768px

- Not ready yet - GO! -
-
-

IPhone quality

-

480×320px

- Not ready yet - GO! -
-
- - -
-
-
- -
-
- Resize canvas - Lock/hide mouse pointer -     - -
- - - - - diff --git a/tools/jenkins_scripts/Monkeyrunner_TestCpp.py b/tools/jenkins-scripts/Monkeyrunner_TestCpp.py similarity index 100% rename from tools/jenkins_scripts/Monkeyrunner_TestCpp.py rename to tools/jenkins-scripts/Monkeyrunner_TestCpp.py diff --git a/tools/jenkins_scripts/ReportManager.py b/tools/jenkins-scripts/ReportManager.py similarity index 100% rename from tools/jenkins_scripts/ReportManager.py rename to tools/jenkins-scripts/ReportManager.py diff --git a/tools/jenkins_scripts/ant.properties b/tools/jenkins-scripts/ant.properties similarity index 100% rename from tools/jenkins_scripts/ant.properties rename to tools/jenkins-scripts/ant.properties diff --git a/tools/jenkins_scripts/build.xml b/tools/jenkins-scripts/build.xml similarity index 100% rename from tools/jenkins_scripts/build.xml rename to tools/jenkins-scripts/build.xml diff --git a/tools/jenkins_scripts/mac/android/build-android-2.2-3.2-debug.sh b/tools/jenkins-scripts/mac/android/build-android-2.2-3.2-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/build-android-2.2-3.2-debug.sh rename to tools/jenkins-scripts/mac/android/build-android-2.2-3.2-debug.sh diff --git a/tools/jenkins_scripts/mac/android/build-android-2.2-3.2-release.sh b/tools/jenkins-scripts/mac/android/build-android-2.2-3.2-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/build-android-2.2-3.2-release.sh rename to tools/jenkins-scripts/mac/android/build-android-2.2-3.2-release.sh diff --git a/tools/jenkins_scripts/mac/android/build-android-4.x-debug.sh b/tools/jenkins-scripts/mac/android/build-android-4.x-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/build-android-4.x-debug.sh rename to tools/jenkins-scripts/mac/android/build-android-4.x-debug.sh diff --git a/tools/jenkins_scripts/mac/android/build-android-4.x-release.sh b/tools/jenkins-scripts/mac/android/build-android-4.x-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/build-android-4.x-release.sh rename to tools/jenkins-scripts/mac/android/build-android-4.x-release.sh diff --git a/tools/jenkins_scripts/mac/android/generate-js-cxx-bindings.sh b/tools/jenkins-scripts/mac/android/generate-js-cxx-bindings.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/generate-js-cxx-bindings.sh rename to tools/jenkins-scripts/mac/android/generate-js-cxx-bindings.sh diff --git a/tools/jenkins_scripts/mac/android/test-android-2.2-3.2-debug.sh b/tools/jenkins-scripts/mac/android/test-android-2.2-3.2-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/test-android-2.2-3.2-debug.sh rename to tools/jenkins-scripts/mac/android/test-android-2.2-3.2-debug.sh diff --git a/tools/jenkins_scripts/mac/android/test-android-2.2-3.2-release.sh b/tools/jenkins-scripts/mac/android/test-android-2.2-3.2-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/test-android-2.2-3.2-release.sh rename to tools/jenkins-scripts/mac/android/test-android-2.2-3.2-release.sh diff --git a/tools/jenkins_scripts/mac/android/test-android-4.x-debug.sh b/tools/jenkins-scripts/mac/android/test-android-4.x-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/test-android-4.x-debug.sh rename to tools/jenkins-scripts/mac/android/test-android-4.x-debug.sh diff --git a/tools/jenkins_scripts/mac/android/test-android-4.x-release.sh b/tools/jenkins-scripts/mac/android/test-android-4.x-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/android/test-android-4.x-release.sh rename to tools/jenkins-scripts/mac/android/test-android-4.x-release.sh diff --git a/tools/jenkins_scripts/mac/debug.keystore b/tools/jenkins-scripts/mac/debug.keystore similarity index 100% rename from tools/jenkins_scripts/mac/debug.keystore rename to tools/jenkins-scripts/mac/debug.keystore diff --git a/tools/jenkins_scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.html b/tools/jenkins-scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.html similarity index 100% rename from tools/jenkins_scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.html rename to tools/jenkins-scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.html diff --git a/tools/jenkins_scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.py b/tools/jenkins-scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.py similarity index 100% rename from tools/jenkins_scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.py rename to tools/jenkins-scripts/mac/iOS_SikuliTest.sikuli/iOS_SikuliTest.py diff --git a/tools/jenkins_scripts/mac/ios/build-ios-all.sh b/tools/jenkins-scripts/mac/ios/build-ios-all.sh similarity index 100% rename from tools/jenkins_scripts/mac/ios/build-ios-all.sh rename to tools/jenkins-scripts/mac/ios/build-ios-all.sh diff --git a/tools/jenkins_scripts/mac/ios/build-ios-debug.sh b/tools/jenkins-scripts/mac/ios/build-ios-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/ios/build-ios-debug.sh rename to tools/jenkins-scripts/mac/ios/build-ios-debug.sh diff --git a/tools/jenkins_scripts/mac/ios/build-ios-release.sh b/tools/jenkins-scripts/mac/ios/build-ios-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/ios/build-ios-release.sh rename to tools/jenkins-scripts/mac/ios/build-ios-release.sh diff --git a/tools/jenkins_scripts/mac/ios/iphonesim b/tools/jenkins-scripts/mac/ios/iphonesim similarity index 100% rename from tools/jenkins_scripts/mac/ios/iphonesim rename to tools/jenkins-scripts/mac/ios/iphonesim diff --git a/tools/jenkins_scripts/mac/ios/test-ios-debug.sh b/tools/jenkins-scripts/mac/ios/test-ios-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/ios/test-ios-debug.sh rename to tools/jenkins-scripts/mac/ios/test-ios-debug.sh diff --git a/tools/jenkins_scripts/mac/ios/test-ios-release.sh b/tools/jenkins-scripts/mac/ios/test-ios-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/ios/test-ios-release.sh rename to tools/jenkins-scripts/mac/ios/test-ios-release.sh diff --git a/tools/jenkins_scripts/mac/mac/build-mac-all.sh b/tools/jenkins-scripts/mac/mac/build-mac-all.sh similarity index 100% rename from tools/jenkins_scripts/mac/mac/build-mac-all.sh rename to tools/jenkins-scripts/mac/mac/build-mac-all.sh diff --git a/tools/jenkins_scripts/mac/mac/build-mac-debug.sh b/tools/jenkins-scripts/mac/mac/build-mac-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/mac/build-mac-debug.sh rename to tools/jenkins-scripts/mac/mac/build-mac-debug.sh diff --git a/tools/jenkins_scripts/mac/mac/build-mac-release.sh b/tools/jenkins-scripts/mac/mac/build-mac-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/mac/build-mac-release.sh rename to tools/jenkins-scripts/mac/mac/build-mac-release.sh diff --git a/tools/jenkins_scripts/mac/mac/test-mac-debug.sh b/tools/jenkins-scripts/mac/mac/test-mac-debug.sh similarity index 100% rename from tools/jenkins_scripts/mac/mac/test-mac-debug.sh rename to tools/jenkins-scripts/mac/mac/test-mac-debug.sh diff --git a/tools/jenkins_scripts/mac/mac/test-mac-release.sh b/tools/jenkins-scripts/mac/mac/test-mac-release.sh similarity index 100% rename from tools/jenkins_scripts/mac/mac/test-mac-release.sh rename to tools/jenkins-scripts/mac/mac/test-mac-release.sh diff --git a/tools/jenkins_scripts/mac/rootconfig-mac.sh b/tools/jenkins-scripts/mac/rootconfig-mac.sh similarity index 100% rename from tools/jenkins_scripts/mac/rootconfig-mac.sh rename to tools/jenkins-scripts/mac/rootconfig-mac.sh diff --git a/tools/jenkins_scripts/windows/android/androidtestcommon.bat b/tools/jenkins-scripts/windows/android/androidtestcommon.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/androidtestcommon.bat rename to tools/jenkins-scripts/windows/android/androidtestcommon.bat diff --git a/tools/jenkins_scripts/windows/android/build-android-2.2-3.2-debug.bat b/tools/jenkins-scripts/windows/android/build-android-2.2-3.2-debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/build-android-2.2-3.2-debug.bat rename to tools/jenkins-scripts/windows/android/build-android-2.2-3.2-debug.bat diff --git a/tools/jenkins_scripts/windows/android/build-android-2.2-3.2-release.bat b/tools/jenkins-scripts/windows/android/build-android-2.2-3.2-release.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/build-android-2.2-3.2-release.bat rename to tools/jenkins-scripts/windows/android/build-android-2.2-3.2-release.bat diff --git a/tools/jenkins_scripts/windows/android/build-android-4.x-debug.bat b/tools/jenkins-scripts/windows/android/build-android-4.x-debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/build-android-4.x-debug.bat rename to tools/jenkins-scripts/windows/android/build-android-4.x-debug.bat diff --git a/tools/jenkins_scripts/windows/android/build-android-4.x-release.bat b/tools/jenkins-scripts/windows/android/build-android-4.x-release.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/build-android-4.x-release.bat rename to tools/jenkins-scripts/windows/android/build-android-4.x-release.bat diff --git a/tools/jenkins_scripts/windows/android/rootconfig.sh b/tools/jenkins-scripts/windows/android/rootconfig.sh similarity index 100% rename from tools/jenkins_scripts/windows/android/rootconfig.sh rename to tools/jenkins-scripts/windows/android/rootconfig.sh diff --git a/tools/jenkins_scripts/windows/android/test-android-2.2-3.2-debug.bat b/tools/jenkins-scripts/windows/android/test-android-2.2-3.2-debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/test-android-2.2-3.2-debug.bat rename to tools/jenkins-scripts/windows/android/test-android-2.2-3.2-debug.bat diff --git a/tools/jenkins_scripts/windows/android/test-android-2.2-3.2-release.bat b/tools/jenkins-scripts/windows/android/test-android-2.2-3.2-release.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/test-android-2.2-3.2-release.bat rename to tools/jenkins-scripts/windows/android/test-android-2.2-3.2-release.bat diff --git a/tools/jenkins_scripts/windows/android/test-android-4.x-debug.bat b/tools/jenkins-scripts/windows/android/test-android-4.x-debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/test-android-4.x-debug.bat rename to tools/jenkins-scripts/windows/android/test-android-4.x-debug.bat diff --git a/tools/jenkins_scripts/windows/android/test-android-4.x-release.bat b/tools/jenkins-scripts/windows/android/test-android-4.x-release.bat similarity index 100% rename from tools/jenkins_scripts/windows/android/test-android-4.x-release.bat rename to tools/jenkins-scripts/windows/android/test-android-4.x-release.bat diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action0/ObjectRepository.bdb.REMOVED.git-id b/tools/jenkins-scripts/windows/win32/qtp_win32/Action0/ObjectRepository.bdb.REMOVED.git-id similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action0/ObjectRepository.bdb.REMOVED.git-id rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action0/ObjectRepository.bdb.REMOVED.git-id diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action0/Resource.mtr b/tools/jenkins-scripts/windows/win32/qtp_win32/Action0/Resource.mtr similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action0/Resource.mtr rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action0/Resource.mtr diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action0/Script.mts b/tools/jenkins-scripts/windows/win32/qtp_win32/Action0/Script.mts similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action0/Script.mts rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action0/Script.mts diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action1/ObjectRepository.bdb.REMOVED.git-id b/tools/jenkins-scripts/windows/win32/qtp_win32/Action1/ObjectRepository.bdb.REMOVED.git-id similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action1/ObjectRepository.bdb.REMOVED.git-id rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action1/ObjectRepository.bdb.REMOVED.git-id diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action1/Resource.mtr b/tools/jenkins-scripts/windows/win32/qtp_win32/Action1/Resource.mtr similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action1/Resource.mtr rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action1/Resource.mtr diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Action1/Script.mts b/tools/jenkins-scripts/windows/win32/qtp_win32/Action1/Script.mts similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Action1/Script.mts rename to tools/jenkins-scripts/windows/win32/qtp_win32/Action1/Script.mts diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Default.xls b/tools/jenkins-scripts/windows/win32/qtp_win32/Default.xls similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Default.xls rename to tools/jenkins-scripts/windows/win32/qtp_win32/Default.xls diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Error_Sub.vbs b/tools/jenkins-scripts/windows/win32/qtp_win32/Error_Sub.vbs similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Error_Sub.vbs rename to tools/jenkins-scripts/windows/win32/qtp_win32/Error_Sub.vbs diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Error_appcrash.qrs b/tools/jenkins-scripts/windows/win32/qtp_win32/Error_appcrash.qrs similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Error_appcrash.qrs rename to tools/jenkins-scripts/windows/win32/qtp_win32/Error_appcrash.qrs diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Parameters.mtr b/tools/jenkins-scripts/windows/win32/qtp_win32/Parameters.mtr similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Parameters.mtr rename to tools/jenkins-scripts/windows/win32/qtp_win32/Parameters.mtr diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/Test.tsp b/tools/jenkins-scripts/windows/win32/qtp_win32/Test.tsp similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/Test.tsp rename to tools/jenkins-scripts/windows/win32/qtp_win32/Test.tsp diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/TestCpp_Appcrash.tsr.REMOVED.git-id b/tools/jenkins-scripts/windows/win32/qtp_win32/TestCpp_Appcrash.tsr.REMOVED.git-id similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/TestCpp_Appcrash.tsr.REMOVED.git-id rename to tools/jenkins-scripts/windows/win32/qtp_win32/TestCpp_Appcrash.tsr.REMOVED.git-id diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/default.cfg b/tools/jenkins-scripts/windows/win32/qtp_win32/default.cfg similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/default.cfg rename to tools/jenkins-scripts/windows/win32/qtp_win32/default.cfg diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/default.usp b/tools/jenkins-scripts/windows/win32/qtp_win32/default.usp similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/default.usp rename to tools/jenkins-scripts/windows/win32/qtp_win32/default.usp diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/lock.lck b/tools/jenkins-scripts/windows/win32/qtp_win32/lock.lck similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/lock.lck rename to tools/jenkins-scripts/windows/win32/qtp_win32/lock.lck diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/qtp_win32.usr b/tools/jenkins-scripts/windows/win32/qtp_win32/qtp_win32.usr similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/qtp_win32.usr rename to tools/jenkins-scripts/windows/win32/qtp_win32/qtp_win32.usr diff --git a/tools/jenkins_scripts/windows/win32/qtp_win32/qtrunner.vbs b/tools/jenkins-scripts/windows/win32/qtp_win32/qtrunner.vbs similarity index 100% rename from tools/jenkins_scripts/windows/win32/qtp_win32/qtrunner.vbs rename to tools/jenkins-scripts/windows/win32/qtp_win32/qtrunner.vbs diff --git a/tools/jenkins_scripts/windows/win32/test-win-vs2008-debug.bat b/tools/jenkins-scripts/windows/win32/test-win-vs2008-debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/win32/test-win-vs2008-debug.bat rename to tools/jenkins-scripts/windows/win32/test-win-vs2008-debug.bat diff --git a/tools/jenkins_scripts/windows/win32/test-win-vs2008_release.bat b/tools/jenkins-scripts/windows/win32/test-win-vs2008_release.bat similarity index 100% rename from tools/jenkins_scripts/windows/win32/test-win-vs2008_release.bat rename to tools/jenkins-scripts/windows/win32/test-win-vs2008_release.bat diff --git a/tools/jenkins_scripts/windows/win32/test-win-vs2010_debug.bat b/tools/jenkins-scripts/windows/win32/test-win-vs2010_debug.bat similarity index 100% rename from tools/jenkins_scripts/windows/win32/test-win-vs2010_debug.bat rename to tools/jenkins-scripts/windows/win32/test-win-vs2010_debug.bat diff --git a/tools/jenkins_scripts/windows/win32/test-win-vs2010_release.bat b/tools/jenkins-scripts/windows/win32/test-win-vs2010_release.bat similarity index 100% rename from tools/jenkins_scripts/windows/win32/test-win-vs2010_release.bat rename to tools/jenkins-scripts/windows/win32/test-win-vs2010_release.bat diff --git a/tools/project_creator/__init__.py b/tools/project-creator/__init__.py similarity index 100% rename from tools/project_creator/__init__.py rename to tools/project-creator/__init__.py diff --git a/tools/project_creator/create_project.py b/tools/project-creator/create_project.py similarity index 100% rename from tools/project_creator/create_project.py rename to tools/project-creator/create_project.py From 5acbe663e09c0199263bbaa9b0434d4082eb53d0 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 13:44:57 +0800 Subject: [PATCH 117/557] issue #2905: add missing files --- CODING_STYLE.md | 131 - Emscripten.TODO | 60 - RELEASE_NOTES | 4 - .../bindings/js/debugger/DevToolsUtils.js | 133 + .../javascript/bindings/js/debugger/README.md | 54 + .../bindings/js/debugger/actors/root.js | 329 ++ .../bindings/js/debugger/actors/script.js | 2948 +++++++++++++++++ .../bindings/js/debugger/core/promise.js | 294 ++ .../javascript/bindings/js/debugger/main.js | 928 ++++++ .../bindings/js/debugger/transport.js | 288 ++ 10 files changed, 4974 insertions(+), 195 deletions(-) delete mode 100644 CODING_STYLE.md delete mode 100644 Emscripten.TODO delete mode 100644 RELEASE_NOTES create mode 100644 cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js create mode 100644 cocos/scripting/javascript/bindings/js/debugger/README.md create mode 100644 cocos/scripting/javascript/bindings/js/debugger/actors/root.js create mode 100644 cocos/scripting/javascript/bindings/js/debugger/actors/script.js create mode 100644 cocos/scripting/javascript/bindings/js/debugger/core/promise.js create mode 100644 cocos/scripting/javascript/bindings/js/debugger/main.js create mode 100644 cocos/scripting/javascript/bindings/js/debugger/transport.js diff --git a/CODING_STYLE.md b/CODING_STYLE.md deleted file mode 100644 index 4b7bf2a7c8..0000000000 --- a/CODING_STYLE.md +++ /dev/null @@ -1,131 +0,0 @@ -# cocos2d-x C++ coding sytle - - -## Detailed information - -Please, refer to this document for a detailed version of the cocos2d-x C++ coding sytle: - -* [cocos2d-x c++ coding style](http://www.cocos2d-x.org/wiki/Cocos2d_c++_coding_style) - - -## Quick Sample - -Use this sample as a quick reference. But DO READ the detailed doc for more info. - -Header file: - -```c++ -/** - * We use Doxygen strings for documentation. - * All public classes, methods, structs should be documented using Doxygen Strings - */ -class CC_DLL Sprite : public NodeRGBA, public TextureProtocol -{ /* class braces start in a new line */ - -/* no indentation here for public, protected or private */ -/* First add all the "public" stuff, then all the "protected" stuff, and finally all the "private" stuff -public: - - /* we don't use tabs, we use spaces, and we use a 4 space identation */ - /* 1st add all static const */ - static const int INDEX_NOT_INITIALIZED = -1; - - /* then add all the creators and other relevant static methods */ - static Sprite* create(); - static Sprite* create(const char *filename); - static Sprite* create(const char *filename, const Rect& rect); - - /* if applicable, then add the consturctors / destructors */ - Sprite(); - virtual ~Sprite(void); - - /* then add all the initialization methods */ - /* notice that they are in the same order as the creators */ - virtual bool init(void); - virtual bool initWithTexture(Texture2D *texture); - virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - - - - /* then add the regular instace methods */ - virtual void updateTransform(void); - virtual SpriteBatchNode* getBatchNode(void); - virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - - - /* then add all the overriden methods */ - /* notice that all overriden methods must use the 'override' keyword */ - /* overriden methods are not forced to have doxygen strings UNLESS they change the behavior in a non obvios way */ - virtual void setPosition(const Point& pos) override; - virtual void setRotation(float rotation) override; - virtual void setRotationX(float rotationX) override; - - - /* once you finish with the 'public' methods, start with the 'protected' ones */ -protected: - - /* protected methods are not forced to have Doxygen strings, but if they have it, better */ - void updateColor(void); - virtual void setTextureCoords(Rect rect); - - /* After adding all the methods, add the ivars */ - /* all ivars must start with _ */ - /* Do not use Hungarian notation */ - TextureAtlas* _textureAtlas; - int _atlasIndex; - SpriteBatchNode* _batchNode; -}; - -``` - -Implementation file: - -```c++ -/* Do not use doxygen comments on the implementation file */ - -/* The methos MUST be in the same order as where declared in the header file */ - -Sprite* Sprite::create(const char *filename) -{ - /* Don't use tabs. Use spaces. Use 4-space indentation */ - Sprite *sprite = new Sprite(); - - /* put curly braces in the same line as in the 'if'*/ - /* leave a space between the 'if' and the '(' */ - /* don't leave spaces between '()' */ - if (sprite && sprite->initWithFile(filename)) { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -/* Initialization list can be indented to 0 spaces, or to 4 spaces. If in doubt, be consistent with the indentation already used in the file */ -/* Only use the Initialization lists for types that can't fail when initialized */ -Sprite::Sprite() -: _shouldBeHidden(false) -, _texture(nullptr) -, _physicsBody(nullptr) -{ -} - -/* use the 'initXXX' methods to initialize types that might fail */ -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - /* it ok not use use curly braces */ - if (something) - do_something(); - else - something_else(); - - /* but if you use curly branches in one branch, all the branches should use curly branches */ - if (something) { - do_something1(); - do_something2(); - } else { - so_something_else(); - } -} - -``` diff --git a/Emscripten.TODO b/Emscripten.TODO deleted file mode 100644 index a00ca3ce9e..0000000000 --- a/Emscripten.TODO +++ /dev/null @@ -1,60 +0,0 @@ -* Need to figure out how to get correct screen resolutions consistently. - -* Touch handler screwed up after TouchesTest? MenuTest? (TestCpp sample) - -* TTF Font rendering is slow and seems to wrap around by a few pixels - horizontally. Need to investigate here, but I suspect the right answer is to - offload font rendering to an offscreen canvas and let the browser handle it. - Potentially creates new challenges in packaging which would need to be solved - somehow. - - - -### -DONE: -### - -* Need to switch to server-side buffers in -- cocos2dx/draw_nodes/CCDrawingPrimitives - -* Need to compile with -O2 -- possible -s VERBOSE=1 will give a clue? - -* SchedulerTest crashes - - cocos2d::CCNode::boundingBox() - -* Parallax Test crashes - - cocos2d::CCAtlasNode::calculateMaxItems() - -* Particle Test crashes - - TIFFClientOpen not a function. Looks like we need to build and link in libtiff. - -* cocos2d::CCAtlasNode::calculateMaxItems() throwing an error; related to - CCTextureAtlas? Preventing particle test from working. - -* Need to switch to server-side buffers in -- cocos2dx/draw_nodes/CCDrawNode.cpp -- Think this is fixed by undef CC_TEXTURE_ATLAS_USE_VAO? -- cocos2dx/particle_nodes/CCParticleSystemQuad.cpp -- Think this is fixed by CC_REBIND_INDICES_BUFFER? -- cocos2dx/textures/CCTextureAtlas.cpp -- Think this works already. - -* Layer Test crashes - - cocos2d::CCLabelBMFont::create(char const*, char const*, float, cocos2d::CCTextAlignment, cocos2d::CCPoint) - -* IntervalTest crashes - - cocos2d::CCLabelBMFont::create(char const*, char const*, float, cocos2d::CCTextAlignment, cocos2d::CCPoint) - -* TileMap Test crashes - - void CCNode::insertChild(CCNode* child, int z) - -* LabelTest crashes - - cocos2d::CCAtlasNode::calculateMaxItems() - -* ZwoptexTest crashes. - - ZwoptexGenericTest::onEnter() - -* ChipmunkTest crashes: - Aborting due to Chipmunk error: Moment of Inertia must be positive and non-zero. - Failed condition: moment > 0.0f - Source:../src/cpBody.c:151 - -* Add linkage to libjpeg to get RenderTexture test to work. - diff --git a/RELEASE_NOTES b/RELEASE_NOTES deleted file mode 100644 index f10872da6c..0000000000 --- a/RELEASE_NOTES +++ /dev/null @@ -1,4 +0,0 @@ -===== cocos2d-x 3.0 Release Notes ===== - -Please, read the online release notes document: -http://www.cocos2d-x.org/wiki/Release_Notes_for_Cocos2d-x_v300 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js b/cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js new file mode 100644 index 0000000000..26d0597644 --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js @@ -0,0 +1,133 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +function utf16to8(str) { + var out, i, len, c; + + out = ""; + len = str.length; + for(i = 0; i < len; i++) + { + c = str.charCodeAt(i); + if ((c >= 0x0001) && (c <= 0x007F)) + { + out += str.charAt(i); + } + else if (c > 0x07FF) + { + out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); + out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); + out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); + } + else + { + out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); + out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); + } + } + return out; +} + +function utf8to16(str) { + var out, i, len, c; + var char2, char3; + + out = ""; + len = str.length; + i = 0; + while(i < len) { c = str.charCodeAt(i++); switch(c >> 4) + { + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: + // 0xxxxxxx + out += str.charAt(i-1); + break; + case 12: case 13: + // 110x xxxx 10xx xxxx + char2 = str.charCodeAt(i++); + out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + char2 = str.charCodeAt(i++); + char3 = str.charCodeAt(i++); + out += String.fromCharCode(((c & 0x0F) << 12) | + ((char2 & 0x3F) << 6) | + ((char3 & 0x3F) << 0)); + break; + } + } + + return out; + } + +var dump = function(msg) { + log(msg); +}; + +/* General utilities used throughout devtools. */ + +/* Turn the error e into a string, without fail. */ +this.safeErrorString = function safeErrorString(aError) { + try { + var s = aError.toString(); + if (typeof s === "string") + return s; + } catch (ee) { } + + return ""; +} + +/** + * Report that |aWho| threw an exception, |aException|. + */ +this.reportException = function reportException(aWho, aException) { + let msg = aWho + " threw an exception: " + safeErrorString(aException); + if (aException.stack) { + msg += "\nCall stack:\n" + aException.stack; + } + + dump(msg + "\n"); + + // if (Components.utils.reportError) { + // /* + // * Note that the xpcshell test harness registers an observer for + // * console messages, so when we're running tests, this will cause + // * the test to quit. + // */ + // Components.utils.reportError(msg); + // } +} + +/** + * Given a handler function that may throw, return an infallible handler + * function that calls the fallible handler, and logs any exceptions it + * throws. + * + * @param aHandler function + * A handler function, which may throw. + * @param aName string + * A name for aHandler, for use in error messages. If omitted, we use + * aHandler.name. + * + * (SpiderMonkey does generate good names for anonymous functions, but we + * don't have a way to get at them from JavaScript at the moment.) + */ +this.makeInfallible = function makeInfallible(aHandler, aName) { + if (!aName) + aName = aHandler.name; + + return function (/* arguments */) { + try { + return aHandler.apply(this, arguments); + } catch (ex) { + let who = "Handler function"; + if (aName) { + who += " " + aName; + } + reportException(who, ex); + } + } +} diff --git a/cocos/scripting/javascript/bindings/js/debugger/README.md b/cocos/scripting/javascript/bindings/js/debugger/README.md new file mode 100644 index 0000000000..9e1d7bebd0 --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/README.md @@ -0,0 +1,54 @@ +Remote Debugging By Using FireFox +================================= + +Requirement +----------- + +* Firefox: From v24 + +How To Use +---------- + +### Prepare ### + +Please refer to https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging . + +### Enable Debugger Support For Your JSB Project ### + +``` +bool AppDelegate::applicationDidFinishLaunching() +{ + ... + + ScriptingCore* sc = ScriptingCore::getInstance(); + sc->addRegisterCallback(register_all_cocos2dx); + sc->addRegisterCallback(register_all_cocos2dx_extension); + sc->addRegisterCallback(register_cocos2dx_js_extensions); + sc->addRegisterCallback(jsb_register_chipmunk); + sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + sc->addRegisterCallback(register_CCBuilderReader); + sc->addRegisterCallback(jsb_register_system); + sc->addRegisterCallback(JSB_register_opengl); + + sc->start(); + +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + sc->enableDebugger(); // Enable debugger here +#endif + + ... +} +``` + +Run your game. + +### Open Firefox And Follow The Step As Follows ### + + +![pic 1](https://lh5.googleusercontent.com/-HoxLGBdV2J0/UlZ7ZoFUjyI/AAAAAAAAADM/68GDaCQ1vP0/s0-I/Firefox-Remote-Debug01.jpg) +![pic 2](https://lh6.googleusercontent.com/-7FDIHAYsKAY/UlZ7Yf8W-pI/AAAAAAAAAFQ/joG0AymnuBk/s0-I/Firefox-Remote-Debug02.jpg) +![pic 3](https://lh4.googleusercontent.com/-idvnMRGcGy8/UlZ7Wj6DDuI/AAAAAAAAAC0/L9IVyHLNqeQ/s0-I/Firefox-Remote-Debug04.jpg) +![pic 4](https://lh6.googleusercontent.com/-YuZj7JGAtFE/UlZ9DDGDczI/AAAAAAAAAEQ/D2qIedjP5FU/s0-I/Firefox-Remote-Debug04.png.png) +![pic 5](https://lh3.googleusercontent.com/-cdIcNa3jT5c/UlZ9uapf3OI/AAAAAAAAAEg/MGq3vLHsauw/s0-I/Firefox-Remote-Debug05.png) +![pic 6](https://lh5.googleusercontent.com/-T79-o5ylJKI/UlZ_JJQe3MI/AAAAAAAAAE8/F63fSVxlJKs/s0-I/Firefox-Remote-Debug06.png) + diff --git a/cocos/scripting/javascript/bindings/js/debugger/actors/root.js b/cocos/scripting/javascript/bindings/js/debugger/actors/root.js new file mode 100644 index 0000000000..aa0d85342b --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/actors/root.js @@ -0,0 +1,329 @@ +/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* Root actor for the remote debugging protocol. */ + +/** + * Methods shared between RootActor and BrowserTabActor. + */ + +/** + * Populate |this._extraActors| as specified by |aFactories|, reusing whatever + * actors are already there. Add all actors in the final extra actors table to + * |aPool|. + * + * The root actor and the tab actor use this to instantiate actors that other + * parts of the browser have specified with DebuggerServer.addTabActor antd + * DebuggerServer.addGlobalActor. + * + * @param aFactories + * An object whose own property names are the names of properties to add to + * some reply packet (say, a tab actor grip or the "listTabs" response + * form), and whose own property values are actor constructor functions, as + * documented for addTabActor and addGlobalActor. + * + * @param this + * The BrowserRootActor or BrowserTabActor with which the new actors will + * be associated. It should support whatever API the |aFactories| + * constructor functions might be interested in, as it is passed to them. + * For the sake of CommonCreateExtraActors itself, it should have at least + * the following properties: + * + * - _extraActors + * An object whose own property names are factory table (and packet) + * property names, and whose values are no-argument actor constructors, + * of the sort that one can add to an ActorPool. + * + * - conn + * The DebuggerServerConnection in which the new actors will participate. + * + * - actorID + * The actor's name, for use as the new actors' parentID. + */ +function CommonCreateExtraActors(aFactories, aPool) { + // Walk over global actors added by extensions. + for (let name in aFactories) { + let actor = this._extraActors[name]; + if (!actor) { + actor = aFactories[name].bind(null, this.conn, this); + actor.prototype = aFactories[name].prototype; + actor.parentID = this.actorID; + this._extraActors[name] = actor; + } + aPool.addActor(actor); + } +} + +/** + * Append the extra actors in |this._extraActors|, constructed by a prior call + * to CommonCreateExtraActors, to |aObject|. + * + * @param aObject + * The object to which the extra actors should be added, under the + * property names given in the |aFactories| table passed to + * CommonCreateExtraActors. + * + * @param this + * The BrowserRootActor or BrowserTabActor whose |_extraActors| table we + * should use; see above. + */ +function CommonAppendExtraActors(aObject) { + for (let name in this._extraActors) { + let actor = this._extraActors[name]; + aObject[name] = actor.actorID; + } +} + +/** + * Create a remote debugging protocol root actor. + * + * @param aConnection + * The DebuggerServerConnection whose root actor we are constructing. + * + * @param aParameters + * The properties of |aParameters| provide backing objects for the root + * actor's requests; if a given property is omitted from |aParameters|, the + * root actor won't implement the corresponding requests or notifications. + * Supported properties: + * + * - tabList: a live list (see below) of tab actors. If present, the + * new root actor supports the 'listTabs' request, providing the live + * list's elements as its tab actors, and sending 'tabListChanged' + * notifications when the live list's contents change. One actor in + * this list must have a true '.selected' property. + * + * - globalActorFactories: an object |A| describing further actors to + * attach to the 'listTabs' reply. This is the type accumulated by + * DebuggerServer.addGlobalActor. For each own property |P| of |A|, + * the root actor adds a property named |P| to the 'listTabs' + * reply whose value is the name of an actor constructed by + * |A[P]|. + * + * - onShutdown: a function to call when the root actor is disconnected. + * + * Instance properties: + * + * - applicationType: the string the root actor will include as the + * "applicationType" property in the greeting packet. By default, this + * is "browser". + * + * Live lists: + * + * A "live list", as used for the |tabList|, is an object that presents a + * list of actors, and also notifies its clients of changes to the list. A + * live list's interface is two properties: + * + * - iterator: a method that returns an iterator. A for-of loop will call + * this method to obtain an iterator for the loop, so if LL is + * a live list, one can simply write 'for (i of LL) ...'. + * + * - onListChanged: a handler called, with no arguments, when the set of + * values the iterator would produce has changed since the last + * time 'iterator' was called. This may only be set to null or a + * callable value (one for which the typeof operator returns + * 'function'). (Note that the live list will not call the + * onListChanged handler until the list has been iterated over + * once; if nobody's seen the list in the first place, nobody + * should care if its contents have changed!) + * + * When the list changes, the list implementation should ensure that any + * actors yielded in previous iterations whose referents (tabs) still exist + * get yielded again in subsequent iterations. If the underlying referent + * is the same, the same actor should be presented for it. + * + * The root actor registers an 'onListChanged' handler on the appropriate + * list when it may need to send the client 'tabListChanged' notifications, + * and is careful to remove the handler whenever it does not need to send + * such notifications (including when it is disconnected). This means that + * live list implementations can use the state of the handler property (set + * or null) to install and remove observers and event listeners. + * + * Note that, as the only way for the root actor to see the members of the + * live list is to begin an iteration over the list, the live list need not + * actually produce any actors until they are reached in the course of + * iteration: alliterative lazy live lists. + */ +function RootActor(aConnection, aParameters) { + this.conn = aConnection; + this._parameters = aParameters; + this._onTabListChanged = this.onTabListChanged.bind(this); + this._extraActors = {}; +} + +RootActor.prototype = { + constructor: RootActor, + applicationType: "browser", + + /** + * Return a 'hello' packet as specified by the Remote Debugging Protocol. + */ + sayHello: function() { + return { + from: "root", + applicationType: this.applicationType, + /* This is not in the spec, but it's used by tests. */ + testConnectionPrefix: this.conn.prefix, + traits: { + sources: true + } + }; + }, + + /** + * Disconnects the actor from the browser window. + */ + disconnect: function() { + /* Tell the live lists we aren't watching any more. */ + if (this._parameters.tabList) { + this._parameters.tabList.onListChanged = null; + } + if (typeof this._parameters.onShutdown === 'function') { + this._parameters.onShutdown(); + } + this._extraActors = null; + }, + + /* The 'listTabs' request and the 'tabListChanged' notification. */ + + /** + * Handles the listTabs request. The actors will survive until at least + * the next listTabs request. + */ + onListTabs: function() { + + let tabList = this._parameters.tabList; + if (!tabList) { + return { from: "root", error: "noTabs", + message: "This root actor has no browser tabs." }; + } + + /* + * Walk the tab list, accumulating the array of tab actors for the + * reply, and moving all the actors to a new ActorPool. We'll + * replace the old tab actor pool with the one we build here, thus + * retiring any actors that didn't get listed again, and preparing any + * new actors to receive packets. + */ + let newActorPool = new ActorPool(this.conn); + let tabActorList = []; + let selected; + for (let tabActor of tabList) { + if (tabActor.selected) { + selected = tabActorList.length; + } + tabActor.parentID = this.actorID; + newActorPool.addActor(tabActor); + tabActorList.push(tabActor); + } + + /* DebuggerServer.addGlobalActor support: create actors. */ + this._createExtraActors(this._parameters.globalActorFactories, newActorPool); + + /* + * Drop the old actorID -> actor map. Actors that still mattered were + * added to the new map; others will go away. + */ + if (this._tabActorPool) { + this.conn.removeActorPool(this._tabActorPool); + } + this._tabActorPool = newActorPool; + this.conn.addActorPool(this._tabActorPool); + + let reply = { + "from": "root", + "selected": selected || 0, + "tabs": [actor.grip() for (actor of tabActorList)] + }; + + /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ + this._appendExtraActors(reply); + + /* + * Now that we're actually going to report the contents of tabList to + * the client, we're responsible for letting the client know if it + * changes. + */ + tabList.onListChanged = this._onTabListChanged; + + return reply; + }, + + onTabListChanged: function () { + this.conn.send({ from:"root", type:"tabListChanged" }); + /* It's a one-shot notification; no need to watch any more. */ + this._parameters.tabList.onListChanged = null; + }, + + /* This is not in the spec, but it's used by tests. */ + onEcho: (aRequest) => aRequest, + + /* Support for DebuggerServer.addGlobalActor. */ + _createExtraActors: CommonCreateExtraActors, + _appendExtraActors: CommonAppendExtraActors, + + /* ThreadActor hooks. */ + + /** + * Prepare to enter a nested event loop by disabling debuggee events. + */ + preNest: function() { + // Disable events in all open windows. + let e = windowMediator.getEnumerator(null); + while (e.hasMoreElements()) { + let win = e.getNext(); + let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + windowUtils.suppressEventHandling(true); + windowUtils.suspendTimeouts(); + } + }, + + /** + * Prepare to exit a nested event loop by enabling debuggee events. + */ + postNest: function(aNestData) { + // Enable events in all open windows. + let e = windowMediator.getEnumerator(null); + while (e.hasMoreElements()) { + let win = e.getNext(); + let windowUtils = win.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + windowUtils.resumeTimeouts(); + windowUtils.suppressEventHandling(false); + } + }, + + /* ChromeDebuggerActor hooks. */ + + /** + * Add the specified actor to the default actor pool connection, in order to + * keep it alive as long as the server is. This is used by breakpoints in the + * thread and chrome debugger actors. + * + * @param actor aActor + * The actor object. + */ + addToParentPool: function(aActor) { + this.conn.addActor(aActor); + }, + + /** + * Remove the specified actor from the default actor pool. + * + * @param BreakpointActor aActor + * The actor object. + */ + removeFromParentPool: function(aActor) { + this.conn.removeActor(aActor); + } +} + +RootActor.prototype.requestTypes = { + "listTabs": RootActor.prototype.onListTabs, + "echo": RootActor.prototype.onEcho +}; diff --git a/cocos/scripting/javascript/bindings/js/debugger/actors/script.js b/cocos/scripting/javascript/bindings/js/debugger/actors/script.js new file mode 100644 index 0000000000..7ddade2b54 --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/actors/script.js @@ -0,0 +1,2948 @@ +/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/** + * JSD2 actors. + */ +/** + * Creates a ThreadActor. + * + * ThreadActors manage a JSInspector object and manage execution/inspection + * of debuggees. + * + * @param aHooks object + * An object with preNest and postNest methods for calling when entering + * and exiting a nested event loop, addToParentPool and + * removeFromParentPool methods for handling the lifetime of actors that + * will outlive the thread, like breakpoints. + * @param aGlobal object [optional] + * An optional (for content debugging only) reference to the content + * window. + */ +function ThreadActor(aHooks, aGlobal) +{ + this._state = "detached"; + this._frameActors = []; + this._environmentActors = []; + this._hooks = aHooks; + this.global = aGlobal; + + this.findGlobals = this.globalManager.findGlobals.bind(this); + this.onNewGlobal = this.globalManager.onNewGlobal.bind(this); + this.onNewSource = this.onNewSource.bind(this); + + this._options = { + useSourceMaps: false + }; +} + +/** + * The breakpoint store must be shared across instances of ThreadActor so that + * page reloads don't blow away all of our breakpoints. + */ +ThreadActor._breakpointStore = {}; + +ThreadActor.prototype = { + actorPrefix: "context", + + get state() { return this._state; }, + get attached() this.state == "attached" || + this.state == "running" || + this.state == "paused", + + get _breakpointStore() { return ThreadActor._breakpointStore; }, + + get threadLifetimePool() { + if (!this._threadLifetimePool) { + this._threadLifetimePool = new ActorPool(this.conn); + this.conn.addActorPool(this._threadLifetimePool); + this._threadLifetimePool.objectActors = new WeakMap(); + } + return this._threadLifetimePool; + }, + + get sources() { + if (!this._sources) { + this._sources = new ThreadSources(this, this._options.useSourceMaps, + this._allowSource, this.onNewSource); + } + return this._sources; + }, + + clearDebuggees: function TA_clearDebuggees() { + if (this.dbg) { + this.dbg.removeAllDebuggees(); + } + this.conn.removeActorPool(this._threadLifetimePool || undefined); + this._threadLifetimePool = null; + this._sources = null; + }, + + /** + * Add a debuggee global to the Debugger object. + */ + addDebuggee: function TA_addDebuggee(aGlobal) { + try { + this.dbg.addDebuggee(aGlobal); + } catch (e) { + // Ignore attempts to add the debugger's compartment as a debuggee. + dumpn("Ignoring request to add the debugger's compartment as a debuggee"); + } + }, + + /** + * Initialize the Debugger. + */ + _initDebugger: function TA__initDebugger() { + this.dbg = new Debugger(); + this.dbg.uncaughtExceptionHook = this.uncaughtExceptionHook.bind(this); + this.dbg.onDebuggerStatement = this.onDebuggerStatement.bind(this); + this.dbg.onNewScript = this.onNewScript.bind(this); + this.dbg.onNewGlobalObject = this.globalManager.onNewGlobal.bind(this); + // Keep the debugger disabled until a client attaches. + this.dbg.enabled = this._state != "detached"; + }, + + /** + * Remove a debuggee global from the JSInspector. + */ + removeDebugee: function TA_removeDebuggee(aGlobal) { + try { + this.dbg.removeDebuggee(aGlobal); + } catch(ex) { + // XXX: This debuggee has code currently executing on the stack, + // we need to save this for later. + } + }, + + /** + * Add the provided window and all windows in its frame tree as debuggees. + */ + _addDebuggees: function TA__addDebuggees(aWindow) { + this.addDebuggee(aWindow); + let frames = aWindow.frames; + if (frames) { + for (let i = 0; i < frames.length; i++) { + this._addDebuggees(frames[i]); + } + } + }, + + /** + * An object that will be used by ThreadActors to tailor their behavior + * depending on the debugging context being required (chrome or content). + */ + globalManager: { + findGlobals: function TA_findGlobals() { + this._addDebuggees(this.global); + }, + + /** + * A function that the engine calls when a new global object has been + * created. + * + * @param aGlobal Debugger.Object + * The new global object that was created. + */ + onNewGlobal: function TA_onNewGlobal(aGlobal) { + // Content debugging only cares about new globals in the contant window, + // like iframe children. + if (aGlobal.hostAnnotations && + aGlobal.hostAnnotations.type == "document" && + aGlobal.hostAnnotations.element === this.global) { + this.addDebuggee(aGlobal); + // Notify the client. + this.conn.send({ + from: this.actorID, + type: "newGlobal", + // TODO: after bug 801084 lands see if we need to JSONify this. + hostAnnotations: aGlobal.hostAnnotations + }); + } + } + }, + + disconnect: function TA_disconnect() { + dumpn("in ThreadActor.prototype.disconnect"); + if (this._state == "paused") { + this.onResume(); + } + + this._state = "exited"; + + this.clearDebuggees(); + + if (!this.dbg) { + return; + } + this.dbg.enabled = false; + this.dbg = null; + }, + + /** + * Disconnect the debugger and put the actor in the exited state. + */ + exit: function TA_exit() { + this.disconnect(); + }, + + // Request handlers + onAttach: function TA_onAttach(aRequest) { + if (this.state === "exited") { + return { type: "exited" }; + } + + if (this.state !== "detached") { + return { error: "wrongState" }; + } + + this._state = "attached"; + + update(this._options, aRequest.options || {}); + + if (!this.dbg) { + this._initDebugger(); + } + this.findGlobals(); + this.dbg.enabled = true; + try { + // Put ourselves in the paused state. + let packet = this._paused(); + if (!packet) { + return { error: "notAttached" }; + } + packet.why = { type: "attached" }; + + this._restoreBreakpoints(); + + // Send the response to the attach request now (rather than + // returning it), because we're going to start a nested event loop + // here. + this.conn.send(packet); + + // Start a nested event loop. + this._nest(); + + // We already sent a response to this request, don't send one + // now. + return null; + } catch (e) { + reportError(e); + return { error: "notAttached", message: e.toString() }; + } + }, + + onDetach: function TA_onDetach(aRequest) { + this.disconnect(); + dumpn("ThreadActor.prototype.onDetach: returning 'detached' packet"); + return { + type: "detached" + }; + }, + + onReconfigure: function TA_onReconfigure(aRequest) { + if (this.state == "exited") { + return { error: "wrongState" }; + } + + update(this._options, aRequest.options || {}); + // Clear existing sources, so they can be recreated on next access. + this._sources = null; + + return {}; + }, + + /** + * Pause the debuggee, by entering a nested event loop, and return a 'paused' + * packet to the client. + * + * @param Debugger.Frame aFrame + * The newest debuggee frame in the stack. + * @param object aReason + * An object with a 'type' property containing the reason for the pause. + * @param function onPacket + * Hook to modify the packet before it is sent. Feel free to return a + * promise. + */ + _pauseAndRespond: function TA__pauseAndRespond(aFrame, aReason, + onPacket=function (k) k) { + try { + let packet = this._paused(aFrame); + if (!packet) { + return undefined; + } + packet.why = aReason; + resolve(onPacket(packet)).then(this.conn.send.bind(this.conn)); + return this._nest(); + } catch(e) { + let msg = "Got an exception during TA__pauseAndRespond: " + e + + ": " + e.stack; + // Cu.reportError(msg); + dumpn(msg); + return undefined; + } + }, + + /** + * Handle a protocol request to resume execution of the debuggee. + */ + onResume: function TA_onResume(aRequest) { + if (this._state !== "paused") { + return { + error: "wrongState", + message: "Can't resume when debuggee isn't paused. Current state is '" + + this._state + "'" + }; + } + + // In case of multiple nested event loops (due to multiple debuggers open in + // different tabs or multiple debugger clients connected to the same tab) + // only allow resumption in a LIFO order. + if (DebuggerServer.xpcInspector.eventLoopNestLevel() > 1) { + log("DebuggerServer.xpcInspector.eventLoopNestLevel: "+DebuggerServer.xpcInspector.eventLoopNestLevel()); + // let lastNestRequestor = DebuggerServer.xpcInspector.lastNestRequestor; + // if (lastNestRequestor.connection != this.conn) { + // return { error: "wrongOrder", + // message: "trying to resume in the wrong order.", + // lastPausedUrl: lastNestRequestor.url }; + // } + } + + if (aRequest && aRequest.forceCompletion) { + // TODO: remove this when Debugger.Frame.prototype.pop is implemented in + // bug 736733. + if (typeof this.frame.pop != "function") { + return { error: "notImplemented", + message: "forced completion is not yet implemented." }; + } + + this.dbg.getNewestFrame().pop(aRequest.completionValue); + let packet = this._resumed(); + DebuggerServer.xpcInspector.exitNestedEventLoop(); + return { type: "resumeLimit", frameFinished: aRequest.forceCompletion }; + } + + if (aRequest && aRequest.resumeLimit) { + log("resumeLimit..."); + // Bind these methods because some of the hooks are called with 'this' + // set to the current frame. + let pauseAndRespond = (aFrame, onPacket=function (k) k) => { + this._pauseAndRespond(aFrame, { type: "resumeLimit" }, onPacket); + }; + let createValueGrip = this.createValueGrip.bind(this); + + let startFrame = this.youngestFrame; + let startLine; + if (this.youngestFrame.script) { + let offset = this.youngestFrame.offset; + startLine = this.youngestFrame.script.getOffsetLine(offset); + } + + // Define the JS hook functions for stepping. + + let onEnterFrame = aFrame => { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + return pauseAndRespond(aFrame); + }; + + let thread = this; + + let onPop = function TA_onPop(aCompletion) { + // onPop is called with 'this' set to the current frame. + if (thread.sources.isBlackBoxed(this.script.url)) { + return undefined; + } + + // Note that we're popping this frame; we need to watch for + // subsequent step events on its caller. + this.reportedPop = true; + + return pauseAndRespond(this, (aPacket) => { + aPacket.why.frameFinished = {}; + if (!aCompletion) { + aPacket.why.frameFinished.terminated = true; + } else if (aCompletion.hasOwnProperty("return")) { + aPacket.why.frameFinished.return = createValueGrip(aCompletion.return); + } else if (aCompletion.hasOwnProperty("yield")) { + aPacket.why.frameFinished.return = createValueGrip(aCompletion.yield); + } else { + aPacket.why.frameFinished.throw = createValueGrip(aCompletion.throw); + } + return aPacket; + }); + }; + + let onStep = function TA_onStep() { + // onStep is called with 'this' set to the current frame. + + if (thread.sources.isBlackBoxed(this.script.url)) { + return undefined; + } + + // If we've changed frame or line, then report that. + if (this !== startFrame || + (this.script && + this.script.getOffsetLine(this.offset) != startLine)) { + return pauseAndRespond(this); + } + + // Otherwise, let execution continue. + return undefined; + }; + + let steppingType = aRequest.resumeLimit.type; + if (["step", "next", "finish"].indexOf(steppingType) == -1) { + return { error: "badParameterType", + message: "Unknown resumeLimit type" }; + } + // Make sure there is still a frame on the stack if we are to continue + // stepping. + let stepFrame = this._getNextStepFrame(startFrame); + if (stepFrame) { + switch (steppingType) { + case "step": + log("--> step..."); + this.dbg.onEnterFrame = onEnterFrame; + // Fall through. + case "next": + log("--> next..."); + stepFrame.onStep = onStep; + stepFrame.onPop = onPop; + break; + case "finish": + log("--> finish..."); + stepFrame.onPop = onPop; + } + } + + } + + if (aRequest && aRequest.pauseOnExceptions) { + this.dbg.onExceptionUnwind = this.onExceptionUnwind.bind(this); + } + let packet = this._resumed(); + DebuggerServer.xpcInspector.exitNestedEventLoop(); + return packet; + }, + + /** + * Helper method that returns the next frame when stepping. + */ + _getNextStepFrame: function TA__getNextStepFrame(aFrame) { + let stepFrame = aFrame.reportedPop ? aFrame.older : aFrame; + if (!stepFrame || !stepFrame.script) { + stepFrame = null; + } + return stepFrame; + }, + + onClientEvaluate: function TA_onClientEvaluate(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Debuggee must be paused to evaluate code." }; + }; + + let frame = this._requestFrame(aRequest.frame); + if (!frame) { + return { error: "unknownFrame", + message: "Evaluation frame not found" }; + } + + if (!frame.environment) { + return { error: "notDebuggee", + message: "cannot access the environment of this frame." }; + }; + + // We'll clobber the youngest frame if the eval causes a pause, so + // save our frame now to be restored after eval returns. + // XXX: or we could just start using dbg.getNewestFrame() now that it + // works as expected. + let youngest = this.youngestFrame; + + // Put ourselves back in the running state and inform the client. + let resumedPacket = this._resumed(); + this.conn.send(resumedPacket); + + // Run the expression. + // XXX: test syntax errors + let completion = frame.eval(aRequest.expression); + + // Put ourselves back in the pause state. + let packet = this._paused(youngest); + packet.why = { type: "clientEvaluated", + frameFinished: this.createProtocolCompletionValue(completion) }; + + // Return back to our previous pause's event loop. + return packet; + }, + + onFrames: function TA_onFrames(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Stack frames are only available while the debuggee is paused."}; + } + + let start = aRequest.start ? aRequest.start : 0; + let count = aRequest.count; + + // Find the starting frame... + let frame = this.youngestFrame; + let i = 0; + while (frame && (i < start)) { + frame = frame.older; + i++; + } + + // Return request.count frames, or all remaining + // frames if count is not defined. + let frames = []; + let promises = []; + for (; frame && (!count || i < (start + count)); i++, frame=frame.older) { + let form = this._createFrameActor(frame).form(); + form.depth = i; + frames.push(form); + + let promise = this.sources.getOriginalLocation(form.where.url, + form.where.line) + .then(function (aOrigLocation) { + form.where = aOrigLocation; + }); + promises.push(promise); + } + + return all(promises).then(function () { + return { frames: frames }; + }); + }, + + onReleaseMany: function TA_onReleaseMany(aRequest) { + if (!aRequest.actors) { + return { error: "missingParameter", + message: "no actors were specified" }; + } + + let res; + for each (let actorID in aRequest.actors) { + let actor = this.threadLifetimePool.get(actorID); + if (!actor) { + if (!res) { + res = { error: "notReleasable", + message: "Only thread-lifetime actors can be released." }; + } + continue; + } + actor.onRelease(); + } + return res ? res : {}; + }, + + /** + * Handle a protocol request to set a breakpoint. + */ + onSetBreakpoint: function TA_onSetBreakpoint(aRequest) { + if (this.state !== "paused") { + return { error: "wrongState", + message: "Breakpoints can only be set while the debuggee is paused."}; + } + + // XXX: `originalColumn` is never used. See bug 827639. + let { url: originalSource, + line: originalLine, + column: originalColumn } = aRequest.location; + + let locationPromise = this.sources.getGeneratedLocation(originalSource, + originalLine) + return locationPromise.then((aLocation) => { + let line = aLocation.line; + if (this.dbg.findScripts({ url: aLocation.url }).length == 0 || + line < 0 || + line == null) { + return { error: "noScript" }; + } + + // Add the breakpoint to the store for later reuse, in case it belongs to a + // script that hasn't appeared yet. + if (!this._breakpointStore[aLocation.url]) { + this._breakpointStore[aLocation.url] = []; + } + let scriptBreakpoints = this._breakpointStore[aLocation.url]; + scriptBreakpoints[line] = { + url: aLocation.url, + line: line, + column: aLocation.column + }; + + let response = this._setBreakpoint(aLocation); + // If the original location of our generated location is different from + // the original location we attempted to set the breakpoint on, we will + // need to know so that we can set actualLocation on the response. + let originalLocation = this.sources.getOriginalLocation(aLocation.url, + aLocation.line); + + return all([response, originalLocation]) + .then(([aResponse, {url, line}]) => { + if (aResponse.actualLocation) { + let actualOrigLocation = this.sources.getOriginalLocation( + aResponse.actualLocation.url, aResponse.actualLocation.line); + return actualOrigLocation.then(function ({ url, line }) { + if (url !== originalSource || line !== originalLine) { + aResponse.actualLocation = { url: url, line: line }; + } + return aResponse; + }); + } + + if (url !== originalSource || line !== originalLine) { + aResponse.actualLocation = { url: url, line: line }; + } + + return aResponse; + }); + }); + }, + + /** + * Set a breakpoint using the jsdbg2 API. If the line on which the breakpoint + * is being set contains no code, then the breakpoint will slide down to the + * next line that has runnable code. In this case the server breakpoint cache + * will be updated, so callers that iterate over the breakpoint cache should + * take that into account. + * + * @param object aLocation + * The location of the breakpoint as specified in the protocol. + */ + _setBreakpoint: function TA__setBreakpoint(aLocation) { + let breakpoints = this._breakpointStore[aLocation.url]; + + // Get or create the breakpoint actor for the given location + let actor; + if (breakpoints[aLocation.line].actor) { + actor = breakpoints[aLocation.line].actor; + } else { + actor = breakpoints[aLocation.line].actor = new BreakpointActor(this, { + url: aLocation.url, + line: aLocation.line + }); + this._hooks.addToParentPool(actor); + } + + // Find all scripts matching the given location + let scripts = this.dbg.findScripts(aLocation); + if (scripts.length == 0) { + return { + error: "noScript", + actor: actor.actorID + }; + } + + /** + * For each script, if the given line has at least one entry point, set + * breakpoint on the bytecode offet for each of them. + */ + let found = false; + for (let script of scripts) { + let offsets = script.getLineOffsets(aLocation.line); + if (offsets.length > 0) { + for (let offset of offsets) { + script.setBreakpoint(offset, actor); + } + actor.addScript(script, this); + found = true; + } + } + if (found) { + return { + actor: actor.actorID + }; + } + + /** + * If we get here, no breakpoint was set. This is because the given line + * has no entry points, for example because it is empty. As a fallback + * strategy, we try to set the breakpoint on the smallest line greater + * than or equal to the given line that as at least one entry point. + */ + + // Find all innermost scripts matching the given location + let scripts = this.dbg.findScripts({ + url: aLocation.url, + line: aLocation.line, + innermost: true + }); + + /** + * For each innermost script, look for the smallest line greater than or + * equal to the given line that has one or more entry points. If found, set + * a breakpoint on the bytecode offset for each of its entry points. + */ + let actualLocation; + let found = false; + for (let script of scripts) { + let offsets = script.getAllOffsets(); + for (let line = aLocation.line; line < offsets.length; ++line) { + if (offsets[line]) { + for (let offset of offsets[line]) { + script.setBreakpoint(offset, actor); + } + actor.addScript(script, this); + if (!actualLocation) { + actualLocation = { + url: aLocation.url, + line: line, + column: 0 + }; + } + found = true; + break; + } + } + } + if (found) { + if (breakpoints[actualLocation.line] && + breakpoints[actualLocation.line].actor) { + /** + * We already have a breakpoint actor for the actual location, so + * actor we created earlier is now redundant. Delete it, update the + * breakpoint store, and return the actor for the actual location. + */ + actor.onDelete(); + delete breakpoints[aLocation.line]; + return { + actor: breakpoints[actualLocation.line].actor.actorID, + actualLocation: actualLocation + }; + } else { + /** + * We don't have a breakpoint actor for the actual location yet. + * Instead or creating a new actor, reuse the actor we created earlier, + * and update the breakpoint store. + */ + actor.location = actualLocation; + breakpoints[actualLocation.line] = breakpoints[aLocation.line]; + delete breakpoints[aLocation.line]; + // WARNING: This overwrites aLocation.line + breakpoints[actualLocation.line].line = actualLocation.line; + return { + actor: actor.actorID, + actualLocation: actualLocation + }; + } + } + + /** + * If we get here, no line matching the given line was found, so just + * epically. + */ + return { + error: "noCodeAtLineColumn", + actor: actor.actorID + }; + }, + + /** + * Get the script and source lists from the debugger. + * + * TODO bug 637572: we should be dealing with sources directly, not inferring + * them through scripts. + */ + _discoverSources: function TA__discoverSources() { + // Only get one script per url. + let scriptsByUrl = {}; + for (let s of this.dbg.findScripts()) { + scriptsByUrl[s.url] = s; + } + + return all([this.sources.sourcesForScript(scriptsByUrl[s]) + for (s of Object.keys(scriptsByUrl))]); + }, + + onSources: function TA_onSources(aRequest) { + return this._discoverSources().then(() => { + return { + sources: [s.form() for (s of this.sources.iter())] + }; + }); + }, + + /** + * Disassociate all breakpoint actors from their scripts and clear the + * breakpoint handlers. This method can be used when the thread actor intends + * to keep the breakpoint store, but needs to clear any actual breakpoints, + * e.g. due to a page navigation. This way the breakpoint actors' script + * caches won't hold on to the Debugger.Script objects leaking memory. + */ + disableAllBreakpoints: function () { + for (let url in this._breakpointStore) { + for (let line in this._breakpointStore[url]) { + let bp = this._breakpointStore[url][line]; + bp.actor.removeScripts(); + } + } + }, + + /** + * Handle a protocol request to pause the debuggee. + */ + onInterrupt: function TA_onInterrupt(aRequest) { + if (this.state == "exited") { + return { type: "exited" }; + } else if (this.state == "paused") { + // TODO: return the actual reason for the existing pause. + return { type: "paused", why: { type: "alreadyPaused" } }; + } else if (this.state != "running") { + return { error: "wrongState", + message: "Received interrupt request in " + this.state + + " state." }; + } + + try { + // Put ourselves in the paused state. + let packet = this._paused(); + if (!packet) { + return { error: "notInterrupted" }; + } + packet.why = { type: "interrupted" }; + + // Send the response to the interrupt request now (rather than + // returning it), because we're going to start a nested event loop + // here. + this.conn.send(packet); + + // Start a nested event loop. + this._nest(); + + // We already sent a response to this request, don't send one + // now. + return null; + } catch (e) { + reportError(e); + return { error: "notInterrupted", message: e.toString() }; + } + }, + + /** + * Return the Debug.Frame for a frame mentioned by the protocol. + */ + _requestFrame: function TA_requestFrame(aFrameID) { + if (!aFrameID) { + return this.youngestFrame; + } + + if (this._framePool.has(aFrameID)) { + return this._framePool.get(aFrameID).frame; + } + + return undefined; + }, + + _paused: function TA_paused(aFrame) { + // We don't handle nested pauses correctly. Don't try - if we're + // paused, just continue running whatever code triggered the pause. + // We don't want to actually have nested pauses (although we + // have nested event loops). If code runs in the debuggee during + // a pause, it should cause the actor to resume (dropping + // pause-lifetime actors etc) and then repause when complete. + + if (this.state === "paused") { + return undefined; + } + + // Clear stepping hooks. + this.dbg.onEnterFrame = undefined; + this.dbg.onExceptionUnwind = undefined; + if (aFrame) { + aFrame.onStep = undefined; + aFrame.onPop = undefined; + } + + this._state = "paused"; + + // Save the pause frame (if any) as the youngest frame for + // stack viewing. + this.youngestFrame = aFrame; + + // Create the actor pool that will hold the pause actor and its + // children. + dbg_assert(!this._pausePool); + this._pausePool = new ActorPool(this.conn); + this.conn.addActorPool(this._pausePool); + + // Give children of the pause pool a quick link back to the + // thread... + this._pausePool.threadActor = this; + + // Create the pause actor itself... + dbg_assert(!this._pauseActor); + this._pauseActor = new PauseActor(this._pausePool); + this._pausePool.addActor(this._pauseActor); + + // Update the list of frames. + let poppedFrames = this._updateFrames(); + + // Send off the paused packet and spin an event loop. + let packet = { from: this.actorID, + type: "paused", + actor: this._pauseActor.actorID }; + if (aFrame) { + packet.frame = this._createFrameActor(aFrame).form(); + } + + if (poppedFrames) { + packet.poppedFrames = poppedFrames; + } + + return packet; + }, + + _nest: function TA_nest() { + if (this._hooks.preNest) { + var nestData = this._hooks.preNest(); + } + + let requestor = Object.create(null); + requestor.url = this._hooks.url; + requestor.connection = this.conn; + DebuggerServer.xpcInspector.enterNestedEventLoop(requestor); + + dbg_assert(this.state === "running"); + + if (this._hooks.postNest) { + this._hooks.postNest(nestData) + } + + // "continue" resumption value. + return undefined; + }, + + _resumed: function TA_resumed() { + this._state = "running"; + + // Drop the actors in the pause actor pool. + this.conn.removeActorPool(this._pausePool); + + this._pausePool = null; + this._pauseActor = null; + this.youngestFrame = null; + + return { from: this.actorID, type: "resumed" }; + }, + + /** + * Expire frame actors for frames that have been popped. + * + * @returns A list of actor IDs whose frames have been popped. + */ + _updateFrames: function TA_updateFrames() { + let popped = []; + + // Create the actor pool that will hold the still-living frames. + let framePool = new ActorPool(this.conn); + let frameList = []; + + for each (let frameActor in this._frameActors) { + if (frameActor.frame.live) { + framePool.addActor(frameActor); + frameList.push(frameActor); + } else { + popped.push(frameActor.actorID); + } + } + + // Remove the old frame actor pool, this will expire + // any actors that weren't added to the new pool. + if (this._framePool) { + this.conn.removeActorPool(this._framePool); + } + + this._frameActors = frameList; + this._framePool = framePool; + this.conn.addActorPool(framePool); + + return popped; + }, + + _createFrameActor: function TA_createFrameActor(aFrame) { + if (aFrame.actor) { + return aFrame.actor; + } + + let actor = new FrameActor(aFrame, this); + this._frameActors.push(actor); + this._framePool.addActor(actor); + aFrame.actor = actor; + + return actor; + }, + + /** + * Create and return an environment actor that corresponds to the provided + * Debugger.Environment. + * @param Debugger.Environment aEnvironment + * The lexical environment we want to extract. + * @param object aPool + * The pool where the newly-created actor will be placed. + * @return The EnvironmentActor for aEnvironment or undefined for host + * functions or functions scoped to a non-debuggee global. + */ + createEnvironmentActor: + function TA_createEnvironmentActor(aEnvironment, aPool) { + if (!aEnvironment) { + return undefined; + } + + if (aEnvironment.actor) { + return aEnvironment.actor; + } + + let actor = new EnvironmentActor(aEnvironment, this); + this._environmentActors.push(actor); + aPool.addActor(actor); + aEnvironment.actor = actor; + + return actor; + }, + + /** + * Create a grip for the given debuggee value. If the value is an + * object, will create an actor with the given lifetime. + */ + createValueGrip: function TA_createValueGrip(aValue, aPool=false) { + if (!aPool) { + aPool = this._pausePool; + } + let type = typeof(aValue); + + if (type === "string" && this._stringIsLong(aValue)) { + return this.longStringGrip(aValue, aPool); + } + + if (type === "boolean" || type === "string" || type === "number") { + return aValue; + } + + if (aValue === null) { + return { type: "null" }; + } + + if (aValue === undefined) { + return { type: "undefined" } + } + + if (typeof(aValue) === "object") { + return this.objectGrip(aValue, aPool); + } + + dbg_assert(false, "Failed to provide a grip for: " + aValue); + return null; + }, + + /** + * Return a protocol completion value representing the given + * Debugger-provided completion value. + */ + createProtocolCompletionValue: + function TA_createProtocolCompletionValue(aCompletion) { + let protoValue = {}; + if ("return" in aCompletion) { + protoValue.return = this.createValueGrip(aCompletion.return); + } else if ("yield" in aCompletion) { + protoValue.return = this.createValueGrip(aCompletion.yield); + } else if ("throw" in aCompletion) { + protoValue.throw = this.createValueGrip(aCompletion.throw); + } else { + protoValue.terminated = true; + } + return protoValue; + }, + + /** + * Create a grip for the given debuggee object. + * + * @param aValue Debugger.Object + * The debuggee object value. + * @param aPool ActorPool + * The actor pool where the new object actor will be added. + */ + objectGrip: function TA_objectGrip(aValue, aPool) { + if (!aPool.objectActors) { + aPool.objectActors = new WeakMap(); + } + + if (aPool.objectActors.has(aValue)) { + return aPool.objectActors.get(aValue).grip(); + } else if (this.threadLifetimePool.objectActors.has(aValue)) { + return this.threadLifetimePool.objectActors.get(aValue).grip(); + } + + let actor = new PauseScopedObjectActor(aValue, this); + aPool.addActor(actor); + aPool.objectActors.set(aValue, actor); + return actor.grip(); + }, + + /** + * Create a grip for the given debuggee object with a pause lifetime. + * + * @param aValue Debugger.Object + * The debuggee object value. + */ + pauseObjectGrip: function TA_pauseObjectGrip(aValue) { + if (!this._pausePool) { + throw "Object grip requested while not paused."; + } + + return this.objectGrip(aValue, this._pausePool); + }, + + /** + * Extend the lifetime of the provided object actor to thread lifetime. + * + * @param aActor object + * The object actor. + */ + threadObjectGrip: function TA_threadObjectGrip(aActor) { + // We want to reuse the existing actor ID, so we just remove it from the + // current pool's weak map and then let pool.addActor do the rest. + aActor.registeredPool.objectActors.delete(aActor.obj); + this.threadLifetimePool.addActor(aActor); + this.threadLifetimePool.objectActors.set(aActor.obj, aActor); + }, + + /** + * Handle a protocol request to promote multiple pause-lifetime grips to + * thread-lifetime grips. + * + * @param aRequest object + * The protocol request object. + */ + onThreadGrips: function OA_onThreadGrips(aRequest) { + if (this.state != "paused") { + return { error: "wrongState" }; + } + + if (!aRequest.actors) { + return { error: "missingParameter", + message: "no actors were specified" }; + } + + for (let actorID of aRequest.actors) { + let actor = this._pausePool.get(actorID); + if (actor) { + this.threadObjectGrip(actor); + } + } + return {}; + }, + + /** + * Create a grip for the given string. + * + * @param aString String + * The string we are creating a grip for. + * @param aPool ActorPool + * The actor pool where the new actor will be added. + */ + longStringGrip: function TA_longStringGrip(aString, aPool) { + if (!aPool.longStringActors) { + aPool.longStringActors = {}; + } + + if (aPool.longStringActors.hasOwnProperty(aString)) { + return aPool.longStringActors[aString].grip(); + } + + let actor = new LongStringActor(aString, this); + aPool.addActor(actor); + aPool.longStringActors[aString] = actor; + return actor.grip(); + }, + + /** + * Create a long string grip that is scoped to a pause. + * + * @param aString String + * The string we are creating a grip for. + */ + pauseLongStringGrip: function TA_pauseLongStringGrip (aString) { + return this.longStringGrip(aString, this._pausePool); + }, + + /** + * Create a long string grip that is scoped to a thread. + * + * @param aString String + * The string we are creating a grip for. + */ + threadLongStringGrip: function TA_pauseLongStringGrip (aString) { + return this.longStringGrip(aString, this._threadLifetimePool); + }, + + /** + * Returns true if the string is long enough to use a LongStringActor instead + * of passing the value directly over the protocol. + * + * @param aString String + * The string we are checking the length of. + */ + _stringIsLong: function TA__stringIsLong(aString) { + return aString.length >= DebuggerServer.LONG_STRING_LENGTH; + }, + + // JS Debugger API hooks. + + /** + * A function that the engine calls when a call to a debug event hook, + * breakpoint handler, watchpoint handler, or similar function throws some + * exception. + * + * @param aException exception + * The exception that was thrown in the debugger code. + */ + uncaughtExceptionHook: function TA_uncaughtExceptionHook(aException) { + dumpn("Got an exception: " + aException.message + "\n" + aException.stack); + }, + + /** + * A function that the engine calls when a debugger statement has been + * executed in the specified frame. + * + * @param aFrame Debugger.Frame + * The stack frame that contained the debugger statement. + */ + onDebuggerStatement: function TA_onDebuggerStatement(aFrame) { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + return this._pauseAndRespond(aFrame, { type: "debuggerStatement" }); + }, + + /** + * A function that the engine calls when an exception has been thrown and has + * propagated to the specified frame. + * + * @param aFrame Debugger.Frame + * The youngest remaining stack frame. + * @param aValue object + * The exception that was thrown. + */ + onExceptionUnwind: function TA_onExceptionUnwind(aFrame, aValue) { + if (this.sources.isBlackBoxed(aFrame.script.url)) { + return undefined; + } + try { + let packet = this._paused(aFrame); + if (!packet) { + return undefined; + } + + packet.why = { type: "exception", + exception: this.createValueGrip(aValue) }; + this.conn.send(packet); + return this._nest(); + } catch(e) { + log("Got an exception during TA_onExceptionUnwind: " + e + + ": " + e.stack); + return undefined; + } + }, + + /** + * A function that the engine calls when a new script has been loaded into the + * scope of the specified debuggee global. + * + * @param aScript Debugger.Script + * The source script that has been loaded into a debuggee compartment. + * @param aGlobal Debugger.Object + * A Debugger.Object instance whose referent is the global object. + */ + onNewScript: function TA_onNewScript(aScript, aGlobal) { + this._addScript(aScript); + this.sources.sourcesForScript(aScript); + }, + + onNewSource: function TA_onNewSource(aSource) { + this.conn.send({ + from: this.actorID, + type: "newSource", + source: aSource.form() + }); + }, + + /** + * Check if scripts from the provided source URL are allowed to be stored in + * the cache. + * + * @param aSourceUrl String + * The url of the script's source that will be stored. + * @returns true, if the script can be added, false otherwise. + */ + _allowSource: function TA__allowSource(aSourceUrl) { + // Ignore anything we don't have a URL for (eval scripts, for example). + if (!aSourceUrl) + return false; + // Ignore XBL bindings for content debugging. + if (aSourceUrl.indexOf("chrome://") == 0) { + return false; + } + // Ignore about:* pages for content debugging. + if (aSourceUrl.indexOf("about:") == 0) { + return false; + } + return true; + }, + + /** + * Restore any pre-existing breakpoints to the scripts that we have access to. + */ + _restoreBreakpoints: function TA__restoreBreakpoints() { + for (let s of this.dbg.findScripts()) { + this._addScript(s); + } + }, + + /** + * Add the provided script to the server cache. + * + * @param aScript Debugger.Script + * The source script that will be stored. + * @returns true, if the script was added; false otherwise. + */ + _addScript: function TA__addScript(aScript) { + if (!this._allowSource(aScript.url)) { + return false; + } + + // Set any stored breakpoints. + let existing = this._breakpointStore[aScript.url]; + if (existing) { + let endLine = aScript.startLine + aScript.lineCount - 1; + // Iterate over the lines backwards, so that sliding breakpoints don't + // affect the loop. + for (let line = existing.length - 1; line >= aScript.startLine; line--) { + let bp = existing[line]; + // Only consider breakpoints that are not already associated with + // scripts, and limit search to the line numbers contained in the new + // script. + if (bp && !bp.actor.scripts.length && line <= endLine) { + this._setBreakpoint(bp); + } + } + } + return true; + }, + +}; + +ThreadActor.prototype.requestTypes = { + "attach": ThreadActor.prototype.onAttach, + "detach": ThreadActor.prototype.onDetach, + "reconfigure": ThreadActor.prototype.onReconfigure, + "resume": ThreadActor.prototype.onResume, + "clientEvaluate": ThreadActor.prototype.onClientEvaluate, + "frames": ThreadActor.prototype.onFrames, + "interrupt": ThreadActor.prototype.onInterrupt, + "releaseMany": ThreadActor.prototype.onReleaseMany, + "setBreakpoint": ThreadActor.prototype.onSetBreakpoint, + "sources": ThreadActor.prototype.onSources, + "threadGrips": ThreadActor.prototype.onThreadGrips +}; + + +/** + * Creates a PauseActor. + * + * PauseActors exist for the lifetime of a given debuggee pause. Used to + * scope pause-lifetime grips. + * + * @param ActorPool aPool + * The actor pool created for this pause. + */ +function PauseActor(aPool) +{ + this.pool = aPool; +} + +PauseActor.prototype = { + actorPrefix: "pause" +}; + + +/** + * A base actor for any actors that should only respond receive messages in the + * paused state. Subclasses may expose a `threadActor` which is used to help + * determine when we are in a paused state. Subclasses should set their own + * "constructor" property if they want better error messages. You should never + * instantiate a PauseScopedActor directly, only through subclasses. + */ +function PauseScopedActor() +{ +} + +/** + * A function decorator for creating methods to handle protocol messages that + * should only be received while in the paused state. + * + * @param aMethod Function + * The function we are decorating. + */ +PauseScopedActor.withPaused = function PSA_withPaused(aMethod) { + return function () { + if (this.isPaused()) { + return aMethod.apply(this, arguments); + } else { + return this._wrongState(); + } + }; +}; + +PauseScopedActor.prototype = { + + /** + * Returns true if we are in the paused state. + */ + isPaused: function PSA_isPaused() { + // When there is not a ThreadActor available (like in the webconsole) we + // have to be optimistic and assume that we are paused so that we can + // respond to requests. + return this.threadActor ? this.threadActor.state === "paused" : true; + }, + + /** + * Returns the wrongState response packet for this actor. + */ + _wrongState: function PSA_wrongState() { + return { + error: "wrongState", + message: this.constructor.name + + " actors can only be accessed while the thread is paused." + }; + } +}; + + +/** + * A SourceActor provides information about the source of a script. + * + * @param aUrl String + * The url of the source we are representing. + * @param aThreadActor ThreadActor + * The current thread actor. + * @param aSourceMap SourceMapConsumer + * Optional. The source map that introduced this source, if available. + */ +function SourceActor(aUrl, aThreadActor, aSourceMap=null) { + this._threadActor = aThreadActor; + this._url = aUrl; + this._sourceMap = aSourceMap; +} + +SourceActor.prototype = { + constructor: SourceActor, + actorPrefix: "source", + + get threadActor() this._threadActor, + get url() this._url, + + form: function SA_form() { + return { + actor: this.actorID, + url: this._url, + isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url) + // TODO bug 637572: introductionScript + }; + }, + + disconnect: function LSA_disconnect() { + if (this.registeredPool && this.registeredPool.sourceActors) { + delete this.registeredPool.sourceActors[this.actorID]; + } + }, + + /** + * Handler for the "source" packet. + */ + onSource: function SA_onSource(aRequest) { + let sourceContent = null; + if (this._sourceMap) { + sourceContent = this._sourceMap.sourceContentFor(this._url); + } + + if (sourceContent) { + return { + from: this.actorID, + source: this.threadActor.createValueGrip( + sourceContent, this.threadActor.threadLifetimePool) + }; + } + + // XXX bug 865252: Don't load from the cache if this is a source mapped + // source because we can't guarantee that the cache has the most up to date + // content for this source like we can if it isn't source mapped. + return fetch(this._url, { loadFromCache: !this._sourceMap }) + .then((aSource) => { + return this.threadActor.createValueGrip( + aSource, this.threadActor.threadLifetimePool); + }) + .then((aSourceGrip) => { + return { + from: this.actorID, + source: aSourceGrip + }; + }, (aError) => { + let msg = "Got an exception during SA_onSource: " + aError + + "\n" + aError.stack; + // Cu.reportError(msg); + dumpn(msg); + return { + "from": this.actorID, + "error": "loadSourceError", + "message": "Could not load the source for " + this._url + "." + }; + }); + }, + + /** + * Handler for the "blackbox" packet. + */ + onBlackBox: function SA_onBlackBox(aRequest) { + this.threadActor.sources.blackBox(this.url); + let packet = { + from: this.actorID + }; + if (this.threadActor.state == "paused" + && this.threadActor.youngestFrame + && this.threadActor.youngestFrame.script.url == this.url) { + packet.pausedInSource = true; + } + return packet; + }, + + /** + * Handler for the "unblackbox" packet. + */ + onUnblackBox: function SA_onUnblackBox(aRequest) { + this.threadActor.sources.unblackBox(this.url); + return { + from: this.actorID + }; + } +}; + +SourceActor.prototype.requestTypes = { + "source": SourceActor.prototype.onSource, + "blackbox": SourceActor.prototype.onBlackBox, + "unblackbox": SourceActor.prototype.onUnblackBox +}; + + +/** + * Creates an actor for the specified object. + * + * @param aObj Debugger.Object + * The debuggee object. + * @param aThreadActor ThreadActor + * The parent thread actor for this object. + */ +function ObjectActor(aObj, aThreadActor) +{ + this.obj = aObj; + this.threadActor = aThreadActor; +} + +ObjectActor.prototype = { + actorPrefix: "obj", + + /** + * Returns a grip for this actor for returning in a protocol message. + */ + grip: function OA_grip() { + let g = { + "type": "object", + "class": this.obj.class, + "actor": this.actorID, + "extensible": this.obj.isExtensible(), + "frozen": this.obj.isFrozen(), + "sealed": this.obj.isSealed() + }; + + // Add additional properties for functions. + if (this.obj.class === "Function") { + if (this.obj.name) { + g.name = this.obj.name; + } else if (this.obj.displayName) { + g.displayName = this.obj.displayName; + } + + // Check if the developer has added a de-facto standard displayName + // property for us to use. + let desc = this.obj.getOwnPropertyDescriptor("displayName"); + if (desc && desc.value && typeof desc.value == "string") { + g.userDisplayName = this.threadActor.createValueGrip(desc.value); + } + } + + return g; + }, + + /** + * Releases this actor from the pool. + */ + release: function OA_release() { + if (this.registeredPool.objectActors) { + this.registeredPool.objectActors.delete(this.obj); + } + this.registeredPool.removeActor(this); + }, + + /** + * Handle a protocol request to provide the names of the properties defined on + * the object and not its prototype. + * + * @param aRequest object + * The protocol request object. + */ + onOwnPropertyNames: function OA_onOwnPropertyNames(aRequest) { + return { from: this.actorID, + ownPropertyNames: this.obj.getOwnPropertyNames() }; + }, + + /** + * Handle a protocol request to provide the prototype and own properties of + * the object. + * + * @param aRequest object + * The protocol request object. + */ + onPrototypeAndProperties: function OA_onPrototypeAndProperties(aRequest) { + let ownProperties = Object.create(null); + let names; + try { + names = this.obj.getOwnPropertyNames(); + } catch (ex) { + // The above can throw if this.obj points to a dead object. + // TODO: we should use Cu.isDeadWrapper() - see bug 885800. + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(null), + ownProperties: ownProperties, + safeGetterValues: Object.create(null) }; + } + for (let name of names) { + ownProperties[name] = this._propertyDescriptor(name); + } + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(this.obj.proto), + ownProperties: ownProperties, + safeGetterValues: this._findSafeGetterValues(ownProperties) }; + }, + + /** + * Find the safe getter values for the current Debugger.Object, |this.obj|. + * + * @private + * @param object aOwnProperties + * The object that holds the list of known ownProperties for + * |this.obj|. + * @return object + * An object that maps property names to safe getter descriptors as + * defined by the remote debugging protocol. + */ + _findSafeGetterValues: function OA__findSafeGetterValues(aOwnProperties) + { + let safeGetterValues = Object.create(null); + let obj = this.obj; + let level = 0; + + while (obj) { + let getters = this._findSafeGetters(obj); + for (let name of getters) { + // Avoid overwriting properties from prototypes closer to this.obj. Also + // avoid providing safeGetterValues from prototypes if property |name| + // is already defined as an own property. + if (name in safeGetterValues || + (obj != this.obj && name in aOwnProperties)) { + continue; + } + + let desc = null, getter = null; + try { + desc = obj.getOwnPropertyDescriptor(name); + getter = desc.get; + } catch (ex) { + // The above can throw if the cache becomes stale. + } + if (!getter) { + obj._safeGetters = null; + continue; + } + + let result = getter.call(this.obj); + if (result && !("throw" in result)) { + let getterValue = undefined; + if ("return" in result) { + getterValue = result.return; + } else if ("yield" in result) { + getterValue = result.yield; + } + // WebIDL attributes specified with the LenientThis extended attribute + // return undefined and should be ignored. + if (getterValue !== undefined) { + safeGetterValues[name] = { + getterValue: this.threadActor.createValueGrip(getterValue), + getterPrototypeLevel: level, + enumerable: desc.enumerable, + writable: level == 0 ? desc.writable : true, + }; + } + } + } + + obj = obj.proto; + level++; + } + + return safeGetterValues; + }, + + /** + * Find the safe getters for a given Debugger.Object. Safe getters are native + * getters which are safe to execute. + * + * @private + * @param Debugger.Object aObject + * The Debugger.Object where you want to find safe getters. + * @return Set + * A Set of names of safe getters. This result is cached for each + * Debugger.Object. + */ + _findSafeGetters: function OA__findSafeGetters(aObject) + { + if (aObject._safeGetters) { + return aObject._safeGetters; + } + + let getters = new Set(); + for (let name of aObject.getOwnPropertyNames()) { + let desc = null; + try { + desc = aObject.getOwnPropertyDescriptor(name); + } catch (e) { + // Calling getOwnPropertyDescriptor on wrapped native prototypes is not + // allowed (bug 560072). + } + if (!desc || desc.value !== undefined || !("get" in desc)) { + continue; + } + + let fn = desc.get; + if (fn && fn.callable && fn.class == "Function" && + fn.script === undefined) { + getters.add(name); + } + } + + aObject._safeGetters = getters; + return getters; + }, + + /** + * Handle a protocol request to provide the prototype of the object. + * + * @param aRequest object + * The protocol request object. + */ + onPrototype: function OA_onPrototype(aRequest) { + return { from: this.actorID, + prototype: this.threadActor.createValueGrip(this.obj.proto) }; + }, + + /** + * Handle a protocol request to provide the property descriptor of the + * object's specified property. + * + * @param aRequest object + * The protocol request object. + */ + onProperty: function OA_onProperty(aRequest) { + if (!aRequest.name) { + return { error: "missingParameter", + message: "no property name was specified" }; + } + + return { from: this.actorID, + descriptor: this._propertyDescriptor(aRequest.name) }; + }, + + /** + * A helper method that creates a property descriptor for the provided object, + * properly formatted for sending in a protocol response. + * + * @param string aName + * The property that the descriptor is generated for. + */ + _propertyDescriptor: function OA_propertyDescriptor(aName) { + let desc; + try { + desc = this.obj.getOwnPropertyDescriptor(aName); + } catch (e) { + // Calling getOwnPropertyDescriptor on wrapped native prototypes is not + // allowed (bug 560072). Inform the user with a bogus, but hopefully + // explanatory, descriptor. + return { + configurable: false, + writable: false, + enumerable: false, + value: e.name + }; + } + + let retval = { + configurable: desc.configurable, + enumerable: desc.enumerable + }; + + if ("value" in desc) { + retval.writable = desc.writable; + retval.value = this.threadActor.createValueGrip(desc.value); + } else { + if ("get" in desc) { + retval.get = this.threadActor.createValueGrip(desc.get); + } + if ("set" in desc) { + retval.set = this.threadActor.createValueGrip(desc.set); + } + } + return retval; + }, + + /** + * Handle a protocol request to provide the source code of a function. + * + * @param aRequest object + * The protocol request object. + */ + onDecompile: function OA_onDecompile(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "decompile request is only valid for object grips " + + "with a 'Function' class." }; + } + + return { from: this.actorID, + decompiledCode: this.obj.decompile(!!aRequest.pretty) }; + }, + + /** + * Handle a protocol request to provide the parameters of a function. + * + * @param aRequest object + * The protocol request object. + */ + onParameterNames: function OA_onParameterNames(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "'parameterNames' request is only valid for object " + + "grips with a 'Function' class." }; + } + + return { parameterNames: this.obj.parameterNames }; + }, + + /** + * Handle a protocol request to release a thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onRelease: function OA_onRelease(aRequest) { + this.release(); + return {}; + }, +}; + +ObjectActor.prototype.requestTypes = { + "parameterNames": ObjectActor.prototype.onParameterNames, + "prototypeAndProperties": ObjectActor.prototype.onPrototypeAndProperties, + "prototype": ObjectActor.prototype.onPrototype, + "property": ObjectActor.prototype.onProperty, + "ownPropertyNames": ObjectActor.prototype.onOwnPropertyNames, + "decompile": ObjectActor.prototype.onDecompile, + "release": ObjectActor.prototype.onRelease, +}; + + +/** + * Creates a pause-scoped actor for the specified object. + * @see ObjectActor + */ +function PauseScopedObjectActor() +{ + ObjectActor.apply(this, arguments); +} + +PauseScopedObjectActor.prototype = Object.create(PauseScopedActor.prototype); + +update(PauseScopedObjectActor.prototype, ObjectActor.prototype); + +update(PauseScopedObjectActor.prototype, { + constructor: PauseScopedObjectActor, + + onOwnPropertyNames: + PauseScopedActor.withPaused(ObjectActor.prototype.onOwnPropertyNames), + + onPrototypeAndProperties: + PauseScopedActor.withPaused(ObjectActor.prototype.onPrototypeAndProperties), + + onPrototype: PauseScopedActor.withPaused(ObjectActor.prototype.onPrototype), + onProperty: PauseScopedActor.withPaused(ObjectActor.prototype.onProperty), + onDecompile: PauseScopedActor.withPaused(ObjectActor.prototype.onDecompile), + + onParameterNames: + PauseScopedActor.withPaused(ObjectActor.prototype.onParameterNames), + + /** + * Handle a protocol request to provide the lexical scope of a function. + * + * @param aRequest object + * The protocol request object. + */ + onScope: PauseScopedActor.withPaused(function OA_onScope(aRequest) { + if (this.obj.class !== "Function") { + return { error: "objectNotFunction", + message: "scope request is only valid for object grips with a" + + " 'Function' class." }; + } + + let envActor = this.threadActor.createEnvironmentActor(this.obj.environment, + this.registeredPool); + if (!envActor) { + return { error: "notDebuggee", + message: "cannot access the environment of this function." }; + } + + return { from: this.actorID, scope: envActor.form() }; + }), + + /** + * Handle a protocol request to promote a pause-lifetime grip to a + * thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onThreadGrip: PauseScopedActor.withPaused(function OA_onThreadGrip(aRequest) { + this.threadActor.threadObjectGrip(this); + return {}; + }), + + /** + * Handle a protocol request to release a thread-lifetime grip. + * + * @param aRequest object + * The protocol request object. + */ + onRelease: PauseScopedActor.withPaused(function OA_onRelease(aRequest) { + if (this.registeredPool !== this.threadActor.threadLifetimePool) { + return { error: "notReleasable", + message: "Only thread-lifetime actors can be released." }; + } + + this.release(); + return {}; + }), +}); + +update(PauseScopedObjectActor.prototype.requestTypes, { + "scope": PauseScopedObjectActor.prototype.onScope, + "threadGrip": PauseScopedObjectActor.prototype.onThreadGrip, +}); + + +/** + * Creates an actor for the specied "very long" string. "Very long" is specified + * at the server's discretion. + * + * @param aString String + * The string. + */ +function LongStringActor(aString) +{ + this.string = aString; + this.stringLength = aString.length; +} + +LongStringActor.prototype = { + + actorPrefix: "longString", + + disconnect: function LSA_disconnect() { + // Because longStringActors is not a weak map, we won't automatically leave + // it so we need to manually leave on disconnect so that we don't leak + // memory. + if (this.registeredPool && this.registeredPool.longStringActors) { + delete this.registeredPool.longStringActors[this.actorID]; + } + }, + + /** + * Returns a grip for this actor for returning in a protocol message. + */ + grip: function LSA_grip() { + return { + "type": "longString", + "initial": this.string.substring( + 0, DebuggerServer.LONG_STRING_INITIAL_LENGTH), + "length": this.stringLength, + "actor": this.actorID + }; + }, + + /** + * Handle a request to extract part of this actor's string. + * + * @param aRequest object + * The protocol request object. + */ + onSubstring: function LSA_onSubString(aRequest) { + return { + "from": this.actorID, + "substring": this.string.substring(aRequest.start, aRequest.end) + }; + }, + + /** + * Handle a request to release this LongStringActor instance. + */ + onRelease: function LSA_onRelease() { + // TODO: also check if registeredPool === threadActor.threadLifetimePool + // when the web console moves aray from manually releasing pause-scoped + // actors. + if (this.registeredPool.longStringActors) { + delete this.registeredPool.longStringActors[this.actorID]; + } + this.registeredPool.removeActor(this); + return {}; + }, +}; + +LongStringActor.prototype.requestTypes = { + "substring": LongStringActor.prototype.onSubstring, + "release": LongStringActor.prototype.onRelease +}; + + +/** + * Creates an actor for the specified stack frame. + * + * @param aFrame Debugger.Frame + * The debuggee frame. + * @param aThreadActor ThreadActor + * The parent thread actor for this frame. + */ +function FrameActor(aFrame, aThreadActor) +{ + this.frame = aFrame; + this.threadActor = aThreadActor; +} + +FrameActor.prototype = { + actorPrefix: "frame", + + /** + * A pool that contains frame-lifetime objects, like the environment. + */ + _frameLifetimePool: null, + get frameLifetimePool() { + if (!this._frameLifetimePool) { + this._frameLifetimePool = new ActorPool(this.conn); + this.conn.addActorPool(this._frameLifetimePool); + } + return this._frameLifetimePool; + }, + + /** + * Finalization handler that is called when the actor is being evicted from + * the pool. + */ + disconnect: function FA_disconnect() { + this.conn.removeActorPool(this._frameLifetimePool); + this._frameLifetimePool = null; + }, + + /** + * Returns a frame form for use in a protocol message. + */ + form: function FA_form() { + let form = { actor: this.actorID, + type: this.frame.type }; + if (this.frame.type === "call") { + form.callee = this.threadActor.createValueGrip(this.frame.callee); + } + + if (this.frame.environment) { + let envActor = this.threadActor + .createEnvironmentActor(this.frame.environment, + this.frameLifetimePool); + form.environment = envActor.form(); + } + form.this = this.threadActor.createValueGrip(this.frame.this); + form.arguments = this._args(); + if (this.frame.script) { + form.where = { url: this.frame.script.url, + line: this.frame.script.getOffsetLine(this.frame.offset) }; + form.isBlackBoxed = this.threadActor.sources.isBlackBoxed(this.frame.script.url) + } + + if (!this.frame.older) { + form.oldest = true; + } + + return form; + }, + + _args: function FA__args() { + if (!this.frame.arguments) { + return []; + } + + return [this.threadActor.createValueGrip(arg) + for each (arg in this.frame.arguments)]; + }, + + /** + * Handle a protocol request to pop this frame from the stack. + * + * @param aRequest object + * The protocol request object. + */ + onPop: function FA_onPop(aRequest) { + // TODO: remove this when Debugger.Frame.prototype.pop is implemented + if (typeof this.frame.pop != "function") { + return { error: "notImplemented", + message: "Popping frames is not yet implemented." }; + } + + while (this.frame != this.threadActor.dbg.getNewestFrame()) { + this.threadActor.dbg.getNewestFrame().pop(); + } + this.frame.pop(aRequest.completionValue); + + // TODO: return the watches property when frame pop watch actors are + // implemented. + return { from: this.actorID }; + } +}; + +FrameActor.prototype.requestTypes = { + "pop": FrameActor.prototype.onPop, +}; + + +/** + * Creates a BreakpointActor. BreakpointActors exist for the lifetime of their + * containing thread and are responsible for deleting breakpoints, handling + * breakpoint hits and associating breakpoints with scripts. + * + * @param ThreadActor aThreadActor + * The parent thread actor that contains this breakpoint. + * @param object aLocation + * The location of the breakpoint as specified in the protocol. + */ +function BreakpointActor(aThreadActor, aLocation) +{ + this.scripts = []; + this.threadActor = aThreadActor; + this.location = aLocation; +} + +BreakpointActor.prototype = { + actorPrefix: "breakpoint", + + /** + * Called when this same breakpoint is added to another Debugger.Script + * instance, in the case of a page reload. + * + * @param aScript Debugger.Script + * The new source script on which the breakpoint has been set. + * @param ThreadActor aThreadActor + * The parent thread actor that contains this breakpoint. + */ + addScript: function BA_addScript(aScript, aThreadActor) { + this.threadActor = aThreadActor; + this.scripts.push(aScript); + }, + + /** + * Remove the breakpoints from associated scripts and clear the script cache. + */ + removeScripts: function () { + for (let script of this.scripts) { + script.clearBreakpoint(this); + } + this.scripts = []; + }, + + /** + * A function that the engine calls when a breakpoint has been hit. + * + * @param aFrame Debugger.Frame + * The stack frame that contained the breakpoint. + */ + hit: function BA_hit(aFrame) { + if (this.threadActor.sources.isBlackBoxed(this.location.url)) { + return undefined; + } + + // TODO: add the rest of the breakpoints on that line (bug 676602). + let reason = { type: "breakpoint", actors: [ this.actorID ] }; + return this.threadActor._pauseAndRespond(aFrame, reason, (aPacket) => { + log("pause callback ..."); + + let { url, line } = aPacket.frame.where; + return this.threadActor.sources.getOriginalLocation(url, line) + .then(function (aOrigPosition) { + aPacket.frame.where = aOrigPosition; + return aPacket; + }); + }); + }, + + /** + * Handle a protocol request to remove this breakpoint. + * + * @param aRequest object + * The protocol request object. + */ + onDelete: function BA_onDelete(aRequest) { + // Remove from the breakpoint store. + let scriptBreakpoints = this.threadActor._breakpointStore[this.location.url]; + delete scriptBreakpoints[this.location.line]; + this.threadActor._hooks.removeFromParentPool(this); + // Remove the actual breakpoint from the associated scripts. + this.removeScripts(); + + return { from: this.actorID }; + } +}; + +BreakpointActor.prototype.requestTypes = { + "delete": BreakpointActor.prototype.onDelete +}; + + +/** + * Creates an EnvironmentActor. EnvironmentActors are responsible for listing + * the bindings introduced by a lexical environment and assigning new values to + * those identifier bindings. + * + * @param Debugger.Environment aEnvironment + * The lexical environment that will be used to create the actor. + * @param ThreadActor aThreadActor + * The parent thread actor that contains this environment. + */ +function EnvironmentActor(aEnvironment, aThreadActor) +{ + this.obj = aEnvironment; + this.threadActor = aThreadActor; +} + +EnvironmentActor.prototype = { + actorPrefix: "environment", + + /** + * Return an environment form for use in a protocol message. + */ + form: function EA_form() { + let form = { actor: this.actorID }; + + // What is this environment's type? + if (this.obj.type == "declarative") { + form.type = this.obj.callee ? "function" : "block"; + } else { + form.type = this.obj.type; + } + + // Does this environment have a parent? + if (this.obj.parent) { + form.parent = (this.threadActor + .createEnvironmentActor(this.obj.parent, + this.registeredPool) + .form()); + } + + // Does this environment reflect the properties of an object as variables? + if (this.obj.type == "object" || this.obj.type == "with") { + form.object = this.threadActor.createValueGrip(this.obj.object); + } + + // Is this the environment created for a function call? + if (this.obj.callee) { + form.function = this.threadActor.createValueGrip(this.obj.callee); + } + + // Shall we list this environment's bindings? + if (this.obj.type == "declarative") { + form.bindings = this._bindings(); + } + + return form; + }, + + /** + * Return the identifier bindings object as required by the remote protocol + * specification. + */ + _bindings: function EA_bindings() { + let bindings = { arguments: [], variables: {} }; + + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands (bug 725815). + if (typeof this.obj.getVariable != "function") { + //if (typeof this.obj.getVariableDescriptor != "function") { + return bindings; + } + + let parameterNames; + if (this.obj.callee) { + parameterNames = this.obj.callee.parameterNames; + } + for each (let name in parameterNames) { + let arg = {}; + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands (bug 725815). + let desc = { + value: this.obj.getVariable(name), + configurable: false, + writable: true, + enumerable: true + }; + + // let desc = this.obj.getVariableDescriptor(name); + let descForm = { + enumerable: true, + configurable: desc.configurable + }; + if ("value" in desc) { + descForm.value = this.threadActor.createValueGrip(desc.value); + descForm.writable = desc.writable; + } else { + descForm.get = this.threadActor.createValueGrip(desc.get); + descForm.set = this.threadActor.createValueGrip(desc.set); + } + arg[name] = descForm; + bindings.arguments.push(arg); + } + + for each (let name in this.obj.names()) { + if (bindings.arguments.some(function exists(element) { + return !!element[name]; + })) { + continue; + } + + // TODO: this part should be removed in favor of the commented-out part + // below when getVariableDescriptor lands. + let desc = { + configurable: false, + writable: true, + enumerable: true + }; + try { + desc.value = this.obj.getVariable(name); + } catch (e) { + // Avoid "Debugger scope is not live" errors for |arguments|, introduced + // in bug 746601. + if (name != "arguments") { + throw e; + } + } + //let desc = this.obj.getVariableDescriptor(name); + let descForm = { + enumerable: true, + configurable: desc.configurable + }; + if ("value" in desc) { + descForm.value = this.threadActor.createValueGrip(desc.value); + descForm.writable = desc.writable; + } else { + descForm.get = this.threadActor.createValueGrip(desc.get); + descForm.set = this.threadActor.createValueGrip(desc.set); + } + bindings.variables[name] = descForm; + } + + return bindings; + }, + + /** + * Handle a protocol request to change the value of a variable bound in this + * lexical environment. + * + * @param aRequest object + * The protocol request object. + */ + onAssign: function EA_onAssign(aRequest) { + // TODO: enable the commented-out part when getVariableDescriptor lands + // (bug 725815). + /*let desc = this.obj.getVariableDescriptor(aRequest.name); + + if (!desc.writable) { + return { error: "immutableBinding", + message: "Changing the value of an immutable binding is not " + + "allowed" }; + }*/ + + try { + this.obj.setVariable(aRequest.name, aRequest.value); + } catch (e) { + if (e instanceof Debugger.DebuggeeWouldRun) { + return { error: "threadWouldRun", + cause: e.cause ? e.cause : "setter", + message: "Assigning a value would cause the debuggee to run" }; + } + // This should never happen, so let it complain loudly if it does. + throw e; + } + return { from: this.actorID }; + }, + + /** + * Handle a protocol request to fully enumerate the bindings introduced by the + * lexical environment. + * + * @param aRequest object + * The protocol request object. + */ + onBindings: function EA_onBindings(aRequest) { + return { from: this.actorID, + bindings: this._bindings() }; + } +}; + +EnvironmentActor.prototype.requestTypes = { + "assign": EnvironmentActor.prototype.onAssign, + "bindings": EnvironmentActor.prototype.onBindings +}; + +/** + * Override the toString method in order to get more meaningful script output + * for debugging the debugger. + */ +Debugger.Script.prototype.toString = function() { + let output = ""; + if (this.url) { + output += this.url; + } + if (typeof this.startLine != "undefined") { + output += ":" + this.startLine; + if (this.lineCount && this.lineCount > 1) { + output += "-" + (this.startLine + this.lineCount - 1); + } + } + if (this.strictMode) { + output += ":strict"; + } + return output; +}; + +/** + * Helper property for quickly getting to the line number a stack frame is + * currently paused at. + */ +Object.defineProperty(Debugger.Frame.prototype, "line", { + configurable: true, + get: function() { + if (this.script) { + return this.script.getOffsetLine(this.offset); + } else { + return null; + } + } +}); + + +/** + * Creates an actor for handling chrome debugging. ChromeDebuggerActor is a + * thin wrapper over ThreadActor, slightly changing some of its behavior. + * + * @param aConnection object + * The DebuggerServerConnection with which this ChromeDebuggerActor + * is associated. (Currently unused, but required to make this + * constructor usable with addGlobalActor.) + * + * @param aHooks object + * An object with preNest and postNest methods for calling when entering + * and exiting a nested event loop and also addToParentPool and + * removeFromParentPool methods for handling the lifetime of actors that + * will outlive the thread, like breakpoints. + */ +function ChromeDebuggerActor(aConnection, aHooks) +{ + ThreadActor.call(this, aHooks); +} + +ChromeDebuggerActor.prototype = Object.create(ThreadActor.prototype); + +update(ChromeDebuggerActor.prototype, { + constructor: ChromeDebuggerActor, + + // A constant prefix that will be used to form the actor ID by the server. + actorPrefix: "chromeDebugger", + + /** + * Override the eligibility check for scripts and sources to make sure every + * script and source with a URL is stored when debugging chrome. + */ + _allowSource: function(aSourceURL) !!aSourceURL, + + /** + * An object that will be used by ThreadActors to tailor their behavior + * depending on the debugging context being required (chrome or content). + * The methods that this object provides must be bound to the ThreadActor + * before use. + */ + globalManager: { + findGlobals: function CDA_findGlobals() { + // Add every global known to the debugger as debuggee. + this.dbg.addAllGlobalsAsDebuggees(); + }, + + /** + * A function that the engine calls when a new global object has been + * created. + * + * @param aGlobal Debugger.Object + * The new global object that was created. + */ + onNewGlobal: function CDA_onNewGlobal(aGlobal) { + this.addDebuggee(aGlobal); + // Notify the client. + this.conn.send({ + from: this.actorID, + type: "newGlobal", + // TODO: after bug 801084 lands see if we need to JSONify this. + hostAnnotations: aGlobal.hostAnnotations + }); + } + } +}); + + +/** + * Manages the sources for a thread. Handles source maps, locations in the + * sources, etc for ThreadActors. + */ +function ThreadSources(aThreadActor, aUseSourceMaps, aAllowPredicate, + aOnNewSource) { + this._thread = aThreadActor; + this._useSourceMaps = aUseSourceMaps; + this._allow = aAllowPredicate; + this._onNewSource = aOnNewSource; + + // source map URL --> promise of SourceMapConsumer + this._sourceMaps = Object.create(null); + // generated source url --> promise of SourceMapConsumer + this._sourceMapsByGeneratedSource = Object.create(null); + // original source url --> promise of SourceMapConsumer + this._sourceMapsByOriginalSource = Object.create(null); + // source url --> SourceActor + this._sourceActors = Object.create(null); + // original url --> generated url + this._generatedUrlsByOriginalUrl = Object.create(null); +} + +/** + * Must be a class property because it needs to persist across reloads, same as + * the breakpoint store. + */ +ThreadSources._blackBoxedSources = new Set(); + +ThreadSources.prototype = { + /** + * Return the source actor representing |aURL|, creating one if none + * exists already. Returns null if |aURL| is not allowed by the 'allow' + * predicate. + * + * Right now this takes a URL, but in the future it should + * take a Debugger.Source. See bug 637572. + * + * @param String aURL + * The source URL. + * @param optional SourceMapConsumer aSourceMap + * The source map that introduced this source, if any. + * @returns a SourceActor representing the source at aURL or null. + */ + source: function TS_source(aURL, aSourceMap=null) { + if (!this._allow(aURL)) { + return null; + } + + if (aURL in this._sourceActors) { + return this._sourceActors[aURL]; + } + + let actor = new SourceActor(aURL, this._thread, aSourceMap); + this._thread.threadLifetimePool.addActor(actor); + this._sourceActors[aURL] = actor; + try { + this._onNewSource(actor); + } catch (e) { + reportError(e); + } + return actor; + }, + + /** + * Return a promise of an array of source actors representing all the + * sources of |aScript|. + * + * If source map handling is enabled and |aScript| has a source map, then + * use it to find all of |aScript|'s *original* sources; return a promise + * of an array of source actors for those. + */ + sourcesForScript: function TS_sourcesForScript(aScript) { + if (!this._useSourceMaps || !aScript.sourceMapURL) { + return resolve([this.source(aScript.url)].filter(isNotNull)); + } + + return this.sourceMap(aScript) + .then((aSourceMap) => { + return [ + this.source(s, aSourceMap) for (s of aSourceMap.sources) + ]; + }) + .then(null, (e) => { + reportError(e); + delete this._sourceMaps[this._normalize(aScript.sourceMapURL, aScript.url)]; + delete this._sourceMapsByGeneratedSource[aScript.url]; + return [this.source(aScript.url)]; + }) + .then(function (aSources) { + return aSources.filter(isNotNull); + }); + }, + + /** + * Return a promise of a SourceMapConsumer for the source map for + * |aScript|; if we already have such a promise extant, return that. + * |aScript| must have a non-null sourceMapURL. + */ + sourceMap: function TS_sourceMap(aScript) { + if (aScript.url in this._sourceMapsByGeneratedSource) { + return this._sourceMapsByGeneratedSource[aScript.url]; + } + dbg_assert(aScript.sourceMapURL); + let sourceMapURL = this._normalize(aScript.sourceMapURL, aScript.url); + let map = this._fetchSourceMap(sourceMapURL) + .then((aSourceMap) => { + for (let s of aSourceMap.sources) { + this._generatedUrlsByOriginalUrl[s] = aScript.url; + this._sourceMapsByOriginalSource[s] = resolve(aSourceMap); + } + return aSourceMap; + }); + this._sourceMapsByGeneratedSource[aScript.url] = map; + return map; + }, + + /** + * Return a promise of a SourceMapConsumer for the source map located at + * |aAbsSourceMapURL|, which must be absolute. If there is already such a + * promise extant, return it. + */ + _fetchSourceMap: function TS__fetchSourceMap(aAbsSourceMapURL) { + if (aAbsSourceMapURL in this._sourceMaps) { + return this._sourceMaps[aAbsSourceMapURL]; + } else { + let promise = fetch(aAbsSourceMapURL).then((rawSourceMap) => { + let map = new SourceMapConsumer(rawSourceMap); + let base = aAbsSourceMapURL.replace(/\/[^\/]+$/, '/'); + if (base.indexOf("data:") !== 0) { + map.sourceRoot = map.sourceRoot + ? this._normalize(map.sourceRoot, base) + : base; + } + return map; + }); + this._sourceMaps[aAbsSourceMapURL] = promise; + return promise; + } + }, + + /** + * Returns a promise of the location in the original source if the source is + * source mapped, otherwise a promise of the same location. + * + * TODO bug 637572: take/return a column + */ + getOriginalLocation: function TS_getOriginalLocation(aSourceUrl, aLine) { + if (aSourceUrl in this._sourceMapsByGeneratedSource) { + return this._sourceMapsByGeneratedSource[aSourceUrl] + .then(function (aSourceMap) { + let { source, line } = aSourceMap.originalPositionFor({ + source: aSourceUrl, + line: aLine, + column: Infinity + }); + return { + url: source, + line: line + }; + }); + } + + // No source map + return resolve({ + url: aSourceUrl, + line: aLine + }); + }, + + /** + * Returns a promise of the location in the generated source corresponding to + * the original source and line given. + * + * When we pass a script S representing generated code to |sourceMap|, + * above, that returns a promise P. The process of resolving P populates + * the tables this function uses; thus, it won't know that S's original + * source URLs map to S until P is resolved. + * + * TODO bug 637572: take/return a column + */ + getGeneratedLocation: function TS_getGeneratedLocation(aSourceUrl, aLine) { + if (aSourceUrl in this._sourceMapsByOriginalSource) { + return this._sourceMapsByOriginalSource[aSourceUrl] + .then((aSourceMap) => { + let { line } = aSourceMap.generatedPositionFor({ + source: aSourceUrl, + line: aLine, + column: Infinity + }); + return { + url: this._generatedUrlsByOriginalUrl[aSourceUrl], + line: line + }; + }); + } + + // No source map + return resolve({ + url: aSourceUrl, + line: aLine + }); + }, + + /** + * Returns true if URL for the given source is black boxed. + * + * @param aURL String + * The URL of the source which we are checking whether it is black + * boxed or not. + */ + isBlackBoxed: function TS_isBlackBoxed(aURL) { + return ThreadSources._blackBoxedSources.has(aURL); + }, + + /** + * Add the given source URL to the set of sources that are black boxed. If the + * thread is currently paused and we are black boxing the yougest frame's + * source, this will force a step. + * + * @param aURL String + * The URL of the source which we are black boxing. + */ + blackBox: function TS_blackBox(aURL) { + ThreadSources._blackBoxedSources.add(aURL); + }, + + /** + * Remove the given source URL to the set of sources that are black boxed. + * + * @param aURL String + * The URL of the source which we are no longer black boxing. + */ + unblackBox: function TS_unblackBox(aURL) { + ThreadSources._blackBoxedSources.delete(aURL); + }, + + /** + * Normalize multiple relative paths towards the base paths on the right. + */ + _normalize: function TS__normalize(...aURLs) { + dbg_assert(aURLs.length > 1); + let base = Services.io.newURI(aURLs.pop(), null, null); + let url; + while ((url = aURLs.pop())) { + base = Services.io.newURI(url, null, base); + } + return base.spec; + }, + + iter: function TS_iter() { + for (let url in this._sourceActors) { + yield this._sourceActors[url]; + } + } +}; + +// Utility functions. + +/** + * Utility function for updating an object with the properties of another + * object. + * + * @param aTarget Object + * The object being updated. + * @param aNewAttrs Object + * The new attributes being set on the target. + */ +function update(aTarget, aNewAttrs) { + for (let key in aNewAttrs) { + let desc = Object.getOwnPropertyDescriptor(aNewAttrs, key); + + if (desc) { + Object.defineProperty(aTarget, key, desc); + } + } +} + +/** + * Returns true if its argument is not null. + */ +function isNotNull(aThing) { + return aThing !== null; +} + +/** + * Performs a request to load the desired URL and returns a promise. + * + * @param aURL String + * The URL we will request. + * @returns Promise + * A promise of the document at that URL, as a string. + * + * XXX: It may be better to use nsITraceableChannel to get to the sources + * without relying on caching when we can (not for eval, etc.): + * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ + */ +function fetch(aURL, aOptions={ loadFromCache: true }) { + let deferred = defer(); + let scheme; + let url = aURL.split(" -> ").pop(); + let charset; + let filePath = url; + // try { + // scheme = Services.io.extractScheme(url); + // } catch (e) { + // In the xpcshell tests, the script url is the absolute path of the test + // file, which will make a malformed URI error be thrown. Add the file + // scheme prefix ourselves. + url = "file://" + url; + // scheme = Services.io.extractScheme(url); + // } + scheme = "file"; + + switch (scheme) { + case "file": + case "chrome": + case "resource": + try { + // NetUtil.asyncFetch(url, function onFetch(aStream, aStatus) { + // if (!Components.isSuccessCode(aStatus)) { + // deferred.reject("Request failed: " + url); + // return; + // } + let cc = globalDebuggee.cc; + let fileUtils = cc.FileUtils.getInstance(); + let source = fileUtils.getStringFromFile(filePath);//NetUtil.readInputStreamToString(aStream, aStream.available()); + if (!source) + { + deferred.reject("Request failed: " + url); + } + else + { + deferred.resolve(source); + } + // aStream.close(); + // }); + } catch (ex) { + deferred.reject("Request failed: " + url); + } + break; + + default: + let channel; + try { + channel = Services.io.newChannel(url, null, null); + } catch (e if e.name == "NS_ERROR_UNKNOWN_PROTOCOL") { + // On Windows xpcshell tests, c:/foo/bar can pass as a valid URL, but + // newChannel won't be able to handle it. + url = "file:///" + url; + channel = Services.io.newChannel(url, null, null); + } + let chunks = []; + let streamListener = { + onStartRequest: function(aRequest, aContext, aStatusCode) { + if (!Components.isSuccessCode(aStatusCode)) { + deferred.reject("Request failed: " + url); + } + }, + onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount) { + chunks.push(NetUtil.readInputStreamToString(aStream, aCount)); + }, + onStopRequest: function(aRequest, aContext, aStatusCode) { + if (!Components.isSuccessCode(aStatusCode)) { + deferred.reject("Request failed: " + url); + return; + } + + charset = channel.contentCharset; + deferred.resolve(chunks.join("")); + } + }; + + channel.loadFlags = aOptions.loadFromCache + ? channel.LOAD_FROM_CACHE + : channel.LOAD_BYPASS_CACHE; + channel.asyncOpen(streamListener, null); + break; + } + + return deferred.promise.then(function (source) { + return convertToUnicode(source, charset); + }); +} + +/** + * Convert a given string, encoded in a given character set, to unicode. + * + * @param string aString + * A string. + * @param string aCharset + * A character set. + */ +function convertToUnicode(aString, aCharset=null) { + // Decoding primitives. + // let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + // .createInstance(Ci.nsIScriptableUnicodeConverter); + // try { + // converter.charset = aCharset || "UTF-8"; + // return converter.ConvertToUnicode(aString); + // } catch(e) { + return aString; + // } +} + +/** + * Report the given error in the error console and to stdout. + */ +function reportError(aError) { + // Cu.reportError(aError); + dumpn(aError.message + ":\n" + aError.stack); +} diff --git a/cocos/scripting/javascript/bindings/js/debugger/core/promise.js b/cocos/scripting/javascript/bindings/js/debugger/core/promise.js new file mode 100644 index 0000000000..a695f5a3ad --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/core/promise.js @@ -0,0 +1,294 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/*jshint undef: true es5: true node: true browser: true devel: true + forin: true latedef: false */ +/*global define: true, Cu: true, __URI__: true */ +//;(function(id, factory) { // Module boilerplate :( +// if (typeof(define) === 'function') { // RequireJS +// define(factory); +// } else if (typeof(require) === 'function') { // CommonJS +// factory.call(this, require, exports, module); +// } else if (String(this).indexOf('BackstagePass') >= 0) { // JSM +// this[factory.name] = {}; +// try { +// this.console = this['Components'].utils +// .import('resource://gre/modules/devtools/Console.jsm', {}).console; +// } +// catch (ex) { +// // Avoid failures on different toolkit configurations. +// } +// factory(function require(uri) { +// var imports = {}; +// this['Components'].utils.import(uri, imports); +// return imports; +// }, this[factory.name], { uri: __URI__, id: id }); +// this.EXPORTED_SYMBOLS = [factory.name]; +// } else { // Browser or alike +// var globals = this; +// factory(function require(id) { +// return globals[id]; +// }, (globals[id] = {}), { uri: document.location.href + '#' + id, id: id }); +// } +//}).call(this, 'promise/core', function Promise(require, exports, module) { + +'use strict'; + +var exports = exports || {}; + +//module.metadata = { +// "stability": "unstable" +//}; + +/** + * Internal utility: Wraps given `value` into simplified promise, successfully + * fulfilled to a given `value`. Note the result is not a complete promise + * implementation, as its method `then` does not returns anything. + */ +function fulfilled(value) { + return { then: function then(fulfill) { fulfill(value); } }; +} + +/** + * Internal utility: Wraps given input into simplified promise, pre-rejected + * with a given `reason`. Note the result is not a complete promise + * implementation, as its method `then` does not returns anything. + */ +function rejected(reason) { + return { then: function then(fulfill, reject) { reject(reason); } }; +} + +/** + * Internal utility: Returns `true` if given `value` is a promise. Value is + * assumed to be a promise if it implements method `then`. + */ +function isPromise(value) { + return value && typeof(value.then) === 'function'; +} + +/** + * Creates deferred object containing fresh promise & methods to either resolve + * or reject it. The result is an object with the following properties: + * - `promise` Eventual value representation implementing CommonJS [Promises/A] + * (http://wiki.commonjs.org/wiki/Promises/A) API. + * - `resolve` Single shot function that resolves enclosed `promise` with a + * given `value`. + * - `reject` Single shot function that rejects enclosed `promise` with a given + * `reason`. + * + * An optional `prototype` argument is used as a prototype of the returned + * `promise` allowing one to implement additional API. If prototype is not + * passed then it falls back to `Object.prototype`. + * + * ## Example + * + * function fetchURI(uri, type) { + * var deferred = defer(); + * var request = new XMLHttpRequest(); + * request.open("GET", uri, true); + * request.responseType = type; + * request.onload = function onload() { + * deferred.resolve(request.response); + * } + * request.onerror = function(event) { + * deferred.reject(event); + * } + * request.send(); + * + * return deferred.promise; + * } + */ +function defer(prototype) { + // Define FIFO queue of observer pairs. Once promise is resolved & all queued + // observers are forwarded to `result` and variable is set to `null`. + var observers = []; + + // Promise `result`, which will be assigned a resolution value once promise + // is resolved. Note that result will always be assigned promise (or alike) + // object to take care of propagation through promise chains. If result is + // `null` promise is not resolved yet. + var result = null; + + prototype = (prototype || prototype === null) ? prototype : Object.prototype; + + // Create an object implementing promise API. + var promise = Object.create(prototype, { + then: { value: function then(onFulfill, onError) { + var deferred = defer(prototype); + + function resolve(value) { + // If `onFulfill` handler is provided resolve `deferred.promise` with + // result of invoking it with a resolution value. If handler is not + // provided propagate value through. + try { + deferred.resolve(onFulfill ? onFulfill(value) : value); + } + // `onFulfill` may throw exception in which case resulting promise + // is rejected with thrown exception. + catch(error) { + if (exports._reportErrors && typeof(console) === 'object') + console.error(error); + // Note: Following is equivalent of `deferred.reject(error)`, + // we use this shortcut to reduce a stack. + deferred.resolve(rejected(error)); + } + } + + function reject(reason) { + try { + if (onError) deferred.resolve(onError(reason)); + else deferred.resolve(rejected(reason)); + } + catch(error) { + if (exports._reportErrors && typeof(console) === 'object') + console.error(error); + deferred.resolve(rejected(error)); + } + } + + // If enclosed promise (`this.promise`) observers queue is still alive + // enqueue a new observer pair into it. Note that this does not + // necessary means that promise is pending, it may already be resolved, + // but we still have to queue observers to guarantee an order of + // propagation. + if (observers) { + observers.push({ resolve: resolve, reject: reject }); + } + // Otherwise just forward observer pair right to a `result` promise. + else { + result.then(resolve, reject); + } + + return deferred.promise; + }} + }) + + var deferred = { + promise: promise, + /** + * Resolves associated `promise` to a given `value`, unless it's already + * resolved or rejected. Note that resolved promise is not necessary a + * successfully fulfilled. Promise may be resolved with a promise `value` + * in which case `value` promise's fulfillment / rejection will propagate + * up to a promise resolved with `value`. + */ + resolve: function resolve(value) { + if (!result) { + // Store resolution `value` in a `result` as a promise, so that all + // the subsequent handlers can be simply forwarded to it. Since + // `result` will be a promise all the value / error propagation will + // be uniformly taken care of. + result = isPromise(value) ? value : fulfilled(value); + + // Forward already registered observers to a `result` promise in the + // order they were registered. Note that we intentionally dequeue + // observer at a time until queue is exhausted. This makes sure that + // handlers registered as side effect of observer forwarding are + // queued instead of being invoked immediately, guaranteeing FIFO + // order. + while (observers.length) { + var observer = observers.shift(); + result.then(observer.resolve, observer.reject); + } + + // Once `observers` queue is exhausted we `null`-ify it, so that + // new handlers are forwarded straight to the `result`. + observers = null; + } + }, + /** + * Rejects associated `promise` with a given `reason`, unless it's already + * resolved / rejected. This is just a (better performing) convenience + * shortcut for `deferred.resolve(reject(reason))`. + */ + reject: function reject(reason) { + // Note that if promise is resolved that does not necessary means that it + // is successfully fulfilled. Resolution value may be a promise in which + // case its result propagates. In other words if promise `a` is resolved + // with promise `b`, `a` is either fulfilled or rejected depending + // on weather `b` is fulfilled or rejected. Here `deferred.promise` is + // resolved with a promise pre-rejected with a given `reason`, there for + // `deferred.promise` is rejected with a given `reason`. This may feel + // little awkward first, but doing it this way greatly simplifies + // propagation through promise chains. + deferred.resolve(rejected(reason)); + } + }; + + return deferred; +} +exports.defer = defer; + +/** + * Returns a promise resolved to a given `value`. Optionally a second + * `prototype` argument may be provided to be used as a prototype for the + * returned promise. + */ +function resolve(value, prototype) { + var deferred = defer(prototype); + deferred.resolve(value); + return deferred.promise; +} +exports.resolve = resolve; + +/** + * Returns a promise rejected with a given `reason`. Optionally a second + * `prototype` argument may be provided to be used as a prototype for the + * returned promise. + */ +function reject(reason, prototype) { + var deferred = defer(prototype); + deferred.reject(reason); + return deferred.promise; +} +exports.reject = reject; + +var promised = (function() { + // Note: Define shortcuts and utility functions here in order to avoid + // slower property accesses and unnecessary closure creations on each + // call of this popular function. + + var call = Function.call; + var concat = Array.prototype.concat; + + // Utility function that does following: + // execute([ f, self, args...]) => f.apply(self, args) + function execute(args) { return call.apply(call, args) } + + // Utility function that takes promise of `a` array and maybe promise `b` + // as arguments and returns promise for `a.concat(b)`. + function promisedConcat(promises, unknown) { + return promises.then(function(values) { + return resolve(unknown).then(function(value) { + return values.concat([ value ]); + }); + }); + } + + return function promised(f, prototype) { + /** + Returns a wrapped `f`, which when called returns a promise that resolves to + `f(...)` passing all the given arguments to it, which by the way may be + promises. Optionally second `prototype` argument may be provided to be used + a prototype for a returned promise. + + ## Example + + var promise = promised(Array)(1, promise(2), promise(3)) + promise.then(console.log) // => [ 1, 2, 3 ] + **/ + + return function promised() { + // create array of [ f, this, args... ] + return concat.apply([ f, this ], arguments). + // reduce it via `promisedConcat` to get promised array of fulfillments + reduce(promisedConcat, resolve([], prototype)). + // finally map that to promise of `f.apply(this, args...)` + then(execute); + }; + } +})(); +exports.promised = promised; +// +var all = promised(Array); +exports.all = all; +// +//}); diff --git a/cocos/scripting/javascript/bindings/js/debugger/main.js b/cocos/scripting/javascript/bindings/js/debugger/main.js new file mode 100644 index 0000000000..f08009ade6 --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/main.js @@ -0,0 +1,928 @@ +/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; +/** + * Toolkit glue for the remote debugging protocol, loaded into the + * debugging global. + */ + +//const Ci = Components.interfaces; +//const Cc = Components.classes; +//const CC = Components.Constructor; +//const Cu = Components.utils; +//const Cr = Components.results; +//const DBG_STRINGS_URI = "chrome://global/locale/devtools/debugger.properties"; +// +//Cu.import("resource://gre/modules/Services.jsm"); +//Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +//let wantLogging = Services.prefs.getBoolPref("devtools.debugger.log"); +// +//Cu.import("resource://gre/modules/jsdebugger.jsm"); +//addDebuggerToGlobal(this); +// +//Cu.import("resource://gre/modules/commonjs/sdk/core/promise.js"); +//const { defer, resolve, reject, all } = Promise; +// +//Cu.import("resource://gre/modules/devtools/SourceMap.jsm"); +// +//loadSubScript.call(this, "resource://gre/modules/devtools/DevToolsUtils.js"); + +let wantLogging = true; +let debuggerServer = null; + +function dumpn(str) { + if (wantLogging) { + log("DBG-SERVER: " + str + "\n"); + } +} + +function dbg_assert(cond, e) { + if (!cond) { + log("assert >>>> " + cond.toString()); + return e; + } +} + +function XPCInspector() { + this.exitNestedEventLoop = _exitNestedEventLoop; + this.enterNestedEventLoop = _enterNestedEventLoop; + this.eventLoopNestLevel = _getEventLoopNestLevel; +} + +//loadSubScript.call(this, "resource://gre/modules/devtools/server/transport.js"); + +// XPCOM constructors +// const ServerSocket = CC("@mozilla.org/network/server-socket;1", +// "nsIServerSocket", +// "initSpecialConnection"); + +function ServerSocket(aPort, flags, c){ + this.asyncListen = function(server){ + log("asyncListen...."); + debuggerServer = server; + }; +}; + +var gRegisteredModules = Object.create(null); + +/** + * The ModuleAPI object is passed to modules loaded using the + * DebuggerServer.registerModule() API. Modules can use this + * object to register actor factories. + * Factories registered through the module API will be removed + * when the module is unregistered or when the server is + * destroyed. + */ +function ModuleAPI() { + let activeTabActors = new Set(); + let activeGlobalActors = new Set(); + + return { + // See DebuggerServer.addGlobalActor for a description. + addGlobalActor: function(factory, name) { + DebuggerServer.addGlobalActor(factory, name); + activeGlobalActors.add(factory); + }, + // See DebuggerServer.removeGlobalActor for a description. + removeGlobalActor: function(factory) { + DebuggerServer.removeGlobalActor(factory); + activeGlobalActors.delete(factory); + }, + + // See DebuggerServer.addTabActor for a description. + addTabActor: function(factory, name) { + DebuggerServer.addTabActor(factory, name); + activeTabActors.add(factory); + }, + // See DebuggerServer.removeTabActor for a description. + removeTabActor: function(factory) { + DebuggerServer.removeTabActor(factory); + activeTabActors.delete(factory); + }, + + // Destroy the module API object, unregistering any + // factories registered by the module. + destroy: function() { + for (let factory of activeTabActors) { + DebuggerServer.removeTabActor(factory); + } + activeTabActors = null; + for (let factory of activeGlobalActors) { + DebuggerServer.removeGlobalActor(factory); + } + activeGlobalActors = null; + } + } +}; + +/*** + * Public API + */ +var DebuggerServer = { + _listener: null, + _initialized: false, + _transportInitialized: false, + xpcInspector: null, + _transport: null, + // Number of currently open TCP connections. + _socketConnections: 0, + // Map of global actor names to actor constructors provided by extensions. + globalActorFactories: {}, + // Map of tab actor names to actor constructors provided by extensions. + tabActorFactories: {}, + + LONG_STRING_LENGTH: 10000, + LONG_STRING_INITIAL_LENGTH: 1000, + LONG_STRING_READ_LENGTH: 1000, + + /** + * A handler function that prompts the user to accept or decline the incoming + * connection. + */ + _allowConnection: null, + + /** + * Prompt the user to accept or decline the incoming connection. This is the + * default implementation that products embedding the debugger server may + * choose to override. + * + * @return true if the connection should be permitted, false otherwise + */ + _defaultAllowConnection: function DS__defaultAllowConnection() { + // let title = L10N.getStr("remoteIncomingPromptTitle"); + // let msg = L10N.getStr("remoteIncomingPromptMessage"); + // let disableButton = L10N.getStr("remoteIncomingPromptDisable"); + // let prompt = Services.prompt; + // let flags = prompt.BUTTON_POS_0 * prompt.BUTTON_TITLE_OK + + // prompt.BUTTON_POS_1 * prompt.BUTTON_TITLE_CANCEL + + // prompt.BUTTON_POS_2 * prompt.BUTTON_TITLE_IS_STRING + + // prompt.BUTTON_POS_1_DEFAULT; + // let result = prompt.confirmEx(null, title, msg, flags, null, null, + // disableButton, null, { value: false }); + // if (result == 0) { + // return true; + // } + // if (result == 2) { + // DebuggerServer.closeListener(true); + // Services.prefs.setBoolPref("devtools.debugger.remote-enabled", false); + // } + // return false; + return true; + }, + + /** + * Initialize the debugger server. + * + * @param function aAllowConnectionCallback + * The embedder-provider callback, that decides whether an incoming + * remote protocol conection should be allowed or refused. + */ + init: function DS_init(aAllowConnectionCallback) { + if (this.initialized) { + return; + } + + this.xpcInspector = new XPCInspector();//Cc["@mozilla.org/jsinspector;1"].getService(Ci.nsIJSInspector); + this.initTransport(aAllowConnectionCallback); + this.addActors("resource://gre/modules/devtools/server/actors/root.js"); + + this._initialized = true; + }, + + /** + * Initialize the debugger server's transport variables. This can be + * in place of init() for cases where the jsdebugger isn't needed. + * + * @param function aAllowConnectionCallback + * The embedder-provider callback, that decides whether an incoming + * remote protocol conection should be allowed or refused. + */ + initTransport: function DS_initTransport(aAllowConnectionCallback) { + if (this._transportInitialized) { + return; + } + + this._connections = {}; + this._nextConnID = 0; + this._transportInitialized = true; + this._allowConnection = aAllowConnectionCallback ? + aAllowConnectionCallback : + this._defaultAllowConnection; + }, + + get initialized() this._initialized, + + /** + * Performs cleanup tasks before shutting down the debugger server, if no + * connections are currently open. Such tasks include clearing any actor + * constructors added at runtime. This method should be called whenever a + * debugger server is no longer useful, to avoid memory leaks. After this + * method returns, the debugger server must be initialized again before use. + */ + destroy: function DS_destroy() { + if (!this._initialized) { + return; + } + + for (let connID of Object.getOwnPropertyNames(this._connections)) { + this._connections[connID].close(); + } + + for (let id of Object.getOwnPropertyNames(gRegisteredModules)) { + let mod = gRegisteredModules[id]; + mod.module.unregister(mod.api); + } + gRegisteredModules = {}; + + this.closeListener(); + this.globalActorFactories = {}; + this.tabActorFactories = {}; + delete this._allowConnection; + this._transportInitialized = false; + this._initialized = false; + dumpn("Debugger server is shut down."); + }, + + /** + * Load a subscript into the debugging global. + * + * @param aURL string A url that will be loaded as a subscript into the + * debugging global. The user must load at least one script + * that implements a createRootActor() function to create the + * server's root actor. + */ + addActors: function DS_addActors(aURL) { + //loadSubScript.call(this, aURL); + }, + + /** + * Register a CommonJS module with the debugger server. + * @param id string + * The ID of a CommonJS module. This module must export + * 'register' and 'unregister' functions. + */ + registerModule: function(id) { + if (id in gRegisteredModules) { + throw new Error("Tried to register a module twice: " + id + "\n"); + } + + let moduleAPI = ModuleAPI(); + + let {devtools} = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); + let mod = devtools.require(id); + mod.register(moduleAPI); + gRegisteredModules[id] = { module: mod, api: moduleAPI }; + }, + + /** + * Returns true if a module id has been registered. + */ + isModuleRegistered: function(id) { + return (id in gRegisteredModules); + }, + + /** + * Unregister a previously-loaded CommonJS module from the debugger server. + */ + unregisterModule: function(id) { + let mod = gRegisteredModules[id]; + if (!mod) { + throw new Error("Tried to unregister a module that was not previously registered."); + } + mod.module.unregister(mod.api); + mod.api.destroy(); + delete gRegisteredModules[id]; + }, + + /** + * Install Firefox-specific actors. + */ + addBrowserActors: function DS_addBrowserActors() { + this.addActors("resource://gre/modules/devtools/server/actors/webbrowser.js"); + this.addActors("resource://gre/modules/devtools/server/actors/script.js"); + this.addGlobalActor(this.ChromeDebuggerActor, "chromeDebugger"); + this.addActors("resource://gre/modules/devtools/server/actors/webconsole.js"); + this.addActors("resource://gre/modules/devtools/server/actors/gcli.js"); + if ("nsIProfiler" in Ci) + this.addActors("resource://gre/modules/devtools/server/actors/profiler.js"); + + this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); + this.addActors("resource://gre/modules/devtools/server/actors/webapps.js"); + this.registerModule("devtools/server/actors/inspector"); + }, + + /** + * Listens on the given port for remote debugger connections. + * + * @param aPort int + * The port to listen on. + */ + openListener: function DS_openListener(aPort) { + // if (!Services.prefs.getBoolPref("devtools.debugger.remote-enabled")) { + // return false; + // } + this._checkInit(); + + // Return early if the server is already listening. + if (this._listener) { + return true; + } + + // let flags = Ci.nsIServerSocket.KeepWhenOffline; + // A preference setting can force binding on the loopback interface. + // if (Services.prefs.getBoolPref("devtools.debugger.force-local")) { + // flags |= Ci.nsIServerSocket.LoopbackOnly; + // } + + let flags = 0; + + try { + let socket = new ServerSocket(aPort, flags, 4); + socket.asyncListen(this); + this._listener = socket; + } catch (e) { + dumpn("Could not start debugging listener on port " + aPort + ": " + e); + throw "Cr.NS_ERROR_NOT_AVAILABLE"; + } + this._socketConnections++; + + return true; + }, + + /** + * Close a previously-opened TCP listener. + * + * @param aForce boolean [optional] + * If set to true, then the socket will be closed, regardless of the + * number of open connections. + */ + closeListener: function DS_closeListener(aForce) { + if (!this._listener || this._socketConnections == 0) { + return false; + } + + // Only close the listener when the last connection is closed, or if the + // aForce flag is passed. + if (--this._socketConnections == 0 || aForce) { + this._listener.close(); + this._listener = null; + this._socketConnections = 0; + } + + return true; + }, + + /** + * Creates a new connection to the local debugger speaking over a fake + * transport. This connection results in straightforward calls to the onPacket + * handlers of each side. + * + * @returns a client-side DebuggerTransport for communicating with + * the newly-created connection. + */ + connectPipe: function DS_connectPipe() { + this._checkInit(); + + let serverTransport = new LocalDebuggerTransport; + let clientTransport = new LocalDebuggerTransport(serverTransport); + serverTransport.other = clientTransport; + let connection = this._onConnection(serverTransport); + + // I'm putting this here because I trust you. + // + // There are times, when using a local connection, when you're going + // to be tempted to just get direct access to the server. Resist that + // temptation! If you succumb to that temptation, you will make the + // fine developers that work on Fennec and Firefox OS sad. They're + // professionals, they'll try to act like they understand, but deep + // down you'll know that you hurt them. + // + // This reference allows you to give in to that temptation. There are + // times this makes sense: tests, for example, and while porting a + // previously local-only codebase to the remote protocol. + // + // But every time you use this, you will feel the shame of having + // used a property that starts with a '_'. + clientTransport._serverConnection = connection; + + return clientTransport; + }, + + + // nsIServerSocketListener implementation + + onSocketAccepted: + makeInfallible(function DS_onSocketAccepted(aSocket, aTransport) { + if (!this._allowConnection()) { + return; + } + dumpn("New debugging connection on " + aTransport.host + ":" + aTransport.port); + + let input = aTransport.openInputStream(0, 0, 0); + let output = aTransport.openOutputStream(0, 0, 0); + let transport = new DebuggerTransport(input, output); + DebuggerServer._onConnection(transport); + }, "DebuggerServer.onSocketAccepted"), + + onStopListening: function DS_onStopListening(aSocket, status) { + dumpn("onStopListening, status: " + status); + }, + + /** + * Raises an exception if the server has not been properly initialized. + */ + _checkInit: function DS_checkInit() { + if (!this._transportInitialized) { + throw "DebuggerServer has not been initialized."; + } + + if (!this.createRootActor) { + throw "Use DebuggerServer.addActors() to add a root actor implementation."; + } + }, + + /** + * Create a new debugger connection for the given transport. Called + * after connectPipe() or after an incoming socket connection. + */ + _onConnection: function DS_onConnection(aTransport) { + log("DebuggerServer._onConnection...."); + + this._transport = aTransport; + + let connID = "conn" + this._nextConnID++ + '.'; + let conn = new DebuggerServerConnection(connID, aTransport); + this._connections[connID] = conn; + + // Create a root actor for the connection and send the hello packet. + conn.rootActor = this.createRootActor(conn); + conn.addActor(conn.rootActor); + + aTransport.send(conn.rootActor.sayHello()); + aTransport.ready(); + + return conn; + }, + + /** + * Remove the connection from the debugging server. + */ + _connectionClosed: function DS_connectionClosed(aConnection) { + delete this._connections[aConnection.prefix]; + }, + + // DebuggerServer extension API. + + /** + * Registers handlers for new tab-scoped request types defined dynamically. + * This is used for example by add-ons to augment the functionality of the tab + * actor. Note that the name or actorPrefix of the request type is not allowed + * to clash with existing protocol packet properties, like 'title', 'url' or + * 'actor', since that would break the protocol. + * + * @param aFunction function + * The constructor function for this request type. This expects to be + * called as a constructor (i.e. with 'new'), and passed two + * arguments: the DebuggerServerConnection, and the BrowserTabActor + * with which it will be associated. + * + * @param aName string [optional] + * The name of the new request type. If this is not present, the + * actorPrefix property of the constructor prototype is used. + */ + addTabActor: function DS_addTabActor(aFunction, aName) { + let name = aName ? aName : aFunction.prototype.actorPrefix; + if (["title", "url", "actor"].indexOf(name) != -1) { + throw Error(name + " is not allowed"); + } + if (DebuggerServer.tabActorFactories.hasOwnProperty(name)) { + throw Error(name + " already exists"); + } + DebuggerServer.tabActorFactories[name] = aFunction; + }, + + /** + * Unregisters the handler for the specified tab-scoped request type. + * This may be used for example by add-ons when shutting down or upgrading. + * + * @param aFunction function + * The constructor function for this request type. + */ + removeTabActor: function DS_removeTabActor(aFunction) { + for (let name in DebuggerServer.tabActorFactories) { + let handler = DebuggerServer.tabActorFactories[name]; + if (handler.name == aFunction.name) { + delete DebuggerServer.tabActorFactories[name]; + } + } + }, + + /** + * Registers handlers for new browser-scoped request types defined + * dynamically. This is used for example by add-ons to augment the + * functionality of the root actor. Note that the name or actorPrefix of the + * request type is not allowed to clash with existing protocol packet + * properties, like 'from', 'tabs' or 'selected', since that would break the + * protocol. + * + * @param aFunction function + * The constructor function for this request type. This expects to be + * called as a constructor (i.e. with 'new'), and passed two + * arguments: the DebuggerServerConnection, and the BrowserRootActor + * with which it will be associated. + * + * @param aName string [optional] + * The name of the new request type. If this is not present, the + * actorPrefix property of the constructor prototype is used. + */ + addGlobalActor: function DS_addGlobalActor(aFunction, aName) { + let name = aName ? aName : aFunction.prototype.actorPrefix; + if (["from", "tabs", "selected"].indexOf(name) != -1) { + throw Error(name + " is not allowed"); + } + if (DebuggerServer.globalActorFactories.hasOwnProperty(name)) { + throw Error(name + " already exists"); + } + DebuggerServer.globalActorFactories[name] = aFunction; + }, + + /** + * Unregisters the handler for the specified browser-scoped request type. + * This may be used for example by add-ons when shutting down or upgrading. + * + * @param aFunction function + * The constructor function for this request type. + */ + removeGlobalActor: function DS_removeGlobalActor(aFunction) { + for (let name in DebuggerServer.globalActorFactories) { + let handler = DebuggerServer.globalActorFactories[name]; + if (handler.name == aFunction.name) { + delete DebuggerServer.globalActorFactories[name]; + } + } + } +}; + + +/** + * Construct an ActorPool. + * + * ActorPools are actorID -> actor mapping and storage. These are + * used to accumulate and quickly dispose of groups of actors that + * share a lifetime. + */ +function ActorPool(aConnection) +{ + this.conn = aConnection; + this._cleanups = {}; + this._actors = {}; +} + +ActorPool.prototype = { + /** + * Add an actor to the actor pool. If the actor doesn't have an ID, + * allocate one from the connection. + * + * @param aActor object + * The actor implementation. If the object has a + * 'disconnect' property, it will be called when the actor + * pool is cleaned up. + */ + addActor: function AP_addActor(aActor) { + aActor.conn = this.conn; + if (!aActor.actorID) { + let prefix = aActor.actorPrefix; + if (typeof aActor == "function") { + prefix = aActor.prototype.actorPrefix; + } + aActor.actorID = this.conn.allocID(prefix || undefined); + } + + if (aActor.registeredPool) { + aActor.registeredPool.removeActor(aActor); + } + aActor.registeredPool = this; + + this._actors[aActor.actorID] = aActor; + if (aActor.disconnect) { + this._cleanups[aActor.actorID] = aActor; + } + }, + + get: function AP_get(aActorID) { + return this._actors[aActorID]; + }, + + has: function AP_has(aActorID) { + return aActorID in this._actors; + }, + + /** + * Returns true if the pool is empty. + */ + isEmpty: function AP_isEmpty() { + return Object.keys(this._actors).length == 0; + }, + + /** + * Remove an actor from the actor pool. + */ + removeActor: function AP_remove(aActor) { + delete this._actors[aActor.actorID]; + delete this._cleanups[aActor.actorID]; + }, + + /** + * Match the api expected by the protocol library. + */ + unmanage: function(aActor) { + return this.removeActor(aActor); + }, + + /** + * Run all actor cleanups. + */ + cleanup: function AP_cleanup() { + for each (let actor in this._cleanups) { + actor.disconnect(); + } + this._cleanups = {}; + } +} + +/** + * Creates a DebuggerServerConnection. + * + * Represents a connection to this debugging global from a client. + * Manages a set of actors and actor pools, allocates actor ids, and + * handles incoming requests. + * + * @param aPrefix string + * All actor IDs created by this connection should be prefixed + * with aPrefix. + * @param aTransport transport + * Packet transport for the debugging protocol. + */ +function DebuggerServerConnection(aPrefix, aTransport) +{ + this._prefix = aPrefix; + this._transport = aTransport; + this._transport.hooks = this; + this._nextID = 1; + + this._actorPool = new ActorPool(this); + this._extraPools = []; +} + +DebuggerServerConnection.prototype = { + _prefix: null, + get prefix() { return this._prefix }, + + _transport: null, + get transport() { return this._transport }, + + close: function() { + this._transport.close(); + }, + + send: function DSC_send(aPacket) { + this.transport.send(aPacket); + }, + + allocID: function DSC_allocID(aPrefix) { + return this.prefix + (aPrefix || '') + this._nextID++; + }, + + /** + * Add a map of actor IDs to the connection. + */ + addActorPool: function DSC_addActorPool(aActorPool) { + this._extraPools.push(aActorPool); + }, + + /** + * Remove a previously-added pool of actors to the connection. + * + * @param ActorPool aActorPool + * The ActorPool instance you want to remove. + * @param boolean aCleanup + * True if you want to disconnect each actor from the pool, false + * otherwise. + */ + removeActorPool: function DSC_removeActorPool(aActorPool, aCleanup) { + let index = this._extraPools.lastIndexOf(aActorPool); + if (index > -1) { + let pool = this._extraPools.splice(index, 1); + if (aCleanup) { + pool.map(function(p) { p.cleanup(); }); + } + } + }, + + /** + * Add an actor to the default actor pool for this connection. + */ + addActor: function DSC_addActor(aActor) { + this._actorPool.addActor(aActor); + }, + + /** + * Remove an actor to the default actor pool for this connection. + */ + removeActor: function DSC_removeActor(aActor) { + this._actorPool.removeActor(aActor); + }, + + /** + * Match the api expected by the protocol library. + */ + unmanage: function(aActor) { + return this.removeActor(aActor); + }, + + /** + * Look up an actor implementation for an actorID. Will search + * all the actor pools registered with the connection. + * + * @param aActorID string + * Actor ID to look up. + */ + getActor: function DSC_getActor(aActorID) { + let pool = this.poolFor(aActorID); + if (pool) { + return pool.get(aActorID); + } + + if (aActorID === "root") { + return this.rootActor; + } + + return null; + }, + + poolFor: function DSC_actorPool(aActorID) { + if (this._actorPool && this._actorPool.has(aActorID)) { + return this._actorPool; + } + + for (let pool of this._extraPools) { + if (pool.has(aActorID)) { + return pool; + } + } + return null; + }, + + _unknownError: function DSC__unknownError(aPrefix, aError) { + let errorString = safeErrorString(aError); + errorString += "\n" + aError.stack; + // Cu.reportError(errorString); + dumpn(errorString); + return { + error: "unknownError", + message: (aPrefix + "': " + errorString) + }; + }, + + // Transport hooks. + + /** + * Called by DebuggerTransport to dispatch incoming packets as appropriate. + * + * @param aPacket object + * The incoming packet. + */ + onPacket: function DSC_onPacket(aPacket) { + let actor = this.getActor(aPacket.to); + if (!actor) { + this.transport.send({ from: aPacket.to ? aPacket.to : "root", + error: "noSuchActor" }); + return; + } + + // Dyamically-loaded actors have to be created lazily. + if (typeof actor == "function") { + let instance; + try { + instance = new actor(); + } catch (e) { + this.transport.send(this._unknownError( + "Error occurred while creating actor '" + actor.name, + e)); + } + instance.parentID = actor.parentID; + // We want the newly-constructed actor to completely replace the factory + // actor. Reusing the existing actor ID will make sure ActorPool.addActor + // does the right thing. + instance.actorID = actor.actorID; + actor.registeredPool.addActor(instance); + actor = instance; + } + + var ret = null; + // log("actor.requestTypes: "+actor.requestTypes+", cb: "+actor.requestTypes[aPacket.type]); + // Dispatch the request to the actor. + if (actor.requestTypes && actor.requestTypes[aPacket.type]) { + try { + this.currentPacket = aPacket; + ret = actor.requestTypes[aPacket.type].bind(actor)(aPacket, this); + } catch(e) { + this.transport.send(this._unknownError( + "error occurred while processing '" + aPacket.type, + e)); + } finally { + delete this.currentPacket; + } + } else { + ret = { error: "unrecognizedPacketType", + message: ('Actor "' + actor.actorID + + '" does not recognize the packet type "' + + aPacket.type + '"') }; + } + + if (!ret) { + // This should become an error once we've converted every user + // of this to promises in bug 794078. + return; + } + + resolve(ret) + .then(null, (e) => { + return this._unknownError( + "error occurred while processing '" + aPacket.type, + e); + }) + .then(function (aResponse) { + if (!aResponse.from) { + aResponse.from = aPacket.to; + } + return aResponse; + }) + .then(this.transport.send.bind(this.transport)); + }, + + /** + * Called by DebuggerTransport when the underlying stream is closed. + * + * @param aStatus nsresult + * The status code that corresponds to the reason for closing + * the stream. + */ + onClosed: function DSC_onClosed(aStatus) { + dumpn("Cleaning up connection."); + + this._actorPool.cleanup(); + this._actorPool = null; + this._extraPools.map(function(p) { p.cleanup(); }); + this._extraPools = null; + + DebuggerServer._connectionClosed(this); + }, + + /* + * Debugging helper for inspecting the state of the actor pools. + */ + _dumpPools: function DSC_dumpPools() { + dumpn("/-------------------- dumping pools:"); + if (this._actorPool) { + dumpn("--------------------- actorPool actors: " + + uneval(Object.keys(this._actorPool._actors))); + } + for each (let pool in this._extraPools) + dumpn("--------------------- extraPool actors: " + + uneval(Object.keys(pool._actors))); + }, + + /* + * Debugging helper for inspecting the state of an actor pool. + */ + _dumpPool: function DSC_dumpPools(aPool) { + dumpn("/-------------------- dumping pool:"); + dumpn("--------------------- actorPool actors: " + + uneval(Object.keys(aPool._actors))); + } +}; + +/** + * Localization convenience methods. + */ +// let L10N = { + +// /** +// * L10N shortcut function. +// * +// * @param string aName +// * @return string +// */ +// getStr: function L10N_getStr(aName) { +// return this.stringBundle.GetStringFromName(aName); +// } +// }; + +// XPCOMUtils.defineLazyGetter(L10N, "stringBundle", function() { +// return Services.strings.createBundle(DBG_STRINGS_URI); +// }); diff --git a/cocos/scripting/javascript/bindings/js/debugger/transport.js b/cocos/scripting/javascript/bindings/js/debugger/transport.js new file mode 100644 index 0000000000..8676e367a8 --- /dev/null +++ b/cocos/scripting/javascript/bindings/js/debugger/transport.js @@ -0,0 +1,288 @@ +/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; +// Components.utils.import("resource://gre/modules/NetUtil.jsm"); + +/** + * An adapter that handles data transfers between the debugger client and + * server. It can work with both nsIPipe and nsIServerSocket transports so + * long as the properly created input and output streams are specified. + * + * @param aInput nsIInputStream + * The input stream. + * @param aOutput nsIAsyncOutputStream + * The output stream. + * + * Given a DebuggerTransport instance dt: + * 1) Set dt.hooks to a packet handler object (described below). + * 2) Call dt.ready() to begin watching for input packets. + * 3) Send packets as you please, and handle incoming packets passed to + * hook.onPacket. + * 4) Call dt.close() to close the connection, and disengage from the event + * loop. + * + * A packet handler object is an object with two methods: + * + * - onPacket(packet) - called when we have received a complete packet. + * |Packet| is the parsed form of the packet --- a JavaScript value, not + * a JSON-syntax string. + * + * - onClosed(status) - called when the connection is closed. |Status| is + * an nsresult, of the sort passed to nsIRequestObserver. + * + * Data is transferred as a JSON packet serialized into a string, with the + * string length prepended to the packet, followed by a colon + * ([length]:[packet]). The contents of the JSON packet are specified in + * the Remote Debugging Protocol specification. + */ +this.DebuggerTransport = function DebuggerTransport(aInput, aOutput) +{ + this._input = aInput; + this._output = aOutput; + + this._converter = null;//Cc["@mozilla.org/intl/scriptableunicodeconverter"] + // .createInstance(Ci.nsIScriptableUnicodeConverter); + // this._converter.charset = "UTF-8"; + + this._outgoing = ""; + this._incoming = ""; + + this.hooks = null; +} + +DebuggerTransport.prototype = { + /** + * Transmit a packet. + * + * This method returns immediately, without waiting for the entire + * packet to be transmitted, registering event handlers as needed to + * transmit the entire packet. Packets are transmitted in the order + * they are passed to this method. + */ + send: function DT_send(aPacket) { + // TODO (bug 709088): remove pretty printing when the protocol is done. + let data = JSON.stringify(aPacket, null, 2); + // data = this._converter.ConvertFromUnicode(data); + + let data_for_len = utf16to8(data); + + this._outgoing = data_for_len.length + ':' + data; + + this._flushOutgoing(); + }, + + /** + * Close the transport. + */ + close: function DT_close() { + this._input.close(); + this._output.close(); + }, + + /** + * Flush the outgoing stream. + */ + _flushOutgoing: function DT_flushOutgoing() { + if (this._outgoing.length > 0) { + // var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(); + // this._output.asyncWait(this, 0, 0, threadManager.currentThread); + log("outgoing: " + this._outgoing);//.substring(0, 200)); + _bufferWrite(this._outgoing); + } + }, + + onOutputStreamReady: + makeInfallible(function DT_onOutputStreamReady(aStream) { + let written = 0; + try { + written = aStream.write(this._outgoing, this._outgoing.length); + } catch(e if e.result == Components.results.NS_BASE_STREAM_CLOSED) { + dumpn("Connection closed."); + this.close(); + return; + } + this._outgoing = this._outgoing.slice(written); + this._flushOutgoing(); + }, "DebuggerTransport.prototype.onOutputStreamReady"), + + /** + * Initialize the input stream for reading. Once this method has been + * called, we watch for packets on the input stream, and pass them to + * this.hook.onPacket. + */ + ready: function DT_ready() { + // let pump = Cc["@mozilla.org/network/input-stream-pump;1"] + // .createInstance(Ci.nsIInputStreamPump); + // pump.init(this._input, -1, -1, 0, 0, false); + // pump.asyncRead(this, null); + }, + + // nsIStreamListener + onStartRequest: + makeInfallible(function DT_onStartRequest(aRequest, aContext) {}, + "DebuggerTransport.prototype.onStartRequest"), + + onStopRequest: + makeInfallible(function DT_onStopRequest(aRequest, aContext, aStatus) { + this.close(); + if (this.hooks) { + this.hooks.onClosed(aStatus); + this.hooks = null; + } + }, "DebuggerTransport.prototype.onStopRequest"), + + onDataAvailable: makeInfallible(function DT_onDataAvailable (incoming) +// makeInfallible(function DT_onDataAvailable(aRequest, aContext, +// aStream, aOffset, aCount) + { + this._incoming = incoming;//+= NetUtil.readInputStreamToString(aStream, + // aStream.available()); + while (this._processIncoming()) {}; + }, "DebuggerTransport.prototype.onDataAvailable"), + + /** + * Process incoming packets. Returns true if a packet has been received, either + * if it was properly parsed or not. Returns false if the incoming stream does + * not contain a full packet yet. After a proper packet is parsed, the dispatch + * handler DebuggerTransport.hooks.onPacket is called with the packet as a + * parameter. + */ + _processIncoming: function DT__processIncoming() { + // Well this is ugly. + let sep = this._incoming.indexOf(':'); + if (sep < 0) { + return false; + } + + let count = parseInt(this._incoming.substring(0, sep)); + if (this._incoming.length - (sep + 1) < count) { + // Don't have a complete request yet. + return false; + } + + // We have a complete request, pluck it out of the data and parse it. + this._incoming = this._incoming.substring(sep + 1); + let packet = this._incoming.substring(0, count); + this._incoming = this._incoming.substring(count); + + try { + // packet = this._converter.ConvertToUnicode(packet); + packet = utf8to16(packet); + var parsed = JSON.parse(packet); + } catch(e) { + let msg = "Error parsing incoming packet: " + packet + " (" + e + " - " + e.stack + ")"; + // if (Cu.reportError) { + // Cu.reportError(msg); + // } + dump(msg + "\n"); + return true; + } + + dumpn("Got: " + packet); + let self = this; + + // Services.tm.currentThread.dispatch(makeInfallible(function() { + self.hooks.onPacket(parsed); + // }, "DebuggerTransport instance's this.hooks.onPacket"), 0); + + return true; + } +} + + +/** + * An adapter that handles data transfers between the debugger client and + * server when they both run in the same process. It presents the same API as + * DebuggerTransport, but instead of transmitting serialized messages across a + * connection it merely calls the packet dispatcher of the other side. + * + * @param aOther LocalDebuggerTransport + * The other endpoint for this debugger connection. + * + * @see DebuggerTransport + */ +this.LocalDebuggerTransport = function LocalDebuggerTransport(aOther) +{ + this.other = aOther; + this.hooks = null; + + /* + * A packet number, shared between this and this.other. This isn't used + * by the protocol at all, but it makes the packet traces a lot easier to + * follow. + */ + this._serial = this.other ? this.other._serial : { count: 0 }; +} + +LocalDebuggerTransport.prototype = { + /** + * Transmit a message by directly calling the onPacket handler of the other + * endpoint. + */ + send: function LDT_send(aPacket) { + let serial = this._serial.count++; + if (wantLogging) { + if (aPacket.to) { + dumpn("Packet " + serial + " sent to " + uneval(aPacket.to)); + } else if (aPacket.from) { + dumpn("Packet " + serial + " sent from " + uneval(aPacket.from)); + } + } + this._deepFreeze(aPacket); + let other = this.other; + if (other) { + Services.tm.currentThread.dispatch(makeInfallible(function() { + // Avoid the cost of JSON.stringify() when logging is disabled. + if (wantLogging) { + dumpn("Received packet " + serial + ": " + JSON.stringify(aPacket, null, 2)); + } + if (other.hooks) { + other.hooks.onPacket(aPacket); + } + }, "LocalDebuggerTransport instance's this.other.hooks.onPacket"), 0); + } + }, + + /** + * Close the transport. + */ + close: function LDT_close() { + if (this.other) { + // Remove the reference to the other endpoint before calling close(), to + // avoid infinite recursion. + let other = this.other; + delete this.other; + other.close(); + } + if (this.hooks) { + this.hooks.onClosed(); + this.hooks = null; + } + }, + + /** + * An empty method for emulating the DebuggerTransport API. + */ + ready: function LDT_ready() {}, + + /** + * Helper function that makes an object fully immutable. + */ + _deepFreeze: function LDT_deepFreeze(aObject) { + Object.freeze(aObject); + for (let prop in aObject) { + // Freeze the properties that are objects, not on the prototype, and not + // already frozen. Note that this might leave an unfrozen reference + // somewhere in the object if there is an already frozen object containing + // an unfrozen object. + if (aObject.hasOwnProperty(prop) && typeof aObject === "object" && + !Object.isFrozen(aObject)) { + this._deepFreeze(o[prop]); + } + } + } +}; From f3f24e3bbd9ad9ab1e8147b9cb6c5a1006c02ed4 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 13:54:16 +0800 Subject: [PATCH 118/557] issue #2905:use - to connect multiple words --- docs/CODING_STYLE.md | 131 ++++++++++++++++++ docs/RELEASE_NOTES | 4 + .../AssetsManager.cpp | 0 .../AssetsManager.h | 0 .../CCPhysicsDebugNode.cpp | 0 .../CCPhysicsDebugNode.h | 0 .../CCPhysicsSprite.cpp | 0 .../CCPhysicsSprite.h | 0 8 files changed, 135 insertions(+) create mode 100644 docs/CODING_STYLE.md create mode 100644 docs/RELEASE_NOTES rename extensions/{AssetsManager => assets-manager}/AssetsManager.cpp (100%) rename extensions/{AssetsManager => assets-manager}/AssetsManager.h (100%) rename extensions/{physics_nodes => physics-nodes}/CCPhysicsDebugNode.cpp (100%) rename extensions/{physics_nodes => physics-nodes}/CCPhysicsDebugNode.h (100%) rename extensions/{physics_nodes => physics-nodes}/CCPhysicsSprite.cpp (100%) rename extensions/{physics_nodes => physics-nodes}/CCPhysicsSprite.h (100%) diff --git a/docs/CODING_STYLE.md b/docs/CODING_STYLE.md new file mode 100644 index 0000000000..4b7bf2a7c8 --- /dev/null +++ b/docs/CODING_STYLE.md @@ -0,0 +1,131 @@ +# cocos2d-x C++ coding sytle + + +## Detailed information + +Please, refer to this document for a detailed version of the cocos2d-x C++ coding sytle: + +* [cocos2d-x c++ coding style](http://www.cocos2d-x.org/wiki/Cocos2d_c++_coding_style) + + +## Quick Sample + +Use this sample as a quick reference. But DO READ the detailed doc for more info. + +Header file: + +```c++ +/** + * We use Doxygen strings for documentation. + * All public classes, methods, structs should be documented using Doxygen Strings + */ +class CC_DLL Sprite : public NodeRGBA, public TextureProtocol +{ /* class braces start in a new line */ + +/* no indentation here for public, protected or private */ +/* First add all the "public" stuff, then all the "protected" stuff, and finally all the "private" stuff +public: + + /* we don't use tabs, we use spaces, and we use a 4 space identation */ + /* 1st add all static const */ + static const int INDEX_NOT_INITIALIZED = -1; + + /* then add all the creators and other relevant static methods */ + static Sprite* create(); + static Sprite* create(const char *filename); + static Sprite* create(const char *filename, const Rect& rect); + + /* if applicable, then add the consturctors / destructors */ + Sprite(); + virtual ~Sprite(void); + + /* then add all the initialization methods */ + /* notice that they are in the same order as the creators */ + virtual bool init(void); + virtual bool initWithTexture(Texture2D *texture); + virtual bool initWithTexture(Texture2D *texture, const Rect& rect); + + + + /* then add the regular instace methods */ + virtual void updateTransform(void); + virtual SpriteBatchNode* getBatchNode(void); + virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); + + + /* then add all the overriden methods */ + /* notice that all overriden methods must use the 'override' keyword */ + /* overriden methods are not forced to have doxygen strings UNLESS they change the behavior in a non obvios way */ + virtual void setPosition(const Point& pos) override; + virtual void setRotation(float rotation) override; + virtual void setRotationX(float rotationX) override; + + + /* once you finish with the 'public' methods, start with the 'protected' ones */ +protected: + + /* protected methods are not forced to have Doxygen strings, but if they have it, better */ + void updateColor(void); + virtual void setTextureCoords(Rect rect); + + /* After adding all the methods, add the ivars */ + /* all ivars must start with _ */ + /* Do not use Hungarian notation */ + TextureAtlas* _textureAtlas; + int _atlasIndex; + SpriteBatchNode* _batchNode; +}; + +``` + +Implementation file: + +```c++ +/* Do not use doxygen comments on the implementation file */ + +/* The methos MUST be in the same order as where declared in the header file */ + +Sprite* Sprite::create(const char *filename) +{ + /* Don't use tabs. Use spaces. Use 4-space indentation */ + Sprite *sprite = new Sprite(); + + /* put curly braces in the same line as in the 'if'*/ + /* leave a space between the 'if' and the '(' */ + /* don't leave spaces between '()' */ + if (sprite && sprite->initWithFile(filename)) { + sprite->autorelease(); + return sprite; + } + CC_SAFE_DELETE(sprite); + return NULL; +} + +/* Initialization list can be indented to 0 spaces, or to 4 spaces. If in doubt, be consistent with the indentation already used in the file */ +/* Only use the Initialization lists for types that can't fail when initialized */ +Sprite::Sprite() +: _shouldBeHidden(false) +, _texture(nullptr) +, _physicsBody(nullptr) +{ +} + +/* use the 'initXXX' methods to initialize types that might fail */ +bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) +{ + /* it ok not use use curly braces */ + if (something) + do_something(); + else + something_else(); + + /* but if you use curly branches in one branch, all the branches should use curly branches */ + if (something) { + do_something1(); + do_something2(); + } else { + so_something_else(); + } +} + +``` diff --git a/docs/RELEASE_NOTES b/docs/RELEASE_NOTES new file mode 100644 index 0000000000..f10872da6c --- /dev/null +++ b/docs/RELEASE_NOTES @@ -0,0 +1,4 @@ +===== cocos2d-x 3.0 Release Notes ===== + +Please, read the online release notes document: +http://www.cocos2d-x.org/wiki/Release_Notes_for_Cocos2d-x_v300 \ No newline at end of file diff --git a/extensions/AssetsManager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp similarity index 100% rename from extensions/AssetsManager/AssetsManager.cpp rename to extensions/assets-manager/AssetsManager.cpp diff --git a/extensions/AssetsManager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h similarity index 100% rename from extensions/AssetsManager/AssetsManager.h rename to extensions/assets-manager/AssetsManager.h diff --git a/extensions/physics_nodes/CCPhysicsDebugNode.cpp b/extensions/physics-nodes/CCPhysicsDebugNode.cpp similarity index 100% rename from extensions/physics_nodes/CCPhysicsDebugNode.cpp rename to extensions/physics-nodes/CCPhysicsDebugNode.cpp diff --git a/extensions/physics_nodes/CCPhysicsDebugNode.h b/extensions/physics-nodes/CCPhysicsDebugNode.h similarity index 100% rename from extensions/physics_nodes/CCPhysicsDebugNode.h rename to extensions/physics-nodes/CCPhysicsDebugNode.h diff --git a/extensions/physics_nodes/CCPhysicsSprite.cpp b/extensions/physics-nodes/CCPhysicsSprite.cpp similarity index 100% rename from extensions/physics_nodes/CCPhysicsSprite.cpp rename to extensions/physics-nodes/CCPhysicsSprite.cpp diff --git a/extensions/physics_nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h similarity index 100% rename from extensions/physics_nodes/CCPhysicsSprite.h rename to extensions/physics-nodes/CCPhysicsSprite.h From 1f38636e84bde6407d9b6e2deeacac1ec6ebe2ea Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 14:02:13 +0800 Subject: [PATCH 119/557] issue #2905: step1 Box2D -> box2d --- cocos/physics/Box2D/CCPhysicsBodyInfo.cpp | 39 - cocos/physics/Box2D/CCPhysicsBodyInfo.h | 43 - cocos/physics/Box2D/CCPhysicsContactInfo.cpp | 39 - cocos/physics/Box2D/CCPhysicsContactInfo.h | 43 - cocos/physics/Box2D/CCPhysicsHelper.h | 43 - cocos/physics/Box2D/CCPhysicsJointInfo.cpp | 39 - cocos/physics/Box2D/CCPhysicsJointInfo.h | 43 - cocos/physics/Box2D/CCPhysicsShapeInfo.cpp | 39 - cocos/physics/Box2D/CCPhysicsShapeInfo.h | 43 - cocos/physics/Box2D/CCPhysicsWorldInfo.cpp | 39 - cocos/physics/Box2D/CCPhysicsWorldInfo.h | 43 - external/Box2D/Android.mk | 60 - external/Box2D/Box2D.h | 67 - .../Box2D/Collision/Shapes/b2ChainShape.cpp | 171 --- .../Box2D/Collision/Shapes/b2ChainShape.h | 102 -- .../Box2D/Collision/Shapes/b2CircleShape.cpp | 100 -- .../Box2D/Collision/Shapes/b2CircleShape.h | 91 -- .../Box2D/Collision/Shapes/b2EdgeShape.cpp | 139 -- external/Box2D/Collision/Shapes/b2EdgeShape.h | 74 - .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 361 ----- .../Box2D/Collision/Shapes/b2PolygonShape.h | 95 -- external/Box2D/Collision/Shapes/b2Shape.h | 101 -- external/Box2D/Collision/b2BroadPhase.cpp | 122 -- external/Box2D/Collision/b2BroadPhase.h | 248 ---- external/Box2D/Collision/b2CollideCircle.cpp | 154 -- external/Box2D/Collision/b2CollideEdge.cpp | 698 --------- external/Box2D/Collision/b2CollidePolygon.cpp | 317 ---- external/Box2D/Collision/b2Collision.cpp | 249 ---- external/Box2D/Collision/b2Collision.h | 276 ---- external/Box2D/Collision/b2Distance.cpp | 603 -------- external/Box2D/Collision/b2Distance.h | 141 -- external/Box2D/Collision/b2DynamicTree.cpp | 775 ---------- external/Box2D/Collision/b2DynamicTree.h | 284 ---- external/Box2D/Collision/b2TimeOfImpact.cpp | 488 ------ external/Box2D/Collision/b2TimeOfImpact.h | 58 - external/Box2D/Common/b2BlockAllocator.cpp | 218 --- external/Box2D/Common/b2BlockAllocator.h | 62 - external/Box2D/Common/b2Draw.cpp | 44 - external/Box2D/Common/b2Draw.h | 81 - external/Box2D/Common/b2GrowableStack.h | 85 -- external/Box2D/Common/b2Math.cpp | 94 -- external/Box2D/Common/b2Math.h | 738 --------- external/Box2D/Common/b2Settings.cpp | 61 - external/Box2D/Common/b2Settings.h | 150 -- external/Box2D/Common/b2StackAllocator.cpp | 83 -- external/Box2D/Common/b2StackAllocator.h | 60 - external/Box2D/Common/b2Timer.cpp | 100 -- external/Box2D/Common/b2Timer.h | 45 - .../Contacts/b2ChainAndCircleContact.cpp | 54 - .../Contacts/b2ChainAndCircleContact.h | 39 - .../Contacts/b2ChainAndPolygonContact.cpp | 54 - .../Contacts/b2ChainAndPolygonContact.h | 39 - .../Dynamics/Contacts/b2CircleContact.cpp | 53 - .../Box2D/Dynamics/Contacts/b2CircleContact.h | 39 - .../Box2D/Dynamics/Contacts/b2Contact.cpp | 240 --- external/Box2D/Dynamics/Contacts/b2Contact.h | 331 ----- .../Dynamics/Contacts/b2ContactSolver.cpp | 832 ----------- .../Box2D/Dynamics/Contacts/b2ContactSolver.h | 94 -- .../Contacts/b2EdgeAndCircleContact.cpp | 50 - .../Contacts/b2EdgeAndCircleContact.h | 39 - .../Contacts/b2EdgeAndPolygonContact.cpp | 50 - .../Contacts/b2EdgeAndPolygonContact.h | 39 - .../Contacts/b2PolygonAndCircleContact.cpp | 50 - .../Contacts/b2PolygonAndCircleContact.h | 38 - .../Dynamics/Contacts/b2PolygonContact.cpp | 53 - .../Dynamics/Contacts/b2PolygonContact.h | 39 - .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 260 ---- .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 169 --- .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 251 ---- .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 119 -- .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 423 ------ external/Box2D/Dynamics/Joints/b2GearJoint.h | 125 -- external/Box2D/Dynamics/Joints/b2Joint.cpp | 199 --- external/Box2D/Dynamics/Joints/b2Joint.h | 222 --- .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 217 --- external/Box2D/Dynamics/Joints/b2MouseJoint.h | 126 -- .../Dynamics/Joints/b2PrismaticJoint.cpp | 637 -------- .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 196 --- .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 332 ----- .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 143 -- .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 504 ------- .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 204 --- .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 241 --- external/Box2D/Dynamics/Joints/b2RopeJoint.h | 114 -- .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 330 ----- external/Box2D/Dynamics/Joints/b2WeldJoint.h | 126 -- .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 419 ------ external/Box2D/Dynamics/Joints/b2WheelJoint.h | 213 --- external/Box2D/Dynamics/b2Body.cpp | 514 ------- external/Box2D/Dynamics/b2Body.h | 846 ----------- external/Box2D/Dynamics/b2ContactManager.cpp | 293 ---- external/Box2D/Dynamics/b2ContactManager.h | 52 - external/Box2D/Dynamics/b2Fixture.cpp | 303 ---- external/Box2D/Dynamics/b2Fixture.h | 345 ----- external/Box2D/Dynamics/b2Island.cpp | 539 ------- external/Box2D/Dynamics/b2Island.h | 93 -- external/Box2D/Dynamics/b2TimeStep.h | 70 - external/Box2D/Dynamics/b2World.cpp | 1316 ----------------- external/Box2D/Dynamics/b2World.h | 349 ----- external/Box2D/Dynamics/b2WorldCallbacks.cpp | 36 - external/Box2D/Dynamics/b2WorldCallbacks.h | 155 -- external/Box2D/Rope/b2Rope.cpp | 259 ---- external/Box2D/Rope/b2Rope.h | 115 -- external/Box2D/proj.linux/.cproject | 267 ---- external/Box2D/proj.linux/.project | 110 -- external/Box2D/proj.linux/Makefile | 72 - external/Box2D/proj.linux/box2d.prf | 19 - external/Box2D/proj.win32/Box2D.vcxproj | 194 --- .../Box2D/proj.win32/Box2D.vcxproj.filters | 301 ---- external/Box2D/proj.win32/Box2D.vcxproj.user | 3 - 110 files changed, 22002 deletions(-) delete mode 100644 cocos/physics/Box2D/CCPhysicsBodyInfo.cpp delete mode 100644 cocos/physics/Box2D/CCPhysicsBodyInfo.h delete mode 100644 cocos/physics/Box2D/CCPhysicsContactInfo.cpp delete mode 100644 cocos/physics/Box2D/CCPhysicsContactInfo.h delete mode 100644 cocos/physics/Box2D/CCPhysicsHelper.h delete mode 100644 cocos/physics/Box2D/CCPhysicsJointInfo.cpp delete mode 100644 cocos/physics/Box2D/CCPhysicsJointInfo.h delete mode 100644 cocos/physics/Box2D/CCPhysicsShapeInfo.cpp delete mode 100644 cocos/physics/Box2D/CCPhysicsShapeInfo.h delete mode 100644 cocos/physics/Box2D/CCPhysicsWorldInfo.cpp delete mode 100644 cocos/physics/Box2D/CCPhysicsWorldInfo.h delete mode 100644 external/Box2D/Android.mk delete mode 100644 external/Box2D/Box2D.h delete mode 100644 external/Box2D/Collision/Shapes/b2ChainShape.cpp delete mode 100644 external/Box2D/Collision/Shapes/b2ChainShape.h delete mode 100644 external/Box2D/Collision/Shapes/b2CircleShape.cpp delete mode 100644 external/Box2D/Collision/Shapes/b2CircleShape.h delete mode 100644 external/Box2D/Collision/Shapes/b2EdgeShape.cpp delete mode 100644 external/Box2D/Collision/Shapes/b2EdgeShape.h delete mode 100644 external/Box2D/Collision/Shapes/b2PolygonShape.cpp delete mode 100644 external/Box2D/Collision/Shapes/b2PolygonShape.h delete mode 100644 external/Box2D/Collision/Shapes/b2Shape.h delete mode 100644 external/Box2D/Collision/b2BroadPhase.cpp delete mode 100644 external/Box2D/Collision/b2BroadPhase.h delete mode 100644 external/Box2D/Collision/b2CollideCircle.cpp delete mode 100644 external/Box2D/Collision/b2CollideEdge.cpp delete mode 100644 external/Box2D/Collision/b2CollidePolygon.cpp delete mode 100644 external/Box2D/Collision/b2Collision.cpp delete mode 100644 external/Box2D/Collision/b2Collision.h delete mode 100644 external/Box2D/Collision/b2Distance.cpp delete mode 100644 external/Box2D/Collision/b2Distance.h delete mode 100644 external/Box2D/Collision/b2DynamicTree.cpp delete mode 100644 external/Box2D/Collision/b2DynamicTree.h delete mode 100644 external/Box2D/Collision/b2TimeOfImpact.cpp delete mode 100644 external/Box2D/Collision/b2TimeOfImpact.h delete mode 100644 external/Box2D/Common/b2BlockAllocator.cpp delete mode 100644 external/Box2D/Common/b2BlockAllocator.h delete mode 100644 external/Box2D/Common/b2Draw.cpp delete mode 100644 external/Box2D/Common/b2Draw.h delete mode 100644 external/Box2D/Common/b2GrowableStack.h delete mode 100644 external/Box2D/Common/b2Math.cpp delete mode 100644 external/Box2D/Common/b2Math.h delete mode 100644 external/Box2D/Common/b2Settings.cpp delete mode 100644 external/Box2D/Common/b2Settings.h delete mode 100644 external/Box2D/Common/b2StackAllocator.cpp delete mode 100644 external/Box2D/Common/b2StackAllocator.h delete mode 100644 external/Box2D/Common/b2Timer.cpp delete mode 100644 external/Box2D/Common/b2Timer.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2CircleContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2CircleContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2Contact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2Contact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2ContactSolver.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h delete mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp delete mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonContact.h delete mode 100644 external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2DistanceJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2FrictionJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2GearJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2GearJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2Joint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2Joint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2MouseJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2MouseJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2PrismaticJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2PulleyJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2RevoluteJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2RopeJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2RopeJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2WeldJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2WeldJoint.h delete mode 100644 external/Box2D/Dynamics/Joints/b2WheelJoint.cpp delete mode 100644 external/Box2D/Dynamics/Joints/b2WheelJoint.h delete mode 100644 external/Box2D/Dynamics/b2Body.cpp delete mode 100644 external/Box2D/Dynamics/b2Body.h delete mode 100644 external/Box2D/Dynamics/b2ContactManager.cpp delete mode 100644 external/Box2D/Dynamics/b2ContactManager.h delete mode 100644 external/Box2D/Dynamics/b2Fixture.cpp delete mode 100644 external/Box2D/Dynamics/b2Fixture.h delete mode 100644 external/Box2D/Dynamics/b2Island.cpp delete mode 100644 external/Box2D/Dynamics/b2Island.h delete mode 100644 external/Box2D/Dynamics/b2TimeStep.h delete mode 100644 external/Box2D/Dynamics/b2World.cpp delete mode 100644 external/Box2D/Dynamics/b2World.h delete mode 100644 external/Box2D/Dynamics/b2WorldCallbacks.cpp delete mode 100644 external/Box2D/Dynamics/b2WorldCallbacks.h delete mode 100644 external/Box2D/Rope/b2Rope.cpp delete mode 100644 external/Box2D/Rope/b2Rope.h delete mode 100644 external/Box2D/proj.linux/.cproject delete mode 100644 external/Box2D/proj.linux/.project delete mode 100644 external/Box2D/proj.linux/Makefile delete mode 100644 external/Box2D/proj.linux/box2d.prf delete mode 100644 external/Box2D/proj.win32/Box2D.vcxproj delete mode 100644 external/Box2D/proj.win32/Box2D.vcxproj.filters delete mode 100644 external/Box2D/proj.win32/Box2D.vcxproj.user diff --git a/cocos/physics/Box2D/CCPhysicsBodyInfo.cpp b/cocos/physics/Box2D/CCPhysicsBodyInfo.cpp deleted file mode 100644 index bfa20b616a..0000000000 --- a/cocos/physics/Box2D/CCPhysicsBodyInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsBodyInfo.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsBodyInfo::PhysicsBodyInfo() -{ -} - -PhysicsBodyInfo::~PhysicsBodyInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsBodyInfo.h b/cocos/physics/Box2D/CCPhysicsBodyInfo.h deleted file mode 100644 index 730837ed9d..0000000000 --- a/cocos/physics/Box2D/CCPhysicsBodyInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ -#include "platform/CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsBodyInfo -{ -public: - PhysicsBodyInfo(); - ~PhysicsBodyInfo(); -}; - -NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsContactInfo.cpp b/cocos/physics/Box2D/CCPhysicsContactInfo.cpp deleted file mode 100644 index 41eaa4f831..0000000000 --- a/cocos/physics/Box2D/CCPhysicsContactInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsContactInfo.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsContactInfo::PhysicsContactInfo() -{ -} - -PhysicsContactInfo::~PhysicsContactInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsContactInfo.h b/cocos/physics/Box2D/CCPhysicsContactInfo.h deleted file mode 100644 index b592caa0af..0000000000 --- a/cocos/physics/Box2D/CCPhysicsContactInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ -#include "platform/CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsContactInfo -{ -public: - PhysicsContactInfo(); - ~PhysicsContactInfo(); -}; - -NS_CC_END -#endif // __CCPHYSICS_CONTACT_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsHelper.h b/cocos/physics/Box2D/CCPhysicsHelper.h deleted file mode 100644 index 86ef7d74ee..0000000000 --- a/cocos/physics/Box2D/CCPhysicsHelper.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsHelper -{ -}; - -NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsJointInfo.cpp b/cocos/physics/Box2D/CCPhysicsJointInfo.cpp deleted file mode 100644 index 753ba41534..0000000000 --- a/cocos/physics/Box2D/CCPhysicsJointInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsJointInfo.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsJointInfo::PhysicsJointInfo() -{ -} - -PhysicsJointInfo::~PhysicsJointInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsJointInfo.h b/cocos/physics/Box2D/CCPhysicsJointInfo.h deleted file mode 100644 index abcf089387..0000000000 --- a/cocos/physics/Box2D/CCPhysicsJointInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ -#include "platform/CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsJointInfo -{ -public: - PhysicsJointInfo(); - ~PhysicsJointInfo(); -}; - -NS_CC_END -#endif // __CCPHYSICS_JOINT_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsShapeInfo.cpp b/cocos/physics/Box2D/CCPhysicsShapeInfo.cpp deleted file mode 100644 index a89ba7dae7..0000000000 --- a/cocos/physics/Box2D/CCPhysicsShapeInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsShapeInfo.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsShapeInfo::PhysicsShapeInfo() -{ -} - -PhysicsShapeInfo::~PhysicsShapeInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsShapeInfo.h b/cocos/physics/Box2D/CCPhysicsShapeInfo.h deleted file mode 100644 index 9091001887..0000000000 --- a/cocos/physics/Box2D/CCPhysicsShapeInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ -#include "platform/CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsShapeInfo -{ -public: - PhysicsShapeInfo(); - ~PhysicsShapeInfo(); -}; - -NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsWorldInfo.cpp b/cocos/physics/Box2D/CCPhysicsWorldInfo.cpp deleted file mode 100644 index 0de6c00d82..0000000000 --- a/cocos/physics/Box2D/CCPhysicsWorldInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsWorldInfo.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsWorldInfo::PhysicsWorldInfo() -{ -} - -PhysicsWorldInfo::~PhysicsWorldInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/Box2D/CCPhysicsWorldInfo.h b/cocos/physics/Box2D/CCPhysicsWorldInfo.h deleted file mode 100644 index bcc09124db..0000000000 --- a/cocos/physics/Box2D/CCPhysicsWorldInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ -#include "platform/CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsWorldInfo -{ -public: - PhysicsWorldInfo(); - ~PhysicsWorldInfo(); -}; - -NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/external/Box2D/Android.mk b/external/Box2D/Android.mk deleted file mode 100644 index c366750c01..0000000000 --- a/external/Box2D/Android.mk +++ /dev/null @@ -1,60 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := box2d_static - -LOCAL_MODULE_FILENAME := libbox2d - -LOCAL_SRC_FILES := \ -Collision/b2BroadPhase.cpp \ -Collision/b2CollideCircle.cpp \ -Collision/b2CollideEdge.cpp \ -Collision/b2CollidePolygon.cpp \ -Collision/b2Collision.cpp \ -Collision/b2Distance.cpp \ -Collision/b2DynamicTree.cpp \ -Collision/b2TimeOfImpact.cpp \ -Collision/Shapes/b2ChainShape.cpp \ -Collision/Shapes/b2CircleShape.cpp \ -Collision/Shapes/b2EdgeShape.cpp \ -Collision/Shapes/b2PolygonShape.cpp \ -Common/b2BlockAllocator.cpp \ -Common/b2Draw.cpp \ -Common/b2Math.cpp \ -Common/b2Settings.cpp \ -Common/b2StackAllocator.cpp \ -Common/b2Timer.cpp \ -Dynamics/b2Body.cpp \ -Dynamics/b2ContactManager.cpp \ -Dynamics/b2Fixture.cpp \ -Dynamics/b2Island.cpp \ -Dynamics/b2World.cpp \ -Dynamics/b2WorldCallbacks.cpp \ -Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -Dynamics/Contacts/b2CircleContact.cpp \ -Dynamics/Contacts/b2Contact.cpp \ -Dynamics/Contacts/b2ContactSolver.cpp \ -Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -Dynamics/Contacts/b2PolygonContact.cpp \ -Dynamics/Joints/b2DistanceJoint.cpp \ -Dynamics/Joints/b2FrictionJoint.cpp \ -Dynamics/Joints/b2GearJoint.cpp \ -Dynamics/Joints/b2Joint.cpp \ -Dynamics/Joints/b2MouseJoint.cpp \ -Dynamics/Joints/b2PrismaticJoint.cpp \ -Dynamics/Joints/b2PulleyJoint.cpp \ -Dynamics/Joints/b2RevoluteJoint.cpp \ -Dynamics/Joints/b2RopeJoint.cpp \ -Dynamics/Joints/b2WeldJoint.cpp \ -Dynamics/Joints/b2WheelJoint.cpp \ -Rope/b2Rope.cpp - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. - -include $(BUILD_STATIC_LIBRARY) diff --git a/external/Box2D/Box2D.h b/external/Box2D/Box2D.h deleted file mode 100644 index f674d82269..0000000000 --- a/external/Box2D/Box2D.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BOX2D_H -#define BOX2D_H - -/** -\mainpage Box2D API Documentation - -\section intro_sec Getting Started - -For documentation please see http://box2d.org/documentation.html - -For discussion please visit http://box2d.org/forum -*/ - -// These include files constitute the main Box2D API - -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.cpp b/external/Box2D/Collision/Shapes/b2ChainShape.cpp deleted file mode 100644 index 79b4304b5b..0000000000 --- a/external/Box2D/Collision/Shapes/b2ChainShape.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -using namespace std; - -b2ChainShape::~b2ChainShape() -{ - b2Free(m_vertices); - m_vertices = NULL; - m_count = 0; -} - -void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 3); - m_count = count + 1; - m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); - m_vertices[count] = m_vertices[0]; - m_prevVertex = m_vertices[m_count - 2]; - m_nextVertex = m_vertices[1]; - m_hasPrevVertex = true; - m_hasNextVertex = true; -} - -void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 2); - m_count = count; - m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); - m_hasPrevVertex = false; - m_hasNextVertex = false; -} - -void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) -{ - m_prevVertex = prevVertex; - m_hasPrevVertex = true; -} - -void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) -{ - m_nextVertex = nextVertex; - m_hasNextVertex = true; -} - -b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2ChainShape)); - b2ChainShape* clone = new (mem) b2ChainShape; - clone->CreateChain(m_vertices, m_count); - clone->m_prevVertex = m_prevVertex; - clone->m_nextVertex = m_nextVertex; - clone->m_hasPrevVertex = m_hasPrevVertex; - clone->m_hasNextVertex = m_hasNextVertex; - return clone; -} - -int32 b2ChainShape::GetChildCount() const -{ - // edge count = vertex count - 1 - return m_count - 1; -} - -void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const -{ - b2Assert(0 <= index && index < m_count - 1); - edge->m_type = b2Shape::e_edge; - edge->m_radius = m_radius; - - edge->m_vertex1 = m_vertices[index + 0]; - edge->m_vertex2 = m_vertices[index + 1]; - - if (index > 0) - { - edge->m_vertex0 = m_vertices[index - 1]; - edge->m_hasVertex0 = true; - } - else - { - edge->m_vertex0 = m_prevVertex; - edge->m_hasVertex0 = m_hasPrevVertex; - } - - if (index < m_count - 2) - { - edge->m_vertex3 = m_vertices[index + 2]; - edge->m_hasVertex3 = true; - } - else - { - edge->m_vertex3 = m_nextVertex; - edge->m_hasVertex3 = m_hasNextVertex; - } -} - -bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - b2EdgeShape edgeShape; - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - edgeShape.m_vertex1 = m_vertices[i1]; - edgeShape.m_vertex2 = m_vertices[i2]; - - return edgeShape.RayCast(output, input, xf, 0); -} - -void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); - b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); - - aabb->lowerBound = b2Min(v1, v2); - aabb->upperBound = b2Max(v1, v2); -} - -void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center.SetZero(); - massData->I = 0.0f; -} diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.h b/external/Box2D/Collision/Shapes/b2ChainShape.h deleted file mode 100644 index 9c9a9eaa7d..0000000000 --- a/external/Box2D/Collision/Shapes/b2ChainShape.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_SHAPE_H -#define B2_CHAIN_SHAPE_H - -#include - -class b2EdgeShape; - -/// A chain shape is a free form sequence of line segments. -/// The chain has two-sided collision, so you can use inside and outside collision. -/// Therefore, you may use any winding order. -/// Since there may be many vertices, they are allocated using b2Alloc. -/// Connectivity information is used to create smooth collisions. -/// WARNING: The chain will not collide properly if there are self-intersections. -class b2ChainShape : public b2Shape -{ -public: - b2ChainShape(); - - /// The destructor frees the vertices using b2Free. - ~b2ChainShape(); - - /// Create a loop. This automatically adjusts connectivity. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateLoop(const b2Vec2* vertices, int32 count); - - /// Create a chain with isolated end vertices. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateChain(const b2Vec2* vertices, int32 count); - - /// Establish connectivity to a vertex that precedes the first vertex. - /// Don't call this for loops. - void SetPrevVertex(const b2Vec2& prevVertex); - - /// Establish connectivity to a vertex that follows the last vertex. - /// Don't call this for loops. - void SetNextVertex(const b2Vec2& nextVertex); - - /// Implement b2Shape. Vertices are cloned using b2Alloc. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Get a child edge. - void GetChildEdge(b2EdgeShape* edge, int32 index) const; - - /// This always return false. - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// Chains have zero mass. - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// The vertices. Owned by this class. - b2Vec2* m_vertices; - - /// The vertex count. - int32 m_count; - - b2Vec2 m_prevVertex, m_nextVertex; - bool m_hasPrevVertex, m_hasNextVertex; -}; - -inline b2ChainShape::b2ChainShape() -{ - m_type = e_chain; - m_radius = b2_polygonRadius; - m_vertices = NULL; - m_count = 0; - m_hasPrevVertex = false; - m_hasNextVertex = false; -} - -#endif diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.cpp b/external/Box2D/Collision/Shapes/b2CircleShape.cpp deleted file mode 100644 index 587ca960b2..0000000000 --- a/external/Box2D/Collision/Shapes/b2CircleShape.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2CircleShape)); - b2CircleShape* clone = new (mem) b2CircleShape; - *clone = *this; - return clone; -} - -int32 b2CircleShape::GetChildCount() const -{ - return 1; -} - -bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const -{ - b2Vec2 center = transform.p + b2Mul(transform.q, m_p); - b2Vec2 d = p - center; - return b2Dot(d, d) <= m_radius * m_radius; -} - -// Collision Detection in Interactive 3D Environments by Gino van den Bergen -// From Section 3.1.2 -// x = s + a * r -// norm(x) = radius -bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 position = transform.p + b2Mul(transform.q, m_p); - b2Vec2 s = input.p1 - position; - float32 b = b2Dot(s, s) - m_radius * m_radius; - - // Solve quadratic equation. - b2Vec2 r = input.p2 - input.p1; - float32 c = b2Dot(s, r); - float32 rr = b2Dot(r, r); - float32 sigma = c * c - rr * b; - - // Check for negative discriminant and short segment. - if (sigma < 0.0f || rr < b2_epsilon) - { - return false; - } - - // Find the point of intersection of the line with the circle. - float32 a = -(c + b2Sqrt(sigma)); - - // Is the intersection point on the segment? - if (0.0f <= a && a <= input.maxFraction * rr) - { - a /= rr; - output->fraction = a; - output->normal = s + a * r; - output->normal.Normalize(); - return true; - } - - return false; -} - -void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 p = transform.p + b2Mul(transform.q, m_p); - aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); - aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); -} - -void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const -{ - massData->mass = density * b2_pi * m_radius * m_radius; - massData->center = m_p; - - // inertia about the local origin - massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); -} diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.h b/external/Box2D/Collision/Shapes/b2CircleShape.h deleted file mode 100644 index c4e23a475b..0000000000 --- a/external/Box2D/Collision/Shapes/b2CircleShape.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CIRCLE_SHAPE_H -#define B2_CIRCLE_SHAPE_H - -#include - -/// A circle shape. -class b2CircleShape : public b2Shape -{ -public: - b2CircleShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Implement b2Shape. - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - - /// Get the vertex count. - int32 GetVertexCount() const { return 1; } - - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; - - /// Position - b2Vec2 m_p; -}; - -inline b2CircleShape::b2CircleShape() -{ - m_type = e_circle; - m_radius = 0.0f; - m_p.SetZero(); -} - -inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const -{ - B2_NOT_USED(d); - return 0; -} - -inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const -{ - B2_NOT_USED(d); - return m_p; -} - -inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const -{ - B2_NOT_USED(index); - b2Assert(index == 0); - return m_p; -} - -#endif diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.cpp b/external/Box2D/Collision/Shapes/b2EdgeShape.cpp deleted file mode 100644 index 7b09e55bf4..0000000000 --- a/external/Box2D/Collision/Shapes/b2EdgeShape.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) -{ - m_vertex1 = v1; - m_vertex2 = v2; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2EdgeShape)); - b2EdgeShape* clone = new (mem) b2EdgeShape; - *clone = *this; - return clone; -} - -int32 b2EdgeShape::GetChildCount() const -{ - return 1; -} - -bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -// p = p1 + t * d -// v = v1 + s * e -// p1 + t * d = v1 + s * e -// s * e - t * d = p1 - v1 -bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the edge's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - b2Vec2 v1 = m_vertex1; - b2Vec2 v2 = m_vertex2; - b2Vec2 e = v2 - v1; - b2Vec2 normal(e.y, -e.x); - normal.Normalize(); - - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float32 numerator = b2Dot(normal, v1 - p1); - float32 denominator = b2Dot(normal, d); - - if (denominator == 0.0f) - { - return false; - } - - float32 t = numerator / denominator; - if (t < 0.0f || input.maxFraction < t) - { - return false; - } - - b2Vec2 q = p1 + t * d; - - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - b2Vec2 r = v2 - v1; - float32 rr = b2Dot(r, r); - if (rr == 0.0f) - { - return false; - } - - float32 s = b2Dot(q - v1, r) / rr; - if (s < 0.0f || 1.0f < s) - { - return false; - } - - output->fraction = t; - if (numerator > 0.0f) - { - output->normal = -normal; - } - else - { - output->normal = normal; - } - return true; -} - -void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 v1 = b2Mul(xf, m_vertex1); - b2Vec2 v2 = b2Mul(xf, m_vertex2); - - b2Vec2 lower = b2Min(v1, v2); - b2Vec2 upper = b2Max(v1, v2); - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center = 0.5f * (m_vertex1 + m_vertex2); - massData->I = 0.0f; -} diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.h b/external/Box2D/Collision/Shapes/b2EdgeShape.h deleted file mode 100644 index 6163bcbf1c..0000000000 --- a/external/Box2D/Collision/Shapes/b2EdgeShape.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_SHAPE_H -#define B2_EDGE_SHAPE_H - -#include - -/// A line segment (edge) shape. These can be connected in chains or loops -/// to other edge shapes. The connectivity information is used to ensure -/// correct contact normals. -class b2EdgeShape : public b2Shape -{ -public: - b2EdgeShape(); - - /// Set this as an isolated edge. - void Set(const b2Vec2& v1, const b2Vec2& v2); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// These are the edge vertices - b2Vec2 m_vertex1, m_vertex2; - - /// Optional adjacent vertices. These are used for smooth collision. - b2Vec2 m_vertex0, m_vertex3; - bool m_hasVertex0, m_hasVertex3; -}; - -inline b2EdgeShape::b2EdgeShape() -{ - m_type = e_edge; - m_radius = b2_polygonRadius; - m_vertex0.x = 0.0f; - m_vertex0.y = 0.0f; - m_vertex3.x = 0.0f; - m_vertex3.y = 0.0f; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -#endif diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.cpp b/external/Box2D/Collision/Shapes/b2PolygonShape.cpp deleted file mode 100644 index c04c1dc49b..0000000000 --- a/external/Box2D/Collision/Shapes/b2PolygonShape.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2PolygonShape)); - b2PolygonShape* clone = new (mem) b2PolygonShape; - *clone = *this; - return clone; -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy) -{ - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid.SetZero(); -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) -{ - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid = center; - - b2Transform xf; - xf.p = center; - xf.q.Set(angle); - - // Transform vertices and normals. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = b2Mul(xf, m_vertices[i]); - m_normals[i] = b2Mul(xf.q, m_normals[i]); - } -} - -int32 b2PolygonShape::GetChildCount() const -{ - return 1; -} - -static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) -{ - b2Assert(count >= 3); - - b2Vec2 c; c.Set(0.0f, 0.0f); - float32 area = 0.0f; - - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < count; ++i) - { - pRef += vs[i]; - } - pRef *= 1.0f / count; -#endif - - const float32 inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < count; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = vs[i]; - b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - c += triangleArea * inv3 * (p1 + p2 + p3); - } - - // Centroid - b2Assert(area > b2_epsilon); - c *= 1.0f / area; - return c; -} - -void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) -{ - b2Assert(3 <= count && count <= b2_maxPolygonVertices); - m_vertexCount = count; - - // Copy vertices. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = vertices[i]; - } - - // Compute normals. Ensure the edges have non-zero length. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); - m_normals[i] = b2Cross(edge, 1.0f); - m_normals[i].Normalize(); - } - -#ifdef _DEBUG - // Ensure the polygon is convex and the interior - // is to the left of each edge. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - - for (int32 j = 0; j < m_vertexCount; ++j) - { - // Don't check vertices on the current edge. - if (j == i1 || j == i2) - { - continue; - } - - b2Vec2 r = m_vertices[j] - m_vertices[i1]; - - // If this crashes, your polygon is non-convex, has colinear edges, - // or the winding order is wrong. - float32 s = b2Cross(edge, r); - b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); - } - } -#endif - - // Compute the polygon centroid. - m_centroid = ComputeCentroid(m_vertices, m_vertexCount); -} - -bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); - - for (int32 i = 0; i < m_vertexCount; ++i) - { - float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); - if (dot > 0.0f) - { - return false; - } - } - - return true; -} - -bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the polygon's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - float32 lower = 0.0f, upper = input.maxFraction; - - int32 index = -1; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); - - if (denominator == 0.0f) - { - if (numerator < 0.0f) - { - return false; - } - } - else - { - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - } - - // The use of epsilon here causes the assert on lower to trip - // in some cases. Apparently the use of epsilon was to make edge - // shapes work, but now those are handled separately. - //if (upper < lower - b2_epsilon) - if (upper < lower) - { - return false; - } - } - - b2Assert(0.0f <= lower && lower <= input.maxFraction); - - if (index >= 0) - { - output->fraction = lower; - output->normal = b2Mul(xf.q, m_normals[index]); - return true; - } - - return false; -} - -void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 lower = b2Mul(xf, m_vertices[0]); - b2Vec2 upper = lower; - - for (int32 i = 1; i < m_vertexCount; ++i) - { - b2Vec2 v = b2Mul(xf, m_vertices[i]); - lower = b2Min(lower, v); - upper = b2Max(upper, v); - } - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const -{ - // Polygon mass, centroid, and inertia. - // Let rho be the polygon density in mass per unit area. - // Then: - // mass = rho * int(dA) - // centroid.x = (1/mass) * rho * int(x * dA) - // centroid.y = (1/mass) * rho * int(y * dA) - // I = rho * int((x*x + y*y) * dA) - // - // We can compute these integrals by summing all the integrals - // for each triangle of the polygon. To evaluate the integral - // for a single triangle, we make a change of variables to - // the (u,v) coordinates of the triangle: - // x = x0 + e1x * u + e2x * v - // y = y0 + e1y * u + e2y * v - // where 0 <= u && 0 <= v && u + v <= 1. - // - // We integrate u from [0,1-v] and then v from [0,1]. - // We also need to use the Jacobian of the transformation: - // D = cross(e1, e2) - // - // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) - // - // The rest of the derivation is handled by computer algebra. - - b2Assert(m_vertexCount >= 3); - - b2Vec2 center; center.Set(0.0f, 0.0f); - float32 area = 0.0f; - float32 I = 0.0f; - - // s is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 s(0.0f, 0.0f); - - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < m_vertexCount; ++i) - { - s += m_vertices[i]; - } - s *= 1.0f / m_vertexCount; - - const float32 k_inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // Triangle vertices. - b2Vec2 e1 = m_vertices[i] - s; - b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - center += triangleArea * k_inv3 * (e1 + e2); - - float32 ex1 = e1.x, ey1 = e1.y; - float32 ex2 = e2.x, ey2 = e2.y; - - float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; - float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; - - I += (0.25f * k_inv3 * D) * (intx2 + inty2); - } - - // Total mass - massData->mass = density * area; - - // Center of mass - b2Assert(area > b2_epsilon); - center *= 1.0f / area; - massData->center = center + s; - - // Inertia tensor relative to the local origin (point s). - massData->I = density * I; - - // Shift to center of mass then to original body origin. - massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); -} diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.h b/external/Box2D/Collision/Shapes/b2PolygonShape.h deleted file mode 100644 index 70daccb2ff..0000000000 --- a/external/Box2D/Collision/Shapes/b2PolygonShape.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_SHAPE_H -#define B2_POLYGON_SHAPE_H - -#include - -/// A convex polygon. It is assumed that the interior of the polygon is to -/// the left of each edge. -/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. -/// In most cases you should not need many vertices for a convex polygon. -class b2PolygonShape : public b2Shape -{ -public: - b2PolygonShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Copy vertices. This assumes the vertices define a convex polygon. - /// It is assumed that the exterior is the the right of each edge. - /// The count must be in the range [3, b2_maxPolygonVertices]. - void Set(const b2Vec2* vertices, int32 vertexCount); - - /// Build vertices to represent an axis-aligned box. - /// @param hx the half-width. - /// @param hy the half-height. - void SetAsBox(float32 hx, float32 hy); - - /// Build vertices to represent an oriented box. - /// @param hx the half-width. - /// @param hy the half-height. - /// @param center the center of the box in local coordinates. - /// @param angle the rotation of the box in local coordinates. - void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// Get the vertex count. - int32 GetVertexCount() const { return m_vertexCount; } - - /// Get a vertex by index. - const b2Vec2& GetVertex(int32 index) const; - - b2Vec2 m_centroid; - b2Vec2 m_vertices[b2_maxPolygonVertices]; - b2Vec2 m_normals[b2_maxPolygonVertices]; - int32 m_vertexCount; -}; - -inline b2PolygonShape::b2PolygonShape() -{ - m_type = e_polygon; - m_radius = b2_polygonRadius; - m_vertexCount = 0; - m_centroid.SetZero(); -} - -inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const -{ - b2Assert(0 <= index && index < m_vertexCount); - return m_vertices[index]; -} - -#endif diff --git a/external/Box2D/Collision/Shapes/b2Shape.h b/external/Box2D/Collision/Shapes/b2Shape.h deleted file mode 100644 index 2e2aedd14a..0000000000 --- a/external/Box2D/Collision/Shapes/b2Shape.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_SHAPE_H -#define B2_SHAPE_H - -#include -#include -#include - -/// This holds the mass data computed for a shape. -struct b2MassData -{ - /// The mass of the shape, usually in kilograms. - float32 mass; - - /// The position of the shape's centroid relative to the shape's origin. - b2Vec2 center; - - /// The rotational inertia of the shape about the local origin. - float32 I; -}; - -/// A shape is used for collision detection. You can create a shape however you like. -/// Shapes used for simulation in b2World are created automatically when a b2Fixture -/// is created. Shapes may encapsulate a one or more child shapes. -class b2Shape -{ -public: - - enum Type - { - e_circle = 0, - e_edge = 1, - e_polygon = 2, - e_chain = 3, - e_typeCount = 4 - }; - - virtual ~b2Shape() {} - - /// Clone the concrete shape using the provided allocator. - virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; - - /// Get the type of this shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - Type GetType() const; - - /// Get the number of child primitives. - virtual int32 GetChildCount() const = 0; - - /// Test a point for containment in this shape. This only works for convex shapes. - /// @param xf the shape world transform. - /// @param p a point in world coordinates. - virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; - - /// Cast a ray against a child shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - /// @param transform the transform to be applied to the shape. - /// @param childIndex the child shape index - virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const = 0; - - /// Given a transform, compute the associated axis aligned bounding box for a child shape. - /// @param aabb returns the axis aligned box. - /// @param xf the world transform of the shape. - /// @param childIndex the child shape - virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; - - /// Compute the mass properties of this shape using its dimensions and density. - /// The inertia tensor is computed about the local origin. - /// @param massData returns the mass data for this shape. - /// @param density the density in kilograms per meter squared. - virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; - - Type m_type; - float32 m_radius; -}; - -inline b2Shape::Type b2Shape::GetType() const -{ - return m_type; -} - -#endif diff --git a/external/Box2D/Collision/b2BroadPhase.cpp b/external/Box2D/Collision/b2BroadPhase.cpp deleted file mode 100644 index 431f6de1ee..0000000000 --- a/external/Box2D/Collision/b2BroadPhase.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -b2BroadPhase::b2BroadPhase() -{ - m_proxyCount = 0; - - m_pairCapacity = 16; - m_pairCount = 0; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - - m_moveCapacity = 16; - m_moveCount = 0; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); -} - -b2BroadPhase::~b2BroadPhase() -{ - b2Free(m_moveBuffer); - b2Free(m_pairBuffer); -} - -int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = m_tree.CreateProxy(aabb, userData); - ++m_proxyCount; - BufferMove(proxyId); - return proxyId; -} - -void b2BroadPhase::DestroyProxy(int32 proxyId) -{ - UnBufferMove(proxyId); - --m_proxyCount; - m_tree.DestroyProxy(proxyId); -} - -void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); - if (buffer) - { - BufferMove(proxyId); - } -} - -void b2BroadPhase::TouchProxy(int32 proxyId) -{ - BufferMove(proxyId); -} - -void b2BroadPhase::BufferMove(int32 proxyId) -{ - if (m_moveCount == m_moveCapacity) - { - int32* oldBuffer = m_moveBuffer; - m_moveCapacity *= 2; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); - memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); - b2Free(oldBuffer); - } - - m_moveBuffer[m_moveCount] = proxyId; - ++m_moveCount; -} - -void b2BroadPhase::UnBufferMove(int32 proxyId) -{ - for (int32 i = 0; i < m_moveCount; ++i) - { - if (m_moveBuffer[i] == proxyId) - { - m_moveBuffer[i] = e_nullProxy; - return; - } - } -} - -// This is called from b2DynamicTree::Query when we are gathering pairs. -bool b2BroadPhase::QueryCallback(int32 proxyId) -{ - // A proxy cannot form a pair with itself. - if (proxyId == m_queryProxyId) - { - return true; - } - - // Grow the pair buffer as needed. - if (m_pairCount == m_pairCapacity) - { - b2Pair* oldBuffer = m_pairBuffer; - m_pairCapacity *= 2; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); - b2Free(oldBuffer); - } - - m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); - m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); - ++m_pairCount; - - return true; -} diff --git a/external/Box2D/Collision/b2BroadPhase.h b/external/Box2D/Collision/b2BroadPhase.h deleted file mode 100644 index cf2414730a..0000000000 --- a/external/Box2D/Collision/b2BroadPhase.h +++ /dev/null @@ -1,248 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BROAD_PHASE_H -#define B2_BROAD_PHASE_H - -#include -#include -#include -#include - -struct b2Pair -{ - int32 proxyIdA; - int32 proxyIdB; - int32 next; -}; - -/// The broad-phase is used for computing pairs and performing volume queries and ray casts. -/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. -/// It is up to the client to consume the new pairs and to track subsequent overlap. -class b2BroadPhase -{ -public: - - enum - { - e_nullProxy = -1 - }; - - b2BroadPhase(); - ~b2BroadPhase(); - - /// Create a proxy with an initial AABB. Pairs are not reported until - /// UpdatePairs is called. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. It is up to the client to remove any pairs. - void DestroyProxy(int32 proxyId); - - /// Call MoveProxy as many times as you like, then when you are done - /// call UpdatePairs to finalized the proxy pairs (for your time step). - void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); - - /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. - void TouchProxy(int32 proxyId); - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Get user data from a proxy. Returns NULL if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Test overlap of fat AABBs. - bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; - - /// Get the number of proxies. - int32 GetProxyCount() const; - - /// Update the pairs. This results in pair callbacks. This can only add pairs. - template - void UpdatePairs(T* callback); - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Get the height of the embedded tree. - int32 GetTreeHeight() const; - - /// Get the balance of the embedded tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the embedded tree. - float32 GetTreeQuality() const; - -private: - - friend class b2DynamicTree; - - void BufferMove(int32 proxyId); - void UnBufferMove(int32 proxyId); - - bool QueryCallback(int32 proxyId); - - b2DynamicTree m_tree; - - int32 m_proxyCount; - - int32* m_moveBuffer; - int32 m_moveCapacity; - int32 m_moveCount; - - b2Pair* m_pairBuffer; - int32 m_pairCapacity; - int32 m_pairCount; - - int32 m_queryProxyId; -}; - -/// This is used to sort pairs. -inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) -{ - if (pair1.proxyIdA < pair2.proxyIdA) - { - return true; - } - - if (pair1.proxyIdA == pair2.proxyIdA) - { - return pair1.proxyIdB < pair2.proxyIdB; - } - - return false; -} - -inline void* b2BroadPhase::GetUserData(int32 proxyId) const -{ - return m_tree.GetUserData(proxyId); -} - -inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const -{ - const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); - const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); - return b2TestOverlap(aabbA, aabbB); -} - -inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const -{ - return m_tree.GetFatAABB(proxyId); -} - -inline int32 b2BroadPhase::GetProxyCount() const -{ - return m_proxyCount; -} - -inline int32 b2BroadPhase::GetTreeHeight() const -{ - return m_tree.GetHeight(); -} - -inline int32 b2BroadPhase::GetTreeBalance() const -{ - return m_tree.GetMaxBalance(); -} - -inline float32 b2BroadPhase::GetTreeQuality() const -{ - return m_tree.GetAreaRatio(); -} - -template -void b2BroadPhase::UpdatePairs(T* callback) -{ - // Reset pair buffer - m_pairCount = 0; - - // Perform tree queries for all moving proxies. - for (int32 i = 0; i < m_moveCount; ++i) - { - m_queryProxyId = m_moveBuffer[i]; - if (m_queryProxyId == e_nullProxy) - { - continue; - } - - // We have to query the tree with the fat AABB so that - // we don't fail to create a pair that may touch later. - const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); - - // Query tree, create pairs and add them pair buffer. - m_tree.Query(this, fatAABB); - } - - // Reset move buffer - m_moveCount = 0; - - // Sort the pair buffer to expose duplicates. - std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); - - // Send the pairs back to the client. - int32 i = 0; - while (i < m_pairCount) - { - b2Pair* primaryPair = m_pairBuffer + i; - void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); - void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); - - callback->AddPair(userDataA, userDataB); - ++i; - - // Skip any duplicate pairs. - while (i < m_pairCount) - { - b2Pair* pair = m_pairBuffer + i; - if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) - { - break; - } - ++i; - } - } - - // Try to keep the tree balanced. - //m_tree.Rebalance(4); -} - -template -inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const -{ - m_tree.Query(callback, aabb); -} - -template -inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const -{ - m_tree.RayCast(callback, input); -} - -#endif diff --git a/external/Box2D/Collision/b2CollideCircle.cpp b/external/Box2D/Collision/b2CollideCircle.cpp deleted file mode 100644 index ed561eb04b..0000000000 --- a/external/Box2D/Collision/b2CollideCircle.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -void b2CollideCircles( - b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - b2Vec2 pA = b2Mul(xfA, circleA->m_p); - b2Vec2 pB = b2Mul(xfB, circleB->m_p); - - b2Vec2 d = pB - pA; - float32 distSqr = b2Dot(d, d); - float32 rA = circleA->m_radius, rB = circleB->m_radius; - float32 radius = rA + rB; - if (distSqr > radius * radius) - { - return; - } - - manifold->type = b2Manifold::e_circles; - manifold->localPoint = circleA->m_p; - manifold->localNormal.SetZero(); - manifold->pointCount = 1; - - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; -} - -void b2CollidePolygonAndCircle( - b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle position in the frame of the polygon. - b2Vec2 c = b2Mul(xfB, circleB->m_p); - b2Vec2 cLocal = b2MulT(xfA, c); - - // Find the min separating edge. - int32 normalIndex = 0; - float32 separation = -b2_maxFloat; - float32 radius = polygonA->m_radius + circleB->m_radius; - int32 vertexCount = polygonA->m_vertexCount; - const b2Vec2* vertices = polygonA->m_vertices; - const b2Vec2* normals = polygonA->m_normals; - - for (int32 i = 0; i < vertexCount; ++i) - { - float32 s = b2Dot(normals[i], cLocal - vertices[i]); - - if (s > radius) - { - // Early out. - return; - } - - if (s > separation) - { - separation = s; - normalIndex = i; - } - } - - // Vertices that subtend the incident face. - int32 vertIndex1 = normalIndex; - int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; - b2Vec2 v1 = vertices[vertIndex1]; - b2Vec2 v2 = vertices[vertIndex2]; - - // If the center is inside the polygon ... - if (separation < b2_epsilon) - { - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[normalIndex]; - manifold->localPoint = 0.5f * (v1 + v2); - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - return; - } - - // Compute barycentric coordinates - float32 u1 = b2Dot(cLocal - v1, v2 - v1); - float32 u2 = b2Dot(cLocal - v2, v1 - v2); - if (u1 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v1) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v1; - manifold->localNormal.Normalize(); - manifold->localPoint = v1; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else if (u2 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v2) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v2; - manifold->localNormal.Normalize(); - manifold->localPoint = v2; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else - { - b2Vec2 faceCenter = 0.5f * (v1 + v2); - float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); - if (separation > radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[vertIndex1]; - manifold->localPoint = faceCenter; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } -} diff --git a/external/Box2D/Collision/b2CollideEdge.cpp b/external/Box2D/Collision/b2CollideEdge.cpp deleted file mode 100644 index 96ca71dccc..0000000000 --- a/external/Box2D/Collision/b2CollideEdge.cpp +++ /dev/null @@ -1,698 +0,0 @@ -/* - * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ - -#include -#include -#include -#include - - -// Compute contact points for edge versus circle. -// This accounts for edge connectivity. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle in frame of edge - b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); - - b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; - b2Vec2 e = B - A; - - // Barycentric coordinates - float32 u = b2Dot(e, B - Q); - float32 v = b2Dot(e, Q - A); - - float32 radius = edgeA->m_radius + circleB->m_radius; - - b2ContactFeature cf; - cf.indexB = 0; - cf.typeB = b2ContactFeature::e_vertex; - - // Region A - if (v <= 0.0f) - { - b2Vec2 P = A; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to A? - if (edgeA->m_hasVertex0) - { - b2Vec2 A1 = edgeA->m_vertex0; - b2Vec2 B1 = A; - b2Vec2 e1 = B1 - A1; - float32 u1 = b2Dot(e1, B1 - Q); - - // Is the circle in Region AB of the previous edge? - if (u1 > 0.0f) - { - return; - } - } - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region B - if (u <= 0.0f) - { - b2Vec2 P = B; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to B? - if (edgeA->m_hasVertex3) - { - b2Vec2 B2 = edgeA->m_vertex3; - b2Vec2 A2 = B; - b2Vec2 e2 = B2 - A2; - float32 v2 = b2Dot(e2, Q - A2); - - // Is the circle in Region AB of the next edge? - if (v2 > 0.0f) - { - return; - } - } - - cf.indexA = 1; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region AB - float32 den = b2Dot(e, e); - b2Assert(den > 0.0f); - b2Vec2 P = (1.0f / den) * (u * A + v * B); - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - b2Vec2 n(-e.y, e.x); - if (b2Dot(n, Q - A) < 0.0f) - { - n.Set(-n.x, -n.y); - } - n.Normalize(); - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_face; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = n; - manifold->localPoint = A; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; -} - -// This structure is used to keep track of the best separating axis. -struct b2EPAxis -{ - enum Type - { - e_unknown, - e_edgeA, - e_edgeB - }; - - Type type; - int32 index; - float32 separation; -}; - -// This holds polygon B expressed in frame A. -struct b2TempPolygon -{ - b2Vec2 vertices[b2_maxPolygonVertices]; - b2Vec2 normals[b2_maxPolygonVertices]; - int32 count; -}; - -// Reference face used for clipping -struct b2ReferenceFace -{ - int32 i1, i2; - - b2Vec2 v1, v2; - - b2Vec2 normal; - - b2Vec2 sideNormal1; - float32 sideOffset1; - - b2Vec2 sideNormal2; - float32 sideOffset2; -}; - -// This class collides and edge and a polygon, taking into account edge adjacency. -struct b2EPCollider -{ - void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - b2EPAxis ComputeEdgeSeparation(); - b2EPAxis ComputePolygonSeparation(); - - enum VertexType - { - e_isolated, - e_concave, - e_convex - }; - - b2TempPolygon m_polygonB; - - b2Transform m_xf; - b2Vec2 m_centroidB; - b2Vec2 m_v0, m_v1, m_v2, m_v3; - b2Vec2 m_normal0, m_normal1, m_normal2; - b2Vec2 m_normal; - VertexType m_type1, m_type2; - b2Vec2 m_lowerLimit, m_upperLimit; - float32 m_radius; - bool m_front; -}; - -// Algorithm: -// 1. Classify v1 and v2 -// 2. Classify polygon centroid as front or back -// 3. Flip normal if necessary -// 4. Initialize normal range to [-pi, pi] about face normal -// 5. Adjust normal range according to adjacent edges -// 6. Visit each separating axes, only accept axes within the range -// 7. Return if _any_ axis indicates separation -// 8. Clip -void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - m_xf = b2MulT(xfA, xfB); - - m_centroidB = b2Mul(m_xf, polygonB->m_centroid); - - m_v0 = edgeA->m_vertex0; - m_v1 = edgeA->m_vertex1; - m_v2 = edgeA->m_vertex2; - m_v3 = edgeA->m_vertex3; - - bool hasVertex0 = edgeA->m_hasVertex0; - bool hasVertex3F = edgeA->m_hasVertex3; - - b2Vec2 edge1 = m_v2 - m_v1; - edge1.Normalize(); - m_normal1.Set(edge1.y, -edge1.x); - float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); - float32 offset0 = 0.0f, offset2 = 0.0f; - bool convex1 = false, convex2 = false; - - // Is there a preceding edge? - if (hasVertex0) - { - b2Vec2 edge0 = m_v1 - m_v0; - edge0.Normalize(); - m_normal0.Set(edge0.y, -edge0.x); - convex1 = b2Cross(edge0, edge1) >= 0.0f; - offset0 = b2Dot(m_normal0, m_centroidB - m_v0); - } - - // Is there a following edge? - if (hasVertex3F) - { - b2Vec2 edge2 = m_v3 - m_v2; - edge2.Normalize(); - m_normal2.Set(edge2.y, -edge2.x); - convex2 = b2Cross(edge1, edge2) > 0.0f; - offset2 = b2Dot(m_normal2, m_centroidB - m_v2); - } - - // Determine front or back collision. Determine collision normal limits. - if (hasVertex0 && hasVertex3F) - { - if (convex1 && convex2) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - } - else if (convex1) - { - m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal1; - } - } - else if (convex2) - { - m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal0; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex0) - { - if (convex1) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex3F) - { - if (convex2) - { - m_front = offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - } - else - { - m_front = offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = m_normal1; - } - } - } - else - { - m_front = offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - } - - // Get polygonB in frameA - m_polygonB.count = polygonB->m_vertexCount; - for (int32 i = 0; i < polygonB->m_vertexCount; ++i) - { - m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); - m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); - } - - m_radius = 2.0f * b2_polygonRadius; - - manifold->pointCount = 0; - - b2EPAxis edgeAxis = ComputeEdgeSeparation(); - - // If no valid normal can be found than this edge should not collide. - if (edgeAxis.type == b2EPAxis::e_unknown) - { - return; - } - - if (edgeAxis.separation > m_radius) - { - return; - } - - b2EPAxis polygonAxis = ComputePolygonSeparation(); - if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) - { - return; - } - - // Use hysteresis for jitter reduction. - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - b2EPAxis primaryAxis; - if (polygonAxis.type == b2EPAxis::e_unknown) - { - primaryAxis = edgeAxis; - } - else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) - { - primaryAxis = polygonAxis; - } - else - { - primaryAxis = edgeAxis; - } - - b2ClipVertex ie[2]; - b2ReferenceFace rf; - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->type = b2Manifold::e_faceA; - - // Search for the polygon normal that is most anti-parallel to the edge normal. - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); - for (int32 i = 1; i < m_polygonB.count; ++i) - { - float32 value = b2Dot(m_normal, m_polygonB.normals[i]); - if (value < bestValue) - { - bestValue = value; - bestIndex = i; - } - } - - int32 i1 = bestIndex; - int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; - - ie[0].v = m_polygonB.vertices[i1]; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = i1; - ie[0].id.cf.typeA = b2ContactFeature::e_face; - ie[0].id.cf.typeB = b2ContactFeature::e_vertex; - - ie[1].v = m_polygonB.vertices[i2]; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = i2; - ie[1].id.cf.typeA = b2ContactFeature::e_face; - ie[1].id.cf.typeB = b2ContactFeature::e_vertex; - - if (m_front) - { - rf.i1 = 0; - rf.i2 = 1; - rf.v1 = m_v1; - rf.v2 = m_v2; - rf.normal = m_normal1; - } - else - { - rf.i1 = 1; - rf.i2 = 0; - rf.v1 = m_v2; - rf.v2 = m_v1; - rf.normal = -m_normal1; - } - } - else - { - manifold->type = b2Manifold::e_faceB; - - ie[0].v = m_v1; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = primaryAxis.index; - ie[0].id.cf.typeA = b2ContactFeature::e_vertex; - ie[0].id.cf.typeB = b2ContactFeature::e_face; - - ie[1].v = m_v2; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = primaryAxis.index; - ie[1].id.cf.typeA = b2ContactFeature::e_vertex; - ie[1].id.cf.typeB = b2ContactFeature::e_face; - - rf.i1 = primaryAxis.index; - rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; - rf.v1 = m_polygonB.vertices[rf.i1]; - rf.v2 = m_polygonB.vertices[rf.i2]; - rf.normal = m_polygonB.normals[rf.i1]; - } - - rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); - rf.sideNormal2 = -rf.sideNormal1; - rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); - rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int32 np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Now clipPoints2 contains the clipped points. - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->localNormal = rf.normal; - manifold->localPoint = rf.v1; - } - else - { - manifold->localNormal = polygonB->m_normals[rf.i1]; - manifold->localPoint = polygonB->m_vertices[rf.i1]; - } - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation; - - separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); - - if (separation <= m_radius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - } - else - { - cp->localPoint = clipPoints2[i].v; - cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; - cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; - cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; - cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; - } - - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} - -b2EPAxis b2EPCollider::ComputeEdgeSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_edgeA; - axis.index = m_front ? 0 : 1; - axis.separation = FLT_MAX; - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); - if (s < axis.separation) - { - axis.separation = s; - } - } - - return axis; -} - -b2EPAxis b2EPCollider::ComputePolygonSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_unknown; - axis.index = -1; - axis.separation = -FLT_MAX; - - b2Vec2 perp(-m_normal.y, m_normal.x); - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - b2Vec2 n = -m_polygonB.normals[i]; - - float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); - float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); - float32 s = b2Min(s1, s2); - - if (s > m_radius) - { - // No collision - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - return axis; - } - - // Adjacency - if (b2Dot(n, perp) >= 0.0f) - { - if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - else - { - if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - - if (s > axis.separation) - { - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - } - } - - return axis; -} - -void b2CollideEdgeAndPolygon( b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - b2EPCollider collider; - collider.Collide(manifold, edgeA, xfA, polygonB, xfB); -} diff --git a/external/Box2D/Collision/b2CollidePolygon.cpp b/external/Box2D/Collision/b2CollidePolygon.cpp deleted file mode 100644 index be2518d966..0000000000 --- a/external/Box2D/Collision/b2CollidePolygon.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -// Find the separation between poly1 and poly2 for a give edge normal on poly1. -static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* vertices1 = poly1->m_vertices; - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); - - // Convert normal from poly1's frame into poly2's frame. - b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); - b2Vec2 normal1 = b2MulT(xf2.q, normal1World); - - // Find support vertex on poly2 for -normal. - int32 index = 0; - float32 minDot = b2_maxFloat; - - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(vertices2[i], normal1); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]); - b2Vec2 v2 = b2Mul(xf2, vertices2[index]); - float32 separation = b2Dot(v2 - v1, normal1World); - return separation; -} - -// Find the max separation between poly1 and poly2 using edge normals from poly1. -static float32 b2FindMaxSeparation(int32* edgeIndex, - const b2PolygonShape* poly1, const b2Transform& xf1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - int32 count1 = poly1->m_vertexCount; - const b2Vec2* normals1 = poly1->m_normals; - - // Vector pointing from the centroid of poly1 to the centroid of poly2. - b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); - b2Vec2 dLocal1 = b2MulT(xf1.q, d); - - // Find edge normal on poly1 that has the largest projection onto d. - int32 edge = 0; - float32 maxDot = -b2_maxFloat; - for (int32 i = 0; i < count1; ++i) - { - float32 dot = b2Dot(normals1[i], dLocal1); - if (dot > maxDot) - { - maxDot = dot; - edge = i; - } - } - - // Get the separation for the edge normal. - float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); - - // Check the separation for the previous edge normal. - int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; - float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); - - // Check the separation for the next edge normal. - int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; - float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); - - // Find the best edge and the search direction. - int32 bestEdge; - float32 bestSeparation; - int32 increment; - if (sPrev > s && sPrev > sNext) - { - increment = -1; - bestEdge = prevEdge; - bestSeparation = sPrev; - } - else if (sNext > s) - { - increment = 1; - bestEdge = nextEdge; - bestSeparation = sNext; - } - else - { - *edgeIndex = edge; - return s; - } - - // Perform a local search for the best edge normal. - for ( ; ; ) - { - if (increment == -1) - edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1; - else - edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; - - s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); - - if (s > bestSeparation) - { - bestEdge = edge; - bestSeparation = s; - } - else - { - break; - } - } - - *edgeIndex = bestEdge; - return bestSeparation; -} - -static void b2FindIncidentEdge(b2ClipVertex c[2], - const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - const b2Vec2* normals2 = poly2->m_normals; - - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); - - // Get the normal of the reference edge in poly2's frame. - b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); - - // Find the incident edge on poly2. - int32 index = 0; - float32 minDot = b2_maxFloat; - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(normal1, normals2[i]); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - // Build the clip vertices for the incident edge. - int32 i1 = index; - int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; - - c[0].v = b2Mul(xf2, vertices2[i1]); - c[0].id.cf.indexA = (uint8)edge1; - c[0].id.cf.indexB = (uint8)i1; - c[0].id.cf.typeA = b2ContactFeature::e_face; - c[0].id.cf.typeB = b2ContactFeature::e_vertex; - - c[1].v = b2Mul(xf2, vertices2[i2]); - c[1].id.cf.indexA = (uint8)edge1; - c[1].id.cf.indexB = (uint8)i2; - c[1].id.cf.typeA = b2ContactFeature::e_face; - c[1].id.cf.typeB = b2ContactFeature::e_vertex; -} - -// Find edge normal of max separation on A - return if separating axis is found -// Find edge normal of max separation on B - return if separation axis is found -// Choose reference edge as min(minA, minB) -// Find incident edge -// Clip - -// The normal points from 1 to 2 -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polyA, const b2Transform& xfA, - const b2PolygonShape* polyB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - float32 totalRadius = polyA->m_radius + polyB->m_radius; - - int32 edgeA = 0; - float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); - if (separationA > totalRadius) - return; - - int32 edgeB = 0; - float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); - if (separationB > totalRadius) - return; - - const b2PolygonShape* poly1; // reference polygon - const b2PolygonShape* poly2; // incident polygon - b2Transform xf1, xf2; - int32 edge1; // reference edge - uint8 flip; - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - if (separationB > k_relativeTol * separationA + k_absoluteTol) - { - poly1 = polyB; - poly2 = polyA; - xf1 = xfB; - xf2 = xfA; - edge1 = edgeB; - manifold->type = b2Manifold::e_faceB; - flip = 1; - } - else - { - poly1 = polyA; - poly2 = polyB; - xf1 = xfA; - xf2 = xfB; - edge1 = edgeA; - manifold->type = b2Manifold::e_faceA; - flip = 0; - } - - b2ClipVertex incidentEdge[2]; - b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); - - int32 count1 = poly1->m_vertexCount; - const b2Vec2* vertices1 = poly1->m_vertices; - - int32 iv1 = edge1; - int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; - - b2Vec2 v11 = vertices1[iv1]; - b2Vec2 v12 = vertices1[iv2]; - - b2Vec2 localTangent = v12 - v11; - localTangent.Normalize(); - - b2Vec2 localNormal = b2Cross(localTangent, 1.0f); - b2Vec2 planePoint = 0.5f * (v11 + v12); - - b2Vec2 tangent = b2Mul(xf1.q, localTangent); - b2Vec2 normal = b2Cross(tangent, 1.0f); - - v11 = b2Mul(xf1, v11); - v12 = b2Mul(xf1, v12); - - // Face offset. - float32 frontOffset = b2Dot(normal, v11); - - // Side offsets, extended by polytope skin thickness. - float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; - float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); - - if (np < 2) - return; - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); - - if (np < 2) - { - return; - } - - // Now clipPoints2 contains the clipped points. - manifold->localNormal = localNormal; - manifold->localPoint = planePoint; - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; - - if (separation <= totalRadius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - cp->localPoint = b2MulT(xf2, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - if (flip) - { - // Swap features - b2ContactFeature cf = cp->id.cf; - cp->id.cf.indexA = cf.indexB; - cp->id.cf.indexB = cf.indexA; - cp->id.cf.typeA = cf.typeB; - cp->id.cf.typeB = cf.typeA; - } - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} diff --git a/external/Box2D/Collision/b2Collision.cpp b/external/Box2D/Collision/b2Collision.cpp deleted file mode 100644 index 2dd5ff0ab6..0000000000 --- a/external/Box2D/Collision/b2Collision.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -void b2WorldManifold::Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB) -{ - if (manifold->pointCount == 0) - { - return; - } - - switch (manifold->type) - { - case b2Manifold::e_circles: - { - normal.Set(1.0f, 0.0f); - b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); - b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } - - b2Vec2 cA = pointA + radiusA * normal; - b2Vec2 cB = pointB - radiusB * normal; - points[0] = 0.5f * (cA + cB); - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); - b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cB = clipPoint - radiusB * normal; - points[i] = 0.5f * (cA + cB); - } - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); - b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cA = clipPoint - radiusA * normal; - points[i] = 0.5f * (cA + cB); - } - - // Ensure normal points from A to B. - normal = -normal; - } - break; - } -} - -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2) -{ - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - state1[i] = b2_nullState; - state2[i] = b2_nullState; - } - - // Detect persists and removes. - for (int32 i = 0; i < manifold1->pointCount; ++i) - { - b2ContactID id = manifold1->points[i].id; - - state1[i] = b2_removeState; - - for (int32 j = 0; j < manifold2->pointCount; ++j) - { - if (manifold2->points[j].id.key == id.key) - { - state1[i] = b2_persistState; - break; - } - } - } - - // Detect persists and adds. - for (int32 i = 0; i < manifold2->pointCount; ++i) - { - b2ContactID id = manifold2->points[i].id; - - state2[i] = b2_addState; - - for (int32 j = 0; j < manifold1->pointCount; ++j) - { - if (manifold1->points[j].id.key == id.key) - { - state2[i] = b2_persistState; - break; - } - } - } -} - -// From Real-time Collision Detection, p179. -bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const -{ - float32 tmin = -b2_maxFloat; - float32 tmax = b2_maxFloat; - - b2Vec2 p = input.p1; - b2Vec2 d = input.p2 - input.p1; - b2Vec2 absD = b2Abs(d); - - b2Vec2 normal; - - for (int32 i = 0; i < 2; ++i) - { - if (absD(i) < b2_epsilon) - { - // Parallel. - if (p(i) < lowerBound(i) || upperBound(i) < p(i)) - { - return false; - } - } - else - { - float32 inv_d = 1.0f / d(i); - float32 t1 = (lowerBound(i) - p(i)) * inv_d; - float32 t2 = (upperBound(i) - p(i)) * inv_d; - - // Sign of the normal vector. - float32 s = -1.0f; - - if (t1 > t2) - { - b2Swap(t1, t2); - s = 1.0f; - } - - // Push the min up - if (t1 > tmin) - { - normal.SetZero(); - normal(i) = s; - tmin = t1; - } - - // Pull the max down - tmax = b2Min(tmax, t2); - - if (tmin > tmax) - { - return false; - } - } - } - - // Does the ray start inside the box? - // Does the ray intersect beyond the max fraction? - if (tmin < 0.0f || input.maxFraction < tmin) - { - return false; - } - - // Intersection. - output->fraction = tmin; - output->normal = normal; - return true; -} - -// Sutherland-Hodgman clipping. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA) -{ - // Start with no output points - int32 numOut = 0; - - // Calculate the distance of end points to the line - float32 distance0 = b2Dot(normal, vIn[0].v) - offset; - float32 distance1 = b2Dot(normal, vIn[1].v) - offset; - - // If the points are behind the plane - if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; - if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; - - // If the points are on different sides of the plane - if (distance0 * distance1 < 0.0f) - { - // Find intersection point of edge and plane - float32 interp = distance0 / (distance0 - distance1); - vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - - // VertexA is hitting edgeB. - vOut[numOut].id.cf.indexA = vertexIndexA; - vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; - vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; - vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; - ++numOut; - } - - return numOut; -} - -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB) -{ - b2DistanceInput input; - input.proxyA.Set(shapeA, indexA); - input.proxyB.Set(shapeB, indexB); - input.transformA = xfA; - input.transformB = xfB; - input.useRadii = true; - - b2SimplexCache cache; - cache.count = 0; - - b2DistanceOutput output; - - b2Distance(&output, &cache, &input); - - return output.distance < 10.0f * b2_epsilon; -} diff --git a/external/Box2D/Collision/b2Collision.h b/external/Box2D/Collision/b2Collision.h deleted file mode 100644 index 2e7386232b..0000000000 --- a/external/Box2D/Collision/b2Collision.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_COLLISION_H -#define B2_COLLISION_H - -#include -#include - -/// @file -/// Structures and functions used for computing contact points, distance -/// queries, and TOI queries. - -class b2Shape; -class b2CircleShape; -class b2EdgeShape; -class b2PolygonShape; - -const uint8 b2_nullFeature = UCHAR_MAX; - -/// The features that intersect to form the contact point -/// This must be 4 bytes or less. -struct b2ContactFeature -{ - enum Type - { - e_vertex = 0, - e_face = 1 - }; - - uint8 indexA; ///< Feature index on shapeA - uint8 indexB; ///< Feature index on shapeB - uint8 typeA; ///< The feature type on shapeA - uint8 typeB; ///< The feature type on shapeB -}; - -/// Contact ids to facilitate warm starting. -union b2ContactID -{ - b2ContactFeature cf; - uint32 key; ///< Used to quickly compare contact ids. -}; - -/// A manifold point is a contact point belonging to a contact -/// manifold. It holds details related to the geometry and dynamics -/// of the contact points. -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleB -/// -e_faceA: the local center of cirlceB or the clip point of polygonB -/// -e_faceB: the clip point of polygonA -/// This structure is stored across time steps, so we keep it small. -/// Note: the impulses are used for internal caching and may not -/// provide reliable contact forces, especially for high speed collisions. -struct b2ManifoldPoint -{ - b2Vec2 localPoint; ///< usage depends on manifold type - float32 normalImpulse; ///< the non-penetration impulse - float32 tangentImpulse; ///< the friction impulse - b2ContactID id; ///< uniquely identifies a contact point between two shapes -}; - -/// A manifold for two touching convex shapes. -/// Box2D supports multiple types of contact: -/// - clip point versus plane with radius -/// - point versus point with radius (circles) -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleA -/// -e_faceA: the center of faceA -/// -e_faceB: the center of faceB -/// Similarly the local normal usage: -/// -e_circles: not used -/// -e_faceA: the normal on polygonA -/// -e_faceB: the normal on polygonB -/// We store contacts in this way so that position correction can -/// account for movement, which is critical for continuous physics. -/// All contact scenarios must be expressed in one of these types. -/// This structure is stored across time steps, so we keep it small. -struct b2Manifold -{ - enum Type - { - e_circles, - e_faceA, - e_faceB - }; - - b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact - b2Vec2 localNormal; ///< not use for Type::e_points - b2Vec2 localPoint; ///< usage depends on manifold type - Type type; - int32 pointCount; ///< the number of manifold points -}; - -/// This is used to compute the current state of a contact manifold. -struct b2WorldManifold -{ - /// Evaluate the manifold with supplied transforms. This assumes - /// modest motion from the original state. This does not change the - /// point count, impulses, etc. The radii must come from the shapes - /// that generated the manifold. - void Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB); - - b2Vec2 normal; ///< world vector pointing from A to B - b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) -}; - -/// This is used for determining the state of contact points. -enum b2PointState -{ - b2_nullState, ///< point does not exist - b2_addState, ///< point was added in the update - b2_persistState, ///< point persisted across the update - b2_removeState ///< point was removed in the update -}; - -/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 -/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2); - -/// Used for computing contact manifolds. -struct b2ClipVertex -{ - b2Vec2 v; - b2ContactID id; -}; - -/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). -struct b2RayCastInput -{ - b2Vec2 p1, p2; - float32 maxFraction; -}; - -/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 -/// come from b2RayCastInput. -struct b2RayCastOutput -{ - b2Vec2 normal; - float32 fraction; -}; - -/// An axis aligned bounding box. -struct b2AABB -{ - /// Verify that the bounds are sorted. - bool IsValid() const; - - /// Get the center of the AABB. - b2Vec2 GetCenter() const - { - return 0.5f * (lowerBound + upperBound); - } - - /// Get the extents of the AABB (half-widths). - b2Vec2 GetExtents() const - { - return 0.5f * (upperBound - lowerBound); - } - - /// Get the perimeter length - float32 GetPerimeter() const - { - float32 wx = upperBound.x - lowerBound.x; - float32 wy = upperBound.y - lowerBound.y; - return 2.0f * (wx + wy); - } - - /// Combine an AABB into this one. - void Combine(const b2AABB& aabb) - { - lowerBound = b2Min(lowerBound, aabb.lowerBound); - upperBound = b2Max(upperBound, aabb.upperBound); - } - - /// Combine two AABBs into this one. - void Combine(const b2AABB& aabb1, const b2AABB& aabb2) - { - lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); - upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); - } - - /// Does this aabb contain the provided AABB. - bool Contains(const b2AABB& aabb) const - { - bool result = true; - result = result && lowerBound.x <= aabb.lowerBound.x; - result = result && lowerBound.y <= aabb.lowerBound.y; - result = result && aabb.upperBound.x <= upperBound.x; - result = result && aabb.upperBound.y <= upperBound.y; - return result; - } - - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; - - b2Vec2 lowerBound; ///< the lower vertex - b2Vec2 upperBound; ///< the upper vertex -}; - -/// Compute the collision manifold between two circles. -void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between a polygon and a circle. -void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between two polygons. -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndPolygon(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* circleB, const b2Transform& xfB); - -/// Clipping for contact manifolds. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA); - -/// Determine if two generic shapes overlap. -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB); - -// ---------------- Inline Functions ------------------------------------------ - -inline bool b2AABB::IsValid() const -{ - b2Vec2 d = upperBound - lowerBound; - bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && lowerBound.IsValid() && upperBound.IsValid(); - return valid; -} - -inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) -{ - b2Vec2 d1, d2; - d1 = b.lowerBound - a.upperBound; - d2 = a.lowerBound - b.upperBound; - - if (d1.x > 0.0f || d1.y > 0.0f) - return false; - - if (d2.x > 0.0f || d2.y > 0.0f) - return false; - - return true; -} - -#endif diff --git a/external/Box2D/Collision/b2Distance.cpp b/external/Box2D/Collision/b2Distance.cpp deleted file mode 100644 index ac67d3be43..0000000000 --- a/external/Box2D/Collision/b2Distance.cpp +++ /dev/null @@ -1,603 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. -int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - -void b2DistanceProxy::Set(const b2Shape* shape, int32 index) -{ - switch (shape->GetType()) - { - case b2Shape::e_circle: - { - const b2CircleShape* circle = (b2CircleShape*)shape; - m_vertices = &circle->m_p; - m_count = 1; - m_radius = circle->m_radius; - } - break; - - case b2Shape::e_polygon: - { - const b2PolygonShape* polygon = (b2PolygonShape*)shape; - m_vertices = polygon->m_vertices; - m_count = polygon->m_vertexCount; - m_radius = polygon->m_radius; - } - break; - - case b2Shape::e_chain: - { - const b2ChainShape* chain = (b2ChainShape*)shape; - b2Assert(0 <= index && index < chain->m_count); - - m_buffer[0] = chain->m_vertices[index]; - if (index + 1 < chain->m_count) - { - m_buffer[1] = chain->m_vertices[index + 1]; - } - else - { - m_buffer[1] = chain->m_vertices[0]; - } - - m_vertices = m_buffer; - m_count = 2; - m_radius = chain->m_radius; - } - break; - - case b2Shape::e_edge: - { - const b2EdgeShape* edge = (b2EdgeShape*)shape; - m_vertices = &edge->m_vertex1; - m_count = 2; - m_radius = edge->m_radius; - } - break; - - default: - b2Assert(false); - } -} - - -struct b2SimplexVertex -{ - b2Vec2 wA; // support point in proxyA - b2Vec2 wB; // support point in proxyB - b2Vec2 w; // wB - wA - float32 a; // barycentric coordinate for closest point - int32 indexA; // wA index - int32 indexB; // wB index -}; - -struct b2Simplex -{ - void ReadCache( const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Transform& transformA, - const b2DistanceProxy* proxyB, const b2Transform& transformB) - { - b2Assert(cache->count <= 3); - - // Copy data from cache. - m_count = cache->count; - b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - b2SimplexVertex* v = vertices + i; - v->indexA = cache->indexA[i]; - v->indexB = cache->indexB[i]; - b2Vec2 wALocal = proxyA->GetVertex(v->indexA); - b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - v->a = 0.0f; - } - - // Compute the new simplex metric, if it is substantially different than - // old metric then flush the simplex. - if (m_count > 1) - { - float32 metric1 = cache->metric; - float32 metric2 = GetMetric(); - if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) - { - // Reset the simplex. - m_count = 0; - } - } - - // If the cache is empty or invalid ... - if (m_count == 0) - { - b2SimplexVertex* v = vertices + 0; - v->indexA = 0; - v->indexB = 0; - b2Vec2 wALocal = proxyA->GetVertex(0); - b2Vec2 wBLocal = proxyB->GetVertex(0); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - m_count = 1; - } - } - - void WriteCache(b2SimplexCache* cache) const - { - cache->metric = GetMetric(); - cache->count = uint16(m_count); - const b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - cache->indexA[i] = uint8(vertices[i].indexA); - cache->indexB[i] = uint8(vertices[i].indexB); - } - } - - b2Vec2 GetSearchDirection() const - { - switch (m_count) - { - case 1: - return -m_v1.w; - - case 2: - { - b2Vec2 e12 = m_v2.w - m_v1.w; - float32 sgn = b2Cross(e12, -m_v1.w); - if (sgn > 0.0f) - { - // Origin is left of e12. - return b2Cross(1.0f, e12); - } - else - { - // Origin is right of e12. - return b2Cross(e12, 1.0f); - } - } - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - b2Vec2 GetClosestPoint() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return b2Vec2_zero; - - case 1: - return m_v1.w; - - case 2: - return m_v1.a * m_v1.w + m_v2.a * m_v2.w; - - case 3: - return b2Vec2_zero; - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const - { - switch (m_count) - { - case 0: - b2Assert(false); - break; - - case 1: - *pA = m_v1.wA; - *pB = m_v1.wB; - break; - - case 2: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; - *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; - break; - - case 3: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; - *pB = *pA; - break; - - default: - b2Assert(false); - break; - } - } - - float32 GetMetric() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return 0.0; - - case 1: - return 0.0f; - - case 2: - return b2Distance(m_v1.w, m_v2.w); - - case 3: - return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); - - default: - b2Assert(false); - return 0.0f; - } - } - - void Solve2(); - void Solve3(); - - b2SimplexVertex m_v1, m_v2, m_v3; - int32 m_count; -}; - - -// Solve a line segment using barycentric coordinates. -// -// p = a1 * w1 + a2 * w2 -// a1 + a2 = 1 -// -// The vector from the origin to the closest point on the line is -// perpendicular to the line. -// e12 = w2 - w1 -// dot(p, e) = 0 -// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 -// -// 2-by-2 linear system -// [1 1 ][a1] = [1] -// [w1.e12 w2.e12][a2] = [0] -// -// Define -// d12_1 = dot(w2, e12) -// d12_2 = -dot(w1, e12) -// d12 = d12_1 + d12_2 -// -// Solution -// a1 = d12_1 / d12 -// a2 = d12_2 / d12 -void b2Simplex::Solve2() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 e12 = w2 - w1; - - // w1 region - float32 d12_2 = -b2Dot(w1, e12); - if (d12_2 <= 0.0f) - { - // a2 <= 0, so we clamp it to 0 - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // w2 region - float32 d12_1 = b2Dot(w2, e12); - if (d12_1 <= 0.0f) - { - // a1 <= 0, so we clamp it to 0 - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // Must be in e12 region. - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; -} - -// Possible regions: -// - points[2] -// - edge points[0]-points[2] -// - edge points[1]-points[2] -// - inside the triangle -void b2Simplex::Solve3() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 w3 = m_v3.w; - - // Edge12 - // [1 1 ][a1] = [1] - // [w1.e12 w2.e12][a2] = [0] - // a3 = 0 - b2Vec2 e12 = w2 - w1; - float32 w1e12 = b2Dot(w1, e12); - float32 w2e12 = b2Dot(w2, e12); - float32 d12_1 = w2e12; - float32 d12_2 = -w1e12; - - // Edge13 - // [1 1 ][a1] = [1] - // [w1.e13 w3.e13][a3] = [0] - // a2 = 0 - b2Vec2 e13 = w3 - w1; - float32 w1e13 = b2Dot(w1, e13); - float32 w3e13 = b2Dot(w3, e13); - float32 d13_1 = w3e13; - float32 d13_2 = -w1e13; - - // Edge23 - // [1 1 ][a2] = [1] - // [w2.e23 w3.e23][a3] = [0] - // a1 = 0 - b2Vec2 e23 = w3 - w2; - float32 w2e23 = b2Dot(w2, e23); - float32 w3e23 = b2Dot(w3, e23); - float32 d23_1 = w3e23; - float32 d23_2 = -w2e23; - - // Triangle123 - float32 n123 = b2Cross(e12, e13); - - float32 d123_1 = n123 * b2Cross(w2, w3); - float32 d123_2 = n123 * b2Cross(w3, w1); - float32 d123_3 = n123 * b2Cross(w1, w2); - - // w1 region - if (d12_2 <= 0.0f && d13_2 <= 0.0f) - { - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // e12 - if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) - { - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; - return; - } - - // e13 - if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) - { - float32 inv_d13 = 1.0f / (d13_1 + d13_2); - m_v1.a = d13_1 * inv_d13; - m_v3.a = d13_2 * inv_d13; - m_count = 2; - m_v2 = m_v3; - return; - } - - // w2 region - if (d12_1 <= 0.0f && d23_2 <= 0.0f) - { - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // w3 region - if (d13_1 <= 0.0f && d23_1 <= 0.0f) - { - m_v3.a = 1.0f; - m_count = 1; - m_v1 = m_v3; - return; - } - - // e23 - if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) - { - float32 inv_d23 = 1.0f / (d23_1 + d23_2); - m_v2.a = d23_1 * inv_d23; - m_v3.a = d23_2 * inv_d23; - m_count = 2; - m_v1 = m_v3; - return; - } - - // Must be in triangle123 - float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); - m_v1.a = d123_1 * inv_d123; - m_v2.a = d123_2 * inv_d123; - m_v3.a = d123_3 * inv_d123; - m_count = 3; -} - -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input) -{ - ++b2_gjkCalls; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Transform transformA = input->transformA; - b2Transform transformB = input->transformB; - - // Initialize the simplex. - b2Simplex simplex; - simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); - - // Get simplex vertices as an array. - b2SimplexVertex* vertices = &simplex.m_v1; - const int32 k_maxIters = 20; - - // These store the vertices of the last simplex so that we - // can check for duplicates and prevent cycling. - int32 saveA[3], saveB[3]; - int32 saveCount = 0; - - b2Vec2 closestPoint = simplex.GetClosestPoint(); - float32 distanceSqr1 = closestPoint.LengthSquared(); - float32 distanceSqr2 = distanceSqr1; - - // Main iteration loop. - int32 iter = 0; - while (iter < k_maxIters) - { - // Copy simplex so we can identify duplicates. - saveCount = simplex.m_count; - for (int32 i = 0; i < saveCount; ++i) - { - saveA[i] = vertices[i].indexA; - saveB[i] = vertices[i].indexB; - } - - switch (simplex.m_count) - { - case 1: - break; - - case 2: - simplex.Solve2(); - break; - - case 3: - simplex.Solve3(); - break; - - default: - b2Assert(false); - } - - // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.m_count == 3) - { - break; - } - - // Compute closest point. - b2Vec2 p = simplex.GetClosestPoint(); - distanceSqr2 = p.LengthSquared(); - - // Ensure progress - if (distanceSqr2 >= distanceSqr1) - { - //break; - } - distanceSqr1 = distanceSqr2; - - // Get search direction. - b2Vec2 d = simplex.GetSearchDirection(); - - // Ensure the search direction is numerically fit. - if (d.LengthSquared() < b2_epsilon * b2_epsilon) - { - // The origin is probably contained by a line segment - // or triangle. Thus the shapes are overlapped. - - // We can't return zero here even though there may be overlap. - // In case the simplex is a point, segment, or triangle it is difficult - // to determine if the origin is contained in the CSO or very close to it. - break; - } - - // Compute a tentative new simplex vertex using support points. - b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); - vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); - b2Vec2 wBLocal; - vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); - vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); - vertex->w = vertex->wB - vertex->wA; - - // Iteration count is equated to the number of support point calls. - ++iter; - ++b2_gjkIters; - - // Check for duplicate support points. This is the main termination criteria. - bool duplicate = false; - for (int32 i = 0; i < saveCount; ++i) - { - if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) - { - duplicate = true; - break; - } - } - - // If we found a duplicate support point we must exit to avoid cycling. - if (duplicate) - { - break; - } - - // New vertex is ok and needed. - ++simplex.m_count; - } - - b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); - - // Prepare output. - simplex.GetWitnessPoints(&output->pointA, &output->pointB); - output->distance = b2Distance(output->pointA, output->pointB); - output->iterations = iter; - - // Cache the simplex. - simplex.WriteCache(cache); - - // Apply radii if requested. - if (input->useRadii) - { - float32 rA = proxyA->m_radius; - float32 rB = proxyB->m_radius; - - if (output->distance > rA + rB && output->distance > b2_epsilon) - { - // Shapes are still no overlapped. - // Move the witness points to the outer surface. - output->distance -= rA + rB; - b2Vec2 normal = output->pointB - output->pointA; - normal.Normalize(); - output->pointA += rA * normal; - output->pointB -= rB * normal; - } - else - { - // Shapes are overlapped when radii are considered. - // Move the witness points to the middle. - b2Vec2 p = 0.5f * (output->pointA + output->pointB); - output->pointA = p; - output->pointB = p; - output->distance = 0.0f; - } - } -} diff --git a/external/Box2D/Collision/b2Distance.h b/external/Box2D/Collision/b2Distance.h deleted file mode 100644 index d598b7339d..0000000000 --- a/external/Box2D/Collision/b2Distance.h +++ /dev/null @@ -1,141 +0,0 @@ - -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DISTANCE_H -#define B2_DISTANCE_H - -#include - -class b2Shape; - -/// A distance proxy is used by the GJK algorithm. -/// It encapsulates any shape. -struct b2DistanceProxy -{ - b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} - - /// Initialize the proxy using the given shape. The shape - /// must remain in scope while the proxy is in use. - void Set(const b2Shape* shape, int32 index); - - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - - /// Get the vertex count. - int32 GetVertexCount() const; - - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; - - b2Vec2 m_buffer[2]; - const b2Vec2* m_vertices; - int32 m_count; - float32 m_radius; -}; - -/// Used to warm start b2Distance. -/// Set count to zero on first call. -struct b2SimplexCache -{ - float32 metric; ///< length or area - uint16 count; - uint8 indexA[3]; ///< vertices on shape A - uint8 indexB[3]; ///< vertices on shape B -}; - -/// Input for b2Distance. -/// You have to option to use the shape radii -/// in the computation. Even -struct b2DistanceInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Transform transformA; - b2Transform transformB; - bool useRadii; -}; - -/// Output for b2Distance. -struct b2DistanceOutput -{ - b2Vec2 pointA; ///< closest point on shapeA - b2Vec2 pointB; ///< closest point on shapeB - float32 distance; - int32 iterations; ///< number of GJK iterations used -}; - -/// Compute the closest points between two shapes. Supports any combination of: -/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. -/// On the first call set b2SimplexCache.count to zero. -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input); - - -////////////////////////////////////////////////////////////////////////// - -inline int32 b2DistanceProxy::GetVertexCount() const -{ - return m_count; -} - -inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const -{ - b2Assert(0 <= index && index < m_count); - return m_vertices[index]; -} - -inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return bestIndex; -} - -inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return m_vertices[bestIndex]; -} - -#endif diff --git a/external/Box2D/Collision/b2DynamicTree.cpp b/external/Box2D/Collision/b2DynamicTree.cpp deleted file mode 100644 index d1d53297e2..0000000000 --- a/external/Box2D/Collision/b2DynamicTree.cpp +++ /dev/null @@ -1,775 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#ifndef SHP -#include -#else -#include -#endif -using namespace std; - - -b2DynamicTree::b2DynamicTree() -{ - m_root = b2_nullNode; - - m_nodeCapacity = 16; - m_nodeCount = 0; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); - - // Build a linked list for the free list. - for (int32 i = 0; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = 0; - - m_path = 0; - - m_insertionCount = 0; -} - -b2DynamicTree::~b2DynamicTree() -{ - // This frees the entire tree in one shot. - b2Free(m_nodes); -} - -// Allocate a node from the pool. Grow the pool if necessary. -int32 b2DynamicTree::AllocateNode() -{ - // Expand the node pool as needed. - if (m_freeList == b2_nullNode) - { - b2Assert(m_nodeCount == m_nodeCapacity); - - // The free list is empty. Rebuild a bigger pool. - b2TreeNode* oldNodes = m_nodes; - m_nodeCapacity *= 2; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); - b2Free(oldNodes); - - // Build a linked list for the free list. The parent - // pointer becomes the "next" pointer. - for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = m_nodeCount; - } - - // Peel a node off the free list. - int32 nodeId = m_freeList; - m_freeList = m_nodes[nodeId].next; - m_nodes[nodeId].parent = b2_nullNode; - m_nodes[nodeId].child1 = b2_nullNode; - m_nodes[nodeId].child2 = b2_nullNode; - m_nodes[nodeId].height = 0; - m_nodes[nodeId].userData = NULL; - ++m_nodeCount; - return nodeId; -} - -// Return a node to the pool. -void b2DynamicTree::FreeNode(int32 nodeId) -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2Assert(0 < m_nodeCount); - m_nodes[nodeId].next = m_freeList; - m_nodes[nodeId].height = -1; - m_freeList = nodeId; - --m_nodeCount; -} - -// Create a proxy in the tree as a leaf node. We return the index -// of the node instead of a pointer so that we can grow -// the node pool. -int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = AllocateNode(); - - // Fatten the aabb. - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; - m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; - m_nodes[proxyId].userData = userData; - m_nodes[proxyId].height = 0; - - InsertLeaf(proxyId); - - return proxyId; -} - -void b2DynamicTree::DestroyProxy(int32 proxyId) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - b2Assert(m_nodes[proxyId].IsLeaf()); - - RemoveLeaf(proxyId); - FreeNode(proxyId); -} - -bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - - b2Assert(m_nodes[proxyId].IsLeaf()); - - if (m_nodes[proxyId].aabb.Contains(aabb)) - { - return false; - } - - RemoveLeaf(proxyId); - - // Extend AABB. - b2AABB b = aabb; - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - b.lowerBound = b.lowerBound - r; - b.upperBound = b.upperBound + r; - - // Predict AABB displacement. - b2Vec2 d = b2_aabbMultiplier * displacement; - - if (d.x < 0.0f) - { - b.lowerBound.x += d.x; - } - else - { - b.upperBound.x += d.x; - } - - if (d.y < 0.0f) - { - b.lowerBound.y += d.y; - } - else - { - b.upperBound.y += d.y; - } - - m_nodes[proxyId].aabb = b; - - InsertLeaf(proxyId); - return true; -} - -void b2DynamicTree::InsertLeaf(int32 leaf) -{ - ++m_insertionCount; - - if (m_root == b2_nullNode) - { - m_root = leaf; - m_nodes[m_root].parent = b2_nullNode; - return; - } - - // Find the best sibling for this node - b2AABB leafAABB = m_nodes[leaf].aabb; - int32 index = m_root; - while (m_nodes[index].IsLeaf() == false) - { - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - float32 area = m_nodes[index].aabb.GetPerimeter(); - - b2AABB combinedAABB; - combinedAABB.Combine(m_nodes[index].aabb, leafAABB); - float32 combinedArea = combinedAABB.GetPerimeter(); - - // Cost of creating a new parent for this node and the new leaf - float32 cost = 2.0f * combinedArea; - - // Minimum cost of pushing the leaf further down the tree - float32 inheritanceCost = 2.0f * (combinedArea - area); - - // Cost of descending into child1 - float32 cost1; - if (m_nodes[child1].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - cost1 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost1 = (newArea - oldArea) + inheritanceCost; - } - - // Cost of descending into child2 - float32 cost2; - if (m_nodes[child2].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - cost2 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost2 = newArea - oldArea + inheritanceCost; - } - - // Descend according to the minimum cost. - if (cost < cost1 && cost < cost2) - { - break; - } - - // Descend - if (cost1 < cost2) - { - index = child1; - } - else - { - index = child2; - } - } - - int32 sibling = index; - - // Create a new parent. - int32 oldParent = m_nodes[sibling].parent; - int32 newParent = AllocateNode(); - m_nodes[newParent].parent = oldParent; - m_nodes[newParent].userData = NULL; - m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); - m_nodes[newParent].height = m_nodes[sibling].height + 1; - - if (oldParent != b2_nullNode) - { - // The sibling was not the root. - if (m_nodes[oldParent].child1 == sibling) - { - m_nodes[oldParent].child1 = newParent; - } - else - { - m_nodes[oldParent].child2 = newParent; - } - - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - } - else - { - // The sibling was the root. - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - m_root = newParent; - } - - // Walk back up the tree fixing heights and AABBs - index = m_nodes[leaf].parent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - b2Assert(child1 != b2_nullNode); - b2Assert(child2 != b2_nullNode); - - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - index = m_nodes[index].parent; - } - - //Validate(); -} - -void b2DynamicTree::RemoveLeaf(int32 leaf) -{ - if (leaf == m_root) - { - m_root = b2_nullNode; - return; - } - - int32 parent = m_nodes[leaf].parent; - int32 grandParent = m_nodes[parent].parent; - int32 sibling; - if (m_nodes[parent].child1 == leaf) - { - sibling = m_nodes[parent].child2; - } - else - { - sibling = m_nodes[parent].child1; - } - - if (grandParent != b2_nullNode) - { - // Destroy parent and connect sibling to grandParent. - if (m_nodes[grandParent].child1 == parent) - { - m_nodes[grandParent].child1 = sibling; - } - else - { - m_nodes[grandParent].child2 = sibling; - } - m_nodes[sibling].parent = grandParent; - FreeNode(parent); - - // Adjust ancestor bounds. - int32 index = grandParent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - - index = m_nodes[index].parent; - } - } - else - { - m_root = sibling; - m_nodes[sibling].parent = b2_nullNode; - FreeNode(parent); - } - - //Validate(); -} - -// Perform a left or right rotation if node A is imbalanced. -// Returns the new root index. -int32 b2DynamicTree::Balance(int32 iA) -{ - b2Assert(iA != b2_nullNode); - - b2TreeNode* A = m_nodes + iA; - if (A->IsLeaf() || A->height < 2) - { - return iA; - } - - int32 iB = A->child1; - int32 iC = A->child2; - b2Assert(0 <= iB && iB < m_nodeCapacity); - b2Assert(0 <= iC && iC < m_nodeCapacity); - - b2TreeNode* B = m_nodes + iB; - b2TreeNode* C = m_nodes + iC; - - int32 balance = C->height - B->height; - - // Rotate C up - if (balance > 1) - { - int32 iF = C->child1; - int32 iG = C->child2; - b2TreeNode* F = m_nodes + iF; - b2TreeNode* G = m_nodes + iG; - b2Assert(0 <= iF && iF < m_nodeCapacity); - b2Assert(0 <= iG && iG < m_nodeCapacity); - - // Swap A and C - C->child1 = iA; - C->parent = A->parent; - A->parent = iC; - - // A's old parent should point to C - if (C->parent != b2_nullNode) - { - if (m_nodes[C->parent].child1 == iA) - { - m_nodes[C->parent].child1 = iC; - } - else - { - b2Assert(m_nodes[C->parent].child2 == iA); - m_nodes[C->parent].child2 = iC; - } - } - else - { - m_root = iC; - } - - // Rotate - if (F->height > G->height) - { - C->child2 = iF; - A->child2 = iG; - G->parent = iA; - A->aabb.Combine(B->aabb, G->aabb); - C->aabb.Combine(A->aabb, F->aabb); - - A->height = 1 + b2Max(B->height, G->height); - C->height = 1 + b2Max(A->height, F->height); - } - else - { - C->child2 = iG; - A->child2 = iF; - F->parent = iA; - A->aabb.Combine(B->aabb, F->aabb); - C->aabb.Combine(A->aabb, G->aabb); - - A->height = 1 + b2Max(B->height, F->height); - C->height = 1 + b2Max(A->height, G->height); - } - - return iC; - } - - // Rotate B up - if (balance < -1) - { - int32 iD = B->child1; - int32 iE = B->child2; - b2TreeNode* D = m_nodes + iD; - b2TreeNode* E = m_nodes + iE; - b2Assert(0 <= iD && iD < m_nodeCapacity); - b2Assert(0 <= iE && iE < m_nodeCapacity); - - // Swap A and B - B->child1 = iA; - B->parent = A->parent; - A->parent = iB; - - // A's old parent should point to B - if (B->parent != b2_nullNode) - { - if (m_nodes[B->parent].child1 == iA) - { - m_nodes[B->parent].child1 = iB; - } - else - { - b2Assert(m_nodes[B->parent].child2 == iA); - m_nodes[B->parent].child2 = iB; - } - } - else - { - m_root = iB; - } - - // Rotate - if (D->height > E->height) - { - B->child2 = iD; - A->child1 = iE; - E->parent = iA; - A->aabb.Combine(C->aabb, E->aabb); - B->aabb.Combine(A->aabb, D->aabb); - - A->height = 1 + b2Max(C->height, E->height); - B->height = 1 + b2Max(A->height, D->height); - } - else - { - B->child2 = iE; - A->child1 = iD; - D->parent = iA; - A->aabb.Combine(C->aabb, D->aabb); - B->aabb.Combine(A->aabb, E->aabb); - - A->height = 1 + b2Max(C->height, D->height); - B->height = 1 + b2Max(A->height, E->height); - } - - return iB; - } - - return iA; -} - -int32 b2DynamicTree::GetHeight() const -{ - if (m_root == b2_nullNode) - { - return 0; - } - - return m_nodes[m_root].height; -} - -// -float32 b2DynamicTree::GetAreaRatio() const -{ - if (m_root == b2_nullNode) - { - return 0.0f; - } - - const b2TreeNode* root = m_nodes + m_root; - float32 rootArea = root->aabb.GetPerimeter(); - - float32 totalArea = 0.0f; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height < 0) - { - // Free node in pool - continue; - } - - totalArea += node->aabb.GetPerimeter(); - } - - return totalArea / rootArea; -} - -// Compute the height of a sub-tree. -int32 b2DynamicTree::ComputeHeight(int32 nodeId) const -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2TreeNode* node = m_nodes + nodeId; - - if (node->IsLeaf()) - { - return 0; - } - - int32 height1 = ComputeHeight(node->child1); - int32 height2 = ComputeHeight(node->child2); - return 1 + b2Max(height1, height2); -} - -int32 b2DynamicTree::ComputeHeight() const -{ - int32 height = ComputeHeight(m_root); - return height; -} - -void b2DynamicTree::ValidateStructure(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - if (index == m_root) - { - b2Assert(m_nodes[index].parent == b2_nullNode); - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - b2Assert(m_nodes[child1].parent == index); - b2Assert(m_nodes[child2].parent == index); - - ValidateStructure(child1); - ValidateStructure(child2); -} - -void b2DynamicTree::ValidateMetrics(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - int32 height1 = m_nodes[child1].height; - int32 height2 = m_nodes[child2].height; - int32 height; - height = 1 + b2Max(height1, height2); - b2Assert(node->height == height); - - b2AABB aabb; - aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - b2Assert(aabb.lowerBound == node->aabb.lowerBound); - b2Assert(aabb.upperBound == node->aabb.upperBound); - - ValidateMetrics(child1); - ValidateMetrics(child2); -} - -void b2DynamicTree::Validate() const -{ - ValidateStructure(m_root); - ValidateMetrics(m_root); - - int32 freeCount = 0; - int32 freeIndex = m_freeList; - while (freeIndex != b2_nullNode) - { - b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); - freeIndex = m_nodes[freeIndex].next; - ++freeCount; - } - - b2Assert(GetHeight() == ComputeHeight()); - - b2Assert(m_nodeCount + freeCount == m_nodeCapacity); -} - -int32 b2DynamicTree::GetMaxBalance() const -{ - int32 maxBalance = 0; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height <= 1) - { - continue; - } - - b2Assert(node->IsLeaf() == false); - - int32 child1 = node->child1; - int32 child2 = node->child2; - int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); - maxBalance = b2Max(maxBalance, balance); - } - - return maxBalance; -} - -void b2DynamicTree::RebuildBottomUp() -{ - int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); - int32 count = 0; - - // Build array of leaves. Free the rest. - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - if (m_nodes[i].height < 0) - { - // free node in pool - continue; - } - - if (m_nodes[i].IsLeaf()) - { - m_nodes[i].parent = b2_nullNode; - nodes[count] = i; - ++count; - } - else - { - FreeNode(i); - } - } - - while (count > 1) - { - float32 minCost = b2_maxFloat; - int32 iMin = -1, jMin = -1; - for (int32 i = 0; i < count; ++i) - { - b2AABB aabbi = m_nodes[nodes[i]].aabb; - - for (int32 j = i + 1; j < count; ++j) - { - b2AABB aabbj = m_nodes[nodes[j]].aabb; - b2AABB b; - b.Combine(aabbi, aabbj); - float32 cost = b.GetPerimeter(); - if (cost < minCost) - { - iMin = i; - jMin = j; - minCost = cost; - } - } - } - - int32 index1 = nodes[iMin]; - int32 index2 = nodes[jMin]; - b2TreeNode* child1 = m_nodes + index1; - b2TreeNode* child2 = m_nodes + index2; - - int32 parentIndex = AllocateNode(); - b2TreeNode* parent = m_nodes + parentIndex; - parent->child1 = index1; - parent->child2 = index2; - parent->height = 1 + b2Max(child1->height, child2->height); - parent->aabb.Combine(child1->aabb, child2->aabb); - parent->parent = b2_nullNode; - - child1->parent = parentIndex; - child2->parent = parentIndex; - - nodes[jMin] = nodes[count-1]; - nodes[iMin] = parentIndex; - --count; - } - - m_root = nodes[0]; - b2Free(nodes); - - Validate(); -} diff --git a/external/Box2D/Collision/b2DynamicTree.h b/external/Box2D/Collision/b2DynamicTree.h deleted file mode 100644 index 33f16b0f32..0000000000 --- a/external/Box2D/Collision/b2DynamicTree.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DYNAMIC_TREE_H -#define B2_DYNAMIC_TREE_H - -#include -#include - -#define b2_nullNode (-1) - -/// A node in the dynamic tree. The client does not interact with this directly. -struct b2TreeNode -{ - bool IsLeaf() const - { - return child1 == b2_nullNode; - } - - /// Enlarged AABB - b2AABB aabb; - - void* userData; - - union - { - int32 parent; - int32 next; - }; - - int32 child1; - int32 child2; - - // leaf = 0, free node = -1 - int32 height; -}; - -/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. -/// A dynamic tree arranges data in a binary tree to accelerate -/// queries such as volume queries and ray casts. Leafs are proxies -/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor -/// so that the proxy AABB is bigger than the client object. This allows the client -/// object to move by small amounts without triggering a tree update. -/// -/// Nodes are pooled and relocatable, so we use node indices rather than pointers. -class b2DynamicTree -{ -public: - /// Constructing the tree initializes the node pool. - b2DynamicTree(); - - /// Destroy the tree, freeing the node pool. - ~b2DynamicTree(); - - /// Create a proxy. Provide a tight fitting AABB and a userData pointer. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. This asserts if the id is invalid. - void DestroyProxy(int32 proxyId); - - /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, - /// then the proxy is removed from the tree and re-inserted. Otherwise - /// the function returns immediately. - /// @return true if the proxy was re-inserted. - bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); - - /// Get proxy user data. - /// @return the proxy user data or 0 if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Validate this tree. For testing. - void Validate() const; - - /// Compute the height of the binary tree in O(N) time. Should not be - /// called often. - int32 GetHeight() const; - - /// Get the maximum balance of an node in the tree. The balance is the difference - /// in height of the two children of a node. - int32 GetMaxBalance() const; - - /// Get the ratio of the sum of the node areas to the root area. - float32 GetAreaRatio() const; - - /// Build an optimal tree. Very expensive. For testing. - void RebuildBottomUp(); - -private: - - int32 AllocateNode(); - void FreeNode(int32 node); - - void InsertLeaf(int32 node); - void RemoveLeaf(int32 node); - - int32 Balance(int32 index); - - int32 ComputeHeight() const; - int32 ComputeHeight(int32 nodeId) const; - - void ValidateStructure(int32 index) const; - void ValidateMetrics(int32 index) const; - - int32 m_root; - - b2TreeNode* m_nodes; - int32 m_nodeCount; - int32 m_nodeCapacity; - - int32 m_freeList; - - /// This is used to incrementally traverse the tree for re-balancing. - uint32 m_path; - - int32 m_insertionCount; -}; - -inline void* b2DynamicTree::GetUserData(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].userData; -} - -inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].aabb; -} - -template -inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const -{ - b2GrowableStack stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, aabb)) - { - if (node->IsLeaf()) - { - bool proceed = callback->QueryCallback(nodeId); - if (proceed == false) - { - return; - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } - } -} - -template -inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const -{ - b2Vec2 p1 = input.p1; - b2Vec2 p2 = input.p2; - b2Vec2 r = p2 - p1; - b2Assert(r.LengthSquared() > 0.0f); - r.Normalize(); - - // v is perpendicular to the segment. - b2Vec2 v = b2Cross(1.0f, r); - b2Vec2 abs_v = b2Abs(v); - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - - float32 maxFraction = input.maxFraction; - - // Build a bounding box for the segment. - b2AABB segmentAABB; - { - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - - b2GrowableStack stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, segmentAABB) == false) - { - continue; - } - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - b2Vec2 c = node->aabb.GetCenter(); - b2Vec2 h = node->aabb.GetExtents(); - float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); - if (separation > 0.0f) - { - continue; - } - - if (node->IsLeaf()) - { - b2RayCastInput subInput; - subInput.p1 = input.p1; - subInput.p2 = input.p2; - subInput.maxFraction = maxFraction; - - float32 value = callback->RayCastCallback(subInput, nodeId); - - if (value == 0.0f) - { - // The client has terminated the ray cast. - return; - } - - if (value > 0.0f) - { - // Update segment bounding box. - maxFraction = value; - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } -} - -#endif diff --git a/external/Box2D/Collision/b2TimeOfImpact.cpp b/external/Box2D/Collision/b2TimeOfImpact.cpp deleted file mode 100644 index 1d643addd8..0000000000 --- a/external/Box2D/Collision/b2TimeOfImpact.cpp +++ /dev/null @@ -1,488 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#ifdef SHP -#include -#else -#include -#endif - -using namespace std; - -int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; -int32 b2_toiRootIters, b2_toiMaxRootIters; - -struct b2SeparationFunction -{ - enum Type - { - e_points, - e_faceA, - e_faceB - }; - - // TODO_ERIN might not need to return the separation - - float32 Initialize(const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Sweep& sweepA, - const b2DistanceProxy* proxyB, const b2Sweep& sweepB, - float32 t1) - { - m_proxyA = proxyA; - m_proxyB = proxyB; - int32 count = cache->count; - b2Assert(0 < count && count < 3); - - m_sweepA = sweepA; - m_sweepB = sweepB; - - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t1); - m_sweepB.GetTransform(&xfB, t1); - - if (count == 1) - { - m_type = e_points; - b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - m_axis = pointB - pointA; - float32 s = m_axis.Normalize(); - return s; - } - else if (cache->indexA[0] == cache->indexA[1]) - { - // Two points on B and one on A. - m_type = e_faceB; - b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); - b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); - - m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfB.q, m_axis); - - m_localPoint = 0.5f * (localPointB1 + localPointB2); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 s = b2Dot(pointA - pointB, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - else - { - // Two points on A and one or two points on B. - m_type = e_faceA; - b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); - - m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfA.q, m_axis); - - m_localPoint = 0.5f * (localPointA1 + localPointA2); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 s = b2Dot(pointB - pointA, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - } - - float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - - *indexA = m_proxyA->GetSupport(axisA); - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, m_axis); - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - *indexA = -1; - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 axisA = b2MulT(xfA.q, -normal); - - *indexB = -1; - *indexA = m_proxyA->GetSupport(axisA); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - *indexA = -1; - *indexB = -1; - return 0.0f; - } - } - - float32 Evaluate(int32 indexA, int32 indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, m_axis); - - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 axisA = b2MulT(xfA.q, -normal); - - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - return 0.0f; - } - } - - const b2DistanceProxy* m_proxyA; - const b2DistanceProxy* m_proxyB; - b2Sweep m_sweepA, m_sweepB; - Type m_type; - b2Vec2 m_localPoint; - b2Vec2 m_axis; -}; - -// CCD via the local separating axis method. This seeks progression -// by computing the largest time at which separation is maintained. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) -{ - ++b2_toiCalls; - - output->state = b2TOIOutput::e_unknown; - output->t = input->tMax; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Sweep sweepA = input->sweepA; - b2Sweep sweepB = input->sweepB; - - // Large rotations can make the root finder fail, so we normalize the - // sweep angles. - sweepA.Normalize(); - sweepB.Normalize(); - - float32 tMax = input->tMax; - - float32 totalRadius = proxyA->m_radius + proxyB->m_radius; - float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); - float32 tolerance = 0.25f * b2_linearSlop; - b2Assert(target > tolerance); - - float32 t1 = 0.0f; - const int32 k_maxIterations = 20; // TODO_ERIN b2Settings - int32 iter = 0; - - // Prepare input for distance query. - b2SimplexCache cache; - cache.count = 0; - b2DistanceInput distanceInput; - distanceInput.proxyA = input->proxyA; - distanceInput.proxyB = input->proxyB; - distanceInput.useRadii = false; - - // The outer loop progressively attempts to compute new separating axes. - // This loop terminates when an axis is repeated (no progress is made). - for(;;) - { - b2Transform xfA, xfB; - sweepA.GetTransform(&xfA, t1); - sweepB.GetTransform(&xfB, t1); - - // Get the distance between shapes. We can also use the results - // to get a separating axis. - distanceInput.transformA = xfA; - distanceInput.transformB = xfB; - b2DistanceOutput distanceOutput; - b2Distance(&distanceOutput, &cache, &distanceInput); - - // If the shapes are overlapped, we give up on continuous collision. - if (distanceOutput.distance <= 0.0f) - { - // Failure! - output->state = b2TOIOutput::e_overlapped; - output->t = 0.0f; - break; - } - - if (distanceOutput.distance < target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_touching; - output->t = t1; - break; - } - - // Initialize the separating axis. - b2SeparationFunction fcn; - fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); -#if 0 - // Dump the curve seen by the root finder - { - const int32 N = 100; - float32 dx = 1.0f / N; - float32 xs[N+1]; - float32 fs[N+1]; - - float32 x = 0.0f; - - for (int32 i = 0; i <= N; ++i) - { - sweepA.GetTransform(&xfA, x); - sweepB.GetTransform(&xfB, x); - float32 f = fcn.Evaluate(xfA, xfB) - target; - - printf("%g %g\n", x, f); - - xs[i] = x; - fs[i] = f; - - x += dx; - } - } -#endif - - // Compute the TOI on the separating axis. We do this by successively - // resolving the deepest point. This loop is bounded by the number of vertices. - bool done = false; - float32 t2 = tMax; - int32 pushBackIter = 0; - for (;;) - { - // Find the deepest point at t2. Store the witness point indices. - int32 indexA, indexB; - float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); - - // Is the final configuration separated? - if (s2 > target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_separated; - output->t = tMax; - done = true; - break; - } - - // Has the separation reached tolerance? - if (s2 > target - tolerance) - { - // Advance the sweeps - t1 = t2; - break; - } - - // Compute the initial separation of the witness points. - float32 s1 = fcn.Evaluate(indexA, indexB, t1); - - // Check for initial overlap. This might happen if the root finder - // runs out of iterations. - if (s1 < target - tolerance) - { - output->state = b2TOIOutput::e_failed; - output->t = t1; - done = true; - break; - } - - // Check for touching - if (s1 <= target + tolerance) - { - // Victory! t1 should hold the TOI (could be 0.0). - output->state = b2TOIOutput::e_touching; - output->t = t1; - done = true; - break; - } - - // Compute 1D root of: f(x) - target = 0 - int32 rootIterCount = 0; - float32 a1 = t1, a2 = t2; - for (;;) - { - // Use a mix of the secant rule and bisection. - float32 t; - if (rootIterCount & 1) - { - // Secant rule to improve convergence. - t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); - } - else - { - // Bisection to guarantee progress. - t = 0.5f * (a1 + a2); - } - - float32 s = fcn.Evaluate(indexA, indexB, t); - - if (b2Abs(s - target) < tolerance) - { - // t2 holds a tentative value for t1 - t2 = t; - break; - } - - // Ensure we continue to bracket the root. - if (s > target) - { - a1 = t; - s1 = s; - } - else - { - a2 = t; - s2 = s; - } - - ++rootIterCount; - ++b2_toiRootIters; - - if (rootIterCount == 50) - { - break; - } - } - - b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); - - ++pushBackIter; - - if (pushBackIter == b2_maxPolygonVertices) - { - break; - } - } - - ++iter; - ++b2_toiIters; - - if (done) - { - break; - } - - if (iter == k_maxIterations) - { - // Root finder got stuck. Semi-victory. - output->state = b2TOIOutput::e_failed; - output->t = t1; - break; - } - } - - b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); -} diff --git a/external/Box2D/Collision/b2TimeOfImpact.h b/external/Box2D/Collision/b2TimeOfImpact.h deleted file mode 100644 index 2e4f8228ff..0000000000 --- a/external/Box2D/Collision/b2TimeOfImpact.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_TIME_OF_IMPACT_H -#define B2_TIME_OF_IMPACT_H - -#include -#include - -/// Input parameters for b2TimeOfImpact -struct b2TOIInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Sweep sweepA; - b2Sweep sweepB; - float32 tMax; // defines sweep interval [0, tMax] -}; - -// Output parameters for b2TimeOfImpact. -struct b2TOIOutput -{ - enum State - { - e_unknown, - e_failed, - e_overlapped, - e_touching, - e_separated - }; - - State state; - float32 t; -}; - -/// Compute the upper bound on time before two shapes penetrate. Time is represented as -/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, -/// non-tunneling collision. If you change the time interval, you should call this function -/// again. -/// Note: use b2Distance to compute the contact point and normal at the time of impact. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); - -#endif diff --git a/external/Box2D/Common/b2BlockAllocator.cpp b/external/Box2D/Common/b2BlockAllocator.cpp deleted file mode 100644 index 2e862091f9..0000000000 --- a/external/Box2D/Common/b2BlockAllocator.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -using namespace std; - -int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = -{ - 16, // 0 - 32, // 1 - 64, // 2 - 96, // 3 - 128, // 4 - 160, // 5 - 192, // 6 - 224, // 7 - 256, // 8 - 320, // 9 - 384, // 10 - 448, // 11 - 512, // 12 - 640, // 13 -}; -uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; -bool b2BlockAllocator::s_blockSizeLookupInitialized; - -struct b2Chunk -{ - int32 blockSize; - b2Block* blocks; -}; - -struct b2Block -{ - b2Block* next; -}; - -b2BlockAllocator::b2BlockAllocator() -{ - b2Assert(b2_blockSizes < UCHAR_MAX); - - m_chunkSpace = b2_chunkArrayIncrement; - m_chunkCount = 0; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - memset(m_freeLists, 0, sizeof(m_freeLists)); - - if (s_blockSizeLookupInitialized == false) - { - int32 j = 0; - for (int32 i = 1; i <= b2_maxBlockSize; ++i) - { - b2Assert(j < b2_blockSizes); - if (i <= s_blockSizes[j]) - { - s_blockSizeLookup[i] = (uint8)j; - } - else - { - ++j; - s_blockSizeLookup[i] = (uint8)j; - } - } - - s_blockSizeLookupInitialized = true; - } -} - -b2BlockAllocator::~b2BlockAllocator() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - b2Free(m_chunks); -} - -void* b2BlockAllocator::Allocate(int32 size) -{ - if (size == 0) - return NULL; - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - return b2Alloc(size); - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - - if (m_freeLists[index]) - { - b2Block* block = m_freeLists[index]; - m_freeLists[index] = block->next; - return block; - } - else - { - if (m_chunkCount == m_chunkSpace) - { - b2Chunk* oldChunks = m_chunks; - m_chunkSpace += b2_chunkArrayIncrement; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); - memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); - b2Free(oldChunks); - } - - b2Chunk* chunk = m_chunks + m_chunkCount; - chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); -#if defined(_DEBUG) - memset(chunk->blocks, 0xcd, b2_chunkSize); -#endif - int32 blockSize = s_blockSizes[index]; - chunk->blockSize = blockSize; - int32 blockCount = b2_chunkSize / blockSize; - b2Assert(blockCount * blockSize <= b2_chunkSize); - for (int32 i = 0; i < blockCount - 1; ++i) - { - b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); - b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); - block->next = next; - } - b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); - last->next = NULL; - - m_freeLists[index] = chunk->blocks->next; - ++m_chunkCount; - - return chunk->blocks; - } -} - -void b2BlockAllocator::Free(void* p, int32 size) -{ - if (size == 0) - { - return; - } - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - b2Free(p); - return; - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - -#ifdef _DEBUG - // Verify the memory address and size is valid. - int32 blockSize = s_blockSizes[index]; - bool found = false; - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Chunk* chunk = m_chunks + i; - if (chunk->blockSize != blockSize) - { - b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || - (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); - } - else - { - if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) - { - found = true; - } - } - } - - b2Assert(found); - - memset(p, 0xfd, blockSize); -#endif - - b2Block* block = (b2Block*)p; - block->next = m_freeLists[index]; - m_freeLists[index] = block; -} - -void b2BlockAllocator::Clear() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - m_chunkCount = 0; - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - - memset(m_freeLists, 0, sizeof(m_freeLists)); -} diff --git a/external/Box2D/Common/b2BlockAllocator.h b/external/Box2D/Common/b2BlockAllocator.h deleted file mode 100644 index ec221fdf61..0000000000 --- a/external/Box2D/Common/b2BlockAllocator.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BLOCK_ALLOCATOR_H -#define B2_BLOCK_ALLOCATOR_H - -#include - -const int32 b2_chunkSize = 16 * 1024; -const int32 b2_maxBlockSize = 640; -const int32 b2_blockSizes = 14; -const int32 b2_chunkArrayIncrement = 128; - -struct b2Block; -struct b2Chunk; - -/// This is a small object allocator used for allocating small -/// objects that persist for more than one time step. -/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp -class b2BlockAllocator -{ -public: - b2BlockAllocator(); - ~b2BlockAllocator(); - - /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. - void* Allocate(int32 size); - - /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. - void Free(void* p, int32 size); - - void Clear(); - -private: - - b2Chunk* m_chunks; - int32 m_chunkCount; - int32 m_chunkSpace; - - b2Block* m_freeLists[b2_blockSizes]; - - static int32 s_blockSizes[b2_blockSizes]; - static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; - static bool s_blockSizeLookupInitialized; -}; - -#endif diff --git a/external/Box2D/Common/b2Draw.cpp b/external/Box2D/Common/b2Draw.cpp deleted file mode 100644 index cb760025e9..0000000000 --- a/external/Box2D/Common/b2Draw.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -b2Draw::b2Draw() -{ - m_drawFlags = 0; -} - -void b2Draw::SetFlags(uint32 flags) -{ - m_drawFlags = flags; -} - -uint32 b2Draw::GetFlags() const -{ - return m_drawFlags; -} - -void b2Draw::AppendFlags(uint32 flags) -{ - m_drawFlags |= flags; -} - -void b2Draw::ClearFlags(uint32 flags) -{ - m_drawFlags &= ~flags; -} diff --git a/external/Box2D/Common/b2Draw.h b/external/Box2D/Common/b2Draw.h deleted file mode 100644 index b33cd8d38f..0000000000 --- a/external/Box2D/Common/b2Draw.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -/// Color for debug drawing. Each value has the range [0,1]. -struct b2Color -{ - b2Color() {} - b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} - void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } - float32 r, g, b; -}; - -/// Implement and register this class with a b2World to provide debug drawing of physics -/// entities in your game. -class b2Draw -{ -public: - b2Draw(); - - virtual ~b2Draw() {} - - enum - { - e_shapeBit = 0x0001, ///< draw shapes - e_jointBit = 0x0002, ///< draw joint connections - e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes - e_pairBit = 0x0008, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0010 ///< draw center of mass frame - }; - - /// Set the drawing flags. - void SetFlags(uint32 flags); - - /// Get the drawing flags. - uint32 GetFlags() const; - - /// Append flags to the current flags. - void AppendFlags(uint32 flags); - - /// Clear flags from the current flags. - void ClearFlags(uint32 flags); - - /// Draw a closed polygon provided in CCW order. - virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a solid closed polygon provided in CCW order. - virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a circle. - virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; - - /// Draw a solid circle. - virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; - - /// Draw a line segment. - virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; - - /// Draw a transform. Choose your own length scale. - /// @param xf a transform. - virtual void DrawTransform(const b2Transform& xf) = 0; - -protected: - uint32 m_drawFlags; -}; diff --git a/external/Box2D/Common/b2GrowableStack.h b/external/Box2D/Common/b2GrowableStack.h deleted file mode 100644 index 68809521f4..0000000000 --- a/external/Box2D/Common/b2GrowableStack.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright (c) 2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_GROWABLE_STACK_H -#define B2_GROWABLE_STACK_H -#include -#include - -/// This is a growable LIFO stack with an initial capacity of N. -/// If the stack size exceeds the initial capacity, the heap is used -/// to increase the size of the stack. -template -class b2GrowableStack -{ -public: - b2GrowableStack() - { - m_stack = m_array; - m_count = 0; - m_capacity = N; - } - - ~b2GrowableStack() - { - if (m_stack != m_array) - { - b2Free(m_stack); - m_stack = NULL; - } - } - - void Push(const T& element) - { - if (m_count == m_capacity) - { - T* old = m_stack; - m_capacity *= 2; - m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); - std::memcpy(m_stack, old, m_count * sizeof(T)); - if (old != m_array) - { - b2Free(old); - } - } - - m_stack[m_count] = element; - ++m_count; - } - - T Pop() - { - b2Assert(m_count > 0); - --m_count; - return m_stack[m_count]; - } - - int32 GetCount() - { - return m_count; - } - -private: - T* m_stack; - T m_array[N]; - int32 m_count; - int32 m_capacity; -}; - - -#endif diff --git a/external/Box2D/Common/b2Math.cpp b/external/Box2D/Common/b2Math.cpp deleted file mode 100644 index 15d68fce96..0000000000 --- a/external/Box2D/Common/b2Math.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -const b2Vec2 b2Vec2_zero(0.0f, 0.0f); - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec3 x; - x.x = det * b2Dot(b, b2Cross(ey, ez)); - x.y = det * b2Dot(ex, b2Cross(b, ez)); - x.z = det * b2Dot(ex, b2Cross(ey, b)); - return x; -} - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const -{ - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; -} - -/// -void b2Mat33::GetInverse22(b2Mat33* M) const -{ - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - - M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; - M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; - M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; -} - -/// Returns the zero matrix if singular. -void b2Mat33::GetSymInverse33(b2Mat33* M) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - - float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; - float32 a22 = ey.y, a23 = ez.y; - float32 a33 = ez.z; - - M->ex.x = det * (a22 * a33 - a23 * a23); - M->ex.y = det * (a13 * a23 - a12 * a33); - M->ex.z = det * (a12 * a23 - a13 * a22); - - M->ey.x = M->ex.y; - M->ey.y = det * (a11 * a33 - a13 * a13); - M->ey.z = det * (a13 * a12 - a11 * a23); - - M->ez.x = M->ex.z; - M->ez.y = M->ey.z; - M->ez.z = det * (a11 * a22 - a12 * a12); -} diff --git a/external/Box2D/Common/b2Math.h b/external/Box2D/Common/b2Math.h deleted file mode 100644 index a6be671139..0000000000 --- a/external/Box2D/Common/b2Math.h +++ /dev/null @@ -1,738 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_MATH_H -#define B2_MATH_H - -#include - -#include -#ifndef SHP -#include -#else -#include -#endif -#include -#include - -using namespace std; - - -/// This function is used to ensure that a floating point number is -/// not a NaN or infinity. -inline bool b2IsValid(float32 x) -{ - if (x != x) - { - // NaN. - return false; - } - - float32 infinity = std::numeric_limits::infinity(); - return -infinity < x && x < infinity; -} - -/// This is a approximate yet fast inverse square-root. -inline float32 b2InvSqrt(float32 x) -{ - union - { - float32 x; - int32 i; - } convert; - - convert.x = x; - float32 xhalf = 0.5f * x; - convert.i = 0x5f3759df - (convert.i >> 1); - x = convert.x; - x = x * (1.5f - xhalf * x * x); - return x; -} - -#define b2Sqrt(x) std::sqrt(x) -#define b2Atan2(y, x) std::atan2(y, x) - -/// A 2D column vector. -struct b2Vec2 -{ - /// Default constructor does nothing (for performance). - b2Vec2() {} - - /// Construct using coordinates. - b2Vec2(float32 x, float32 y) : x(x), y(y) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_) { x = x_; y = y_; } - - /// Negate this vector. - b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } - - /// Read from and indexed element. - float32 operator () (int32 i) const - { - return (&x)[i]; - } - - /// Write to an indexed element. - float32& operator () (int32 i) - { - return (&x)[i]; - } - - /// Add a vector to this vector. - void operator += (const b2Vec2& v) - { - x += v.x; y += v.y; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec2& v) - { - x -= v.x; y -= v.y; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 a) - { - x *= a; y *= a; - } - - /// Get the length of this vector (the norm). - float32 Length() const - { - return b2Sqrt(x * x + y * y); - } - - /// Get the length squared. For performance, use this instead of - /// b2Vec2::Length (if possible). - float32 LengthSquared() const - { - return x * x + y * y; - } - - /// Convert this vector into a unit vector. Returns the length. - float32 Normalize() - { - float32 length = Length(); - if (length < b2_epsilon) - { - return 0.0f; - } - float32 invLength = 1.0f / length; - x *= invLength; - y *= invLength; - - return length; - } - - /// Does this vector contain finite coordinates? - bool IsValid() const - { - return b2IsValid(x) && b2IsValid(y); - } - - /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - b2Vec2 Skew() const - { - return b2Vec2(-y, x); - } - - float32 x, y; -}; - -/// A 2D column vector with 3 elements. -struct b2Vec3 -{ - /// Default constructor does nothing (for performance). - b2Vec3() {} - - /// Construct using coordinates. - b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } - - /// Negate this vector. - b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } - - /// Add a vector to this vector. - void operator += (const b2Vec3& v) - { - x += v.x; y += v.y; z += v.z; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec3& v) - { - x -= v.x; y -= v.y; z -= v.z; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 s) - { - x *= s; y *= s; z *= s; - } - - float32 x, y, z; -}; - -/// A 2-by-2 matrix. Stored in column-major order. -struct b2Mat22 -{ - /// The default constructor does nothing (for performance). - b2Mat22() {} - - /// Construct this matrix using columns. - b2Mat22(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Construct this matrix using scalars. - b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) - { - ex.x = a11; ex.y = a21; - ey.x = a12; ey.y = a22; - } - - /// Initialize this matrix using columns. - void Set(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Set this to the identity matrix. - void SetIdentity() - { - ex.x = 1.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 1.0f; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.x = 0.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 0.0f; - } - - b2Mat22 GetInverse() const - { - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - b2Mat22 B; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - B.ex.x = det * d; B.ey.x = -det * b; - B.ex.y = -det * c; B.ey.y = det * a; - return B; - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec2 Solve(const b2Vec2& b) const - { - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; - } - - b2Vec2 ex, ey; -}; - -/// A 3-by-3 matrix. Stored in column-major order. -struct b2Mat33 -{ - /// The default constructor does nothing (for performance). - b2Mat33() {} - - /// Construct this matrix using columns. - b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) - { - ex = c1; - ey = c2; - ez = c3; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.SetZero(); - ey.SetZero(); - ez.SetZero(); - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec3 Solve33(const b2Vec3& b) const; - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. Solve only the upper - /// 2-by-2 matrix equation. - b2Vec2 Solve22(const b2Vec2& b) const; - - /// Get the inverse of this matrix as a 2-by-2. - /// Returns the zero matrix if singular. - void GetInverse22(b2Mat33* M) const; - - /// Get the symmetric inverse of this matrix as a 3-by-3. - /// Returns the zero matrix if singular. - void GetSymInverse33(b2Mat33* M) const; - - b2Vec3 ex, ey, ez; -}; - -/// Rotation -struct b2Rot -{ - b2Rot() {} - - /// Initialize from an angle in radians - explicit b2Rot(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set using an angle in radians. - void Set(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set to the identity rotation - void SetIdentity() - { - s = 0.0f; - c = 1.0f; - } - - /// Get the angle in radians - float32 GetAngle() const - { - return b2Atan2(s, c); - } - - /// Get the x-axis - b2Vec2 GetXAxis() const - { - return b2Vec2(c, s); - } - - /// Get the u-axis - b2Vec2 GetYAxis() const - { - return b2Vec2(-s, c); - } - - /// Sine and cosine - float32 s, c; -}; - -/// A transform contains translation and rotation. It is used to represent -/// the position and orientation of rigid frames. -struct b2Transform -{ - /// The default constructor does nothing. - b2Transform() {} - - /// Initialize using a position vector and a rotation. - b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} - - /// Set this to the identity transform. - void SetIdentity() - { - p.SetZero(); - q.SetIdentity(); - } - - /// Set this based on the position and angle. - void Set(const b2Vec2& position, float32 angle) - { - p = position; - q.Set(angle); - } - - b2Vec2 p; - b2Rot q; -}; - -/// This describes the motion of a body/shape for TOI computation. -/// Shapes are defined with respect to the body origin, which may -/// no coincide with the center of mass. However, to support dynamics -/// we must interpolate the center of mass position. -struct b2Sweep -{ - /// Get the interpolated transform at a specific time. - /// @param beta is a factor in [0,1], where 0 indicates alpha0. - void GetTransform(b2Transform* xfb, float32 beta) const; - - /// Advance the sweep forward, yielding a new initial state. - /// @param alpha the new initial time. - void Advance(float32 alpha); - - /// Normalize the angles. - void Normalize(); - - b2Vec2 localCenter; ///< local center of mass position - b2Vec2 c0, c; ///< center world positions - float32 a0, a; ///< world angles - - /// Fraction of the current time step in the range [0,1] - /// c0 and a0 are the positions at alpha0. - float32 alpha0; -}; - -/// Useful constant -extern const b2Vec2 b2Vec2_zero; - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.x + a.y * b.y; -} - -/// Perform the cross product on two vectors. In 2D this produces a scalar. -inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.y - a.y * b.x; -} - -/// Perform the cross product on a vector and a scalar. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) -{ - return b2Vec2(s * a.y, -s * a.x); -} - -/// Perform the cross product on a scalar and a vector. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) -{ - return b2Vec2(-s * a.y, s * a.x); -} - -/// Multiply a matrix times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another. -inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply a matrix transpose times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another (inverse transform). -inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); -} - -/// Add two vectors component-wise. -inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x + b.x, a.y + b.y); -} - -/// Subtract two vectors component-wise. -inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x - b.x, a.y - b.y); -} - -inline b2Vec2 operator * (float32 s, const b2Vec2& a) -{ - return b2Vec2(s * a.x, s * a.y); -} - -inline bool operator == (const b2Vec2& a, const b2Vec2& b) -{ - return a.x == b.x && a.y == b.y; -} - -inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return c.Length(); -} - -inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return b2Dot(c, c); -} - -inline b2Vec3 operator * (float32 s, const b2Vec3& a) -{ - return b2Vec3(s * a.x, s * a.y, s * a.z); -} - -/// Add two vectors component-wise. -inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); -} - -/// Subtract two vectors component-wise. -inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); -} - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -/// Perform the cross product on two vectors. -inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); -} - -inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(A.ex + B.ex, A.ey + B.ey); -} - -// A * B -inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); -} - -// A^T * B -inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) -{ - b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); - b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); - return b2Mat22(c1, c2); -} - -/// Multiply a matrix times a vector. -inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) -{ - return v.x * A.ex + v.y * A.ey + v.z * A.ez; -} - -/// Multiply a matrix times a vector. -inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply two rotations: q * r -inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) -{ - // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] - // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] - // s = qs * rc + qc * rs - // c = qc * rc - qs * rs - b2Rot qr; - qr.s = q.s * r.c + q.c * r.s; - qr.c = q.c * r.c - q.s * r.s; - return qr; -} - -/// Transpose multiply two rotations: qT * r -inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) -{ - // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] - // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] - // s = qc * rs - qs * rc - // c = qc * rc + qs * rs - b2Rot qr; - qr.s = q.c * r.s - q.s * r.c; - qr.c = q.c * r.c + q.s * r.s; - return qr; -} - -/// Rotate a vector -inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); -} - -/// Inverse rotate a vector -inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); -} - -inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) -{ - float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; - float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; - - return b2Vec2(x, y); -} - -inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) -{ - float32 px = v.x - T.p.x; - float32 py = v.y - T.p.y; - float32 x = (T.q.c * px + T.q.s * py); - float32 y = (-T.q.s * px + T.q.c * py); - - return b2Vec2(x, y); -} - -// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p -// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p -inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2Mul(A.q, B.q); - C.p = b2Mul(A.q, B.p) + A.p; - return C; -} - -// v2 = A.q' * (B.q * v1 + B.p - A.p) -// = A.q' * B.q * v1 + A.q' * (B.p - A.p) -inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2MulT(A.q, B.q); - C.p = b2MulT(A.q, B.p - A.p); - return C; -} - -template -inline T b2Abs(T a) -{ - return a > T(0) ? a : -a; -} - -inline b2Vec2 b2Abs(const b2Vec2& a) -{ - return b2Vec2(b2Abs(a.x), b2Abs(a.y)); -} - -inline b2Mat22 b2Abs(const b2Mat22& A) -{ - return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); -} - -template -inline T b2Min(T a, T b) -{ - return a < b ? a : b; -} - -inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); -} - -template -inline T b2Max(T a, T b) -{ - return a > b ? a : b; -} - -inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); -} - -template -inline T b2Clamp(T a, T low, T high) -{ - return b2Max(low, b2Min(a, high)); -} - -inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) -{ - return b2Max(low, b2Min(a, high)); -} - -template inline void b2Swap(T& a, T& b) -{ - T tmp = a; - a = b; - b = tmp; -} - -/// "Next Largest Power of 2 -/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm -/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with -/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next -/// largest power of 2. For a 32-bit value:" -inline uint32 b2NextPowerOfTwo(uint32 x) -{ - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - return x + 1; -} - -inline bool b2IsPowerOfTwo(uint32 x) -{ - bool result = x > 0 && (x & (x - 1)) == 0; - return result; -} - -inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const -{ - xf->p = (1.0f - beta) * c0 + beta * c; - float32 angle = (1.0f - beta) * a0 + beta * a; - xf->q.Set(angle); - - // Shift to origin - xf->p -= b2Mul(xf->q, localCenter); -} - -inline void b2Sweep::Advance(float32 alpha) -{ - b2Assert(alpha0 < 1.0f); - float32 beta = (alpha - alpha0) / (1.0f - alpha0); - c0 = (1.0f - beta) * c0 + beta * c; - a0 = (1.0f - beta) * a0 + beta * a; - alpha0 = alpha; -} - -/// Normalize an angle in radians to be between -pi and pi -inline void b2Sweep::Normalize() -{ - float32 twoPi = 2.0f * b2_pi; - float32 d = twoPi * floorf(a0 / twoPi); - a0 -= d; - a -= d; -} - -#endif diff --git a/external/Box2D/Common/b2Settings.cpp b/external/Box2D/Common/b2Settings.cpp deleted file mode 100644 index 84d6f1d0e4..0000000000 --- a/external/Box2D/Common/b2Settings.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#ifdef SHP -#include -#include -#include -#include -#else -#include -#include -#include -#endif - - -using namespace std; - - -b2Version b2_version = {2, 2, 1}; - -// Memory allocators. Modify these to use your own allocator. -void* b2Alloc(int32 size) -{ - return malloc(size); -} - -void b2Free(void* mem) -{ - free(mem); -} - -// You can modify this to use your logging facility. -void b2Log(const char* string, ...) -{ -#if defined(SHP) - #ifdef _DEBUG - __App_info(__PRETTY_FUNCTION__ , __LINE__, string); - #endif -#else - va_list args; - va_start(args, string); - vprintf(string, args); - va_end(args); -#endif -} diff --git a/external/Box2D/Common/b2Settings.h b/external/Box2D/Common/b2Settings.h deleted file mode 100644 index aaf4b12ccf..0000000000 --- a/external/Box2D/Common/b2Settings.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_SETTINGS_H -#define B2_SETTINGS_H - -#include -#include - -#define B2_NOT_USED(x) ((void)(x)) -#define b2Assert(A) assert(A) - -typedef signed char int8; -typedef signed short int16; -typedef signed int int32; -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; -typedef float float32; -typedef double float64; - -#define b2_maxFloat FLT_MAX -#define b2_epsilon FLT_EPSILON -#define b2_pi 3.14159265359f - -/// @file -/// Global tuning constants based on meters-kilograms-seconds (MKS) units. -/// - -// Collision - -/// The maximum number of contact points between two convex shapes. Do -/// not change this value. -#define b2_maxManifoldPoints 2 - -/// The maximum number of vertices on a convex polygon. You cannot increase -/// this too much because b2BlockAllocator has a maximum object size. -#define b2_maxPolygonVertices 8 - -/// This is used to fatten AABBs in the dynamic tree. This allows proxies -/// to move by a small amount without triggering a tree adjustment. -/// This is in meters. -#define b2_aabbExtension 0.1f - -/// This is used to fatten AABBs in the dynamic tree. This is used to predict -/// the future position based on the current displacement. -/// This is a dimensionless multiplier. -#define b2_aabbMultiplier 2.0f - -/// A small length used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_linearSlop 0.005f - -/// A small angle used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_angularSlop (2.0f / 180.0f * b2_pi) - -/// The radius of the polygon/edge shape skin. This should not be modified. Making -/// this smaller means polygons will have an insufficient buffer for continuous collision. -/// Making it larger may create artifacts for vertex collision. -#define b2_polygonRadius (2.0f * b2_linearSlop) - -/// Maximum number of sub-steps per contact in continuous physics simulation. -#define b2_maxSubSteps 8 - - -// Dynamics - -/// Maximum number of contacts to be handled to solve a TOI impact. -#define b2_maxTOIContacts 32 - -/// A velocity threshold for elastic collisions. Any collision with a relative linear -/// velocity below this threshold will be treated as inelastic. -#define b2_velocityThreshold 1.0f - -/// The maximum linear position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxLinearCorrection 0.2f - -/// The maximum angular position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) - -/// The maximum linear velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxTranslation 2.0f -#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) - -/// The maximum angular velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxRotation (0.5f * b2_pi) -#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) - -/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so -/// that overlap is removed in one time step. However using values close to 1 often lead -/// to overshoot. -#define b2_baumgarte 0.2f -#define b2_toiBaugarte 0.75f - - -// Sleep - -/// The time that a body must be still before it will go to sleep. -#define b2_timeToSleep 0.5f - -/// A body cannot sleep if its linear velocity is above this tolerance. -#define b2_linearSleepTolerance 0.01f - -/// A body cannot sleep if its angular velocity is above this tolerance. -#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) - -// Memory Allocation - -/// Implement this function to use your own memory allocator. -void* b2Alloc(int32 size); - -/// If you implement b2Alloc, you should also implement this function. -void b2Free(void* mem); - -/// Logging function. -void b2Log(const char* string, ...); - -/// Version numbering scheme. -/// See http://en.wikipedia.org/wiki/Software_versioning -struct b2Version -{ - int32 major; ///< significant changes - int32 minor; ///< incremental changes - int32 revision; ///< bug fixes -}; - -/// Current version. -extern b2Version b2_version; - -#endif diff --git a/external/Box2D/Common/b2StackAllocator.cpp b/external/Box2D/Common/b2StackAllocator.cpp deleted file mode 100644 index 3caa5d9127..0000000000 --- a/external/Box2D/Common/b2StackAllocator.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2StackAllocator::b2StackAllocator() -{ - m_index = 0; - m_allocation = 0; - m_maxAllocation = 0; - m_entryCount = 0; -} - -b2StackAllocator::~b2StackAllocator() -{ - b2Assert(m_index == 0); - b2Assert(m_entryCount == 0); -} - -void* b2StackAllocator::Allocate(int32 size) -{ - b2Assert(m_entryCount < b2_maxStackEntries); - - b2StackEntry* entry = m_entries + m_entryCount; - entry->size = size; - if (m_index + size > b2_stackSize) - { - entry->data = (char*)b2Alloc(size); - entry->usedMalloc = true; - } - else - { - entry->data = m_data + m_index; - entry->usedMalloc = false; - m_index += size; - } - - m_allocation += size; - m_maxAllocation = b2Max(m_maxAllocation, m_allocation); - ++m_entryCount; - - return entry->data; -} - -void b2StackAllocator::Free(void* p) -{ - b2Assert(m_entryCount > 0); - b2StackEntry* entry = m_entries + m_entryCount - 1; - b2Assert(p == entry->data); - if (entry->usedMalloc) - { - b2Free(p); - } - else - { - m_index -= entry->size; - } - m_allocation -= entry->size; - --m_entryCount; - - p = NULL; -} - -int32 b2StackAllocator::GetMaxAllocation() const -{ - return m_maxAllocation; -} diff --git a/external/Box2D/Common/b2StackAllocator.h b/external/Box2D/Common/b2StackAllocator.h deleted file mode 100644 index 6140d0d802..0000000000 --- a/external/Box2D/Common/b2StackAllocator.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_STACK_ALLOCATOR_H -#define B2_STACK_ALLOCATOR_H - -#include - -const int32 b2_stackSize = 100 * 1024; // 100k -const int32 b2_maxStackEntries = 32; - -struct b2StackEntry -{ - char* data; - int32 size; - bool usedMalloc; -}; - -// This is a stack allocator used for fast per step allocations. -// You must nest allocate/free pairs. The code will assert -// if you try to interleave multiple allocate/free pairs. -class b2StackAllocator -{ -public: - b2StackAllocator(); - ~b2StackAllocator(); - - void* Allocate(int32 size); - void Free(void* p); - - int32 GetMaxAllocation() const; - -private: - - char m_data[b2_stackSize]; - int32 m_index; - - int32 m_allocation; - int32 m_maxAllocation; - - b2StackEntry m_entries[b2_maxStackEntries]; - int32 m_entryCount; -}; - -#endif diff --git a/external/Box2D/Common/b2Timer.cpp b/external/Box2D/Common/b2Timer.cpp deleted file mode 100644 index b2bee94513..0000000000 --- a/external/Box2D/Common/b2Timer.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -#if defined(_WIN32) && !defined(SHP) - -float64 b2Timer::s_invFrequency = 0.0f; - -#include - -b2Timer::b2Timer() -{ - LARGE_INTEGER largeInteger; - - if (s_invFrequency == 0.0f) - { - QueryPerformanceFrequency(&largeInteger); - s_invFrequency = float64(largeInteger.QuadPart); - if (s_invFrequency > 0.0f) - { - s_invFrequency = 1000.0f / s_invFrequency; - } - } - - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -void b2Timer::Reset() -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -float32 b2Timer::GetMilliseconds() const -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - float64 count = float64(largeInteger.QuadPart); - float32 ms = float32(s_invFrequency * (count - m_start)); - return ms; -} - -#elif defined(__linux__) || defined (__APPLE__) - -#include - -b2Timer::b2Timer() -{ - Reset(); -} - -void b2Timer::Reset() -{ - timeval t; - gettimeofday(&t, 0); - m_start_sec = t.tv_sec; - m_start_msec = t.tv_usec * 0.001f; -} - -float32 b2Timer::GetMilliseconds() const -{ - timeval t; - gettimeofday(&t, 0); - return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; -} - -#else - -b2Timer::b2Timer() -{ -} - -void b2Timer::Reset() -{ -} - -float32 b2Timer::GetMilliseconds() const -{ - return 0.0f; -} - -#endif diff --git a/external/Box2D/Common/b2Timer.h b/external/Box2D/Common/b2Timer.h deleted file mode 100644 index 053a107a56..0000000000 --- a/external/Box2D/Common/b2Timer.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -/// Timer for profiling. This has platform specific code and may -/// not work on every platform. -class b2Timer -{ -public: - - /// Constructor - b2Timer(); - - /// Reset the timer. - void Reset(); - - /// Get the time since construction or the last reset. - float32 GetMilliseconds() const; - -private: - -#if defined(_WIN32) - float64 m_start; - static float64 s_invFrequency; -#elif defined(__linux__) || defined (__APPLE__) - unsigned long m_start_sec; - unsigned long m_start_msec; -#endif -}; diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp deleted file mode 100644 index 4ae4c41cd3..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); - return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); - allocator->Free(contact, sizeof(b2ChainAndCircleContact)); -} - -b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndCircle( manifold, &edge, xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h deleted file mode 100644 index 1cf601a61f..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H -#define B2_CHAIN_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2ChainAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp deleted file mode 100644 index 8116c34d1b..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); - return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); - allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); -} - -b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndPolygon( manifold, &edge, xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h deleted file mode 100644 index 381c49b844..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H -#define B2_CHAIN_AND_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2ChainAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp deleted file mode 100644 index 2436da5132..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2CircleContact)); - return new (mem) b2CircleContact(fixtureA, fixtureB); -} - -void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2CircleContact*)contact)->~b2CircleContact(); - allocator->Free(contact, sizeof(b2CircleContact)); -} - -b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideCircles(manifold, - (b2CircleShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.h b/external/Box2D/Dynamics/Contacts/b2CircleContact.h deleted file mode 100644 index 6da056ae0d..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2CircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CIRCLE_CONTACT_H -#define B2_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2CircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2CircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.cpp b/external/Box2D/Dynamics/Contacts/b2Contact.cpp deleted file mode 100644 index 2389af6434..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2Contact.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; -bool b2Contact::s_initialized = false; - -void b2Contact::InitializeRegisters() -{ - AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); - AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); - AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); - AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); - AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); - AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); - AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); -} - -void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, - b2Shape::Type type1, b2Shape::Type type2) -{ - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - s_registers[type1][type2].createFcn = createFcn; - s_registers[type1][type2].destroyFcn = destoryFcn; - s_registers[type1][type2].primary = true; - - if (type1 != type2) - { - s_registers[type2][type1].createFcn = createFcn; - s_registers[type2][type1].destroyFcn = destoryFcn; - s_registers[type2][type1].primary = false; - } -} - -b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - if (s_initialized == false) - { - InitializeRegisters(); - s_initialized = true; - } - - b2Shape::Type type1 = fixtureA->GetType(); - b2Shape::Type type2 = fixtureB->GetType(); - - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; - if (createFcn) - { - if (s_registers[type1][type2].primary) - { - return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); - } - else - { - return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); - } - } - else - { - return NULL; - } -} - -void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - b2Assert(s_initialized == true); - - if (contact->m_manifold.pointCount > 0) - { - contact->GetFixtureA()->GetBody()->SetAwake(true); - contact->GetFixtureB()->GetBody()->SetAwake(true); - } - - b2Shape::Type typeA = contact->GetFixtureA()->GetType(); - b2Shape::Type typeB = contact->GetFixtureB()->GetType(); - - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - - b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; - destroyFcn(contact, allocator); -} - -b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) -{ - m_flags = e_enabledFlag; - - m_fixtureA = fA; - m_fixtureB = fB; - - m_indexA = indexA; - m_indexB = indexB; - - m_manifold.pointCount = 0; - - m_prev = NULL; - m_next = NULL; - - m_nodeA.contact = NULL; - m_nodeA.prev = NULL; - m_nodeA.next = NULL; - m_nodeA.other = NULL; - - m_nodeB.contact = NULL; - m_nodeB.prev = NULL; - m_nodeB.next = NULL; - m_nodeB.other = NULL; - - m_toiCount = 0; - - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); -} - -// Update the contact manifold and touching status. -// Note: do not assume the fixture AABBs are overlapping or are valid. -void b2Contact::Update(b2ContactListener* listener) -{ - b2Manifold oldManifold = m_manifold; - - // Re-enable this contact. - m_flags |= e_enabledFlag; - - bool touching = false; - bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; - - bool sensorA = m_fixtureA->IsSensor(); - bool sensorB = m_fixtureB->IsSensor(); - bool sensor = sensorA || sensorB; - - b2Body* bodyA = m_fixtureA->GetBody(); - b2Body* bodyB = m_fixtureB->GetBody(); - const b2Transform& xfA = bodyA->GetTransform(); - const b2Transform& xfB = bodyB->GetTransform(); - - // Is this contact a sensor? - if (sensor) - { - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); - - // Sensors don't generate manifolds. - m_manifold.pointCount = 0; - } - else - { - Evaluate(&m_manifold, xfA, xfB); - touching = m_manifold.pointCount > 0; - - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp2 = m_manifold.points + i; - mp2->normalImpulse = 0.0f; - mp2->tangentImpulse = 0.0f; - b2ContactID id2 = mp2->id; - - for (int32 j = 0; j < oldManifold.pointCount; ++j) - { - b2ManifoldPoint* mp1 = oldManifold.points + j; - - if (mp1->id.key == id2.key) - { - mp2->normalImpulse = mp1->normalImpulse; - mp2->tangentImpulse = mp1->tangentImpulse; - break; - } - } - } - - if (touching != wasTouching) - { - bodyA->SetAwake(true); - bodyB->SetAwake(true); - } - } - - if (touching) - { - m_flags |= e_touchingFlag; - } - else - { - m_flags &= ~e_touchingFlag; - } - - if (wasTouching == false && touching == true && listener) - { - listener->BeginContact(this); - } - - if (wasTouching == true && touching == false && listener) - { - listener->EndContact(this); - } - - if (sensor == false && touching && listener) - { - listener->PreSolve(this, &oldManifold); - } -} diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.h b/external/Box2D/Dynamics/Contacts/b2Contact.h deleted file mode 100644 index 20d9403ce7..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2Contact.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_H -#define B2_CONTACT_H - -#include -#include -#include -#include - -class b2Body; -class b2Contact; -class b2Fixture; -class b2World; -class b2BlockAllocator; -class b2StackAllocator; -class b2ContactListener; - -/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. -/// For example, anything slides on ice. -inline float32 b2MixFriction(float32 friction1, float32 friction2) -{ - return std::sqrt(friction1 * friction2); -} - -/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. -/// For example, a superball bounces on anything. -inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) -{ - return restitution1 > restitution2 ? restitution1 : restitution2; -} - -typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, - b2BlockAllocator* allocator); -typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); - -struct b2ContactRegister -{ - b2ContactCreateFcn* createFcn; - b2ContactDestroyFcn* destroyFcn; - bool primary; -}; - -/// A contact edge is used to connect bodies and contacts together -/// in a contact graph where each body is a node and each contact -/// is an edge. A contact edge belongs to a doubly linked list -/// maintained in each attached body. Each contact has two contact -/// nodes, one for each attached body. -struct b2ContactEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Contact* contact; ///< the contact - b2ContactEdge* prev; ///< the previous contact edge in the body's contact list - b2ContactEdge* next; ///< the next contact edge in the body's contact list -}; - -/// The class manages contact between two shapes. A contact exists for each overlapping -/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist -/// that has no contact points. -class b2Contact -{ -public: - - /// Get the contact manifold. Do not modify the manifold unless you understand the - /// internals of Box2D. - b2Manifold* GetManifold(); - const b2Manifold* GetManifold() const; - - /// Get the world manifold. - void GetWorldManifold(b2WorldManifold* worldManifold) const; - - /// Is this contact touching? - bool IsTouching() const; - - /// Enable/disable this contact. This can be used inside the pre-solve - /// contact listener. The contact is only disabled for the current - /// time step (or sub-step in continuous collisions). - void SetEnabled(bool flag); - - /// Has this contact been disabled? - bool IsEnabled() const; - - /// Get the next contact in the world's contact list. - b2Contact* GetNext(); - const b2Contact* GetNext() const; - - /// Get fixture A in this contact. - b2Fixture* GetFixtureA(); - const b2Fixture* GetFixtureA() const; - - /// Get the child primitive index for fixture A. - int32 GetChildIndexA() const; - - /// Get fixture B in this contact. - b2Fixture* GetFixtureB(); - const b2Fixture* GetFixtureB() const; - - /// Get the child primitive index for fixture B. - int32 GetChildIndexB() const; - - /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. - /// This value persists until set or reset. - void SetFriction(float32 friction); - - /// Get the friction. - float32 GetFriction() const; - - /// Reset the friction mixture to the default value. - void ResetFriction(); - - /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. - /// The value persists until you set or reset. - void SetRestitution(float32 restitution); - - /// Get the restitution. - float32 GetRestitution() const; - - /// Reset the restitution to the default value. - void ResetRestitution(); - - /// Evaluate this contact with your own manifold and transforms. - virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; - -protected: - friend class b2ContactManager; - friend class b2World; - friend class b2ContactSolver; - friend class b2Body; - friend class b2Fixture; - - // Flags stored in m_flags - enum - { - // Used when crawling contact graph when forming islands. - e_islandFlag = 0x0001, - - // Set when the shapes are touching. - e_touchingFlag = 0x0002, - - // This contact can be disabled (by user) - e_enabledFlag = 0x0004, - - // This contact needs filtering because a fixture filter was changed. - e_filterFlag = 0x0008, - - // This bullet contact had a TOI event - e_bulletHitFlag = 0x0010, - - // This contact has a valid TOI in m_toi - e_toiFlag = 0x0020 - }; - - /// Flag this contact for filtering. Filtering will occur the next time step. - void FlagForFiltering(); - - static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, - b2Shape::Type typeA, b2Shape::Type typeB); - static void InitializeRegisters(); - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} - b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - virtual ~b2Contact() {} - - void Update(b2ContactListener* listener); - - static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; - static bool s_initialized; - - uint32 m_flags; - - // World pool and list pointers. - b2Contact* m_prev; - b2Contact* m_next; - - // Nodes for connecting bodies. - b2ContactEdge m_nodeA; - b2ContactEdge m_nodeB; - - b2Fixture* m_fixtureA; - b2Fixture* m_fixtureB; - - int32 m_indexA; - int32 m_indexB; - - b2Manifold m_manifold; - - int32 m_toiCount; - float32 m_toi; - - float32 m_friction; - float32 m_restitution; -}; - -inline b2Manifold* b2Contact::GetManifold() -{ - return &m_manifold; -} - -inline const b2Manifold* b2Contact::GetManifold() const -{ - return &m_manifold; -} - -inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const -{ - const b2Body* bodyA = m_fixtureA->GetBody(); - const b2Body* bodyB = m_fixtureB->GetBody(); - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - - worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); -} - -inline void b2Contact::SetEnabled(bool flag) -{ - if (flag) - { - m_flags |= e_enabledFlag; - } - else - { - m_flags &= ~e_enabledFlag; - } -} - -inline bool b2Contact::IsEnabled() const -{ - return (m_flags & e_enabledFlag) == e_enabledFlag; -} - -inline bool b2Contact::IsTouching() const -{ - return (m_flags & e_touchingFlag) == e_touchingFlag; -} - -inline b2Contact* b2Contact::GetNext() -{ - return m_next; -} - -inline const b2Contact* b2Contact::GetNext() const -{ - return m_next; -} - -inline b2Fixture* b2Contact::GetFixtureA() -{ - return m_fixtureA; -} - -inline const b2Fixture* b2Contact::GetFixtureA() const -{ - return m_fixtureA; -} - -inline b2Fixture* b2Contact::GetFixtureB() -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexA() const -{ - return m_indexA; -} - -inline const b2Fixture* b2Contact::GetFixtureB() const -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexB() const -{ - return m_indexB; -} - -inline void b2Contact::FlagForFiltering() -{ - m_flags |= e_filterFlag; -} - -inline void b2Contact::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Contact::GetFriction() const -{ - return m_friction; -} - -inline void b2Contact::ResetFriction() -{ - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); -} - -inline void b2Contact::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline float32 b2Contact::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Contact::ResetRestitution() -{ - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); -} - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp deleted file mode 100644 index 0dc740342a..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp +++ /dev/null @@ -1,832 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -#include -#include -#include -#include -#include - -#define B2_DEBUG_SOLVER 0 - -struct b2ContactPositionConstraint -{ - b2Vec2 localPoints[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - b2Vec2 localCenterA, localCenterB; - float32 invIA, invIB; - b2Manifold::Type type; - float32 radiusA, radiusB; - int32 pointCount; -}; - -b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) -{ - m_step = def->step; - m_allocator = def->allocator; - m_count = def->count; - m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); - m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); - m_positions = def->positions; - m_velocities = def->velocities; - m_contacts = def->contacts; - - // Initialize position independent portions of the constraints. - for (int32 i = 0; i < m_count; ++i) - { - b2Contact* contact = m_contacts[i]; - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - b2Shape* shapeA = fixtureA->GetShape(); - b2Shape* shapeB = fixtureB->GetShape(); - float32 radiusA = shapeA->m_radius; - float32 radiusB = shapeB->m_radius; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - b2Manifold* manifold = contact->GetManifold(); - - int32 pointCount = manifold->pointCount; - b2Assert(pointCount > 0); - - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - vc->friction = contact->m_friction; - vc->restitution = contact->m_restitution; - vc->indexA = bodyA->m_islandIndex; - vc->indexB = bodyB->m_islandIndex; - vc->invMassA = bodyA->m_invMass; - vc->invMassB = bodyB->m_invMass; - vc->invIA = bodyA->m_invI; - vc->invIB = bodyB->m_invI; - vc->contactIndex = i; - vc->pointCount = pointCount; - vc->K.SetZero(); - vc->normalMass.SetZero(); - - b2ContactPositionConstraint* pc = m_positionConstraints + i; - pc->indexA = bodyA->m_islandIndex; - pc->indexB = bodyB->m_islandIndex; - pc->invMassA = bodyA->m_invMass; - pc->invMassB = bodyB->m_invMass; - pc->localCenterA = bodyA->m_sweep.localCenter; - pc->localCenterB = bodyB->m_sweep.localCenter; - pc->invIA = bodyA->m_invI; - pc->invIB = bodyB->m_invI; - pc->localNormal = manifold->localNormal; - pc->localPoint = manifold->localPoint; - pc->pointCount = pointCount; - pc->radiusA = radiusA; - pc->radiusB = radiusB; - pc->type = manifold->type; - - for (int32 j = 0; j < pointCount; ++j) - { - b2ManifoldPoint* cp = manifold->points + j; - b2VelocityConstraintPoint* vcp = vc->points + j; - - if (m_step.warmStarting) - { - vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; - vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; - } - else - { - vcp->normalImpulse = 0.0f; - vcp->tangentImpulse = 0.0f; - } - - vcp->rA.SetZero(); - vcp->rB.SetZero(); - vcp->normalMass = 0.0f; - vcp->tangentMass = 0.0f; - vcp->velocityBias = 0.0f; - - pc->localPoints[j] = cp->localPoint; - } - } -} - -b2ContactSolver::~b2ContactSolver() -{ - m_allocator->Free(m_velocityConstraints); - m_allocator->Free(m_positionConstraints); -} - -// Initialize position dependent portions of the velocity constraints. -void b2ContactSolver::InitializeVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - float32 radiusA = pc->radiusA; - float32 radiusB = pc->radiusB; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - - float32 mA = vc->invMassA; - float32 mB = vc->invMassB; - float32 iA = vc->invIA; - float32 iB = vc->invIB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Assert(manifold->pointCount > 0); - - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2WorldManifold worldManifold; - worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); - - vc->normal = worldManifold.normal; - - int32 pointCount = vc->pointCount; - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - vcp->rA = worldManifold.points[j] - cA; - vcp->rB = worldManifold.points[j] - cB; - - float32 rnA = b2Cross(vcp->rA, vc->normal); - float32 rnB = b2Cross(vcp->rB, vc->normal); - - float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - - b2Vec2 tangent = b2Cross(vc->normal, 1.0f); - - float32 rtA = b2Cross(vcp->rA, tangent); - float32 rtB = b2Cross(vcp->rB, tangent); - - float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - - vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; - - // Setup a velocity bias for restitution. - vcp->velocityBias = 0.0f; - float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); - if (vRel < -b2_velocityThreshold) - { - vcp->velocityBias = -vc->restitution * vRel; - } - } - - // If we have two points, then prepare the block solver. - if (vc->pointCount == 2) - { - b2VelocityConstraintPoint* vcp1 = vc->points + 0; - b2VelocityConstraintPoint* vcp2 = vc->points + 1; - - float32 rn1A = b2Cross(vcp1->rA, vc->normal); - float32 rn1B = b2Cross(vcp1->rB, vc->normal); - float32 rn2A = b2Cross(vcp2->rA, vc->normal); - float32 rn2B = b2Cross(vcp2->rB, vc->normal); - - float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; - float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; - float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; - - // Ensure a reasonable condition number. - const float32 k_maxConditionNumber = 1000.0f; - if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) - { - // K is safe to invert. - vc->K.ex.Set(k11, k12); - vc->K.ey.Set(k12, k22); - vc->normalMass = vc->K.GetInverse(); - } - else - { - // The constraints are redundant, just use one. - // TODO_ERIN use deepest? - vc->pointCount = 1; - } - } - } -} - -void b2ContactSolver::WarmStart() -{ - // Warm start. - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; - wA -= iA * b2Cross(vcp->rA, P); - vA -= mA * P; - wB += iB * b2Cross(vcp->rB, P); - vB += mB * P; - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::SolveVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = vc->friction; - - b2Assert(pointCount == 1 || pointCount == 2); - - // Solve tangent constraints first because non-penetration is more important - // than friction. - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute tangent force - float32 vt = b2Dot(dv, tangent); - float32 lambda = vcp->tangentMass * (-vt); - - // b2Clamp the accumulated force - float32 maxFriction = friction * vcp->normalImpulse; - float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - vcp->tangentImpulse; - vcp->tangentImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * tangent; - - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - - // Solve normal constraints - if (vc->pointCount == 1) - { - b2VelocityConstraintPoint* vcp = vc->points + 0; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute normal impulse - float32 vn = b2Dot(dv, normal); - float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); - - // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - vcp->normalImpulse; - vcp->normalImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * normal; - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - else - { - // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). - // Build the mini LCP for this contact patch - // - // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 - // - // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) - // b = vn0 - velocityBias - // - // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i - // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases - // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid - // solution that satisfies the problem is chosen. - // - // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires - // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). - // - // Substitute: - // - // x = a + d - // - // a := old total impulse - // x := new total impulse - // d := incremental impulse - // - // For the current iteration we extend the formula for the incremental impulse - // to compute the new total impulse: - // - // vn = A * d + b - // = A * (x - a) + b - // = A * x + b - A * a - // = A * x + b' - // b' = b - A * a; - - b2VelocityConstraintPoint* cp1 = vc->points + 0; - b2VelocityConstraintPoint* cp2 = vc->points + 1; - - b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); - b2Assert(a.x >= 0.0f && a.y >= 0.0f); - - // Relative velocity at contact - b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - float32 vn1 = b2Dot(dv1, normal); - float32 vn2 = b2Dot(dv2, normal); - - b2Vec2 b; - b.x = vn1 - cp1->velocityBias; - b.y = vn2 - cp2->velocityBias; - - // Compute b' - b -= b2Mul(vc->K, a); - - const float32 k_errorTol = 1e-3f; - B2_NOT_USED(k_errorTol); - - for (;;) - { - // - // Case 1: vn = 0 - // - // 0 = A * x + b' - // - // Solve for x: - // - // x = - inv(A) * b' - // - b2Vec2 x = - b2Mul(vc->normalMass, b); - - if (x.x >= 0.0f && x.y >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 2: vn1 = 0 and x2 = 0 - // - // 0 = a11 * x1 + a12 * 0 + b1' - // vn2 = a21 * x1 + a22 * 0 + b2' - // - x.x = - cp1->normalMass * b.x; - x.y = 0.0f; - vn1 = 0.0f; - vn2 = vc->K.ex.y * x.x + b.y; - - if (x.x >= 0.0f && vn2 >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); -#endif - break; - } - - - // - // Case 3: vn2 = 0 and x1 = 0 - // - // vn1 = a11 * 0 + a12 * x2 + b1' - // 0 = a21 * 0 + a22 * x2 + b2' - // - x.x = 0.0f; - x.y = - cp2->normalMass * b.y; - vn1 = vc->K.ey.x * x.y + b.x; - vn2 = 0.0f; - - if (x.y >= 0.0f && vn1 >= 0.0f) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 4: x1 = 0 and x2 = 0 - // - // vn1 = b1 - // vn2 = b2; - x.x = 0.0f; - x.y = 0.0f; - vn1 = b.x; - vn2 = b.y; - - if (vn1 >= 0.0f && vn2 >= 0.0f ) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - - break; - } - - // No solution, give up. This is hit sometimes, but it doesn't seem to matter. - break; - } - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::StoreImpulses() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - for (int32 j = 0; j < vc->pointCount; ++j) - { - manifold->points[j].normalImpulse = vc->points[j].normalImpulse; - manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; - } - } -} - -struct b2PositionSolverManifold -{ - void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) - { - b2Assert(pc->pointCount > 0); - - switch (pc->type) - { - case b2Manifold::e_circles: - { - b2Vec2 pointA = b2Mul(xfA, pc->localPoint); - b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); - normal = pointB - pointA; - normal.Normalize(); - point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - - // Ensure normal points from A to B - normal = -normal; - } - break; - } - } - - b2Vec2 normal; - b2Vec2 point; - float32 separation; -}; - -// Sequential solver. -bool b2ContactSolver::SolvePositionConstraints() -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - float32 mA = pc->invMassA; - float32 iA = pc->invIA; - b2Vec2 localCenterB = pc->localCenterB; - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - int32 pointCount = pc->pointCount; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -3.0f * b2_linearSlop; -} - -// Sequential position solver for position constraints. -bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - int32 pointCount = pc->pointCount; - - float32 mA = 0.0f; - float32 iA = 0.0f; - if (indexA == toiIndexA || indexA == toiIndexB) - { - mA = pc->invMassA; - iA = pc->invIA; - } - - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - if (indexB == toiIndexA || indexB == toiIndexB) - { - mB = pc->invMassB; - iB = pc->invIB; - } - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; -} diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.h b/external/Box2D/Dynamics/Contacts/b2ContactSolver.h deleted file mode 100644 index aef1987a9e..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2ContactSolver.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_SOLVER_H -#define B2_CONTACT_SOLVER_H - -#include -#include -#include - -class b2Contact; -class b2Body; -class b2StackAllocator; -struct b2ContactPositionConstraint; - -struct b2VelocityConstraintPoint -{ - b2Vec2 rA; - b2Vec2 rB; - float32 normalImpulse; - float32 tangentImpulse; - float32 normalMass; - float32 tangentMass; - float32 velocityBias; -}; - -struct b2ContactVelocityConstraint -{ - b2VelocityConstraintPoint points[b2_maxManifoldPoints]; - b2Vec2 normal; - b2Mat22 normalMass; - b2Mat22 K; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - float32 invIA, invIB; - float32 friction; - float32 restitution; - int32 pointCount; - int32 contactIndex; -}; - -struct b2ContactSolverDef -{ - b2TimeStep step; - b2Contact** contacts; - int32 count; - b2Position* positions; - b2Velocity* velocities; - b2StackAllocator* allocator; -}; - -class b2ContactSolver -{ -public: - b2ContactSolver(b2ContactSolverDef* def); - ~b2ContactSolver(); - - void InitializeVelocityConstraints(); - - void WarmStart(); - void SolveVelocityConstraints(); - void StoreImpulses(); - - bool SolvePositionConstraints(); - bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); - - b2TimeStep m_step; - b2Position* m_positions; - b2Velocity* m_velocities; - b2StackAllocator* m_allocator; - b2ContactPositionConstraint* m_positionConstraints; - b2ContactVelocityConstraint* m_velocityConstraints; - b2Contact** m_contacts; - int m_count; -}; - -#endif - diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp deleted file mode 100644 index aade42880a..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); - return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); -} - -void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); - allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); -} - -b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndCircle( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h deleted file mode 100644 index 70771ec536..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H -#define B2_EDGE_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2EdgeAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp deleted file mode 100644 index 04ce394107..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); - return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); -} - -void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); - allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); -} - -b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndPolygon( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h deleted file mode 100644 index f65f3acca9..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_AND_POLYGON_CONTACT_H -#define B2_EDGE_AND_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2EdgeAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp deleted file mode 100644 index 961b26f38a..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); - return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); -} - -void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); - allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); -} - -b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygonAndCircle( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h deleted file mode 100644 index 7b1a5288b4..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H -#define B2_POLYGON_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2PolygonAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp deleted file mode 100644 index a2884a440d..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonContact)); - return new (mem) b2PolygonContact(fixtureA, fixtureB); -} - -void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonContact*)contact)->~b2PolygonContact(); - allocator->Free(contact, sizeof(b2PolygonContact)); -} - -b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygons( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonContact.h deleted file mode 100644 index 302684232a..0000000000 --- a/external/Box2D/Dynamics/Contacts/b2PolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_CONTACT_H -#define B2_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2PolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp deleted file mode 100644 index b2d4bd006c..0000000000 --- a/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// 1-D constrained system -// m (v2 - v1) = lambda -// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. -// x2 = x1 + h * v2 - -// 1-D mass-damper-spring system -// m (v2 - v1) + h * d * v2 + h * k * - -// C = norm(p2 - p1) - L -// u = (p2 - p1) / norm(p2 - p1) -// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// J = [-u -cross(r1, u) u cross(r2, u)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 - -void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, - const b2Vec2& anchor1, const b2Vec2& anchor2) -{ - bodyA = b1; - bodyB = b2; - localAnchorA = bodyA->GetLocalPoint(anchor1); - localAnchorB = bodyB->GetLocalPoint(anchor2); - b2Vec2 d = anchor2 - anchor1; - length = d.Length(); -} - -b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_length = def->length; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - m_impulse = 0.0f; - m_gamma = 0.0f; - m_bias = 0.0f; -} - -void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - // Handle singularity. - float32 length = m_u.Length(); - if (length > b2_linearSlop) - { - m_u *= 1.0f / length; - } - else - { - m_u.Set(0.0f, 0.0f); - } - - float32 crAu = b2Cross(m_rA, m_u); - float32 crBu = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; - - // Compute the effective mass matrix. - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (m_frequencyHz > 0.0f) - { - float32 C = length - m_length; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m_mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_mass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invMass += m_gamma; - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - } - else - { - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 Cdot = b2Dot(m_u, vpB - vpA); - - float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); - m_impulse += impulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) -{ - if (m_frequencyHz > 0.0f) - { - // There is no position correction for soft distance constraints. - return true; - } - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_length; - C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) < b2_linearSlop; -} - -b2Vec2 b2DistanceJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2DistanceJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -void b2DistanceJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2DistanceJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.length = %.15lef;\n", m_length); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.h b/external/Box2D/Dynamics/Joints/b2DistanceJoint.h deleted file mode 100644 index fc11476ff9..0000000000 --- a/external/Box2D/Dynamics/Joints/b2DistanceJoint.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DISTANCE_JOINT_H -#define B2_DISTANCE_JOINT_H - -#include - -/// Distance joint definition. This requires defining an -/// anchor point on both bodies and the non-zero length of the -/// distance joint. The definition uses local anchor points -/// so that the initial configuration can violate the constraint -/// slightly. This helps when saving and loading a game. -/// @warning Do not use a zero or short length. -struct b2DistanceJointDef : public b2JointDef -{ - b2DistanceJointDef() - { - type = e_distanceJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - length = 1.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and length using the world - /// anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& anchorA, const b2Vec2& anchorB); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The natural length between the anchor points. - float32 length; - - /// The mass-spring-damper frequency in Hertz. A value of 0 - /// disables softness. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A distance joint constrains two points on two bodies -/// to remain at a fixed distance from each other. You can view -/// this as a massless, rigid rod. -class b2DistanceJoint : public b2Joint -{ -public: - - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Get the reaction torque given the inverse time step. - /// Unit is N*m. This is always zero for a distance joint. - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/get the natural length. - /// Manipulating the length can lead to non-physical behavior when the frequency is zero. - void SetLength(float32 length); - float32 GetLength() const; - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2DistanceJoint(const b2DistanceJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_gamma; - float32 m_impulse; - float32 m_length; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -inline void b2DistanceJoint::SetLength(float32 length) -{ - m_length = length; -} - -inline float32 b2DistanceJoint::GetLength() const -{ - return m_length; -} - -inline void b2DistanceJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2DistanceJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -inline void b2DistanceJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2DistanceJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp deleted file mode 100644 index 6e6018db10..0000000000 --- a/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); -} - -b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - - m_maxForce = def->maxForce; - m_maxTorque = def->maxTorque; -} - -void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective mass matrix. - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; - K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - - m_linearMass = K.GetInverse(); - - m_angularMass = iA + iB; - if (m_angularMass > 0.0f) - { - m_angularMass = 1.0f / m_angularMass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_linearImpulse *= data.step.dtRatio; - m_angularImpulse *= data.step.dtRatio; - - b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); - } - else - { - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - float32 h = data.step.dt; - - // Solve angular friction - { - float32 Cdot = wB - wA; - float32 impulse = -m_angularMass * Cdot; - - float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = h * m_maxTorque; - m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_angularImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve linear friction - { - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); - b2Vec2 oldImpulse = m_linearImpulse; - m_linearImpulse += impulse; - - float32 maxImpulse = h * m_maxForce; - - if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_linearImpulse.Normalize(); - m_linearImpulse *= maxImpulse; - } - - impulse = m_linearImpulse - oldImpulse; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - - return true; -} - -b2Vec2 b2FrictionJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2FrictionJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_linearImpulse; -} - -float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_angularImpulse; -} - -void b2FrictionJoint::SetMaxForce(float32 force) -{ - b2Assert(b2IsValid(force) && force >= 0.0f); - m_maxForce = force; -} - -float32 b2FrictionJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2FrictionJoint::SetMaxTorque(float32 torque) -{ - b2Assert(b2IsValid(torque) && torque >= 0.0f); - m_maxTorque = torque; -} - -float32 b2FrictionJoint::GetMaxTorque() const -{ - return m_maxTorque; -} - -void b2FrictionJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2FrictionJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); - b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.h b/external/Box2D/Dynamics/Joints/b2FrictionJoint.h deleted file mode 100644 index 3ee40c6298..0000000000 --- a/external/Box2D/Dynamics/Joints/b2FrictionJoint.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_FRICTION_JOINT_H -#define B2_FRICTION_JOINT_H - -#include - -/// Friction joint definition. -struct b2FrictionJointDef : public b2JointDef -{ - b2FrictionJointDef() - { - type = e_frictionJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - maxForce = 0.0f; - maxTorque = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum friction force in N. - float32 maxForce; - - /// The maximum friction torque in N-m. - float32 maxTorque; -}; - -/// Friction joint. This is used for top-down friction. -/// It provides 2D translational friction and angular friction. -class b2FrictionJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set the maximum friction force in N. - void SetMaxForce(float32 force); - - /// Get the maximum friction force in N. - float32 GetMaxForce() const; - - /// Set the maximum friction torque in N*m. - void SetMaxTorque(float32 torque); - - /// Get the maximum friction torque in N*m. - float32 GetMaxTorque() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - - b2FrictionJoint(const b2FrictionJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - - // Solver shared - b2Vec2 m_linearImpulse; - float32 m_angularImpulse; - float32 m_maxForce; - float32 m_maxTorque; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat22 m_linearMass; - float32 m_angularMass; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.cpp b/external/Box2D/Dynamics/Joints/b2GearJoint.cpp deleted file mode 100644 index 9741cdd5a4..0000000000 --- a/external/Box2D/Dynamics/Joints/b2GearJoint.cpp +++ /dev/null @@ -1,423 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -// Gear Joint: -// C0 = (coordinate1 + ratio * coordinate2)_initial -// C = (coordinate1 + ratio * coordinate2) - C0 = 0 -// J = [J1 ratio * J2] -// K = J * invM * JT -// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T -// -// Revolute: -// coordinate = rotation -// Cdot = angularVelocity -// J = [0 0 1] -// K = J * invM * JT = invI -// -// Prismatic: -// coordinate = dot(p - pg, ug) -// Cdot = dot(v + cross(w, r), ug) -// J = [ug cross(r, ug)] -// K = J * invM * JT = invMass + invI * cross(r, ug)^2 - -b2GearJoint::b2GearJoint(const b2GearJointDef* def) -: b2Joint(def) -{ - m_joint1 = def->joint1; - m_joint2 = def->joint2; - - m_typeA = m_joint1->GetType(); - m_typeB = m_joint2->GetType(); - - b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); - b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); - - float32 coordinateA, coordinateB; - - // TODO_ERIN there might be some problem with the joint edges in b2Joint. - - m_bodyC = m_joint1->GetBodyA(); - m_bodyA = m_joint1->GetBodyB(); - - // Get geometry of joint1 - b2Transform xfA = m_bodyA->m_xf; - float32 aA = m_bodyA->m_sweep.a; - b2Transform xfC = m_bodyC->m_xf; - float32 aC = m_bodyC->m_sweep.a; - - if (m_typeA == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; - m_localAnchorC = revolute->m_localAnchorA; - m_localAnchorA = revolute->m_localAnchorB; - m_referenceAngleA = revolute->m_referenceAngle; - m_localAxisC.SetZero(); - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; - m_localAnchorC = prismatic->m_localAnchorA; - m_localAnchorA = prismatic->m_localAnchorB; - m_referenceAngleA = prismatic->m_referenceAngle; - m_localAxisC = prismatic->m_localXAxisA; - - b2Vec2 pC = m_localAnchorC; - b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - m_bodyD = m_joint2->GetBodyA(); - m_bodyB = m_joint2->GetBodyB(); - - // Get geometry of joint2 - b2Transform xfB = m_bodyB->m_xf; - float32 aB = m_bodyB->m_sweep.a; - b2Transform xfD = m_bodyD->m_xf; - float32 aD = m_bodyD->m_sweep.a; - - if (m_typeB == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; - m_localAnchorD = revolute->m_localAnchorA; - m_localAnchorB = revolute->m_localAnchorB; - m_referenceAngleB = revolute->m_referenceAngle; - m_localAxisD.SetZero(); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; - m_localAnchorD = prismatic->m_localAnchorA; - m_localAnchorB = prismatic->m_localAnchorB; - m_referenceAngleB = prismatic->m_referenceAngle; - m_localAxisD = prismatic->m_localXAxisA; - - b2Vec2 pD = m_localAnchorD; - b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - m_ratio = def->ratio; - - m_constant = coordinateA + m_ratio * coordinateB; - - m_impulse = 0.0f; -} - -void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_indexC = m_bodyC->m_islandIndex; - m_indexD = m_bodyD->m_islandIndex; - m_lcA = m_bodyA->m_sweep.localCenter; - m_lcB = m_bodyB->m_sweep.localCenter; - m_lcC = m_bodyC->m_sweep.localCenter; - m_lcD = m_bodyD->m_sweep.localCenter; - m_mA = m_bodyA->m_invMass; - m_mB = m_bodyB->m_invMass; - m_mC = m_bodyC->m_invMass; - m_mD = m_bodyD->m_invMass; - m_iA = m_bodyA->m_invI; - m_iB = m_bodyB->m_invI; - m_iC = m_bodyC->m_invI; - m_iD = m_bodyD->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - m_mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - m_JvAC.SetZero(); - m_JwA = 1.0f; - m_JwC = 1.0f; - m_mass += m_iA + m_iC; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - m_JvAC = u; - m_JwC = b2Cross(rC, u); - m_JwA = b2Cross(rA, u); - m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; - } - - if (m_typeB == e_revoluteJoint) - { - m_JvBD.SetZero(); - m_JwB = m_ratio; - m_JwD = m_ratio; - m_mass += m_ratio * m_ratio * (m_iB + m_iD); - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - m_JvBD = m_ratio * u; - m_JwD = m_ratio * b2Cross(rD, u); - m_JwB = m_ratio * b2Cross(rB, u); - m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; - } - - // Compute effective mass. - m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; - - if (data.step.warmStarting) - { - vA += (m_mA * m_impulse) * m_JvAC; - wA += m_iA * m_impulse * m_JwA; - vB += (m_mB * m_impulse) * m_JvBD; - wB += m_iB * m_impulse * m_JwB; - vC -= (m_mC * m_impulse) * m_JvAC; - wC -= m_iC * m_impulse * m_JwC; - vD -= (m_mD * m_impulse) * m_JvBD; - wD -= m_iD * m_impulse * m_JwD; - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); - Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); - - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - vA += (m_mA * impulse) * m_JvAC; - wA += m_iA * impulse * m_JwA; - vB += (m_mB * impulse) * m_JvBD; - wB += m_iB * impulse * m_JwB; - vC -= (m_mC * impulse) * m_JvAC; - wC -= m_iC * impulse * m_JwC; - vD -= (m_mD * impulse) * m_JvBD; - wD -= m_iD * impulse * m_JwD; - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - float32 linearError = 0.0f; - - float32 coordinateA, coordinateB; - - b2Vec2 JvAC, JvBD; - float32 JwA, JwB, JwC, JwD; - float32 mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - JvAC.SetZero(); - JwA = 1.0f; - JwC = 1.0f; - mass += m_iA + m_iC; - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - JvAC = u; - JwC = b2Cross(rC, u); - JwA = b2Cross(rA, u); - mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; - - b2Vec2 pC = m_localAnchorC - m_lcC; - b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - if (m_typeB == e_revoluteJoint) - { - JvBD.SetZero(); - JwB = m_ratio; - JwD = m_ratio; - mass += m_ratio * m_ratio * (m_iB + m_iD); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - JvBD = m_ratio * u; - JwD = m_ratio * b2Cross(rD, u); - JwB = m_ratio * b2Cross(rB, u); - mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; - - b2Vec2 pD = m_localAnchorD - m_lcD; - b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; - - float32 impulse = 0.0f; - if (mass > 0.0f) - { - impulse = -C / mass; - } - - cA += m_mA * impulse * JvAC; - aA += m_iA * impulse * JwA; - cB += m_mB * impulse * JvBD; - aB += m_iB * impulse * JwB; - cC -= m_mC * impulse * JvAC; - aC -= m_iC * impulse * JwC; - cD -= m_mD * impulse * JvBD; - aD -= m_iD * impulse * JwD; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - data.positions[m_indexC].c = cC; - data.positions[m_indexC].a = aC; - data.positions[m_indexD].c = cD; - data.positions[m_indexD].a = aD; - - // TODO_ERIN not implemented - return linearError < b2_linearSlop; -} - -b2Vec2 b2GearJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2GearJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_JvAC; - return inv_dt * P; -} - -float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const -{ - float32 L = m_impulse * m_JwA; - return inv_dt * L; -} - -void b2GearJoint::SetRatio(float32 ratio) -{ - b2Assert(b2IsValid(ratio)); - m_ratio = ratio; -} - -float32 b2GearJoint::GetRatio() const -{ - return m_ratio; -} - -void b2GearJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - int32 index1 = m_joint1->m_index; - int32 index2 = m_joint2->m_index; - - b2Log(" b2GearJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.joint1 = joints[%d];\n", index1); - b2Log(" jd.joint2 = joints[%d];\n", index2); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.h b/external/Box2D/Dynamics/Joints/b2GearJoint.h deleted file mode 100644 index f926bf6ef1..0000000000 --- a/external/Box2D/Dynamics/Joints/b2GearJoint.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_GEAR_JOINT_H -#define B2_GEAR_JOINT_H - -#include - -/// Gear joint definition. This definition requires two existing -/// revolute or prismatic joints (any combination will work). -struct b2GearJointDef : public b2JointDef -{ - b2GearJointDef() - { - type = e_gearJoint; - joint1 = NULL; - joint2 = NULL; - ratio = 1.0f; - } - - /// The first revolute/prismatic joint attached to the gear joint. - b2Joint* joint1; - - /// The second revolute/prismatic joint attached to the gear joint. - b2Joint* joint2; - - /// The gear ratio. - /// @see b2GearJoint for explanation. - float32 ratio; -}; - -/// A gear joint is used to connect two joints together. Either joint -/// can be a revolute or prismatic joint. You specify a gear ratio -/// to bind the motions together: -/// coordinate1 + ratio * coordinate2 = constant -/// The ratio can be negative or positive. If one joint is a revolute joint -/// and the other joint is a prismatic joint, then the ratio will have units -/// of length or units of 1/length. -/// @warning You have to manually destroy the gear joint if joint1 or joint2 -/// is destroyed. -class b2GearJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the first joint. - b2Joint* GetJoint1() { return m_joint1; } - - /// Get the second joint. - b2Joint* GetJoint2() { return m_joint2; } - - /// Set/Get the gear ratio. - void SetRatio(float32 ratio); - float32 GetRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2GearJoint(const b2GearJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Joint* m_joint1; - b2Joint* m_joint2; - - b2JointType m_typeA; - b2JointType m_typeB; - - // Body A is connected to body C - // Body B is connected to body D - b2Body* m_bodyC; - b2Body* m_bodyD; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localAnchorC; - b2Vec2 m_localAnchorD; - - b2Vec2 m_localAxisC; - b2Vec2 m_localAxisD; - - float32 m_referenceAngleA; - float32 m_referenceAngleB; - - float32 m_constant; - float32 m_ratio; - - float32 m_impulse; - - // Solver temp - int32 m_indexA, m_indexB, m_indexC, m_indexD; - b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; - float32 m_mA, m_mB, m_mC, m_mD; - float32 m_iA, m_iB, m_iC, m_iD; - b2Vec2 m_JvAC, m_JvBD; - float32 m_JwA, m_JwB, m_JwC, m_JwD; - float32 m_mass; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2Joint.cpp b/external/Box2D/Dynamics/Joints/b2Joint.cpp deleted file mode 100644 index 6853b09f0b..0000000000 --- a/external/Box2D/Dynamics/Joints/b2Joint.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) -{ - b2Joint* joint = NULL; - - switch (def->type) - { - case e_distanceJoint: - { - void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); - joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def); - } - break; - - case e_mouseJoint: - { - void* mem = allocator->Allocate(sizeof(b2MouseJoint)); - joint = new (mem) b2MouseJoint((b2MouseJointDef*)def); - } - break; - - case e_prismaticJoint: - { - void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); - joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def); - } - break; - - case e_revoluteJoint: - { - void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); - joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def); - } - break; - - case e_pulleyJoint: - { - void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); - joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def); - } - break; - - case e_gearJoint: - { - void* mem = allocator->Allocate(sizeof(b2GearJoint)); - joint = new (mem) b2GearJoint((b2GearJointDef*)def); - } - break; - - case e_wheelJoint: - { - void* mem = allocator->Allocate(sizeof(b2WheelJoint)); - joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); - } - break; - - case e_weldJoint: - { - void* mem = allocator->Allocate(sizeof(b2WeldJoint)); - joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); - } - break; - - case e_frictionJoint: - { - void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); - joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); - } - break; - - case e_ropeJoint: - { - void* mem = allocator->Allocate(sizeof(b2RopeJoint)); - joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); - } - break; - - default: - b2Assert(false); - break; - } - - return joint; -} - -void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) -{ - joint->~b2Joint(); - switch (joint->m_type) - { - case e_distanceJoint: - allocator->Free(joint, sizeof(b2DistanceJoint)); - break; - - case e_mouseJoint: - allocator->Free(joint, sizeof(b2MouseJoint)); - break; - - case e_prismaticJoint: - allocator->Free(joint, sizeof(b2PrismaticJoint)); - break; - - case e_revoluteJoint: - allocator->Free(joint, sizeof(b2RevoluteJoint)); - break; - - case e_pulleyJoint: - allocator->Free(joint, sizeof(b2PulleyJoint)); - break; - - case e_gearJoint: - allocator->Free(joint, sizeof(b2GearJoint)); - break; - - case e_wheelJoint: - allocator->Free(joint, sizeof(b2WheelJoint)); - break; - - case e_weldJoint: - allocator->Free(joint, sizeof(b2WeldJoint)); - break; - - case e_frictionJoint: - allocator->Free(joint, sizeof(b2FrictionJoint)); - break; - - case e_ropeJoint: - allocator->Free(joint, sizeof(b2RopeJoint)); - break; - - default: - b2Assert(false); - break; - } -} - -b2Joint::b2Joint(const b2JointDef* def) -{ - b2Assert(def->bodyA != def->bodyB); - - m_type = def->type; - m_prev = NULL; - m_next = NULL; - m_bodyA = def->bodyA; - m_bodyB = def->bodyB; - m_index = 0; - m_collideConnected = def->collideConnected; - m_islandFlag = false; - m_userData = def->userData; - - m_edgeA.joint = NULL; - m_edgeA.other = NULL; - m_edgeA.prev = NULL; - m_edgeA.next = NULL; - - m_edgeB.joint = NULL; - m_edgeB.other = NULL; - m_edgeB.prev = NULL; - m_edgeB.next = NULL; -} - -bool b2Joint::IsActive() const -{ - return m_bodyA->IsActive() && m_bodyB->IsActive(); -} diff --git a/external/Box2D/Dynamics/Joints/b2Joint.h b/external/Box2D/Dynamics/Joints/b2Joint.h deleted file mode 100644 index b4ea576665..0000000000 --- a/external/Box2D/Dynamics/Joints/b2Joint.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_JOINT_H -#define B2_JOINT_H - -#include - -class b2Body; -class b2Joint; -struct b2SolverData; -class b2BlockAllocator; - -enum b2JointType -{ - e_unknownJoint, - e_revoluteJoint, - e_prismaticJoint, - e_distanceJoint, - e_pulleyJoint, - e_mouseJoint, - e_gearJoint, - e_wheelJoint, - e_weldJoint, - e_frictionJoint, - e_ropeJoint -}; - -enum b2LimitState -{ - e_inactiveLimit, - e_atLowerLimit, - e_atUpperLimit, - e_equalLimits -}; - -struct b2Jacobian -{ - b2Vec2 linear; - float32 angularA; - float32 angularB; -}; - -/// A joint edge is used to connect bodies and joints together -/// in a joint graph where each body is a node and each joint -/// is an edge. A joint edge belongs to a doubly linked list -/// maintained in each attached body. Each joint has two joint -/// nodes, one for each attached body. -struct b2JointEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Joint* joint; ///< the joint - b2JointEdge* prev; ///< the previous joint edge in the body's joint list - b2JointEdge* next; ///< the next joint edge in the body's joint list -}; - -/// Joint definitions are used to construct joints. -struct b2JointDef -{ - b2JointDef() - { - type = e_unknownJoint; - userData = NULL; - bodyA = NULL; - bodyB = NULL; - collideConnected = false; - } - - /// The joint type is set automatically for concrete joint types. - b2JointType type; - - /// Use this to attach application specific data to your joints. - void* userData; - - /// The first attached body. - b2Body* bodyA; - - /// The second attached body. - b2Body* bodyB; - - /// Set this flag to true if the attached bodies should collide. - bool collideConnected; -}; - -/// The base joint class. Joints are used to constraint two bodies together in -/// various fashions. Some joints also feature limits and motors. -class b2Joint -{ -public: - - /// Get the type of the concrete joint. - b2JointType GetType() const; - - /// Get the first body attached to this joint. - b2Body* GetBodyA(); - - /// Get the second body attached to this joint. - b2Body* GetBodyB(); - - /// Get the anchor point on bodyA in world coordinates. - virtual b2Vec2 GetAnchorA() const = 0; - - /// Get the anchor point on bodyB in world coordinates. - virtual b2Vec2 GetAnchorB() const = 0; - - /// Get the reaction force on bodyB at the joint anchor in Newtons. - virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - - /// Get the reaction torque on bodyB in N*m. - virtual float32 GetReactionTorque(float32 inv_dt) const = 0; - - /// Get the next joint the world joint list. - b2Joint* GetNext(); - const b2Joint* GetNext() const; - - /// Get the user data pointer. - void* GetUserData() const; - - /// Set the user data pointer. - void SetUserData(void* data); - - /// Short-cut function to determine if either body is inactive. - bool IsActive() const; - - /// Get collide connected. - /// Note: modifying the collide connect flag won't work correctly because - /// the flag is only checked when fixture AABBs begin to overlap. - bool GetCollideConnected() const; - - /// Dump this joint to the log file. - virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } - -protected: - friend class b2World; - friend class b2Body; - friend class b2Island; - friend class b2GearJoint; - - static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); - static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); - - b2Joint(const b2JointDef* def); - virtual ~b2Joint() {} - - virtual void InitVelocityConstraints(const b2SolverData& data) = 0; - virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; - - // This returns true if the position errors are within tolerance. - virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; - - b2JointType m_type; - b2Joint* m_prev; - b2Joint* m_next; - b2JointEdge m_edgeA; - b2JointEdge m_edgeB; - b2Body* m_bodyA; - b2Body* m_bodyB; - - int32 m_index; - - bool m_islandFlag; - bool m_collideConnected; - - void* m_userData; -}; - -inline b2JointType b2Joint::GetType() const -{ - return m_type; -} - -inline b2Body* b2Joint::GetBodyA() -{ - return m_bodyA; -} - -inline b2Body* b2Joint::GetBodyB() -{ - return m_bodyB; -} - -inline b2Joint* b2Joint::GetNext() -{ - return m_next; -} - -inline const b2Joint* b2Joint::GetNext() const -{ - return m_next; -} - -inline void* b2Joint::GetUserData() const -{ - return m_userData; -} - -inline void b2Joint::SetUserData(void* data) -{ - m_userData = data; -} - -inline bool b2Joint::GetCollideConnected() const -{ - return m_collideConnected; -} - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp deleted file mode 100644 index 237d9d519a..0000000000 --- a/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// p = attached point, m = mouse point -// C = p - m -// Cdot = v -// = v + cross(w, r) -// J = [I r_skew] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) -: b2Joint(def) -{ - b2Assert(def->target.IsValid()); - b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); - b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); - b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); - - m_targetA = def->target; - m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); - - m_maxForce = def->maxForce; - m_impulse.SetZero(); - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_beta = 0.0f; - m_gamma = 0.0f; -} - -void b2MouseJoint::SetTarget(const b2Vec2& target) -{ - if (m_bodyB->IsAwake() == false) - { - m_bodyB->SetAwake(true); - } - m_targetA = target; -} - -const b2Vec2& b2MouseJoint::GetTarget() const -{ - return m_targetA; -} - -void b2MouseJoint::SetMaxForce(float32 force) -{ - m_maxForce = force; -} - -float32 b2MouseJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2MouseJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -float32 b2MouseJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -void b2MouseJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -float32 b2MouseJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexB = m_bodyB->m_islandIndex; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassB = m_bodyB->m_invMass; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qB(aB); - - float32 mass = m_bodyB->GetMass(); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = mass * (omega * omega); - - // magic formulas - // gamma has units of inverse mass. - // beta has units of inverse time. - float32 h = data.step.dt; - b2Assert(d + h * k > b2_epsilon); - m_gamma = h * (d + h * k); - if (m_gamma != 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - m_beta = h * k * m_gamma; - - // Compute the effective mass matrix. - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - b2Mat22 K; - K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; - K.ex.y = -m_invIB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; - - m_mass = K.GetInverse(); - - m_C = cB + m_rB - m_targetA; - m_C *= m_beta; - - // Cheat with some damping - wB *= 0.98f; - - if (data.step.warmStarting) - { - m_impulse *= data.step.dtRatio; - vB += m_invMassB * m_impulse; - wB += m_invIB * b2Cross(m_rB, m_impulse); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = v + cross(w, r) - b2Vec2 Cdot = vB + b2Cross(wB, m_rB); - b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); - - b2Vec2 oldImpulse = m_impulse; - m_impulse += impulse; - float32 maxImpulse = data.step.dt * m_maxForce; - if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_impulse *= maxImpulse / m_impulse.Length(); - } - impulse = m_impulse - oldImpulse; - - vB += m_invMassB * impulse; - wB += m_invIB * b2Cross(m_rB, impulse); - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - return true; -} - -b2Vec2 b2MouseJoint::GetAnchorA() const -{ - return m_targetA; -} - -b2Vec2 b2MouseJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_impulse; -} - -float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * 0.0f; -} diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.h b/external/Box2D/Dynamics/Joints/b2MouseJoint.h deleted file mode 100644 index 1bbc194f4c..0000000000 --- a/external/Box2D/Dynamics/Joints/b2MouseJoint.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_MOUSE_JOINT_H -#define B2_MOUSE_JOINT_H - -#include - -/// Mouse joint definition. This requires a world target point, -/// tuning parameters, and the time step. -struct b2MouseJointDef : public b2JointDef -{ - b2MouseJointDef() - { - type = e_mouseJoint; - target.Set(0.0f, 0.0f); - maxForce = 0.0f; - frequencyHz = 5.0f; - dampingRatio = 0.7f; - } - - /// The initial world target point. This is assumed - /// to coincide with the body anchor initially. - b2Vec2 target; - - /// The maximum constraint force that can be exerted - /// to move the candidate body. Usually you will express - /// as some multiple of the weight (multiplier * mass * gravity). - float32 maxForce; - - /// The response speed. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A mouse joint is used to make a point on a body track a -/// specified world point. This a soft constraint with a maximum -/// force. This allows the constraint to stretch and without -/// applying huge forces. -/// NOTE: this joint is not documented in the manual because it was -/// developed to be used in the testbed. If you want to learn how to -/// use the mouse joint, look at the testbed. -class b2MouseJoint : public b2Joint -{ -public: - - /// Implements b2Joint. - b2Vec2 GetAnchorA() const; - - /// Implements b2Joint. - b2Vec2 GetAnchorB() const; - - /// Implements b2Joint. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Implements b2Joint. - float32 GetReactionTorque(float32 inv_dt) const; - - /// Use this to update the target point. - void SetTarget(const b2Vec2& target); - const b2Vec2& GetTarget() const; - - /// Set/get the maximum force in Newtons. - void SetMaxForce(float32 force); - float32 GetMaxForce() const; - - /// Set/get the frequency in Hertz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get the damping ratio (dimensionless). - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// The mouse joint does not support dumping. - void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } - -protected: - friend class b2Joint; - - b2MouseJoint(const b2MouseJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_localAnchorB; - b2Vec2 m_targetA; - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_beta; - - // Solver shared - b2Vec2 m_impulse; - float32 m_maxForce; - float32 m_gamma; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rB; - b2Vec2 m_localCenterB; - float32 m_invMassB; - float32 m_invIB; - b2Mat22 m_mass; - b2Vec2 m_C; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp deleted file mode 100644 index 4849f729f5..0000000000 --- a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp +++ /dev/null @@ -1,637 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Linear constraint (point-to-line) -// d = p2 - p1 = x2 + r2 - x1 - r1 -// C = dot(perp, d) -// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) -// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] -// -// Angular constraint -// C = a2 - a1 + a_initial -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// -// K = J * invM * JT -// -// J = [-a -s1 a s2] -// [0 -1 0 1] -// a = perp -// s1 = cross(d + r1, a) = cross(p2 - x1, a) -// s2 = cross(r2, a) = cross(p2 - x2, a) - - -// Motor/Limit linear constraint -// C = dot(ax1, d) -// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) -// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] - -// Block Solver -// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even -// when the mass has poor distribution (leading to large torques about the joint anchor points). -// -// The Jacobian has 3 rows: -// J = [-uT -s1 uT s2] // linear -// [0 -1 0 1] // angular -// [-vT -a1 vT a2] // limit -// -// u = perp -// v = axis -// s1 = cross(d + r1, u), s2 = cross(r2, u) -// a1 = cross(d + r1, v), a2 = cross(r2, v) - -// M * (v2 - v1) = JT * df -// J * v2 = bias -// -// v2 = v1 + invM * JT * df -// J * (v1 + invM * JT * df) = bias -// K * df = bias - J * v1 = -Cdot -// K = J * invM * JT -// Cdot = J * v1 - bias -// -// Now solve for f2. -// df = f2 - f1 -// K * (f2 - f1) = -Cdot -// f2 = invK * (-Cdot) + f1 -// -// Clamp accumulated limit impulse. -// lower: f2(3) = max(f2(3), 0) -// upper: f2(3) = min(f2(3), 0) -// -// Solve for correct f2(1:2) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 -// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) -// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) -// -// Now compute impulse to be applied: -// df = f2 - f1 - -void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localXAxisA.Normalize(); - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = def->maxMotorForce; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; - - m_axis.SetZero(); - m_perp.SetZero(); -} - -void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute motor Jacobian and effective mass. - { - m_axis = b2Mul(qA, m_localXAxisA); - m_a1 = b2Cross(d + rA, m_axis); - m_a2 = b2Cross(rB, m_axis); - - m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - - // Prismatic constraint. - { - m_perp = b2Mul(qA, m_localYAxisA); - - m_s1 = b2Cross(d + rA, m_perp); - m_s2 = b2Cross(rB, m_perp); - - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; - float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For bodies with fixed rotation. - k22 = 1.0f; - } - float32 k23 = iA * m_a1 + iB * m_a2; - float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - - m_K.ex.Set(k11, k12, k13); - m_K.ey.Set(k12, k22, k23); - m_K.ez.Set(k13, k23, k33); - } - - // Compute motor and limit terms. - if (m_enableLimit) - { - float32 jointTranslation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitState = e_atLowerLimit; - m_impulse.z = 0.0f; - } - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitState = e_atUpperLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - - if (m_enableMotor == false) - { - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; - float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; - float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - float32 impulse = m_motorMass * (m_motorSpeed - Cdot); - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorForce; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - b2Vec2 P = impulse * m_axis; - float32 LA = impulse * m_a1; - float32 LB = impulse * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - b2Vec2 Cdot1; - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - // Solve prismatic and limit constraint in block form. - float32 Cdot2; - Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 f1 = m_impulse; - b2Vec3 df = m_K.Solve33(-Cdot); - m_impulse += df; - - if (m_limitState == e_atLowerLimit) - { - m_impulse.z = b2Max(m_impulse.z, 0.0f); - } - else if (m_limitState == e_atUpperLimit) - { - m_impulse.z = b2Min(m_impulse.z, 0.0f); - } - - // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) - b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); - b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); - m_impulse.x = f2r.x; - m_impulse.y = f2r.y; - - df = m_impulse - f1; - - b2Vec2 P = df.x * m_perp + df.z * m_axis; - float32 LA = df.x * m_s1 + df.y + df.z * m_a1; - float32 LB = df.x * m_s2 + df.y + df.z * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - // Limit is inactive, just solve the prismatic constraint in block form. - b2Vec2 df = m_K.Solve22(-Cdot1); - m_impulse.x += df.x; - m_impulse.y += df.y; - - b2Vec2 P = df.x * m_perp; - float32 LA = df.x * m_s1 + df.y; - float32 LB = df.x * m_s2 + df.y; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - - b2Vec2 Cdot10 = Cdot1; - - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) - { - b2Vec2 test = b2Mul22(m_K, df); - Cdot1.x += 0.0f; - } - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute fresh Jacobians - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - b2Vec2 axis = b2Mul(qA, m_localXAxisA); - float32 a1 = b2Cross(d + rA, axis); - float32 a2 = b2Cross(rB, axis); - b2Vec2 perp = b2Mul(qA, m_localYAxisA); - - float32 s1 = b2Cross(d + rA, perp); - float32 s2 = b2Cross(rB, perp); - - b2Vec3 impulse; - b2Vec2 C1; - C1.x = b2Dot(perp, d); - C1.y = aB - aA - m_referenceAngle; - - float32 linearError = b2Abs(C1.x); - float32 angularError = b2Abs(C1.y); - - bool active = false; - float32 C2 = 0.0f; - if (m_enableLimit) - { - float32 translation = b2Dot(axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - // Prevent large angular corrections - C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Max(linearError, b2Abs(translation)); - active = true; - } - else if (translation <= m_lowerTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = b2Max(linearError, m_lowerTranslation - translation); - active = true; - } - else if (translation >= m_upperTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = b2Max(linearError, translation - m_upperTranslation); - active = true; - } - } - - if (active) - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k13 = iA * s1 * a1 + iB * s2 * a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For fixed rotation - k22 = 1.0f; - } - float32 k23 = iA * a1 + iB * a2; - float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - - b2Mat33 K; - K.ex.Set(k11, k12, k13); - K.ey.Set(k12, k22, k23); - K.ez.Set(k13, k23, k33); - - b2Vec3 C; - C.x = C1.x; - C.y = C1.y; - C.z = C2; - - impulse = K.Solve33(-C); - } - else - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - k22 = 1.0f; - } - - b2Mat22 K; - K.ex.Set(k11, k12); - K.ey.Set(k12, k22); - - b2Vec2 impulse1 = K.Solve(-C1); - impulse.x = impulse1.x; - impulse.y = impulse1.y; - impulse.z = 0.0f; - } - - b2Vec2 P = impulse.x * perp + impulse.z * axis; - float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; - float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; - - cA -= mA * P; - aA -= iA * LA; - cB += mB * P; - aB += iB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2PrismaticJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PrismaticJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); -} - -float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.y; -} - -float32 b2PrismaticJoint::GetJointTranslation() const -{ - b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2PrismaticJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); - b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); - b2Vec2 p1 = bA->m_sweep.c + rA; - b2Vec2 p2 = bB->m_sweep.c + rB; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - - b2Vec2 vA = bA->m_linearVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - float32 wB = bB->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); - return speed; -} - -bool b2PrismaticJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2PrismaticJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2PrismaticJoint::GetLowerLimit() const -{ - return m_lowerTranslation; -} - -float32 b2PrismaticJoint::GetUpperLimit() const -{ - return m_upperTranslation; -} - -void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - if (lower != m_lowerTranslation || upper != m_upperTranslation) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; - m_impulse.z = 0.0f; - } -} - -bool b2PrismaticJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2PrismaticJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -void b2PrismaticJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2PrismaticJoint::SetMaxMotorForce(float32 force) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorForce = force; -} - -float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2PrismaticJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PrismaticJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); - b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h deleted file mode 100644 index aca2859b45..0000000000 --- a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_PRISMATIC_JOINT_H -#define B2_PRISMATIC_JOINT_H - -#include - -/// Prismatic joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2PrismaticJointDef : public b2JointDef -{ - b2PrismaticJointDef() - { - type = e_prismaticJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - referenceAngle = 0.0f; - enableLimit = false; - lowerTranslation = 0.0f; - upperTranslation = 0.0f; - enableMotor = false; - maxMotorForce = 0.0f; - motorSpeed = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and unit world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation unit axis in bodyA. - b2Vec2 localAxisA; - - /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. - float32 referenceAngle; - - /// Enable/disable the joint limit. - bool enableLimit; - - /// The lower translation limit, usually in meters. - float32 lowerTranslation; - - /// The upper translation limit, usually in meters. - float32 upperTranslation; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorForce; - - /// The desired motor speed in radians per second. - float32 motorSpeed; -}; - -/// A prismatic joint. This joint provides one degree of freedom: translation -/// along an axis fixed in bodyA. Relative rotation is prevented. You can -/// use a joint limit to restrict the range of motion and a joint motor to -/// drive the motion or to model joint friction. -class b2PrismaticJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit, usually in meters. - float32 GetLowerLimit() const; - - /// Get the upper joint limit, usually in meters. - float32 GetUpperLimit() const; - - /// Set the joint limits, usually in meters. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in meters per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in meters per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor force, usually in N. - void SetMaxMotorForce(float32 force); - float32 GetMaxMotorForce() const { return m_maxMotorForce; } - - /// Get the current motor force given the inverse time step, usually in N. - float32 GetMotorForce(float32 inv_dt) const; - - /// Dump to b2Log - void Dump(); - -protected: - friend class b2Joint; - friend class b2GearJoint; - b2PrismaticJoint(const b2PrismaticJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - float32 m_referenceAngle; - b2Vec3 m_impulse; - float32 m_motorImpulse; - float32 m_lowerTranslation; - float32 m_upperTranslation; - float32 m_maxMotorForce; - float32 m_motorSpeed; - bool m_enableLimit; - bool m_enableMotor; - b2LimitState m_limitState; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - b2Mat33 m_K; - float32 m_motorMass; -}; - -inline float32 b2PrismaticJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp deleted file mode 100644 index da30fae222..0000000000 --- a/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Pulley: -// length1 = norm(p1 - s1) -// length2 = norm(p2 - s2) -// C0 = (length1 + ratio * length2)_initial -// C = C0 - (length1 + ratio * length2) -// u1 = (p1 - s1) / norm(p1 - s1) -// u2 = (p2 - s2) / norm(p2 - s2) -// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) -// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) - -void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, - const b2Vec2& groundA, const b2Vec2& groundB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 r) -{ - bodyA = bA; - bodyB = bB; - groundAnchorA = groundA; - groundAnchorB = groundB; - localAnchorA = bodyA->GetLocalPoint(anchorA); - localAnchorB = bodyB->GetLocalPoint(anchorB); - b2Vec2 dA = anchorA - groundA; - lengthA = dA.Length(); - b2Vec2 dB = anchorB - groundB; - lengthB = dB.Length(); - ratio = r; - b2Assert(ratio > b2_epsilon); -} - -b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) -: b2Joint(def) -{ - m_groundAnchorA = def->groundAnchorA; - m_groundAnchorB = def->groundAnchorB; - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_lengthA = def->lengthA; - m_lengthB = def->lengthB; - - b2Assert(def->ratio != 0.0f); - m_ratio = def->ratio; - - m_constant = def->lengthA + m_ratio * def->lengthB; - - m_impulse = 0.0f; -} - -void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - m_uA = cA + m_rA - m_groundAnchorA; - m_uB = cB + m_rB - m_groundAnchorB; - - float32 lengthA = m_uA.Length(); - float32 lengthB = m_uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - m_uA *= 1.0f / lengthA; - } - else - { - m_uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - m_uB *= 1.0f / lengthB; - } - else - { - m_uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(m_rA, m_uA); - float32 ruB = b2Cross(m_rB, m_uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - m_mass = mA + m_ratio * m_ratio * mB; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support variable time steps. - m_impulse *= data.step.dtRatio; - - // Warm starting. - b2Vec2 PA = -(m_impulse) * m_uA; - b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; - - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - - float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 PA = -impulse * m_uA; - b2Vec2 PB = -m_ratio * impulse * m_uB; - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - b2Vec2 uA = cA + rA - m_groundAnchorA; - b2Vec2 uB = cB + rB - m_groundAnchorB; - - float32 lengthA = uA.Length(); - float32 lengthB = uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - uA *= 1.0f / lengthA; - } - else - { - uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - uB *= 1.0f / lengthB; - } - else - { - uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(rA, uA); - float32 ruB = b2Cross(rB, uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - float32 mass = mA + m_ratio * m_ratio * mB; - - if (mass > 0.0f) - { - mass = 1.0f / mass; - } - - float32 C = m_constant - lengthA - m_ratio * lengthB; - float32 linearError = b2Abs(C); - - float32 impulse = -mass * C; - - b2Vec2 PA = -impulse * uA; - b2Vec2 PB = -m_ratio * impulse * uB; - - cA += m_invMassA * PA; - aA += m_invIA * b2Cross(rA, PA); - cB += m_invMassB * PB; - aB += m_invIB * b2Cross(rB, PB); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError < b2_linearSlop; -} - -b2Vec2 b2PulleyJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PulleyJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_uB; - return inv_dt * P; -} - -float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorA() const -{ - return m_groundAnchorA; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorB() const -{ - return m_groundAnchorB; -} - -float32 b2PulleyJoint::GetLengthA() const -{ - b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 s = m_groundAnchorA; - b2Vec2 d = p - s; - return d.Length(); -} - -float32 b2PulleyJoint::GetLengthB() const -{ - b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 s = m_groundAnchorB; - b2Vec2 d = p - s; - return d.Length(); -} - -float32 b2PulleyJoint::GetRatio() const -{ - return m_ratio; -} - -void b2PulleyJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PulleyJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); - b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); - b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.h b/external/Box2D/Dynamics/Joints/b2PulleyJoint.h deleted file mode 100644 index 2f6df4395c..0000000000 --- a/external/Box2D/Dynamics/Joints/b2PulleyJoint.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_PULLEY_JOINT_H -#define B2_PULLEY_JOINT_H - -#include - -const float32 b2_minPulleyLength = 2.0f; - -/// Pulley joint definition. This requires two ground anchors, -/// two dynamic body anchor points, and a pulley ratio. -struct b2PulleyJointDef : public b2JointDef -{ - b2PulleyJointDef() - { - type = e_pulleyJoint; - groundAnchorA.Set(-1.0f, 1.0f); - groundAnchorB.Set(1.0f, 1.0f); - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - lengthA = 0.0f; - lengthB = 0.0f; - ratio = 1.0f; - collideConnected = true; - } - - /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 ratio); - - /// The first ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorA; - - /// The second ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorB; - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The a reference length for the segment attached to bodyA. - float32 lengthA; - - /// The a reference length for the segment attached to bodyB. - float32 lengthB; - - /// The pulley ratio, used to simulate a block-and-tackle. - float32 ratio; -}; - -/// The pulley joint is connected to two bodies and two fixed ground points. -/// The pulley supports a ratio such that: -/// length1 + ratio * length2 <= constant -/// Yes, the force transmitted is scaled by the ratio. -/// Warning: the pulley joint can get a bit squirrelly by itself. They often -/// work better when combined with prismatic joints. You should also cover the -/// the anchor points with static shapes to prevent one side from going to -/// zero length. -class b2PulleyJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the first ground anchor. - b2Vec2 GetGroundAnchorA() const; - - /// Get the second ground anchor. - b2Vec2 GetGroundAnchorB() const; - - /// Get the current length of the segment attached to bodyA. - float32 GetLengthA() const; - - /// Get the current length of the segment attached to bodyB. - float32 GetLengthB() const; - - /// Get the pulley ratio. - float32 GetRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2PulleyJoint(const b2PulleyJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_groundAnchorA; - b2Vec2 m_groundAnchorB; - float32 m_lengthA; - float32 m_lengthB; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_constant; - float32 m_ratio; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_uA; - b2Vec2 m_uB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp deleted file mode 100644 index e265d8192b..0000000000 --- a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp +++ /dev/null @@ -1,504 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Motor constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - - m_lowerAngle = def->lowerAngle; - m_upperAngle = def->upperAngle; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; -} - -void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; - - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - - if (m_enableMotor == false || fixedRotation) - { - m_motorImpulse = 0.0f; - } - - if (m_enableLimit && fixedRotation == false) - { - float32 jointAngle = aB - aA - m_referenceAngle; - if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) - { - m_limitState = e_equalLimits; - } - else if (jointAngle <= m_lowerAngle) - { - if (m_limitState != e_atLowerLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointAngle >= m_upperAngle) - { - if (m_limitState != e_atUpperLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - // Solve motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -m_mass.Solve33(Cdot); - - if (m_limitState == e_equalLimits) - { - m_impulse += impulse; - } - else if (m_limitState == e_atLowerLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse < 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - else if (m_limitState == e_atUpperLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse > 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - else - { - // Solve point-to-point constraint - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse = m_mass.Solve22(-Cdot); - - m_impulse.x += impulse.x; - m_impulse.y += impulse.y; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 angularError = 0.0f; - float32 positionError = 0.0f; - - bool fixedRotation = (m_invIA + m_invIB == 0.0f); - - // Solve angular limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - float32 angle = aB - aA - m_referenceAngle; - float32 limitImpulse = 0.0f; - - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - angularError = b2Abs(C); - } - else if (m_limitState == e_atLowerLimit) - { - float32 C = angle - m_lowerAngle; - angularError = -C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); - limitImpulse = -m_motorMass * C; - } - else if (m_limitState == e_atUpperLimit) - { - float32 C = angle - m_upperAngle; - angularError = C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - } - - aA -= m_invIA * limitImpulse; - aB += m_invIB * limitImpulse; - } - - // Solve point-to-point constraint. - { - qA.Set(aA); - qB.Set(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - b2Vec2 C = cB + rB - cA - rA; - positionError = C.Length(); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; - K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; - - b2Vec2 impulse = -K.Solve(C); - - cA -= mA * impulse; - aA -= iA * b2Cross(rA, impulse); - - cB += mB * impulse; - aB += iB * b2Cross(rB, impulse); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2RevoluteJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RevoluteJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -float32 b2RevoluteJoint::GetJointAngle() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; -} - -float32 b2RevoluteJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_angularVelocity - bA->m_angularVelocity; -} - -bool b2RevoluteJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2RevoluteJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2RevoluteJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; -} - -bool b2RevoluteJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2RevoluteJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2RevoluteJoint::GetLowerLimit() const -{ - return m_lowerAngle; -} - -float32 b2RevoluteJoint::GetUpperLimit() const -{ - return m_upperAngle; -} - -void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - - if (lower != m_lowerAngle || upper != m_upperAngle) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_impulse.z = 0.0f; - m_lowerAngle = lower; - m_upperAngle = upper; - } -} - -void b2RevoluteJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RevoluteJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); - b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h deleted file mode 100644 index 978f16259a..0000000000 --- a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h +++ /dev/null @@ -1,204 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_REVOLUTE_JOINT_H -#define B2_REVOLUTE_JOINT_H - -#include - -/// Revolute joint definition. This requires defining an -/// anchor point where the bodies are joined. The definition -/// uses local anchor points so that the initial configuration -/// can violate the constraint slightly. You also need to -/// specify the initial relative angle for joint limits. This -/// helps when saving and loading a game. -/// The local anchor points are measured from the body's origin -/// rather than the center of mass because: -/// 1. you might not know where the center of mass will be. -/// 2. if you add/remove shapes from a body and recompute the mass, -/// the joints will be broken. -struct b2RevoluteJointDef : public b2JointDef -{ - b2RevoluteJointDef() - { - type = e_revoluteJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - lowerAngle = 0.0f; - upperAngle = 0.0f; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - enableLimit = false; - enableMotor = false; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// A flag to enable joint limits. - bool enableLimit; - - /// The lower angle for the joint limit (radians). - float32 lowerAngle; - - /// The upper angle for the joint limit (radians). - float32 upperAngle; - - /// A flag to enable the joint motor. - bool enableMotor; - - /// The desired motor speed. Usually in radians per second. - float32 motorSpeed; - - /// The maximum motor torque used to achieve the desired motor speed. - /// Usually in N-m. - float32 maxMotorTorque; -}; - -/// A revolute joint constrains two bodies to share a common point while they -/// are free to rotate about the point. The relative rotation about the shared -/// point is the joint angle. You can limit the relative rotation with -/// a joint limit that specifies a lower and upper angle. You can use a motor -/// to drive the relative rotation about the shared point. A maximum motor torque -/// is provided so that infinite forces are not generated. -class b2RevoluteJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint angle in radians. - float32 GetJointAngle() const; - - /// Get the current joint angle speed in radians per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit in radians. - float32 GetLowerLimit() const; - - /// Get the upper joint limit in radians. - float32 GetUpperLimit() const; - - /// Set the joint limits in radians. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed in radians per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor torque, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Get the reaction torque due to the joint limit given the inverse time step. - /// Unit is N*m. - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the current motor torque given the inverse time step. - /// Unit is N*m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Dump to b2Log. - void Dump(); - -protected: - - friend class b2Joint; - friend class b2GearJoint; - - b2RevoluteJoint(const b2RevoluteJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec3 m_impulse; - float32 m_motorImpulse; - - bool m_enableMotor; - float32 m_maxMotorTorque; - float32 m_motorSpeed; - - bool m_enableLimit; - float32 m_referenceAngle; - float32 m_lowerAngle; - float32 m_upperAngle; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; // effective mass for point-to-point constraint. - float32 m_motorMass; // effective mass for motor/limit angular constraint. - b2LimitState m_limitState; -}; - -inline float32 b2RevoluteJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp deleted file mode 100644 index 17a70d9230..0000000000 --- a/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - - -// Limit: -// C = norm(pB - pA) - L -// u = (pB - pA) / norm(pB - pA) -// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) -// J = [-u -cross(rA, u) u cross(rB, u)] -// K = J * invM * JT -// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 - -b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_maxLength = def->maxLength; - - m_mass = 0.0f; - m_impulse = 0.0f; - m_state = e_inactiveLimit; - m_length = 0.0f; -} - -void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - m_length = m_u.Length(); - - float32 C = m_length - m_maxLength; - if (C > 0.0f) - { - m_state = e_atUpperLimit; - } - else - { - m_state = e_inactiveLimit; - } - - if (m_length > b2_linearSlop) - { - m_u *= 1.0f / m_length; - } - else - { - m_u.SetZero(); - m_mass = 0.0f; - m_impulse = 0.0f; - return; - } - - // Compute effective mass. - float32 crA = b2Cross(m_rA, m_u); - float32 crB = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; - - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 C = m_length - m_maxLength; - float32 Cdot = b2Dot(m_u, vpB - vpA); - - // Predictive constraint. - if (C < 0.0f) - { - Cdot += data.step.inv_dt * C; - } - - float32 impulse = -m_mass * Cdot; - float32 oldImpulse = m_impulse; - m_impulse = b2Min(0.0f, m_impulse + impulse); - impulse = m_impulse - oldImpulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_maxLength; - - C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return length - m_maxLength < b2_linearSlop; -} - -b2Vec2 b2RopeJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RopeJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -float32 b2RopeJoint::GetMaxLength() const -{ - return m_maxLength; -} - -b2LimitState b2RopeJoint::GetLimitState() const -{ - return m_state; -} - -void b2RopeJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RopeJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.h b/external/Box2D/Dynamics/Joints/b2RopeJoint.h deleted file mode 100644 index d7091b6650..0000000000 --- a/external/Box2D/Dynamics/Joints/b2RopeJoint.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ROPE_JOINT_H -#define B2_ROPE_JOINT_H - -#include - -/// Rope joint definition. This requires two body anchor points and -/// a maximum lengths. -/// Note: by default the connected objects will not collide. -/// see collideConnected in b2JointDef. -struct b2RopeJointDef : public b2JointDef -{ - b2RopeJointDef() - { - type = e_ropeJoint; - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - maxLength = 0.0f; - } - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum length of the rope. - /// Warning: this must be larger than b2_linearSlop or - /// the joint will have no effect. - float32 maxLength; -}; - -/// A rope joint enforces a maximum distance between two points -/// on two bodies. It has no other effect. -/// Warning: if you attempt to change the maximum length during -/// the simulation you will get some non-physical behavior. -/// A model that would allow you to dynamically modify the length -/// would have some sponginess, so I chose not to implement it -/// that way. See b2DistanceJoint if you want to dynamically -/// control length. -class b2RopeJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/Get the maximum length of the rope. - void SetMaxLength(float32 length) { m_maxLength = length; } - float32 GetMaxLength() const; - - b2LimitState GetLimitState() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2RopeJoint(const b2RopeJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_maxLength; - float32 m_length; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; - b2LimitState m_state; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp deleted file mode 100644 index f50bdd6587..0000000000 --- a/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// C = angle2 - angle1 - referenceAngle -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_impulse.SetZero(); -} - -void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat33 K; - K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - K.ez.x = -m_rA.y * iA - m_rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - K.ez.y = m_rA.x * iA + m_rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - K.GetInverse22(&m_mass); - - float32 invM = iA + iB; - float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; - - float32 C = aB - aA - m_referenceAngle; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invM += m_gamma; - m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; - } - else - { - K.GetSymInverse33(&m_mass); - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_impulse.z); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - if (m_frequencyHz > 0.0f) - { - float32 Cdot2 = wB - wA; - - float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); - m_impulse.z += impulse2; - - wA -= iA * impulse2; - wB += iB * impulse2; - - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); - m_impulse.x += impulse1.x; - m_impulse.y += impulse1.y; - - b2Vec2 P = impulse1; - - vA -= mA * P; - wA -= iA * b2Cross(m_rA, P); - - vB += mB * P; - wB += iB * b2Cross(m_rB, P); - } - else - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -b2Mul(m_mass, Cdot); - m_impulse += impulse; - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - float32 positionError, angularError; - - b2Mat33 K; - K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - K.ez.x = -rA.y * iA - rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - K.ez.y = rA.x * iA + rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - b2Vec2 C1 = cB + rB - cA - rA; - - positionError = C1.Length(); - angularError = 0.0f; - - b2Vec2 P = -K.Solve22(C1); - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - else - { - b2Vec2 C1 = cB + rB - cA - rA; - float32 C2 = aB - aA - m_referenceAngle; - - positionError = C1.Length(); - angularError = b2Abs(C2); - - b2Vec3 C(C1.x, C1.y, C2); - - b2Vec3 impulse = -K.Solve33(C); - b2Vec2 P(impulse.x, impulse.y); - - cA -= mA * P; - aA -= iA * (b2Cross(rA, P) + impulse.z); - - cB += mB * P; - aB += iB * (b2Cross(rB, P) + impulse.z); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2WeldJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WeldJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -void b2WeldJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WeldJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.h b/external/Box2D/Dynamics/Joints/b2WeldJoint.h deleted file mode 100644 index 751c6a8770..0000000000 --- a/external/Box2D/Dynamics/Joints/b2WeldJoint.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WELD_JOINT_H -#define B2_WELD_JOINT_H - -#include - -/// Weld joint definition. You need to specify local anchor points -/// where they are attached and the relative body angle. The position -/// of the anchor points is important for computing the reaction torque. -struct b2WeldJointDef : public b2JointDef -{ - b2WeldJointDef() - { - type = e_weldJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// The mass-spring-damper frequency in Hertz. Rotation only. - /// Disable softness with a value of 0. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A weld joint essentially glues two bodies together. A weld joint may -/// distort somewhat because the island constraint solver is approximate. -class b2WeldJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz) { m_frequencyHz = hz; } - float32 GetFrequency() const { return m_frequencyHz; } - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } - float32 GetDampingRatio() const { return m_dampingRatio; } - - /// Dump to b2Log - void Dump(); - -protected: - - friend class b2Joint; - - b2WeldJoint(const b2WeldJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_referenceAngle; - float32 m_gamma; - b2Vec3 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; -}; - -#endif diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp deleted file mode 100644 index 6253437706..0000000000 --- a/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Linear constraint (point-to-line) -// d = pB - pA = xB + rB - xA - rA -// C = dot(ay, d) -// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) -// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) -// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] - -// Spring linear constraint -// C = dot(ax, d) -// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) -// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] - -// Motor rotational constraint -// Cdot = wB - wA -// J = [0 0 -1 0 0 1] - -void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); -} - -b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - - m_mass = 0.0f; - m_impulse = 0.0f; - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - m_springMass = 0.0f; - m_springImpulse = 0.0f; - - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableMotor = def->enableMotor; - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_bias = 0.0f; - m_gamma = 0.0f; - - m_ax.SetZero(); - m_ay.SetZero(); -} - -void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - // Point to line constraint - { - m_ay = b2Mul(qA, m_localYAxisA); - m_sAy = b2Cross(d + rA, m_ay); - m_sBy = b2Cross(rB, m_ay); - - m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - } - - // Spring constraint - m_springMass = 0.0f; - m_bias = 0.0f; - m_gamma = 0.0f; - if (m_frequencyHz > 0.0f) - { - m_ax = b2Mul(qA, m_localXAxisA); - m_sAx = b2Cross(d + rA, m_ax); - m_sBx = b2Cross(rB, m_ax); - - float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; - - if (invMass > 0.0f) - { - m_springMass = 1.0f / invMass; - - float32 C = b2Dot(d, m_ax); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m_springMass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_springMass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - if (m_gamma > 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - - m_bias = C * h * k * m_gamma; - - m_springMass = invMass + m_gamma; - if (m_springMass > 0.0f) - { - m_springMass = 1.0f / m_springMass; - } - } - } - else - { - m_springImpulse = 0.0f; - } - - // Rotational motor - if (m_enableMotor) - { - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - else - { - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_springImpulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; - float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; - float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; - - vA -= m_invMassA * P; - wA -= m_invIA * LA; - - vB += m_invMassB * P; - wB += m_invIB * LB; - } - else - { - m_impulse = 0.0f; - m_springImpulse = 0.0f; - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Solve spring constraint - { - float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; - float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); - m_springImpulse += impulse; - - b2Vec2 P = impulse * m_ax; - float32 LA = impulse * m_sAx; - float32 LB = impulse * m_sBx; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - // Solve rotational motor constraint - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve point to line constraint - { - float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 P = impulse * m_ay; - float32 LA = impulse * m_sAy; - float32 LB = impulse * m_sBy; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - b2Vec2 ay = b2Mul(qA, m_localYAxisA); - - float32 sAy = b2Cross(d + rA, ay); - float32 sBy = b2Cross(rB, ay); - - float32 C = b2Dot(d, ay); - - float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; - - float32 impulse; - if (k != 0.0f) - { - impulse = - C / k; - } - else - { - impulse = 0.0f; - } - - b2Vec2 P = impulse * ay; - float32 LA = impulse * sAy; - float32 LB = impulse * sBy; - - cA -= m_invMassA * P; - aA -= m_invIA * LA; - cB += m_invMassB * P; - aB += m_invIB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) <= b2_linearSlop; -} - -b2Vec2 b2WheelJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WheelJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); -} - -float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -float32 b2WheelJoint::GetJointTranslation() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2WheelJoint::GetJointSpeed() const -{ - float32 wA = m_bodyA->m_angularVelocity; - float32 wB = m_bodyB->m_angularVelocity; - return wB - wA; -} - -bool b2WheelJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2WheelJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -void b2WheelJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2WheelJoint::SetMaxMotorTorque(float32 torque) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; -} - -float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2WheelJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WheelJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.h b/external/Box2D/Dynamics/Joints/b2WheelJoint.h deleted file mode 100644 index ede1b08b7c..0000000000 --- a/external/Box2D/Dynamics/Joints/b2WheelJoint.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WHEEL_JOINT_H -#define B2_WHEEL_JOINT_H - -#include - -/// Wheel joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2WheelJointDef : public b2JointDef -{ - b2WheelJointDef() - { - type = e_wheelJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - enableMotor = false; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - frequencyHz = 2.0f; - dampingRatio = 0.7f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation axis in bodyA. - b2Vec2 localAxisA; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorTorque; - - /// The desired motor speed in radians per second. - float32 motorSpeed; - - /// Suspension frequency, zero indicates no suspension - float32 frequencyHz; - - /// Suspension damping ratio, one indicates critical damping - float32 dampingRatio; -}; - -/// A wheel joint. This joint provides two degrees of freedom: translation -/// along an axis fixed in bodyA and rotation in the plane. You can use a -/// joint limit to restrict the range of motion and a joint motor to drive -/// the rotation or to model rotational friction. -/// This joint is designed for vehicle suspensions. -class b2WheelJoint : public b2Joint -{ -public: - void GetDefinition(b2WheelJointDef* def) const; - - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in radians per second. - float32 GetMotorSpeed() const; - - /// Set/Get the maximum motor force, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const; - - /// Get the current motor torque given the inverse time step, usually in N-m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. - void SetSpringFrequencyHz(float32 hz); - float32 GetSpringFrequencyHz() const; - - /// Set/Get the spring damping ratio - void SetSpringDampingRatio(float32 ratio); - float32 GetSpringDampingRatio() const; - - /// Dump to b2Log - void Dump(); - -protected: - - friend class b2Joint; - b2WheelJoint(const b2WheelJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - - float32 m_impulse; - float32 m_motorImpulse; - float32 m_springImpulse; - - float32 m_maxMotorTorque; - float32 m_motorSpeed; - bool m_enableMotor; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - - b2Vec2 m_ax, m_ay; - float32 m_sAx, m_sBx; - float32 m_sAy, m_sBy; - - float32 m_mass; - float32 m_motorMass; - float32 m_springMass; - - float32 m_bias; - float32 m_gamma; -}; - -inline float32 b2WheelJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -inline float32 b2WheelJoint::GetMaxMotorTorque() const -{ - return m_maxMotorTorque; -} - -inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2WheelJoint::GetSpringFrequencyHz() const -{ - return m_frequencyHz; -} - -inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2WheelJoint::GetSpringDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/external/Box2D/Dynamics/b2Body.cpp b/external/Box2D/Dynamics/b2Body.cpp deleted file mode 100644 index b22b574023..0000000000 --- a/external/Box2D/Dynamics/b2Body.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -b2Body::b2Body(const b2BodyDef* bd, b2World* world) -{ - b2Assert(bd->position.IsValid()); - b2Assert(bd->linearVelocity.IsValid()); - b2Assert(b2IsValid(bd->angle)); - b2Assert(b2IsValid(bd->angularVelocity)); - b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); - b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); - - m_flags = 0; - - if (bd->bullet) - { - m_flags |= e_bulletFlag; - } - if (bd->fixedRotation) - { - m_flags |= e_fixedRotationFlag; - } - if (bd->allowSleep) - { - m_flags |= e_autoSleepFlag; - } - if (bd->awake) - { - m_flags |= e_awakeFlag; - } - if (bd->active) - { - m_flags |= e_activeFlag; - } - - m_world = world; - - m_xf.p = bd->position; - m_xf.q.Set(bd->angle); - - m_sweep.localCenter.SetZero(); - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = bd->angle; - m_sweep.a = bd->angle; - m_sweep.alpha0 = 0.0f; - - m_jointList = NULL; - m_contactList = NULL; - m_prev = NULL; - m_next = NULL; - - m_linearVelocity = bd->linearVelocity; - m_angularVelocity = bd->angularVelocity; - - m_linearDamping = bd->linearDamping; - m_angularDamping = bd->angularDamping; - m_gravityScale = bd->gravityScale; - - m_force.SetZero(); - m_torque = 0.0f; - - m_sleepTime = 0.0f; - - m_type = bd->type; - - if (m_type == b2_dynamicBody) - { - m_mass = 1.0f; - m_invMass = 1.0f; - } - else - { - m_mass = 0.0f; - m_invMass = 0.0f; - } - - m_I = 0.0f; - m_invI = 0.0f; - - m_userData = bd->userData; - - m_fixtureList = NULL; - m_fixtureCount = 0; -} - -b2Body::~b2Body() -{ - // shapes and joints are destroyed in b2World::Destroy -} - -void b2Body::SetType(b2BodyType type) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type == type) - { - return; - } - - m_type = type; - - ResetMassData(); - - if (m_type == b2_staticBody) - { - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_sweep.a0 = m_sweep.a; - m_sweep.c0 = m_sweep.c; - SynchronizeFixtures(); - } - - SetAwake(true); - - m_force.SetZero(); - m_torque = 0.0f; - - // Since the body type changed, we need to flag contacts for filtering. - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Refilter(); - } -} - -b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return NULL; - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - void* memory = allocator->Allocate(sizeof(b2Fixture)); - b2Fixture* fixture = new (memory) b2Fixture; - fixture->Create(allocator, this, def); - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->CreateProxies(broadPhase, m_xf); - } - - fixture->m_next = m_fixtureList; - m_fixtureList = fixture; - ++m_fixtureCount; - - fixture->m_body = this; - - // Adjust mass properties if needed. - if (fixture->m_density > 0.0f) - { - ResetMassData(); - } - - // Let the world know we have a new fixture. This will cause new contacts - // to be created at the beginning of the next time step. - m_world->m_flags |= b2World::e_newFixture; - - return fixture; -} - -b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) -{ - b2FixtureDef def; - def.shape = shape; - def.density = density; - - return CreateFixture(&def); -} - -void b2Body::DestroyFixture(b2Fixture* fixture) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - b2Assert(fixture->m_body == this); - - // Remove the fixture from this body's singly linked list. - b2Assert(m_fixtureCount > 0); - b2Fixture** node = &m_fixtureList; - bool found = false; - while (*node != NULL) - { - if (*node == fixture) - { - *node = fixture->m_next; - found = true; - break; - } - - node = &(*node)->m_next; - } - - // You tried to remove a shape that is not attached to this body. - b2Assert(found); - - // Destroy any contacts associated with the fixture. - b2ContactEdge* edge = m_contactList; - while (edge) - { - b2Contact* c = edge->contact; - edge = edge->next; - - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - - if (fixture == fixtureA || fixture == fixtureB) - { - // This destroys the contact and removes it from - // this body's contact list. - m_world->m_contactManager.Destroy(c); - } - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->DestroyProxies(broadPhase); - } - - fixture->Destroy(allocator); - fixture->m_body = NULL; - fixture->m_next = NULL; - fixture->~b2Fixture(); - allocator->Free(fixture, sizeof(b2Fixture)); - - --m_fixtureCount; - - // Reset the mass data. - ResetMassData(); -} - -void b2Body::ResetMassData() -{ - // Compute mass data from shapes. Each shape has its own density. - m_mass = 0.0f; - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - m_sweep.localCenter.SetZero(); - - // Static and kinematic bodies have zero mass. - if (m_type == b2_staticBody || m_type == b2_kinematicBody) - { - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = m_sweep.a; - return; - } - - b2Assert(m_type == b2_dynamicBody); - - // Accumulate mass over all fixtures. - b2Vec2 localCenter = b2Vec2_zero; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - if (f->m_density == 0.0f) - { - continue; - } - - b2MassData massData; - f->GetMassData(&massData); - m_mass += massData.mass; - localCenter += massData.mass * massData.center; - m_I += massData.I; - } - - // Compute center of mass. - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - localCenter *= m_invMass; - } - else - { - // Force all dynamic bodies to have a positive mass. - m_mass = 1.0f; - m_invMass = 1.0f; - } - - if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) - { - // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(localCenter, localCenter); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - - } - else - { - m_I = 0.0f; - m_invI = 0.0f; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = localCenter; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -void b2Body::SetMassData(const b2MassData* massData) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type != b2_dynamicBody) - { - return; - } - - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - m_mass = massData->mass; - if (m_mass <= 0.0f) - { - m_mass = 1.0f; - } - - m_invMass = 1.0f / m_mass; - - if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = massData->center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -bool b2Body::ShouldCollide(const b2Body* other) const -{ - // At least one body should be dynamic. - if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) - { - return false; - } - - // Does a joint prevent collision? - for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) - { - if (jn->other == other) - { - if (jn->joint->m_collideConnected == false) - { - return false; - } - } - } - - return true; -} - -void b2Body::SetTransform(const b2Vec2& position, float32 angle) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - m_xf.q.Set(angle); - m_xf.p = position; - - m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a = angle; - - m_sweep.c0 = m_sweep.c; - m_sweep.a0 = angle; - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, m_xf, m_xf); - } - - m_world->m_contactManager.FindNewContacts(); -} - -void b2Body::SynchronizeFixtures() -{ - b2Transform xf1; - xf1.q.Set(m_sweep.a0); - xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, xf1, m_xf); - } -} - -void b2Body::SetActive(bool flag) -{ - b2Assert(m_world->IsLocked() == false); - - if (flag == IsActive()) - { - return; - } - - if (flag) - { - m_flags |= e_activeFlag; - - // Create all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->CreateProxies(broadPhase, m_xf); - } - - // Contacts are created the next time step. - } - else - { - m_flags &= ~e_activeFlag; - - // Destroy all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->DestroyProxies(broadPhase); - } - - // Destroy the attached contacts. - b2ContactEdge* ce = m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_world->m_contactManager.Destroy(ce0->contact); - } - m_contactList = NULL; - } -} - -void b2Body::Dump() -{ - int32 bodyIndex = m_islandIndex; - - b2Log("{\n"); - b2Log(" b2BodyDef bd;\n"); - b2Log(" bd.type = b2BodyType(%d);\n", m_type); - b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); - b2Log(" bd.angle = %.15lef;\n", m_sweep.a); - b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); - b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); - b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); - b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); - b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); - b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); - b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); - b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); - b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); - b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); - b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); - b2Log("\n"); - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - b2Log(" {\n"); - f->Dump(bodyIndex); - b2Log(" }\n"); - } - b2Log("}\n"); -} \ No newline at end of file diff --git a/external/Box2D/Dynamics/b2Body.h b/external/Box2D/Dynamics/b2Body.h deleted file mode 100644 index e2d16bf630..0000000000 --- a/external/Box2D/Dynamics/b2Body.h +++ /dev/null @@ -1,846 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BODY_H -#define B2_BODY_H - -#include -#include -#include - -class b2Fixture; -class b2Joint; -class b2Contact; -class b2Controller; -class b2World; -struct b2FixtureDef; -struct b2JointEdge; -struct b2ContactEdge; - -/// The body type. -/// static: zero mass, zero velocity, may be manually moved -/// kinematic: zero mass, non-zero velocity set by user, moved by solver -/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver -enum b2BodyType -{ - b2_staticBody = 0, - b2_kinematicBody, - b2_dynamicBody - - // TODO_ERIN - //b2_bulletBody, -}; - -/// A body definition holds all the data needed to construct a rigid body. -/// You can safely re-use body definitions. Shapes are added to a body after construction. -struct b2BodyDef -{ - /// This constructor sets the body definition default values. - b2BodyDef() - { - userData = NULL; - position.Set(0.0f, 0.0f); - angle = 0.0f; - linearVelocity.Set(0.0f, 0.0f); - angularVelocity = 0.0f; - linearDamping = 0.0f; - angularDamping = 0.0f; - allowSleep = true; - awake = true; - fixedRotation = false; - bullet = false; - type = b2_staticBody; - active = true; - gravityScale = 1.0f; - } - - /// The body type: static, kinematic, or dynamic. - /// Note: if a dynamic body would have zero mass, the mass is set to one. - b2BodyType type; - - /// The world position of the body. Avoid creating bodies at the origin - /// since this can lead to many overlapping shapes. - b2Vec2 position; - - /// The world angle of the body in radians. - float32 angle; - - /// The linear velocity of the body's origin in world co-ordinates. - b2Vec2 linearVelocity; - - /// The angular velocity of the body. - float32 angularVelocity; - - /// Linear damping is use to reduce the linear velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 linearDamping; - - /// Angular damping is use to reduce the angular velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 angularDamping; - - /// Set this flag to false if this body should never fall asleep. Note that - /// this increases CPU usage. - bool allowSleep; - - /// Is this body initially awake or sleeping? - bool awake; - - /// Should this body be prevented from rotating? Useful for characters. - bool fixedRotation; - - /// Is this a fast moving body that should be prevented from tunneling through - /// other moving bodies? Note that all bodies are prevented from tunneling through - /// kinematic and static bodies. This setting is only considered on dynamic bodies. - /// @warning You should use this flag sparingly since it increases processing time. - bool bullet; - - /// Does this body start out active? - bool active; - - /// Use this to store application specific body data. - void* userData; - - /// Scale the gravity applied to this body. - float32 gravityScale; -}; - -/// A rigid body. These are created via b2World::CreateBody. -class b2Body -{ -public: - /// Creates a fixture and attach it to this body. Use this function if you need - /// to set some fixture parameters, like friction. Otherwise you can create the - /// fixture directly from a shape. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// Contacts are not created until the next time step. - /// @param def the fixture definition. - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2FixtureDef* def); - - /// Creates a fixture from a shape and attach it to this body. - /// This is a convenience function. Use b2FixtureDef if you need to set parameters - /// like friction, restitution, user data, or filtering. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// @param shape the shape to be cloned. - /// @param density the shape density (set to zero for static bodies). - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2Shape* shape, float32 density); - - /// Destroy a fixture. This removes the fixture from the broad-phase and - /// destroys all contacts associated with this fixture. This will - /// automatically adjust the mass of the body if the body is dynamic and the - /// fixture has positive density. - /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. - /// @param fixture the fixture to be removed. - /// @warning This function is locked during callbacks. - void DestroyFixture(b2Fixture* fixture); - - /// Set the position of the body's origin and rotation. - /// This breaks any contacts and wakes the other bodies. - /// Manipulating a body's transform may cause non-physical behavior. - /// @param position the world position of the body's local origin. - /// @param angle the world rotation in radians. - void SetTransform(const b2Vec2& position, float32 angle); - - /// Get the body transform for the body's origin. - /// @return the world transform of the body's origin. - const b2Transform& GetTransform() const; - - /// Get the world body origin position. - /// @return the world position of the body's origin. - const b2Vec2& GetPosition() const; - - /// Get the angle in radians. - /// @return the current world rotation angle in radians. - float32 GetAngle() const; - - /// Get the world position of the center of mass. - const b2Vec2& GetWorldCenter() const; - - /// Get the local position of the center of mass. - const b2Vec2& GetLocalCenter() const; - - /// Set the linear velocity of the center of mass. - /// @param v the new linear velocity of the center of mass. - void SetLinearVelocity(const b2Vec2& v); - - /// Get the linear velocity of the center of mass. - /// @return the linear velocity of the center of mass. - b2Vec2 GetLinearVelocity() const; - - /// Set the angular velocity. - /// @param omega the new angular velocity in radians/second. - void SetAngularVelocity(float32 omega); - - /// Get the angular velocity. - /// @return the angular velocity in radians/second. - float32 GetAngularVelocity() const; - - /// Apply a force at a world point. If the force is not - /// applied at the center of mass, it will generate a torque and - /// affect the angular velocity. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param point the world position of the point of application. - void ApplyForce(const b2Vec2& force, const b2Vec2& point); - - /// Apply a force to the center of mass. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - void ApplyForceToCenter(const b2Vec2& force); - - /// Apply a torque. This affects the angular velocity - /// without affecting the linear velocity of the center of mass. - /// This wakes up the body. - /// @param torque about the z-axis (out of the screen), usually in N-m. - void ApplyTorque(float32 torque); - - /// Apply an impulse at a point. This immediately modifies the velocity. - /// It also modifies the angular velocity if the point of application - /// is not at the center of mass. This wakes up the body. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param point the world position of the point of application. - void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); - - /// Apply an angular impulse. - /// @param impulse the angular impulse in units of kg*m*m/s - void ApplyAngularImpulse(float32 impulse); - - /// Get the total mass of the body. - /// @return the mass, usually in kilograms (kg). - float32 GetMass() const; - - /// Get the rotational inertia of the body about the local origin. - /// @return the rotational inertia, usually in kg-m^2. - float32 GetInertia() const; - - /// Get the mass data of the body. - /// @return a struct containing the mass, inertia and center of the body. - void GetMassData(b2MassData* data) const; - - /// Set the mass properties to override the mass properties of the fixtures. - /// Note that this changes the center of mass position. - /// Note that creating or destroying fixtures can also alter the mass. - /// This function has no effect if the body isn't dynamic. - /// @param massData the mass properties. - void SetMassData(const b2MassData* data); - - /// This resets the mass properties to the sum of the mass properties of the fixtures. - /// This normally does not need to be called unless you called SetMassData to override - /// the mass and you later want to reset the mass. - void ResetMassData(); - - /// Get the world coordinates of a point given the local coordinates. - /// @param localPoint a point on the body measured relative the the body's origin. - /// @return the same point expressed in world coordinates. - b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; - - /// Get the world coordinates of a vector given the local coordinates. - /// @param localVector a vector fixed in the body. - /// @return the same vector expressed in world coordinates. - b2Vec2 GetWorldVector(const b2Vec2& localVector) const; - - /// Gets a local point relative to the body's origin given a world point. - /// @param a point in world coordinates. - /// @return the corresponding local point relative to the body's origin. - b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; - - /// Gets a local vector given a world vector. - /// @param a vector in world coordinates. - /// @return the corresponding local vector. - b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; - - /// Get the world linear velocity of a world point attached to this body. - /// @param a point in world coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; - - /// Get the world velocity of a local point. - /// @param a point in local coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; - - /// Get the linear damping of the body. - float32 GetLinearDamping() const; - - /// Set the linear damping of the body. - void SetLinearDamping(float32 linearDamping); - - /// Get the angular damping of the body. - float32 GetAngularDamping() const; - - /// Set the angular damping of the body. - void SetAngularDamping(float32 angularDamping); - - /// Get the gravity scale of the body. - float32 GetGravityScale() const; - - /// Set the gravity scale of the body. - void SetGravityScale(float32 scale); - - /// Set the type of this body. This may alter the mass and velocity. - void SetType(b2BodyType type); - - /// Get the type of this body. - b2BodyType GetType() const; - - /// Should this body be treated like a bullet for continuous collision detection? - void SetBullet(bool flag); - - /// Is this body treated like a bullet for continuous collision detection? - bool IsBullet() const; - - /// You can disable sleeping on this body. If you disable sleeping, the - /// body will be woken. - void SetSleepingAllowed(bool flag); - - /// Is this body allowed to sleep - bool IsSleepingAllowed() const; - - /// Set the sleep state of the body. A sleeping body has very - /// low CPU cost. - /// @param flag set to true to put body to sleep, false to wake it. - void SetAwake(bool flag); - - /// Get the sleeping state of this body. - /// @return true if the body is sleeping. - bool IsAwake() const; - - /// Set the active state of the body. An inactive body is not - /// simulated and cannot be collided with or woken up. - /// If you pass a flag of true, all fixtures will be added to the - /// broad-phase. - /// If you pass a flag of false, all fixtures will be removed from - /// the broad-phase and all contacts will be destroyed. - /// Fixtures and joints are otherwise unaffected. You may continue - /// to create/destroy fixtures and joints on inactive bodies. - /// Fixtures on an inactive body are implicitly inactive and will - /// not participate in collisions, ray-casts, or queries. - /// Joints connected to an inactive body are implicitly inactive. - /// An inactive body is still owned by a b2World object and remains - /// in the body list. - void SetActive(bool flag); - - /// Get the active state of the body. - bool IsActive() const; - - /// Set this body to have fixed rotation. This causes the mass - /// to be reset. - void SetFixedRotation(bool flag); - - /// Does this body have fixed rotation? - bool IsFixedRotation() const; - - /// Get the list of all fixtures attached to this body. - b2Fixture* GetFixtureList(); - const b2Fixture* GetFixtureList() const; - - /// Get the list of all joints attached to this body. - b2JointEdge* GetJointList(); - const b2JointEdge* GetJointList() const; - - /// Get the list of all contacts attached to this body. - /// @warning this list changes during the time step and you may - /// miss some collisions if you don't use b2ContactListener. - b2ContactEdge* GetContactList(); - const b2ContactEdge* GetContactList() const; - - /// Get the next body in the world's body list. - b2Body* GetNext(); - const b2Body* GetNext() const; - - /// Get the user data pointer that was provided in the body definition. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Get the parent world of this body. - b2World* GetWorld(); - const b2World* GetWorld() const; - - /// Dump this body to a log file - void Dump(); - -private: - - friend class b2World; - friend class b2Island; - friend class b2ContactManager; - friend class b2ContactSolver; - friend class b2Contact; - - friend class b2DistanceJoint; - friend class b2GearJoint; - friend class b2WheelJoint; - friend class b2MouseJoint; - friend class b2PrismaticJoint; - friend class b2PulleyJoint; - friend class b2RevoluteJoint; - friend class b2WeldJoint; - friend class b2FrictionJoint; - friend class b2RopeJoint; - - // m_flags - enum - { - e_islandFlag = 0x0001, - e_awakeFlag = 0x0002, - e_autoSleepFlag = 0x0004, - e_bulletFlag = 0x0008, - e_fixedRotationFlag = 0x0010, - e_activeFlag = 0x0020, - e_toiFlag = 0x0040 - }; - - b2Body(const b2BodyDef* bd, b2World* world); - ~b2Body(); - - void SynchronizeFixtures(); - void SynchronizeTransform(); - - // This is used to prevent connected bodies from colliding. - // It may lie, depending on the collideConnected flag. - bool ShouldCollide(const b2Body* other) const; - - void Advance(float32 t); - - b2BodyType m_type; - - uint16 m_flags; - - int32 m_islandIndex; - - b2Transform m_xf; // the body origin transform - b2Sweep m_sweep; // the swept motion for CCD - - b2Vec2 m_linearVelocity; - float32 m_angularVelocity; - - b2Vec2 m_force; - float32 m_torque; - - b2World* m_world; - b2Body* m_prev; - b2Body* m_next; - - b2Fixture* m_fixtureList; - int32 m_fixtureCount; - - b2JointEdge* m_jointList; - b2ContactEdge* m_contactList; - - float32 m_mass, m_invMass; - - // Rotational inertia about the center of mass. - float32 m_I, m_invI; - - float32 m_linearDamping; - float32 m_angularDamping; - float32 m_gravityScale; - - float32 m_sleepTime; - - void* m_userData; -}; - -inline b2BodyType b2Body::GetType() const -{ - return m_type; -} - -inline const b2Transform& b2Body::GetTransform() const -{ - return m_xf; -} - -inline const b2Vec2& b2Body::GetPosition() const -{ - return m_xf.p; -} - -inline float32 b2Body::GetAngle() const -{ - return m_sweep.a; -} - -inline const b2Vec2& b2Body::GetWorldCenter() const -{ - return m_sweep.c; -} - -inline const b2Vec2& b2Body::GetLocalCenter() const -{ - return m_sweep.localCenter; -} - -inline void b2Body::SetLinearVelocity(const b2Vec2& v) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (b2Dot(v,v) > 0.0f) - { - SetAwake(true); - } - - m_linearVelocity = v; -} - -inline b2Vec2 b2Body::GetLinearVelocity() const -{ - return m_linearVelocity; -} - -inline void b2Body::SetAngularVelocity(float32 w) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (w * w > 0.0f) - { - SetAwake(true); - } - - m_angularVelocity = w; -} - -inline float32 b2Body::GetAngularVelocity() const -{ - return m_angularVelocity; -} - -inline float32 b2Body::GetMass() const -{ - return m_mass; -} - -inline float32 b2Body::GetInertia() const -{ - return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); -} - -inline void b2Body::GetMassData(b2MassData* data) const -{ - data->mass = m_mass; - data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); - data->center = m_sweep.localCenter; -} - -inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const -{ - return b2Mul(m_xf, localPoint); -} - -inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const -{ - return b2Mul(m_xf.q, localVector); -} - -inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const -{ - return b2MulT(m_xf, worldPoint); -} - -inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const -{ - return b2MulT(m_xf.q, worldVector); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const -{ - return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const -{ - return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); -} - -inline float32 b2Body::GetLinearDamping() const -{ - return m_linearDamping; -} - -inline void b2Body::SetLinearDamping(float32 linearDamping) -{ - m_linearDamping = linearDamping; -} - -inline float32 b2Body::GetAngularDamping() const -{ - return m_angularDamping; -} - -inline void b2Body::SetAngularDamping(float32 angularDamping) -{ - m_angularDamping = angularDamping; -} - -inline float32 b2Body::GetGravityScale() const -{ - return m_gravityScale; -} - -inline void b2Body::SetGravityScale(float32 scale) -{ - m_gravityScale = scale; -} - -inline void b2Body::SetBullet(bool flag) -{ - if (flag) - { - m_flags |= e_bulletFlag; - } - else - { - m_flags &= ~e_bulletFlag; - } -} - -inline bool b2Body::IsBullet() const -{ - return (m_flags & e_bulletFlag) == e_bulletFlag; -} - -inline void b2Body::SetAwake(bool flag) -{ - if (flag) - { - if ((m_flags & e_awakeFlag) == 0) - { - m_flags |= e_awakeFlag; - m_sleepTime = 0.0f; - } - } - else - { - m_flags &= ~e_awakeFlag; - m_sleepTime = 0.0f; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_force.SetZero(); - m_torque = 0.0f; - } -} - -inline bool b2Body::IsAwake() const -{ - return (m_flags & e_awakeFlag) == e_awakeFlag; -} - -inline bool b2Body::IsActive() const -{ - return (m_flags & e_activeFlag) == e_activeFlag; -} - -inline void b2Body::SetFixedRotation(bool flag) -{ - if (flag) - { - m_flags |= e_fixedRotationFlag; - } - else - { - m_flags &= ~e_fixedRotationFlag; - } - - ResetMassData(); -} - -inline bool b2Body::IsFixedRotation() const -{ - return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; -} - -inline void b2Body::SetSleepingAllowed(bool flag) -{ - if (flag) - { - m_flags |= e_autoSleepFlag; - } - else - { - m_flags &= ~e_autoSleepFlag; - SetAwake(true); - } -} - -inline bool b2Body::IsSleepingAllowed() const -{ - return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; -} - -inline b2Fixture* b2Body::GetFixtureList() -{ - return m_fixtureList; -} - -inline const b2Fixture* b2Body::GetFixtureList() const -{ - return m_fixtureList; -} - -inline b2JointEdge* b2Body::GetJointList() -{ - return m_jointList; -} - -inline const b2JointEdge* b2Body::GetJointList() const -{ - return m_jointList; -} - -inline b2ContactEdge* b2Body::GetContactList() -{ - return m_contactList; -} - -inline const b2ContactEdge* b2Body::GetContactList() const -{ - return m_contactList; -} - -inline b2Body* b2Body::GetNext() -{ - return m_next; -} - -inline const b2Body* b2Body::GetNext() const -{ - return m_next; -} - -inline void b2Body::SetUserData(void* data) -{ - m_userData = data; -} - -inline void* b2Body::GetUserData() const -{ - return m_userData; -} - -inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_force += force; - m_torque += b2Cross(point - m_sweep.c, force); -} - -inline void b2Body::ApplyForceToCenter(const b2Vec2& force) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_force += force; -} - -inline void b2Body::ApplyTorque(float32 torque) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_torque += torque; -} - -inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - m_linearVelocity += m_invMass * impulse; - m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); -} - -inline void b2Body::ApplyAngularImpulse(float32 impulse) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - m_angularVelocity += m_invI * impulse; -} - -inline void b2Body::SynchronizeTransform() -{ - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline void b2Body::Advance(float32 alpha) -{ - // Advance to the new safe time. This doesn't sync the broad-phase. - m_sweep.Advance(alpha); - m_sweep.c = m_sweep.c0; - m_sweep.a = m_sweep.a0; - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline b2World* b2Body::GetWorld() -{ - return m_world; -} - -inline const b2World* b2Body::GetWorld() const -{ - return m_world; -} - -#endif diff --git a/external/Box2D/Dynamics/b2ContactManager.cpp b/external/Box2D/Dynamics/b2ContactManager.cpp deleted file mode 100644 index c14cc4ce45..0000000000 --- a/external/Box2D/Dynamics/b2ContactManager.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -b2ContactFilter b2_defaultFilter; -b2ContactListener b2_defaultListener; - -b2ContactManager::b2ContactManager() -{ - m_contactList = NULL; - m_contactCount = 0; - m_contactFilter = &b2_defaultFilter; - m_contactListener = &b2_defaultListener; - m_allocator = NULL; -} - -void b2ContactManager::Destroy(b2Contact* c) -{ - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - if (m_contactListener && c->IsTouching()) - { - m_contactListener->EndContact(c); - } - - // Remove from the world. - if (c->m_prev) - { - c->m_prev->m_next = c->m_next; - } - - if (c->m_next) - { - c->m_next->m_prev = c->m_prev; - } - - if (c == m_contactList) - { - m_contactList = c->m_next; - } - - // Remove from body 1 - if (c->m_nodeA.prev) - { - c->m_nodeA.prev->next = c->m_nodeA.next; - } - - if (c->m_nodeA.next) - { - c->m_nodeA.next->prev = c->m_nodeA.prev; - } - - if (&c->m_nodeA == bodyA->m_contactList) - { - bodyA->m_contactList = c->m_nodeA.next; - } - - // Remove from body 2 - if (c->m_nodeB.prev) - { - c->m_nodeB.prev->next = c->m_nodeB.next; - } - - if (c->m_nodeB.next) - { - c->m_nodeB.next->prev = c->m_nodeB.prev; - } - - if (&c->m_nodeB == bodyB->m_contactList) - { - bodyB->m_contactList = c->m_nodeB.next; - } - - // Call the factory. - b2Contact::Destroy(c, m_allocator); - --m_contactCount; -} - -// This is the top level collision call for the time step. Here -// all the narrow phase collision is processed for the world -// contact list. -void b2ContactManager::Collide() -{ - // Update awake contacts. - b2Contact* c = m_contactList; - while (c) - { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Is this contact flagged for filtering? - if (c->m_flags & b2Contact::e_filterFlag) - { - // Should these bodies collide? - if (bodyB->ShouldCollide(bodyA) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Clear the filtering flag. - c->m_flags &= ~b2Contact::e_filterFlag; - } - - bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; - bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - - // At least one body must be awake and it must be dynamic or kinematic. - if (activeA == false && activeB == false) - { - c = c->GetNext(); - continue; - } - - int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; - int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; - bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); - - // Here we destroy contacts that cease to overlap in the broad-phase. - if (overlap == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // The contact persists. - c->Update(m_contactListener); - c = c->GetNext(); - } -} - -void b2ContactManager::FindNewContacts() -{ - m_broadPhase.UpdatePairs(this); -} - -void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) -{ - b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; - b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; - - b2Fixture* fixtureA = proxyA->fixture; - b2Fixture* fixtureB = proxyB->fixture; - - int32 indexA = proxyA->childIndex; - int32 indexB = proxyB->childIndex; - - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Are the fixtures on the same body? - if (bodyA == bodyB) - { - return; - } - - // TODO_ERIN use a hash table to remove a potential bottleneck when both - // bodies have a lot of contacts. - // Does a contact already exist? - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - b2Fixture* fA = edge->contact->GetFixtureA(); - b2Fixture* fB = edge->contact->GetFixtureB(); - int32 iA = edge->contact->GetChildIndexA(); - int32 iB = edge->contact->GetChildIndexB(); - - if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) - { - // A contact already exists. - return; - } - - if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) - { - // A contact already exists. - return; - } - } - - edge = edge->next; - } - - // Does a joint override collision? Is at least one body dynamic? - if (bodyB->ShouldCollide(bodyA) == false) - { - return; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - return; - } - - // Call the factory. - b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); - if (c == NULL) - { - return; - } - - // Contact creation may swap fixtures. - fixtureA = c->GetFixtureA(); - fixtureB = c->GetFixtureB(); - indexA = c->GetChildIndexA(); - indexB = c->GetChildIndexB(); - bodyA = fixtureA->GetBody(); - bodyB = fixtureB->GetBody(); - - // Insert into the world. - c->m_prev = NULL; - c->m_next = m_contactList; - if (m_contactList != NULL) - { - m_contactList->m_prev = c; - } - m_contactList = c; - - // Connect to island graph. - - // Connect to body A - c->m_nodeA.contact = c; - c->m_nodeA.other = bodyB; - - c->m_nodeA.prev = NULL; - c->m_nodeA.next = bodyA->m_contactList; - if (bodyA->m_contactList != NULL) - { - bodyA->m_contactList->prev = &c->m_nodeA; - } - bodyA->m_contactList = &c->m_nodeA; - - // Connect to body B - c->m_nodeB.contact = c; - c->m_nodeB.other = bodyA; - - c->m_nodeB.prev = NULL; - c->m_nodeB.next = bodyB->m_contactList; - if (bodyB->m_contactList != NULL) - { - bodyB->m_contactList->prev = &c->m_nodeB; - } - bodyB->m_contactList = &c->m_nodeB; - - // Wake up the bodies - bodyA->SetAwake(true); - bodyB->SetAwake(true); - - ++m_contactCount; -} diff --git a/external/Box2D/Dynamics/b2ContactManager.h b/external/Box2D/Dynamics/b2ContactManager.h deleted file mode 100644 index 9cb5718145..0000000000 --- a/external/Box2D/Dynamics/b2ContactManager.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_MANAGER_H -#define B2_CONTACT_MANAGER_H - -#include - -class b2Contact; -class b2ContactFilter; -class b2ContactListener; -class b2BlockAllocator; - -// Delegate of b2World. -class b2ContactManager -{ -public: - b2ContactManager(); - - // Broad-phase callback. - void AddPair(void* proxyUserDataA, void* proxyUserDataB); - - void FindNewContacts(); - - void Destroy(b2Contact* c); - - void Collide(); - - b2BroadPhase m_broadPhase; - b2Contact* m_contactList; - int32 m_contactCount; - b2ContactFilter* m_contactFilter; - b2ContactListener* m_contactListener; - b2BlockAllocator* m_allocator; -}; - -#endif diff --git a/external/Box2D/Dynamics/b2Fixture.cpp b/external/Box2D/Dynamics/b2Fixture.cpp deleted file mode 100644 index 774a78e5bb..0000000000 --- a/external/Box2D/Dynamics/b2Fixture.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -b2Fixture::b2Fixture() -{ - m_userData = NULL; - m_body = NULL; - m_next = NULL; - m_proxies = NULL; - m_proxyCount = 0; - m_shape = NULL; - m_density = 0.0f; -} - -void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) -{ - m_userData = def->userData; - m_friction = def->friction; - m_restitution = def->restitution; - - m_body = body; - m_next = NULL; - - m_filter = def->filter; - - m_isSensor = def->isSensor; - - m_shape = def->shape->Clone(allocator); - - // Reserve proxy space - int32 childCount = m_shape->GetChildCount(); - m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); - for (int32 i = 0; i < childCount; ++i) - { - m_proxies[i].fixture = NULL; - m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; - } - m_proxyCount = 0; - - m_density = def->density; -} - -void b2Fixture::Destroy(b2BlockAllocator* allocator) -{ - // The proxies must be destroyed before calling this. - b2Assert(m_proxyCount == 0); - - // Free the proxy array. - int32 childCount = m_shape->GetChildCount(); - allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); - m_proxies = NULL; - - // Free the child shape. - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - s->~b2CircleShape(); - allocator->Free(s, sizeof(b2CircleShape)); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - s->~b2EdgeShape(); - allocator->Free(s, sizeof(b2EdgeShape)); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - s->~b2PolygonShape(); - allocator->Free(s, sizeof(b2PolygonShape)); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - s->~b2ChainShape(); - allocator->Free(s, sizeof(b2ChainShape)); - } - break; - - default: - b2Assert(false); - break; - } - - m_shape = NULL; -} - -void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) -{ - b2Assert(m_proxyCount == 0); - - // Create proxies in the broad-phase. - m_proxyCount = m_shape->GetChildCount(); - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - m_shape->ComputeAABB(&proxy->aabb, xf, i); - proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); - proxy->fixture = this; - proxy->childIndex = i; - } -} - -void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) -{ - // Destroy proxies in the broad-phase. - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - broadPhase->DestroyProxy(proxy->proxyId); - proxy->proxyId = b2BroadPhase::e_nullProxy; - } - - m_proxyCount = 0; -} - -void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) -{ - if (m_proxyCount == 0) - { - return; - } - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb1, aabb2; - m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); - m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); - - proxy->aabb.Combine(aabb1, aabb2); - - b2Vec2 displacement = transform2.p - transform1.p; - - broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); - } -} - -void b2Fixture::SetFilterData(const b2Filter& filter) -{ - m_filter = filter; - - Refilter(); -} - -void b2Fixture::Refilter() -{ - if (m_body == NULL) - { - return; - } - - // Flag associated contacts for filtering. - b2ContactEdge* edge = m_body->GetContactList(); - while (edge) - { - b2Contact* contact = edge->contact; - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == this || fixtureB == this) - { - contact->FlagForFiltering(); - } - - edge = edge->next; - } - - b2World* world = m_body->GetWorld(); - - if (world == NULL) - { - return; - } - - // Touch each proxy so that new pairs may be created - b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; - for (int32 i = 0; i < m_proxyCount; ++i) - { - broadPhase->TouchProxy(m_proxies[i].proxyId); - } -} - -void b2Fixture::SetSensor(bool sensor) -{ - if (sensor != m_isSensor) - { - m_body->SetAwake(true); - m_isSensor = sensor; - } -} - -void b2Fixture::Dump(int32 bodyIndex) -{ - b2Log(" b2FixtureDef fd;\n"); - b2Log(" fd.friction = %.15lef;\n", m_friction); - b2Log(" fd.restitution = %.15lef;\n", m_restitution); - b2Log(" fd.density = %.15lef;\n", m_density); - b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); - b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); - b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); - b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); - - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - b2Log(" b2CircleShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - b2Log(" b2EdgeShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); - b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); - b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); - b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); - b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); - b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - b2Log(" b2PolygonShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); - for (int32 i = 0; i < s->m_vertexCount; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - b2Log(" b2ChainShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", s->m_count); - for (int32 i = 0; i < s->m_count; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); - b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); - b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); - b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); - b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); - } - break; - - default: - return; - } - - b2Log("\n"); - b2Log(" fd.shape = &shape;\n"); - b2Log("\n"); - b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); -} diff --git a/external/Box2D/Dynamics/b2Fixture.h b/external/Box2D/Dynamics/b2Fixture.h deleted file mode 100644 index d390410b93..0000000000 --- a/external/Box2D/Dynamics/b2Fixture.h +++ /dev/null @@ -1,345 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_FIXTURE_H -#define B2_FIXTURE_H - -#include -#include -#include - -class b2BlockAllocator; -class b2Body; -class b2BroadPhase; -class b2Fixture; - -/// This holds contact filtering data. -struct b2Filter -{ - b2Filter() - { - categoryBits = 0x0001; - maskBits = 0xFFFF; - groupIndex = 0; - } - - /// The collision category bits. Normally you would just set one bit. - uint16 categoryBits; - - /// The collision mask bits. This states the categories that this - /// shape would accept for collision. - uint16 maskBits; - - /// Collision groups allow a certain group of objects to never collide (negative) - /// or always collide (positive). Zero means no collision group. Non-zero group - /// filtering always wins against the mask bits. - int16 groupIndex; -}; - -/// A fixture definition is used to create a fixture. This class defines an -/// abstract fixture definition. You can reuse fixture definitions safely. -struct b2FixtureDef -{ - /// The constructor sets the default fixture definition values. - b2FixtureDef() - { - shape = NULL; - userData = NULL; - friction = 0.2f; - restitution = 0.0f; - density = 0.0f; - isSensor = false; - } - - /// The shape, this must be set. The shape will be cloned, so you - /// can create the shape on the stack. - const b2Shape* shape; - - /// Use this to store application specific fixture data. - void* userData; - - /// The friction coefficient, usually in the range [0,1]. - float32 friction; - - /// The restitution (elasticity) usually in the range [0,1]. - float32 restitution; - - /// The density, usually in kg/m^2. - float32 density; - - /// A sensor shape collects contact information but never generates a collision - /// response. - bool isSensor; - - /// Contact filtering data. - b2Filter filter; -}; - -/// This proxy is used internally to connect fixtures to the broad-phase. -struct b2FixtureProxy -{ - b2AABB aabb; - b2Fixture* fixture; - int32 childIndex; - int32 proxyId; -}; - -/// A fixture is used to attach a shape to a body for collision detection. A fixture -/// inherits its transform from its parent. Fixtures hold additional non-geometric data -/// such as friction, collision filters, etc. -/// Fixtures are created via b2Body::CreateFixture. -/// @warning you cannot reuse fixtures. -class b2Fixture -{ -public: - /// Get the type of the child shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - b2Shape::Type GetType() const; - - /// Get the child shape. You can modify the child shape, however you should not change the - /// number of vertices because this will crash some collision caching mechanisms. - /// Manipulating the shape may lead to non-physical behavior. - b2Shape* GetShape(); - const b2Shape* GetShape() const; - - /// Set if this fixture is a sensor. - void SetSensor(bool sensor); - - /// Is this fixture a sensor (non-solid)? - /// @return the true if the shape is a sensor. - bool IsSensor() const; - - /// Set the contact filtering data. This will not update contacts until the next time - /// step when either parent body is active and awake. - /// This automatically calls Refilter. - void SetFilterData(const b2Filter& filter); - - /// Get the contact filtering data. - const b2Filter& GetFilterData() const; - - /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. - void Refilter(); - - /// Get the parent body of this fixture. This is NULL if the fixture is not attached. - /// @return the parent body. - b2Body* GetBody(); - const b2Body* GetBody() const; - - /// Get the next fixture in the parent body's fixture list. - /// @return the next shape. - b2Fixture* GetNext(); - const b2Fixture* GetNext() const; - - /// Get the user data that was assigned in the fixture definition. Use this to - /// store your application specific data. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Test a point for containment in this fixture. - /// @param p a point in world coordinates. - bool TestPoint(const b2Vec2& p) const; - - /// Cast a ray against this shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; - - /// Get the mass data for this fixture. The mass data is based on the density and - /// the shape. The rotational inertia is about the shape's origin. This operation - /// may be expensive. - void GetMassData(b2MassData* massData) const; - - /// Set the density of this fixture. This will _not_ automatically adjust the mass - /// of the body. You must call b2Body::ResetMassData to update the body's mass. - void SetDensity(float32 density); - - /// Get the density of this fixture. - float32 GetDensity() const; - - /// Get the coefficient of friction. - float32 GetFriction() const; - - /// Set the coefficient of friction. This will _not_ change the friction of - /// existing contacts. - void SetFriction(float32 friction); - - /// Get the coefficient of restitution. - float32 GetRestitution() const; - - /// Set the coefficient of restitution. This will _not_ change the restitution of - /// existing contacts. - void SetRestitution(float32 restitution); - - /// Get the fixture's AABB. This AABB may be enlarge and/or stale. - /// If you need a more accurate AABB, compute it using the shape and - /// the body transform. - const b2AABB& GetAABB(int32 childIndex) const; - - /// Dump this fixture to the log file. - void Dump(int32 bodyIndex); - -protected: - - friend class b2Body; - friend class b2World; - friend class b2Contact; - friend class b2ContactManager; - - b2Fixture(); - - // We need separation create/destroy functions from the constructor/destructor because - // the destructor cannot access the allocator (no destructor arguments allowed by C++). - void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); - void Destroy(b2BlockAllocator* allocator); - - // These support body activation/deactivation. - void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); - void DestroyProxies(b2BroadPhase* broadPhase); - - void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); - - float32 m_density; - - b2Fixture* m_next; - b2Body* m_body; - - b2Shape* m_shape; - - float32 m_friction; - float32 m_restitution; - - b2FixtureProxy* m_proxies; - int32 m_proxyCount; - - b2Filter m_filter; - - bool m_isSensor; - - void* m_userData; -}; - -inline b2Shape::Type b2Fixture::GetType() const -{ - return m_shape->GetType(); -} - -inline b2Shape* b2Fixture::GetShape() -{ - return m_shape; -} - -inline const b2Shape* b2Fixture::GetShape() const -{ - return m_shape; -} - -inline bool b2Fixture::IsSensor() const -{ - return m_isSensor; -} - -inline const b2Filter& b2Fixture::GetFilterData() const -{ - return m_filter; -} - -inline void* b2Fixture::GetUserData() const -{ - return m_userData; -} - -inline void b2Fixture::SetUserData(void* data) -{ - m_userData = data; -} - -inline b2Body* b2Fixture::GetBody() -{ - return m_body; -} - -inline const b2Body* b2Fixture::GetBody() const -{ - return m_body; -} - -inline b2Fixture* b2Fixture::GetNext() -{ - return m_next; -} - -inline const b2Fixture* b2Fixture::GetNext() const -{ - return m_next; -} - -inline void b2Fixture::SetDensity(float32 density) -{ - b2Assert(b2IsValid(density) && density >= 0.0f); - m_density = density; -} - -inline float32 b2Fixture::GetDensity() const -{ - return m_density; -} - -inline float32 b2Fixture::GetFriction() const -{ - return m_friction; -} - -inline void b2Fixture::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Fixture::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Fixture::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline bool b2Fixture::TestPoint(const b2Vec2& p) const -{ - return m_shape->TestPoint(m_body->GetTransform(), p); -} - -inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const -{ - return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); -} - -inline void b2Fixture::GetMassData(b2MassData* massData) const -{ - m_shape->ComputeMass(massData, m_density); -} - -inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const -{ - b2Assert(0 <= childIndex && childIndex < m_proxyCount); - return m_proxies[childIndex].aabb; -} - -#endif diff --git a/external/Box2D/Dynamics/b2Island.cpp b/external/Box2D/Dynamics/b2Island.cpp deleted file mode 100644 index e767d383d5..0000000000 --- a/external/Box2D/Dynamics/b2Island.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* -Position Correction Notes -========================= -I tried the several algorithms for position correction of the 2D revolute joint. -I looked at these systems: -- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. -- suspension bridge with 30 1m long planks of length 1m. -- multi-link chain with 30 1m long links. - -Here are the algorithms: - -Baumgarte - A fraction of the position error is added to the velocity error. There is no -separate position solver. - -Pseudo Velocities - After the velocity solver and position integration, -the position error, Jacobian, and effective mass are recomputed. Then -the velocity constraints are solved with pseudo velocities and a fraction -of the position error is added to the pseudo velocity error. The pseudo -velocities are initialized to zero and there is no warm-starting. After -the position solver, the pseudo velocities are added to the positions. -This is also called the First Order World method or the Position LCP method. - -Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the -position error is re-computed for each constraint and the positions are updated -after the constraint is solved. The radius vectors (aka Jacobians) are -re-computed too (otherwise the algorithm has horrible instability). The pseudo -velocity states are not needed because they are effectively zero at the beginning -of each iteration. Since we have the current position error, we allow the -iterations to terminate early if the error becomes smaller than b2_linearSlop. - -Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed -each time a constraint is solved. - -Here are the results: -Baumgarte - this is the cheapest algorithm but it has some stability problems, -especially with the bridge. The chain links separate easily close to the root -and they jitter as they struggle to pull together. This is one of the most common -methods in the field. The big drawback is that the position correction artificially -affects the momentum, thus leading to instabilities and false bounce. I used a -bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller -factor makes joints and contacts more spongy. - -Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is -stable. However, joints still separate with large angular velocities. Drag the -simple pendulum in a circle quickly and the joint will separate. The chain separates -easily and does not recover. I used a bias factor of 0.2. A larger value lead to -the bridge collapsing when a heavy cube drops on it. - -Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo -Velocities, but in other ways it is worse. The bridge and chain are much more -stable, but the simple pendulum goes unstable at high angular velocities. - -Full NGS - stable in all tests. The joints display good stiffness. The bridge -still sags, but this is better than infinite forces. - -Recommendations -Pseudo Velocities are not really worthwhile because the bridge and chain cannot -recover from joint separation. In other cases the benefit over Baumgarte is small. - -Modified NGS is not a robust method for the revolute joint due to the violent -instability seen in the simple pendulum. Perhaps it is viable with other constraint -types, especially scalar constraints where the effective mass is a scalar. - -This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities -and is very fast. I don't think we can escape Baumgarte, especially in highly -demanding cases where high constraint fidelity is not needed. - -Full NGS is robust and easy on the eyes. I recommend this as an option for -higher fidelity simulation and certainly for suspension bridges and long chains. -Full NGS might be a good choice for ragdolls, especially motorized ragdolls where -joint separation can be problematic. The number of NGS iterations can be reduced -for better performance without harming robustness much. - -Each joint in a can be handled differently in the position solver. So I recommend -a system where the user can select the algorithm on a per joint basis. I would -probably default to the slower Full NGS and let the user select the faster -Baumgarte method in performance critical scenarios. -*/ - -/* -Cache Performance - -The Box2D solvers are dominated by cache misses. Data structures are designed -to increase the number of cache hits. Much of misses are due to random access -to body data. The constraint structures are iterated over linearly, which leads -to few cache misses. - -The bodies are not accessed during iteration. Instead read only data, such as -the mass values are stored with the constraints. The mutable data are the constraint -impulses and the bodies velocities/positions. The impulses are held inside the -constraint structures. The body velocities/positions are held in compact, temporary -arrays to increase the number of cache hits. Linear and angular velocity are -stored in a single array since multiple arrays lead to multiple misses. -*/ - -/* -2D Rotation - -R = [cos(theta) -sin(theta)] - [sin(theta) cos(theta) ] - -thetaDot = omega - -Let q1 = cos(theta), q2 = sin(theta). -R = [q1 -q2] - [q2 q1] - -q1Dot = -thetaDot * q2 -q2Dot = thetaDot * q1 - -q1_new = q1_old - dt * w * q2 -q2_new = q2_old + dt * w * q1 -then normalize. - -This might be faster than computing sin+cos. -However, we can compute sin+cos of the same angle fast. -*/ - -b2Island::b2Island( - int32 bodyCapacity, - int32 contactCapacity, - int32 jointCapacity, - b2StackAllocator* allocator, - b2ContactListener* listener) -{ - m_bodyCapacity = bodyCapacity; - m_contactCapacity = contactCapacity; - m_jointCapacity = jointCapacity; - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - - m_allocator = allocator; - m_listener = listener; - - m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); - m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); - m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); - - m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); - m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); -} - -b2Island::~b2Island() -{ - // Warning: the order should reverse the constructor order. - m_allocator->Free(m_positions); - m_allocator->Free(m_velocities); - m_allocator->Free(m_joints); - m_allocator->Free(m_contacts); - m_allocator->Free(m_bodies); -} - -void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) -{ - b2Timer timer; - - float32 h = step.dt; - - // Integrate velocities and apply damping. Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - - b2Vec2 c = b->m_sweep.c; - float32 a = b->m_sweep.a; - b2Vec2 v = b->m_linearVelocity; - float32 w = b->m_angularVelocity; - - // Store positions for continuous collision. - b->m_sweep.c0 = b->m_sweep.c; - b->m_sweep.a0 = b->m_sweep.a; - - if (b->m_type == b2_dynamicBody) - { - // Integrate velocities. - v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); - w += h * b->m_invI * b->m_torque; - - // Apply damping. - // ODE: dv/dt + c * v = 0 - // Solution: v(t) = v0 * exp(-c * t) - // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) - // v2 = exp(-c * dt) * v1 - // Taylor expansion: - // v2 = (1.0f - c * dt) * v1 - v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); - w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); - } - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - timer.Reset(); - - // Solver data - b2SolverData solverData; - solverData.step = step; - solverData.positions = m_positions; - solverData.velocities = m_velocities; - - // Initialize velocity constraints. - b2ContactSolverDef contactSolverDef; - contactSolverDef.step = step; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - contactSolverDef.allocator = m_allocator; - - b2ContactSolver contactSolver(&contactSolverDef); - contactSolver.InitializeVelocityConstraints(); - - if (step.warmStarting) - { - contactSolver.WarmStart(); - } - - for (int32 i = 0; i < m_jointCount; ++i) - { - m_joints[i]->InitVelocityConstraints(solverData); - } - - profile->solveInit = timer.GetMilliseconds(); - - // Solve velocity constraints - timer.Reset(); - for (int32 i = 0; i < step.velocityIterations; ++i) - { - for (int32 j = 0; j < m_jointCount; ++j) - { - m_joints[j]->SolveVelocityConstraints(solverData); - } - - contactSolver.SolveVelocityConstraints(); - } - - // Store impulses for warm starting - contactSolver.StoreImpulses(); - profile->solveVelocity = timer.GetMilliseconds(); - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - // Solve position constraints - timer.Reset(); - bool positionSolved = false; - for (int32 i = 0; i < step.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolvePositionConstraints(); - - bool jointsOkay = true; - for (int32 i = 0; i < m_jointCount; ++i) - { - bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); - jointsOkay = jointsOkay && jointOkay; - } - - if (contactsOkay && jointsOkay) - { - // Exit early if the position errors are small. - positionSolved = true; - break; - } - } - - // Copy state buffers back to the bodies - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* body = m_bodies[i]; - body->m_sweep.c = m_positions[i].c; - body->m_sweep.a = m_positions[i].a; - body->m_linearVelocity = m_velocities[i].v; - body->m_angularVelocity = m_velocities[i].w; - body->SynchronizeTransform(); - } - - profile->solvePosition = timer.GetMilliseconds(); - - Report(contactSolver.m_velocityConstraints); - - if (allowSleep) - { - float32 minSleepTime = b2_maxFloat; - - const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; - const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; - - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - continue; - } - - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || - b->m_angularVelocity * b->m_angularVelocity > angTolSqr || - b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) - { - b->m_sleepTime = 0.0f; - minSleepTime = 0.0f; - } - else - { - b->m_sleepTime += h; - minSleepTime = b2Min(minSleepTime, b->m_sleepTime); - } - } - - if (minSleepTime >= b2_timeToSleep && positionSolved) - { - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - b->SetAwake(false); - } - } - } -} - -void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) -{ - b2Assert(toiIndexA < m_bodyCount); - b2Assert(toiIndexB < m_bodyCount); - - // Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - m_positions[i].c = b->m_sweep.c; - m_positions[i].a = b->m_sweep.a; - m_velocities[i].v = b->m_linearVelocity; - m_velocities[i].w = b->m_angularVelocity; - } - - b2ContactSolverDef contactSolverDef; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.allocator = m_allocator; - contactSolverDef.step = subStep; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - b2ContactSolver contactSolver(&contactSolverDef); - - // Solve position constraints. - for (int32 i = 0; i < subStep.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); - if (contactsOkay) - { - break; - } - } - -#if 0 - // Is the new position really safe? - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - b2DistanceInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.transformA = bA->GetTransform(); - input.transformB = bB->GetTransform(); - input.useRadii = false; - - b2DistanceOutput output; - b2SimplexCache cache; - cache.count = 0; - b2Distance(&output, &cache, &input); - - if (output.distance == 0 || cache.count == 3) - { - cache.count += 0; - } - } -#endif - - // Leap of faith to new safe state. - m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; - m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; - m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; - m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; - - // No warm starting is needed for TOI events because warm - // starting impulses were applied in the discrete solver. - contactSolver.InitializeVelocityConstraints(); - - // Solve velocity constraints. - for (int32 i = 0; i < subStep.velocityIterations; ++i) - { - contactSolver.SolveVelocityConstraints(); - } - - // Don't store the TOI contact forces for warm starting - // because they can be quite large. - - float32 h = subStep.dt; - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - - // Sync bodies - b2Body* body = m_bodies[i]; - body->m_sweep.c = c; - body->m_sweep.a = a; - body->m_linearVelocity = v; - body->m_angularVelocity = w; - body->SynchronizeTransform(); - } - - Report(contactSolver.m_velocityConstraints); -} - -void b2Island::Report(const b2ContactVelocityConstraint* constraints) -{ - if (m_listener == NULL) - { - return; - } - - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - - const b2ContactVelocityConstraint* vc = constraints + i; - - b2ContactImpulse impulse; - impulse.count = vc->pointCount; - for (int32 j = 0; j < vc->pointCount; ++j) - { - impulse.normalImpulses[j] = vc->points[j].normalImpulse; - impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; - } - - m_listener->PostSolve(c, &impulse); - } -} diff --git a/external/Box2D/Dynamics/b2Island.h b/external/Box2D/Dynamics/b2Island.h deleted file mode 100644 index e0a6e41fc3..0000000000 --- a/external/Box2D/Dynamics/b2Island.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ISLAND_H -#define B2_ISLAND_H - -#include -#include -#include - -class b2Contact; -class b2Joint; -class b2StackAllocator; -class b2ContactListener; -struct b2ContactVelocityConstraint; -struct b2Profile; - -/// This is an internal class. -class b2Island -{ -public: - b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, - b2StackAllocator* allocator, b2ContactListener* listener); - ~b2Island(); - - void Clear() - { - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - } - - void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); - - void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); - - void Add(b2Body* body) - { - b2Assert(m_bodyCount < m_bodyCapacity); - body->m_islandIndex = m_bodyCount; - m_bodies[m_bodyCount] = body; - ++m_bodyCount; - } - - void Add(b2Contact* contact) - { - b2Assert(m_contactCount < m_contactCapacity); - m_contacts[m_contactCount++] = contact; - } - - void Add(b2Joint* joint) - { - b2Assert(m_jointCount < m_jointCapacity); - m_joints[m_jointCount++] = joint; - } - - void Report(const b2ContactVelocityConstraint* constraints); - - b2StackAllocator* m_allocator; - b2ContactListener* m_listener; - - b2Body** m_bodies; - b2Contact** m_contacts; - b2Joint** m_joints; - - b2Position* m_positions; - b2Velocity* m_velocities; - - int32 m_bodyCount; - int32 m_jointCount; - int32 m_contactCount; - - int32 m_bodyCapacity; - int32 m_contactCapacity; - int32 m_jointCapacity; -}; - -#endif diff --git a/external/Box2D/Dynamics/b2TimeStep.h b/external/Box2D/Dynamics/b2TimeStep.h deleted file mode 100644 index 30d723fcc3..0000000000 --- a/external/Box2D/Dynamics/b2TimeStep.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_TIME_STEP_H -#define B2_TIME_STEP_H - -#include - -/// Profiling data. Times are in milliseconds. -struct b2Profile -{ - float32 step; - float32 collide; - float32 solve; - float32 solveInit; - float32 solveVelocity; - float32 solvePosition; - float32 broadphase; - float32 solveTOI; -}; - -/// This is an internal structure. -struct b2TimeStep -{ - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 velocityIterations; - int32 positionIterations; - bool warmStarting; -}; - -/// This is an internal structure. -struct b2Position -{ - b2Vec2 c; - float32 a; -}; - -/// This is an internal structure. -struct b2Velocity -{ - b2Vec2 v; - float32 w; -}; - -/// Solver Data -struct b2SolverData -{ - b2TimeStep step; - b2Position* positions; - b2Velocity* velocities; -}; - -#endif diff --git a/external/Box2D/Dynamics/b2World.cpp b/external/Box2D/Dynamics/b2World.cpp deleted file mode 100644 index 8a0aff5114..0000000000 --- a/external/Box2D/Dynamics/b2World.cpp +++ /dev/null @@ -1,1316 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -b2World::b2World(const b2Vec2& gravity) -{ - m_destructionListener = NULL; - m_debugDraw = NULL; - - m_bodyList = NULL; - m_jointList = NULL; - - m_bodyCount = 0; - m_jointCount = 0; - - m_warmStarting = true; - m_continuousPhysics = true; - m_subStepping = false; - - m_stepComplete = true; - - m_allowSleep = true; - m_gravity = gravity; - - m_flags = e_clearForces; - - m_inv_dt0 = 0.0f; - - m_contactManager.m_allocator = &m_blockAllocator; - - memset(&m_profile, 0, sizeof(b2Profile)); -} - -b2World::~b2World() -{ - // Some shapes allocate using b2Alloc. - b2Body* b = m_bodyList; - while (b) - { - b2Body* bNext = b->m_next; - - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* fNext = f->m_next; - f->m_proxyCount = 0; - f->Destroy(&m_blockAllocator); - f = fNext; - } - - b = bNext; - } -} - -void b2World::SetDestructionListener(b2DestructionListener* listener) -{ - m_destructionListener = listener; -} - -void b2World::SetContactFilter(b2ContactFilter* filter) -{ - m_contactManager.m_contactFilter = filter; -} - -void b2World::SetContactListener(b2ContactListener* listener) -{ - m_contactManager.m_contactListener = listener; -} - -void b2World::SetDebugDraw(b2Draw* debugDraw) -{ - m_debugDraw = debugDraw; -} - -b2Body* b2World::CreateBody(const b2BodyDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } - - void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); - b2Body* b = new (mem) b2Body(def, this); - - // Add to world doubly linked list. - b->m_prev = NULL; - b->m_next = m_bodyList; - if (m_bodyList) - { - m_bodyList->m_prev = b; - } - m_bodyList = b; - ++m_bodyCount; - - return b; -} - -void b2World::DestroyBody(b2Body* b) -{ - b2Assert(m_bodyCount > 0); - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - // Delete the attached joints. - b2JointEdge* je = b->m_jointList; - while (je) - { - b2JointEdge* je0 = je; - je = je->next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(je0->joint); - } - - DestroyJoint(je0->joint); - - b->m_jointList = je; - } - b->m_jointList = NULL; - - // Delete the attached contacts. - b2ContactEdge* ce = b->m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_contactManager.Destroy(ce0->contact); - } - b->m_contactList = NULL; - - // Delete the attached fixtures. This destroys broad-phase proxies. - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* f0 = f; - f = f->m_next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(f0); - } - - f0->DestroyProxies(&m_contactManager.m_broadPhase); - f0->Destroy(&m_blockAllocator); - f0->~b2Fixture(); - m_blockAllocator.Free(f0, sizeof(b2Fixture)); - - b->m_fixtureList = f; - b->m_fixtureCount -= 1; - } - b->m_fixtureList = NULL; - b->m_fixtureCount = 0; - - // Remove world body list. - if (b->m_prev) - { - b->m_prev->m_next = b->m_next; - } - - if (b->m_next) - { - b->m_next->m_prev = b->m_prev; - } - - if (b == m_bodyList) - { - m_bodyList = b->m_next; - } - - --m_bodyCount; - b->~b2Body(); - m_blockAllocator.Free(b, sizeof(b2Body)); -} - -b2Joint* b2World::CreateJoint(const b2JointDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } - - b2Joint* j = b2Joint::Create(def, &m_blockAllocator); - - // Connect to the world list. - j->m_prev = NULL; - j->m_next = m_jointList; - if (m_jointList) - { - m_jointList->m_prev = j; - } - m_jointList = j; - ++m_jointCount; - - // Connect to the bodies' doubly linked lists. - j->m_edgeA.joint = j; - j->m_edgeA.other = j->m_bodyB; - j->m_edgeA.prev = NULL; - j->m_edgeA.next = j->m_bodyA->m_jointList; - if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; - j->m_bodyA->m_jointList = &j->m_edgeA; - - j->m_edgeB.joint = j; - j->m_edgeB.other = j->m_bodyA; - j->m_edgeB.prev = NULL; - j->m_edgeB.next = j->m_bodyB->m_jointList; - if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; - j->m_bodyB->m_jointList = &j->m_edgeB; - - b2Body* bodyA = def->bodyA; - b2Body* bodyB = def->bodyB; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (def->collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } - - // Note: creating a joint doesn't wake the bodies. - - return j; -} - -void b2World::DestroyJoint(b2Joint* j) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - bool collideConnected = j->m_collideConnected; - - // Remove from the doubly linked list. - if (j->m_prev) - { - j->m_prev->m_next = j->m_next; - } - - if (j->m_next) - { - j->m_next->m_prev = j->m_prev; - } - - if (j == m_jointList) - { - m_jointList = j->m_next; - } - - // Disconnect from island graph. - b2Body* bodyA = j->m_bodyA; - b2Body* bodyB = j->m_bodyB; - - // Wake up connected bodies. - bodyA->SetAwake(true); - bodyB->SetAwake(true); - - // Remove from body 1. - if (j->m_edgeA.prev) - { - j->m_edgeA.prev->next = j->m_edgeA.next; - } - - if (j->m_edgeA.next) - { - j->m_edgeA.next->prev = j->m_edgeA.prev; - } - - if (&j->m_edgeA == bodyA->m_jointList) - { - bodyA->m_jointList = j->m_edgeA.next; - } - - j->m_edgeA.prev = NULL; - j->m_edgeA.next = NULL; - - // Remove from body 2 - if (j->m_edgeB.prev) - { - j->m_edgeB.prev->next = j->m_edgeB.next; - } - - if (j->m_edgeB.next) - { - j->m_edgeB.next->prev = j->m_edgeB.prev; - } - - if (&j->m_edgeB == bodyB->m_jointList) - { - bodyB->m_jointList = j->m_edgeB.next; - } - - j->m_edgeB.prev = NULL; - j->m_edgeB.next = NULL; - - b2Joint::Destroy(j, &m_blockAllocator); - - b2Assert(m_jointCount > 0); - --m_jointCount; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } -} - -// -void b2World::SetAllowSleeping(bool flag) -{ - if (flag == m_allowSleep) - { - return; - } - - m_allowSleep = flag; - if (m_allowSleep == false) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->SetAwake(true); - } - } -} - -// Find islands, integrate and solve constraints, solve position constraints -void b2World::Solve(const b2TimeStep& step) -{ - m_profile.solveInit = 0.0f; - m_profile.solveVelocity = 0.0f; - m_profile.solvePosition = 0.0f; - - // Size the island for the worst case. - b2Island island(m_bodyCount, - m_contactManager.m_contactCount, - m_jointCount, - &m_stackAllocator, - m_contactManager.m_contactListener); - - // Clear all the island flags. - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - c->m_flags &= ~b2Contact::e_islandFlag; - } - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_islandFlag = false; - } - - // Build and simulate all awake islands. - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) - { - if (seed->m_flags & b2Body::e_islandFlag) - { - continue; - } - - if (seed->IsAwake() == false || seed->IsActive() == false) - { - continue; - } - - // The seed can be dynamic or kinematic. - if (seed->GetType() == b2_staticBody) - { - continue; - } - - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; - - // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - b2Assert(b->IsActive() == true); - island.Add(b); - - // Make sure the body is awake. - b->SetAwake(true); - - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Search all contacts connected to this body. - for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) - { - b2Contact* contact = ce->contact; - - // Has this contact already been added to an island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Is this contact solid and touching? - if (contact->IsEnabled() == false || - contact->IsTouching() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - island.Add(contact); - contact->m_flags |= b2Contact::e_islandFlag; - - b2Body* other = ce->other; - - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - - // Search all joints connect to this body. - for (b2JointEdge* je = b->m_jointList; je; je = je->next) - { - if (je->joint->m_islandFlag == true) - { - continue; - } - - b2Body* other = je->other; - - // Don't simulate joints connected to inactive bodies. - if (other->IsActive() == false) - { - continue; - } - - island.Add(je->joint); - je->joint->m_islandFlag = true; - - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } - - b2Profile profile; - island.Solve(&profile, step, m_gravity, m_allowSleep); - m_profile.solveInit += profile.solveInit; - m_profile.solveVelocity += profile.solveVelocity; - m_profile.solvePosition += profile.solvePosition; - - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow static bodies to participate in other islands. - b2Body* b = island.m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - } - } - - m_stackAllocator.Free(stack); - - { - b2Timer timer; - // Synchronize fixtures, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - // If a body was not in an island then it did not move. - if ((b->m_flags & b2Body::e_islandFlag) == 0) - { - continue; - } - - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Update fixtures (for broad-phase). - b->SynchronizeFixtures(); - } - - // Look for new contacts. - m_contactManager.FindNewContacts(); - m_profile.broadphase = timer.GetMilliseconds(); - } -} - -// Find TOI contacts and solve them. -void b2World::SolveTOI(const b2TimeStep& step) -{ - b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); - - if (m_stepComplete) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - b->m_sweep.alpha0 = 0.0f; - } - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Invalidate TOI - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - c->m_toiCount = 0; - c->m_toi = 1.0f; - } - } - - // Find TOI events and solve them. - for (;;) - { - // Find the first TOI. - b2Contact* minContact = NULL; - float32 minAlpha = 1.0f; - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Is this contact disabled? - if (c->IsEnabled() == false) - { - continue; - } - - // Prevent excessive sub-stepping. - if (c->m_toiCount > b2_maxSubSteps) - { - continue; - } - - float32 alpha = 1.0f; - if (c->m_flags & b2Contact::e_toiFlag) - { - // This contact has a valid cached TOI. - alpha = c->m_toi; - } - else - { - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - // Is there a sensor? - if (fA->IsSensor() || fB->IsSensor()) - { - continue; - } - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2BodyType typeA = bA->m_type; - b2BodyType typeB = bB->m_type; - b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); - - bool activeA = bA->IsAwake() && typeA != b2_staticBody; - bool activeB = bB->IsAwake() && typeB != b2_staticBody; - - // Is at least one body active (awake and dynamic or kinematic)? - if (activeA == false && activeB == false) - { - continue; - } - - bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; - bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; - - // Are these two non-bullet dynamic bodies? - if (collideA == false && collideB == false) - { - continue; - } - - // Compute the TOI for this contact. - // Put the sweeps onto the same time interval. - float32 alpha0 = bA->m_sweep.alpha0; - - if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) - { - alpha0 = bB->m_sweep.alpha0; - bA->m_sweep.Advance(alpha0); - } - else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) - { - alpha0 = bA->m_sweep.alpha0; - bB->m_sweep.Advance(alpha0); - } - - b2Assert(alpha0 < 1.0f); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - // Compute the time of impact in interval [0, minTOI] - b2TOIInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.sweepA = bA->m_sweep; - input.sweepB = bB->m_sweep; - input.tMax = 1.0f; - - b2TOIOutput output; - b2TimeOfImpact(&output, &input); - - // Beta is the fraction of the remaining portion of the . - float32 beta = output.t; - if (output.state == b2TOIOutput::e_touching) - { - alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); - } - else - { - alpha = 1.0f; - } - - c->m_toi = alpha; - c->m_flags |= b2Contact::e_toiFlag; - } - - if (alpha < minAlpha) - { - // This is the minimum TOI found so far. - minContact = c; - minAlpha = alpha; - } - } - - if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) - { - // No more TOI events. Done! - m_stepComplete = true; - break; - } - - // Advance the bodies to the TOI. - b2Fixture* fA = minContact->GetFixtureA(); - b2Fixture* fB = minContact->GetFixtureB(); - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2Sweep backup1 = bA->m_sweep; - b2Sweep backup2 = bB->m_sweep; - - bA->Advance(minAlpha); - bB->Advance(minAlpha); - - // The TOI contact likely has some new contact points. - minContact->Update(m_contactManager.m_contactListener); - minContact->m_flags &= ~b2Contact::e_toiFlag; - ++minContact->m_toiCount; - - // Is the contact solid? - if (minContact->IsEnabled() == false || minContact->IsTouching() == false) - { - // Restore the sweeps. - minContact->SetEnabled(false); - bA->m_sweep = backup1; - bB->m_sweep = backup2; - bA->SynchronizeTransform(); - bB->SynchronizeTransform(); - continue; - } - - bA->SetAwake(true); - bB->SetAwake(true); - - // Build the island - island.Clear(); - island.Add(bA); - island.Add(bB); - island.Add(minContact); - - bA->m_flags |= b2Body::e_islandFlag; - bB->m_flags |= b2Body::e_islandFlag; - minContact->m_flags |= b2Contact::e_islandFlag; - - // Get contacts on bodyA and bodyB. - b2Body* bodies[2] = {bA, bB}; - for (int32 i = 0; i < 2; ++i) - { - b2Body* body = bodies[i]; - if (body->m_type == b2_dynamicBody) - { - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - if (island.m_bodyCount == island.m_bodyCapacity) - { - break; - } - - if (island.m_contactCount == island.m_contactCapacity) - { - break; - } - - b2Contact* contact = ce->contact; - - // Has this contact already been added to the island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Only add static, kinematic, or bullet bodies. - b2Body* other = ce->other; - if (other->m_type == b2_dynamicBody && - body->IsBullet() == false && other->IsBullet() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - // Tentatively advance the body to the TOI. - b2Sweep backup = other->m_sweep; - if ((other->m_flags & b2Body::e_islandFlag) == 0) - { - other->Advance(minAlpha); - } - - // Update the contact points - contact->Update(m_contactManager.m_contactListener); - - // Was the contact disabled by the user? - if (contact->IsEnabled() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Are there contact points? - if (contact->IsTouching() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Add the contact to the island - contact->m_flags |= b2Contact::e_islandFlag; - island.Add(contact); - - // Has the other body already been added to the island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - // Add the other body to the island. - other->m_flags |= b2Body::e_islandFlag; - - if (other->m_type != b2_staticBody) - { - other->SetAwake(true); - } - - island.Add(other); - } - } - } - - b2TimeStep subStep; - subStep.dt = (1.0f - minAlpha) * step.dt; - subStep.inv_dt = 1.0f / subStep.dt; - subStep.dtRatio = 1.0f; - subStep.positionIterations = 20; - subStep.velocityIterations = step.velocityIterations; - subStep.warmStarting = false; - island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); - - // Reset island flags and synchronize broad-phase proxies. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - b2Body* body = island.m_bodies[i]; - body->m_flags &= ~b2Body::e_islandFlag; - - if (body->m_type != b2_dynamicBody) - { - continue; - } - - body->SynchronizeFixtures(); - - // Invalidate all contact TOIs on this displaced body. - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - } - - // Commit fixture proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_contactManager.FindNewContacts(); - - if (m_subStepping) - { - m_stepComplete = false; - break; - } - } -} - -void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) -{ - b2Timer stepTimer; - - // If new fixtures were added, we need to find the new contacts. - if (m_flags & e_newFixture) - { - m_contactManager.FindNewContacts(); - m_flags &= ~e_newFixture; - } - - m_flags |= e_locked; - - b2TimeStep step; - step.dt = dt; - step.velocityIterations = velocityIterations; - step.positionIterations = positionIterations; - if (dt > 0.0f) - { - step.inv_dt = 1.0f / dt; - } - else - { - step.inv_dt = 0.0f; - } - - step.dtRatio = m_inv_dt0 * dt; - - step.warmStarting = m_warmStarting; - - // Update contacts. This is where some contacts are destroyed. - { - b2Timer timer; - m_contactManager.Collide(); - m_profile.collide = timer.GetMilliseconds(); - } - - // Integrate velocities, solve velocity constraints, and integrate positions. - if (m_stepComplete && step.dt > 0.0f) - { - b2Timer timer; - Solve(step); - m_profile.solve = timer.GetMilliseconds(); - } - - // Handle TOI events. - if (m_continuousPhysics && step.dt > 0.0f) - { - b2Timer timer; - SolveTOI(step); - m_profile.solveTOI = timer.GetMilliseconds(); - } - - if (step.dt > 0.0f) - { - m_inv_dt0 = step.inv_dt; - } - - if (m_flags & e_clearForces) - { - ClearForces(); - } - - m_flags &= ~e_locked; - - m_profile.step = stepTimer.GetMilliseconds(); -} - -void b2World::ClearForces() -{ - for (b2Body* body = m_bodyList; body; body = body->GetNext()) - { - body->m_force.SetZero(); - body->m_torque = 0.0f; - } -} - -struct b2WorldQueryWrapper -{ - bool QueryCallback(int32 proxyId) - { - b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); - return callback->ReportFixture(proxy->fixture); - } - - const b2BroadPhase* broadPhase; - b2QueryCallback* callback; -}; - -void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const -{ - b2WorldQueryWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - m_contactManager.m_broadPhase.Query(&wrapper, aabb); -} - -struct b2WorldRayCastWrapper -{ - float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - void* userData = broadPhase->GetUserData(proxyId); - b2FixtureProxy* proxy = (b2FixtureProxy*)userData; - b2Fixture* fixture = proxy->fixture; - int32 index = proxy->childIndex; - b2RayCastOutput output; - bool hit = fixture->RayCast(&output, input, index); - - if (hit) - { - float32 fraction = output.fraction; - b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; - return callback->ReportFixture(fixture, point, output.normal, fraction); - } - - return input.maxFraction; - } - - const b2BroadPhase* broadPhase; - b2RayCastCallback* callback; -}; - -void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const -{ - b2WorldRayCastWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - b2RayCastInput input; - input.maxFraction = 1.0f; - input.p1 = point1; - input.p2 = point2; - m_contactManager.m_broadPhase.RayCast(&wrapper, input); -} - -void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) -{ - switch (fixture->GetType()) - { - case b2Shape::e_circle: - { - b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); - - b2Vec2 center = b2Mul(xf, circle->m_p); - float32 radius = circle->m_radius; - b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); - - m_debugDraw->DrawSolidCircle(center, radius, axis, color); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); - b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); - b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); - m_debugDraw->DrawSegment(v1, v2, color); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); - int32 count = chain->m_count; - const b2Vec2* vertices = chain->m_vertices; - - b2Vec2 v1 = b2Mul(xf, vertices[0]); - for (int32 i = 1; i < count; ++i) - { - b2Vec2 v2 = b2Mul(xf, vertices[i]); - m_debugDraw->DrawSegment(v1, v2, color); - m_debugDraw->DrawCircle(v1, 0.05f, color); - v1 = v2; - } - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); - int32 vertexCount = poly->m_vertexCount; - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; - - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, poly->m_vertices[i]); - } - - m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); - } - break; - - default: - break; - } -} - -void b2World::DrawJoint(b2Joint* joint) -{ - b2Body* bodyA = joint->GetBodyA(); - b2Body* bodyB = joint->GetBodyB(); - const b2Transform& xf1 = bodyA->GetTransform(); - const b2Transform& xf2 = bodyB->GetTransform(); - b2Vec2 x1 = xf1.p; - b2Vec2 x2 = xf2.p; - b2Vec2 p1 = joint->GetAnchorA(); - b2Vec2 p2 = joint->GetAnchorB(); - - b2Color color(0.5f, 0.8f, 0.8f); - - switch (joint->GetType()) - { - case e_distanceJoint: - m_debugDraw->DrawSegment(p1, p2, color); - break; - - case e_pulleyJoint: - { - b2PulleyJoint* pulley = (b2PulleyJoint*)joint; - b2Vec2 s1 = pulley->GetGroundAnchorA(); - b2Vec2 s2 = pulley->GetGroundAnchorB(); - m_debugDraw->DrawSegment(s1, p1, color); - m_debugDraw->DrawSegment(s2, p2, color); - m_debugDraw->DrawSegment(s1, s2, color); - } - break; - - case e_mouseJoint: - // don't draw this - break; - - default: - m_debugDraw->DrawSegment(x1, p1, color); - m_debugDraw->DrawSegment(p1, p2, color); - m_debugDraw->DrawSegment(x2, p2, color); - } -} - -void b2World::DrawDebugData() -{ - if (m_debugDraw == NULL) - { - return; - } - - uint32 flags = m_debugDraw->GetFlags(); - - if (flags & b2Draw::e_shapeBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2Transform& xf = b->GetTransform(); - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - if (b->IsActive() == false) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); - } - else if (b->GetType() == b2_staticBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); - } - else if (b->GetType() == b2_kinematicBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); - } - else if (b->IsAwake() == false) - { - DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); - } - else - { - DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); - } - } - } - } - - if (flags & b2Draw::e_jointBit) - { - for (b2Joint* j = m_jointList; j; j = j->GetNext()) - { - DrawJoint(j); - } - } - - if (flags & b2Draw::e_pairBit) - { - b2Color color(0.3f, 0.9f, 0.9f); - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) - { - //b2Fixture* fixtureA = c->GetFixtureA(); - //b2Fixture* fixtureB = c->GetFixtureB(); - - //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); - //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); - - //m_debugDraw->DrawSegment(cA, cB, color); - } - } - - if (flags & b2Draw::e_aabbBit) - { - b2Color color(0.9f, 0.3f, 0.9f); - b2BroadPhase* bp = &m_contactManager.m_broadPhase; - - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - if (b->IsActive() == false) - { - continue; - } - - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - for (int32 i = 0; i < f->m_proxyCount; ++i) - { - b2FixtureProxy* proxy = f->m_proxies + i; - b2AABB aabb = bp->GetFatAABB(proxy->proxyId); - b2Vec2 vs[4]; - vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); - vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); - vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); - vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); - - m_debugDraw->DrawPolygon(vs, 4, color); - } - } - } - } - - if (flags & b2Draw::e_centerOfMassBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - b2Transform xf = b->GetTransform(); - xf.p = b->GetWorldCenter(); - m_debugDraw->DrawTransform(xf); - } - } -} - -int32 b2World::GetProxyCount() const -{ - return m_contactManager.m_broadPhase.GetProxyCount(); -} - -int32 b2World::GetTreeHeight() const -{ - return m_contactManager.m_broadPhase.GetTreeHeight(); -} - -int32 b2World::GetTreeBalance() const -{ - return m_contactManager.m_broadPhase.GetTreeBalance(); -} - -float32 b2World::GetTreeQuality() const -{ - return m_contactManager.m_broadPhase.GetTreeQuality(); -} - -void b2World::Dump() -{ - if ((m_flags & e_locked) == e_locked) - { - return; - } - - b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); - b2Log("m_world->SetGravity(g);\n"); - - b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); - b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); - int32 i = 0; - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_islandIndex = i; - b->Dump(); - ++i; - } - - i = 0; - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_index = i; - ++i; - } - - // First pass on joints, skip gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type == e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - // Second pass on joints, only gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type != e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - b2Log("b2Free(joints);\n"); - b2Log("b2Free(bodies);\n"); - b2Log("joints = NULL;\n"); - b2Log("bodies = NULL;\n"); -} diff --git a/external/Box2D/Dynamics/b2World.h b/external/Box2D/Dynamics/b2World.h deleted file mode 100644 index f207930511..0000000000 --- a/external/Box2D/Dynamics/b2World.h +++ /dev/null @@ -1,349 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WORLD_H -#define B2_WORLD_H - -#include -#include -#include -#include -#include -#include - -struct b2AABB; -struct b2BodyDef; -struct b2Color; -struct b2JointDef; -class b2Body; -class b2Draw; -class b2Fixture; -class b2Joint; - -/// The world class manages all physics entities, dynamic simulation, -/// and asynchronous queries. The world also contains efficient memory -/// management facilities. -class b2World -{ -public: - /// Construct a world object. - /// @param gravity the world gravity vector. - b2World(const b2Vec2& gravity); - - /// Destruct the world. All physics entities are destroyed and all heap memory is released. - ~b2World(); - - /// Register a destruction listener. The listener is owned by you and must - /// remain in scope. - void SetDestructionListener(b2DestructionListener* listener); - - /// Register a contact filter to provide specific control over collision. - /// Otherwise the default filter is used (b2_defaultFilter). The listener is - /// owned by you and must remain in scope. - void SetContactFilter(b2ContactFilter* filter); - - /// Register a contact event listener. The listener is owned by you and must - /// remain in scope. - void SetContactListener(b2ContactListener* listener); - - /// Register a routine for debug drawing. The debug draw functions are called - /// inside with b2World::DrawDebugData method. The debug draw object is owned - /// by you and must remain in scope. - void SetDebugDraw(b2Draw* debugDraw); - - /// Create a rigid body given a definition. No reference to the definition - /// is retained. - /// @warning This function is locked during callbacks. - b2Body* CreateBody(const b2BodyDef* def); - - /// Destroy a rigid body given a definition. No reference to the definition - /// is retained. This function is locked during callbacks. - /// @warning This automatically deletes all associated shapes and joints. - /// @warning This function is locked during callbacks. - void DestroyBody(b2Body* body); - - /// Create a joint to constrain bodies together. No reference to the definition - /// is retained. This may cause the connected bodies to cease colliding. - /// @warning This function is locked during callbacks. - b2Joint* CreateJoint(const b2JointDef* def); - - /// Destroy a joint. This may cause the connected bodies to begin colliding. - /// @warning This function is locked during callbacks. - void DestroyJoint(b2Joint* joint); - - /// Take a time step. This performs collision detection, integration, - /// and constraint solution. - /// @param timeStep the amount of time to simulate, this should not vary. - /// @param velocityIterations for the velocity constraint solver. - /// @param positionIterations for the position constraint solver. - void Step( float32 timeStep, - int32 velocityIterations, - int32 positionIterations); - - /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically - /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. - /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain - /// a fixed sized time step under a variable frame-rate. - /// When you perform sub-stepping you will disable auto clearing of forces and instead call - /// ClearForces after all sub-steps are complete in one pass of your game loop. - /// @see SetAutoClearForces - void ClearForces(); - - /// Call this to draw shapes and other debug draw data. - void DrawDebugData(); - - /// Query the world for all fixtures that potentially overlap the - /// provided AABB. - /// @param callback a user implemented callback class. - /// @param aabb the query box. - void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; - - /// Ray-cast the world for all fixtures in the path of the ray. Your callback - /// controls whether you get the closest point, any point, or n-points. - /// The ray-cast ignores shapes that contain the starting point. - /// @param callback a user implemented callback class. - /// @param point1 the ray starting point - /// @param point2 the ray ending point - void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; - - /// Get the world body list. With the returned body, use b2Body::GetNext to get - /// the next body in the world list. A NULL body indicates the end of the list. - /// @return the head of the world body list. - b2Body* GetBodyList(); - const b2Body* GetBodyList() const; - - /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get - /// the next joint in the world list. A NULL joint indicates the end of the list. - /// @return the head of the world joint list. - b2Joint* GetJointList(); - const b2Joint* GetJointList() const; - - /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get - /// the next contact in the world list. A NULL contact indicates the end of the list. - /// @return the head of the world contact list. - /// @warning contacts are created and destroyed in the middle of a time step. - /// Use b2ContactListener to avoid missing contacts. - b2Contact* GetContactList(); - const b2Contact* GetContactList() const; - - /// Enable/disable sleep. - void SetAllowSleeping(bool flag); - bool GetAllowSleeping() const { return m_allowSleep; } - - /// Enable/disable warm starting. For testing. - void SetWarmStarting(bool flag) { m_warmStarting = flag; } - bool GetWarmStarting() const { return m_warmStarting; } - - /// Enable/disable continuous physics. For testing. - void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } - bool GetContinuousPhysics() const { return m_continuousPhysics; } - - /// Enable/disable single stepped continuous physics. For testing. - void SetSubStepping(bool flag) { m_subStepping = flag; } - bool GetSubStepping() const { return m_subStepping; } - - /// Get the number of broad-phase proxies. - int32 GetProxyCount() const; - - /// Get the number of bodies. - int32 GetBodyCount() const; - - /// Get the number of joints. - int32 GetJointCount() const; - - /// Get the number of contacts (each may have 0 or more contact points). - int32 GetContactCount() const; - - /// Get the height of the dynamic tree. - int32 GetTreeHeight() const; - - /// Get the balance of the dynamic tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the dynamic tree. The smaller the better. - /// The minimum is 1. - float32 GetTreeQuality() const; - - /// Change the global gravity vector. - void SetGravity(const b2Vec2& gravity); - - /// Get the global gravity vector. - b2Vec2 GetGravity() const; - - /// Is the world locked (in the middle of a time step). - bool IsLocked() const; - - /// Set flag to control automatic clearing of forces after each time step. - void SetAutoClearForces(bool flag); - - /// Get the flag that controls automatic clearing of forces after each time step. - bool GetAutoClearForces() const; - - /// Get the contact manager for testing. - const b2ContactManager& GetContactManager() const; - - /// Get the current profile. - const b2Profile& GetProfile() const; - - /// Dump the world into the log file. - /// @warning this should be called outside of a time step. - void Dump(); - -private: - - // m_flags - enum - { - e_newFixture = 0x0001, - e_locked = 0x0002, - e_clearForces = 0x0004 - }; - - friend class b2Body; - friend class b2Fixture; - friend class b2ContactManager; - friend class b2Controller; - - void Solve(const b2TimeStep& step); - void SolveTOI(const b2TimeStep& step); - - void DrawJoint(b2Joint* joint); - void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); - - b2BlockAllocator m_blockAllocator; - b2StackAllocator m_stackAllocator; - - int32 m_flags; - - b2ContactManager m_contactManager; - - b2Body* m_bodyList; - b2Joint* m_jointList; - - int32 m_bodyCount; - int32 m_jointCount; - - b2Vec2 m_gravity; - bool m_allowSleep; - - b2DestructionListener* m_destructionListener; - b2Draw* m_debugDraw; - - // This is used to compute the time step ratio to - // support a variable time step. - float32 m_inv_dt0; - - // These are for debugging the solver. - bool m_warmStarting; - bool m_continuousPhysics; - bool m_subStepping; - - bool m_stepComplete; - - b2Profile m_profile; -}; - -inline b2Body* b2World::GetBodyList() -{ - return m_bodyList; -} - -inline const b2Body* b2World::GetBodyList() const -{ - return m_bodyList; -} - -inline b2Joint* b2World::GetJointList() -{ - return m_jointList; -} - -inline const b2Joint* b2World::GetJointList() const -{ - return m_jointList; -} - -inline b2Contact* b2World::GetContactList() -{ - return m_contactManager.m_contactList; -} - -inline const b2Contact* b2World::GetContactList() const -{ - return m_contactManager.m_contactList; -} - -inline int32 b2World::GetBodyCount() const -{ - return m_bodyCount; -} - -inline int32 b2World::GetJointCount() const -{ - return m_jointCount; -} - -inline int32 b2World::GetContactCount() const -{ - return m_contactManager.m_contactCount; -} - -inline void b2World::SetGravity(const b2Vec2& gravity) -{ - m_gravity = gravity; -} - -inline b2Vec2 b2World::GetGravity() const -{ - return m_gravity; -} - -inline bool b2World::IsLocked() const -{ - return (m_flags & e_locked) == e_locked; -} - -inline void b2World::SetAutoClearForces(bool flag) -{ - if (flag) - { - m_flags |= e_clearForces; - } - else - { - m_flags &= ~e_clearForces; - } -} - -/// Get the flag that controls automatic clearing of forces after each time step. -inline bool b2World::GetAutoClearForces() const -{ - return (m_flags & e_clearForces) == e_clearForces; -} - -inline const b2ContactManager& b2World::GetContactManager() const -{ - return m_contactManager; -} - -inline const b2Profile& b2World::GetProfile() const -{ - return m_profile; -} - -#endif diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.cpp b/external/Box2D/Dynamics/b2WorldCallbacks.cpp deleted file mode 100644 index 48ad0cc46a..0000000000 --- a/external/Box2D/Dynamics/b2WorldCallbacks.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -// Return true if contact calculations should be performed between these two shapes. -// If you implement your own collision filter you may want to build from this implementation. -bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) -{ - const b2Filter& filterA = fixtureA->GetFilterData(); - const b2Filter& filterB = fixtureB->GetFilterData(); - - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) - { - return filterA.groupIndex > 0; - } - - bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; - return collide; -} diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.h b/external/Box2D/Dynamics/b2WorldCallbacks.h deleted file mode 100644 index 86c04e3e32..0000000000 --- a/external/Box2D/Dynamics/b2WorldCallbacks.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WORLD_CALLBACKS_H -#define B2_WORLD_CALLBACKS_H - -#include - -struct b2Vec2; -struct b2Transform; -class b2Fixture; -class b2Body; -class b2Joint; -class b2Contact; -struct b2ContactResult; -struct b2Manifold; - -/// Joints and fixtures are destroyed when their associated -/// body is destroyed. Implement this listener so that you -/// may nullify references to these joints and shapes. -class b2DestructionListener -{ -public: - virtual ~b2DestructionListener() {} - - /// Called when any joint is about to be destroyed due - /// to the destruction of one of its attached bodies. - virtual void SayGoodbye(b2Joint* joint) = 0; - - /// Called when any fixture is about to be destroyed due - /// to the destruction of its parent body. - virtual void SayGoodbye(b2Fixture* fixture) = 0; -}; - -/// Implement this class to provide collision filtering. In other words, you can implement -/// this class if you want finer control over contact creation. -class b2ContactFilter -{ -public: - virtual ~b2ContactFilter() {} - - /// Return true if contact calculations should be performed between these two shapes. - /// @warning for performance reasons this is only called when the AABBs begin to overlap. - virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); -}; - -/// Contact impulses for reporting. Impulses are used instead of forces because -/// sub-step forces may approach infinity for rigid body collisions. These -/// match up one-to-one with the contact points in b2Manifold. -struct b2ContactImpulse -{ - float32 normalImpulses[b2_maxManifoldPoints]; - float32 tangentImpulses[b2_maxManifoldPoints]; - int32 count; -}; - -/// Implement this class to get contact information. You can use these results for -/// things like sounds and game logic. You can also get contact results by -/// traversing the contact lists after the time step. However, you might miss -/// some contacts because continuous physics leads to sub-stepping. -/// Additionally you may receive multiple callbacks for the same contact in a -/// single time step. -/// You should strive to make your callbacks efficient because there may be -/// many callbacks per time step. -/// @warning You cannot create/destroy Box2D entities inside these callbacks. -class b2ContactListener -{ -public: - virtual ~b2ContactListener() {} - - /// Called when two fixtures begin to touch. - virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// Called when two fixtures cease to touch. - virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// This is called after a contact is updated. This allows you to inspect a - /// contact before it goes to the solver. If you are careful, you can modify the - /// contact manifold (e.g. disable contact). - /// A copy of the old manifold is provided so that you can detect changes. - /// Note: this is called only for awake bodies. - /// Note: this is called even when the number of contact points is zero. - /// Note: this is not called for sensors. - /// Note: if you set the number of contact points to zero, you will not - /// get an EndContact callback. However, you may get a BeginContact callback - /// the next step. - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) - { - B2_NOT_USED(contact); - B2_NOT_USED(oldManifold); - } - - /// This lets you inspect a contact after the solver is finished. This is useful - /// for inspecting impulses. - /// Note: the contact manifold does not include time of impact impulses, which can be - /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - /// in a separate data structure. - /// Note: this is only called for contacts that are touching, solid, and awake. - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } -}; - -/// Callback class for AABB queries. -/// See b2World::Query -class b2QueryCallback -{ -public: - virtual ~b2QueryCallback() {} - - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - virtual bool ReportFixture(b2Fixture* fixture) = 0; -}; - -/// Callback class for ray casts. -/// See b2World::RayCast -class b2RayCastCallback -{ -public: - virtual ~b2RayCastCallback() {} - - /// Called for each fixture found in the query. You control how the ray cast - /// proceeds by returning a float: - /// return -1: ignore this fixture and continue - /// return 0: terminate the ray cast - /// return fraction: clip the ray to this point - /// return 1: don't clip the ray and continue - /// @param fixture the fixture hit by the ray - /// @param point the point of initial intersection - /// @param normal the normal vector at the point of intersection - /// @return -1 to filter, 0 to terminate, fraction to clip the ray for - /// closest hit, 1 to continue - virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) = 0; -}; - -#endif diff --git a/external/Box2D/Rope/b2Rope.cpp b/external/Box2D/Rope/b2Rope.cpp deleted file mode 100644 index 9bf671aec9..0000000000 --- a/external/Box2D/Rope/b2Rope.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2Rope::b2Rope() -{ - m_count = 0; - m_ps = NULL; - m_p0s = NULL; - m_vs = NULL; - m_ims = NULL; - m_Ls = NULL; - m_as = NULL; - m_gravity.SetZero(); - m_k2 = 1.0f; - m_k3 = 0.1f; -} - -b2Rope::~b2Rope() -{ - b2Free(m_ps); - b2Free(m_p0s); - b2Free(m_vs); - b2Free(m_ims); - b2Free(m_Ls); - b2Free(m_as); -} - -void b2Rope::Initialize(const b2RopeDef* def) -{ - b2Assert(def->count >= 3); - m_count = def->count; - m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); - - for (int32 i = 0; i < m_count; ++i) - { - m_ps[i] = def->vertices[i]; - m_p0s[i] = def->vertices[i]; - m_vs[i].SetZero(); - - float32 m = def->masses[i]; - if (m > 0.0f) - { - m_ims[i] = 1.0f / m; - } - else - { - m_ims[i] = 0.0f; - } - } - - int32 count2 = m_count - 1; - int32 count3 = m_count - 2; - m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); - m_as = (float32*)b2Alloc(count3 * sizeof(float32)); - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i+1]; - m_Ls[i] = b2Distance(p1, p2); - } - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - m_as[i] = b2Atan2(a, b); - } - - m_gravity = def->gravity; - m_damping = def->damping; - m_k2 = def->k2; - m_k3 = def->k3; -} - -void b2Rope::Step(float32 h, int32 iterations) -{ - if (h == 0.0) - { - return; - } - - float32 d = expf(- h * m_damping); - - for (int32 i = 0; i < m_count; ++i) - { - m_p0s[i] = m_ps[i]; - if (m_ims[i] > 0.0f) - { - m_vs[i] += h * m_gravity; - } - m_vs[i] *= d; - m_ps[i] += h * m_vs[i]; - - } - - for (int32 i = 0; i < iterations; ++i) - { - SolveC2(); - SolveC3(); - SolveC2(); - } - - float32 inv_h = 1.0f / h; - for (int32 i = 0; i < m_count; ++i) - { - m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); - } -} - -void b2Rope::SolveC2() -{ - int32 count2 = m_count - 1; - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - - b2Vec2 d = p2 - p1; - float32 L = d.Normalize(); - - float32 im1 = m_ims[i]; - float32 im2 = m_ims[i + 1]; - - if (im1 + im2 == 0.0f) - { - continue; - } - - float32 s1 = im1 / (im1 + im2); - float32 s2 = im2 / (im1 + im2); - - p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; - p2 += m_k2 * s2 * (m_Ls[i] - L) * d; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - } -} - -void b2Rope::SetAngle(float32 angle) -{ - int32 count3 = m_count - 2; - for (int32 i = 0; i < count3; ++i) - { - m_as[i] = angle; - } -} - -void b2Rope::SolveC3() -{ - int32 count3 = m_count - 2; - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - float32 m1 = m_ims[i]; - float32 m2 = m_ims[i + 1]; - float32 m3 = m_ims[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 L1sqr = d1.LengthSquared(); - float32 L2sqr = d2.LengthSquared(); - - if (L1sqr * L2sqr == 0.0f) - { - continue; - } - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - float32 angle = b2Atan2(a, b); - - b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); - b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); - - b2Vec2 J1 = -Jd1; - b2Vec2 J2 = Jd1 - Jd2; - b2Vec2 J3 = Jd2; - - float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); - if (mass == 0.0f) - { - continue; - } - - mass = 1.0f / mass; - - float32 C = angle - m_as[i]; - - while (C > b2_pi) - { - angle -= 2 * b2_pi; - C = angle - m_as[i]; - } - - while (C < -b2_pi) - { - angle += 2.0f * b2_pi; - C = angle - m_as[i]; - } - - float32 impulse = - m_k3 * mass * C; - - p1 += (m1 * impulse) * J1; - p2 += (m2 * impulse) * J2; - p3 += (m3 * impulse) * J3; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - m_ps[i + 2] = p3; - } -} - -void b2Rope::Draw(b2Draw* draw) const -{ - b2Color c(0.4f, 0.5f, 0.7f); - - for (int32 i = 0; i < m_count - 1; ++i) - { - draw->DrawSegment(m_ps[i], m_ps[i+1], c); - } -} diff --git a/external/Box2D/Rope/b2Rope.h b/external/Box2D/Rope/b2Rope.h deleted file mode 100644 index b981dfd6c5..0000000000 --- a/external/Box2D/Rope/b2Rope.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ROPE_H -#define B2_ROPE_H - -#include - -class b2Draw; - -/// -struct b2RopeDef -{ - b2RopeDef() - { - vertices = NULL; - count = 0; - masses = NULL; - gravity.SetZero(); - damping = 0.1f; - k2 = 0.9f; - k3 = 0.1f; - } - - /// - b2Vec2* vertices; - - /// - int32 count; - - /// - float32* masses; - - /// - b2Vec2 gravity; - - /// - float32 damping; - - /// Stretching stiffness - float32 k2; - - /// Bending stiffness. Values above 0.5 can make the simulation blow up. - float32 k3; -}; - -/// -class b2Rope -{ -public: - b2Rope(); - ~b2Rope(); - - /// - void Initialize(const b2RopeDef* def); - - /// - void Step(float32 timeStep, int32 iterations); - - /// - int32 GetVertexCount() const - { - return m_count; - } - - /// - const b2Vec2* GetVertices() const - { - return m_ps; - } - - /// - void Draw(b2Draw* draw) const; - - /// - void SetAngle(float32 angle); - -private: - - void SolveC2(); - void SolveC3(); - - int32 m_count; - b2Vec2* m_ps; - b2Vec2* m_p0s; - b2Vec2* m_vs; - - float32* m_ims; - - float32* m_Ls; - float32* m_as; - - b2Vec2 m_gravity; - float32 m_damping; - - float32 m_k2; - float32 m_k3; -}; - -#endif diff --git a/external/Box2D/proj.linux/.cproject b/external/Box2D/proj.linux/.cproject deleted file mode 100644 index 5aa092cac3..0000000000 --- a/external/Box2D/proj.linux/.cproject +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/Box2D/proj.linux/.project b/external/Box2D/proj.linux/.project deleted file mode 100644 index 164d50f52a..0000000000 --- a/external/Box2D/proj.linux/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - libBox2D - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libBox2D/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Box2D.h - 1 - PARENT-1-PROJECT_LOC/Box2D.h - - - Collision - 2 - PARENT-1-PROJECT_LOC/Collision - - - Common - 2 - PARENT-1-PROJECT_LOC/Common - - - Dynamics - 2 - PARENT-1-PROJECT_LOC/Dynamics - - - Rope - 2 - PARENT-1-PROJECT_LOC/Rope - - - diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile deleted file mode 100644 index e430bc9883..0000000000 --- a/external/Box2D/proj.linux/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -TARGET = libbox2d.a - -SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ -../Collision/Shapes/b2CircleShape.cpp \ -../Collision/Shapes/b2EdgeShape.cpp \ -../Collision/Shapes/b2PolygonShape.cpp \ -../Collision/b2BroadPhase.cpp \ -../Collision/b2CollideCircle.cpp \ -../Collision/b2CollideEdge.cpp \ -../Collision/b2CollidePolygon.cpp \ -../Collision/b2Collision.cpp \ -../Collision/b2Distance.cpp \ -../Collision/b2DynamicTree.cpp \ -../Collision/b2TimeOfImpact.cpp \ -../Common/b2BlockAllocator.cpp \ -../Common/b2Draw.cpp \ -../Common/b2Math.cpp \ -../Common/b2Settings.cpp \ -../Common/b2StackAllocator.cpp \ -../Common/b2Timer.cpp \ -../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -../Dynamics/Contacts/b2CircleContact.cpp \ -../Dynamics/Contacts/b2Contact.cpp \ -../Dynamics/Contacts/b2ContactSolver.cpp \ -../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -../Dynamics/Contacts/b2PolygonContact.cpp \ -../Dynamics/Joints/b2DistanceJoint.cpp \ -../Dynamics/Joints/b2FrictionJoint.cpp \ -../Dynamics/Joints/b2GearJoint.cpp \ -../Dynamics/Joints/b2Joint.cpp \ -../Dynamics/Joints/b2MouseJoint.cpp \ -../Dynamics/Joints/b2PrismaticJoint.cpp \ -../Dynamics/Joints/b2PulleyJoint.cpp \ -../Dynamics/Joints/b2RevoluteJoint.cpp \ -../Dynamics/Joints/b2RopeJoint.cpp \ -../Dynamics/Joints/b2WeldJoint.cpp \ -../Dynamics/Joints/b2WheelJoint.cpp \ -../Dynamics/b2Body.cpp \ -../Dynamics/b2ContactManager.cpp \ -../Dynamics/b2Fixture.cpp \ -../Dynamics/b2Island.cpp \ -../Dynamics/b2World.cpp \ -../Dynamics/b2WorldCallbacks.cpp \ -../Rope/b2Rope.cpp - -include ../../../cocos2dx/proj.linux/cocos2dx.mk - -INCLUDES = -I../.. - -# Cocos2d is not responsible for warnings in external projects -CXXFLAGS += -w - -ifeq ($(DEBUG), 1) -DEFINES = -D_DEBUG -else -DEFINES = -endif - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/box2d.prf b/external/Box2D/proj.linux/box2d.prf deleted file mode 100644 index 434ad88406..0000000000 --- a/external/Box2D/proj.linux/box2d.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile box2d on demand using Makefile. - build_box2d.name = Build box2d static library - build_box2d.input = $$PWD/Makefile - build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.CONFIG = no_link target_predeps - build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_box2d - QMAKE_EXTRA_TARGETS += build_box2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a - LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic -} diff --git a/external/Box2D/proj.win32/Box2D.vcxproj b/external/Box2D/proj.win32/Box2D.vcxproj deleted file mode 100644 index cd4bd2086c..0000000000 --- a/external/Box2D/proj.win32/Box2D.vcxproj +++ /dev/null @@ -1,194 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - libBox2D - {929480E7-23C0-4DF6-8456-096D71547116} - Box2D.win32 - Win32Proj - - - - StaticLibrary - Unicode - v100 - v110 - v110_xp - - - StaticLibrary - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - true - - - $(OutDir)$(ProjectName).lib - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDLL - - - Level3 - ProgramDatabase - true - - - $(OutDir)$(ProjectName).lib - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/external/Box2D/proj.win32/Box2D.vcxproj.filters b/external/Box2D/proj.win32/Box2D.vcxproj.filters deleted file mode 100644 index e810cbb0cf..0000000000 --- a/external/Box2D/proj.win32/Box2D.vcxproj.filters +++ /dev/null @@ -1,301 +0,0 @@ - - - - - {bdf099c5-cc32-468b-b53f-ec010d7f823f} - - - {92792f88-4e5c-46ee-8d87-002f3b2297ae} - - - {f41a6fa6-5ac1-4514-9ac0-6f3a38f35b4d} - - - {0b56913a-34b7-410a-b386-869d6f7a20be} - - - {f0e7b230-79cc-49b8-9ed7-9dbfa062f2a4} - - - {932f2008-afbe-42f5-993d-a1df0ec67756} - - - {f8937e09-93a4-49fa-8f3e-dfc36da764df} - - - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Rope - - - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Rope - - - - \ No newline at end of file diff --git a/external/Box2D/proj.win32/Box2D.vcxproj.user b/external/Box2D/proj.win32/Box2D.vcxproj.user deleted file mode 100644 index ace9a86acb..0000000000 --- a/external/Box2D/proj.win32/Box2D.vcxproj.user +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file From 19ee87e29a16bc086e2b2eb3e5582d87b27fd970 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 14:03:04 +0800 Subject: [PATCH 120/557] issue #2905: step2 Box2D -> box2d --- cocos/physics/box2d/CCPhysicsBodyInfo.cpp | 39 + cocos/physics/box2d/CCPhysicsBodyInfo.h | 43 + cocos/physics/box2d/CCPhysicsContactInfo.cpp | 39 + cocos/physics/box2d/CCPhysicsContactInfo.h | 43 + cocos/physics/box2d/CCPhysicsHelper.h | 43 + cocos/physics/box2d/CCPhysicsJointInfo.cpp | 39 + cocos/physics/box2d/CCPhysicsJointInfo.h | 43 + cocos/physics/box2d/CCPhysicsShapeInfo.cpp | 39 + cocos/physics/box2d/CCPhysicsShapeInfo.h | 43 + cocos/physics/box2d/CCPhysicsWorldInfo.cpp | 39 + cocos/physics/box2d/CCPhysicsWorldInfo.h | 43 + external/box2d/Android.mk | 60 + external/box2d/Box2D.h | 67 + .../box2d/Collision/Shapes/b2ChainShape.cpp | 171 +++ .../box2d/Collision/Shapes/b2ChainShape.h | 102 ++ .../box2d/Collision/Shapes/b2CircleShape.cpp | 100 ++ .../box2d/Collision/Shapes/b2CircleShape.h | 91 ++ .../box2d/Collision/Shapes/b2EdgeShape.cpp | 139 ++ external/box2d/Collision/Shapes/b2EdgeShape.h | 74 + .../box2d/Collision/Shapes/b2PolygonShape.cpp | 361 +++++ .../box2d/Collision/Shapes/b2PolygonShape.h | 95 ++ external/box2d/Collision/Shapes/b2Shape.h | 101 ++ external/box2d/Collision/b2BroadPhase.cpp | 122 ++ external/box2d/Collision/b2BroadPhase.h | 248 ++++ external/box2d/Collision/b2CollideCircle.cpp | 154 ++ external/box2d/Collision/b2CollideEdge.cpp | 698 +++++++++ external/box2d/Collision/b2CollidePolygon.cpp | 317 ++++ external/box2d/Collision/b2Collision.cpp | 249 ++++ external/box2d/Collision/b2Collision.h | 276 ++++ external/box2d/Collision/b2Distance.cpp | 603 ++++++++ external/box2d/Collision/b2Distance.h | 141 ++ external/box2d/Collision/b2DynamicTree.cpp | 775 ++++++++++ external/box2d/Collision/b2DynamicTree.h | 284 ++++ external/box2d/Collision/b2TimeOfImpact.cpp | 488 ++++++ external/box2d/Collision/b2TimeOfImpact.h | 58 + external/box2d/Common/b2BlockAllocator.cpp | 218 +++ external/box2d/Common/b2BlockAllocator.h | 62 + external/box2d/Common/b2Draw.cpp | 44 + external/box2d/Common/b2Draw.h | 81 + external/box2d/Common/b2GrowableStack.h | 85 ++ external/box2d/Common/b2Math.cpp | 94 ++ external/box2d/Common/b2Math.h | 738 +++++++++ external/box2d/Common/b2Settings.cpp | 61 + external/box2d/Common/b2Settings.h | 150 ++ external/box2d/Common/b2StackAllocator.cpp | 83 ++ external/box2d/Common/b2StackAllocator.h | 60 + external/box2d/Common/b2Timer.cpp | 100 ++ external/box2d/Common/b2Timer.h | 45 + .../Contacts/b2ChainAndCircleContact.cpp | 54 + .../Contacts/b2ChainAndCircleContact.h | 39 + .../Contacts/b2ChainAndPolygonContact.cpp | 54 + .../Contacts/b2ChainAndPolygonContact.h | 39 + .../Dynamics/Contacts/b2CircleContact.cpp | 53 + .../box2d/Dynamics/Contacts/b2CircleContact.h | 39 + .../box2d/Dynamics/Contacts/b2Contact.cpp | 240 +++ external/box2d/Dynamics/Contacts/b2Contact.h | 331 +++++ .../Dynamics/Contacts/b2ContactSolver.cpp | 832 +++++++++++ .../box2d/Dynamics/Contacts/b2ContactSolver.h | 94 ++ .../Contacts/b2EdgeAndCircleContact.cpp | 50 + .../Contacts/b2EdgeAndCircleContact.h | 39 + .../Contacts/b2EdgeAndPolygonContact.cpp | 50 + .../Contacts/b2EdgeAndPolygonContact.h | 39 + .../Contacts/b2PolygonAndCircleContact.cpp | 50 + .../Contacts/b2PolygonAndCircleContact.h | 38 + .../Dynamics/Contacts/b2PolygonContact.cpp | 53 + .../Dynamics/Contacts/b2PolygonContact.h | 39 + .../box2d/Dynamics/Joints/b2DistanceJoint.cpp | 260 ++++ .../box2d/Dynamics/Joints/b2DistanceJoint.h | 169 +++ .../box2d/Dynamics/Joints/b2FrictionJoint.cpp | 251 ++++ .../box2d/Dynamics/Joints/b2FrictionJoint.h | 119 ++ .../box2d/Dynamics/Joints/b2GearJoint.cpp | 423 ++++++ external/box2d/Dynamics/Joints/b2GearJoint.h | 125 ++ external/box2d/Dynamics/Joints/b2Joint.cpp | 199 +++ external/box2d/Dynamics/Joints/b2Joint.h | 222 +++ .../box2d/Dynamics/Joints/b2MouseJoint.cpp | 217 +++ external/box2d/Dynamics/Joints/b2MouseJoint.h | 126 ++ .../Dynamics/Joints/b2PrismaticJoint.cpp | 637 ++++++++ .../box2d/Dynamics/Joints/b2PrismaticJoint.h | 196 +++ .../box2d/Dynamics/Joints/b2PulleyJoint.cpp | 332 +++++ .../box2d/Dynamics/Joints/b2PulleyJoint.h | 143 ++ .../box2d/Dynamics/Joints/b2RevoluteJoint.cpp | 504 +++++++ .../box2d/Dynamics/Joints/b2RevoluteJoint.h | 204 +++ .../box2d/Dynamics/Joints/b2RopeJoint.cpp | 241 +++ external/box2d/Dynamics/Joints/b2RopeJoint.h | 114 ++ .../box2d/Dynamics/Joints/b2WeldJoint.cpp | 330 +++++ external/box2d/Dynamics/Joints/b2WeldJoint.h | 126 ++ .../box2d/Dynamics/Joints/b2WheelJoint.cpp | 419 ++++++ external/box2d/Dynamics/Joints/b2WheelJoint.h | 213 +++ external/box2d/Dynamics/b2Body.cpp | 514 +++++++ external/box2d/Dynamics/b2Body.h | 846 +++++++++++ external/box2d/Dynamics/b2ContactManager.cpp | 293 ++++ external/box2d/Dynamics/b2ContactManager.h | 52 + external/box2d/Dynamics/b2Fixture.cpp | 303 ++++ external/box2d/Dynamics/b2Fixture.h | 345 +++++ external/box2d/Dynamics/b2Island.cpp | 539 +++++++ external/box2d/Dynamics/b2Island.h | 93 ++ external/box2d/Dynamics/b2TimeStep.h | 70 + external/box2d/Dynamics/b2World.cpp | 1316 +++++++++++++++++ external/box2d/Dynamics/b2World.h | 349 +++++ external/box2d/Dynamics/b2WorldCallbacks.cpp | 36 + external/box2d/Dynamics/b2WorldCallbacks.h | 155 ++ external/box2d/Rope/b2Rope.cpp | 259 ++++ external/box2d/Rope/b2Rope.h | 115 ++ external/box2d/proj.linux/.cproject | 267 ++++ external/box2d/proj.linux/.project | 110 ++ external/box2d/proj.linux/Makefile | 72 + external/box2d/proj.linux/box2d.prf | 19 + external/box2d/proj.win32/Box2D.vcxproj | 194 +++ .../box2d/proj.win32/Box2D.vcxproj.filters | 301 ++++ external/box2d/proj.win32/Box2D.vcxproj.user | 3 + 110 files changed, 22002 insertions(+) create mode 100644 cocos/physics/box2d/CCPhysicsBodyInfo.cpp create mode 100644 cocos/physics/box2d/CCPhysicsBodyInfo.h create mode 100644 cocos/physics/box2d/CCPhysicsContactInfo.cpp create mode 100644 cocos/physics/box2d/CCPhysicsContactInfo.h create mode 100644 cocos/physics/box2d/CCPhysicsHelper.h create mode 100644 cocos/physics/box2d/CCPhysicsJointInfo.cpp create mode 100644 cocos/physics/box2d/CCPhysicsJointInfo.h create mode 100644 cocos/physics/box2d/CCPhysicsShapeInfo.cpp create mode 100644 cocos/physics/box2d/CCPhysicsShapeInfo.h create mode 100644 cocos/physics/box2d/CCPhysicsWorldInfo.cpp create mode 100644 cocos/physics/box2d/CCPhysicsWorldInfo.h create mode 100644 external/box2d/Android.mk create mode 100644 external/box2d/Box2D.h create mode 100644 external/box2d/Collision/Shapes/b2ChainShape.cpp create mode 100644 external/box2d/Collision/Shapes/b2ChainShape.h create mode 100644 external/box2d/Collision/Shapes/b2CircleShape.cpp create mode 100644 external/box2d/Collision/Shapes/b2CircleShape.h create mode 100644 external/box2d/Collision/Shapes/b2EdgeShape.cpp create mode 100644 external/box2d/Collision/Shapes/b2EdgeShape.h create mode 100644 external/box2d/Collision/Shapes/b2PolygonShape.cpp create mode 100644 external/box2d/Collision/Shapes/b2PolygonShape.h create mode 100644 external/box2d/Collision/Shapes/b2Shape.h create mode 100644 external/box2d/Collision/b2BroadPhase.cpp create mode 100644 external/box2d/Collision/b2BroadPhase.h create mode 100644 external/box2d/Collision/b2CollideCircle.cpp create mode 100644 external/box2d/Collision/b2CollideEdge.cpp create mode 100644 external/box2d/Collision/b2CollidePolygon.cpp create mode 100644 external/box2d/Collision/b2Collision.cpp create mode 100644 external/box2d/Collision/b2Collision.h create mode 100644 external/box2d/Collision/b2Distance.cpp create mode 100644 external/box2d/Collision/b2Distance.h create mode 100644 external/box2d/Collision/b2DynamicTree.cpp create mode 100644 external/box2d/Collision/b2DynamicTree.h create mode 100644 external/box2d/Collision/b2TimeOfImpact.cpp create mode 100644 external/box2d/Collision/b2TimeOfImpact.h create mode 100644 external/box2d/Common/b2BlockAllocator.cpp create mode 100644 external/box2d/Common/b2BlockAllocator.h create mode 100644 external/box2d/Common/b2Draw.cpp create mode 100644 external/box2d/Common/b2Draw.h create mode 100644 external/box2d/Common/b2GrowableStack.h create mode 100644 external/box2d/Common/b2Math.cpp create mode 100644 external/box2d/Common/b2Math.h create mode 100644 external/box2d/Common/b2Settings.cpp create mode 100644 external/box2d/Common/b2Settings.h create mode 100644 external/box2d/Common/b2StackAllocator.cpp create mode 100644 external/box2d/Common/b2StackAllocator.h create mode 100644 external/box2d/Common/b2Timer.cpp create mode 100644 external/box2d/Common/b2Timer.h create mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2CircleContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2CircleContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2Contact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2Contact.h create mode 100644 external/box2d/Dynamics/Contacts/b2ContactSolver.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2ContactSolver.h create mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h create mode 100644 external/box2d/Dynamics/Contacts/b2PolygonContact.cpp create mode 100644 external/box2d/Dynamics/Contacts/b2PolygonContact.h create mode 100644 external/box2d/Dynamics/Joints/b2DistanceJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2DistanceJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2FrictionJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2FrictionJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2GearJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2GearJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2Joint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2Joint.h create mode 100644 external/box2d/Dynamics/Joints/b2MouseJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2MouseJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2PrismaticJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2PulleyJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2PulleyJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2RevoluteJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2RopeJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2RopeJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2WeldJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2WeldJoint.h create mode 100644 external/box2d/Dynamics/Joints/b2WheelJoint.cpp create mode 100644 external/box2d/Dynamics/Joints/b2WheelJoint.h create mode 100644 external/box2d/Dynamics/b2Body.cpp create mode 100644 external/box2d/Dynamics/b2Body.h create mode 100644 external/box2d/Dynamics/b2ContactManager.cpp create mode 100644 external/box2d/Dynamics/b2ContactManager.h create mode 100644 external/box2d/Dynamics/b2Fixture.cpp create mode 100644 external/box2d/Dynamics/b2Fixture.h create mode 100644 external/box2d/Dynamics/b2Island.cpp create mode 100644 external/box2d/Dynamics/b2Island.h create mode 100644 external/box2d/Dynamics/b2TimeStep.h create mode 100644 external/box2d/Dynamics/b2World.cpp create mode 100644 external/box2d/Dynamics/b2World.h create mode 100644 external/box2d/Dynamics/b2WorldCallbacks.cpp create mode 100644 external/box2d/Dynamics/b2WorldCallbacks.h create mode 100644 external/box2d/Rope/b2Rope.cpp create mode 100644 external/box2d/Rope/b2Rope.h create mode 100644 external/box2d/proj.linux/.cproject create mode 100644 external/box2d/proj.linux/.project create mode 100644 external/box2d/proj.linux/Makefile create mode 100644 external/box2d/proj.linux/box2d.prf create mode 100644 external/box2d/proj.win32/Box2D.vcxproj create mode 100644 external/box2d/proj.win32/Box2D.vcxproj.filters create mode 100644 external/box2d/proj.win32/Box2D.vcxproj.user diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp b/cocos/physics/box2d/CCPhysicsBodyInfo.cpp new file mode 100644 index 0000000000..bfa20b616a --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsBodyInfo.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCPhysicsBodyInfo.h" + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +NS_CC_BEGIN + +PhysicsBodyInfo::PhysicsBodyInfo() +{ +} + +PhysicsBodyInfo::~PhysicsBodyInfo() +{ +} + +NS_CC_END +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.h b/cocos/physics/box2d/CCPhysicsBodyInfo.h new file mode 100644 index 0000000000..730837ed9d --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsBodyInfo.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_BODY_INFO_H__ +#define __CCPHYSICS_BODY_INFO_H__ +#include "platform/CCPlatformMacros.h" +NS_CC_BEGIN + +class PhysicsBodyInfo +{ +public: + PhysicsBodyInfo(); + ~PhysicsBodyInfo(); +}; + +NS_CC_END +#endif // __CCPHYSICS_BODY_INFO_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.cpp b/cocos/physics/box2d/CCPhysicsContactInfo.cpp new file mode 100644 index 0000000000..41eaa4f831 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsContactInfo.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCPhysicsContactInfo.h" + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +NS_CC_BEGIN + +PhysicsContactInfo::PhysicsContactInfo() +{ +} + +PhysicsContactInfo::~PhysicsContactInfo() +{ +} + +NS_CC_END +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.h b/cocos/physics/box2d/CCPhysicsContactInfo.h new file mode 100644 index 0000000000..b592caa0af --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsContactInfo.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_CONTACT_INFO_H__ +#define __CCPHYSICS_CONTACT_INFO_H__ +#include "platform/CCPlatformMacros.h" +NS_CC_BEGIN + +class PhysicsContactInfo +{ +public: + PhysicsContactInfo(); + ~PhysicsContactInfo(); +}; + +NS_CC_END +#endif // __CCPHYSICS_CONTACT_INFO_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsHelper.h b/cocos/physics/box2d/CCPhysicsHelper.h new file mode 100644 index 0000000000..86ef7d74ee --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsHelper.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_HELPER_H__ +#define __CCPHYSICS_HELPER_H__ + +#include "platform/CCPlatformMacros.h" +#include "cocoa/CCGeometry.h" + +NS_CC_BEGIN + +class PhysicsHelper +{ +}; + +NS_CC_END +#endif // __CCPHYSICS_HELPER_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.cpp b/cocos/physics/box2d/CCPhysicsJointInfo.cpp new file mode 100644 index 0000000000..753ba41534 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsJointInfo.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCPhysicsJointInfo.h" + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +NS_CC_BEGIN + +PhysicsJointInfo::PhysicsJointInfo() +{ +} + +PhysicsJointInfo::~PhysicsJointInfo() +{ +} + +NS_CC_END +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.h b/cocos/physics/box2d/CCPhysicsJointInfo.h new file mode 100644 index 0000000000..abcf089387 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsJointInfo.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_JOINT_INFO_H__ +#define __CCPHYSICS_JOINT_INFO_H__ +#include "platform/CCPlatformMacros.h" +NS_CC_BEGIN + +class PhysicsJointInfo +{ +public: + PhysicsJointInfo(); + ~PhysicsJointInfo(); +}; + +NS_CC_END +#endif // __CCPHYSICS_JOINT_INFO_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo.cpp new file mode 100644 index 0000000000..a89ba7dae7 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsShapeInfo.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCPhysicsShapeInfo.h" + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +NS_CC_BEGIN + +PhysicsShapeInfo::PhysicsShapeInfo() +{ +} + +PhysicsShapeInfo::~PhysicsShapeInfo() +{ +} + +NS_CC_END +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.h b/cocos/physics/box2d/CCPhysicsShapeInfo.h new file mode 100644 index 0000000000..9091001887 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsShapeInfo.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_SHAPE_INFO_H__ +#define __CCPHYSICS_SHAPE_INFO_H__ +#include "platform/CCPlatformMacros.h" +NS_CC_BEGIN + +class PhysicsShapeInfo +{ +public: + PhysicsShapeInfo(); + ~PhysicsShapeInfo(); +}; + +NS_CC_END +#endif // __CCPHYSICS_SHAPE_INFO_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo.cpp new file mode 100644 index 0000000000..0de6c00d82 --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsWorldInfo.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCPhysicsWorldInfo.h" + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +NS_CC_BEGIN + +PhysicsWorldInfo::PhysicsWorldInfo() +{ +} + +PhysicsWorldInfo::~PhysicsWorldInfo() +{ +} + +NS_CC_END +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.h b/cocos/physics/box2d/CCPhysicsWorldInfo.h new file mode 100644 index 0000000000..bcc09124db --- /dev/null +++ b/cocos/physics/box2d/CCPhysicsWorldInfo.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) + +#ifndef __CCPHYSICS_WORLD_INFO_H__ +#define __CCPHYSICS_WORLD_INFO_H__ +#include "platform/CCPlatformMacros.h" +NS_CC_BEGIN + +class PhysicsWorldInfo +{ +public: + PhysicsWorldInfo(); + ~PhysicsWorldInfo(); +}; + +NS_CC_END +#endif // __CCPHYSICS_WORLD_INFO_H__ + +#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/external/box2d/Android.mk b/external/box2d/Android.mk new file mode 100644 index 0000000000..c366750c01 --- /dev/null +++ b/external/box2d/Android.mk @@ -0,0 +1,60 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := box2d_static + +LOCAL_MODULE_FILENAME := libbox2d + +LOCAL_SRC_FILES := \ +Collision/b2BroadPhase.cpp \ +Collision/b2CollideCircle.cpp \ +Collision/b2CollideEdge.cpp \ +Collision/b2CollidePolygon.cpp \ +Collision/b2Collision.cpp \ +Collision/b2Distance.cpp \ +Collision/b2DynamicTree.cpp \ +Collision/b2TimeOfImpact.cpp \ +Collision/Shapes/b2ChainShape.cpp \ +Collision/Shapes/b2CircleShape.cpp \ +Collision/Shapes/b2EdgeShape.cpp \ +Collision/Shapes/b2PolygonShape.cpp \ +Common/b2BlockAllocator.cpp \ +Common/b2Draw.cpp \ +Common/b2Math.cpp \ +Common/b2Settings.cpp \ +Common/b2StackAllocator.cpp \ +Common/b2Timer.cpp \ +Dynamics/b2Body.cpp \ +Dynamics/b2ContactManager.cpp \ +Dynamics/b2Fixture.cpp \ +Dynamics/b2Island.cpp \ +Dynamics/b2World.cpp \ +Dynamics/b2WorldCallbacks.cpp \ +Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +Dynamics/Contacts/b2CircleContact.cpp \ +Dynamics/Contacts/b2Contact.cpp \ +Dynamics/Contacts/b2ContactSolver.cpp \ +Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +Dynamics/Contacts/b2PolygonContact.cpp \ +Dynamics/Joints/b2DistanceJoint.cpp \ +Dynamics/Joints/b2FrictionJoint.cpp \ +Dynamics/Joints/b2GearJoint.cpp \ +Dynamics/Joints/b2Joint.cpp \ +Dynamics/Joints/b2MouseJoint.cpp \ +Dynamics/Joints/b2PrismaticJoint.cpp \ +Dynamics/Joints/b2PulleyJoint.cpp \ +Dynamics/Joints/b2RevoluteJoint.cpp \ +Dynamics/Joints/b2RopeJoint.cpp \ +Dynamics/Joints/b2WeldJoint.cpp \ +Dynamics/Joints/b2WheelJoint.cpp \ +Rope/b2Rope.cpp + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. + +include $(BUILD_STATIC_LIBRARY) diff --git a/external/box2d/Box2D.h b/external/box2d/Box2D.h new file mode 100644 index 0000000000..f674d82269 --- /dev/null +++ b/external/box2d/Box2D.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef BOX2D_H +#define BOX2D_H + +/** +\mainpage Box2D API Documentation + +\section intro_sec Getting Started + +For documentation please see http://box2d.org/documentation.html + +For discussion please visit http://box2d.org/forum +*/ + +// These include files constitute the main Box2D API + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/external/box2d/Collision/Shapes/b2ChainShape.cpp b/external/box2d/Collision/Shapes/b2ChainShape.cpp new file mode 100644 index 0000000000..79b4304b5b --- /dev/null +++ b/external/box2d/Collision/Shapes/b2ChainShape.cpp @@ -0,0 +1,171 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +using namespace std; + +b2ChainShape::~b2ChainShape() +{ + b2Free(m_vertices); + m_vertices = NULL; + m_count = 0; +} + +void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 3); + m_count = count + 1; + m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); + m_vertices[count] = m_vertices[0]; + m_prevVertex = m_vertices[m_count - 2]; + m_nextVertex = m_vertices[1]; + m_hasPrevVertex = true; + m_hasNextVertex = true; +} + +void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 2); + m_count = count; + m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); + m_hasPrevVertex = false; + m_hasNextVertex = false; +} + +void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) +{ + m_prevVertex = prevVertex; + m_hasPrevVertex = true; +} + +void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) +{ + m_nextVertex = nextVertex; + m_hasNextVertex = true; +} + +b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2ChainShape)); + b2ChainShape* clone = new (mem) b2ChainShape; + clone->CreateChain(m_vertices, m_count); + clone->m_prevVertex = m_prevVertex; + clone->m_nextVertex = m_nextVertex; + clone->m_hasPrevVertex = m_hasPrevVertex; + clone->m_hasNextVertex = m_hasNextVertex; + return clone; +} + +int32 b2ChainShape::GetChildCount() const +{ + // edge count = vertex count - 1 + return m_count - 1; +} + +void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const +{ + b2Assert(0 <= index && index < m_count - 1); + edge->m_type = b2Shape::e_edge; + edge->m_radius = m_radius; + + edge->m_vertex1 = m_vertices[index + 0]; + edge->m_vertex2 = m_vertices[index + 1]; + + if (index > 0) + { + edge->m_vertex0 = m_vertices[index - 1]; + edge->m_hasVertex0 = true; + } + else + { + edge->m_vertex0 = m_prevVertex; + edge->m_hasVertex0 = m_hasPrevVertex; + } + + if (index < m_count - 2) + { + edge->m_vertex3 = m_vertices[index + 2]; + edge->m_hasVertex3 = true; + } + else + { + edge->m_vertex3 = m_nextVertex; + edge->m_hasVertex3 = m_hasNextVertex; + } +} + +bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + b2EdgeShape edgeShape; + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + edgeShape.m_vertex1 = m_vertices[i1]; + edgeShape.m_vertex2 = m_vertices[i2]; + + return edgeShape.RayCast(output, input, xf, 0); +} + +void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); + b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); + + aabb->lowerBound = b2Min(v1, v2); + aabb->upperBound = b2Max(v1, v2); +} + +void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center.SetZero(); + massData->I = 0.0f; +} diff --git a/external/box2d/Collision/Shapes/b2ChainShape.h b/external/box2d/Collision/Shapes/b2ChainShape.h new file mode 100644 index 0000000000..9c9a9eaa7d --- /dev/null +++ b/external/box2d/Collision/Shapes/b2ChainShape.h @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_SHAPE_H +#define B2_CHAIN_SHAPE_H + +#include + +class b2EdgeShape; + +/// A chain shape is a free form sequence of line segments. +/// The chain has two-sided collision, so you can use inside and outside collision. +/// Therefore, you may use any winding order. +/// Since there may be many vertices, they are allocated using b2Alloc. +/// Connectivity information is used to create smooth collisions. +/// WARNING: The chain will not collide properly if there are self-intersections. +class b2ChainShape : public b2Shape +{ +public: + b2ChainShape(); + + /// The destructor frees the vertices using b2Free. + ~b2ChainShape(); + + /// Create a loop. This automatically adjusts connectivity. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateLoop(const b2Vec2* vertices, int32 count); + + /// Create a chain with isolated end vertices. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateChain(const b2Vec2* vertices, int32 count); + + /// Establish connectivity to a vertex that precedes the first vertex. + /// Don't call this for loops. + void SetPrevVertex(const b2Vec2& prevVertex); + + /// Establish connectivity to a vertex that follows the last vertex. + /// Don't call this for loops. + void SetNextVertex(const b2Vec2& nextVertex); + + /// Implement b2Shape. Vertices are cloned using b2Alloc. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Get a child edge. + void GetChildEdge(b2EdgeShape* edge, int32 index) const; + + /// This always return false. + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// Chains have zero mass. + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// The vertices. Owned by this class. + b2Vec2* m_vertices; + + /// The vertex count. + int32 m_count; + + b2Vec2 m_prevVertex, m_nextVertex; + bool m_hasPrevVertex, m_hasNextVertex; +}; + +inline b2ChainShape::b2ChainShape() +{ + m_type = e_chain; + m_radius = b2_polygonRadius; + m_vertices = NULL; + m_count = 0; + m_hasPrevVertex = false; + m_hasNextVertex = false; +} + +#endif diff --git a/external/box2d/Collision/Shapes/b2CircleShape.cpp b/external/box2d/Collision/Shapes/b2CircleShape.cpp new file mode 100644 index 0000000000..587ca960b2 --- /dev/null +++ b/external/box2d/Collision/Shapes/b2CircleShape.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2CircleShape)); + b2CircleShape* clone = new (mem) b2CircleShape; + *clone = *this; + return clone; +} + +int32 b2CircleShape::GetChildCount() const +{ + return 1; +} + +bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const +{ + b2Vec2 center = transform.p + b2Mul(transform.q, m_p); + b2Vec2 d = p - center; + return b2Dot(d, d) <= m_radius * m_radius; +} + +// Collision Detection in Interactive 3D Environments by Gino van den Bergen +// From Section 3.1.2 +// x = s + a * r +// norm(x) = radius +bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 position = transform.p + b2Mul(transform.q, m_p); + b2Vec2 s = input.p1 - position; + float32 b = b2Dot(s, s) - m_radius * m_radius; + + // Solve quadratic equation. + b2Vec2 r = input.p2 - input.p1; + float32 c = b2Dot(s, r); + float32 rr = b2Dot(r, r); + float32 sigma = c * c - rr * b; + + // Check for negative discriminant and short segment. + if (sigma < 0.0f || rr < b2_epsilon) + { + return false; + } + + // Find the point of intersection of the line with the circle. + float32 a = -(c + b2Sqrt(sigma)); + + // Is the intersection point on the segment? + if (0.0f <= a && a <= input.maxFraction * rr) + { + a /= rr; + output->fraction = a; + output->normal = s + a * r; + output->normal.Normalize(); + return true; + } + + return false; +} + +void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 p = transform.p + b2Mul(transform.q, m_p); + aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); + aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); +} + +void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const +{ + massData->mass = density * b2_pi * m_radius * m_radius; + massData->center = m_p; + + // inertia about the local origin + massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); +} diff --git a/external/box2d/Collision/Shapes/b2CircleShape.h b/external/box2d/Collision/Shapes/b2CircleShape.h new file mode 100644 index 0000000000..c4e23a475b --- /dev/null +++ b/external/box2d/Collision/Shapes/b2CircleShape.h @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CIRCLE_SHAPE_H +#define B2_CIRCLE_SHAPE_H + +#include + +/// A circle shape. +class b2CircleShape : public b2Shape +{ +public: + b2CircleShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Implement b2Shape. + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return 1; } + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + /// Position + b2Vec2 m_p; +}; + +inline b2CircleShape::b2CircleShape() +{ + m_type = e_circle; + m_radius = 0.0f; + m_p.SetZero(); +} + +inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return 0; +} + +inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return m_p; +} + +inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const +{ + B2_NOT_USED(index); + b2Assert(index == 0); + return m_p; +} + +#endif diff --git a/external/box2d/Collision/Shapes/b2EdgeShape.cpp b/external/box2d/Collision/Shapes/b2EdgeShape.cpp new file mode 100644 index 0000000000..7b09e55bf4 --- /dev/null +++ b/external/box2d/Collision/Shapes/b2EdgeShape.cpp @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) +{ + m_vertex1 = v1; + m_vertex2 = v2; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2EdgeShape)); + b2EdgeShape* clone = new (mem) b2EdgeShape; + *clone = *this; + return clone; +} + +int32 b2EdgeShape::GetChildCount() const +{ + return 1; +} + +bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +// p = p1 + t * d +// v = v1 + s * e +// p1 + t * d = v1 + s * e +// s * e - t * d = p1 - v1 +bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + // Put the ray into the edge's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; + + b2Vec2 v1 = m_vertex1; + b2Vec2 v2 = m_vertex2; + b2Vec2 e = v2 - v1; + b2Vec2 normal(e.y, -e.x); + normal.Normalize(); + + // q = p1 + t * d + // dot(normal, q - v1) = 0 + // dot(normal, p1 - v1) + t * dot(normal, d) = 0 + float32 numerator = b2Dot(normal, v1 - p1); + float32 denominator = b2Dot(normal, d); + + if (denominator == 0.0f) + { + return false; + } + + float32 t = numerator / denominator; + if (t < 0.0f || input.maxFraction < t) + { + return false; + } + + b2Vec2 q = p1 + t * d; + + // q = v1 + s * r + // s = dot(q - v1, r) / dot(r, r) + b2Vec2 r = v2 - v1; + float32 rr = b2Dot(r, r); + if (rr == 0.0f) + { + return false; + } + + float32 s = b2Dot(q - v1, r) / rr; + if (s < 0.0f || 1.0f < s) + { + return false; + } + + output->fraction = t; + if (numerator > 0.0f) + { + output->normal = -normal; + } + else + { + output->normal = normal; + } + return true; +} + +void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 v1 = b2Mul(xf, m_vertex1); + b2Vec2 v2 = b2Mul(xf, m_vertex2); + + b2Vec2 lower = b2Min(v1, v2); + b2Vec2 upper = b2Max(v1, v2); + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center = 0.5f * (m_vertex1 + m_vertex2); + massData->I = 0.0f; +} diff --git a/external/box2d/Collision/Shapes/b2EdgeShape.h b/external/box2d/Collision/Shapes/b2EdgeShape.h new file mode 100644 index 0000000000..6163bcbf1c --- /dev/null +++ b/external/box2d/Collision/Shapes/b2EdgeShape.h @@ -0,0 +1,74 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_SHAPE_H +#define B2_EDGE_SHAPE_H + +#include + +/// A line segment (edge) shape. These can be connected in chains or loops +/// to other edge shapes. The connectivity information is used to ensure +/// correct contact normals. +class b2EdgeShape : public b2Shape +{ +public: + b2EdgeShape(); + + /// Set this as an isolated edge. + void Set(const b2Vec2& v1, const b2Vec2& v2); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// These are the edge vertices + b2Vec2 m_vertex1, m_vertex2; + + /// Optional adjacent vertices. These are used for smooth collision. + b2Vec2 m_vertex0, m_vertex3; + bool m_hasVertex0, m_hasVertex3; +}; + +inline b2EdgeShape::b2EdgeShape() +{ + m_type = e_edge; + m_radius = b2_polygonRadius; + m_vertex0.x = 0.0f; + m_vertex0.y = 0.0f; + m_vertex3.x = 0.0f; + m_vertex3.y = 0.0f; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +#endif diff --git a/external/box2d/Collision/Shapes/b2PolygonShape.cpp b/external/box2d/Collision/Shapes/b2PolygonShape.cpp new file mode 100644 index 0000000000..c04c1dc49b --- /dev/null +++ b/external/box2d/Collision/Shapes/b2PolygonShape.cpp @@ -0,0 +1,361 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2PolygonShape)); + b2PolygonShape* clone = new (mem) b2PolygonShape; + *clone = *this; + return clone; +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid.SetZero(); +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid = center; + + b2Transform xf; + xf.p = center; + xf.q.Set(angle); + + // Transform vertices and normals. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = b2Mul(xf, m_vertices[i]); + m_normals[i] = b2Mul(xf.q, m_normals[i]); + } +} + +int32 b2PolygonShape::GetChildCount() const +{ + return 1; +} + +static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) +{ + b2Assert(count >= 3); + + b2Vec2 c; c.Set(0.0f, 0.0f); + float32 area = 0.0f; + + // pRef is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 pRef(0.0f, 0.0f); +#if 0 + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < count; ++i) + { + pRef += vs[i]; + } + pRef *= 1.0f / count; +#endif + + const float32 inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < count; ++i) + { + // Triangle vertices. + b2Vec2 p1 = pRef; + b2Vec2 p2 = vs[i]; + b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; + + b2Vec2 e1 = p2 - p1; + b2Vec2 e2 = p3 - p1; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + c += triangleArea * inv3 * (p1 + p2 + p3); + } + + // Centroid + b2Assert(area > b2_epsilon); + c *= 1.0f / area; + return c; +} + +void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) +{ + b2Assert(3 <= count && count <= b2_maxPolygonVertices); + m_vertexCount = count; + + // Copy vertices. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = vertices[i]; + } + + // Compute normals. Ensure the edges have non-zero length. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); + m_normals[i] = b2Cross(edge, 1.0f); + m_normals[i].Normalize(); + } + +#ifdef _DEBUG + // Ensure the polygon is convex and the interior + // is to the left of each edge. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + + for (int32 j = 0; j < m_vertexCount; ++j) + { + // Don't check vertices on the current edge. + if (j == i1 || j == i2) + { + continue; + } + + b2Vec2 r = m_vertices[j] - m_vertices[i1]; + + // If this crashes, your polygon is non-convex, has colinear edges, + // or the winding order is wrong. + float32 s = b2Cross(edge, r); + b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); + } + } +#endif + + // Compute the polygon centroid. + m_centroid = ComputeCentroid(m_vertices, m_vertexCount); +} + +bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); + + for (int32 i = 0; i < m_vertexCount; ++i) + { + float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); + if (dot > 0.0f) + { + return false; + } + } + + return true; +} + +bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + // Put the ray into the polygon's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; + + float32 lower = 0.0f, upper = input.maxFraction; + + int32 index = -1; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // p = p1 + a * d + // dot(normal, p - v) = 0 + // dot(normal, p1 - v) + a * dot(normal, d) = 0 + float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); + float32 denominator = b2Dot(m_normals[i], d); + + if (denominator == 0.0f) + { + if (numerator < 0.0f) + { + return false; + } + } + else + { + // Note: we want this predicate without division: + // lower < numerator / denominator, where denominator < 0 + // Since denominator < 0, we have to flip the inequality: + // lower < numerator / denominator <==> denominator * lower > numerator. + if (denominator < 0.0f && numerator < lower * denominator) + { + // Increase lower. + // The segment enters this half-space. + lower = numerator / denominator; + index = i; + } + else if (denominator > 0.0f && numerator < upper * denominator) + { + // Decrease upper. + // The segment exits this half-space. + upper = numerator / denominator; + } + } + + // The use of epsilon here causes the assert on lower to trip + // in some cases. Apparently the use of epsilon was to make edge + // shapes work, but now those are handled separately. + //if (upper < lower - b2_epsilon) + if (upper < lower) + { + return false; + } + } + + b2Assert(0.0f <= lower && lower <= input.maxFraction); + + if (index >= 0) + { + output->fraction = lower; + output->normal = b2Mul(xf.q, m_normals[index]); + return true; + } + + return false; +} + +void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 lower = b2Mul(xf, m_vertices[0]); + b2Vec2 upper = lower; + + for (int32 i = 1; i < m_vertexCount; ++i) + { + b2Vec2 v = b2Mul(xf, m_vertices[i]); + lower = b2Min(lower, v); + upper = b2Max(upper, v); + } + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const +{ + // Polygon mass, centroid, and inertia. + // Let rho be the polygon density in mass per unit area. + // Then: + // mass = rho * int(dA) + // centroid.x = (1/mass) * rho * int(x * dA) + // centroid.y = (1/mass) * rho * int(y * dA) + // I = rho * int((x*x + y*y) * dA) + // + // We can compute these integrals by summing all the integrals + // for each triangle of the polygon. To evaluate the integral + // for a single triangle, we make a change of variables to + // the (u,v) coordinates of the triangle: + // x = x0 + e1x * u + e2x * v + // y = y0 + e1y * u + e2y * v + // where 0 <= u && 0 <= v && u + v <= 1. + // + // We integrate u from [0,1-v] and then v from [0,1]. + // We also need to use the Jacobian of the transformation: + // D = cross(e1, e2) + // + // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) + // + // The rest of the derivation is handled by computer algebra. + + b2Assert(m_vertexCount >= 3); + + b2Vec2 center; center.Set(0.0f, 0.0f); + float32 area = 0.0f; + float32 I = 0.0f; + + // s is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 s(0.0f, 0.0f); + + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < m_vertexCount; ++i) + { + s += m_vertices[i]; + } + s *= 1.0f / m_vertexCount; + + const float32 k_inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // Triangle vertices. + b2Vec2 e1 = m_vertices[i] - s; + b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + center += triangleArea * k_inv3 * (e1 + e2); + + float32 ex1 = e1.x, ey1 = e1.y; + float32 ex2 = e2.x, ey2 = e2.y; + + float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; + float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; + + I += (0.25f * k_inv3 * D) * (intx2 + inty2); + } + + // Total mass + massData->mass = density * area; + + // Center of mass + b2Assert(area > b2_epsilon); + center *= 1.0f / area; + massData->center = center + s; + + // Inertia tensor relative to the local origin (point s). + massData->I = density * I; + + // Shift to center of mass then to original body origin. + massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); +} diff --git a/external/box2d/Collision/Shapes/b2PolygonShape.h b/external/box2d/Collision/Shapes/b2PolygonShape.h new file mode 100644 index 0000000000..70daccb2ff --- /dev/null +++ b/external/box2d/Collision/Shapes/b2PolygonShape.h @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_SHAPE_H +#define B2_POLYGON_SHAPE_H + +#include + +/// A convex polygon. It is assumed that the interior of the polygon is to +/// the left of each edge. +/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. +/// In most cases you should not need many vertices for a convex polygon. +class b2PolygonShape : public b2Shape +{ +public: + b2PolygonShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Copy vertices. This assumes the vertices define a convex polygon. + /// It is assumed that the exterior is the the right of each edge. + /// The count must be in the range [3, b2_maxPolygonVertices]. + void Set(const b2Vec2* vertices, int32 vertexCount); + + /// Build vertices to represent an axis-aligned box. + /// @param hx the half-width. + /// @param hy the half-height. + void SetAsBox(float32 hx, float32 hy); + + /// Build vertices to represent an oriented box. + /// @param hx the half-width. + /// @param hy the half-height. + /// @param center the center of the box in local coordinates. + /// @param angle the rotation of the box in local coordinates. + void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return m_vertexCount; } + + /// Get a vertex by index. + const b2Vec2& GetVertex(int32 index) const; + + b2Vec2 m_centroid; + b2Vec2 m_vertices[b2_maxPolygonVertices]; + b2Vec2 m_normals[b2_maxPolygonVertices]; + int32 m_vertexCount; +}; + +inline b2PolygonShape::b2PolygonShape() +{ + m_type = e_polygon; + m_radius = b2_polygonRadius; + m_vertexCount = 0; + m_centroid.SetZero(); +} + +inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_vertexCount); + return m_vertices[index]; +} + +#endif diff --git a/external/box2d/Collision/Shapes/b2Shape.h b/external/box2d/Collision/Shapes/b2Shape.h new file mode 100644 index 0000000000..2e2aedd14a --- /dev/null +++ b/external/box2d/Collision/Shapes/b2Shape.h @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_SHAPE_H +#define B2_SHAPE_H + +#include +#include +#include + +/// This holds the mass data computed for a shape. +struct b2MassData +{ + /// The mass of the shape, usually in kilograms. + float32 mass; + + /// The position of the shape's centroid relative to the shape's origin. + b2Vec2 center; + + /// The rotational inertia of the shape about the local origin. + float32 I; +}; + +/// A shape is used for collision detection. You can create a shape however you like. +/// Shapes used for simulation in b2World are created automatically when a b2Fixture +/// is created. Shapes may encapsulate a one or more child shapes. +class b2Shape +{ +public: + + enum Type + { + e_circle = 0, + e_edge = 1, + e_polygon = 2, + e_chain = 3, + e_typeCount = 4 + }; + + virtual ~b2Shape() {} + + /// Clone the concrete shape using the provided allocator. + virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; + + /// Get the type of this shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + Type GetType() const; + + /// Get the number of child primitives. + virtual int32 GetChildCount() const = 0; + + /// Test a point for containment in this shape. This only works for convex shapes. + /// @param xf the shape world transform. + /// @param p a point in world coordinates. + virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; + + /// Cast a ray against a child shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + /// @param transform the transform to be applied to the shape. + /// @param childIndex the child shape index + virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const = 0; + + /// Given a transform, compute the associated axis aligned bounding box for a child shape. + /// @param aabb returns the axis aligned box. + /// @param xf the world transform of the shape. + /// @param childIndex the child shape + virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; + + /// Compute the mass properties of this shape using its dimensions and density. + /// The inertia tensor is computed about the local origin. + /// @param massData returns the mass data for this shape. + /// @param density the density in kilograms per meter squared. + virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; + + Type m_type; + float32 m_radius; +}; + +inline b2Shape::Type b2Shape::GetType() const +{ + return m_type; +} + +#endif diff --git a/external/box2d/Collision/b2BroadPhase.cpp b/external/box2d/Collision/b2BroadPhase.cpp new file mode 100644 index 0000000000..431f6de1ee --- /dev/null +++ b/external/box2d/Collision/b2BroadPhase.cpp @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +b2BroadPhase::b2BroadPhase() +{ + m_proxyCount = 0; + + m_pairCapacity = 16; + m_pairCount = 0; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + + m_moveCapacity = 16; + m_moveCount = 0; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); +} + +b2BroadPhase::~b2BroadPhase() +{ + b2Free(m_moveBuffer); + b2Free(m_pairBuffer); +} + +int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = m_tree.CreateProxy(aabb, userData); + ++m_proxyCount; + BufferMove(proxyId); + return proxyId; +} + +void b2BroadPhase::DestroyProxy(int32 proxyId) +{ + UnBufferMove(proxyId); + --m_proxyCount; + m_tree.DestroyProxy(proxyId); +} + +void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); + if (buffer) + { + BufferMove(proxyId); + } +} + +void b2BroadPhase::TouchProxy(int32 proxyId) +{ + BufferMove(proxyId); +} + +void b2BroadPhase::BufferMove(int32 proxyId) +{ + if (m_moveCount == m_moveCapacity) + { + int32* oldBuffer = m_moveBuffer; + m_moveCapacity *= 2; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); + memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); + b2Free(oldBuffer); + } + + m_moveBuffer[m_moveCount] = proxyId; + ++m_moveCount; +} + +void b2BroadPhase::UnBufferMove(int32 proxyId) +{ + for (int32 i = 0; i < m_moveCount; ++i) + { + if (m_moveBuffer[i] == proxyId) + { + m_moveBuffer[i] = e_nullProxy; + return; + } + } +} + +// This is called from b2DynamicTree::Query when we are gathering pairs. +bool b2BroadPhase::QueryCallback(int32 proxyId) +{ + // A proxy cannot form a pair with itself. + if (proxyId == m_queryProxyId) + { + return true; + } + + // Grow the pair buffer as needed. + if (m_pairCount == m_pairCapacity) + { + b2Pair* oldBuffer = m_pairBuffer; + m_pairCapacity *= 2; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); + b2Free(oldBuffer); + } + + m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); + m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); + ++m_pairCount; + + return true; +} diff --git a/external/box2d/Collision/b2BroadPhase.h b/external/box2d/Collision/b2BroadPhase.h new file mode 100644 index 0000000000..cf2414730a --- /dev/null +++ b/external/box2d/Collision/b2BroadPhase.h @@ -0,0 +1,248 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BROAD_PHASE_H +#define B2_BROAD_PHASE_H + +#include +#include +#include +#include + +struct b2Pair +{ + int32 proxyIdA; + int32 proxyIdB; + int32 next; +}; + +/// The broad-phase is used for computing pairs and performing volume queries and ray casts. +/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. +/// It is up to the client to consume the new pairs and to track subsequent overlap. +class b2BroadPhase +{ +public: + + enum + { + e_nullProxy = -1 + }; + + b2BroadPhase(); + ~b2BroadPhase(); + + /// Create a proxy with an initial AABB. Pairs are not reported until + /// UpdatePairs is called. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. It is up to the client to remove any pairs. + void DestroyProxy(int32 proxyId); + + /// Call MoveProxy as many times as you like, then when you are done + /// call UpdatePairs to finalized the proxy pairs (for your time step). + void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); + + /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. + void TouchProxy(int32 proxyId); + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Get user data from a proxy. Returns NULL if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Test overlap of fat AABBs. + bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; + + /// Get the number of proxies. + int32 GetProxyCount() const; + + /// Update the pairs. This results in pair callbacks. This can only add pairs. + template + void UpdatePairs(T* callback); + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + + /// Get the height of the embedded tree. + int32 GetTreeHeight() const; + + /// Get the balance of the embedded tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the embedded tree. + float32 GetTreeQuality() const; + +private: + + friend class b2DynamicTree; + + void BufferMove(int32 proxyId); + void UnBufferMove(int32 proxyId); + + bool QueryCallback(int32 proxyId); + + b2DynamicTree m_tree; + + int32 m_proxyCount; + + int32* m_moveBuffer; + int32 m_moveCapacity; + int32 m_moveCount; + + b2Pair* m_pairBuffer; + int32 m_pairCapacity; + int32 m_pairCount; + + int32 m_queryProxyId; +}; + +/// This is used to sort pairs. +inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) +{ + if (pair1.proxyIdA < pair2.proxyIdA) + { + return true; + } + + if (pair1.proxyIdA == pair2.proxyIdA) + { + return pair1.proxyIdB < pair2.proxyIdB; + } + + return false; +} + +inline void* b2BroadPhase::GetUserData(int32 proxyId) const +{ + return m_tree.GetUserData(proxyId); +} + +inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const +{ + const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); + const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); + return b2TestOverlap(aabbA, aabbB); +} + +inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const +{ + return m_tree.GetFatAABB(proxyId); +} + +inline int32 b2BroadPhase::GetProxyCount() const +{ + return m_proxyCount; +} + +inline int32 b2BroadPhase::GetTreeHeight() const +{ + return m_tree.GetHeight(); +} + +inline int32 b2BroadPhase::GetTreeBalance() const +{ + return m_tree.GetMaxBalance(); +} + +inline float32 b2BroadPhase::GetTreeQuality() const +{ + return m_tree.GetAreaRatio(); +} + +template +void b2BroadPhase::UpdatePairs(T* callback) +{ + // Reset pair buffer + m_pairCount = 0; + + // Perform tree queries for all moving proxies. + for (int32 i = 0; i < m_moveCount; ++i) + { + m_queryProxyId = m_moveBuffer[i]; + if (m_queryProxyId == e_nullProxy) + { + continue; + } + + // We have to query the tree with the fat AABB so that + // we don't fail to create a pair that may touch later. + const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); + + // Query tree, create pairs and add them pair buffer. + m_tree.Query(this, fatAABB); + } + + // Reset move buffer + m_moveCount = 0; + + // Sort the pair buffer to expose duplicates. + std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); + + // Send the pairs back to the client. + int32 i = 0; + while (i < m_pairCount) + { + b2Pair* primaryPair = m_pairBuffer + i; + void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); + void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); + + callback->AddPair(userDataA, userDataB); + ++i; + + // Skip any duplicate pairs. + while (i < m_pairCount) + { + b2Pair* pair = m_pairBuffer + i; + if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) + { + break; + } + ++i; + } + } + + // Try to keep the tree balanced. + //m_tree.Rebalance(4); +} + +template +inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const +{ + m_tree.Query(callback, aabb); +} + +template +inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const +{ + m_tree.RayCast(callback, input); +} + +#endif diff --git a/external/box2d/Collision/b2CollideCircle.cpp b/external/box2d/Collision/b2CollideCircle.cpp new file mode 100644 index 0000000000..ed561eb04b --- /dev/null +++ b/external/box2d/Collision/b2CollideCircle.cpp @@ -0,0 +1,154 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +void b2CollideCircles( + b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + b2Vec2 pA = b2Mul(xfA, circleA->m_p); + b2Vec2 pB = b2Mul(xfB, circleB->m_p); + + b2Vec2 d = pB - pA; + float32 distSqr = b2Dot(d, d); + float32 rA = circleA->m_radius, rB = circleB->m_radius; + float32 radius = rA + rB; + if (distSqr > radius * radius) + { + return; + } + + manifold->type = b2Manifold::e_circles; + manifold->localPoint = circleA->m_p; + manifold->localNormal.SetZero(); + manifold->pointCount = 1; + + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; +} + +void b2CollidePolygonAndCircle( + b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle position in the frame of the polygon. + b2Vec2 c = b2Mul(xfB, circleB->m_p); + b2Vec2 cLocal = b2MulT(xfA, c); + + // Find the min separating edge. + int32 normalIndex = 0; + float32 separation = -b2_maxFloat; + float32 radius = polygonA->m_radius + circleB->m_radius; + int32 vertexCount = polygonA->m_vertexCount; + const b2Vec2* vertices = polygonA->m_vertices; + const b2Vec2* normals = polygonA->m_normals; + + for (int32 i = 0; i < vertexCount; ++i) + { + float32 s = b2Dot(normals[i], cLocal - vertices[i]); + + if (s > radius) + { + // Early out. + return; + } + + if (s > separation) + { + separation = s; + normalIndex = i; + } + } + + // Vertices that subtend the incident face. + int32 vertIndex1 = normalIndex; + int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; + b2Vec2 v1 = vertices[vertIndex1]; + b2Vec2 v2 = vertices[vertIndex2]; + + // If the center is inside the polygon ... + if (separation < b2_epsilon) + { + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[normalIndex]; + manifold->localPoint = 0.5f * (v1 + v2); + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + return; + } + + // Compute barycentric coordinates + float32 u1 = b2Dot(cLocal - v1, v2 - v1); + float32 u2 = b2Dot(cLocal - v2, v1 - v2); + if (u1 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v1) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v1; + manifold->localNormal.Normalize(); + manifold->localPoint = v1; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else if (u2 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v2) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v2; + manifold->localNormal.Normalize(); + manifold->localPoint = v2; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else + { + b2Vec2 faceCenter = 0.5f * (v1 + v2); + float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); + if (separation > radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[vertIndex1]; + manifold->localPoint = faceCenter; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } +} diff --git a/external/box2d/Collision/b2CollideEdge.cpp b/external/box2d/Collision/b2CollideEdge.cpp new file mode 100644 index 0000000000..96ca71dccc --- /dev/null +++ b/external/box2d/Collision/b2CollideEdge.cpp @@ -0,0 +1,698 @@ +/* + * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#include +#include +#include +#include + + +// Compute contact points for edge versus circle. +// This accounts for edge connectivity. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle in frame of edge + b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); + + b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; + b2Vec2 e = B - A; + + // Barycentric coordinates + float32 u = b2Dot(e, B - Q); + float32 v = b2Dot(e, Q - A); + + float32 radius = edgeA->m_radius + circleB->m_radius; + + b2ContactFeature cf; + cf.indexB = 0; + cf.typeB = b2ContactFeature::e_vertex; + + // Region A + if (v <= 0.0f) + { + b2Vec2 P = A; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to A? + if (edgeA->m_hasVertex0) + { + b2Vec2 A1 = edgeA->m_vertex0; + b2Vec2 B1 = A; + b2Vec2 e1 = B1 - A1; + float32 u1 = b2Dot(e1, B1 - Q); + + // Is the circle in Region AB of the previous edge? + if (u1 > 0.0f) + { + return; + } + } + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region B + if (u <= 0.0f) + { + b2Vec2 P = B; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to B? + if (edgeA->m_hasVertex3) + { + b2Vec2 B2 = edgeA->m_vertex3; + b2Vec2 A2 = B; + b2Vec2 e2 = B2 - A2; + float32 v2 = b2Dot(e2, Q - A2); + + // Is the circle in Region AB of the next edge? + if (v2 > 0.0f) + { + return; + } + } + + cf.indexA = 1; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region AB + float32 den = b2Dot(e, e); + b2Assert(den > 0.0f); + b2Vec2 P = (1.0f / den) * (u * A + v * B); + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + b2Vec2 n(-e.y, e.x); + if (b2Dot(n, Q - A) < 0.0f) + { + n.Set(-n.x, -n.y); + } + n.Normalize(); + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_face; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = n; + manifold->localPoint = A; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; +} + +// This structure is used to keep track of the best separating axis. +struct b2EPAxis +{ + enum Type + { + e_unknown, + e_edgeA, + e_edgeB + }; + + Type type; + int32 index; + float32 separation; +}; + +// This holds polygon B expressed in frame A. +struct b2TempPolygon +{ + b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 normals[b2_maxPolygonVertices]; + int32 count; +}; + +// Reference face used for clipping +struct b2ReferenceFace +{ + int32 i1, i2; + + b2Vec2 v1, v2; + + b2Vec2 normal; + + b2Vec2 sideNormal1; + float32 sideOffset1; + + b2Vec2 sideNormal2; + float32 sideOffset2; +}; + +// This class collides and edge and a polygon, taking into account edge adjacency. +struct b2EPCollider +{ + void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + b2EPAxis ComputeEdgeSeparation(); + b2EPAxis ComputePolygonSeparation(); + + enum VertexType + { + e_isolated, + e_concave, + e_convex + }; + + b2TempPolygon m_polygonB; + + b2Transform m_xf; + b2Vec2 m_centroidB; + b2Vec2 m_v0, m_v1, m_v2, m_v3; + b2Vec2 m_normal0, m_normal1, m_normal2; + b2Vec2 m_normal; + VertexType m_type1, m_type2; + b2Vec2 m_lowerLimit, m_upperLimit; + float32 m_radius; + bool m_front; +}; + +// Algorithm: +// 1. Classify v1 and v2 +// 2. Classify polygon centroid as front or back +// 3. Flip normal if necessary +// 4. Initialize normal range to [-pi, pi] about face normal +// 5. Adjust normal range according to adjacent edges +// 6. Visit each separating axes, only accept axes within the range +// 7. Return if _any_ axis indicates separation +// 8. Clip +void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + m_xf = b2MulT(xfA, xfB); + + m_centroidB = b2Mul(m_xf, polygonB->m_centroid); + + m_v0 = edgeA->m_vertex0; + m_v1 = edgeA->m_vertex1; + m_v2 = edgeA->m_vertex2; + m_v3 = edgeA->m_vertex3; + + bool hasVertex0 = edgeA->m_hasVertex0; + bool hasVertex3F = edgeA->m_hasVertex3; + + b2Vec2 edge1 = m_v2 - m_v1; + edge1.Normalize(); + m_normal1.Set(edge1.y, -edge1.x); + float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); + float32 offset0 = 0.0f, offset2 = 0.0f; + bool convex1 = false, convex2 = false; + + // Is there a preceding edge? + if (hasVertex0) + { + b2Vec2 edge0 = m_v1 - m_v0; + edge0.Normalize(); + m_normal0.Set(edge0.y, -edge0.x); + convex1 = b2Cross(edge0, edge1) >= 0.0f; + offset0 = b2Dot(m_normal0, m_centroidB - m_v0); + } + + // Is there a following edge? + if (hasVertex3F) + { + b2Vec2 edge2 = m_v3 - m_v2; + edge2.Normalize(); + m_normal2.Set(edge2.y, -edge2.x); + convex2 = b2Cross(edge1, edge2) > 0.0f; + offset2 = b2Dot(m_normal2, m_centroidB - m_v2); + } + + // Determine front or back collision. Determine collision normal limits. + if (hasVertex0 && hasVertex3F) + { + if (convex1 && convex2) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + } + else if (convex1) + { + m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal1; + } + } + else if (convex2) + { + m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal0; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex0) + { + if (convex1) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex3F) + { + if (convex2) + { + m_front = offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + } + else + { + m_front = offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = m_normal1; + } + } + } + else + { + m_front = offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + } + + // Get polygonB in frameA + m_polygonB.count = polygonB->m_vertexCount; + for (int32 i = 0; i < polygonB->m_vertexCount; ++i) + { + m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); + m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); + } + + m_radius = 2.0f * b2_polygonRadius; + + manifold->pointCount = 0; + + b2EPAxis edgeAxis = ComputeEdgeSeparation(); + + // If no valid normal can be found than this edge should not collide. + if (edgeAxis.type == b2EPAxis::e_unknown) + { + return; + } + + if (edgeAxis.separation > m_radius) + { + return; + } + + b2EPAxis polygonAxis = ComputePolygonSeparation(); + if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) + { + return; + } + + // Use hysteresis for jitter reduction. + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + b2EPAxis primaryAxis; + if (polygonAxis.type == b2EPAxis::e_unknown) + { + primaryAxis = edgeAxis; + } + else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) + { + primaryAxis = polygonAxis; + } + else + { + primaryAxis = edgeAxis; + } + + b2ClipVertex ie[2]; + b2ReferenceFace rf; + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->type = b2Manifold::e_faceA; + + // Search for the polygon normal that is most anti-parallel to the edge normal. + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); + for (int32 i = 1; i < m_polygonB.count; ++i) + { + float32 value = b2Dot(m_normal, m_polygonB.normals[i]); + if (value < bestValue) + { + bestValue = value; + bestIndex = i; + } + } + + int32 i1 = bestIndex; + int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; + + ie[0].v = m_polygonB.vertices[i1]; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = i1; + ie[0].id.cf.typeA = b2ContactFeature::e_face; + ie[0].id.cf.typeB = b2ContactFeature::e_vertex; + + ie[1].v = m_polygonB.vertices[i2]; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = i2; + ie[1].id.cf.typeA = b2ContactFeature::e_face; + ie[1].id.cf.typeB = b2ContactFeature::e_vertex; + + if (m_front) + { + rf.i1 = 0; + rf.i2 = 1; + rf.v1 = m_v1; + rf.v2 = m_v2; + rf.normal = m_normal1; + } + else + { + rf.i1 = 1; + rf.i2 = 0; + rf.v1 = m_v2; + rf.v2 = m_v1; + rf.normal = -m_normal1; + } + } + else + { + manifold->type = b2Manifold::e_faceB; + + ie[0].v = m_v1; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = primaryAxis.index; + ie[0].id.cf.typeA = b2ContactFeature::e_vertex; + ie[0].id.cf.typeB = b2ContactFeature::e_face; + + ie[1].v = m_v2; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = primaryAxis.index; + ie[1].id.cf.typeA = b2ContactFeature::e_vertex; + ie[1].id.cf.typeB = b2ContactFeature::e_face; + + rf.i1 = primaryAxis.index; + rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; + rf.v1 = m_polygonB.vertices[rf.i1]; + rf.v2 = m_polygonB.vertices[rf.i2]; + rf.normal = m_polygonB.normals[rf.i1]; + } + + rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); + rf.sideNormal2 = -rf.sideNormal1; + rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); + rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int32 np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Now clipPoints2 contains the clipped points. + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->localNormal = rf.normal; + manifold->localPoint = rf.v1; + } + else + { + manifold->localNormal = polygonB->m_normals[rf.i1]; + manifold->localPoint = polygonB->m_vertices[rf.i1]; + } + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation; + + separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); + + if (separation <= m_radius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + } + else + { + cp->localPoint = clipPoints2[i].v; + cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; + cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; + cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; + cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; + } + + ++pointCount; + } + } + + manifold->pointCount = pointCount; +} + +b2EPAxis b2EPCollider::ComputeEdgeSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_edgeA; + axis.index = m_front ? 0 : 1; + axis.separation = FLT_MAX; + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); + if (s < axis.separation) + { + axis.separation = s; + } + } + + return axis; +} + +b2EPAxis b2EPCollider::ComputePolygonSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_unknown; + axis.index = -1; + axis.separation = -FLT_MAX; + + b2Vec2 perp(-m_normal.y, m_normal.x); + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + b2Vec2 n = -m_polygonB.normals[i]; + + float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); + float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); + float32 s = b2Min(s1, s2); + + if (s > m_radius) + { + // No collision + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + return axis; + } + + // Adjacency + if (b2Dot(n, perp) >= 0.0f) + { + if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + else + { + if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + + if (s > axis.separation) + { + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + } + } + + return axis; +} + +void b2CollideEdgeAndPolygon( b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + b2EPCollider collider; + collider.Collide(manifold, edgeA, xfA, polygonB, xfB); +} diff --git a/external/box2d/Collision/b2CollidePolygon.cpp b/external/box2d/Collision/b2CollidePolygon.cpp new file mode 100644 index 0000000000..be2518d966 --- /dev/null +++ b/external/box2d/Collision/b2CollidePolygon.cpp @@ -0,0 +1,317 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +// Find the separation between poly1 and poly2 for a give edge normal on poly1. +static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + const b2Vec2* vertices1 = poly1->m_vertices; + const b2Vec2* normals1 = poly1->m_normals; + + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; + + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); + + // Convert normal from poly1's frame into poly2's frame. + b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); + b2Vec2 normal1 = b2MulT(xf2.q, normal1World); + + // Find support vertex on poly2 for -normal. + int32 index = 0; + float32 minDot = b2_maxFloat; + + for (int32 i = 0; i < count2; ++i) + { + float32 dot = b2Dot(vertices2[i], normal1); + if (dot < minDot) + { + minDot = dot; + index = i; + } + } + + b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]); + b2Vec2 v2 = b2Mul(xf2, vertices2[index]); + float32 separation = b2Dot(v2 - v1, normal1World); + return separation; +} + +// Find the max separation between poly1 and poly2 using edge normals from poly1. +static float32 b2FindMaxSeparation(int32* edgeIndex, + const b2PolygonShape* poly1, const b2Transform& xf1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + int32 count1 = poly1->m_vertexCount; + const b2Vec2* normals1 = poly1->m_normals; + + // Vector pointing from the centroid of poly1 to the centroid of poly2. + b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); + b2Vec2 dLocal1 = b2MulT(xf1.q, d); + + // Find edge normal on poly1 that has the largest projection onto d. + int32 edge = 0; + float32 maxDot = -b2_maxFloat; + for (int32 i = 0; i < count1; ++i) + { + float32 dot = b2Dot(normals1[i], dLocal1); + if (dot > maxDot) + { + maxDot = dot; + edge = i; + } + } + + // Get the separation for the edge normal. + float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); + + // Check the separation for the previous edge normal. + int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; + float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); + + // Check the separation for the next edge normal. + int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; + float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); + + // Find the best edge and the search direction. + int32 bestEdge; + float32 bestSeparation; + int32 increment; + if (sPrev > s && sPrev > sNext) + { + increment = -1; + bestEdge = prevEdge; + bestSeparation = sPrev; + } + else if (sNext > s) + { + increment = 1; + bestEdge = nextEdge; + bestSeparation = sNext; + } + else + { + *edgeIndex = edge; + return s; + } + + // Perform a local search for the best edge normal. + for ( ; ; ) + { + if (increment == -1) + edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1; + else + edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; + + s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); + + if (s > bestSeparation) + { + bestEdge = edge; + bestSeparation = s; + } + else + { + break; + } + } + + *edgeIndex = bestEdge; + return bestSeparation; +} + +static void b2FindIncidentEdge(b2ClipVertex c[2], + const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + const b2Vec2* normals1 = poly1->m_normals; + + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; + const b2Vec2* normals2 = poly2->m_normals; + + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); + + // Get the normal of the reference edge in poly2's frame. + b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); + + // Find the incident edge on poly2. + int32 index = 0; + float32 minDot = b2_maxFloat; + for (int32 i = 0; i < count2; ++i) + { + float32 dot = b2Dot(normal1, normals2[i]); + if (dot < minDot) + { + minDot = dot; + index = i; + } + } + + // Build the clip vertices for the incident edge. + int32 i1 = index; + int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; + + c[0].v = b2Mul(xf2, vertices2[i1]); + c[0].id.cf.indexA = (uint8)edge1; + c[0].id.cf.indexB = (uint8)i1; + c[0].id.cf.typeA = b2ContactFeature::e_face; + c[0].id.cf.typeB = b2ContactFeature::e_vertex; + + c[1].v = b2Mul(xf2, vertices2[i2]); + c[1].id.cf.indexA = (uint8)edge1; + c[1].id.cf.indexB = (uint8)i2; + c[1].id.cf.typeA = b2ContactFeature::e_face; + c[1].id.cf.typeB = b2ContactFeature::e_vertex; +} + +// Find edge normal of max separation on A - return if separating axis is found +// Find edge normal of max separation on B - return if separation axis is found +// Choose reference edge as min(minA, minB) +// Find incident edge +// Clip + +// The normal points from 1 to 2 +void b2CollidePolygons(b2Manifold* manifold, + const b2PolygonShape* polyA, const b2Transform& xfA, + const b2PolygonShape* polyB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + float32 totalRadius = polyA->m_radius + polyB->m_radius; + + int32 edgeA = 0; + float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); + if (separationA > totalRadius) + return; + + int32 edgeB = 0; + float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); + if (separationB > totalRadius) + return; + + const b2PolygonShape* poly1; // reference polygon + const b2PolygonShape* poly2; // incident polygon + b2Transform xf1, xf2; + int32 edge1; // reference edge + uint8 flip; + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + if (separationB > k_relativeTol * separationA + k_absoluteTol) + { + poly1 = polyB; + poly2 = polyA; + xf1 = xfB; + xf2 = xfA; + edge1 = edgeB; + manifold->type = b2Manifold::e_faceB; + flip = 1; + } + else + { + poly1 = polyA; + poly2 = polyB; + xf1 = xfA; + xf2 = xfB; + edge1 = edgeA; + manifold->type = b2Manifold::e_faceA; + flip = 0; + } + + b2ClipVertex incidentEdge[2]; + b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); + + int32 count1 = poly1->m_vertexCount; + const b2Vec2* vertices1 = poly1->m_vertices; + + int32 iv1 = edge1; + int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; + + b2Vec2 v11 = vertices1[iv1]; + b2Vec2 v12 = vertices1[iv2]; + + b2Vec2 localTangent = v12 - v11; + localTangent.Normalize(); + + b2Vec2 localNormal = b2Cross(localTangent, 1.0f); + b2Vec2 planePoint = 0.5f * (v11 + v12); + + b2Vec2 tangent = b2Mul(xf1.q, localTangent); + b2Vec2 normal = b2Cross(tangent, 1.0f); + + v11 = b2Mul(xf1, v11); + v12 = b2Mul(xf1, v12); + + // Face offset. + float32 frontOffset = b2Dot(normal, v11); + + // Side offsets, extended by polytope skin thickness. + float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; + float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); + + if (np < 2) + return; + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); + + if (np < 2) + { + return; + } + + // Now clipPoints2 contains the clipped points. + manifold->localNormal = localNormal; + manifold->localPoint = planePoint; + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; + + if (separation <= totalRadius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + cp->localPoint = b2MulT(xf2, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + if (flip) + { + // Swap features + b2ContactFeature cf = cp->id.cf; + cp->id.cf.indexA = cf.indexB; + cp->id.cf.indexB = cf.indexA; + cp->id.cf.typeA = cf.typeB; + cp->id.cf.typeB = cf.typeA; + } + ++pointCount; + } + } + + manifold->pointCount = pointCount; +} diff --git a/external/box2d/Collision/b2Collision.cpp b/external/box2d/Collision/b2Collision.cpp new file mode 100644 index 0000000000..2dd5ff0ab6 --- /dev/null +++ b/external/box2d/Collision/b2Collision.cpp @@ -0,0 +1,249 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +void b2WorldManifold::Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB) +{ + if (manifold->pointCount == 0) + { + return; + } + + switch (manifold->type) + { + case b2Manifold::e_circles: + { + normal.Set(1.0f, 0.0f); + b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); + b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } + + b2Vec2 cA = pointA + radiusA * normal; + b2Vec2 cB = pointB - radiusB * normal; + points[0] = 0.5f * (cA + cB); + } + break; + + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); + b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cB = clipPoint - radiusB * normal; + points[i] = 0.5f * (cA + cB); + } + } + break; + + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); + b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cA = clipPoint - radiusA * normal; + points[i] = 0.5f * (cA + cB); + } + + // Ensure normal points from A to B. + normal = -normal; + } + break; + } +} + +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2) +{ + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + state1[i] = b2_nullState; + state2[i] = b2_nullState; + } + + // Detect persists and removes. + for (int32 i = 0; i < manifold1->pointCount; ++i) + { + b2ContactID id = manifold1->points[i].id; + + state1[i] = b2_removeState; + + for (int32 j = 0; j < manifold2->pointCount; ++j) + { + if (manifold2->points[j].id.key == id.key) + { + state1[i] = b2_persistState; + break; + } + } + } + + // Detect persists and adds. + for (int32 i = 0; i < manifold2->pointCount; ++i) + { + b2ContactID id = manifold2->points[i].id; + + state2[i] = b2_addState; + + for (int32 j = 0; j < manifold1->pointCount; ++j) + { + if (manifold1->points[j].id.key == id.key) + { + state2[i] = b2_persistState; + break; + } + } + } +} + +// From Real-time Collision Detection, p179. +bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const +{ + float32 tmin = -b2_maxFloat; + float32 tmax = b2_maxFloat; + + b2Vec2 p = input.p1; + b2Vec2 d = input.p2 - input.p1; + b2Vec2 absD = b2Abs(d); + + b2Vec2 normal; + + for (int32 i = 0; i < 2; ++i) + { + if (absD(i) < b2_epsilon) + { + // Parallel. + if (p(i) < lowerBound(i) || upperBound(i) < p(i)) + { + return false; + } + } + else + { + float32 inv_d = 1.0f / d(i); + float32 t1 = (lowerBound(i) - p(i)) * inv_d; + float32 t2 = (upperBound(i) - p(i)) * inv_d; + + // Sign of the normal vector. + float32 s = -1.0f; + + if (t1 > t2) + { + b2Swap(t1, t2); + s = 1.0f; + } + + // Push the min up + if (t1 > tmin) + { + normal.SetZero(); + normal(i) = s; + tmin = t1; + } + + // Pull the max down + tmax = b2Min(tmax, t2); + + if (tmin > tmax) + { + return false; + } + } + } + + // Does the ray start inside the box? + // Does the ray intersect beyond the max fraction? + if (tmin < 0.0f || input.maxFraction < tmin) + { + return false; + } + + // Intersection. + output->fraction = tmin; + output->normal = normal; + return true; +} + +// Sutherland-Hodgman clipping. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset, int32 vertexIndexA) +{ + // Start with no output points + int32 numOut = 0; + + // Calculate the distance of end points to the line + float32 distance0 = b2Dot(normal, vIn[0].v) - offset; + float32 distance1 = b2Dot(normal, vIn[1].v) - offset; + + // If the points are behind the plane + if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; + if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; + + // If the points are on different sides of the plane + if (distance0 * distance1 < 0.0f) + { + // Find intersection point of edge and plane + float32 interp = distance0 / (distance0 - distance1); + vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); + + // VertexA is hitting edgeB. + vOut[numOut].id.cf.indexA = vertexIndexA; + vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; + vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; + vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; + ++numOut; + } + + return numOut; +} + +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB) +{ + b2DistanceInput input; + input.proxyA.Set(shapeA, indexA); + input.proxyB.Set(shapeB, indexB); + input.transformA = xfA; + input.transformB = xfB; + input.useRadii = true; + + b2SimplexCache cache; + cache.count = 0; + + b2DistanceOutput output; + + b2Distance(&output, &cache, &input); + + return output.distance < 10.0f * b2_epsilon; +} diff --git a/external/box2d/Collision/b2Collision.h b/external/box2d/Collision/b2Collision.h new file mode 100644 index 0000000000..2e7386232b --- /dev/null +++ b/external/box2d/Collision/b2Collision.h @@ -0,0 +1,276 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_COLLISION_H +#define B2_COLLISION_H + +#include +#include + +/// @file +/// Structures and functions used for computing contact points, distance +/// queries, and TOI queries. + +class b2Shape; +class b2CircleShape; +class b2EdgeShape; +class b2PolygonShape; + +const uint8 b2_nullFeature = UCHAR_MAX; + +/// The features that intersect to form the contact point +/// This must be 4 bytes or less. +struct b2ContactFeature +{ + enum Type + { + e_vertex = 0, + e_face = 1 + }; + + uint8 indexA; ///< Feature index on shapeA + uint8 indexB; ///< Feature index on shapeB + uint8 typeA; ///< The feature type on shapeA + uint8 typeB; ///< The feature type on shapeB +}; + +/// Contact ids to facilitate warm starting. +union b2ContactID +{ + b2ContactFeature cf; + uint32 key; ///< Used to quickly compare contact ids. +}; + +/// A manifold point is a contact point belonging to a contact +/// manifold. It holds details related to the geometry and dynamics +/// of the contact points. +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleB +/// -e_faceA: the local center of cirlceB or the clip point of polygonB +/// -e_faceB: the clip point of polygonA +/// This structure is stored across time steps, so we keep it small. +/// Note: the impulses are used for internal caching and may not +/// provide reliable contact forces, especially for high speed collisions. +struct b2ManifoldPoint +{ + b2Vec2 localPoint; ///< usage depends on manifold type + float32 normalImpulse; ///< the non-penetration impulse + float32 tangentImpulse; ///< the friction impulse + b2ContactID id; ///< uniquely identifies a contact point between two shapes +}; + +/// A manifold for two touching convex shapes. +/// Box2D supports multiple types of contact: +/// - clip point versus plane with radius +/// - point versus point with radius (circles) +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleA +/// -e_faceA: the center of faceA +/// -e_faceB: the center of faceB +/// Similarly the local normal usage: +/// -e_circles: not used +/// -e_faceA: the normal on polygonA +/// -e_faceB: the normal on polygonB +/// We store contacts in this way so that position correction can +/// account for movement, which is critical for continuous physics. +/// All contact scenarios must be expressed in one of these types. +/// This structure is stored across time steps, so we keep it small. +struct b2Manifold +{ + enum Type + { + e_circles, + e_faceA, + e_faceB + }; + + b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact + b2Vec2 localNormal; ///< not use for Type::e_points + b2Vec2 localPoint; ///< usage depends on manifold type + Type type; + int32 pointCount; ///< the number of manifold points +}; + +/// This is used to compute the current state of a contact manifold. +struct b2WorldManifold +{ + /// Evaluate the manifold with supplied transforms. This assumes + /// modest motion from the original state. This does not change the + /// point count, impulses, etc. The radii must come from the shapes + /// that generated the manifold. + void Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB); + + b2Vec2 normal; ///< world vector pointing from A to B + b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) +}; + +/// This is used for determining the state of contact points. +enum b2PointState +{ + b2_nullState, ///< point does not exist + b2_addState, ///< point was added in the update + b2_persistState, ///< point persisted across the update + b2_removeState ///< point was removed in the update +}; + +/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 +/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2); + +/// Used for computing contact manifolds. +struct b2ClipVertex +{ + b2Vec2 v; + b2ContactID id; +}; + +/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). +struct b2RayCastInput +{ + b2Vec2 p1, p2; + float32 maxFraction; +}; + +/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 +/// come from b2RayCastInput. +struct b2RayCastOutput +{ + b2Vec2 normal; + float32 fraction; +}; + +/// An axis aligned bounding box. +struct b2AABB +{ + /// Verify that the bounds are sorted. + bool IsValid() const; + + /// Get the center of the AABB. + b2Vec2 GetCenter() const + { + return 0.5f * (lowerBound + upperBound); + } + + /// Get the extents of the AABB (half-widths). + b2Vec2 GetExtents() const + { + return 0.5f * (upperBound - lowerBound); + } + + /// Get the perimeter length + float32 GetPerimeter() const + { + float32 wx = upperBound.x - lowerBound.x; + float32 wy = upperBound.y - lowerBound.y; + return 2.0f * (wx + wy); + } + + /// Combine an AABB into this one. + void Combine(const b2AABB& aabb) + { + lowerBound = b2Min(lowerBound, aabb.lowerBound); + upperBound = b2Max(upperBound, aabb.upperBound); + } + + /// Combine two AABBs into this one. + void Combine(const b2AABB& aabb1, const b2AABB& aabb2) + { + lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); + upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); + } + + /// Does this aabb contain the provided AABB. + bool Contains(const b2AABB& aabb) const + { + bool result = true; + result = result && lowerBound.x <= aabb.lowerBound.x; + result = result && lowerBound.y <= aabb.lowerBound.y; + result = result && aabb.upperBound.x <= upperBound.x; + result = result && aabb.upperBound.y <= upperBound.y; + return result; + } + + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + + b2Vec2 lowerBound; ///< the lower vertex + b2Vec2 upperBound; ///< the upper vertex +}; + +/// Compute the collision manifold between two circles. +void b2CollideCircles(b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between a polygon and a circle. +void b2CollidePolygonAndCircle(b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between two polygons. +void b2CollidePolygons(b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndPolygon(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* circleB, const b2Transform& xfB); + +/// Clipping for contact manifolds. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset, int32 vertexIndexA); + +/// Determine if two generic shapes overlap. +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB); + +// ---------------- Inline Functions ------------------------------------------ + +inline bool b2AABB::IsValid() const +{ + b2Vec2 d = upperBound - lowerBound; + bool valid = d.x >= 0.0f && d.y >= 0.0f; + valid = valid && lowerBound.IsValid() && upperBound.IsValid(); + return valid; +} + +inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) +{ + b2Vec2 d1, d2; + d1 = b.lowerBound - a.upperBound; + d2 = a.lowerBound - b.upperBound; + + if (d1.x > 0.0f || d1.y > 0.0f) + return false; + + if (d2.x > 0.0f || d2.y > 0.0f) + return false; + + return true; +} + +#endif diff --git a/external/box2d/Collision/b2Distance.cpp b/external/box2d/Collision/b2Distance.cpp new file mode 100644 index 0000000000..ac67d3be43 --- /dev/null +++ b/external/box2d/Collision/b2Distance.cpp @@ -0,0 +1,603 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. +int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + +void b2DistanceProxy::Set(const b2Shape* shape, int32 index) +{ + switch (shape->GetType()) + { + case b2Shape::e_circle: + { + const b2CircleShape* circle = (b2CircleShape*)shape; + m_vertices = &circle->m_p; + m_count = 1; + m_radius = circle->m_radius; + } + break; + + case b2Shape::e_polygon: + { + const b2PolygonShape* polygon = (b2PolygonShape*)shape; + m_vertices = polygon->m_vertices; + m_count = polygon->m_vertexCount; + m_radius = polygon->m_radius; + } + break; + + case b2Shape::e_chain: + { + const b2ChainShape* chain = (b2ChainShape*)shape; + b2Assert(0 <= index && index < chain->m_count); + + m_buffer[0] = chain->m_vertices[index]; + if (index + 1 < chain->m_count) + { + m_buffer[1] = chain->m_vertices[index + 1]; + } + else + { + m_buffer[1] = chain->m_vertices[0]; + } + + m_vertices = m_buffer; + m_count = 2; + m_radius = chain->m_radius; + } + break; + + case b2Shape::e_edge: + { + const b2EdgeShape* edge = (b2EdgeShape*)shape; + m_vertices = &edge->m_vertex1; + m_count = 2; + m_radius = edge->m_radius; + } + break; + + default: + b2Assert(false); + } +} + + +struct b2SimplexVertex +{ + b2Vec2 wA; // support point in proxyA + b2Vec2 wB; // support point in proxyB + b2Vec2 w; // wB - wA + float32 a; // barycentric coordinate for closest point + int32 indexA; // wA index + int32 indexB; // wB index +}; + +struct b2Simplex +{ + void ReadCache( const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Transform& transformA, + const b2DistanceProxy* proxyB, const b2Transform& transformB) + { + b2Assert(cache->count <= 3); + + // Copy data from cache. + m_count = cache->count; + b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + b2SimplexVertex* v = vertices + i; + v->indexA = cache->indexA[i]; + v->indexB = cache->indexB[i]; + b2Vec2 wALocal = proxyA->GetVertex(v->indexA); + b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + v->a = 0.0f; + } + + // Compute the new simplex metric, if it is substantially different than + // old metric then flush the simplex. + if (m_count > 1) + { + float32 metric1 = cache->metric; + float32 metric2 = GetMetric(); + if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) + { + // Reset the simplex. + m_count = 0; + } + } + + // If the cache is empty or invalid ... + if (m_count == 0) + { + b2SimplexVertex* v = vertices + 0; + v->indexA = 0; + v->indexB = 0; + b2Vec2 wALocal = proxyA->GetVertex(0); + b2Vec2 wBLocal = proxyB->GetVertex(0); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + m_count = 1; + } + } + + void WriteCache(b2SimplexCache* cache) const + { + cache->metric = GetMetric(); + cache->count = uint16(m_count); + const b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + cache->indexA[i] = uint8(vertices[i].indexA); + cache->indexB[i] = uint8(vertices[i].indexB); + } + } + + b2Vec2 GetSearchDirection() const + { + switch (m_count) + { + case 1: + return -m_v1.w; + + case 2: + { + b2Vec2 e12 = m_v2.w - m_v1.w; + float32 sgn = b2Cross(e12, -m_v1.w); + if (sgn > 0.0f) + { + // Origin is left of e12. + return b2Cross(1.0f, e12); + } + else + { + // Origin is right of e12. + return b2Cross(e12, 1.0f); + } + } + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + b2Vec2 GetClosestPoint() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return b2Vec2_zero; + + case 1: + return m_v1.w; + + case 2: + return m_v1.a * m_v1.w + m_v2.a * m_v2.w; + + case 3: + return b2Vec2_zero; + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const + { + switch (m_count) + { + case 0: + b2Assert(false); + break; + + case 1: + *pA = m_v1.wA; + *pB = m_v1.wB; + break; + + case 2: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; + *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; + break; + + case 3: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; + *pB = *pA; + break; + + default: + b2Assert(false); + break; + } + } + + float32 GetMetric() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return 0.0; + + case 1: + return 0.0f; + + case 2: + return b2Distance(m_v1.w, m_v2.w); + + case 3: + return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); + + default: + b2Assert(false); + return 0.0f; + } + } + + void Solve2(); + void Solve3(); + + b2SimplexVertex m_v1, m_v2, m_v3; + int32 m_count; +}; + + +// Solve a line segment using barycentric coordinates. +// +// p = a1 * w1 + a2 * w2 +// a1 + a2 = 1 +// +// The vector from the origin to the closest point on the line is +// perpendicular to the line. +// e12 = w2 - w1 +// dot(p, e) = 0 +// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 +// +// 2-by-2 linear system +// [1 1 ][a1] = [1] +// [w1.e12 w2.e12][a2] = [0] +// +// Define +// d12_1 = dot(w2, e12) +// d12_2 = -dot(w1, e12) +// d12 = d12_1 + d12_2 +// +// Solution +// a1 = d12_1 / d12 +// a2 = d12_2 / d12 +void b2Simplex::Solve2() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 e12 = w2 - w1; + + // w1 region + float32 d12_2 = -b2Dot(w1, e12); + if (d12_2 <= 0.0f) + { + // a2 <= 0, so we clamp it to 0 + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // w2 region + float32 d12_1 = b2Dot(w2, e12); + if (d12_1 <= 0.0f) + { + // a1 <= 0, so we clamp it to 0 + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // Must be in e12 region. + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; +} + +// Possible regions: +// - points[2] +// - edge points[0]-points[2] +// - edge points[1]-points[2] +// - inside the triangle +void b2Simplex::Solve3() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 w3 = m_v3.w; + + // Edge12 + // [1 1 ][a1] = [1] + // [w1.e12 w2.e12][a2] = [0] + // a3 = 0 + b2Vec2 e12 = w2 - w1; + float32 w1e12 = b2Dot(w1, e12); + float32 w2e12 = b2Dot(w2, e12); + float32 d12_1 = w2e12; + float32 d12_2 = -w1e12; + + // Edge13 + // [1 1 ][a1] = [1] + // [w1.e13 w3.e13][a3] = [0] + // a2 = 0 + b2Vec2 e13 = w3 - w1; + float32 w1e13 = b2Dot(w1, e13); + float32 w3e13 = b2Dot(w3, e13); + float32 d13_1 = w3e13; + float32 d13_2 = -w1e13; + + // Edge23 + // [1 1 ][a2] = [1] + // [w2.e23 w3.e23][a3] = [0] + // a1 = 0 + b2Vec2 e23 = w3 - w2; + float32 w2e23 = b2Dot(w2, e23); + float32 w3e23 = b2Dot(w3, e23); + float32 d23_1 = w3e23; + float32 d23_2 = -w2e23; + + // Triangle123 + float32 n123 = b2Cross(e12, e13); + + float32 d123_1 = n123 * b2Cross(w2, w3); + float32 d123_2 = n123 * b2Cross(w3, w1); + float32 d123_3 = n123 * b2Cross(w1, w2); + + // w1 region + if (d12_2 <= 0.0f && d13_2 <= 0.0f) + { + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // e12 + if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) + { + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; + return; + } + + // e13 + if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) + { + float32 inv_d13 = 1.0f / (d13_1 + d13_2); + m_v1.a = d13_1 * inv_d13; + m_v3.a = d13_2 * inv_d13; + m_count = 2; + m_v2 = m_v3; + return; + } + + // w2 region + if (d12_1 <= 0.0f && d23_2 <= 0.0f) + { + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // w3 region + if (d13_1 <= 0.0f && d23_1 <= 0.0f) + { + m_v3.a = 1.0f; + m_count = 1; + m_v1 = m_v3; + return; + } + + // e23 + if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) + { + float32 inv_d23 = 1.0f / (d23_1 + d23_2); + m_v2.a = d23_1 * inv_d23; + m_v3.a = d23_2 * inv_d23; + m_count = 2; + m_v1 = m_v3; + return; + } + + // Must be in triangle123 + float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); + m_v1.a = d123_1 * inv_d123; + m_v2.a = d123_2 * inv_d123; + m_v3.a = d123_3 * inv_d123; + m_count = 3; +} + +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input) +{ + ++b2_gjkCalls; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Transform transformA = input->transformA; + b2Transform transformB = input->transformB; + + // Initialize the simplex. + b2Simplex simplex; + simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); + + // Get simplex vertices as an array. + b2SimplexVertex* vertices = &simplex.m_v1; + const int32 k_maxIters = 20; + + // These store the vertices of the last simplex so that we + // can check for duplicates and prevent cycling. + int32 saveA[3], saveB[3]; + int32 saveCount = 0; + + b2Vec2 closestPoint = simplex.GetClosestPoint(); + float32 distanceSqr1 = closestPoint.LengthSquared(); + float32 distanceSqr2 = distanceSqr1; + + // Main iteration loop. + int32 iter = 0; + while (iter < k_maxIters) + { + // Copy simplex so we can identify duplicates. + saveCount = simplex.m_count; + for (int32 i = 0; i < saveCount; ++i) + { + saveA[i] = vertices[i].indexA; + saveB[i] = vertices[i].indexB; + } + + switch (simplex.m_count) + { + case 1: + break; + + case 2: + simplex.Solve2(); + break; + + case 3: + simplex.Solve3(); + break; + + default: + b2Assert(false); + } + + // If we have 3 points, then the origin is in the corresponding triangle. + if (simplex.m_count == 3) + { + break; + } + + // Compute closest point. + b2Vec2 p = simplex.GetClosestPoint(); + distanceSqr2 = p.LengthSquared(); + + // Ensure progress + if (distanceSqr2 >= distanceSqr1) + { + //break; + } + distanceSqr1 = distanceSqr2; + + // Get search direction. + b2Vec2 d = simplex.GetSearchDirection(); + + // Ensure the search direction is numerically fit. + if (d.LengthSquared() < b2_epsilon * b2_epsilon) + { + // The origin is probably contained by a line segment + // or triangle. Thus the shapes are overlapped. + + // We can't return zero here even though there may be overlap. + // In case the simplex is a point, segment, or triangle it is difficult + // to determine if the origin is contained in the CSO or very close to it. + break; + } + + // Compute a tentative new simplex vertex using support points. + b2SimplexVertex* vertex = vertices + simplex.m_count; + vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); + vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); + b2Vec2 wBLocal; + vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); + vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); + vertex->w = vertex->wB - vertex->wA; + + // Iteration count is equated to the number of support point calls. + ++iter; + ++b2_gjkIters; + + // Check for duplicate support points. This is the main termination criteria. + bool duplicate = false; + for (int32 i = 0; i < saveCount; ++i) + { + if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) + { + duplicate = true; + break; + } + } + + // If we found a duplicate support point we must exit to avoid cycling. + if (duplicate) + { + break; + } + + // New vertex is ok and needed. + ++simplex.m_count; + } + + b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); + + // Prepare output. + simplex.GetWitnessPoints(&output->pointA, &output->pointB); + output->distance = b2Distance(output->pointA, output->pointB); + output->iterations = iter; + + // Cache the simplex. + simplex.WriteCache(cache); + + // Apply radii if requested. + if (input->useRadii) + { + float32 rA = proxyA->m_radius; + float32 rB = proxyB->m_radius; + + if (output->distance > rA + rB && output->distance > b2_epsilon) + { + // Shapes are still no overlapped. + // Move the witness points to the outer surface. + output->distance -= rA + rB; + b2Vec2 normal = output->pointB - output->pointA; + normal.Normalize(); + output->pointA += rA * normal; + output->pointB -= rB * normal; + } + else + { + // Shapes are overlapped when radii are considered. + // Move the witness points to the middle. + b2Vec2 p = 0.5f * (output->pointA + output->pointB); + output->pointA = p; + output->pointB = p; + output->distance = 0.0f; + } + } +} diff --git a/external/box2d/Collision/b2Distance.h b/external/box2d/Collision/b2Distance.h new file mode 100644 index 0000000000..d598b7339d --- /dev/null +++ b/external/box2d/Collision/b2Distance.h @@ -0,0 +1,141 @@ + +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DISTANCE_H +#define B2_DISTANCE_H + +#include + +class b2Shape; + +/// A distance proxy is used by the GJK algorithm. +/// It encapsulates any shape. +struct b2DistanceProxy +{ + b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} + + /// Initialize the proxy using the given shape. The shape + /// must remain in scope while the proxy is in use. + void Set(const b2Shape* shape, int32 index); + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const; + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + b2Vec2 m_buffer[2]; + const b2Vec2* m_vertices; + int32 m_count; + float32 m_radius; +}; + +/// Used to warm start b2Distance. +/// Set count to zero on first call. +struct b2SimplexCache +{ + float32 metric; ///< length or area + uint16 count; + uint8 indexA[3]; ///< vertices on shape A + uint8 indexB[3]; ///< vertices on shape B +}; + +/// Input for b2Distance. +/// You have to option to use the shape radii +/// in the computation. Even +struct b2DistanceInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Transform transformA; + b2Transform transformB; + bool useRadii; +}; + +/// Output for b2Distance. +struct b2DistanceOutput +{ + b2Vec2 pointA; ///< closest point on shapeA + b2Vec2 pointB; ///< closest point on shapeB + float32 distance; + int32 iterations; ///< number of GJK iterations used +}; + +/// Compute the closest points between two shapes. Supports any combination of: +/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. +/// On the first call set b2SimplexCache.count to zero. +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input); + + +////////////////////////////////////////////////////////////////////////// + +inline int32 b2DistanceProxy::GetVertexCount() const +{ + return m_count; +} + +inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; +} + +inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return bestIndex; +} + +inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return m_vertices[bestIndex]; +} + +#endif diff --git a/external/box2d/Collision/b2DynamicTree.cpp b/external/box2d/Collision/b2DynamicTree.cpp new file mode 100644 index 0000000000..d1d53297e2 --- /dev/null +++ b/external/box2d/Collision/b2DynamicTree.cpp @@ -0,0 +1,775 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#ifndef SHP +#include +#else +#include +#endif +using namespace std; + + +b2DynamicTree::b2DynamicTree() +{ + m_root = b2_nullNode; + + m_nodeCapacity = 16; + m_nodeCount = 0; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); + + // Build a linked list for the free list. + for (int32 i = 0; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = 0; + + m_path = 0; + + m_insertionCount = 0; +} + +b2DynamicTree::~b2DynamicTree() +{ + // This frees the entire tree in one shot. + b2Free(m_nodes); +} + +// Allocate a node from the pool. Grow the pool if necessary. +int32 b2DynamicTree::AllocateNode() +{ + // Expand the node pool as needed. + if (m_freeList == b2_nullNode) + { + b2Assert(m_nodeCount == m_nodeCapacity); + + // The free list is empty. Rebuild a bigger pool. + b2TreeNode* oldNodes = m_nodes; + m_nodeCapacity *= 2; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); + b2Free(oldNodes); + + // Build a linked list for the free list. The parent + // pointer becomes the "next" pointer. + for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = m_nodeCount; + } + + // Peel a node off the free list. + int32 nodeId = m_freeList; + m_freeList = m_nodes[nodeId].next; + m_nodes[nodeId].parent = b2_nullNode; + m_nodes[nodeId].child1 = b2_nullNode; + m_nodes[nodeId].child2 = b2_nullNode; + m_nodes[nodeId].height = 0; + m_nodes[nodeId].userData = NULL; + ++m_nodeCount; + return nodeId; +} + +// Return a node to the pool. +void b2DynamicTree::FreeNode(int32 nodeId) +{ + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2Assert(0 < m_nodeCount); + m_nodes[nodeId].next = m_freeList; + m_nodes[nodeId].height = -1; + m_freeList = nodeId; + --m_nodeCount; +} + +// Create a proxy in the tree as a leaf node. We return the index +// of the node instead of a pointer so that we can grow +// the node pool. +int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = AllocateNode(); + + // Fatten the aabb. + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; + m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; + m_nodes[proxyId].userData = userData; + m_nodes[proxyId].height = 0; + + InsertLeaf(proxyId); + + return proxyId; +} + +void b2DynamicTree::DestroyProxy(int32 proxyId) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + b2Assert(m_nodes[proxyId].IsLeaf()); + + RemoveLeaf(proxyId); + FreeNode(proxyId); +} + +bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + + b2Assert(m_nodes[proxyId].IsLeaf()); + + if (m_nodes[proxyId].aabb.Contains(aabb)) + { + return false; + } + + RemoveLeaf(proxyId); + + // Extend AABB. + b2AABB b = aabb; + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + b.lowerBound = b.lowerBound - r; + b.upperBound = b.upperBound + r; + + // Predict AABB displacement. + b2Vec2 d = b2_aabbMultiplier * displacement; + + if (d.x < 0.0f) + { + b.lowerBound.x += d.x; + } + else + { + b.upperBound.x += d.x; + } + + if (d.y < 0.0f) + { + b.lowerBound.y += d.y; + } + else + { + b.upperBound.y += d.y; + } + + m_nodes[proxyId].aabb = b; + + InsertLeaf(proxyId); + return true; +} + +void b2DynamicTree::InsertLeaf(int32 leaf) +{ + ++m_insertionCount; + + if (m_root == b2_nullNode) + { + m_root = leaf; + m_nodes[m_root].parent = b2_nullNode; + return; + } + + // Find the best sibling for this node + b2AABB leafAABB = m_nodes[leaf].aabb; + int32 index = m_root; + while (m_nodes[index].IsLeaf() == false) + { + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + float32 area = m_nodes[index].aabb.GetPerimeter(); + + b2AABB combinedAABB; + combinedAABB.Combine(m_nodes[index].aabb, leafAABB); + float32 combinedArea = combinedAABB.GetPerimeter(); + + // Cost of creating a new parent for this node and the new leaf + float32 cost = 2.0f * combinedArea; + + // Minimum cost of pushing the leaf further down the tree + float32 inheritanceCost = 2.0f * (combinedArea - area); + + // Cost of descending into child1 + float32 cost1; + if (m_nodes[child1].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + cost1 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost1 = (newArea - oldArea) + inheritanceCost; + } + + // Cost of descending into child2 + float32 cost2; + if (m_nodes[child2].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + cost2 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost2 = newArea - oldArea + inheritanceCost; + } + + // Descend according to the minimum cost. + if (cost < cost1 && cost < cost2) + { + break; + } + + // Descend + if (cost1 < cost2) + { + index = child1; + } + else + { + index = child2; + } + } + + int32 sibling = index; + + // Create a new parent. + int32 oldParent = m_nodes[sibling].parent; + int32 newParent = AllocateNode(); + m_nodes[newParent].parent = oldParent; + m_nodes[newParent].userData = NULL; + m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); + m_nodes[newParent].height = m_nodes[sibling].height + 1; + + if (oldParent != b2_nullNode) + { + // The sibling was not the root. + if (m_nodes[oldParent].child1 == sibling) + { + m_nodes[oldParent].child1 = newParent; + } + else + { + m_nodes[oldParent].child2 = newParent; + } + + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + } + else + { + // The sibling was the root. + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + m_root = newParent; + } + + // Walk back up the tree fixing heights and AABBs + index = m_nodes[leaf].parent; + while (index != b2_nullNode) + { + index = Balance(index); + + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + b2Assert(child1 != b2_nullNode); + b2Assert(child2 != b2_nullNode); + + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + index = m_nodes[index].parent; + } + + //Validate(); +} + +void b2DynamicTree::RemoveLeaf(int32 leaf) +{ + if (leaf == m_root) + { + m_root = b2_nullNode; + return; + } + + int32 parent = m_nodes[leaf].parent; + int32 grandParent = m_nodes[parent].parent; + int32 sibling; + if (m_nodes[parent].child1 == leaf) + { + sibling = m_nodes[parent].child2; + } + else + { + sibling = m_nodes[parent].child1; + } + + if (grandParent != b2_nullNode) + { + // Destroy parent and connect sibling to grandParent. + if (m_nodes[grandParent].child1 == parent) + { + m_nodes[grandParent].child1 = sibling; + } + else + { + m_nodes[grandParent].child2 = sibling; + } + m_nodes[sibling].parent = grandParent; + FreeNode(parent); + + // Adjust ancestor bounds. + int32 index = grandParent; + while (index != b2_nullNode) + { + index = Balance(index); + + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + + index = m_nodes[index].parent; + } + } + else + { + m_root = sibling; + m_nodes[sibling].parent = b2_nullNode; + FreeNode(parent); + } + + //Validate(); +} + +// Perform a left or right rotation if node A is imbalanced. +// Returns the new root index. +int32 b2DynamicTree::Balance(int32 iA) +{ + b2Assert(iA != b2_nullNode); + + b2TreeNode* A = m_nodes + iA; + if (A->IsLeaf() || A->height < 2) + { + return iA; + } + + int32 iB = A->child1; + int32 iC = A->child2; + b2Assert(0 <= iB && iB < m_nodeCapacity); + b2Assert(0 <= iC && iC < m_nodeCapacity); + + b2TreeNode* B = m_nodes + iB; + b2TreeNode* C = m_nodes + iC; + + int32 balance = C->height - B->height; + + // Rotate C up + if (balance > 1) + { + int32 iF = C->child1; + int32 iG = C->child2; + b2TreeNode* F = m_nodes + iF; + b2TreeNode* G = m_nodes + iG; + b2Assert(0 <= iF && iF < m_nodeCapacity); + b2Assert(0 <= iG && iG < m_nodeCapacity); + + // Swap A and C + C->child1 = iA; + C->parent = A->parent; + A->parent = iC; + + // A's old parent should point to C + if (C->parent != b2_nullNode) + { + if (m_nodes[C->parent].child1 == iA) + { + m_nodes[C->parent].child1 = iC; + } + else + { + b2Assert(m_nodes[C->parent].child2 == iA); + m_nodes[C->parent].child2 = iC; + } + } + else + { + m_root = iC; + } + + // Rotate + if (F->height > G->height) + { + C->child2 = iF; + A->child2 = iG; + G->parent = iA; + A->aabb.Combine(B->aabb, G->aabb); + C->aabb.Combine(A->aabb, F->aabb); + + A->height = 1 + b2Max(B->height, G->height); + C->height = 1 + b2Max(A->height, F->height); + } + else + { + C->child2 = iG; + A->child2 = iF; + F->parent = iA; + A->aabb.Combine(B->aabb, F->aabb); + C->aabb.Combine(A->aabb, G->aabb); + + A->height = 1 + b2Max(B->height, F->height); + C->height = 1 + b2Max(A->height, G->height); + } + + return iC; + } + + // Rotate B up + if (balance < -1) + { + int32 iD = B->child1; + int32 iE = B->child2; + b2TreeNode* D = m_nodes + iD; + b2TreeNode* E = m_nodes + iE; + b2Assert(0 <= iD && iD < m_nodeCapacity); + b2Assert(0 <= iE && iE < m_nodeCapacity); + + // Swap A and B + B->child1 = iA; + B->parent = A->parent; + A->parent = iB; + + // A's old parent should point to B + if (B->parent != b2_nullNode) + { + if (m_nodes[B->parent].child1 == iA) + { + m_nodes[B->parent].child1 = iB; + } + else + { + b2Assert(m_nodes[B->parent].child2 == iA); + m_nodes[B->parent].child2 = iB; + } + } + else + { + m_root = iB; + } + + // Rotate + if (D->height > E->height) + { + B->child2 = iD; + A->child1 = iE; + E->parent = iA; + A->aabb.Combine(C->aabb, E->aabb); + B->aabb.Combine(A->aabb, D->aabb); + + A->height = 1 + b2Max(C->height, E->height); + B->height = 1 + b2Max(A->height, D->height); + } + else + { + B->child2 = iE; + A->child1 = iD; + D->parent = iA; + A->aabb.Combine(C->aabb, D->aabb); + B->aabb.Combine(A->aabb, E->aabb); + + A->height = 1 + b2Max(C->height, D->height); + B->height = 1 + b2Max(A->height, E->height); + } + + return iB; + } + + return iA; +} + +int32 b2DynamicTree::GetHeight() const +{ + if (m_root == b2_nullNode) + { + return 0; + } + + return m_nodes[m_root].height; +} + +// +float32 b2DynamicTree::GetAreaRatio() const +{ + if (m_root == b2_nullNode) + { + return 0.0f; + } + + const b2TreeNode* root = m_nodes + m_root; + float32 rootArea = root->aabb.GetPerimeter(); + + float32 totalArea = 0.0f; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height < 0) + { + // Free node in pool + continue; + } + + totalArea += node->aabb.GetPerimeter(); + } + + return totalArea / rootArea; +} + +// Compute the height of a sub-tree. +int32 b2DynamicTree::ComputeHeight(int32 nodeId) const +{ + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2TreeNode* node = m_nodes + nodeId; + + if (node->IsLeaf()) + { + return 0; + } + + int32 height1 = ComputeHeight(node->child1); + int32 height2 = ComputeHeight(node->child2); + return 1 + b2Max(height1, height2); +} + +int32 b2DynamicTree::ComputeHeight() const +{ + int32 height = ComputeHeight(m_root); + return height; +} + +void b2DynamicTree::ValidateStructure(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + if (index == m_root) + { + b2Assert(m_nodes[index].parent == b2_nullNode); + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + b2Assert(m_nodes[child1].parent == index); + b2Assert(m_nodes[child2].parent == index); + + ValidateStructure(child1); + ValidateStructure(child2); +} + +void b2DynamicTree::ValidateMetrics(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + int32 height1 = m_nodes[child1].height; + int32 height2 = m_nodes[child2].height; + int32 height; + height = 1 + b2Max(height1, height2); + b2Assert(node->height == height); + + b2AABB aabb; + aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + b2Assert(aabb.lowerBound == node->aabb.lowerBound); + b2Assert(aabb.upperBound == node->aabb.upperBound); + + ValidateMetrics(child1); + ValidateMetrics(child2); +} + +void b2DynamicTree::Validate() const +{ + ValidateStructure(m_root); + ValidateMetrics(m_root); + + int32 freeCount = 0; + int32 freeIndex = m_freeList; + while (freeIndex != b2_nullNode) + { + b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); + freeIndex = m_nodes[freeIndex].next; + ++freeCount; + } + + b2Assert(GetHeight() == ComputeHeight()); + + b2Assert(m_nodeCount + freeCount == m_nodeCapacity); +} + +int32 b2DynamicTree::GetMaxBalance() const +{ + int32 maxBalance = 0; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height <= 1) + { + continue; + } + + b2Assert(node->IsLeaf() == false); + + int32 child1 = node->child1; + int32 child2 = node->child2; + int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); + maxBalance = b2Max(maxBalance, balance); + } + + return maxBalance; +} + +void b2DynamicTree::RebuildBottomUp() +{ + int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); + int32 count = 0; + + // Build array of leaves. Free the rest. + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + if (m_nodes[i].height < 0) + { + // free node in pool + continue; + } + + if (m_nodes[i].IsLeaf()) + { + m_nodes[i].parent = b2_nullNode; + nodes[count] = i; + ++count; + } + else + { + FreeNode(i); + } + } + + while (count > 1) + { + float32 minCost = b2_maxFloat; + int32 iMin = -1, jMin = -1; + for (int32 i = 0; i < count; ++i) + { + b2AABB aabbi = m_nodes[nodes[i]].aabb; + + for (int32 j = i + 1; j < count; ++j) + { + b2AABB aabbj = m_nodes[nodes[j]].aabb; + b2AABB b; + b.Combine(aabbi, aabbj); + float32 cost = b.GetPerimeter(); + if (cost < minCost) + { + iMin = i; + jMin = j; + minCost = cost; + } + } + } + + int32 index1 = nodes[iMin]; + int32 index2 = nodes[jMin]; + b2TreeNode* child1 = m_nodes + index1; + b2TreeNode* child2 = m_nodes + index2; + + int32 parentIndex = AllocateNode(); + b2TreeNode* parent = m_nodes + parentIndex; + parent->child1 = index1; + parent->child2 = index2; + parent->height = 1 + b2Max(child1->height, child2->height); + parent->aabb.Combine(child1->aabb, child2->aabb); + parent->parent = b2_nullNode; + + child1->parent = parentIndex; + child2->parent = parentIndex; + + nodes[jMin] = nodes[count-1]; + nodes[iMin] = parentIndex; + --count; + } + + m_root = nodes[0]; + b2Free(nodes); + + Validate(); +} diff --git a/external/box2d/Collision/b2DynamicTree.h b/external/box2d/Collision/b2DynamicTree.h new file mode 100644 index 0000000000..33f16b0f32 --- /dev/null +++ b/external/box2d/Collision/b2DynamicTree.h @@ -0,0 +1,284 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DYNAMIC_TREE_H +#define B2_DYNAMIC_TREE_H + +#include +#include + +#define b2_nullNode (-1) + +/// A node in the dynamic tree. The client does not interact with this directly. +struct b2TreeNode +{ + bool IsLeaf() const + { + return child1 == b2_nullNode; + } + + /// Enlarged AABB + b2AABB aabb; + + void* userData; + + union + { + int32 parent; + int32 next; + }; + + int32 child1; + int32 child2; + + // leaf = 0, free node = -1 + int32 height; +}; + +/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. +/// A dynamic tree arranges data in a binary tree to accelerate +/// queries such as volume queries and ray casts. Leafs are proxies +/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor +/// so that the proxy AABB is bigger than the client object. This allows the client +/// object to move by small amounts without triggering a tree update. +/// +/// Nodes are pooled and relocatable, so we use node indices rather than pointers. +class b2DynamicTree +{ +public: + /// Constructing the tree initializes the node pool. + b2DynamicTree(); + + /// Destroy the tree, freeing the node pool. + ~b2DynamicTree(); + + /// Create a proxy. Provide a tight fitting AABB and a userData pointer. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. This asserts if the id is invalid. + void DestroyProxy(int32 proxyId); + + /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, + /// then the proxy is removed from the tree and re-inserted. Otherwise + /// the function returns immediately. + /// @return true if the proxy was re-inserted. + bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); + + /// Get proxy user data. + /// @return the proxy user data or 0 if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + + /// Validate this tree. For testing. + void Validate() const; + + /// Compute the height of the binary tree in O(N) time. Should not be + /// called often. + int32 GetHeight() const; + + /// Get the maximum balance of an node in the tree. The balance is the difference + /// in height of the two children of a node. + int32 GetMaxBalance() const; + + /// Get the ratio of the sum of the node areas to the root area. + float32 GetAreaRatio() const; + + /// Build an optimal tree. Very expensive. For testing. + void RebuildBottomUp(); + +private: + + int32 AllocateNode(); + void FreeNode(int32 node); + + void InsertLeaf(int32 node); + void RemoveLeaf(int32 node); + + int32 Balance(int32 index); + + int32 ComputeHeight() const; + int32 ComputeHeight(int32 nodeId) const; + + void ValidateStructure(int32 index) const; + void ValidateMetrics(int32 index) const; + + int32 m_root; + + b2TreeNode* m_nodes; + int32 m_nodeCount; + int32 m_nodeCapacity; + + int32 m_freeList; + + /// This is used to incrementally traverse the tree for re-balancing. + uint32 m_path; + + int32 m_insertionCount; +}; + +inline void* b2DynamicTree::GetUserData(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].userData; +} + +inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].aabb; +} + +template +inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const +{ + b2GrowableStack stack; + stack.Push(m_root); + + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } + + const b2TreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, aabb)) + { + if (node->IsLeaf()) + { + bool proceed = callback->QueryCallback(nodeId); + if (proceed == false) + { + return; + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } + } +} + +template +inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const +{ + b2Vec2 p1 = input.p1; + b2Vec2 p2 = input.p2; + b2Vec2 r = p2 - p1; + b2Assert(r.LengthSquared() > 0.0f); + r.Normalize(); + + // v is perpendicular to the segment. + b2Vec2 v = b2Cross(1.0f, r); + b2Vec2 abs_v = b2Abs(v); + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + + float32 maxFraction = input.maxFraction; + + // Build a bounding box for the segment. + b2AABB segmentAABB; + { + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + + b2GrowableStack stack; + stack.Push(m_root); + + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } + + const b2TreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, segmentAABB) == false) + { + continue; + } + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + b2Vec2 c = node->aabb.GetCenter(); + b2Vec2 h = node->aabb.GetExtents(); + float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); + if (separation > 0.0f) + { + continue; + } + + if (node->IsLeaf()) + { + b2RayCastInput subInput; + subInput.p1 = input.p1; + subInput.p2 = input.p2; + subInput.maxFraction = maxFraction; + + float32 value = callback->RayCastCallback(subInput, nodeId); + + if (value == 0.0f) + { + // The client has terminated the ray cast. + return; + } + + if (value > 0.0f) + { + // Update segment bounding box. + maxFraction = value; + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } +} + +#endif diff --git a/external/box2d/Collision/b2TimeOfImpact.cpp b/external/box2d/Collision/b2TimeOfImpact.cpp new file mode 100644 index 0000000000..1d643addd8 --- /dev/null +++ b/external/box2d/Collision/b2TimeOfImpact.cpp @@ -0,0 +1,488 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#ifdef SHP +#include +#else +#include +#endif + +using namespace std; + +int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; +int32 b2_toiRootIters, b2_toiMaxRootIters; + +struct b2SeparationFunction +{ + enum Type + { + e_points, + e_faceA, + e_faceB + }; + + // TODO_ERIN might not need to return the separation + + float32 Initialize(const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Sweep& sweepA, + const b2DistanceProxy* proxyB, const b2Sweep& sweepB, + float32 t1) + { + m_proxyA = proxyA; + m_proxyB = proxyB; + int32 count = cache->count; + b2Assert(0 < count && count < 3); + + m_sweepA = sweepA; + m_sweepB = sweepB; + + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t1); + m_sweepB.GetTransform(&xfB, t1); + + if (count == 1) + { + m_type = e_points; + b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + m_axis = pointB - pointA; + float32 s = m_axis.Normalize(); + return s; + } + else if (cache->indexA[0] == cache->indexA[1]) + { + // Two points on B and one on A. + m_type = e_faceB; + b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); + b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); + + m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfB.q, m_axis); + + m_localPoint = 0.5f * (localPointB1 + localPointB2); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 s = b2Dot(pointA - pointB, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + else + { + // Two points on A and one or two points on B. + m_type = e_faceA; + b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); + + m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfA.q, m_axis); + + m_localPoint = 0.5f * (localPointA1 + localPointA2); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 s = b2Dot(pointB - pointA, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + } + + float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + + *indexA = m_proxyA->GetSupport(axisA); + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, m_axis); + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.q, -normal); + + *indexA = -1; + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.q, -normal); + + *indexB = -1; + *indexA = m_proxyA->GetSupport(axisA); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + *indexA = -1; + *indexB = -1; + return 0.0f; + } + } + + float32 Evaluate(int32 indexA, int32 indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + float32 separation = b2Dot(pointB - pointA, m_axis); + + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.q, -normal); + + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.q, -normal); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + return 0.0f; + } + } + + const b2DistanceProxy* m_proxyA; + const b2DistanceProxy* m_proxyB; + b2Sweep m_sweepA, m_sweepB; + Type m_type; + b2Vec2 m_localPoint; + b2Vec2 m_axis; +}; + +// CCD via the local separating axis method. This seeks progression +// by computing the largest time at which separation is maintained. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) +{ + ++b2_toiCalls; + + output->state = b2TOIOutput::e_unknown; + output->t = input->tMax; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Sweep sweepA = input->sweepA; + b2Sweep sweepB = input->sweepB; + + // Large rotations can make the root finder fail, so we normalize the + // sweep angles. + sweepA.Normalize(); + sweepB.Normalize(); + + float32 tMax = input->tMax; + + float32 totalRadius = proxyA->m_radius + proxyB->m_radius; + float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); + float32 tolerance = 0.25f * b2_linearSlop; + b2Assert(target > tolerance); + + float32 t1 = 0.0f; + const int32 k_maxIterations = 20; // TODO_ERIN b2Settings + int32 iter = 0; + + // Prepare input for distance query. + b2SimplexCache cache; + cache.count = 0; + b2DistanceInput distanceInput; + distanceInput.proxyA = input->proxyA; + distanceInput.proxyB = input->proxyB; + distanceInput.useRadii = false; + + // The outer loop progressively attempts to compute new separating axes. + // This loop terminates when an axis is repeated (no progress is made). + for(;;) + { + b2Transform xfA, xfB; + sweepA.GetTransform(&xfA, t1); + sweepB.GetTransform(&xfB, t1); + + // Get the distance between shapes. We can also use the results + // to get a separating axis. + distanceInput.transformA = xfA; + distanceInput.transformB = xfB; + b2DistanceOutput distanceOutput; + b2Distance(&distanceOutput, &cache, &distanceInput); + + // If the shapes are overlapped, we give up on continuous collision. + if (distanceOutput.distance <= 0.0f) + { + // Failure! + output->state = b2TOIOutput::e_overlapped; + output->t = 0.0f; + break; + } + + if (distanceOutput.distance < target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_touching; + output->t = t1; + break; + } + + // Initialize the separating axis. + b2SeparationFunction fcn; + fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); +#if 0 + // Dump the curve seen by the root finder + { + const int32 N = 100; + float32 dx = 1.0f / N; + float32 xs[N+1]; + float32 fs[N+1]; + + float32 x = 0.0f; + + for (int32 i = 0; i <= N; ++i) + { + sweepA.GetTransform(&xfA, x); + sweepB.GetTransform(&xfB, x); + float32 f = fcn.Evaluate(xfA, xfB) - target; + + printf("%g %g\n", x, f); + + xs[i] = x; + fs[i] = f; + + x += dx; + } + } +#endif + + // Compute the TOI on the separating axis. We do this by successively + // resolving the deepest point. This loop is bounded by the number of vertices. + bool done = false; + float32 t2 = tMax; + int32 pushBackIter = 0; + for (;;) + { + // Find the deepest point at t2. Store the witness point indices. + int32 indexA, indexB; + float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); + + // Is the final configuration separated? + if (s2 > target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_separated; + output->t = tMax; + done = true; + break; + } + + // Has the separation reached tolerance? + if (s2 > target - tolerance) + { + // Advance the sweeps + t1 = t2; + break; + } + + // Compute the initial separation of the witness points. + float32 s1 = fcn.Evaluate(indexA, indexB, t1); + + // Check for initial overlap. This might happen if the root finder + // runs out of iterations. + if (s1 < target - tolerance) + { + output->state = b2TOIOutput::e_failed; + output->t = t1; + done = true; + break; + } + + // Check for touching + if (s1 <= target + tolerance) + { + // Victory! t1 should hold the TOI (could be 0.0). + output->state = b2TOIOutput::e_touching; + output->t = t1; + done = true; + break; + } + + // Compute 1D root of: f(x) - target = 0 + int32 rootIterCount = 0; + float32 a1 = t1, a2 = t2; + for (;;) + { + // Use a mix of the secant rule and bisection. + float32 t; + if (rootIterCount & 1) + { + // Secant rule to improve convergence. + t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); + } + else + { + // Bisection to guarantee progress. + t = 0.5f * (a1 + a2); + } + + float32 s = fcn.Evaluate(indexA, indexB, t); + + if (b2Abs(s - target) < tolerance) + { + // t2 holds a tentative value for t1 + t2 = t; + break; + } + + // Ensure we continue to bracket the root. + if (s > target) + { + a1 = t; + s1 = s; + } + else + { + a2 = t; + s2 = s; + } + + ++rootIterCount; + ++b2_toiRootIters; + + if (rootIterCount == 50) + { + break; + } + } + + b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); + + ++pushBackIter; + + if (pushBackIter == b2_maxPolygonVertices) + { + break; + } + } + + ++iter; + ++b2_toiIters; + + if (done) + { + break; + } + + if (iter == k_maxIterations) + { + // Root finder got stuck. Semi-victory. + output->state = b2TOIOutput::e_failed; + output->t = t1; + break; + } + } + + b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); +} diff --git a/external/box2d/Collision/b2TimeOfImpact.h b/external/box2d/Collision/b2TimeOfImpact.h new file mode 100644 index 0000000000..2e4f8228ff --- /dev/null +++ b/external/box2d/Collision/b2TimeOfImpact.h @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TIME_OF_IMPACT_H +#define B2_TIME_OF_IMPACT_H + +#include +#include + +/// Input parameters for b2TimeOfImpact +struct b2TOIInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Sweep sweepA; + b2Sweep sweepB; + float32 tMax; // defines sweep interval [0, tMax] +}; + +// Output parameters for b2TimeOfImpact. +struct b2TOIOutput +{ + enum State + { + e_unknown, + e_failed, + e_overlapped, + e_touching, + e_separated + }; + + State state; + float32 t; +}; + +/// Compute the upper bound on time before two shapes penetrate. Time is represented as +/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, +/// non-tunneling collision. If you change the time interval, you should call this function +/// again. +/// Note: use b2Distance to compute the contact point and normal at the time of impact. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); + +#endif diff --git a/external/box2d/Common/b2BlockAllocator.cpp b/external/box2d/Common/b2BlockAllocator.cpp new file mode 100644 index 0000000000..2e862091f9 --- /dev/null +++ b/external/box2d/Common/b2BlockAllocator.cpp @@ -0,0 +1,218 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +using namespace std; + +int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = +{ + 16, // 0 + 32, // 1 + 64, // 2 + 96, // 3 + 128, // 4 + 160, // 5 + 192, // 6 + 224, // 7 + 256, // 8 + 320, // 9 + 384, // 10 + 448, // 11 + 512, // 12 + 640, // 13 +}; +uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; +bool b2BlockAllocator::s_blockSizeLookupInitialized; + +struct b2Chunk +{ + int32 blockSize; + b2Block* blocks; +}; + +struct b2Block +{ + b2Block* next; +}; + +b2BlockAllocator::b2BlockAllocator() +{ + b2Assert(b2_blockSizes < UCHAR_MAX); + + m_chunkSpace = b2_chunkArrayIncrement; + m_chunkCount = 0; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + memset(m_freeLists, 0, sizeof(m_freeLists)); + + if (s_blockSizeLookupInitialized == false) + { + int32 j = 0; + for (int32 i = 1; i <= b2_maxBlockSize; ++i) + { + b2Assert(j < b2_blockSizes); + if (i <= s_blockSizes[j]) + { + s_blockSizeLookup[i] = (uint8)j; + } + else + { + ++j; + s_blockSizeLookup[i] = (uint8)j; + } + } + + s_blockSizeLookupInitialized = true; + } +} + +b2BlockAllocator::~b2BlockAllocator() +{ + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } + + b2Free(m_chunks); +} + +void* b2BlockAllocator::Allocate(int32 size) +{ + if (size == 0) + return NULL; + + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + return b2Alloc(size); + } + + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); + + if (m_freeLists[index]) + { + b2Block* block = m_freeLists[index]; + m_freeLists[index] = block->next; + return block; + } + else + { + if (m_chunkCount == m_chunkSpace) + { + b2Chunk* oldChunks = m_chunks; + m_chunkSpace += b2_chunkArrayIncrement; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); + memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); + b2Free(oldChunks); + } + + b2Chunk* chunk = m_chunks + m_chunkCount; + chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); +#if defined(_DEBUG) + memset(chunk->blocks, 0xcd, b2_chunkSize); +#endif + int32 blockSize = s_blockSizes[index]; + chunk->blockSize = blockSize; + int32 blockCount = b2_chunkSize / blockSize; + b2Assert(blockCount * blockSize <= b2_chunkSize); + for (int32 i = 0; i < blockCount - 1; ++i) + { + b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); + b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); + block->next = next; + } + b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); + last->next = NULL; + + m_freeLists[index] = chunk->blocks->next; + ++m_chunkCount; + + return chunk->blocks; + } +} + +void b2BlockAllocator::Free(void* p, int32 size) +{ + if (size == 0) + { + return; + } + + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + b2Free(p); + return; + } + + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); + +#ifdef _DEBUG + // Verify the memory address and size is valid. + int32 blockSize = s_blockSizes[index]; + bool found = false; + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Chunk* chunk = m_chunks + i; + if (chunk->blockSize != blockSize) + { + b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || + (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); + } + else + { + if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) + { + found = true; + } + } + } + + b2Assert(found); + + memset(p, 0xfd, blockSize); +#endif + + b2Block* block = (b2Block*)p; + block->next = m_freeLists[index]; + m_freeLists[index] = block; +} + +void b2BlockAllocator::Clear() +{ + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } + + m_chunkCount = 0; + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + + memset(m_freeLists, 0, sizeof(m_freeLists)); +} diff --git a/external/box2d/Common/b2BlockAllocator.h b/external/box2d/Common/b2BlockAllocator.h new file mode 100644 index 0000000000..ec221fdf61 --- /dev/null +++ b/external/box2d/Common/b2BlockAllocator.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BLOCK_ALLOCATOR_H +#define B2_BLOCK_ALLOCATOR_H + +#include + +const int32 b2_chunkSize = 16 * 1024; +const int32 b2_maxBlockSize = 640; +const int32 b2_blockSizes = 14; +const int32 b2_chunkArrayIncrement = 128; + +struct b2Block; +struct b2Chunk; + +/// This is a small object allocator used for allocating small +/// objects that persist for more than one time step. +/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp +class b2BlockAllocator +{ +public: + b2BlockAllocator(); + ~b2BlockAllocator(); + + /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. + void* Allocate(int32 size); + + /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. + void Free(void* p, int32 size); + + void Clear(); + +private: + + b2Chunk* m_chunks; + int32 m_chunkCount; + int32 m_chunkSpace; + + b2Block* m_freeLists[b2_blockSizes]; + + static int32 s_blockSizes[b2_blockSizes]; + static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; + static bool s_blockSizeLookupInitialized; +}; + +#endif diff --git a/external/box2d/Common/b2Draw.cpp b/external/box2d/Common/b2Draw.cpp new file mode 100644 index 0000000000..cb760025e9 --- /dev/null +++ b/external/box2d/Common/b2Draw.cpp @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +b2Draw::b2Draw() +{ + m_drawFlags = 0; +} + +void b2Draw::SetFlags(uint32 flags) +{ + m_drawFlags = flags; +} + +uint32 b2Draw::GetFlags() const +{ + return m_drawFlags; +} + +void b2Draw::AppendFlags(uint32 flags) +{ + m_drawFlags |= flags; +} + +void b2Draw::ClearFlags(uint32 flags) +{ + m_drawFlags &= ~flags; +} diff --git a/external/box2d/Common/b2Draw.h b/external/box2d/Common/b2Draw.h new file mode 100644 index 0000000000..b33cd8d38f --- /dev/null +++ b/external/box2d/Common/b2Draw.h @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +/// Color for debug drawing. Each value has the range [0,1]. +struct b2Color +{ + b2Color() {} + b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} + void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } + float32 r, g, b; +}; + +/// Implement and register this class with a b2World to provide debug drawing of physics +/// entities in your game. +class b2Draw +{ +public: + b2Draw(); + + virtual ~b2Draw() {} + + enum + { + e_shapeBit = 0x0001, ///< draw shapes + e_jointBit = 0x0002, ///< draw joint connections + e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes + e_pairBit = 0x0008, ///< draw broad-phase pairs + e_centerOfMassBit = 0x0010 ///< draw center of mass frame + }; + + /// Set the drawing flags. + void SetFlags(uint32 flags); + + /// Get the drawing flags. + uint32 GetFlags() const; + + /// Append flags to the current flags. + void AppendFlags(uint32 flags); + + /// Clear flags from the current flags. + void ClearFlags(uint32 flags); + + /// Draw a closed polygon provided in CCW order. + virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a solid closed polygon provided in CCW order. + virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a circle. + virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; + + /// Draw a solid circle. + virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; + + /// Draw a line segment. + virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; + + /// Draw a transform. Choose your own length scale. + /// @param xf a transform. + virtual void DrawTransform(const b2Transform& xf) = 0; + +protected: + uint32 m_drawFlags; +}; diff --git a/external/box2d/Common/b2GrowableStack.h b/external/box2d/Common/b2GrowableStack.h new file mode 100644 index 0000000000..68809521f4 --- /dev/null +++ b/external/box2d/Common/b2GrowableStack.h @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_GROWABLE_STACK_H +#define B2_GROWABLE_STACK_H +#include +#include + +/// This is a growable LIFO stack with an initial capacity of N. +/// If the stack size exceeds the initial capacity, the heap is used +/// to increase the size of the stack. +template +class b2GrowableStack +{ +public: + b2GrowableStack() + { + m_stack = m_array; + m_count = 0; + m_capacity = N; + } + + ~b2GrowableStack() + { + if (m_stack != m_array) + { + b2Free(m_stack); + m_stack = NULL; + } + } + + void Push(const T& element) + { + if (m_count == m_capacity) + { + T* old = m_stack; + m_capacity *= 2; + m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); + std::memcpy(m_stack, old, m_count * sizeof(T)); + if (old != m_array) + { + b2Free(old); + } + } + + m_stack[m_count] = element; + ++m_count; + } + + T Pop() + { + b2Assert(m_count > 0); + --m_count; + return m_stack[m_count]; + } + + int32 GetCount() + { + return m_count; + } + +private: + T* m_stack; + T m_array[N]; + int32 m_count; + int32 m_capacity; +}; + + +#endif diff --git a/external/box2d/Common/b2Math.cpp b/external/box2d/Common/b2Math.cpp new file mode 100644 index 0000000000..15d68fce96 --- /dev/null +++ b/external/box2d/Common/b2Math.cpp @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +const b2Vec2 b2Vec2_zero(0.0f, 0.0f); + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const +{ + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec3 x; + x.x = det * b2Dot(b, b2Cross(ey, ez)); + x.y = det * b2Dot(ex, b2Cross(b, ez)); + x.z = det * b2Dot(ex, b2Cross(ey, b)); + return x; +} + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const +{ + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; +} + +/// +void b2Mat33::GetInverse22(b2Mat33* M) const +{ + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + + M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; + M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; + M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; +} + +/// Returns the zero matrix if singular. +void b2Mat33::GetSymInverse33(b2Mat33* M) const +{ + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + + float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; + float32 a22 = ey.y, a23 = ez.y; + float32 a33 = ez.z; + + M->ex.x = det * (a22 * a33 - a23 * a23); + M->ex.y = det * (a13 * a23 - a12 * a33); + M->ex.z = det * (a12 * a23 - a13 * a22); + + M->ey.x = M->ex.y; + M->ey.y = det * (a11 * a33 - a13 * a13); + M->ey.z = det * (a13 * a12 - a11 * a23); + + M->ez.x = M->ex.z; + M->ez.y = M->ey.z; + M->ez.z = det * (a11 * a22 - a12 * a12); +} diff --git a/external/box2d/Common/b2Math.h b/external/box2d/Common/b2Math.h new file mode 100644 index 0000000000..a6be671139 --- /dev/null +++ b/external/box2d/Common/b2Math.h @@ -0,0 +1,738 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_MATH_H +#define B2_MATH_H + +#include + +#include +#ifndef SHP +#include +#else +#include +#endif +#include +#include + +using namespace std; + + +/// This function is used to ensure that a floating point number is +/// not a NaN or infinity. +inline bool b2IsValid(float32 x) +{ + if (x != x) + { + // NaN. + return false; + } + + float32 infinity = std::numeric_limits::infinity(); + return -infinity < x && x < infinity; +} + +/// This is a approximate yet fast inverse square-root. +inline float32 b2InvSqrt(float32 x) +{ + union + { + float32 x; + int32 i; + } convert; + + convert.x = x; + float32 xhalf = 0.5f * x; + convert.i = 0x5f3759df - (convert.i >> 1); + x = convert.x; + x = x * (1.5f - xhalf * x * x); + return x; +} + +#define b2Sqrt(x) std::sqrt(x) +#define b2Atan2(y, x) std::atan2(y, x) + +/// A 2D column vector. +struct b2Vec2 +{ + /// Default constructor does nothing (for performance). + b2Vec2() {} + + /// Construct using coordinates. + b2Vec2(float32 x, float32 y) : x(x), y(y) {} + + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; } + + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_) { x = x_; y = y_; } + + /// Negate this vector. + b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } + + /// Read from and indexed element. + float32 operator () (int32 i) const + { + return (&x)[i]; + } + + /// Write to an indexed element. + float32& operator () (int32 i) + { + return (&x)[i]; + } + + /// Add a vector to this vector. + void operator += (const b2Vec2& v) + { + x += v.x; y += v.y; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec2& v) + { + x -= v.x; y -= v.y; + } + + /// Multiply this vector by a scalar. + void operator *= (float32 a) + { + x *= a; y *= a; + } + + /// Get the length of this vector (the norm). + float32 Length() const + { + return b2Sqrt(x * x + y * y); + } + + /// Get the length squared. For performance, use this instead of + /// b2Vec2::Length (if possible). + float32 LengthSquared() const + { + return x * x + y * y; + } + + /// Convert this vector into a unit vector. Returns the length. + float32 Normalize() + { + float32 length = Length(); + if (length < b2_epsilon) + { + return 0.0f; + } + float32 invLength = 1.0f / length; + x *= invLength; + y *= invLength; + + return length; + } + + /// Does this vector contain finite coordinates? + bool IsValid() const + { + return b2IsValid(x) && b2IsValid(y); + } + + /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + b2Vec2 Skew() const + { + return b2Vec2(-y, x); + } + + float32 x, y; +}; + +/// A 2D column vector with 3 elements. +struct b2Vec3 +{ + /// Default constructor does nothing (for performance). + b2Vec3() {} + + /// Construct using coordinates. + b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} + + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } + + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } + + /// Negate this vector. + b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } + + /// Add a vector to this vector. + void operator += (const b2Vec3& v) + { + x += v.x; y += v.y; z += v.z; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec3& v) + { + x -= v.x; y -= v.y; z -= v.z; + } + + /// Multiply this vector by a scalar. + void operator *= (float32 s) + { + x *= s; y *= s; z *= s; + } + + float32 x, y, z; +}; + +/// A 2-by-2 matrix. Stored in column-major order. +struct b2Mat22 +{ + /// The default constructor does nothing (for performance). + b2Mat22() {} + + /// Construct this matrix using columns. + b2Mat22(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } + + /// Construct this matrix using scalars. + b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) + { + ex.x = a11; ex.y = a21; + ey.x = a12; ey.y = a22; + } + + /// Initialize this matrix using columns. + void Set(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } + + /// Set this to the identity matrix. + void SetIdentity() + { + ex.x = 1.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 1.0f; + } + + /// Set this matrix to all zeros. + void SetZero() + { + ex.x = 0.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 0.0f; + } + + b2Mat22 GetInverse() const + { + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + b2Mat22 B; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + B.ex.x = det * d; B.ey.x = -det * b; + B.ex.y = -det * c; B.ey.y = det * a; + return B; + } + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec2 Solve(const b2Vec2& b) const + { + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; + } + + b2Vec2 ex, ey; +}; + +/// A 3-by-3 matrix. Stored in column-major order. +struct b2Mat33 +{ + /// The default constructor does nothing (for performance). + b2Mat33() {} + + /// Construct this matrix using columns. + b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) + { + ex = c1; + ey = c2; + ez = c3; + } + + /// Set this matrix to all zeros. + void SetZero() + { + ex.SetZero(); + ey.SetZero(); + ez.SetZero(); + } + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec3 Solve33(const b2Vec3& b) const; + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. Solve only the upper + /// 2-by-2 matrix equation. + b2Vec2 Solve22(const b2Vec2& b) const; + + /// Get the inverse of this matrix as a 2-by-2. + /// Returns the zero matrix if singular. + void GetInverse22(b2Mat33* M) const; + + /// Get the symmetric inverse of this matrix as a 3-by-3. + /// Returns the zero matrix if singular. + void GetSymInverse33(b2Mat33* M) const; + + b2Vec3 ex, ey, ez; +}; + +/// Rotation +struct b2Rot +{ + b2Rot() {} + + /// Initialize from an angle in radians + explicit b2Rot(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set using an angle in radians. + void Set(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set to the identity rotation + void SetIdentity() + { + s = 0.0f; + c = 1.0f; + } + + /// Get the angle in radians + float32 GetAngle() const + { + return b2Atan2(s, c); + } + + /// Get the x-axis + b2Vec2 GetXAxis() const + { + return b2Vec2(c, s); + } + + /// Get the u-axis + b2Vec2 GetYAxis() const + { + return b2Vec2(-s, c); + } + + /// Sine and cosine + float32 s, c; +}; + +/// A transform contains translation and rotation. It is used to represent +/// the position and orientation of rigid frames. +struct b2Transform +{ + /// The default constructor does nothing. + b2Transform() {} + + /// Initialize using a position vector and a rotation. + b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} + + /// Set this to the identity transform. + void SetIdentity() + { + p.SetZero(); + q.SetIdentity(); + } + + /// Set this based on the position and angle. + void Set(const b2Vec2& position, float32 angle) + { + p = position; + q.Set(angle); + } + + b2Vec2 p; + b2Rot q; +}; + +/// This describes the motion of a body/shape for TOI computation. +/// Shapes are defined with respect to the body origin, which may +/// no coincide with the center of mass. However, to support dynamics +/// we must interpolate the center of mass position. +struct b2Sweep +{ + /// Get the interpolated transform at a specific time. + /// @param beta is a factor in [0,1], where 0 indicates alpha0. + void GetTransform(b2Transform* xfb, float32 beta) const; + + /// Advance the sweep forward, yielding a new initial state. + /// @param alpha the new initial time. + void Advance(float32 alpha); + + /// Normalize the angles. + void Normalize(); + + b2Vec2 localCenter; ///< local center of mass position + b2Vec2 c0, c; ///< center world positions + float32 a0, a; ///< world angles + + /// Fraction of the current time step in the range [0,1] + /// c0 and a0 are the positions at alpha0. + float32 alpha0; +}; + +/// Useful constant +extern const b2Vec2 b2Vec2_zero; + +/// Perform the dot product on two vectors. +inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) +{ + return a.x * b.x + a.y * b.y; +} + +/// Perform the cross product on two vectors. In 2D this produces a scalar. +inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) +{ + return a.x * b.y - a.y * b.x; +} + +/// Perform the cross product on a vector and a scalar. In 2D this produces +/// a vector. +inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) +{ + return b2Vec2(s * a.y, -s * a.x); +} + +/// Perform the cross product on a scalar and a vector. In 2D this produces +/// a vector. +inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) +{ + return b2Vec2(-s * a.y, s * a.x); +} + +/// Multiply a matrix times a vector. If a rotation matrix is provided, +/// then this transforms the vector from one frame to another. +inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) +{ + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); +} + +/// Multiply a matrix transpose times a vector. If a rotation matrix is provided, +/// then this transforms the vector from one frame to another (inverse transform). +inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) +{ + return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); +} + +/// Add two vectors component-wise. +inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(a.x + b.x, a.y + b.y); +} + +/// Subtract two vectors component-wise. +inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(a.x - b.x, a.y - b.y); +} + +inline b2Vec2 operator * (float32 s, const b2Vec2& a) +{ + return b2Vec2(s * a.x, s * a.y); +} + +inline bool operator == (const b2Vec2& a, const b2Vec2& b) +{ + return a.x == b.x && a.y == b.y; +} + +inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) +{ + b2Vec2 c = a - b; + return c.Length(); +} + +inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) +{ + b2Vec2 c = a - b; + return b2Dot(c, c); +} + +inline b2Vec3 operator * (float32 s, const b2Vec3& a) +{ + return b2Vec3(s * a.x, s * a.y, s * a.z); +} + +/// Add two vectors component-wise. +inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); +} + +/// Subtract two vectors component-wise. +inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); +} + +/// Perform the dot product on two vectors. +inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +/// Perform the cross product on two vectors. +inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); +} + +inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) +{ + return b2Mat22(A.ex + B.ex, A.ey + B.ey); +} + +// A * B +inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) +{ + return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); +} + +// A^T * B +inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) +{ + b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); + b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); + return b2Mat22(c1, c2); +} + +/// Multiply a matrix times a vector. +inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) +{ + return v.x * A.ex + v.y * A.ey + v.z * A.ez; +} + +/// Multiply a matrix times a vector. +inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) +{ + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); +} + +/// Multiply two rotations: q * r +inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) +{ + // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] + // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] + // s = qs * rc + qc * rs + // c = qc * rc - qs * rs + b2Rot qr; + qr.s = q.s * r.c + q.c * r.s; + qr.c = q.c * r.c - q.s * r.s; + return qr; +} + +/// Transpose multiply two rotations: qT * r +inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) +{ + // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] + // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] + // s = qc * rs - qs * rc + // c = qc * rc + qs * rs + b2Rot qr; + qr.s = q.c * r.s - q.s * r.c; + qr.c = q.c * r.c + q.s * r.s; + return qr; +} + +/// Rotate a vector +inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); +} + +/// Inverse rotate a vector +inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); +} + +inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) +{ + float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; + float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; + + return b2Vec2(x, y); +} + +inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) +{ + float32 px = v.x - T.p.x; + float32 py = v.y - T.p.y; + float32 x = (T.q.c * px + T.q.s * py); + float32 y = (-T.q.s * px + T.q.c * py); + + return b2Vec2(x, y); +} + +// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p +// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p +inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2Mul(A.q, B.q); + C.p = b2Mul(A.q, B.p) + A.p; + return C; +} + +// v2 = A.q' * (B.q * v1 + B.p - A.p) +// = A.q' * B.q * v1 + A.q' * (B.p - A.p) +inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2MulT(A.q, B.q); + C.p = b2MulT(A.q, B.p - A.p); + return C; +} + +template +inline T b2Abs(T a) +{ + return a > T(0) ? a : -a; +} + +inline b2Vec2 b2Abs(const b2Vec2& a) +{ + return b2Vec2(b2Abs(a.x), b2Abs(a.y)); +} + +inline b2Mat22 b2Abs(const b2Mat22& A) +{ + return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); +} + +template +inline T b2Min(T a, T b) +{ + return a < b ? a : b; +} + +inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); +} + +template +inline T b2Max(T a, T b) +{ + return a > b ? a : b; +} + +inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); +} + +template +inline T b2Clamp(T a, T low, T high) +{ + return b2Max(low, b2Min(a, high)); +} + +inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) +{ + return b2Max(low, b2Min(a, high)); +} + +template inline void b2Swap(T& a, T& b) +{ + T tmp = a; + a = b; + b = tmp; +} + +/// "Next Largest Power of 2 +/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm +/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with +/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next +/// largest power of 2. For a 32-bit value:" +inline uint32 b2NextPowerOfTwo(uint32 x) +{ + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x + 1; +} + +inline bool b2IsPowerOfTwo(uint32 x) +{ + bool result = x > 0 && (x & (x - 1)) == 0; + return result; +} + +inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const +{ + xf->p = (1.0f - beta) * c0 + beta * c; + float32 angle = (1.0f - beta) * a0 + beta * a; + xf->q.Set(angle); + + // Shift to origin + xf->p -= b2Mul(xf->q, localCenter); +} + +inline void b2Sweep::Advance(float32 alpha) +{ + b2Assert(alpha0 < 1.0f); + float32 beta = (alpha - alpha0) / (1.0f - alpha0); + c0 = (1.0f - beta) * c0 + beta * c; + a0 = (1.0f - beta) * a0 + beta * a; + alpha0 = alpha; +} + +/// Normalize an angle in radians to be between -pi and pi +inline void b2Sweep::Normalize() +{ + float32 twoPi = 2.0f * b2_pi; + float32 d = twoPi * floorf(a0 / twoPi); + a0 -= d; + a -= d; +} + +#endif diff --git a/external/box2d/Common/b2Settings.cpp b/external/box2d/Common/b2Settings.cpp new file mode 100644 index 0000000000..84d6f1d0e4 --- /dev/null +++ b/external/box2d/Common/b2Settings.cpp @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#ifdef SHP +#include +#include +#include +#include +#else +#include +#include +#include +#endif + + +using namespace std; + + +b2Version b2_version = {2, 2, 1}; + +// Memory allocators. Modify these to use your own allocator. +void* b2Alloc(int32 size) +{ + return malloc(size); +} + +void b2Free(void* mem) +{ + free(mem); +} + +// You can modify this to use your logging facility. +void b2Log(const char* string, ...) +{ +#if defined(SHP) + #ifdef _DEBUG + __App_info(__PRETTY_FUNCTION__ , __LINE__, string); + #endif +#else + va_list args; + va_start(args, string); + vprintf(string, args); + va_end(args); +#endif +} diff --git a/external/box2d/Common/b2Settings.h b/external/box2d/Common/b2Settings.h new file mode 100644 index 0000000000..aaf4b12ccf --- /dev/null +++ b/external/box2d/Common/b2Settings.h @@ -0,0 +1,150 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_SETTINGS_H +#define B2_SETTINGS_H + +#include +#include + +#define B2_NOT_USED(x) ((void)(x)) +#define b2Assert(A) assert(A) + +typedef signed char int8; +typedef signed short int16; +typedef signed int int32; +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint32; +typedef float float32; +typedef double float64; + +#define b2_maxFloat FLT_MAX +#define b2_epsilon FLT_EPSILON +#define b2_pi 3.14159265359f + +/// @file +/// Global tuning constants based on meters-kilograms-seconds (MKS) units. +/// + +// Collision + +/// The maximum number of contact points between two convex shapes. Do +/// not change this value. +#define b2_maxManifoldPoints 2 + +/// The maximum number of vertices on a convex polygon. You cannot increase +/// this too much because b2BlockAllocator has a maximum object size. +#define b2_maxPolygonVertices 8 + +/// This is used to fatten AABBs in the dynamic tree. This allows proxies +/// to move by a small amount without triggering a tree adjustment. +/// This is in meters. +#define b2_aabbExtension 0.1f + +/// This is used to fatten AABBs in the dynamic tree. This is used to predict +/// the future position based on the current displacement. +/// This is a dimensionless multiplier. +#define b2_aabbMultiplier 2.0f + +/// A small length used as a collision and constraint tolerance. Usually it is +/// chosen to be numerically significant, but visually insignificant. +#define b2_linearSlop 0.005f + +/// A small angle used as a collision and constraint tolerance. Usually it is +/// chosen to be numerically significant, but visually insignificant. +#define b2_angularSlop (2.0f / 180.0f * b2_pi) + +/// The radius of the polygon/edge shape skin. This should not be modified. Making +/// this smaller means polygons will have an insufficient buffer for continuous collision. +/// Making it larger may create artifacts for vertex collision. +#define b2_polygonRadius (2.0f * b2_linearSlop) + +/// Maximum number of sub-steps per contact in continuous physics simulation. +#define b2_maxSubSteps 8 + + +// Dynamics + +/// Maximum number of contacts to be handled to solve a TOI impact. +#define b2_maxTOIContacts 32 + +/// A velocity threshold for elastic collisions. Any collision with a relative linear +/// velocity below this threshold will be treated as inelastic. +#define b2_velocityThreshold 1.0f + +/// The maximum linear position correction used when solving constraints. This helps to +/// prevent overshoot. +#define b2_maxLinearCorrection 0.2f + +/// The maximum angular position correction used when solving constraints. This helps to +/// prevent overshoot. +#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) + +/// The maximum linear velocity of a body. This limit is very large and is used +/// to prevent numerical problems. You shouldn't need to adjust this. +#define b2_maxTranslation 2.0f +#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) + +/// The maximum angular velocity of a body. This limit is very large and is used +/// to prevent numerical problems. You shouldn't need to adjust this. +#define b2_maxRotation (0.5f * b2_pi) +#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) + +/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so +/// that overlap is removed in one time step. However using values close to 1 often lead +/// to overshoot. +#define b2_baumgarte 0.2f +#define b2_toiBaugarte 0.75f + + +// Sleep + +/// The time that a body must be still before it will go to sleep. +#define b2_timeToSleep 0.5f + +/// A body cannot sleep if its linear velocity is above this tolerance. +#define b2_linearSleepTolerance 0.01f + +/// A body cannot sleep if its angular velocity is above this tolerance. +#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) + +// Memory Allocation + +/// Implement this function to use your own memory allocator. +void* b2Alloc(int32 size); + +/// If you implement b2Alloc, you should also implement this function. +void b2Free(void* mem); + +/// Logging function. +void b2Log(const char* string, ...); + +/// Version numbering scheme. +/// See http://en.wikipedia.org/wiki/Software_versioning +struct b2Version +{ + int32 major; ///< significant changes + int32 minor; ///< incremental changes + int32 revision; ///< bug fixes +}; + +/// Current version. +extern b2Version b2_version; + +#endif diff --git a/external/box2d/Common/b2StackAllocator.cpp b/external/box2d/Common/b2StackAllocator.cpp new file mode 100644 index 0000000000..3caa5d9127 --- /dev/null +++ b/external/box2d/Common/b2StackAllocator.cpp @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2StackAllocator::b2StackAllocator() +{ + m_index = 0; + m_allocation = 0; + m_maxAllocation = 0; + m_entryCount = 0; +} + +b2StackAllocator::~b2StackAllocator() +{ + b2Assert(m_index == 0); + b2Assert(m_entryCount == 0); +} + +void* b2StackAllocator::Allocate(int32 size) +{ + b2Assert(m_entryCount < b2_maxStackEntries); + + b2StackEntry* entry = m_entries + m_entryCount; + entry->size = size; + if (m_index + size > b2_stackSize) + { + entry->data = (char*)b2Alloc(size); + entry->usedMalloc = true; + } + else + { + entry->data = m_data + m_index; + entry->usedMalloc = false; + m_index += size; + } + + m_allocation += size; + m_maxAllocation = b2Max(m_maxAllocation, m_allocation); + ++m_entryCount; + + return entry->data; +} + +void b2StackAllocator::Free(void* p) +{ + b2Assert(m_entryCount > 0); + b2StackEntry* entry = m_entries + m_entryCount - 1; + b2Assert(p == entry->data); + if (entry->usedMalloc) + { + b2Free(p); + } + else + { + m_index -= entry->size; + } + m_allocation -= entry->size; + --m_entryCount; + + p = NULL; +} + +int32 b2StackAllocator::GetMaxAllocation() const +{ + return m_maxAllocation; +} diff --git a/external/box2d/Common/b2StackAllocator.h b/external/box2d/Common/b2StackAllocator.h new file mode 100644 index 0000000000..6140d0d802 --- /dev/null +++ b/external/box2d/Common/b2StackAllocator.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_STACK_ALLOCATOR_H +#define B2_STACK_ALLOCATOR_H + +#include + +const int32 b2_stackSize = 100 * 1024; // 100k +const int32 b2_maxStackEntries = 32; + +struct b2StackEntry +{ + char* data; + int32 size; + bool usedMalloc; +}; + +// This is a stack allocator used for fast per step allocations. +// You must nest allocate/free pairs. The code will assert +// if you try to interleave multiple allocate/free pairs. +class b2StackAllocator +{ +public: + b2StackAllocator(); + ~b2StackAllocator(); + + void* Allocate(int32 size); + void Free(void* p); + + int32 GetMaxAllocation() const; + +private: + + char m_data[b2_stackSize]; + int32 m_index; + + int32 m_allocation; + int32 m_maxAllocation; + + b2StackEntry m_entries[b2_maxStackEntries]; + int32 m_entryCount; +}; + +#endif diff --git a/external/box2d/Common/b2Timer.cpp b/external/box2d/Common/b2Timer.cpp new file mode 100644 index 0000000000..b2bee94513 --- /dev/null +++ b/external/box2d/Common/b2Timer.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +#if defined(_WIN32) && !defined(SHP) + +float64 b2Timer::s_invFrequency = 0.0f; + +#include + +b2Timer::b2Timer() +{ + LARGE_INTEGER largeInteger; + + if (s_invFrequency == 0.0f) + { + QueryPerformanceFrequency(&largeInteger); + s_invFrequency = float64(largeInteger.QuadPart); + if (s_invFrequency > 0.0f) + { + s_invFrequency = 1000.0f / s_invFrequency; + } + } + + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +void b2Timer::Reset() +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +float32 b2Timer::GetMilliseconds() const +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + float64 count = float64(largeInteger.QuadPart); + float32 ms = float32(s_invFrequency * (count - m_start)); + return ms; +} + +#elif defined(__linux__) || defined (__APPLE__) + +#include + +b2Timer::b2Timer() +{ + Reset(); +} + +void b2Timer::Reset() +{ + timeval t; + gettimeofday(&t, 0); + m_start_sec = t.tv_sec; + m_start_msec = t.tv_usec * 0.001f; +} + +float32 b2Timer::GetMilliseconds() const +{ + timeval t; + gettimeofday(&t, 0); + return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; +} + +#else + +b2Timer::b2Timer() +{ +} + +void b2Timer::Reset() +{ +} + +float32 b2Timer::GetMilliseconds() const +{ + return 0.0f; +} + +#endif diff --git a/external/box2d/Common/b2Timer.h b/external/box2d/Common/b2Timer.h new file mode 100644 index 0000000000..053a107a56 --- /dev/null +++ b/external/box2d/Common/b2Timer.h @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +/// Timer for profiling. This has platform specific code and may +/// not work on every platform. +class b2Timer +{ +public: + + /// Constructor + b2Timer(); + + /// Reset the timer. + void Reset(); + + /// Get the time since construction or the last reset. + float32 GetMilliseconds() const; + +private: + +#if defined(_WIN32) + float64 m_start; + static float64 s_invFrequency; +#elif defined(__linux__) || defined (__APPLE__) + unsigned long m_start_sec; + unsigned long m_start_msec; +#endif +}; diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp new file mode 100644 index 0000000000..4ae4c41cd3 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); + return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); + allocator->Free(contact, sizeof(b2ChainAndCircleContact)); +} + +b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndCircle( manifold, &edge, xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h new file mode 100644 index 0000000000..1cf601a61f --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H +#define B2_CHAIN_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp new file mode 100644 index 0000000000..8116c34d1b --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); + return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); + allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); +} + +b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndPolygon( manifold, &edge, xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h new file mode 100644 index 0000000000..381c49b844 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H +#define B2_CHAIN_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2CircleContact.cpp b/external/box2d/Dynamics/Contacts/b2CircleContact.cpp new file mode 100644 index 0000000000..2436da5132 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2CircleContact.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2CircleContact)); + return new (mem) b2CircleContact(fixtureA, fixtureB); +} + +void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2CircleContact*)contact)->~b2CircleContact(); + allocator->Free(contact, sizeof(b2CircleContact)); +} + +b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideCircles(manifold, + (b2CircleShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2CircleContact.h b/external/box2d/Dynamics/Contacts/b2CircleContact.h new file mode 100644 index 0000000000..6da056ae0d --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2CircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CIRCLE_CONTACT_H +#define B2_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2CircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2CircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2Contact.cpp b/external/box2d/Dynamics/Contacts/b2Contact.cpp new file mode 100644 index 0000000000..2389af6434 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2Contact.cpp @@ -0,0 +1,240 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; +bool b2Contact::s_initialized = false; + +void b2Contact::InitializeRegisters() +{ + AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); + AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); + AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); + AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); + AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); + AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); + AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); +} + +void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, + b2Shape::Type type1, b2Shape::Type type2) +{ + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + s_registers[type1][type2].createFcn = createFcn; + s_registers[type1][type2].destroyFcn = destoryFcn; + s_registers[type1][type2].primary = true; + + if (type1 != type2) + { + s_registers[type2][type1].createFcn = createFcn; + s_registers[type2][type1].destroyFcn = destoryFcn; + s_registers[type2][type1].primary = false; + } +} + +b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + if (s_initialized == false) + { + InitializeRegisters(); + s_initialized = true; + } + + b2Shape::Type type1 = fixtureA->GetType(); + b2Shape::Type type2 = fixtureB->GetType(); + + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; + if (createFcn) + { + if (s_registers[type1][type2].primary) + { + return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); + } + else + { + return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); + } + } + else + { + return NULL; + } +} + +void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + b2Assert(s_initialized == true); + + if (contact->m_manifold.pointCount > 0) + { + contact->GetFixtureA()->GetBody()->SetAwake(true); + contact->GetFixtureB()->GetBody()->SetAwake(true); + } + + b2Shape::Type typeA = contact->GetFixtureA()->GetType(); + b2Shape::Type typeB = contact->GetFixtureB()->GetType(); + + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + + b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; + destroyFcn(contact, allocator); +} + +b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) +{ + m_flags = e_enabledFlag; + + m_fixtureA = fA; + m_fixtureB = fB; + + m_indexA = indexA; + m_indexB = indexB; + + m_manifold.pointCount = 0; + + m_prev = NULL; + m_next = NULL; + + m_nodeA.contact = NULL; + m_nodeA.prev = NULL; + m_nodeA.next = NULL; + m_nodeA.other = NULL; + + m_nodeB.contact = NULL; + m_nodeB.prev = NULL; + m_nodeB.next = NULL; + m_nodeB.other = NULL; + + m_toiCount = 0; + + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + +// Update the contact manifold and touching status. +// Note: do not assume the fixture AABBs are overlapping or are valid. +void b2Contact::Update(b2ContactListener* listener) +{ + b2Manifold oldManifold = m_manifold; + + // Re-enable this contact. + m_flags |= e_enabledFlag; + + bool touching = false; + bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; + + bool sensorA = m_fixtureA->IsSensor(); + bool sensorB = m_fixtureB->IsSensor(); + bool sensor = sensorA || sensorB; + + b2Body* bodyA = m_fixtureA->GetBody(); + b2Body* bodyB = m_fixtureB->GetBody(); + const b2Transform& xfA = bodyA->GetTransform(); + const b2Transform& xfB = bodyB->GetTransform(); + + // Is this contact a sensor? + if (sensor) + { + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); + + // Sensors don't generate manifolds. + m_manifold.pointCount = 0; + } + else + { + Evaluate(&m_manifold, xfA, xfB); + touching = m_manifold.pointCount > 0; + + // Match old contact ids to new contact ids and copy the + // stored impulses to warm start the solver. + for (int32 i = 0; i < m_manifold.pointCount; ++i) + { + b2ManifoldPoint* mp2 = m_manifold.points + i; + mp2->normalImpulse = 0.0f; + mp2->tangentImpulse = 0.0f; + b2ContactID id2 = mp2->id; + + for (int32 j = 0; j < oldManifold.pointCount; ++j) + { + b2ManifoldPoint* mp1 = oldManifold.points + j; + + if (mp1->id.key == id2.key) + { + mp2->normalImpulse = mp1->normalImpulse; + mp2->tangentImpulse = mp1->tangentImpulse; + break; + } + } + } + + if (touching != wasTouching) + { + bodyA->SetAwake(true); + bodyB->SetAwake(true); + } + } + + if (touching) + { + m_flags |= e_touchingFlag; + } + else + { + m_flags &= ~e_touchingFlag; + } + + if (wasTouching == false && touching == true && listener) + { + listener->BeginContact(this); + } + + if (wasTouching == true && touching == false && listener) + { + listener->EndContact(this); + } + + if (sensor == false && touching && listener) + { + listener->PreSolve(this, &oldManifold); + } +} diff --git a/external/box2d/Dynamics/Contacts/b2Contact.h b/external/box2d/Dynamics/Contacts/b2Contact.h new file mode 100644 index 0000000000..20d9403ce7 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2Contact.h @@ -0,0 +1,331 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_H +#define B2_CONTACT_H + +#include +#include +#include +#include + +class b2Body; +class b2Contact; +class b2Fixture; +class b2World; +class b2BlockAllocator; +class b2StackAllocator; +class b2ContactListener; + +/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. +/// For example, anything slides on ice. +inline float32 b2MixFriction(float32 friction1, float32 friction2) +{ + return std::sqrt(friction1 * friction2); +} + +/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. +/// For example, a superball bounces on anything. +inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) +{ + return restitution1 > restitution2 ? restitution1 : restitution2; +} + +typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, + b2BlockAllocator* allocator); +typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); + +struct b2ContactRegister +{ + b2ContactCreateFcn* createFcn; + b2ContactDestroyFcn* destroyFcn; + bool primary; +}; + +/// A contact edge is used to connect bodies and contacts together +/// in a contact graph where each body is a node and each contact +/// is an edge. A contact edge belongs to a doubly linked list +/// maintained in each attached body. Each contact has two contact +/// nodes, one for each attached body. +struct b2ContactEdge +{ + b2Body* other; ///< provides quick access to the other body attached. + b2Contact* contact; ///< the contact + b2ContactEdge* prev; ///< the previous contact edge in the body's contact list + b2ContactEdge* next; ///< the next contact edge in the body's contact list +}; + +/// The class manages contact between two shapes. A contact exists for each overlapping +/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist +/// that has no contact points. +class b2Contact +{ +public: + + /// Get the contact manifold. Do not modify the manifold unless you understand the + /// internals of Box2D. + b2Manifold* GetManifold(); + const b2Manifold* GetManifold() const; + + /// Get the world manifold. + void GetWorldManifold(b2WorldManifold* worldManifold) const; + + /// Is this contact touching? + bool IsTouching() const; + + /// Enable/disable this contact. This can be used inside the pre-solve + /// contact listener. The contact is only disabled for the current + /// time step (or sub-step in continuous collisions). + void SetEnabled(bool flag); + + /// Has this contact been disabled? + bool IsEnabled() const; + + /// Get the next contact in the world's contact list. + b2Contact* GetNext(); + const b2Contact* GetNext() const; + + /// Get fixture A in this contact. + b2Fixture* GetFixtureA(); + const b2Fixture* GetFixtureA() const; + + /// Get the child primitive index for fixture A. + int32 GetChildIndexA() const; + + /// Get fixture B in this contact. + b2Fixture* GetFixtureB(); + const b2Fixture* GetFixtureB() const; + + /// Get the child primitive index for fixture B. + int32 GetChildIndexB() const; + + /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. + /// This value persists until set or reset. + void SetFriction(float32 friction); + + /// Get the friction. + float32 GetFriction() const; + + /// Reset the friction mixture to the default value. + void ResetFriction(); + + /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. + /// The value persists until you set or reset. + void SetRestitution(float32 restitution); + + /// Get the restitution. + float32 GetRestitution() const; + + /// Reset the restitution to the default value. + void ResetRestitution(); + + /// Evaluate this contact with your own manifold and transforms. + virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; + +protected: + friend class b2ContactManager; + friend class b2World; + friend class b2ContactSolver; + friend class b2Body; + friend class b2Fixture; + + // Flags stored in m_flags + enum + { + // Used when crawling contact graph when forming islands. + e_islandFlag = 0x0001, + + // Set when the shapes are touching. + e_touchingFlag = 0x0002, + + // This contact can be disabled (by user) + e_enabledFlag = 0x0004, + + // This contact needs filtering because a fixture filter was changed. + e_filterFlag = 0x0008, + + // This bullet contact had a TOI event + e_bulletHitFlag = 0x0010, + + // This contact has a valid TOI in m_toi + e_toiFlag = 0x0020 + }; + + /// Flag this contact for filtering. Filtering will occur the next time step. + void FlagForFiltering(); + + static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, + b2Shape::Type typeA, b2Shape::Type typeB); + static void InitializeRegisters(); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} + b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + virtual ~b2Contact() {} + + void Update(b2ContactListener* listener); + + static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; + static bool s_initialized; + + uint32 m_flags; + + // World pool and list pointers. + b2Contact* m_prev; + b2Contact* m_next; + + // Nodes for connecting bodies. + b2ContactEdge m_nodeA; + b2ContactEdge m_nodeB; + + b2Fixture* m_fixtureA; + b2Fixture* m_fixtureB; + + int32 m_indexA; + int32 m_indexB; + + b2Manifold m_manifold; + + int32 m_toiCount; + float32 m_toi; + + float32 m_friction; + float32 m_restitution; +}; + +inline b2Manifold* b2Contact::GetManifold() +{ + return &m_manifold; +} + +inline const b2Manifold* b2Contact::GetManifold() const +{ + return &m_manifold; +} + +inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const +{ + const b2Body* bodyA = m_fixtureA->GetBody(); + const b2Body* bodyB = m_fixtureB->GetBody(); + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + + worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); +} + +inline void b2Contact::SetEnabled(bool flag) +{ + if (flag) + { + m_flags |= e_enabledFlag; + } + else + { + m_flags &= ~e_enabledFlag; + } +} + +inline bool b2Contact::IsEnabled() const +{ + return (m_flags & e_enabledFlag) == e_enabledFlag; +} + +inline bool b2Contact::IsTouching() const +{ + return (m_flags & e_touchingFlag) == e_touchingFlag; +} + +inline b2Contact* b2Contact::GetNext() +{ + return m_next; +} + +inline const b2Contact* b2Contact::GetNext() const +{ + return m_next; +} + +inline b2Fixture* b2Contact::GetFixtureA() +{ + return m_fixtureA; +} + +inline const b2Fixture* b2Contact::GetFixtureA() const +{ + return m_fixtureA; +} + +inline b2Fixture* b2Contact::GetFixtureB() +{ + return m_fixtureB; +} + +inline int32 b2Contact::GetChildIndexA() const +{ + return m_indexA; +} + +inline const b2Fixture* b2Contact::GetFixtureB() const +{ + return m_fixtureB; +} + +inline int32 b2Contact::GetChildIndexB() const +{ + return m_indexB; +} + +inline void b2Contact::FlagForFiltering() +{ + m_flags |= e_filterFlag; +} + +inline void b2Contact::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Contact::GetFriction() const +{ + return m_friction; +} + +inline void b2Contact::ResetFriction() +{ + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); +} + +inline void b2Contact::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline float32 b2Contact::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Contact::ResetRestitution() +{ + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp b/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp new file mode 100644 index 0000000000..0dc740342a --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp @@ -0,0 +1,832 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +#include +#include +#include +#include +#include + +#define B2_DEBUG_SOLVER 0 + +struct b2ContactPositionConstraint +{ + b2Vec2 localPoints[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + b2Vec2 localCenterA, localCenterB; + float32 invIA, invIB; + b2Manifold::Type type; + float32 radiusA, radiusB; + int32 pointCount; +}; + +b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) +{ + m_step = def->step; + m_allocator = def->allocator; + m_count = def->count; + m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); + m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); + m_positions = def->positions; + m_velocities = def->velocities; + m_contacts = def->contacts; + + // Initialize position independent portions of the constraints. + for (int32 i = 0; i < m_count; ++i) + { + b2Contact* contact = m_contacts[i]; + + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + b2Shape* shapeA = fixtureA->GetShape(); + b2Shape* shapeB = fixtureB->GetShape(); + float32 radiusA = shapeA->m_radius; + float32 radiusB = shapeB->m_radius; + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + b2Manifold* manifold = contact->GetManifold(); + + int32 pointCount = manifold->pointCount; + b2Assert(pointCount > 0); + + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + vc->friction = contact->m_friction; + vc->restitution = contact->m_restitution; + vc->indexA = bodyA->m_islandIndex; + vc->indexB = bodyB->m_islandIndex; + vc->invMassA = bodyA->m_invMass; + vc->invMassB = bodyB->m_invMass; + vc->invIA = bodyA->m_invI; + vc->invIB = bodyB->m_invI; + vc->contactIndex = i; + vc->pointCount = pointCount; + vc->K.SetZero(); + vc->normalMass.SetZero(); + + b2ContactPositionConstraint* pc = m_positionConstraints + i; + pc->indexA = bodyA->m_islandIndex; + pc->indexB = bodyB->m_islandIndex; + pc->invMassA = bodyA->m_invMass; + pc->invMassB = bodyB->m_invMass; + pc->localCenterA = bodyA->m_sweep.localCenter; + pc->localCenterB = bodyB->m_sweep.localCenter; + pc->invIA = bodyA->m_invI; + pc->invIB = bodyB->m_invI; + pc->localNormal = manifold->localNormal; + pc->localPoint = manifold->localPoint; + pc->pointCount = pointCount; + pc->radiusA = radiusA; + pc->radiusB = radiusB; + pc->type = manifold->type; + + for (int32 j = 0; j < pointCount; ++j) + { + b2ManifoldPoint* cp = manifold->points + j; + b2VelocityConstraintPoint* vcp = vc->points + j; + + if (m_step.warmStarting) + { + vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; + vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; + } + else + { + vcp->normalImpulse = 0.0f; + vcp->tangentImpulse = 0.0f; + } + + vcp->rA.SetZero(); + vcp->rB.SetZero(); + vcp->normalMass = 0.0f; + vcp->tangentMass = 0.0f; + vcp->velocityBias = 0.0f; + + pc->localPoints[j] = cp->localPoint; + } + } +} + +b2ContactSolver::~b2ContactSolver() +{ + m_allocator->Free(m_velocityConstraints); + m_allocator->Free(m_positionConstraints); +} + +// Initialize position dependent portions of the velocity constraints. +void b2ContactSolver::InitializeVelocityConstraints() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + float32 radiusA = pc->radiusA; + float32 radiusB = pc->radiusB; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + + float32 mA = vc->invMassA; + float32 mB = vc->invMassB; + float32 iA = vc->invIA; + float32 iB = vc->invIB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Assert(manifold->pointCount > 0); + + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2WorldManifold worldManifold; + worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); + + vc->normal = worldManifold.normal; + + int32 pointCount = vc->pointCount; + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + + vcp->rA = worldManifold.points[j] - cA; + vcp->rB = worldManifold.points[j] - cB; + + float32 rnA = b2Cross(vcp->rA, vc->normal); + float32 rnB = b2Cross(vcp->rB, vc->normal); + + float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + b2Vec2 tangent = b2Cross(vc->normal, 1.0f); + + float32 rtA = b2Cross(vcp->rA, tangent); + float32 rtB = b2Cross(vcp->rB, tangent); + + float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; + + vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + + // Setup a velocity bias for restitution. + vcp->velocityBias = 0.0f; + float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); + if (vRel < -b2_velocityThreshold) + { + vcp->velocityBias = -vc->restitution * vRel; + } + } + + // If we have two points, then prepare the block solver. + if (vc->pointCount == 2) + { + b2VelocityConstraintPoint* vcp1 = vc->points + 0; + b2VelocityConstraintPoint* vcp2 = vc->points + 1; + + float32 rn1A = b2Cross(vcp1->rA, vc->normal); + float32 rn1B = b2Cross(vcp1->rB, vc->normal); + float32 rn2A = b2Cross(vcp2->rA, vc->normal); + float32 rn2B = b2Cross(vcp2->rB, vc->normal); + + float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; + float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; + float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; + + // Ensure a reasonable condition number. + const float32 k_maxConditionNumber = 1000.0f; + if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) + { + // K is safe to invert. + vc->K.ex.Set(k11, k12); + vc->K.ey.Set(k12, k22); + vc->normalMass = vc->K.GetInverse(); + } + else + { + // The constraints are redundant, just use one. + // TODO_ERIN use deepest? + vc->pointCount = 1; + } + } + } +} + +void b2ContactSolver::WarmStart() +{ + // Warm start. + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; + wA -= iA * b2Cross(vcp->rA, P); + vA -= mA * P; + wB += iB * b2Cross(vcp->rB, P); + vB += mB * P; + } + + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } +} + +void b2ContactSolver::SolveVelocityConstraints() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + float32 friction = vc->friction; + + b2Assert(pointCount == 1 || pointCount == 2); + + // Solve tangent constraints first because non-penetration is more important + // than friction. + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + + // Compute tangent force + float32 vt = b2Dot(dv, tangent); + float32 lambda = vcp->tangentMass * (-vt); + + // b2Clamp the accumulated force + float32 maxFriction = friction * vcp->normalImpulse; + float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); + lambda = newImpulse - vcp->tangentImpulse; + vcp->tangentImpulse = newImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * tangent; + + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); + + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } + + // Solve normal constraints + if (vc->pointCount == 1) + { + b2VelocityConstraintPoint* vcp = vc->points + 0; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + + // Compute normal impulse + float32 vn = b2Dot(dv, normal); + float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); + + // b2Clamp the accumulated impulse + float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); + lambda = newImpulse - vcp->normalImpulse; + vcp->normalImpulse = newImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * normal; + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); + + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } + else + { + // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). + // Build the mini LCP for this contact patch + // + // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 + // + // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) + // b = vn0 - velocityBias + // + // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i + // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases + // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid + // solution that satisfies the problem is chosen. + // + // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires + // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). + // + // Substitute: + // + // x = a + d + // + // a := old total impulse + // x := new total impulse + // d := incremental impulse + // + // For the current iteration we extend the formula for the incremental impulse + // to compute the new total impulse: + // + // vn = A * d + b + // = A * (x - a) + b + // = A * x + b - A * a + // = A * x + b' + // b' = b - A * a; + + b2VelocityConstraintPoint* cp1 = vc->points + 0; + b2VelocityConstraintPoint* cp2 = vc->points + 1; + + b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); + b2Assert(a.x >= 0.0f && a.y >= 0.0f); + + // Relative velocity at contact + b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + float32 vn1 = b2Dot(dv1, normal); + float32 vn2 = b2Dot(dv2, normal); + + b2Vec2 b; + b.x = vn1 - cp1->velocityBias; + b.y = vn2 - cp2->velocityBias; + + // Compute b' + b -= b2Mul(vc->K, a); + + const float32 k_errorTol = 1e-3f; + B2_NOT_USED(k_errorTol); + + for (;;) + { + // + // Case 1: vn = 0 + // + // 0 = A * x + b' + // + // Solve for x: + // + // x = - inv(A) * b' + // + b2Vec2 x = - b2Mul(vc->normalMass, b); + + if (x.x >= 0.0f && x.y >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 2: vn1 = 0 and x2 = 0 + // + // 0 = a11 * x1 + a12 * 0 + b1' + // vn2 = a21 * x1 + a22 * 0 + b2' + // + x.x = - cp1->normalMass * b.x; + x.y = 0.0f; + vn1 = 0.0f; + vn2 = vc->K.ex.y * x.x + b.y; + + if (x.x >= 0.0f && vn2 >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); +#endif + break; + } + + + // + // Case 3: vn2 = 0 and x1 = 0 + // + // vn1 = a11 * 0 + a12 * x2 + b1' + // 0 = a21 * 0 + a22 * x2 + b2' + // + x.x = 0.0f; + x.y = - cp2->normalMass * b.y; + vn1 = vc->K.ey.x * x.y + b.x; + vn2 = 0.0f; + + if (x.y >= 0.0f && vn1 >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 4: x1 = 0 and x2 = 0 + // + // vn1 = b1 + // vn2 = b2; + x.x = 0.0f; + x.y = 0.0f; + vn1 = b.x; + vn2 = b.y; + + if (vn1 >= 0.0f && vn2 >= 0.0f ) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + + break; + } + + // No solution, give up. This is hit sometimes, but it doesn't seem to matter. + break; + } + } + + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } +} + +void b2ContactSolver::StoreImpulses() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + + for (int32 j = 0; j < vc->pointCount; ++j) + { + manifold->points[j].normalImpulse = vc->points[j].normalImpulse; + manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; + } + } +} + +struct b2PositionSolverManifold +{ + void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) + { + b2Assert(pc->pointCount > 0); + + switch (pc->type) + { + case b2Manifold::e_circles: + { + b2Vec2 pointA = b2Mul(xfA, pc->localPoint); + b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); + normal = pointB - pointA; + normal.Normalize(); + point = 0.5f * (pointA + pointB); + separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; + } + break; + + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); + + b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; + } + break; + + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); + + b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; + + // Ensure normal points from A to B + normal = -normal; + } + break; + } + } + + b2Vec2 normal; + b2Vec2 point; + float32 separation; +}; + +// Sequential solver. +bool b2ContactSolver::SolvePositionConstraints() +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + float32 mA = pc->invMassA; + float32 iA = pc->invIA; + b2Vec2 localCenterB = pc->localCenterB; + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + int32 pointCount = pc->pointCount; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -3.0f * b2_linearSlop; +} + +// Sequential position solver for position constraints. +bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + int32 pointCount = pc->pointCount; + + float32 mA = 0.0f; + float32 iA = 0.0f; + if (indexA == toiIndexA || indexA == toiIndexB) + { + mA = pc->invMassA; + iA = pc->invIA; + } + + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + if (indexB == toiIndexA || indexB == toiIndexB) + { + mB = pc->invMassB; + iB = pc->invIB; + } + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -1.5f * b2_linearSlop; +} diff --git a/external/box2d/Dynamics/Contacts/b2ContactSolver.h b/external/box2d/Dynamics/Contacts/b2ContactSolver.h new file mode 100644 index 0000000000..aef1987a9e --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2ContactSolver.h @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_SOLVER_H +#define B2_CONTACT_SOLVER_H + +#include +#include +#include + +class b2Contact; +class b2Body; +class b2StackAllocator; +struct b2ContactPositionConstraint; + +struct b2VelocityConstraintPoint +{ + b2Vec2 rA; + b2Vec2 rB; + float32 normalImpulse; + float32 tangentImpulse; + float32 normalMass; + float32 tangentMass; + float32 velocityBias; +}; + +struct b2ContactVelocityConstraint +{ + b2VelocityConstraintPoint points[b2_maxManifoldPoints]; + b2Vec2 normal; + b2Mat22 normalMass; + b2Mat22 K; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + float32 invIA, invIB; + float32 friction; + float32 restitution; + int32 pointCount; + int32 contactIndex; +}; + +struct b2ContactSolverDef +{ + b2TimeStep step; + b2Contact** contacts; + int32 count; + b2Position* positions; + b2Velocity* velocities; + b2StackAllocator* allocator; +}; + +class b2ContactSolver +{ +public: + b2ContactSolver(b2ContactSolverDef* def); + ~b2ContactSolver(); + + void InitializeVelocityConstraints(); + + void WarmStart(); + void SolveVelocityConstraints(); + void StoreImpulses(); + + bool SolvePositionConstraints(); + bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); + + b2TimeStep m_step; + b2Position* m_positions; + b2Velocity* m_velocities; + b2StackAllocator* m_allocator; + b2ContactPositionConstraint* m_positionConstraints; + b2ContactVelocityConstraint* m_velocityConstraints; + b2Contact** m_contacts; + int m_count; +}; + +#endif + diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp new file mode 100644 index 0000000000..aade42880a --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); + return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); +} + +void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); + allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); +} + +b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndCircle( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h new file mode 100644 index 0000000000..70771ec536 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H +#define B2_EDGE_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp new file mode 100644 index 0000000000..04ce394107 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); + return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); +} + +void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); + allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); +} + +b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndPolygon( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h new file mode 100644 index 0000000000..f65f3acca9 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_POLYGON_CONTACT_H +#define B2_EDGE_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp new file mode 100644 index 0000000000..961b26f38a --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); + return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); +} + +void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); + allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); +} + +b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygonAndCircle( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h new file mode 100644 index 0000000000..7b1a5288b4 --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H +#define B2_POLYGON_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2PolygonAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp new file mode 100644 index 0000000000..a2884a440d --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonContact)); + return new (mem) b2PolygonContact(fixtureA, fixtureB); +} + +void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonContact*)contact)->~b2PolygonContact(); + allocator->Free(contact, sizeof(b2PolygonContact)); +} + +b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygons( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/box2d/Dynamics/Contacts/b2PolygonContact.h b/external/box2d/Dynamics/Contacts/b2PolygonContact.h new file mode 100644 index 0000000000..302684232a --- /dev/null +++ b/external/box2d/Dynamics/Contacts/b2PolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_CONTACT_H +#define B2_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2PolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp b/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp new file mode 100644 index 0000000000..b2d4bd006c --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp @@ -0,0 +1,260 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// 1-D constrained system +// m (v2 - v1) = lambda +// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. +// x2 = x1 + h * v2 + +// 1-D mass-damper-spring system +// m (v2 - v1) + h * d * v2 + h * k * + +// C = norm(p2 - p1) - L +// u = (p2 - p1) / norm(p2 - p1) +// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// J = [-u -cross(r1, u) u cross(r2, u)] +// K = J * invM * JT +// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 + +void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, + const b2Vec2& anchor1, const b2Vec2& anchor2) +{ + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor1); + localAnchorB = bodyB->GetLocalPoint(anchor2); + b2Vec2 d = anchor2 - anchor1; + length = d.Length(); +} + +b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_length = def->length; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + m_impulse = 0.0f; + m_gamma = 0.0f; + m_bias = 0.0f; +} + +void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; + + // Handle singularity. + float32 length = m_u.Length(); + if (length > b2_linearSlop) + { + m_u *= 1.0f / length; + } + else + { + m_u.Set(0.0f, 0.0f); + } + + float32 crAu = b2Cross(m_rA, m_u); + float32 crBu = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; + + // Compute the effective mass matrix. + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + + if (m_frequencyHz > 0.0f) + { + float32 C = length - m_length; + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m_mass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m_mass * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; + + invMass += m_gamma; + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + } + else + { + m_gamma = 0.0f; + m_bias = 0.0f; + } + + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 Cdot = b2Dot(m_u, vpB - vpA); + + float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); + m_impulse += impulse; + + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) +{ + if (m_frequencyHz > 0.0f) + { + // There is no position correction for soft distance constraints. + return true; + } + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; + + float32 length = u.Normalize(); + float32 C = length - m_length; + C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); + + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; + + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return b2Abs(C) < b2_linearSlop; +} + +b2Vec2 b2DistanceJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2DistanceJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; +} + +float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +void b2DistanceJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2DistanceJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.length = %.15lef;\n", m_length); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2DistanceJoint.h b/external/box2d/Dynamics/Joints/b2DistanceJoint.h new file mode 100644 index 0000000000..fc11476ff9 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2DistanceJoint.h @@ -0,0 +1,169 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DISTANCE_JOINT_H +#define B2_DISTANCE_JOINT_H + +#include + +/// Distance joint definition. This requires defining an +/// anchor point on both bodies and the non-zero length of the +/// distance joint. The definition uses local anchor points +/// so that the initial configuration can violate the constraint +/// slightly. This helps when saving and loading a game. +/// @warning Do not use a zero or short length. +struct b2DistanceJointDef : public b2JointDef +{ + b2DistanceJointDef() + { + type = e_distanceJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + length = 1.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } + + /// Initialize the bodies, anchors, and length using the world + /// anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& anchorA, const b2Vec2& anchorB); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The natural length between the anchor points. + float32 length; + + /// The mass-spring-damper frequency in Hertz. A value of 0 + /// disables softness. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A distance joint constrains two points on two bodies +/// to remain at a fixed distance from each other. You can view +/// this as a massless, rigid rod. +class b2DistanceJoint : public b2Joint +{ +public: + + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque given the inverse time step. + /// Unit is N*m. This is always zero for a distance joint. + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set/get the natural length. + /// Manipulating the length can lead to non-physical behavior when the frequency is zero. + void SetLength(float32 length); + float32 GetLength() const; + + /// Set/get frequency in Hz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2DistanceJoint(const b2DistanceJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_gamma; + float32 m_impulse; + float32 m_length; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; +}; + +inline void b2DistanceJoint::SetLength(float32 length) +{ + m_length = length; +} + +inline float32 b2DistanceJoint::GetLength() const +{ + return m_length; +} + +inline void b2DistanceJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2DistanceJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +inline void b2DistanceJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2DistanceJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + +#endif diff --git a/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp b/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp new file mode 100644 index 0000000000..6e6018db10 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp @@ -0,0 +1,251 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); +} + +b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + + m_maxForce = def->maxForce; + m_maxTorque = def->maxTorque; +} + +void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective mass matrix. + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat22 K; + K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; + K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; + + m_linearMass = K.GetInverse(); + + m_angularMass = iA + iB; + if (m_angularMass > 0.0f) + { + m_angularMass = 1.0f / m_angularMass; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_linearImpulse *= data.step.dtRatio; + m_angularImpulse *= data.step.dtRatio; + + b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); + } + else + { + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + float32 h = data.step.dt; + + // Solve angular friction + { + float32 Cdot = wB - wA; + float32 impulse = -m_angularMass * Cdot; + + float32 oldImpulse = m_angularImpulse; + float32 maxImpulse = h * m_maxTorque; + m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_angularImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve linear friction + { + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + + b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); + b2Vec2 oldImpulse = m_linearImpulse; + m_linearImpulse += impulse; + + float32 maxImpulse = h * m_maxForce; + + if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_linearImpulse.Normalize(); + m_linearImpulse *= maxImpulse; + } + + impulse = m_linearImpulse - oldImpulse; + + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + + return true; +} + +b2Vec2 b2FrictionJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2FrictionJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_linearImpulse; +} + +float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_angularImpulse; +} + +void b2FrictionJoint::SetMaxForce(float32 force) +{ + b2Assert(b2IsValid(force) && force >= 0.0f); + m_maxForce = force; +} + +float32 b2FrictionJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2FrictionJoint::SetMaxTorque(float32 torque) +{ + b2Assert(b2IsValid(torque) && torque >= 0.0f); + m_maxTorque = torque; +} + +float32 b2FrictionJoint::GetMaxTorque() const +{ + return m_maxTorque; +} + +void b2FrictionJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2FrictionJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); + b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2FrictionJoint.h b/external/box2d/Dynamics/Joints/b2FrictionJoint.h new file mode 100644 index 0000000000..3ee40c6298 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2FrictionJoint.h @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FRICTION_JOINT_H +#define B2_FRICTION_JOINT_H + +#include + +/// Friction joint definition. +struct b2FrictionJointDef : public b2JointDef +{ + b2FrictionJointDef() + { + type = e_frictionJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + maxForce = 0.0f; + maxTorque = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum friction force in N. + float32 maxForce; + + /// The maximum friction torque in N-m. + float32 maxTorque; +}; + +/// Friction joint. This is used for top-down friction. +/// It provides 2D translational friction and angular friction. +class b2FrictionJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set the maximum friction force in N. + void SetMaxForce(float32 force); + + /// Get the maximum friction force in N. + float32 GetMaxForce() const; + + /// Set the maximum friction torque in N*m. + void SetMaxTorque(float32 torque); + + /// Get the maximum friction torque in N*m. + float32 GetMaxTorque() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + + b2FrictionJoint(const b2FrictionJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + + // Solver shared + b2Vec2 m_linearImpulse; + float32 m_angularImpulse; + float32 m_maxForce; + float32 m_maxTorque; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat22 m_linearMass; + float32 m_angularMass; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2GearJoint.cpp b/external/box2d/Dynamics/Joints/b2GearJoint.cpp new file mode 100644 index 0000000000..9741cdd5a4 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2GearJoint.cpp @@ -0,0 +1,423 @@ +/* +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +// Gear Joint: +// C0 = (coordinate1 + ratio * coordinate2)_initial +// C = (coordinate1 + ratio * coordinate2) - C0 = 0 +// J = [J1 ratio * J2] +// K = J * invM * JT +// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T +// +// Revolute: +// coordinate = rotation +// Cdot = angularVelocity +// J = [0 0 1] +// K = J * invM * JT = invI +// +// Prismatic: +// coordinate = dot(p - pg, ug) +// Cdot = dot(v + cross(w, r), ug) +// J = [ug cross(r, ug)] +// K = J * invM * JT = invMass + invI * cross(r, ug)^2 + +b2GearJoint::b2GearJoint(const b2GearJointDef* def) +: b2Joint(def) +{ + m_joint1 = def->joint1; + m_joint2 = def->joint2; + + m_typeA = m_joint1->GetType(); + m_typeB = m_joint2->GetType(); + + b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); + b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); + + float32 coordinateA, coordinateB; + + // TODO_ERIN there might be some problem with the joint edges in b2Joint. + + m_bodyC = m_joint1->GetBodyA(); + m_bodyA = m_joint1->GetBodyB(); + + // Get geometry of joint1 + b2Transform xfA = m_bodyA->m_xf; + float32 aA = m_bodyA->m_sweep.a; + b2Transform xfC = m_bodyC->m_xf; + float32 aC = m_bodyC->m_sweep.a; + + if (m_typeA == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; + m_localAnchorC = revolute->m_localAnchorA; + m_localAnchorA = revolute->m_localAnchorB; + m_referenceAngleA = revolute->m_referenceAngle; + m_localAxisC.SetZero(); + + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; + m_localAnchorC = prismatic->m_localAnchorA; + m_localAnchorA = prismatic->m_localAnchorB; + m_referenceAngleA = prismatic->m_referenceAngle; + m_localAxisC = prismatic->m_localXAxisA; + + b2Vec2 pC = m_localAnchorC; + b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } + + m_bodyD = m_joint2->GetBodyA(); + m_bodyB = m_joint2->GetBodyB(); + + // Get geometry of joint2 + b2Transform xfB = m_bodyB->m_xf; + float32 aB = m_bodyB->m_sweep.a; + b2Transform xfD = m_bodyD->m_xf; + float32 aD = m_bodyD->m_sweep.a; + + if (m_typeB == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; + m_localAnchorD = revolute->m_localAnchorA; + m_localAnchorB = revolute->m_localAnchorB; + m_referenceAngleB = revolute->m_referenceAngle; + m_localAxisD.SetZero(); + + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; + m_localAnchorD = prismatic->m_localAnchorA; + m_localAnchorB = prismatic->m_localAnchorB; + m_referenceAngleB = prismatic->m_referenceAngle; + m_localAxisD = prismatic->m_localXAxisA; + + b2Vec2 pD = m_localAnchorD; + b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } + + m_ratio = def->ratio; + + m_constant = coordinateA + m_ratio * coordinateB; + + m_impulse = 0.0f; +} + +void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_indexC = m_bodyC->m_islandIndex; + m_indexD = m_bodyD->m_islandIndex; + m_lcA = m_bodyA->m_sweep.localCenter; + m_lcB = m_bodyB->m_sweep.localCenter; + m_lcC = m_bodyC->m_sweep.localCenter; + m_lcD = m_bodyD->m_sweep.localCenter; + m_mA = m_bodyA->m_invMass; + m_mB = m_bodyB->m_invMass; + m_mC = m_bodyC->m_invMass; + m_mD = m_bodyD->m_invMass; + m_iA = m_bodyA->m_invI; + m_iB = m_bodyB->m_invI; + m_iC = m_bodyC->m_invI; + m_iD = m_bodyD->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + + m_mass = 0.0f; + + if (m_typeA == e_revoluteJoint) + { + m_JvAC.SetZero(); + m_JwA = 1.0f; + m_JwC = 1.0f; + m_mass += m_iA + m_iC; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + m_JvAC = u; + m_JwC = b2Cross(rC, u); + m_JwA = b2Cross(rA, u); + m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; + } + + if (m_typeB == e_revoluteJoint) + { + m_JvBD.SetZero(); + m_JwB = m_ratio; + m_JwD = m_ratio; + m_mass += m_ratio * m_ratio * (m_iB + m_iD); + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + m_JvBD = m_ratio * u; + m_JwD = m_ratio * b2Cross(rD, u); + m_JwB = m_ratio * b2Cross(rB, u); + m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; + } + + // Compute effective mass. + m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; + + if (data.step.warmStarting) + { + vA += (m_mA * m_impulse) * m_JvAC; + wA += m_iA * m_impulse * m_JwA; + vB += (m_mB * m_impulse) * m_JvBD; + wB += m_iB * m_impulse * m_JwB; + vC -= (m_mC * m_impulse) * m_JvAC; + wC -= m_iC * m_impulse * m_JwC; + vD -= (m_mD * m_impulse) * m_JvBD; + wD -= m_iD * m_impulse * m_JwD; + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; +} + +void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; + + float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); + Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); + + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + vA += (m_mA * impulse) * m_JvAC; + wA += m_iA * impulse * m_JwA; + vB += (m_mB * impulse) * m_JvBD; + wB += m_iB * impulse * m_JwB; + vC -= (m_mC * impulse) * m_JvAC; + wC -= m_iC * impulse * m_JwC; + vD -= (m_mD * impulse) * m_JvBD; + wD -= m_iD * impulse * m_JwD; + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; +} + +bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + + float32 linearError = 0.0f; + + float32 coordinateA, coordinateB; + + b2Vec2 JvAC, JvBD; + float32 JwA, JwB, JwC, JwD; + float32 mass = 0.0f; + + if (m_typeA == e_revoluteJoint) + { + JvAC.SetZero(); + JwA = 1.0f; + JwC = 1.0f; + mass += m_iA + m_iC; + + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + JvAC = u; + JwC = b2Cross(rC, u); + JwA = b2Cross(rA, u); + mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; + + b2Vec2 pC = m_localAnchorC - m_lcC; + b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } + + if (m_typeB == e_revoluteJoint) + { + JvBD.SetZero(); + JwB = m_ratio; + JwD = m_ratio; + mass += m_ratio * m_ratio * (m_iB + m_iD); + + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + JvBD = m_ratio * u; + JwD = m_ratio * b2Cross(rD, u); + JwB = m_ratio * b2Cross(rB, u); + mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; + + b2Vec2 pD = m_localAnchorD - m_lcD; + b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } + + float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; + + float32 impulse = 0.0f; + if (mass > 0.0f) + { + impulse = -C / mass; + } + + cA += m_mA * impulse * JvAC; + aA += m_iA * impulse * JwA; + cB += m_mB * impulse * JvBD; + aB += m_iB * impulse * JwB; + cC -= m_mC * impulse * JvAC; + aC -= m_iC * impulse * JwC; + cD -= m_mD * impulse * JvBD; + aD -= m_iD * impulse * JwD; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + data.positions[m_indexC].c = cC; + data.positions[m_indexC].a = aC; + data.positions[m_indexD].c = cD; + data.positions[m_indexD].a = aD; + + // TODO_ERIN not implemented + return linearError < b2_linearSlop; +} + +b2Vec2 b2GearJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2GearJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P = m_impulse * m_JvAC; + return inv_dt * P; +} + +float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const +{ + float32 L = m_impulse * m_JwA; + return inv_dt * L; +} + +void b2GearJoint::SetRatio(float32 ratio) +{ + b2Assert(b2IsValid(ratio)); + m_ratio = ratio; +} + +float32 b2GearJoint::GetRatio() const +{ + return m_ratio; +} + +void b2GearJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + int32 index1 = m_joint1->m_index; + int32 index2 = m_joint2->m_index; + + b2Log(" b2GearJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.joint1 = joints[%d];\n", index1); + b2Log(" jd.joint2 = joints[%d];\n", index2); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2GearJoint.h b/external/box2d/Dynamics/Joints/b2GearJoint.h new file mode 100644 index 0000000000..f926bf6ef1 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2GearJoint.h @@ -0,0 +1,125 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_GEAR_JOINT_H +#define B2_GEAR_JOINT_H + +#include + +/// Gear joint definition. This definition requires two existing +/// revolute or prismatic joints (any combination will work). +struct b2GearJointDef : public b2JointDef +{ + b2GearJointDef() + { + type = e_gearJoint; + joint1 = NULL; + joint2 = NULL; + ratio = 1.0f; + } + + /// The first revolute/prismatic joint attached to the gear joint. + b2Joint* joint1; + + /// The second revolute/prismatic joint attached to the gear joint. + b2Joint* joint2; + + /// The gear ratio. + /// @see b2GearJoint for explanation. + float32 ratio; +}; + +/// A gear joint is used to connect two joints together. Either joint +/// can be a revolute or prismatic joint. You specify a gear ratio +/// to bind the motions together: +/// coordinate1 + ratio * coordinate2 = constant +/// The ratio can be negative or positive. If one joint is a revolute joint +/// and the other joint is a prismatic joint, then the ratio will have units +/// of length or units of 1/length. +/// @warning You have to manually destroy the gear joint if joint1 or joint2 +/// is destroyed. +class b2GearJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the first joint. + b2Joint* GetJoint1() { return m_joint1; } + + /// Get the second joint. + b2Joint* GetJoint2() { return m_joint2; } + + /// Set/Get the gear ratio. + void SetRatio(float32 ratio); + float32 GetRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2GearJoint(const b2GearJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Joint* m_joint1; + b2Joint* m_joint2; + + b2JointType m_typeA; + b2JointType m_typeB; + + // Body A is connected to body C + // Body B is connected to body D + b2Body* m_bodyC; + b2Body* m_bodyD; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localAnchorC; + b2Vec2 m_localAnchorD; + + b2Vec2 m_localAxisC; + b2Vec2 m_localAxisD; + + float32 m_referenceAngleA; + float32 m_referenceAngleB; + + float32 m_constant; + float32 m_ratio; + + float32 m_impulse; + + // Solver temp + int32 m_indexA, m_indexB, m_indexC, m_indexD; + b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; + float32 m_mA, m_mB, m_mC, m_mD; + float32 m_iA, m_iB, m_iC, m_iD; + b2Vec2 m_JvAC, m_JvBD; + float32 m_JwA, m_JwB, m_JwC, m_JwD; + float32 m_mass; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2Joint.cpp b/external/box2d/Dynamics/Joints/b2Joint.cpp new file mode 100644 index 0000000000..6853b09f0b --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2Joint.cpp @@ -0,0 +1,199 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) +{ + b2Joint* joint = NULL; + + switch (def->type) + { + case e_distanceJoint: + { + void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); + joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def); + } + break; + + case e_mouseJoint: + { + void* mem = allocator->Allocate(sizeof(b2MouseJoint)); + joint = new (mem) b2MouseJoint((b2MouseJointDef*)def); + } + break; + + case e_prismaticJoint: + { + void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); + joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def); + } + break; + + case e_revoluteJoint: + { + void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); + joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def); + } + break; + + case e_pulleyJoint: + { + void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); + joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def); + } + break; + + case e_gearJoint: + { + void* mem = allocator->Allocate(sizeof(b2GearJoint)); + joint = new (mem) b2GearJoint((b2GearJointDef*)def); + } + break; + + case e_wheelJoint: + { + void* mem = allocator->Allocate(sizeof(b2WheelJoint)); + joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); + } + break; + + case e_weldJoint: + { + void* mem = allocator->Allocate(sizeof(b2WeldJoint)); + joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); + } + break; + + case e_frictionJoint: + { + void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); + joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); + } + break; + + case e_ropeJoint: + { + void* mem = allocator->Allocate(sizeof(b2RopeJoint)); + joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); + } + break; + + default: + b2Assert(false); + break; + } + + return joint; +} + +void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) +{ + joint->~b2Joint(); + switch (joint->m_type) + { + case e_distanceJoint: + allocator->Free(joint, sizeof(b2DistanceJoint)); + break; + + case e_mouseJoint: + allocator->Free(joint, sizeof(b2MouseJoint)); + break; + + case e_prismaticJoint: + allocator->Free(joint, sizeof(b2PrismaticJoint)); + break; + + case e_revoluteJoint: + allocator->Free(joint, sizeof(b2RevoluteJoint)); + break; + + case e_pulleyJoint: + allocator->Free(joint, sizeof(b2PulleyJoint)); + break; + + case e_gearJoint: + allocator->Free(joint, sizeof(b2GearJoint)); + break; + + case e_wheelJoint: + allocator->Free(joint, sizeof(b2WheelJoint)); + break; + + case e_weldJoint: + allocator->Free(joint, sizeof(b2WeldJoint)); + break; + + case e_frictionJoint: + allocator->Free(joint, sizeof(b2FrictionJoint)); + break; + + case e_ropeJoint: + allocator->Free(joint, sizeof(b2RopeJoint)); + break; + + default: + b2Assert(false); + break; + } +} + +b2Joint::b2Joint(const b2JointDef* def) +{ + b2Assert(def->bodyA != def->bodyB); + + m_type = def->type; + m_prev = NULL; + m_next = NULL; + m_bodyA = def->bodyA; + m_bodyB = def->bodyB; + m_index = 0; + m_collideConnected = def->collideConnected; + m_islandFlag = false; + m_userData = def->userData; + + m_edgeA.joint = NULL; + m_edgeA.other = NULL; + m_edgeA.prev = NULL; + m_edgeA.next = NULL; + + m_edgeB.joint = NULL; + m_edgeB.other = NULL; + m_edgeB.prev = NULL; + m_edgeB.next = NULL; +} + +bool b2Joint::IsActive() const +{ + return m_bodyA->IsActive() && m_bodyB->IsActive(); +} diff --git a/external/box2d/Dynamics/Joints/b2Joint.h b/external/box2d/Dynamics/Joints/b2Joint.h new file mode 100644 index 0000000000..b4ea576665 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2Joint.h @@ -0,0 +1,222 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_JOINT_H +#define B2_JOINT_H + +#include + +class b2Body; +class b2Joint; +struct b2SolverData; +class b2BlockAllocator; + +enum b2JointType +{ + e_unknownJoint, + e_revoluteJoint, + e_prismaticJoint, + e_distanceJoint, + e_pulleyJoint, + e_mouseJoint, + e_gearJoint, + e_wheelJoint, + e_weldJoint, + e_frictionJoint, + e_ropeJoint +}; + +enum b2LimitState +{ + e_inactiveLimit, + e_atLowerLimit, + e_atUpperLimit, + e_equalLimits +}; + +struct b2Jacobian +{ + b2Vec2 linear; + float32 angularA; + float32 angularB; +}; + +/// A joint edge is used to connect bodies and joints together +/// in a joint graph where each body is a node and each joint +/// is an edge. A joint edge belongs to a doubly linked list +/// maintained in each attached body. Each joint has two joint +/// nodes, one for each attached body. +struct b2JointEdge +{ + b2Body* other; ///< provides quick access to the other body attached. + b2Joint* joint; ///< the joint + b2JointEdge* prev; ///< the previous joint edge in the body's joint list + b2JointEdge* next; ///< the next joint edge in the body's joint list +}; + +/// Joint definitions are used to construct joints. +struct b2JointDef +{ + b2JointDef() + { + type = e_unknownJoint; + userData = NULL; + bodyA = NULL; + bodyB = NULL; + collideConnected = false; + } + + /// The joint type is set automatically for concrete joint types. + b2JointType type; + + /// Use this to attach application specific data to your joints. + void* userData; + + /// The first attached body. + b2Body* bodyA; + + /// The second attached body. + b2Body* bodyB; + + /// Set this flag to true if the attached bodies should collide. + bool collideConnected; +}; + +/// The base joint class. Joints are used to constraint two bodies together in +/// various fashions. Some joints also feature limits and motors. +class b2Joint +{ +public: + + /// Get the type of the concrete joint. + b2JointType GetType() const; + + /// Get the first body attached to this joint. + b2Body* GetBodyA(); + + /// Get the second body attached to this joint. + b2Body* GetBodyB(); + + /// Get the anchor point on bodyA in world coordinates. + virtual b2Vec2 GetAnchorA() const = 0; + + /// Get the anchor point on bodyB in world coordinates. + virtual b2Vec2 GetAnchorB() const = 0; + + /// Get the reaction force on bodyB at the joint anchor in Newtons. + virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; + + /// Get the reaction torque on bodyB in N*m. + virtual float32 GetReactionTorque(float32 inv_dt) const = 0; + + /// Get the next joint the world joint list. + b2Joint* GetNext(); + const b2Joint* GetNext() const; + + /// Get the user data pointer. + void* GetUserData() const; + + /// Set the user data pointer. + void SetUserData(void* data); + + /// Short-cut function to determine if either body is inactive. + bool IsActive() const; + + /// Get collide connected. + /// Note: modifying the collide connect flag won't work correctly because + /// the flag is only checked when fixture AABBs begin to overlap. + bool GetCollideConnected() const; + + /// Dump this joint to the log file. + virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } + +protected: + friend class b2World; + friend class b2Body; + friend class b2Island; + friend class b2GearJoint; + + static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); + static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); + + b2Joint(const b2JointDef* def); + virtual ~b2Joint() {} + + virtual void InitVelocityConstraints(const b2SolverData& data) = 0; + virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; + + // This returns true if the position errors are within tolerance. + virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; + + b2JointType m_type; + b2Joint* m_prev; + b2Joint* m_next; + b2JointEdge m_edgeA; + b2JointEdge m_edgeB; + b2Body* m_bodyA; + b2Body* m_bodyB; + + int32 m_index; + + bool m_islandFlag; + bool m_collideConnected; + + void* m_userData; +}; + +inline b2JointType b2Joint::GetType() const +{ + return m_type; +} + +inline b2Body* b2Joint::GetBodyA() +{ + return m_bodyA; +} + +inline b2Body* b2Joint::GetBodyB() +{ + return m_bodyB; +} + +inline b2Joint* b2Joint::GetNext() +{ + return m_next; +} + +inline const b2Joint* b2Joint::GetNext() const +{ + return m_next; +} + +inline void* b2Joint::GetUserData() const +{ + return m_userData; +} + +inline void b2Joint::SetUserData(void* data) +{ + m_userData = data; +} + +inline bool b2Joint::GetCollideConnected() const +{ + return m_collideConnected; +} + +#endif diff --git a/external/box2d/Dynamics/Joints/b2MouseJoint.cpp b/external/box2d/Dynamics/Joints/b2MouseJoint.cpp new file mode 100644 index 0000000000..237d9d519a --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2MouseJoint.cpp @@ -0,0 +1,217 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// p = attached point, m = mouse point +// C = p - m +// Cdot = v +// = v + cross(w, r) +// J = [I r_skew] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) +: b2Joint(def) +{ + b2Assert(def->target.IsValid()); + b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); + b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); + b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); + + m_targetA = def->target; + m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); + + m_maxForce = def->maxForce; + m_impulse.SetZero(); + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_beta = 0.0f; + m_gamma = 0.0f; +} + +void b2MouseJoint::SetTarget(const b2Vec2& target) +{ + if (m_bodyB->IsAwake() == false) + { + m_bodyB->SetAwake(true); + } + m_targetA = target; +} + +const b2Vec2& b2MouseJoint::GetTarget() const +{ + return m_targetA; +} + +void b2MouseJoint::SetMaxForce(float32 force) +{ + m_maxForce = force; +} + +float32 b2MouseJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2MouseJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +float32 b2MouseJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +void b2MouseJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +float32 b2MouseJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + +void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexB = m_bodyB->m_islandIndex; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassB = m_bodyB->m_invMass; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qB(aB); + + float32 mass = m_bodyB->GetMass(); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * mass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = mass * (omega * omega); + + // magic formulas + // gamma has units of inverse mass. + // beta has units of inverse time. + float32 h = data.step.dt; + b2Assert(d + h * k > b2_epsilon); + m_gamma = h * (d + h * k); + if (m_gamma != 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + m_beta = h * k * m_gamma; + + // Compute the effective mass matrix. + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] + // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] + b2Mat22 K; + K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; + K.ex.y = -m_invIB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; + + m_mass = K.GetInverse(); + + m_C = cB + m_rB - m_targetA; + m_C *= m_beta; + + // Cheat with some damping + wB *= 0.98f; + + if (data.step.warmStarting) + { + m_impulse *= data.step.dtRatio; + vB += m_invMassB * m_impulse; + wB += m_invIB * b2Cross(m_rB, m_impulse); + } + else + { + m_impulse.SetZero(); + } + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = v + cross(w, r) + b2Vec2 Cdot = vB + b2Cross(wB, m_rB); + b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); + + b2Vec2 oldImpulse = m_impulse; + m_impulse += impulse; + float32 maxImpulse = data.step.dt * m_maxForce; + if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_impulse *= maxImpulse / m_impulse.Length(); + } + impulse = m_impulse - oldImpulse; + + vB += m_invMassB * impulse; + wB += m_invIB * b2Cross(m_rB, impulse); + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + return true; +} + +b2Vec2 b2MouseJoint::GetAnchorA() const +{ + return m_targetA; +} + +b2Vec2 b2MouseJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_impulse; +} + +float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * 0.0f; +} diff --git a/external/box2d/Dynamics/Joints/b2MouseJoint.h b/external/box2d/Dynamics/Joints/b2MouseJoint.h new file mode 100644 index 0000000000..1bbc194f4c --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2MouseJoint.h @@ -0,0 +1,126 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_MOUSE_JOINT_H +#define B2_MOUSE_JOINT_H + +#include + +/// Mouse joint definition. This requires a world target point, +/// tuning parameters, and the time step. +struct b2MouseJointDef : public b2JointDef +{ + b2MouseJointDef() + { + type = e_mouseJoint; + target.Set(0.0f, 0.0f); + maxForce = 0.0f; + frequencyHz = 5.0f; + dampingRatio = 0.7f; + } + + /// The initial world target point. This is assumed + /// to coincide with the body anchor initially. + b2Vec2 target; + + /// The maximum constraint force that can be exerted + /// to move the candidate body. Usually you will express + /// as some multiple of the weight (multiplier * mass * gravity). + float32 maxForce; + + /// The response speed. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A mouse joint is used to make a point on a body track a +/// specified world point. This a soft constraint with a maximum +/// force. This allows the constraint to stretch and without +/// applying huge forces. +/// NOTE: this joint is not documented in the manual because it was +/// developed to be used in the testbed. If you want to learn how to +/// use the mouse joint, look at the testbed. +class b2MouseJoint : public b2Joint +{ +public: + + /// Implements b2Joint. + b2Vec2 GetAnchorA() const; + + /// Implements b2Joint. + b2Vec2 GetAnchorB() const; + + /// Implements b2Joint. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Implements b2Joint. + float32 GetReactionTorque(float32 inv_dt) const; + + /// Use this to update the target point. + void SetTarget(const b2Vec2& target); + const b2Vec2& GetTarget() const; + + /// Set/get the maximum force in Newtons. + void SetMaxForce(float32 force); + float32 GetMaxForce() const; + + /// Set/get the frequency in Hertz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + /// Set/get the damping ratio (dimensionless). + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + + /// The mouse joint does not support dumping. + void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } + +protected: + friend class b2Joint; + + b2MouseJoint(const b2MouseJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_localAnchorB; + b2Vec2 m_targetA; + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_beta; + + // Solver shared + b2Vec2 m_impulse; + float32 m_maxForce; + float32 m_gamma; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rB; + b2Vec2 m_localCenterB; + float32 m_invMassB; + float32 m_invIB; + b2Mat22 m_mass; + b2Vec2 m_C; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp b/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp new file mode 100644 index 0000000000..4849f729f5 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp @@ -0,0 +1,637 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = p2 - p1 = x2 + r2 - x1 - r1 +// C = dot(perp, d) +// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) +// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] +// +// Angular constraint +// C = a2 - a1 + a_initial +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// +// K = J * invM * JT +// +// J = [-a -s1 a s2] +// [0 -1 0 1] +// a = perp +// s1 = cross(d + r1, a) = cross(p2 - x1, a) +// s2 = cross(r2, a) = cross(p2 - x2, a) + + +// Motor/Limit linear constraint +// C = dot(ax1, d) +// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) +// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] + +// Block Solver +// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even +// when the mass has poor distribution (leading to large torques about the joint anchor points). +// +// The Jacobian has 3 rows: +// J = [-uT -s1 uT s2] // linear +// [0 -1 0 1] // angular +// [-vT -a1 vT a2] // limit +// +// u = perp +// v = axis +// s1 = cross(d + r1, u), s2 = cross(r2, u) +// a1 = cross(d + r1, v), a2 = cross(r2, v) + +// M * (v2 - v1) = JT * df +// J * v2 = bias +// +// v2 = v1 + invM * JT * df +// J * (v1 + invM * JT * df) = bias +// K * df = bias - J * v1 = -Cdot +// K = J * invM * JT +// Cdot = J * v1 - bias +// +// Now solve for f2. +// df = f2 - f1 +// K * (f2 - f1) = -Cdot +// f2 = invK * (-Cdot) + f1 +// +// Clamp accumulated limit impulse. +// lower: f2(3) = max(f2(3), 0) +// upper: f2(3) = min(f2(3), 0) +// +// Solve for correct f2(1:2) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 +// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) +// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) +// +// Now compute impulse to be applied: +// df = f2 - f1 + +void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localXAxisA.Normalize(); + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + + m_lowerTranslation = def->lowerTranslation; + m_upperTranslation = def->upperTranslation; + m_maxMotorForce = def->maxMotorForce; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; + + m_axis.SetZero(); + m_perp.SetZero(); +} + +void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Compute motor Jacobian and effective mass. + { + m_axis = b2Mul(qA, m_localXAxisA); + m_a1 = b2Cross(d + rA, m_axis); + m_a2 = b2Cross(rB, m_axis); + + m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + + // Prismatic constraint. + { + m_perp = b2Mul(qA, m_localYAxisA); + + m_s1 = b2Cross(d + rA, m_perp); + m_s2 = b2Cross(rB, m_perp); + + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For bodies with fixed rotation. + k22 = 1.0f; + } + float32 k23 = iA * m_a1 + iB * m_a2; + float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + + m_K.ex.Set(k11, k12, k13); + m_K.ey.Set(k12, k22, k23); + m_K.ez.Set(k13, k23, k33); + } + + // Compute motor and limit terms. + if (m_enableLimit) + { + float32 jointTranslation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + m_limitState = e_equalLimits; + } + else if (jointTranslation <= m_lowerTranslation) + { + if (m_limitState != e_atLowerLimit) + { + m_limitState = e_atLowerLimit; + m_impulse.z = 0.0f; + } + } + else if (jointTranslation >= m_upperTranslation) + { + if (m_limitState != e_atUpperLimit) + { + m_limitState = e_atUpperLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } + + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; + float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; + float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Solve linear motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + float32 impulse = m_motorMass * (m_motorSpeed - Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorForce; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + b2Vec2 P = impulse * m_axis; + float32 LA = impulse * m_a1; + float32 LB = impulse * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + b2Vec2 Cdot1; + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; + + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + // Solve prismatic and limit constraint in block form. + float32 Cdot2; + Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 f1 = m_impulse; + b2Vec3 df = m_K.Solve33(-Cdot); + m_impulse += df; + + if (m_limitState == e_atLowerLimit) + { + m_impulse.z = b2Max(m_impulse.z, 0.0f); + } + else if (m_limitState == e_atUpperLimit) + { + m_impulse.z = b2Min(m_impulse.z, 0.0f); + } + + // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) + b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); + b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); + m_impulse.x = f2r.x; + m_impulse.y = f2r.y; + + df = m_impulse - f1; + + b2Vec2 P = df.x * m_perp + df.z * m_axis; + float32 LA = df.x * m_s1 + df.y + df.z * m_a1; + float32 LB = df.x * m_s2 + df.y + df.z * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + else + { + // Limit is inactive, just solve the prismatic constraint in block form. + b2Vec2 df = m_K.Solve22(-Cdot1); + m_impulse.x += df.x; + m_impulse.y += df.y; + + b2Vec2 P = df.x * m_perp; + float32 LA = df.x * m_s1 + df.y; + float32 LB = df.x * m_s2 + df.y; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + + b2Vec2 Cdot10 = Cdot1; + + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; + + if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) + { + b2Vec2 test = b2Mul22(m_K, df); + Cdot1.x += 0.0f; + } + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Compute fresh Jacobians + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + b2Vec2 axis = b2Mul(qA, m_localXAxisA); + float32 a1 = b2Cross(d + rA, axis); + float32 a2 = b2Cross(rB, axis); + b2Vec2 perp = b2Mul(qA, m_localYAxisA); + + float32 s1 = b2Cross(d + rA, perp); + float32 s2 = b2Cross(rB, perp); + + b2Vec3 impulse; + b2Vec2 C1; + C1.x = b2Dot(perp, d); + C1.y = aB - aA - m_referenceAngle; + + float32 linearError = b2Abs(C1.x); + float32 angularError = b2Abs(C1.y); + + bool active = false; + float32 C2 = 0.0f; + if (m_enableLimit) + { + float32 translation = b2Dot(axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + // Prevent large angular corrections + C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); + linearError = b2Max(linearError, b2Abs(translation)); + active = true; + } + else if (translation <= m_lowerTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); + linearError = b2Max(linearError, m_lowerTranslation - translation); + active = true; + } + else if (translation >= m_upperTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); + linearError = b2Max(linearError, translation - m_upperTranslation); + active = true; + } + } + + if (active) + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k13 = iA * s1 * a1 + iB * s2 * a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For fixed rotation + k22 = 1.0f; + } + float32 k23 = iA * a1 + iB * a2; + float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; + + b2Mat33 K; + K.ex.Set(k11, k12, k13); + K.ey.Set(k12, k22, k23); + K.ez.Set(k13, k23, k33); + + b2Vec3 C; + C.x = C1.x; + C.y = C1.y; + C.z = C2; + + impulse = K.Solve33(-C); + } + else + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + k22 = 1.0f; + } + + b2Mat22 K; + K.ex.Set(k11, k12); + K.ey.Set(k12, k22); + + b2Vec2 impulse1 = K.Solve(-C1); + impulse.x = impulse1.x; + impulse.y = impulse1.y; + impulse.z = 0.0f; + } + + b2Vec2 P = impulse.x * perp + impulse.z * axis; + float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; + float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; + + cA -= mA * P; + aA -= iA * LA; + cB += mB * P; + aB += iB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return linearError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2PrismaticJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2PrismaticJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); +} + +float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.y; +} + +float32 b2PrismaticJoint::GetJointTranslation() const +{ + b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2PrismaticJoint::GetJointSpeed() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); + b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); + b2Vec2 p1 = bA->m_sweep.c + rA; + b2Vec2 p2 = bB->m_sweep.c + rB; + b2Vec2 d = p2 - p1; + b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); + + b2Vec2 vA = bA->m_linearVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + float32 wB = bB->m_angularVelocity; + + float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); + return speed; +} + +bool b2PrismaticJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2PrismaticJoint::EnableLimit(bool flag) +{ + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } +} + +float32 b2PrismaticJoint::GetLowerLimit() const +{ + return m_lowerTranslation; +} + +float32 b2PrismaticJoint::GetUpperLimit() const +{ + return m_upperTranslation; +} + +void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + if (lower != m_lowerTranslation || upper != m_upperTranslation) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; + m_impulse.z = 0.0f; + } +} + +bool b2PrismaticJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2PrismaticJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2PrismaticJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2PrismaticJoint::SetMaxMotorForce(float32 force) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorForce = force; +} + +float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2PrismaticJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PrismaticJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); + b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2PrismaticJoint.h b/external/box2d/Dynamics/Joints/b2PrismaticJoint.h new file mode 100644 index 0000000000..aca2859b45 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2PrismaticJoint.h @@ -0,0 +1,196 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_PRISMATIC_JOINT_H +#define B2_PRISMATIC_JOINT_H + +#include + +/// Prismatic joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2PrismaticJointDef : public b2JointDef +{ + b2PrismaticJointDef() + { + type = e_prismaticJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + referenceAngle = 0.0f; + enableLimit = false; + lowerTranslation = 0.0f; + upperTranslation = 0.0f; + enableMotor = false; + maxMotorForce = 0.0f; + motorSpeed = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and unit world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The local translation unit axis in bodyA. + b2Vec2 localAxisA; + + /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. + float32 referenceAngle; + + /// Enable/disable the joint limit. + bool enableLimit; + + /// The lower translation limit, usually in meters. + float32 lowerTranslation; + + /// The upper translation limit, usually in meters. + float32 upperTranslation; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorForce; + + /// The desired motor speed in radians per second. + float32 motorSpeed; +}; + +/// A prismatic joint. This joint provides one degree of freedom: translation +/// along an axis fixed in bodyA. Relative rotation is prevented. You can +/// use a joint limit to restrict the range of motion and a joint motor to +/// drive the motion or to model joint friction. +class b2PrismaticJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint limit enabled? + bool IsLimitEnabled() const; + + /// Enable/disable the joint limit. + void EnableLimit(bool flag); + + /// Get the lower joint limit, usually in meters. + float32 GetLowerLimit() const; + + /// Get the upper joint limit, usually in meters. + float32 GetUpperLimit() const; + + /// Set the joint limits, usually in meters. + void SetLimits(float32 lower, float32 upper); + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in meters per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in meters per second. + float32 GetMotorSpeed() const; + + /// Set the maximum motor force, usually in N. + void SetMaxMotorForce(float32 force); + float32 GetMaxMotorForce() const { return m_maxMotorForce; } + + /// Get the current motor force given the inverse time step, usually in N. + float32 GetMotorForce(float32 inv_dt) const; + + /// Dump to b2Log + void Dump(); + +protected: + friend class b2Joint; + friend class b2GearJoint; + b2PrismaticJoint(const b2PrismaticJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + float32 m_referenceAngle; + b2Vec3 m_impulse; + float32 m_motorImpulse; + float32 m_lowerTranslation; + float32 m_upperTranslation; + float32 m_maxMotorForce; + float32 m_motorSpeed; + bool m_enableLimit; + bool m_enableMotor; + b2LimitState m_limitState; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + b2Mat33 m_K; + float32 m_motorMass; +}; + +inline float32 b2PrismaticJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +#endif diff --git a/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp b/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp new file mode 100644 index 0000000000..da30fae222 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp @@ -0,0 +1,332 @@ +/* +* Copyright (c) 2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Pulley: +// length1 = norm(p1 - s1) +// length2 = norm(p2 - s2) +// C0 = (length1 + ratio * length2)_initial +// C = C0 - (length1 + ratio * length2) +// u1 = (p1 - s1) / norm(p1 - s1) +// u2 = (p2 - s2) / norm(p2 - s2) +// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) +// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] +// K = J * invM * JT +// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) + +void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, + const b2Vec2& groundA, const b2Vec2& groundB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 r) +{ + bodyA = bA; + bodyB = bB; + groundAnchorA = groundA; + groundAnchorB = groundB; + localAnchorA = bodyA->GetLocalPoint(anchorA); + localAnchorB = bodyB->GetLocalPoint(anchorB); + b2Vec2 dA = anchorA - groundA; + lengthA = dA.Length(); + b2Vec2 dB = anchorB - groundB; + lengthB = dB.Length(); + ratio = r; + b2Assert(ratio > b2_epsilon); +} + +b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) +: b2Joint(def) +{ + m_groundAnchorA = def->groundAnchorA; + m_groundAnchorB = def->groundAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_lengthA = def->lengthA; + m_lengthB = def->lengthB; + + b2Assert(def->ratio != 0.0f); + m_ratio = def->ratio; + + m_constant = def->lengthA + m_ratio * def->lengthB; + + m_impulse = 0.0f; +} + +void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // Get the pulley axes. + m_uA = cA + m_rA - m_groundAnchorA; + m_uB = cB + m_rB - m_groundAnchorB; + + float32 lengthA = m_uA.Length(); + float32 lengthB = m_uB.Length(); + + if (lengthA > 10.0f * b2_linearSlop) + { + m_uA *= 1.0f / lengthA; + } + else + { + m_uA.SetZero(); + } + + if (lengthB > 10.0f * b2_linearSlop) + { + m_uB *= 1.0f / lengthB; + } + else + { + m_uB.SetZero(); + } + + // Compute effective mass. + float32 ruA = b2Cross(m_rA, m_uA); + float32 ruB = b2Cross(m_rB, m_uB); + + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; + + m_mass = mA + m_ratio * m_ratio * mB; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + + if (data.step.warmStarting) + { + // Scale impulses to support variable time steps. + m_impulse *= data.step.dtRatio; + + // Warm starting. + b2Vec2 PA = -(m_impulse) * m_uA; + b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; + + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + + float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + b2Vec2 PA = -impulse * m_uA; + b2Vec2 PB = -m_ratio * impulse * m_uB; + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // Get the pulley axes. + b2Vec2 uA = cA + rA - m_groundAnchorA; + b2Vec2 uB = cB + rB - m_groundAnchorB; + + float32 lengthA = uA.Length(); + float32 lengthB = uB.Length(); + + if (lengthA > 10.0f * b2_linearSlop) + { + uA *= 1.0f / lengthA; + } + else + { + uA.SetZero(); + } + + if (lengthB > 10.0f * b2_linearSlop) + { + uB *= 1.0f / lengthB; + } + else + { + uB.SetZero(); + } + + // Compute effective mass. + float32 ruA = b2Cross(rA, uA); + float32 ruB = b2Cross(rB, uB); + + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; + + float32 mass = mA + m_ratio * m_ratio * mB; + + if (mass > 0.0f) + { + mass = 1.0f / mass; + } + + float32 C = m_constant - lengthA - m_ratio * lengthB; + float32 linearError = b2Abs(C); + + float32 impulse = -mass * C; + + b2Vec2 PA = -impulse * uA; + b2Vec2 PB = -m_ratio * impulse * uB; + + cA += m_invMassA * PA; + aA += m_invIA * b2Cross(rA, PA); + cB += m_invMassB * PB; + aB += m_invIB * b2Cross(rB, PB); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return linearError < b2_linearSlop; +} + +b2Vec2 b2PulleyJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2PulleyJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P = m_impulse * m_uB; + return inv_dt * P; +} + +float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +b2Vec2 b2PulleyJoint::GetGroundAnchorA() const +{ + return m_groundAnchorA; +} + +b2Vec2 b2PulleyJoint::GetGroundAnchorB() const +{ + return m_groundAnchorB; +} + +float32 b2PulleyJoint::GetLengthA() const +{ + b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 s = m_groundAnchorA; + b2Vec2 d = p - s; + return d.Length(); +} + +float32 b2PulleyJoint::GetLengthB() const +{ + b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 s = m_groundAnchorB; + b2Vec2 d = p - s; + return d.Length(); +} + +float32 b2PulleyJoint::GetRatio() const +{ + return m_ratio; +} + +void b2PulleyJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PulleyJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); + b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); + b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2PulleyJoint.h b/external/box2d/Dynamics/Joints/b2PulleyJoint.h new file mode 100644 index 0000000000..2f6df4395c --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2PulleyJoint.h @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_PULLEY_JOINT_H +#define B2_PULLEY_JOINT_H + +#include + +const float32 b2_minPulleyLength = 2.0f; + +/// Pulley joint definition. This requires two ground anchors, +/// two dynamic body anchor points, and a pulley ratio. +struct b2PulleyJointDef : public b2JointDef +{ + b2PulleyJointDef() + { + type = e_pulleyJoint; + groundAnchorA.Set(-1.0f, 1.0f); + groundAnchorB.Set(1.0f, 1.0f); + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + lengthA = 0.0f; + lengthB = 0.0f; + ratio = 1.0f; + collideConnected = true; + } + + /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 ratio); + + /// The first ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorA; + + /// The second ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorB; + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The a reference length for the segment attached to bodyA. + float32 lengthA; + + /// The a reference length for the segment attached to bodyB. + float32 lengthB; + + /// The pulley ratio, used to simulate a block-and-tackle. + float32 ratio; +}; + +/// The pulley joint is connected to two bodies and two fixed ground points. +/// The pulley supports a ratio such that: +/// length1 + ratio * length2 <= constant +/// Yes, the force transmitted is scaled by the ratio. +/// Warning: the pulley joint can get a bit squirrelly by itself. They often +/// work better when combined with prismatic joints. You should also cover the +/// the anchor points with static shapes to prevent one side from going to +/// zero length. +class b2PulleyJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the first ground anchor. + b2Vec2 GetGroundAnchorA() const; + + /// Get the second ground anchor. + b2Vec2 GetGroundAnchorB() const; + + /// Get the current length of the segment attached to bodyA. + float32 GetLengthA() const; + + /// Get the current length of the segment attached to bodyB. + float32 GetLengthB() const; + + /// Get the pulley ratio. + float32 GetRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2PulleyJoint(const b2PulleyJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_groundAnchorA; + b2Vec2 m_groundAnchorB; + float32 m_lengthA; + float32 m_lengthB; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_constant; + float32 m_ratio; + float32 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_uA; + b2Vec2 m_uB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp b/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp new file mode 100644 index 0000000000..e265d8192b --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp @@ -0,0 +1,504 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Motor constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + + m_lowerAngle = def->lowerAngle; + m_upperAngle = def->upperAngle; + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; +} + +void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + bool fixedRotation = (iA + iB == 0.0f); + + m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; + + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + + if (m_enableMotor == false || fixedRotation) + { + m_motorImpulse = 0.0f; + } + + if (m_enableLimit && fixedRotation == false) + { + float32 jointAngle = aB - aA - m_referenceAngle; + if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) + { + m_limitState = e_equalLimits; + } + else if (jointAngle <= m_lowerAngle) + { + if (m_limitState != e_atLowerLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atLowerLimit; + } + else if (jointAngle >= m_upperAngle) + { + if (m_limitState != e_atUpperLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atUpperLimit; + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + bool fixedRotation = (iA + iB == 0.0f); + + // Solve motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = -m_mass.Solve33(Cdot); + + if (m_limitState == e_equalLimits) + { + m_impulse += impulse; + } + else if (m_limitState == e_atLowerLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse < 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } + else if (m_limitState == e_atUpperLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse > 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } + else + { + // Solve point-to-point constraint + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + b2Vec2 impulse = m_mass.Solve22(-Cdot); + + m_impulse.x += impulse.x; + m_impulse.y += impulse.y; + + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 angularError = 0.0f; + float32 positionError = 0.0f; + + bool fixedRotation = (m_invIA + m_invIB == 0.0f); + + // Solve angular limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + float32 angle = aB - aA - m_referenceAngle; + float32 limitImpulse = 0.0f; + + if (m_limitState == e_equalLimits) + { + // Prevent large angular corrections + float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + angularError = b2Abs(C); + } + else if (m_limitState == e_atLowerLimit) + { + float32 C = angle - m_lowerAngle; + angularError = -C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); + limitImpulse = -m_motorMass * C; + } + else if (m_limitState == e_atUpperLimit) + { + float32 C = angle - m_upperAngle; + angularError = C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + } + + aA -= m_invIA * limitImpulse; + aB += m_invIB * limitImpulse; + } + + // Solve point-to-point constraint. + { + qA.Set(aA); + qB.Set(aB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + b2Vec2 C = cB + rB - cA - rA; + positionError = C.Length(); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat22 K; + K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; + K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; + + b2Vec2 impulse = -K.Solve(C); + + cA -= mA * impulse; + aA -= iA * b2Cross(rA, impulse); + + cB += mB * impulse; + aB += iB * b2Cross(rB, impulse); + } + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2RevoluteJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2RevoluteJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} + +float32 b2RevoluteJoint::GetJointAngle() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; +} + +float32 b2RevoluteJoint::GetJointSpeed() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_angularVelocity - bA->m_angularVelocity; +} + +bool b2RevoluteJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2RevoluteJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2RevoluteJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +bool b2RevoluteJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2RevoluteJoint::EnableLimit(bool flag) +{ + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } +} + +float32 b2RevoluteJoint::GetLowerLimit() const +{ + return m_lowerAngle; +} + +float32 b2RevoluteJoint::GetUpperLimit() const +{ + return m_upperAngle; +} + +void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + + if (lower != m_lowerAngle || upper != m_upperAngle) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_impulse.z = 0.0f; + m_lowerAngle = lower; + m_upperAngle = upper; + } +} + +void b2RevoluteJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RevoluteJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); + b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2RevoluteJoint.h b/external/box2d/Dynamics/Joints/b2RevoluteJoint.h new file mode 100644 index 0000000000..978f16259a --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2RevoluteJoint.h @@ -0,0 +1,204 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_REVOLUTE_JOINT_H +#define B2_REVOLUTE_JOINT_H + +#include + +/// Revolute joint definition. This requires defining an +/// anchor point where the bodies are joined. The definition +/// uses local anchor points so that the initial configuration +/// can violate the constraint slightly. You also need to +/// specify the initial relative angle for joint limits. This +/// helps when saving and loading a game. +/// The local anchor points are measured from the body's origin +/// rather than the center of mass because: +/// 1. you might not know where the center of mass will be. +/// 2. if you add/remove shapes from a body and recompute the mass, +/// the joints will be broken. +struct b2RevoluteJointDef : public b2JointDef +{ + b2RevoluteJointDef() + { + type = e_revoluteJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + lowerAngle = 0.0f; + upperAngle = 0.0f; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + enableLimit = false; + enableMotor = false; + } + + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; + + /// A flag to enable joint limits. + bool enableLimit; + + /// The lower angle for the joint limit (radians). + float32 lowerAngle; + + /// The upper angle for the joint limit (radians). + float32 upperAngle; + + /// A flag to enable the joint motor. + bool enableMotor; + + /// The desired motor speed. Usually in radians per second. + float32 motorSpeed; + + /// The maximum motor torque used to achieve the desired motor speed. + /// Usually in N-m. + float32 maxMotorTorque; +}; + +/// A revolute joint constrains two bodies to share a common point while they +/// are free to rotate about the point. The relative rotation about the shared +/// point is the joint angle. You can limit the relative rotation with +/// a joint limit that specifies a lower and upper angle. You can use a motor +/// to drive the relative rotation about the shared point. A maximum motor torque +/// is provided so that infinite forces are not generated. +class b2RevoluteJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Get the current joint angle in radians. + float32 GetJointAngle() const; + + /// Get the current joint angle speed in radians per second. + float32 GetJointSpeed() const; + + /// Is the joint limit enabled? + bool IsLimitEnabled() const; + + /// Enable/disable the joint limit. + void EnableLimit(bool flag); + + /// Get the lower joint limit in radians. + float32 GetLowerLimit() const; + + /// Get the upper joint limit in radians. + float32 GetUpperLimit() const; + + /// Set the joint limits in radians. + void SetLimits(float32 lower, float32 upper); + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed in radians per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed in radians per second. + float32 GetMotorSpeed() const; + + /// Set the maximum motor torque, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } + + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque due to the joint limit given the inverse time step. + /// Unit is N*m. + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the current motor torque given the inverse time step. + /// Unit is N*m. + float32 GetMotorTorque(float32 inv_dt) const; + + /// Dump to b2Log. + void Dump(); + +protected: + + friend class b2Joint; + friend class b2GearJoint; + + b2RevoluteJoint(const b2RevoluteJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec3 m_impulse; + float32 m_motorImpulse; + + bool m_enableMotor; + float32 m_maxMotorTorque; + float32 m_motorSpeed; + + bool m_enableLimit; + float32 m_referenceAngle; + float32 m_lowerAngle; + float32 m_upperAngle; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; // effective mass for point-to-point constraint. + float32 m_motorMass; // effective mass for motor/limit angular constraint. + b2LimitState m_limitState; +}; + +inline float32 b2RevoluteJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +#endif diff --git a/external/box2d/Dynamics/Joints/b2RopeJoint.cpp b/external/box2d/Dynamics/Joints/b2RopeJoint.cpp new file mode 100644 index 0000000000..17a70d9230 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2RopeJoint.cpp @@ -0,0 +1,241 @@ +/* +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + + +// Limit: +// C = norm(pB - pA) - L +// u = (pB - pA) / norm(pB - pA) +// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) +// J = [-u -cross(rA, u) u cross(rB, u)] +// K = J * invM * JT +// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 + +b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_maxLength = def->maxLength; + + m_mass = 0.0f; + m_impulse = 0.0f; + m_state = e_inactiveLimit; + m_length = 0.0f; +} + +void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; + + m_length = m_u.Length(); + + float32 C = m_length - m_maxLength; + if (C > 0.0f) + { + m_state = e_atUpperLimit; + } + else + { + m_state = e_inactiveLimit; + } + + if (m_length > b2_linearSlop) + { + m_u *= 1.0f / m_length; + } + else + { + m_u.SetZero(); + m_mass = 0.0f; + m_impulse = 0.0f; + return; + } + + // Compute effective mass. + float32 crA = b2Cross(m_rA, m_u); + float32 crB = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; + + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 C = m_length - m_maxLength; + float32 Cdot = b2Dot(m_u, vpB - vpA); + + // Predictive constraint. + if (C < 0.0f) + { + Cdot += data.step.inv_dt * C; + } + + float32 impulse = -m_mass * Cdot; + float32 oldImpulse = m_impulse; + m_impulse = b2Min(0.0f, m_impulse + impulse); + impulse = m_impulse - oldImpulse; + + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; + + float32 length = u.Normalize(); + float32 C = length - m_maxLength; + + C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); + + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; + + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return length - m_maxLength < b2_linearSlop; +} + +b2Vec2 b2RopeJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2RopeJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; +} + +float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +float32 b2RopeJoint::GetMaxLength() const +{ + return m_maxLength; +} + +b2LimitState b2RopeJoint::GetLimitState() const +{ + return m_state; +} + +void b2RopeJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RopeJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2RopeJoint.h b/external/box2d/Dynamics/Joints/b2RopeJoint.h new file mode 100644 index 0000000000..d7091b6650 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2RopeJoint.h @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_JOINT_H +#define B2_ROPE_JOINT_H + +#include + +/// Rope joint definition. This requires two body anchor points and +/// a maximum lengths. +/// Note: by default the connected objects will not collide. +/// see collideConnected in b2JointDef. +struct b2RopeJointDef : public b2JointDef +{ + b2RopeJointDef() + { + type = e_ropeJoint; + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + maxLength = 0.0f; + } + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum length of the rope. + /// Warning: this must be larger than b2_linearSlop or + /// the joint will have no effect. + float32 maxLength; +}; + +/// A rope joint enforces a maximum distance between two points +/// on two bodies. It has no other effect. +/// Warning: if you attempt to change the maximum length during +/// the simulation you will get some non-physical behavior. +/// A model that would allow you to dynamically modify the length +/// would have some sponginess, so I chose not to implement it +/// that way. See b2DistanceJoint if you want to dynamically +/// control length. +class b2RopeJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set/Get the maximum length of the rope. + void SetMaxLength(float32 length) { m_maxLength = length; } + float32 GetMaxLength() const; + + b2LimitState GetLimitState() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2RopeJoint(const b2RopeJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_maxLength; + float32 m_length; + float32 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; + b2LimitState m_state; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2WeldJoint.cpp b/external/box2d/Dynamics/Joints/b2WeldJoint.cpp new file mode 100644 index 0000000000..f50bdd6587 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2WeldJoint.cpp @@ -0,0 +1,330 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// C = angle2 - angle1 - referenceAngle +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_impulse.SetZero(); +} + +void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat33 K; + K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + K.ez.x = -m_rA.y * iA - m_rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + K.ez.y = m_rA.x * iA + m_rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; + + if (m_frequencyHz > 0.0f) + { + K.GetInverse22(&m_mass); + + float32 invM = iA + iB; + float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; + + float32 C = aB - aA - m_referenceAngle; + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; + + invM += m_gamma; + m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; + } + else + { + K.GetSymInverse33(&m_mass); + m_gamma = 0.0f; + m_bias = 0.0f; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_impulse.z); + } + else + { + m_impulse.SetZero(); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + if (m_frequencyHz > 0.0f) + { + float32 Cdot2 = wB - wA; + + float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); + m_impulse.z += impulse2; + + wA -= iA * impulse2; + wB += iB * impulse2; + + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + + b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); + m_impulse.x += impulse1.x; + m_impulse.y += impulse1.y; + + b2Vec2 P = impulse1; + + vA -= mA * P; + wA -= iA * b2Cross(m_rA, P); + + vB += mB * P; + wB += iB * b2Cross(m_rB, P); + } + else + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = -b2Mul(m_mass, Cdot); + m_impulse += impulse; + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + float32 positionError, angularError; + + b2Mat33 K; + K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + K.ez.x = -rA.y * iA - rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + K.ez.y = rA.x * iA + rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; + + if (m_frequencyHz > 0.0f) + { + b2Vec2 C1 = cB + rB - cA - rA; + + positionError = C1.Length(); + angularError = 0.0f; + + b2Vec2 P = -K.Solve22(C1); + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + else + { + b2Vec2 C1 = cB + rB - cA - rA; + float32 C2 = aB - aA - m_referenceAngle; + + positionError = C1.Length(); + angularError = b2Abs(C2); + + b2Vec3 C(C1.x, C1.y, C2); + + b2Vec3 impulse = -K.Solve33(C); + b2Vec2 P(impulse.x, impulse.y); + + cA -= mA * P; + aA -= iA * (b2Cross(rA, P) + impulse.z); + + cB += mB * P; + aB += iB * (b2Cross(rB, P) + impulse.z); + } + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2WeldJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WeldJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} + +void b2WeldJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2WeldJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2WeldJoint.h b/external/box2d/Dynamics/Joints/b2WeldJoint.h new file mode 100644 index 0000000000..751c6a8770 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2WeldJoint.h @@ -0,0 +1,126 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WELD_JOINT_H +#define B2_WELD_JOINT_H + +#include + +/// Weld joint definition. You need to specify local anchor points +/// where they are attached and the relative body angle. The position +/// of the anchor points is important for computing the reaction torque. +struct b2WeldJointDef : public b2JointDef +{ + b2WeldJointDef() + { + type = e_weldJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } + + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; + + /// The mass-spring-damper frequency in Hertz. Rotation only. + /// Disable softness with a value of 0. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A weld joint essentially glues two bodies together. A weld joint may +/// distort somewhat because the island constraint solver is approximate. +class b2WeldJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Set/get frequency in Hz. + void SetFrequency(float32 hz) { m_frequencyHz = hz; } + float32 GetFrequency() const { return m_frequencyHz; } + + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } + float32 GetDampingRatio() const { return m_dampingRatio; } + + /// Dump to b2Log + void Dump(); + +protected: + + friend class b2Joint; + + b2WeldJoint(const b2WeldJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_referenceAngle; + float32 m_gamma; + b2Vec3 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; +}; + +#endif diff --git a/external/box2d/Dynamics/Joints/b2WheelJoint.cpp b/external/box2d/Dynamics/Joints/b2WheelJoint.cpp new file mode 100644 index 0000000000..6253437706 --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2WheelJoint.cpp @@ -0,0 +1,419 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = pB - pA = xB + rB - xA - rA +// C = dot(ay, d) +// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) +// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) +// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] + +// Spring linear constraint +// C = dot(ax, d) +// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) +// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] + +// Motor rotational constraint +// Cdot = wB - wA +// J = [0 0 -1 0 0 1] + +void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); +} + +b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + + m_mass = 0.0f; + m_impulse = 0.0f; + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + m_springMass = 0.0f; + m_springImpulse = 0.0f; + + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableMotor = def->enableMotor; + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_bias = 0.0f; + m_gamma = 0.0f; + + m_ax.SetZero(); + m_ay.SetZero(); +} + +void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + // Point to line constraint + { + m_ay = b2Mul(qA, m_localYAxisA); + m_sAy = b2Cross(d + rA, m_ay); + m_sBy = b2Cross(rB, m_ay); + + m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + } + + // Spring constraint + m_springMass = 0.0f; + m_bias = 0.0f; + m_gamma = 0.0f; + if (m_frequencyHz > 0.0f) + { + m_ax = b2Mul(qA, m_localXAxisA); + m_sAx = b2Cross(d + rA, m_ax); + m_sBx = b2Cross(rB, m_ax); + + float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; + + if (invMass > 0.0f) + { + m_springMass = 1.0f / invMass; + + float32 C = b2Dot(d, m_ax); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m_springMass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m_springMass * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + if (m_gamma > 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + + m_bias = C * h * k * m_gamma; + + m_springMass = invMass + m_gamma; + if (m_springMass > 0.0f) + { + m_springMass = 1.0f / m_springMass; + } + } + } + else + { + m_springImpulse = 0.0f; + } + + // Rotational motor + if (m_enableMotor) + { + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + else + { + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; + } + + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_springImpulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; + float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; + float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; + + vA -= m_invMassA * P; + wA -= m_invIA * LA; + + vB += m_invMassB * P; + wB += m_invIB * LB; + } + else + { + m_impulse = 0.0f; + m_springImpulse = 0.0f; + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Solve spring constraint + { + float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; + float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); + m_springImpulse += impulse; + + b2Vec2 P = impulse * m_ax; + float32 LA = impulse * m_sAx; + float32 LB = impulse * m_sBx; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + // Solve rotational motor constraint + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve point to line constraint + { + float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + b2Vec2 P = impulse * m_ay; + float32 LA = impulse * m_sAy; + float32 LB = impulse * m_sBy; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; + + b2Vec2 ay = b2Mul(qA, m_localYAxisA); + + float32 sAy = b2Cross(d + rA, ay); + float32 sBy = b2Cross(rB, ay); + + float32 C = b2Dot(d, ay); + + float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; + + float32 impulse; + if (k != 0.0f) + { + impulse = - C / k; + } + else + { + impulse = 0.0f; + } + + b2Vec2 P = impulse * ay; + float32 LA = impulse * sAy; + float32 LB = impulse * sBy; + + cA -= m_invMassA * P; + aA -= m_invIA * LA; + cB += m_invMassB * P; + aB += m_invIB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return b2Abs(C) <= b2_linearSlop; +} + +b2Vec2 b2WheelJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WheelJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); +} + +float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +float32 b2WheelJoint::GetJointTranslation() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2WheelJoint::GetJointSpeed() const +{ + float32 wA = m_bodyA->m_angularVelocity; + float32 wB = m_bodyB->m_angularVelocity; + return wB - wA; +} + +bool b2WheelJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2WheelJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2WheelJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2WheelJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2WheelJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2WheelJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/box2d/Dynamics/Joints/b2WheelJoint.h b/external/box2d/Dynamics/Joints/b2WheelJoint.h new file mode 100644 index 0000000000..ede1b08b7c --- /dev/null +++ b/external/box2d/Dynamics/Joints/b2WheelJoint.h @@ -0,0 +1,213 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WHEEL_JOINT_H +#define B2_WHEEL_JOINT_H + +#include + +/// Wheel joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2WheelJointDef : public b2JointDef +{ + b2WheelJointDef() + { + type = e_wheelJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + enableMotor = false; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + frequencyHz = 2.0f; + dampingRatio = 0.7f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The local translation axis in bodyA. + b2Vec2 localAxisA; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorTorque; + + /// The desired motor speed in radians per second. + float32 motorSpeed; + + /// Suspension frequency, zero indicates no suspension + float32 frequencyHz; + + /// Suspension damping ratio, one indicates critical damping + float32 dampingRatio; +}; + +/// A wheel joint. This joint provides two degrees of freedom: translation +/// along an axis fixed in bodyA and rotation in the plane. You can use a +/// joint limit to restrict the range of motion and a joint motor to drive +/// the rotation or to model rotational friction. +/// This joint is designed for vehicle suspensions. +class b2WheelJoint : public b2Joint +{ +public: + void GetDefinition(b2WheelJointDef* def) const; + + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in radians per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in radians per second. + float32 GetMotorSpeed() const; + + /// Set/Get the maximum motor force, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const; + + /// Get the current motor torque given the inverse time step, usually in N-m. + float32 GetMotorTorque(float32 inv_dt) const; + + /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. + void SetSpringFrequencyHz(float32 hz); + float32 GetSpringFrequencyHz() const; + + /// Set/Get the spring damping ratio + void SetSpringDampingRatio(float32 ratio); + float32 GetSpringDampingRatio() const; + + /// Dump to b2Log + void Dump(); + +protected: + + friend class b2Joint; + b2WheelJoint(const b2WheelJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + + float32 m_impulse; + float32 m_motorImpulse; + float32 m_springImpulse; + + float32 m_maxMotorTorque; + float32 m_motorSpeed; + bool m_enableMotor; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + + b2Vec2 m_ax, m_ay; + float32 m_sAx, m_sBx; + float32 m_sAy, m_sBy; + + float32 m_mass; + float32 m_motorMass; + float32 m_springMass; + + float32 m_bias; + float32 m_gamma; +}; + +inline float32 b2WheelJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +inline float32 b2WheelJoint::GetMaxMotorTorque() const +{ + return m_maxMotorTorque; +} + +inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2WheelJoint::GetSpringFrequencyHz() const +{ + return m_frequencyHz; +} + +inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2WheelJoint::GetSpringDampingRatio() const +{ + return m_dampingRatio; +} + +#endif diff --git a/external/box2d/Dynamics/b2Body.cpp b/external/box2d/Dynamics/b2Body.cpp new file mode 100644 index 0000000000..b22b574023 --- /dev/null +++ b/external/box2d/Dynamics/b2Body.cpp @@ -0,0 +1,514 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2Body::b2Body(const b2BodyDef* bd, b2World* world) +{ + b2Assert(bd->position.IsValid()); + b2Assert(bd->linearVelocity.IsValid()); + b2Assert(b2IsValid(bd->angle)); + b2Assert(b2IsValid(bd->angularVelocity)); + b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); + b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); + + m_flags = 0; + + if (bd->bullet) + { + m_flags |= e_bulletFlag; + } + if (bd->fixedRotation) + { + m_flags |= e_fixedRotationFlag; + } + if (bd->allowSleep) + { + m_flags |= e_autoSleepFlag; + } + if (bd->awake) + { + m_flags |= e_awakeFlag; + } + if (bd->active) + { + m_flags |= e_activeFlag; + } + + m_world = world; + + m_xf.p = bd->position; + m_xf.q.Set(bd->angle); + + m_sweep.localCenter.SetZero(); + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = bd->angle; + m_sweep.a = bd->angle; + m_sweep.alpha0 = 0.0f; + + m_jointList = NULL; + m_contactList = NULL; + m_prev = NULL; + m_next = NULL; + + m_linearVelocity = bd->linearVelocity; + m_angularVelocity = bd->angularVelocity; + + m_linearDamping = bd->linearDamping; + m_angularDamping = bd->angularDamping; + m_gravityScale = bd->gravityScale; + + m_force.SetZero(); + m_torque = 0.0f; + + m_sleepTime = 0.0f; + + m_type = bd->type; + + if (m_type == b2_dynamicBody) + { + m_mass = 1.0f; + m_invMass = 1.0f; + } + else + { + m_mass = 0.0f; + m_invMass = 0.0f; + } + + m_I = 0.0f; + m_invI = 0.0f; + + m_userData = bd->userData; + + m_fixtureList = NULL; + m_fixtureCount = 0; +} + +b2Body::~b2Body() +{ + // shapes and joints are destroyed in b2World::Destroy +} + +void b2Body::SetType(b2BodyType type) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + if (m_type == type) + { + return; + } + + m_type = type; + + ResetMassData(); + + if (m_type == b2_staticBody) + { + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_sweep.a0 = m_sweep.a; + m_sweep.c0 = m_sweep.c; + SynchronizeFixtures(); + } + + SetAwake(true); + + m_force.SetZero(); + m_torque = 0.0f; + + // Since the body type changed, we need to flag contacts for filtering. + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Refilter(); + } +} + +b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return NULL; + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + void* memory = allocator->Allocate(sizeof(b2Fixture)); + b2Fixture* fixture = new (memory) b2Fixture; + fixture->Create(allocator, this, def); + + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->CreateProxies(broadPhase, m_xf); + } + + fixture->m_next = m_fixtureList; + m_fixtureList = fixture; + ++m_fixtureCount; + + fixture->m_body = this; + + // Adjust mass properties if needed. + if (fixture->m_density > 0.0f) + { + ResetMassData(); + } + + // Let the world know we have a new fixture. This will cause new contacts + // to be created at the beginning of the next time step. + m_world->m_flags |= b2World::e_newFixture; + + return fixture; +} + +b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) +{ + b2FixtureDef def; + def.shape = shape; + def.density = density; + + return CreateFixture(&def); +} + +void b2Body::DestroyFixture(b2Fixture* fixture) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + b2Assert(fixture->m_body == this); + + // Remove the fixture from this body's singly linked list. + b2Assert(m_fixtureCount > 0); + b2Fixture** node = &m_fixtureList; + bool found = false; + while (*node != NULL) + { + if (*node == fixture) + { + *node = fixture->m_next; + found = true; + break; + } + + node = &(*node)->m_next; + } + + // You tried to remove a shape that is not attached to this body. + b2Assert(found); + + // Destroy any contacts associated with the fixture. + b2ContactEdge* edge = m_contactList; + while (edge) + { + b2Contact* c = edge->contact; + edge = edge->next; + + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + + if (fixture == fixtureA || fixture == fixtureB) + { + // This destroys the contact and removes it from + // this body's contact list. + m_world->m_contactManager.Destroy(c); + } + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->DestroyProxies(broadPhase); + } + + fixture->Destroy(allocator); + fixture->m_body = NULL; + fixture->m_next = NULL; + fixture->~b2Fixture(); + allocator->Free(fixture, sizeof(b2Fixture)); + + --m_fixtureCount; + + // Reset the mass data. + ResetMassData(); +} + +void b2Body::ResetMassData() +{ + // Compute mass data from shapes. Each shape has its own density. + m_mass = 0.0f; + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + m_sweep.localCenter.SetZero(); + + // Static and kinematic bodies have zero mass. + if (m_type == b2_staticBody || m_type == b2_kinematicBody) + { + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = m_sweep.a; + return; + } + + b2Assert(m_type == b2_dynamicBody); + + // Accumulate mass over all fixtures. + b2Vec2 localCenter = b2Vec2_zero; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + if (f->m_density == 0.0f) + { + continue; + } + + b2MassData massData; + f->GetMassData(&massData); + m_mass += massData.mass; + localCenter += massData.mass * massData.center; + m_I += massData.I; + } + + // Compute center of mass. + if (m_mass > 0.0f) + { + m_invMass = 1.0f / m_mass; + localCenter *= m_invMass; + } + else + { + // Force all dynamic bodies to have a positive mass. + m_mass = 1.0f; + m_invMass = 1.0f; + } + + if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) + { + // Center the inertia about the center of mass. + m_I -= m_mass * b2Dot(localCenter, localCenter); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + + } + else + { + m_I = 0.0f; + m_invI = 0.0f; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = localCenter; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +void b2Body::SetMassData(const b2MassData* massData) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + if (m_type != b2_dynamicBody) + { + return; + } + + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + + m_mass = massData->mass; + if (m_mass <= 0.0f) + { + m_mass = 1.0f; + } + + m_invMass = 1.0f / m_mass; + + if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) + { + m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = massData->center; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +bool b2Body::ShouldCollide(const b2Body* other) const +{ + // At least one body should be dynamic. + if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) + { + return false; + } + + // Does a joint prevent collision? + for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) + { + if (jn->other == other) + { + if (jn->joint->m_collideConnected == false) + { + return false; + } + } + } + + return true; +} + +void b2Body::SetTransform(const b2Vec2& position, float32 angle) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + m_xf.q.Set(angle); + m_xf.p = position; + + m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.a = angle; + + m_sweep.c0 = m_sweep.c; + m_sweep.a0 = angle; + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, m_xf, m_xf); + } + + m_world->m_contactManager.FindNewContacts(); +} + +void b2Body::SynchronizeFixtures() +{ + b2Transform xf1; + xf1.q.Set(m_sweep.a0); + xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, xf1, m_xf); + } +} + +void b2Body::SetActive(bool flag) +{ + b2Assert(m_world->IsLocked() == false); + + if (flag == IsActive()) + { + return; + } + + if (flag) + { + m_flags |= e_activeFlag; + + // Create all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->CreateProxies(broadPhase, m_xf); + } + + // Contacts are created the next time step. + } + else + { + m_flags &= ~e_activeFlag; + + // Destroy all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->DestroyProxies(broadPhase); + } + + // Destroy the attached contacts. + b2ContactEdge* ce = m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_world->m_contactManager.Destroy(ce0->contact); + } + m_contactList = NULL; + } +} + +void b2Body::Dump() +{ + int32 bodyIndex = m_islandIndex; + + b2Log("{\n"); + b2Log(" b2BodyDef bd;\n"); + b2Log(" bd.type = b2BodyType(%d);\n", m_type); + b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); + b2Log(" bd.angle = %.15lef;\n", m_sweep.a); + b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); + b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); + b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); + b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); + b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); + b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); + b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); + b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); + b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); + b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); + b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); + b2Log("\n"); + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + b2Log(" {\n"); + f->Dump(bodyIndex); + b2Log(" }\n"); + } + b2Log("}\n"); +} \ No newline at end of file diff --git a/external/box2d/Dynamics/b2Body.h b/external/box2d/Dynamics/b2Body.h new file mode 100644 index 0000000000..e2d16bf630 --- /dev/null +++ b/external/box2d/Dynamics/b2Body.h @@ -0,0 +1,846 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BODY_H +#define B2_BODY_H + +#include +#include +#include + +class b2Fixture; +class b2Joint; +class b2Contact; +class b2Controller; +class b2World; +struct b2FixtureDef; +struct b2JointEdge; +struct b2ContactEdge; + +/// The body type. +/// static: zero mass, zero velocity, may be manually moved +/// kinematic: zero mass, non-zero velocity set by user, moved by solver +/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver +enum b2BodyType +{ + b2_staticBody = 0, + b2_kinematicBody, + b2_dynamicBody + + // TODO_ERIN + //b2_bulletBody, +}; + +/// A body definition holds all the data needed to construct a rigid body. +/// You can safely re-use body definitions. Shapes are added to a body after construction. +struct b2BodyDef +{ + /// This constructor sets the body definition default values. + b2BodyDef() + { + userData = NULL; + position.Set(0.0f, 0.0f); + angle = 0.0f; + linearVelocity.Set(0.0f, 0.0f); + angularVelocity = 0.0f; + linearDamping = 0.0f; + angularDamping = 0.0f; + allowSleep = true; + awake = true; + fixedRotation = false; + bullet = false; + type = b2_staticBody; + active = true; + gravityScale = 1.0f; + } + + /// The body type: static, kinematic, or dynamic. + /// Note: if a dynamic body would have zero mass, the mass is set to one. + b2BodyType type; + + /// The world position of the body. Avoid creating bodies at the origin + /// since this can lead to many overlapping shapes. + b2Vec2 position; + + /// The world angle of the body in radians. + float32 angle; + + /// The linear velocity of the body's origin in world co-ordinates. + b2Vec2 linearVelocity; + + /// The angular velocity of the body. + float32 angularVelocity; + + /// Linear damping is use to reduce the linear velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 linearDamping; + + /// Angular damping is use to reduce the angular velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 angularDamping; + + /// Set this flag to false if this body should never fall asleep. Note that + /// this increases CPU usage. + bool allowSleep; + + /// Is this body initially awake or sleeping? + bool awake; + + /// Should this body be prevented from rotating? Useful for characters. + bool fixedRotation; + + /// Is this a fast moving body that should be prevented from tunneling through + /// other moving bodies? Note that all bodies are prevented from tunneling through + /// kinematic and static bodies. This setting is only considered on dynamic bodies. + /// @warning You should use this flag sparingly since it increases processing time. + bool bullet; + + /// Does this body start out active? + bool active; + + /// Use this to store application specific body data. + void* userData; + + /// Scale the gravity applied to this body. + float32 gravityScale; +}; + +/// A rigid body. These are created via b2World::CreateBody. +class b2Body +{ +public: + /// Creates a fixture and attach it to this body. Use this function if you need + /// to set some fixture parameters, like friction. Otherwise you can create the + /// fixture directly from a shape. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// Contacts are not created until the next time step. + /// @param def the fixture definition. + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2FixtureDef* def); + + /// Creates a fixture from a shape and attach it to this body. + /// This is a convenience function. Use b2FixtureDef if you need to set parameters + /// like friction, restitution, user data, or filtering. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// @param shape the shape to be cloned. + /// @param density the shape density (set to zero for static bodies). + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2Shape* shape, float32 density); + + /// Destroy a fixture. This removes the fixture from the broad-phase and + /// destroys all contacts associated with this fixture. This will + /// automatically adjust the mass of the body if the body is dynamic and the + /// fixture has positive density. + /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. + /// @param fixture the fixture to be removed. + /// @warning This function is locked during callbacks. + void DestroyFixture(b2Fixture* fixture); + + /// Set the position of the body's origin and rotation. + /// This breaks any contacts and wakes the other bodies. + /// Manipulating a body's transform may cause non-physical behavior. + /// @param position the world position of the body's local origin. + /// @param angle the world rotation in radians. + void SetTransform(const b2Vec2& position, float32 angle); + + /// Get the body transform for the body's origin. + /// @return the world transform of the body's origin. + const b2Transform& GetTransform() const; + + /// Get the world body origin position. + /// @return the world position of the body's origin. + const b2Vec2& GetPosition() const; + + /// Get the angle in radians. + /// @return the current world rotation angle in radians. + float32 GetAngle() const; + + /// Get the world position of the center of mass. + const b2Vec2& GetWorldCenter() const; + + /// Get the local position of the center of mass. + const b2Vec2& GetLocalCenter() const; + + /// Set the linear velocity of the center of mass. + /// @param v the new linear velocity of the center of mass. + void SetLinearVelocity(const b2Vec2& v); + + /// Get the linear velocity of the center of mass. + /// @return the linear velocity of the center of mass. + b2Vec2 GetLinearVelocity() const; + + /// Set the angular velocity. + /// @param omega the new angular velocity in radians/second. + void SetAngularVelocity(float32 omega); + + /// Get the angular velocity. + /// @return the angular velocity in radians/second. + float32 GetAngularVelocity() const; + + /// Apply a force at a world point. If the force is not + /// applied at the center of mass, it will generate a torque and + /// affect the angular velocity. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + /// @param point the world position of the point of application. + void ApplyForce(const b2Vec2& force, const b2Vec2& point); + + /// Apply a force to the center of mass. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + void ApplyForceToCenter(const b2Vec2& force); + + /// Apply a torque. This affects the angular velocity + /// without affecting the linear velocity of the center of mass. + /// This wakes up the body. + /// @param torque about the z-axis (out of the screen), usually in N-m. + void ApplyTorque(float32 torque); + + /// Apply an impulse at a point. This immediately modifies the velocity. + /// It also modifies the angular velocity if the point of application + /// is not at the center of mass. This wakes up the body. + /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. + /// @param point the world position of the point of application. + void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); + + /// Apply an angular impulse. + /// @param impulse the angular impulse in units of kg*m*m/s + void ApplyAngularImpulse(float32 impulse); + + /// Get the total mass of the body. + /// @return the mass, usually in kilograms (kg). + float32 GetMass() const; + + /// Get the rotational inertia of the body about the local origin. + /// @return the rotational inertia, usually in kg-m^2. + float32 GetInertia() const; + + /// Get the mass data of the body. + /// @return a struct containing the mass, inertia and center of the body. + void GetMassData(b2MassData* data) const; + + /// Set the mass properties to override the mass properties of the fixtures. + /// Note that this changes the center of mass position. + /// Note that creating or destroying fixtures can also alter the mass. + /// This function has no effect if the body isn't dynamic. + /// @param massData the mass properties. + void SetMassData(const b2MassData* data); + + /// This resets the mass properties to the sum of the mass properties of the fixtures. + /// This normally does not need to be called unless you called SetMassData to override + /// the mass and you later want to reset the mass. + void ResetMassData(); + + /// Get the world coordinates of a point given the local coordinates. + /// @param localPoint a point on the body measured relative the the body's origin. + /// @return the same point expressed in world coordinates. + b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; + + /// Get the world coordinates of a vector given the local coordinates. + /// @param localVector a vector fixed in the body. + /// @return the same vector expressed in world coordinates. + b2Vec2 GetWorldVector(const b2Vec2& localVector) const; + + /// Gets a local point relative to the body's origin given a world point. + /// @param a point in world coordinates. + /// @return the corresponding local point relative to the body's origin. + b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; + + /// Gets a local vector given a world vector. + /// @param a vector in world coordinates. + /// @return the corresponding local vector. + b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; + + /// Get the world linear velocity of a world point attached to this body. + /// @param a point in world coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; + + /// Get the world velocity of a local point. + /// @param a point in local coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; + + /// Get the linear damping of the body. + float32 GetLinearDamping() const; + + /// Set the linear damping of the body. + void SetLinearDamping(float32 linearDamping); + + /// Get the angular damping of the body. + float32 GetAngularDamping() const; + + /// Set the angular damping of the body. + void SetAngularDamping(float32 angularDamping); + + /// Get the gravity scale of the body. + float32 GetGravityScale() const; + + /// Set the gravity scale of the body. + void SetGravityScale(float32 scale); + + /// Set the type of this body. This may alter the mass and velocity. + void SetType(b2BodyType type); + + /// Get the type of this body. + b2BodyType GetType() const; + + /// Should this body be treated like a bullet for continuous collision detection? + void SetBullet(bool flag); + + /// Is this body treated like a bullet for continuous collision detection? + bool IsBullet() const; + + /// You can disable sleeping on this body. If you disable sleeping, the + /// body will be woken. + void SetSleepingAllowed(bool flag); + + /// Is this body allowed to sleep + bool IsSleepingAllowed() const; + + /// Set the sleep state of the body. A sleeping body has very + /// low CPU cost. + /// @param flag set to true to put body to sleep, false to wake it. + void SetAwake(bool flag); + + /// Get the sleeping state of this body. + /// @return true if the body is sleeping. + bool IsAwake() const; + + /// Set the active state of the body. An inactive body is not + /// simulated and cannot be collided with or woken up. + /// If you pass a flag of true, all fixtures will be added to the + /// broad-phase. + /// If you pass a flag of false, all fixtures will be removed from + /// the broad-phase and all contacts will be destroyed. + /// Fixtures and joints are otherwise unaffected. You may continue + /// to create/destroy fixtures and joints on inactive bodies. + /// Fixtures on an inactive body are implicitly inactive and will + /// not participate in collisions, ray-casts, or queries. + /// Joints connected to an inactive body are implicitly inactive. + /// An inactive body is still owned by a b2World object and remains + /// in the body list. + void SetActive(bool flag); + + /// Get the active state of the body. + bool IsActive() const; + + /// Set this body to have fixed rotation. This causes the mass + /// to be reset. + void SetFixedRotation(bool flag); + + /// Does this body have fixed rotation? + bool IsFixedRotation() const; + + /// Get the list of all fixtures attached to this body. + b2Fixture* GetFixtureList(); + const b2Fixture* GetFixtureList() const; + + /// Get the list of all joints attached to this body. + b2JointEdge* GetJointList(); + const b2JointEdge* GetJointList() const; + + /// Get the list of all contacts attached to this body. + /// @warning this list changes during the time step and you may + /// miss some collisions if you don't use b2ContactListener. + b2ContactEdge* GetContactList(); + const b2ContactEdge* GetContactList() const; + + /// Get the next body in the world's body list. + b2Body* GetNext(); + const b2Body* GetNext() const; + + /// Get the user data pointer that was provided in the body definition. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Get the parent world of this body. + b2World* GetWorld(); + const b2World* GetWorld() const; + + /// Dump this body to a log file + void Dump(); + +private: + + friend class b2World; + friend class b2Island; + friend class b2ContactManager; + friend class b2ContactSolver; + friend class b2Contact; + + friend class b2DistanceJoint; + friend class b2GearJoint; + friend class b2WheelJoint; + friend class b2MouseJoint; + friend class b2PrismaticJoint; + friend class b2PulleyJoint; + friend class b2RevoluteJoint; + friend class b2WeldJoint; + friend class b2FrictionJoint; + friend class b2RopeJoint; + + // m_flags + enum + { + e_islandFlag = 0x0001, + e_awakeFlag = 0x0002, + e_autoSleepFlag = 0x0004, + e_bulletFlag = 0x0008, + e_fixedRotationFlag = 0x0010, + e_activeFlag = 0x0020, + e_toiFlag = 0x0040 + }; + + b2Body(const b2BodyDef* bd, b2World* world); + ~b2Body(); + + void SynchronizeFixtures(); + void SynchronizeTransform(); + + // This is used to prevent connected bodies from colliding. + // It may lie, depending on the collideConnected flag. + bool ShouldCollide(const b2Body* other) const; + + void Advance(float32 t); + + b2BodyType m_type; + + uint16 m_flags; + + int32 m_islandIndex; + + b2Transform m_xf; // the body origin transform + b2Sweep m_sweep; // the swept motion for CCD + + b2Vec2 m_linearVelocity; + float32 m_angularVelocity; + + b2Vec2 m_force; + float32 m_torque; + + b2World* m_world; + b2Body* m_prev; + b2Body* m_next; + + b2Fixture* m_fixtureList; + int32 m_fixtureCount; + + b2JointEdge* m_jointList; + b2ContactEdge* m_contactList; + + float32 m_mass, m_invMass; + + // Rotational inertia about the center of mass. + float32 m_I, m_invI; + + float32 m_linearDamping; + float32 m_angularDamping; + float32 m_gravityScale; + + float32 m_sleepTime; + + void* m_userData; +}; + +inline b2BodyType b2Body::GetType() const +{ + return m_type; +} + +inline const b2Transform& b2Body::GetTransform() const +{ + return m_xf; +} + +inline const b2Vec2& b2Body::GetPosition() const +{ + return m_xf.p; +} + +inline float32 b2Body::GetAngle() const +{ + return m_sweep.a; +} + +inline const b2Vec2& b2Body::GetWorldCenter() const +{ + return m_sweep.c; +} + +inline const b2Vec2& b2Body::GetLocalCenter() const +{ + return m_sweep.localCenter; +} + +inline void b2Body::SetLinearVelocity(const b2Vec2& v) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (b2Dot(v,v) > 0.0f) + { + SetAwake(true); + } + + m_linearVelocity = v; +} + +inline b2Vec2 b2Body::GetLinearVelocity() const +{ + return m_linearVelocity; +} + +inline void b2Body::SetAngularVelocity(float32 w) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (w * w > 0.0f) + { + SetAwake(true); + } + + m_angularVelocity = w; +} + +inline float32 b2Body::GetAngularVelocity() const +{ + return m_angularVelocity; +} + +inline float32 b2Body::GetMass() const +{ + return m_mass; +} + +inline float32 b2Body::GetInertia() const +{ + return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); +} + +inline void b2Body::GetMassData(b2MassData* data) const +{ + data->mass = m_mass; + data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); + data->center = m_sweep.localCenter; +} + +inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const +{ + return b2Mul(m_xf, localPoint); +} + +inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const +{ + return b2Mul(m_xf.q, localVector); +} + +inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const +{ + return b2MulT(m_xf, worldPoint); +} + +inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const +{ + return b2MulT(m_xf.q, worldVector); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const +{ + return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const +{ + return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); +} + +inline float32 b2Body::GetLinearDamping() const +{ + return m_linearDamping; +} + +inline void b2Body::SetLinearDamping(float32 linearDamping) +{ + m_linearDamping = linearDamping; +} + +inline float32 b2Body::GetAngularDamping() const +{ + return m_angularDamping; +} + +inline void b2Body::SetAngularDamping(float32 angularDamping) +{ + m_angularDamping = angularDamping; +} + +inline float32 b2Body::GetGravityScale() const +{ + return m_gravityScale; +} + +inline void b2Body::SetGravityScale(float32 scale) +{ + m_gravityScale = scale; +} + +inline void b2Body::SetBullet(bool flag) +{ + if (flag) + { + m_flags |= e_bulletFlag; + } + else + { + m_flags &= ~e_bulletFlag; + } +} + +inline bool b2Body::IsBullet() const +{ + return (m_flags & e_bulletFlag) == e_bulletFlag; +} + +inline void b2Body::SetAwake(bool flag) +{ + if (flag) + { + if ((m_flags & e_awakeFlag) == 0) + { + m_flags |= e_awakeFlag; + m_sleepTime = 0.0f; + } + } + else + { + m_flags &= ~e_awakeFlag; + m_sleepTime = 0.0f; + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; + } +} + +inline bool b2Body::IsAwake() const +{ + return (m_flags & e_awakeFlag) == e_awakeFlag; +} + +inline bool b2Body::IsActive() const +{ + return (m_flags & e_activeFlag) == e_activeFlag; +} + +inline void b2Body::SetFixedRotation(bool flag) +{ + if (flag) + { + m_flags |= e_fixedRotationFlag; + } + else + { + m_flags &= ~e_fixedRotationFlag; + } + + ResetMassData(); +} + +inline bool b2Body::IsFixedRotation() const +{ + return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; +} + +inline void b2Body::SetSleepingAllowed(bool flag) +{ + if (flag) + { + m_flags |= e_autoSleepFlag; + } + else + { + m_flags &= ~e_autoSleepFlag; + SetAwake(true); + } +} + +inline bool b2Body::IsSleepingAllowed() const +{ + return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; +} + +inline b2Fixture* b2Body::GetFixtureList() +{ + return m_fixtureList; +} + +inline const b2Fixture* b2Body::GetFixtureList() const +{ + return m_fixtureList; +} + +inline b2JointEdge* b2Body::GetJointList() +{ + return m_jointList; +} + +inline const b2JointEdge* b2Body::GetJointList() const +{ + return m_jointList; +} + +inline b2ContactEdge* b2Body::GetContactList() +{ + return m_contactList; +} + +inline const b2ContactEdge* b2Body::GetContactList() const +{ + return m_contactList; +} + +inline b2Body* b2Body::GetNext() +{ + return m_next; +} + +inline const b2Body* b2Body::GetNext() const +{ + return m_next; +} + +inline void b2Body::SetUserData(void* data) +{ + m_userData = data; +} + +inline void* b2Body::GetUserData() const +{ + return m_userData; +} + +inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; + m_torque += b2Cross(point - m_sweep.c, force); +} + +inline void b2Body::ApplyForceToCenter(const b2Vec2& force) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; +} + +inline void b2Body::ApplyTorque(float32 torque) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_torque += torque; +} + +inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_linearVelocity += m_invMass * impulse; + m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); +} + +inline void b2Body::ApplyAngularImpulse(float32 impulse) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_angularVelocity += m_invI * impulse; +} + +inline void b2Body::SynchronizeTransform() +{ + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); +} + +inline void b2Body::Advance(float32 alpha) +{ + // Advance to the new safe time. This doesn't sync the broad-phase. + m_sweep.Advance(alpha); + m_sweep.c = m_sweep.c0; + m_sweep.a = m_sweep.a0; + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); +} + +inline b2World* b2Body::GetWorld() +{ + return m_world; +} + +inline const b2World* b2Body::GetWorld() const +{ + return m_world; +} + +#endif diff --git a/external/box2d/Dynamics/b2ContactManager.cpp b/external/box2d/Dynamics/b2ContactManager.cpp new file mode 100644 index 0000000000..c14cc4ce45 --- /dev/null +++ b/external/box2d/Dynamics/b2ContactManager.cpp @@ -0,0 +1,293 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2ContactFilter b2_defaultFilter; +b2ContactListener b2_defaultListener; + +b2ContactManager::b2ContactManager() +{ + m_contactList = NULL; + m_contactCount = 0; + m_contactFilter = &b2_defaultFilter; + m_contactListener = &b2_defaultListener; + m_allocator = NULL; +} + +void b2ContactManager::Destroy(b2Contact* c) +{ + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + if (m_contactListener && c->IsTouching()) + { + m_contactListener->EndContact(c); + } + + // Remove from the world. + if (c->m_prev) + { + c->m_prev->m_next = c->m_next; + } + + if (c->m_next) + { + c->m_next->m_prev = c->m_prev; + } + + if (c == m_contactList) + { + m_contactList = c->m_next; + } + + // Remove from body 1 + if (c->m_nodeA.prev) + { + c->m_nodeA.prev->next = c->m_nodeA.next; + } + + if (c->m_nodeA.next) + { + c->m_nodeA.next->prev = c->m_nodeA.prev; + } + + if (&c->m_nodeA == bodyA->m_contactList) + { + bodyA->m_contactList = c->m_nodeA.next; + } + + // Remove from body 2 + if (c->m_nodeB.prev) + { + c->m_nodeB.prev->next = c->m_nodeB.next; + } + + if (c->m_nodeB.next) + { + c->m_nodeB.next->prev = c->m_nodeB.prev; + } + + if (&c->m_nodeB == bodyB->m_contactList) + { + bodyB->m_contactList = c->m_nodeB.next; + } + + // Call the factory. + b2Contact::Destroy(c, m_allocator); + --m_contactCount; +} + +// This is the top level collision call for the time step. Here +// all the narrow phase collision is processed for the world +// contact list. +void b2ContactManager::Collide() +{ + // Update awake contacts. + b2Contact* c = m_contactList; + while (c) + { + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Is this contact flagged for filtering? + if (c->m_flags & b2Contact::e_filterFlag) + { + // Should these bodies collide? + if (bodyB->ShouldCollide(bodyA) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Clear the filtering flag. + c->m_flags &= ~b2Contact::e_filterFlag; + } + + bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; + bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; + + // At least one body must be awake and it must be dynamic or kinematic. + if (activeA == false && activeB == false) + { + c = c->GetNext(); + continue; + } + + int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; + int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; + bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); + + // Here we destroy contacts that cease to overlap in the broad-phase. + if (overlap == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // The contact persists. + c->Update(m_contactListener); + c = c->GetNext(); + } +} + +void b2ContactManager::FindNewContacts() +{ + m_broadPhase.UpdatePairs(this); +} + +void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) +{ + b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; + b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; + + b2Fixture* fixtureA = proxyA->fixture; + b2Fixture* fixtureB = proxyB->fixture; + + int32 indexA = proxyA->childIndex; + int32 indexB = proxyB->childIndex; + + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Are the fixtures on the same body? + if (bodyA == bodyB) + { + return; + } + + // TODO_ERIN use a hash table to remove a potential bottleneck when both + // bodies have a lot of contacts. + // Does a contact already exist? + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + b2Fixture* fA = edge->contact->GetFixtureA(); + b2Fixture* fB = edge->contact->GetFixtureB(); + int32 iA = edge->contact->GetChildIndexA(); + int32 iB = edge->contact->GetChildIndexB(); + + if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) + { + // A contact already exists. + return; + } + + if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) + { + // A contact already exists. + return; + } + } + + edge = edge->next; + } + + // Does a joint override collision? Is at least one body dynamic? + if (bodyB->ShouldCollide(bodyA) == false) + { + return; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + return; + } + + // Call the factory. + b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); + if (c == NULL) + { + return; + } + + // Contact creation may swap fixtures. + fixtureA = c->GetFixtureA(); + fixtureB = c->GetFixtureB(); + indexA = c->GetChildIndexA(); + indexB = c->GetChildIndexB(); + bodyA = fixtureA->GetBody(); + bodyB = fixtureB->GetBody(); + + // Insert into the world. + c->m_prev = NULL; + c->m_next = m_contactList; + if (m_contactList != NULL) + { + m_contactList->m_prev = c; + } + m_contactList = c; + + // Connect to island graph. + + // Connect to body A + c->m_nodeA.contact = c; + c->m_nodeA.other = bodyB; + + c->m_nodeA.prev = NULL; + c->m_nodeA.next = bodyA->m_contactList; + if (bodyA->m_contactList != NULL) + { + bodyA->m_contactList->prev = &c->m_nodeA; + } + bodyA->m_contactList = &c->m_nodeA; + + // Connect to body B + c->m_nodeB.contact = c; + c->m_nodeB.other = bodyA; + + c->m_nodeB.prev = NULL; + c->m_nodeB.next = bodyB->m_contactList; + if (bodyB->m_contactList != NULL) + { + bodyB->m_contactList->prev = &c->m_nodeB; + } + bodyB->m_contactList = &c->m_nodeB; + + // Wake up the bodies + bodyA->SetAwake(true); + bodyB->SetAwake(true); + + ++m_contactCount; +} diff --git a/external/box2d/Dynamics/b2ContactManager.h b/external/box2d/Dynamics/b2ContactManager.h new file mode 100644 index 0000000000..9cb5718145 --- /dev/null +++ b/external/box2d/Dynamics/b2ContactManager.h @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_MANAGER_H +#define B2_CONTACT_MANAGER_H + +#include + +class b2Contact; +class b2ContactFilter; +class b2ContactListener; +class b2BlockAllocator; + +// Delegate of b2World. +class b2ContactManager +{ +public: + b2ContactManager(); + + // Broad-phase callback. + void AddPair(void* proxyUserDataA, void* proxyUserDataB); + + void FindNewContacts(); + + void Destroy(b2Contact* c); + + void Collide(); + + b2BroadPhase m_broadPhase; + b2Contact* m_contactList; + int32 m_contactCount; + b2ContactFilter* m_contactFilter; + b2ContactListener* m_contactListener; + b2BlockAllocator* m_allocator; +}; + +#endif diff --git a/external/box2d/Dynamics/b2Fixture.cpp b/external/box2d/Dynamics/b2Fixture.cpp new file mode 100644 index 0000000000..774a78e5bb --- /dev/null +++ b/external/box2d/Dynamics/b2Fixture.cpp @@ -0,0 +1,303 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +b2Fixture::b2Fixture() +{ + m_userData = NULL; + m_body = NULL; + m_next = NULL; + m_proxies = NULL; + m_proxyCount = 0; + m_shape = NULL; + m_density = 0.0f; +} + +void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) +{ + m_userData = def->userData; + m_friction = def->friction; + m_restitution = def->restitution; + + m_body = body; + m_next = NULL; + + m_filter = def->filter; + + m_isSensor = def->isSensor; + + m_shape = def->shape->Clone(allocator); + + // Reserve proxy space + int32 childCount = m_shape->GetChildCount(); + m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); + for (int32 i = 0; i < childCount; ++i) + { + m_proxies[i].fixture = NULL; + m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; + } + m_proxyCount = 0; + + m_density = def->density; +} + +void b2Fixture::Destroy(b2BlockAllocator* allocator) +{ + // The proxies must be destroyed before calling this. + b2Assert(m_proxyCount == 0); + + // Free the proxy array. + int32 childCount = m_shape->GetChildCount(); + allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); + m_proxies = NULL; + + // Free the child shape. + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + s->~b2CircleShape(); + allocator->Free(s, sizeof(b2CircleShape)); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + s->~b2EdgeShape(); + allocator->Free(s, sizeof(b2EdgeShape)); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + s->~b2PolygonShape(); + allocator->Free(s, sizeof(b2PolygonShape)); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + s->~b2ChainShape(); + allocator->Free(s, sizeof(b2ChainShape)); + } + break; + + default: + b2Assert(false); + break; + } + + m_shape = NULL; +} + +void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) +{ + b2Assert(m_proxyCount == 0); + + // Create proxies in the broad-phase. + m_proxyCount = m_shape->GetChildCount(); + + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + m_shape->ComputeAABB(&proxy->aabb, xf, i); + proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); + proxy->fixture = this; + proxy->childIndex = i; + } +} + +void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) +{ + // Destroy proxies in the broad-phase. + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + broadPhase->DestroyProxy(proxy->proxyId); + proxy->proxyId = b2BroadPhase::e_nullProxy; + } + + m_proxyCount = 0; +} + +void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) +{ + if (m_proxyCount == 0) + { + return; + } + + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + + // Compute an AABB that covers the swept shape (may miss some rotation effect). + b2AABB aabb1, aabb2; + m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); + m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); + + proxy->aabb.Combine(aabb1, aabb2); + + b2Vec2 displacement = transform2.p - transform1.p; + + broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); + } +} + +void b2Fixture::SetFilterData(const b2Filter& filter) +{ + m_filter = filter; + + Refilter(); +} + +void b2Fixture::Refilter() +{ + if (m_body == NULL) + { + return; + } + + // Flag associated contacts for filtering. + b2ContactEdge* edge = m_body->GetContactList(); + while (edge) + { + b2Contact* contact = edge->contact; + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + if (fixtureA == this || fixtureB == this) + { + contact->FlagForFiltering(); + } + + edge = edge->next; + } + + b2World* world = m_body->GetWorld(); + + if (world == NULL) + { + return; + } + + // Touch each proxy so that new pairs may be created + b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; + for (int32 i = 0; i < m_proxyCount; ++i) + { + broadPhase->TouchProxy(m_proxies[i].proxyId); + } +} + +void b2Fixture::SetSensor(bool sensor) +{ + if (sensor != m_isSensor) + { + m_body->SetAwake(true); + m_isSensor = sensor; + } +} + +void b2Fixture::Dump(int32 bodyIndex) +{ + b2Log(" b2FixtureDef fd;\n"); + b2Log(" fd.friction = %.15lef;\n", m_friction); + b2Log(" fd.restitution = %.15lef;\n", m_restitution); + b2Log(" fd.density = %.15lef;\n", m_density); + b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); + b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); + b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); + b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); + + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + b2Log(" b2CircleShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + b2Log(" b2EdgeShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); + b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); + b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); + b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); + b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); + b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + b2Log(" b2PolygonShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); + for (int32 i = 0; i < s->m_vertexCount; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + b2Log(" b2ChainShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", s->m_count); + for (int32 i = 0; i < s->m_count; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); + b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); + b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); + b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); + b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); + } + break; + + default: + return; + } + + b2Log("\n"); + b2Log(" fd.shape = &shape;\n"); + b2Log("\n"); + b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); +} diff --git a/external/box2d/Dynamics/b2Fixture.h b/external/box2d/Dynamics/b2Fixture.h new file mode 100644 index 0000000000..d390410b93 --- /dev/null +++ b/external/box2d/Dynamics/b2Fixture.h @@ -0,0 +1,345 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FIXTURE_H +#define B2_FIXTURE_H + +#include +#include +#include + +class b2BlockAllocator; +class b2Body; +class b2BroadPhase; +class b2Fixture; + +/// This holds contact filtering data. +struct b2Filter +{ + b2Filter() + { + categoryBits = 0x0001; + maskBits = 0xFFFF; + groupIndex = 0; + } + + /// The collision category bits. Normally you would just set one bit. + uint16 categoryBits; + + /// The collision mask bits. This states the categories that this + /// shape would accept for collision. + uint16 maskBits; + + /// Collision groups allow a certain group of objects to never collide (negative) + /// or always collide (positive). Zero means no collision group. Non-zero group + /// filtering always wins against the mask bits. + int16 groupIndex; +}; + +/// A fixture definition is used to create a fixture. This class defines an +/// abstract fixture definition. You can reuse fixture definitions safely. +struct b2FixtureDef +{ + /// The constructor sets the default fixture definition values. + b2FixtureDef() + { + shape = NULL; + userData = NULL; + friction = 0.2f; + restitution = 0.0f; + density = 0.0f; + isSensor = false; + } + + /// The shape, this must be set. The shape will be cloned, so you + /// can create the shape on the stack. + const b2Shape* shape; + + /// Use this to store application specific fixture data. + void* userData; + + /// The friction coefficient, usually in the range [0,1]. + float32 friction; + + /// The restitution (elasticity) usually in the range [0,1]. + float32 restitution; + + /// The density, usually in kg/m^2. + float32 density; + + /// A sensor shape collects contact information but never generates a collision + /// response. + bool isSensor; + + /// Contact filtering data. + b2Filter filter; +}; + +/// This proxy is used internally to connect fixtures to the broad-phase. +struct b2FixtureProxy +{ + b2AABB aabb; + b2Fixture* fixture; + int32 childIndex; + int32 proxyId; +}; + +/// A fixture is used to attach a shape to a body for collision detection. A fixture +/// inherits its transform from its parent. Fixtures hold additional non-geometric data +/// such as friction, collision filters, etc. +/// Fixtures are created via b2Body::CreateFixture. +/// @warning you cannot reuse fixtures. +class b2Fixture +{ +public: + /// Get the type of the child shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + b2Shape::Type GetType() const; + + /// Get the child shape. You can modify the child shape, however you should not change the + /// number of vertices because this will crash some collision caching mechanisms. + /// Manipulating the shape may lead to non-physical behavior. + b2Shape* GetShape(); + const b2Shape* GetShape() const; + + /// Set if this fixture is a sensor. + void SetSensor(bool sensor); + + /// Is this fixture a sensor (non-solid)? + /// @return the true if the shape is a sensor. + bool IsSensor() const; + + /// Set the contact filtering data. This will not update contacts until the next time + /// step when either parent body is active and awake. + /// This automatically calls Refilter. + void SetFilterData(const b2Filter& filter); + + /// Get the contact filtering data. + const b2Filter& GetFilterData() const; + + /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. + void Refilter(); + + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. + /// @return the parent body. + b2Body* GetBody(); + const b2Body* GetBody() const; + + /// Get the next fixture in the parent body's fixture list. + /// @return the next shape. + b2Fixture* GetNext(); + const b2Fixture* GetNext() const; + + /// Get the user data that was assigned in the fixture definition. Use this to + /// store your application specific data. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Test a point for containment in this fixture. + /// @param p a point in world coordinates. + bool TestPoint(const b2Vec2& p) const; + + /// Cast a ray against this shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; + + /// Get the mass data for this fixture. The mass data is based on the density and + /// the shape. The rotational inertia is about the shape's origin. This operation + /// may be expensive. + void GetMassData(b2MassData* massData) const; + + /// Set the density of this fixture. This will _not_ automatically adjust the mass + /// of the body. You must call b2Body::ResetMassData to update the body's mass. + void SetDensity(float32 density); + + /// Get the density of this fixture. + float32 GetDensity() const; + + /// Get the coefficient of friction. + float32 GetFriction() const; + + /// Set the coefficient of friction. This will _not_ change the friction of + /// existing contacts. + void SetFriction(float32 friction); + + /// Get the coefficient of restitution. + float32 GetRestitution() const; + + /// Set the coefficient of restitution. This will _not_ change the restitution of + /// existing contacts. + void SetRestitution(float32 restitution); + + /// Get the fixture's AABB. This AABB may be enlarge and/or stale. + /// If you need a more accurate AABB, compute it using the shape and + /// the body transform. + const b2AABB& GetAABB(int32 childIndex) const; + + /// Dump this fixture to the log file. + void Dump(int32 bodyIndex); + +protected: + + friend class b2Body; + friend class b2World; + friend class b2Contact; + friend class b2ContactManager; + + b2Fixture(); + + // We need separation create/destroy functions from the constructor/destructor because + // the destructor cannot access the allocator (no destructor arguments allowed by C++). + void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); + void Destroy(b2BlockAllocator* allocator); + + // These support body activation/deactivation. + void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); + void DestroyProxies(b2BroadPhase* broadPhase); + + void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); + + float32 m_density; + + b2Fixture* m_next; + b2Body* m_body; + + b2Shape* m_shape; + + float32 m_friction; + float32 m_restitution; + + b2FixtureProxy* m_proxies; + int32 m_proxyCount; + + b2Filter m_filter; + + bool m_isSensor; + + void* m_userData; +}; + +inline b2Shape::Type b2Fixture::GetType() const +{ + return m_shape->GetType(); +} + +inline b2Shape* b2Fixture::GetShape() +{ + return m_shape; +} + +inline const b2Shape* b2Fixture::GetShape() const +{ + return m_shape; +} + +inline bool b2Fixture::IsSensor() const +{ + return m_isSensor; +} + +inline const b2Filter& b2Fixture::GetFilterData() const +{ + return m_filter; +} + +inline void* b2Fixture::GetUserData() const +{ + return m_userData; +} + +inline void b2Fixture::SetUserData(void* data) +{ + m_userData = data; +} + +inline b2Body* b2Fixture::GetBody() +{ + return m_body; +} + +inline const b2Body* b2Fixture::GetBody() const +{ + return m_body; +} + +inline b2Fixture* b2Fixture::GetNext() +{ + return m_next; +} + +inline const b2Fixture* b2Fixture::GetNext() const +{ + return m_next; +} + +inline void b2Fixture::SetDensity(float32 density) +{ + b2Assert(b2IsValid(density) && density >= 0.0f); + m_density = density; +} + +inline float32 b2Fixture::GetDensity() const +{ + return m_density; +} + +inline float32 b2Fixture::GetFriction() const +{ + return m_friction; +} + +inline void b2Fixture::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Fixture::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Fixture::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline bool b2Fixture::TestPoint(const b2Vec2& p) const +{ + return m_shape->TestPoint(m_body->GetTransform(), p); +} + +inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const +{ + return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); +} + +inline void b2Fixture::GetMassData(b2MassData* massData) const +{ + m_shape->ComputeMass(massData, m_density); +} + +inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const +{ + b2Assert(0 <= childIndex && childIndex < m_proxyCount); + return m_proxies[childIndex].aabb; +} + +#endif diff --git a/external/box2d/Dynamics/b2Island.cpp b/external/box2d/Dynamics/b2Island.cpp new file mode 100644 index 0000000000..e767d383d5 --- /dev/null +++ b/external/box2d/Dynamics/b2Island.cpp @@ -0,0 +1,539 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +Position Correction Notes +========================= +I tried the several algorithms for position correction of the 2D revolute joint. +I looked at these systems: +- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. +- suspension bridge with 30 1m long planks of length 1m. +- multi-link chain with 30 1m long links. + +Here are the algorithms: + +Baumgarte - A fraction of the position error is added to the velocity error. There is no +separate position solver. + +Pseudo Velocities - After the velocity solver and position integration, +the position error, Jacobian, and effective mass are recomputed. Then +the velocity constraints are solved with pseudo velocities and a fraction +of the position error is added to the pseudo velocity error. The pseudo +velocities are initialized to zero and there is no warm-starting. After +the position solver, the pseudo velocities are added to the positions. +This is also called the First Order World method or the Position LCP method. + +Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the +position error is re-computed for each constraint and the positions are updated +after the constraint is solved. The radius vectors (aka Jacobians) are +re-computed too (otherwise the algorithm has horrible instability). The pseudo +velocity states are not needed because they are effectively zero at the beginning +of each iteration. Since we have the current position error, we allow the +iterations to terminate early if the error becomes smaller than b2_linearSlop. + +Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed +each time a constraint is solved. + +Here are the results: +Baumgarte - this is the cheapest algorithm but it has some stability problems, +especially with the bridge. The chain links separate easily close to the root +and they jitter as they struggle to pull together. This is one of the most common +methods in the field. The big drawback is that the position correction artificially +affects the momentum, thus leading to instabilities and false bounce. I used a +bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller +factor makes joints and contacts more spongy. + +Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is +stable. However, joints still separate with large angular velocities. Drag the +simple pendulum in a circle quickly and the joint will separate. The chain separates +easily and does not recover. I used a bias factor of 0.2. A larger value lead to +the bridge collapsing when a heavy cube drops on it. + +Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo +Velocities, but in other ways it is worse. The bridge and chain are much more +stable, but the simple pendulum goes unstable at high angular velocities. + +Full NGS - stable in all tests. The joints display good stiffness. The bridge +still sags, but this is better than infinite forces. + +Recommendations +Pseudo Velocities are not really worthwhile because the bridge and chain cannot +recover from joint separation. In other cases the benefit over Baumgarte is small. + +Modified NGS is not a robust method for the revolute joint due to the violent +instability seen in the simple pendulum. Perhaps it is viable with other constraint +types, especially scalar constraints where the effective mass is a scalar. + +This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities +and is very fast. I don't think we can escape Baumgarte, especially in highly +demanding cases where high constraint fidelity is not needed. + +Full NGS is robust and easy on the eyes. I recommend this as an option for +higher fidelity simulation and certainly for suspension bridges and long chains. +Full NGS might be a good choice for ragdolls, especially motorized ragdolls where +joint separation can be problematic. The number of NGS iterations can be reduced +for better performance without harming robustness much. + +Each joint in a can be handled differently in the position solver. So I recommend +a system where the user can select the algorithm on a per joint basis. I would +probably default to the slower Full NGS and let the user select the faster +Baumgarte method in performance critical scenarios. +*/ + +/* +Cache Performance + +The Box2D solvers are dominated by cache misses. Data structures are designed +to increase the number of cache hits. Much of misses are due to random access +to body data. The constraint structures are iterated over linearly, which leads +to few cache misses. + +The bodies are not accessed during iteration. Instead read only data, such as +the mass values are stored with the constraints. The mutable data are the constraint +impulses and the bodies velocities/positions. The impulses are held inside the +constraint structures. The body velocities/positions are held in compact, temporary +arrays to increase the number of cache hits. Linear and angular velocity are +stored in a single array since multiple arrays lead to multiple misses. +*/ + +/* +2D Rotation + +R = [cos(theta) -sin(theta)] + [sin(theta) cos(theta) ] + +thetaDot = omega + +Let q1 = cos(theta), q2 = sin(theta). +R = [q1 -q2] + [q2 q1] + +q1Dot = -thetaDot * q2 +q2Dot = thetaDot * q1 + +q1_new = q1_old - dt * w * q2 +q2_new = q2_old + dt * w * q1 +then normalize. + +This might be faster than computing sin+cos. +However, we can compute sin+cos of the same angle fast. +*/ + +b2Island::b2Island( + int32 bodyCapacity, + int32 contactCapacity, + int32 jointCapacity, + b2StackAllocator* allocator, + b2ContactListener* listener) +{ + m_bodyCapacity = bodyCapacity; + m_contactCapacity = contactCapacity; + m_jointCapacity = jointCapacity; + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; + + m_allocator = allocator; + m_listener = listener; + + m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); + m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); + m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); + + m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); + m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); +} + +b2Island::~b2Island() +{ + // Warning: the order should reverse the constructor order. + m_allocator->Free(m_positions); + m_allocator->Free(m_velocities); + m_allocator->Free(m_joints); + m_allocator->Free(m_contacts); + m_allocator->Free(m_bodies); +} + +void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) +{ + b2Timer timer; + + float32 h = step.dt; + + // Integrate velocities and apply damping. Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + + b2Vec2 c = b->m_sweep.c; + float32 a = b->m_sweep.a; + b2Vec2 v = b->m_linearVelocity; + float32 w = b->m_angularVelocity; + + // Store positions for continuous collision. + b->m_sweep.c0 = b->m_sweep.c; + b->m_sweep.a0 = b->m_sweep.a; + + if (b->m_type == b2_dynamicBody) + { + // Integrate velocities. + v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); + w += h * b->m_invI * b->m_torque; + + // Apply damping. + // ODE: dv/dt + c * v = 0 + // Solution: v(t) = v0 * exp(-c * t) + // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) + // v2 = exp(-c * dt) * v1 + // Taylor expansion: + // v2 = (1.0f - c * dt) * v1 + v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); + w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); + } + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } + + timer.Reset(); + + // Solver data + b2SolverData solverData; + solverData.step = step; + solverData.positions = m_positions; + solverData.velocities = m_velocities; + + // Initialize velocity constraints. + b2ContactSolverDef contactSolverDef; + contactSolverDef.step = step; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + contactSolverDef.allocator = m_allocator; + + b2ContactSolver contactSolver(&contactSolverDef); + contactSolver.InitializeVelocityConstraints(); + + if (step.warmStarting) + { + contactSolver.WarmStart(); + } + + for (int32 i = 0; i < m_jointCount; ++i) + { + m_joints[i]->InitVelocityConstraints(solverData); + } + + profile->solveInit = timer.GetMilliseconds(); + + // Solve velocity constraints + timer.Reset(); + for (int32 i = 0; i < step.velocityIterations; ++i) + { + for (int32 j = 0; j < m_jointCount; ++j) + { + m_joints[j]->SolveVelocityConstraints(solverData); + } + + contactSolver.SolveVelocityConstraints(); + } + + // Store impulses for warm starting + contactSolver.StoreImpulses(); + profile->solveVelocity = timer.GetMilliseconds(); + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } + + // Solve position constraints + timer.Reset(); + bool positionSolved = false; + for (int32 i = 0; i < step.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolvePositionConstraints(); + + bool jointsOkay = true; + for (int32 i = 0; i < m_jointCount; ++i) + { + bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); + jointsOkay = jointsOkay && jointOkay; + } + + if (contactsOkay && jointsOkay) + { + // Exit early if the position errors are small. + positionSolved = true; + break; + } + } + + // Copy state buffers back to the bodies + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* body = m_bodies[i]; + body->m_sweep.c = m_positions[i].c; + body->m_sweep.a = m_positions[i].a; + body->m_linearVelocity = m_velocities[i].v; + body->m_angularVelocity = m_velocities[i].w; + body->SynchronizeTransform(); + } + + profile->solvePosition = timer.GetMilliseconds(); + + Report(contactSolver.m_velocityConstraints); + + if (allowSleep) + { + float32 minSleepTime = b2_maxFloat; + + const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; + const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; + + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + continue; + } + + if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || + b->m_angularVelocity * b->m_angularVelocity > angTolSqr || + b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) + { + b->m_sleepTime = 0.0f; + minSleepTime = 0.0f; + } + else + { + b->m_sleepTime += h; + minSleepTime = b2Min(minSleepTime, b->m_sleepTime); + } + } + + if (minSleepTime >= b2_timeToSleep && positionSolved) + { + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + b->SetAwake(false); + } + } + } +} + +void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) +{ + b2Assert(toiIndexA < m_bodyCount); + b2Assert(toiIndexB < m_bodyCount); + + // Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + m_positions[i].c = b->m_sweep.c; + m_positions[i].a = b->m_sweep.a; + m_velocities[i].v = b->m_linearVelocity; + m_velocities[i].w = b->m_angularVelocity; + } + + b2ContactSolverDef contactSolverDef; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.allocator = m_allocator; + contactSolverDef.step = subStep; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + b2ContactSolver contactSolver(&contactSolverDef); + + // Solve position constraints. + for (int32 i = 0; i < subStep.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); + if (contactsOkay) + { + break; + } + } + +#if 0 + // Is the new position really safe? + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + b2DistanceInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.transformA = bA->GetTransform(); + input.transformB = bB->GetTransform(); + input.useRadii = false; + + b2DistanceOutput output; + b2SimplexCache cache; + cache.count = 0; + b2Distance(&output, &cache, &input); + + if (output.distance == 0 || cache.count == 3) + { + cache.count += 0; + } + } +#endif + + // Leap of faith to new safe state. + m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; + m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; + m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; + m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; + + // No warm starting is needed for TOI events because warm + // starting impulses were applied in the discrete solver. + contactSolver.InitializeVelocityConstraints(); + + // Solve velocity constraints. + for (int32 i = 0; i < subStep.velocityIterations; ++i) + { + contactSolver.SolveVelocityConstraints(); + } + + // Don't store the TOI contact forces for warm starting + // because they can be quite large. + + float32 h = subStep.dt; + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + + // Sync bodies + b2Body* body = m_bodies[i]; + body->m_sweep.c = c; + body->m_sweep.a = a; + body->m_linearVelocity = v; + body->m_angularVelocity = w; + body->SynchronizeTransform(); + } + + Report(contactSolver.m_velocityConstraints); +} + +void b2Island::Report(const b2ContactVelocityConstraint* constraints) +{ + if (m_listener == NULL) + { + return; + } + + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + + const b2ContactVelocityConstraint* vc = constraints + i; + + b2ContactImpulse impulse; + impulse.count = vc->pointCount; + for (int32 j = 0; j < vc->pointCount; ++j) + { + impulse.normalImpulses[j] = vc->points[j].normalImpulse; + impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; + } + + m_listener->PostSolve(c, &impulse); + } +} diff --git a/external/box2d/Dynamics/b2Island.h b/external/box2d/Dynamics/b2Island.h new file mode 100644 index 0000000000..e0a6e41fc3 --- /dev/null +++ b/external/box2d/Dynamics/b2Island.h @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ISLAND_H +#define B2_ISLAND_H + +#include +#include +#include + +class b2Contact; +class b2Joint; +class b2StackAllocator; +class b2ContactListener; +struct b2ContactVelocityConstraint; +struct b2Profile; + +/// This is an internal class. +class b2Island +{ +public: + b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, + b2StackAllocator* allocator, b2ContactListener* listener); + ~b2Island(); + + void Clear() + { + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; + } + + void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); + + void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); + + void Add(b2Body* body) + { + b2Assert(m_bodyCount < m_bodyCapacity); + body->m_islandIndex = m_bodyCount; + m_bodies[m_bodyCount] = body; + ++m_bodyCount; + } + + void Add(b2Contact* contact) + { + b2Assert(m_contactCount < m_contactCapacity); + m_contacts[m_contactCount++] = contact; + } + + void Add(b2Joint* joint) + { + b2Assert(m_jointCount < m_jointCapacity); + m_joints[m_jointCount++] = joint; + } + + void Report(const b2ContactVelocityConstraint* constraints); + + b2StackAllocator* m_allocator; + b2ContactListener* m_listener; + + b2Body** m_bodies; + b2Contact** m_contacts; + b2Joint** m_joints; + + b2Position* m_positions; + b2Velocity* m_velocities; + + int32 m_bodyCount; + int32 m_jointCount; + int32 m_contactCount; + + int32 m_bodyCapacity; + int32 m_contactCapacity; + int32 m_jointCapacity; +}; + +#endif diff --git a/external/box2d/Dynamics/b2TimeStep.h b/external/box2d/Dynamics/b2TimeStep.h new file mode 100644 index 0000000000..30d723fcc3 --- /dev/null +++ b/external/box2d/Dynamics/b2TimeStep.h @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TIME_STEP_H +#define B2_TIME_STEP_H + +#include + +/// Profiling data. Times are in milliseconds. +struct b2Profile +{ + float32 step; + float32 collide; + float32 solve; + float32 solveInit; + float32 solveVelocity; + float32 solvePosition; + float32 broadphase; + float32 solveTOI; +}; + +/// This is an internal structure. +struct b2TimeStep +{ + float32 dt; // time step + float32 inv_dt; // inverse time step (0 if dt == 0). + float32 dtRatio; // dt * inv_dt0 + int32 velocityIterations; + int32 positionIterations; + bool warmStarting; +}; + +/// This is an internal structure. +struct b2Position +{ + b2Vec2 c; + float32 a; +}; + +/// This is an internal structure. +struct b2Velocity +{ + b2Vec2 v; + float32 w; +}; + +/// Solver Data +struct b2SolverData +{ + b2TimeStep step; + b2Position* positions; + b2Velocity* velocities; +}; + +#endif diff --git a/external/box2d/Dynamics/b2World.cpp b/external/box2d/Dynamics/b2World.cpp new file mode 100644 index 0000000000..8a0aff5114 --- /dev/null +++ b/external/box2d/Dynamics/b2World.cpp @@ -0,0 +1,1316 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +b2World::b2World(const b2Vec2& gravity) +{ + m_destructionListener = NULL; + m_debugDraw = NULL; + + m_bodyList = NULL; + m_jointList = NULL; + + m_bodyCount = 0; + m_jointCount = 0; + + m_warmStarting = true; + m_continuousPhysics = true; + m_subStepping = false; + + m_stepComplete = true; + + m_allowSleep = true; + m_gravity = gravity; + + m_flags = e_clearForces; + + m_inv_dt0 = 0.0f; + + m_contactManager.m_allocator = &m_blockAllocator; + + memset(&m_profile, 0, sizeof(b2Profile)); +} + +b2World::~b2World() +{ + // Some shapes allocate using b2Alloc. + b2Body* b = m_bodyList; + while (b) + { + b2Body* bNext = b->m_next; + + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* fNext = f->m_next; + f->m_proxyCount = 0; + f->Destroy(&m_blockAllocator); + f = fNext; + } + + b = bNext; + } +} + +void b2World::SetDestructionListener(b2DestructionListener* listener) +{ + m_destructionListener = listener; +} + +void b2World::SetContactFilter(b2ContactFilter* filter) +{ + m_contactManager.m_contactFilter = filter; +} + +void b2World::SetContactListener(b2ContactListener* listener) +{ + m_contactManager.m_contactListener = listener; +} + +void b2World::SetDebugDraw(b2Draw* debugDraw) +{ + m_debugDraw = debugDraw; +} + +b2Body* b2World::CreateBody(const b2BodyDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); + b2Body* b = new (mem) b2Body(def, this); + + // Add to world doubly linked list. + b->m_prev = NULL; + b->m_next = m_bodyList; + if (m_bodyList) + { + m_bodyList->m_prev = b; + } + m_bodyList = b; + ++m_bodyCount; + + return b; +} + +void b2World::DestroyBody(b2Body* b) +{ + b2Assert(m_bodyCount > 0); + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + // Delete the attached joints. + b2JointEdge* je = b->m_jointList; + while (je) + { + b2JointEdge* je0 = je; + je = je->next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(je0->joint); + } + + DestroyJoint(je0->joint); + + b->m_jointList = je; + } + b->m_jointList = NULL; + + // Delete the attached contacts. + b2ContactEdge* ce = b->m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_contactManager.Destroy(ce0->contact); + } + b->m_contactList = NULL; + + // Delete the attached fixtures. This destroys broad-phase proxies. + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* f0 = f; + f = f->m_next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(f0); + } + + f0->DestroyProxies(&m_contactManager.m_broadPhase); + f0->Destroy(&m_blockAllocator); + f0->~b2Fixture(); + m_blockAllocator.Free(f0, sizeof(b2Fixture)); + + b->m_fixtureList = f; + b->m_fixtureCount -= 1; + } + b->m_fixtureList = NULL; + b->m_fixtureCount = 0; + + // Remove world body list. + if (b->m_prev) + { + b->m_prev->m_next = b->m_next; + } + + if (b->m_next) + { + b->m_next->m_prev = b->m_prev; + } + + if (b == m_bodyList) + { + m_bodyList = b->m_next; + } + + --m_bodyCount; + b->~b2Body(); + m_blockAllocator.Free(b, sizeof(b2Body)); +} + +b2Joint* b2World::CreateJoint(const b2JointDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + b2Joint* j = b2Joint::Create(def, &m_blockAllocator); + + // Connect to the world list. + j->m_prev = NULL; + j->m_next = m_jointList; + if (m_jointList) + { + m_jointList->m_prev = j; + } + m_jointList = j; + ++m_jointCount; + + // Connect to the bodies' doubly linked lists. + j->m_edgeA.joint = j; + j->m_edgeA.other = j->m_bodyB; + j->m_edgeA.prev = NULL; + j->m_edgeA.next = j->m_bodyA->m_jointList; + if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; + j->m_bodyA->m_jointList = &j->m_edgeA; + + j->m_edgeB.joint = j; + j->m_edgeB.other = j->m_bodyA; + j->m_edgeB.prev = NULL; + j->m_edgeB.next = j->m_bodyB->m_jointList; + if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; + j->m_bodyB->m_jointList = &j->m_edgeB; + + b2Body* bodyA = def->bodyA; + b2Body* bodyB = def->bodyB; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (def->collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } + + // Note: creating a joint doesn't wake the bodies. + + return j; +} + +void b2World::DestroyJoint(b2Joint* j) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + bool collideConnected = j->m_collideConnected; + + // Remove from the doubly linked list. + if (j->m_prev) + { + j->m_prev->m_next = j->m_next; + } + + if (j->m_next) + { + j->m_next->m_prev = j->m_prev; + } + + if (j == m_jointList) + { + m_jointList = j->m_next; + } + + // Disconnect from island graph. + b2Body* bodyA = j->m_bodyA; + b2Body* bodyB = j->m_bodyB; + + // Wake up connected bodies. + bodyA->SetAwake(true); + bodyB->SetAwake(true); + + // Remove from body 1. + if (j->m_edgeA.prev) + { + j->m_edgeA.prev->next = j->m_edgeA.next; + } + + if (j->m_edgeA.next) + { + j->m_edgeA.next->prev = j->m_edgeA.prev; + } + + if (&j->m_edgeA == bodyA->m_jointList) + { + bodyA->m_jointList = j->m_edgeA.next; + } + + j->m_edgeA.prev = NULL; + j->m_edgeA.next = NULL; + + // Remove from body 2 + if (j->m_edgeB.prev) + { + j->m_edgeB.prev->next = j->m_edgeB.next; + } + + if (j->m_edgeB.next) + { + j->m_edgeB.next->prev = j->m_edgeB.prev; + } + + if (&j->m_edgeB == bodyB->m_jointList) + { + bodyB->m_jointList = j->m_edgeB.next; + } + + j->m_edgeB.prev = NULL; + j->m_edgeB.next = NULL; + + b2Joint::Destroy(j, &m_blockAllocator); + + b2Assert(m_jointCount > 0); + --m_jointCount; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } +} + +// +void b2World::SetAllowSleeping(bool flag) +{ + if (flag == m_allowSleep) + { + return; + } + + m_allowSleep = flag; + if (m_allowSleep == false) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->SetAwake(true); + } + } +} + +// Find islands, integrate and solve constraints, solve position constraints +void b2World::Solve(const b2TimeStep& step) +{ + m_profile.solveInit = 0.0f; + m_profile.solveVelocity = 0.0f; + m_profile.solvePosition = 0.0f; + + // Size the island for the worst case. + b2Island island(m_bodyCount, + m_contactManager.m_contactCount, + m_jointCount, + &m_stackAllocator, + m_contactManager.m_contactListener); + + // Clear all the island flags. + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + c->m_flags &= ~b2Contact::e_islandFlag; + } + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_islandFlag = false; + } + + // Build and simulate all awake islands. + int32 stackSize = m_bodyCount; + b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); + for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) + { + if (seed->m_flags & b2Body::e_islandFlag) + { + continue; + } + + if (seed->IsAwake() == false || seed->IsActive() == false) + { + continue; + } + + // The seed can be dynamic or kinematic. + if (seed->GetType() == b2_staticBody) + { + continue; + } + + // Reset island and stack. + island.Clear(); + int32 stackCount = 0; + stack[stackCount++] = seed; + seed->m_flags |= b2Body::e_islandFlag; + + // Perform a depth first search (DFS) on the constraint graph. + while (stackCount > 0) + { + // Grab the next body off the stack and add it to the island. + b2Body* b = stack[--stackCount]; + b2Assert(b->IsActive() == true); + island.Add(b); + + // Make sure the body is awake. + b->SetAwake(true); + + // To keep islands as small as possible, we don't + // propagate islands across static bodies. + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Search all contacts connected to this body. + for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) + { + b2Contact* contact = ce->contact; + + // Has this contact already been added to an island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Is this contact solid and touching? + if (contact->IsEnabled() == false || + contact->IsTouching() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + island.Add(contact); + contact->m_flags |= b2Contact::e_islandFlag; + + b2Body* other = ce->other; + + // Was the other body already added to this island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + + // Search all joints connect to this body. + for (b2JointEdge* je = b->m_jointList; je; je = je->next) + { + if (je->joint->m_islandFlag == true) + { + continue; + } + + b2Body* other = je->other; + + // Don't simulate joints connected to inactive bodies. + if (other->IsActive() == false) + { + continue; + } + + island.Add(je->joint); + je->joint->m_islandFlag = true; + + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + } + + b2Profile profile; + island.Solve(&profile, step, m_gravity, m_allowSleep); + m_profile.solveInit += profile.solveInit; + m_profile.solveVelocity += profile.solveVelocity; + m_profile.solvePosition += profile.solvePosition; + + // Post solve cleanup. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + // Allow static bodies to participate in other islands. + b2Body* b = island.m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + } + } + + m_stackAllocator.Free(stack); + + { + b2Timer timer; + // Synchronize fixtures, check for out of range bodies. + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + // If a body was not in an island then it did not move. + if ((b->m_flags & b2Body::e_islandFlag) == 0) + { + continue; + } + + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Update fixtures (for broad-phase). + b->SynchronizeFixtures(); + } + + // Look for new contacts. + m_contactManager.FindNewContacts(); + m_profile.broadphase = timer.GetMilliseconds(); + } +} + +// Find TOI contacts and solve them. +void b2World::SolveTOI(const b2TimeStep& step) +{ + b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); + + if (m_stepComplete) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + b->m_sweep.alpha0 = 0.0f; + } + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Invalidate TOI + c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + c->m_toiCount = 0; + c->m_toi = 1.0f; + } + } + + // Find TOI events and solve them. + for (;;) + { + // Find the first TOI. + b2Contact* minContact = NULL; + float32 minAlpha = 1.0f; + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Is this contact disabled? + if (c->IsEnabled() == false) + { + continue; + } + + // Prevent excessive sub-stepping. + if (c->m_toiCount > b2_maxSubSteps) + { + continue; + } + + float32 alpha = 1.0f; + if (c->m_flags & b2Contact::e_toiFlag) + { + // This contact has a valid cached TOI. + alpha = c->m_toi; + } + else + { + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + // Is there a sensor? + if (fA->IsSensor() || fB->IsSensor()) + { + continue; + } + + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + b2BodyType typeA = bA->m_type; + b2BodyType typeB = bB->m_type; + b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); + + bool activeA = bA->IsAwake() && typeA != b2_staticBody; + bool activeB = bB->IsAwake() && typeB != b2_staticBody; + + // Is at least one body active (awake and dynamic or kinematic)? + if (activeA == false && activeB == false) + { + continue; + } + + bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; + bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; + + // Are these two non-bullet dynamic bodies? + if (collideA == false && collideB == false) + { + continue; + } + + // Compute the TOI for this contact. + // Put the sweeps onto the same time interval. + float32 alpha0 = bA->m_sweep.alpha0; + + if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) + { + alpha0 = bB->m_sweep.alpha0; + bA->m_sweep.Advance(alpha0); + } + else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) + { + alpha0 = bA->m_sweep.alpha0; + bB->m_sweep.Advance(alpha0); + } + + b2Assert(alpha0 < 1.0f); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + // Compute the time of impact in interval [0, minTOI] + b2TOIInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.sweepA = bA->m_sweep; + input.sweepB = bB->m_sweep; + input.tMax = 1.0f; + + b2TOIOutput output; + b2TimeOfImpact(&output, &input); + + // Beta is the fraction of the remaining portion of the . + float32 beta = output.t; + if (output.state == b2TOIOutput::e_touching) + { + alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); + } + else + { + alpha = 1.0f; + } + + c->m_toi = alpha; + c->m_flags |= b2Contact::e_toiFlag; + } + + if (alpha < minAlpha) + { + // This is the minimum TOI found so far. + minContact = c; + minAlpha = alpha; + } + } + + if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) + { + // No more TOI events. Done! + m_stepComplete = true; + break; + } + + // Advance the bodies to the TOI. + b2Fixture* fA = minContact->GetFixtureA(); + b2Fixture* fB = minContact->GetFixtureB(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + b2Sweep backup1 = bA->m_sweep; + b2Sweep backup2 = bB->m_sweep; + + bA->Advance(minAlpha); + bB->Advance(minAlpha); + + // The TOI contact likely has some new contact points. + minContact->Update(m_contactManager.m_contactListener); + minContact->m_flags &= ~b2Contact::e_toiFlag; + ++minContact->m_toiCount; + + // Is the contact solid? + if (minContact->IsEnabled() == false || minContact->IsTouching() == false) + { + // Restore the sweeps. + minContact->SetEnabled(false); + bA->m_sweep = backup1; + bB->m_sweep = backup2; + bA->SynchronizeTransform(); + bB->SynchronizeTransform(); + continue; + } + + bA->SetAwake(true); + bB->SetAwake(true); + + // Build the island + island.Clear(); + island.Add(bA); + island.Add(bB); + island.Add(minContact); + + bA->m_flags |= b2Body::e_islandFlag; + bB->m_flags |= b2Body::e_islandFlag; + minContact->m_flags |= b2Contact::e_islandFlag; + + // Get contacts on bodyA and bodyB. + b2Body* bodies[2] = {bA, bB}; + for (int32 i = 0; i < 2; ++i) + { + b2Body* body = bodies[i]; + if (body->m_type == b2_dynamicBody) + { + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + if (island.m_bodyCount == island.m_bodyCapacity) + { + break; + } + + if (island.m_contactCount == island.m_contactCapacity) + { + break; + } + + b2Contact* contact = ce->contact; + + // Has this contact already been added to the island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Only add static, kinematic, or bullet bodies. + b2Body* other = ce->other; + if (other->m_type == b2_dynamicBody && + body->IsBullet() == false && other->IsBullet() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + // Tentatively advance the body to the TOI. + b2Sweep backup = other->m_sweep; + if ((other->m_flags & b2Body::e_islandFlag) == 0) + { + other->Advance(minAlpha); + } + + // Update the contact points + contact->Update(m_contactManager.m_contactListener); + + // Was the contact disabled by the user? + if (contact->IsEnabled() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Are there contact points? + if (contact->IsTouching() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Add the contact to the island + contact->m_flags |= b2Contact::e_islandFlag; + island.Add(contact); + + // Has the other body already been added to the island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + // Add the other body to the island. + other->m_flags |= b2Body::e_islandFlag; + + if (other->m_type != b2_staticBody) + { + other->SetAwake(true); + } + + island.Add(other); + } + } + } + + b2TimeStep subStep; + subStep.dt = (1.0f - minAlpha) * step.dt; + subStep.inv_dt = 1.0f / subStep.dt; + subStep.dtRatio = 1.0f; + subStep.positionIterations = 20; + subStep.velocityIterations = step.velocityIterations; + subStep.warmStarting = false; + island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); + + // Reset island flags and synchronize broad-phase proxies. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + b2Body* body = island.m_bodies[i]; + body->m_flags &= ~b2Body::e_islandFlag; + + if (body->m_type != b2_dynamicBody) + { + continue; + } + + body->SynchronizeFixtures(); + + // Invalidate all contact TOIs on this displaced body. + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + } + } + + // Commit fixture proxy movements to the broad-phase so that new contacts are created. + // Also, some contacts can be destroyed. + m_contactManager.FindNewContacts(); + + if (m_subStepping) + { + m_stepComplete = false; + break; + } + } +} + +void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) +{ + b2Timer stepTimer; + + // If new fixtures were added, we need to find the new contacts. + if (m_flags & e_newFixture) + { + m_contactManager.FindNewContacts(); + m_flags &= ~e_newFixture; + } + + m_flags |= e_locked; + + b2TimeStep step; + step.dt = dt; + step.velocityIterations = velocityIterations; + step.positionIterations = positionIterations; + if (dt > 0.0f) + { + step.inv_dt = 1.0f / dt; + } + else + { + step.inv_dt = 0.0f; + } + + step.dtRatio = m_inv_dt0 * dt; + + step.warmStarting = m_warmStarting; + + // Update contacts. This is where some contacts are destroyed. + { + b2Timer timer; + m_contactManager.Collide(); + m_profile.collide = timer.GetMilliseconds(); + } + + // Integrate velocities, solve velocity constraints, and integrate positions. + if (m_stepComplete && step.dt > 0.0f) + { + b2Timer timer; + Solve(step); + m_profile.solve = timer.GetMilliseconds(); + } + + // Handle TOI events. + if (m_continuousPhysics && step.dt > 0.0f) + { + b2Timer timer; + SolveTOI(step); + m_profile.solveTOI = timer.GetMilliseconds(); + } + + if (step.dt > 0.0f) + { + m_inv_dt0 = step.inv_dt; + } + + if (m_flags & e_clearForces) + { + ClearForces(); + } + + m_flags &= ~e_locked; + + m_profile.step = stepTimer.GetMilliseconds(); +} + +void b2World::ClearForces() +{ + for (b2Body* body = m_bodyList; body; body = body->GetNext()) + { + body->m_force.SetZero(); + body->m_torque = 0.0f; + } +} + +struct b2WorldQueryWrapper +{ + bool QueryCallback(int32 proxyId) + { + b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); + return callback->ReportFixture(proxy->fixture); + } + + const b2BroadPhase* broadPhase; + b2QueryCallback* callback; +}; + +void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const +{ + b2WorldQueryWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + m_contactManager.m_broadPhase.Query(&wrapper, aabb); +} + +struct b2WorldRayCastWrapper +{ + float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + void* userData = broadPhase->GetUserData(proxyId); + b2FixtureProxy* proxy = (b2FixtureProxy*)userData; + b2Fixture* fixture = proxy->fixture; + int32 index = proxy->childIndex; + b2RayCastOutput output; + bool hit = fixture->RayCast(&output, input, index); + + if (hit) + { + float32 fraction = output.fraction; + b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; + return callback->ReportFixture(fixture, point, output.normal, fraction); + } + + return input.maxFraction; + } + + const b2BroadPhase* broadPhase; + b2RayCastCallback* callback; +}; + +void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const +{ + b2WorldRayCastWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + b2RayCastInput input; + input.maxFraction = 1.0f; + input.p1 = point1; + input.p2 = point2; + m_contactManager.m_broadPhase.RayCast(&wrapper, input); +} + +void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) +{ + switch (fixture->GetType()) + { + case b2Shape::e_circle: + { + b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); + + b2Vec2 center = b2Mul(xf, circle->m_p); + float32 radius = circle->m_radius; + b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); + + m_debugDraw->DrawSolidCircle(center, radius, axis, color); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); + b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); + b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); + m_debugDraw->DrawSegment(v1, v2, color); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); + int32 count = chain->m_count; + const b2Vec2* vertices = chain->m_vertices; + + b2Vec2 v1 = b2Mul(xf, vertices[0]); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v2 = b2Mul(xf, vertices[i]); + m_debugDraw->DrawSegment(v1, v2, color); + m_debugDraw->DrawCircle(v1, 0.05f, color); + v1 = v2; + } + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); + int32 vertexCount = poly->m_vertexCount; + b2Assert(vertexCount <= b2_maxPolygonVertices); + b2Vec2 vertices[b2_maxPolygonVertices]; + + for (int32 i = 0; i < vertexCount; ++i) + { + vertices[i] = b2Mul(xf, poly->m_vertices[i]); + } + + m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); + } + break; + + default: + break; + } +} + +void b2World::DrawJoint(b2Joint* joint) +{ + b2Body* bodyA = joint->GetBodyA(); + b2Body* bodyB = joint->GetBodyB(); + const b2Transform& xf1 = bodyA->GetTransform(); + const b2Transform& xf2 = bodyB->GetTransform(); + b2Vec2 x1 = xf1.p; + b2Vec2 x2 = xf2.p; + b2Vec2 p1 = joint->GetAnchorA(); + b2Vec2 p2 = joint->GetAnchorB(); + + b2Color color(0.5f, 0.8f, 0.8f); + + switch (joint->GetType()) + { + case e_distanceJoint: + m_debugDraw->DrawSegment(p1, p2, color); + break; + + case e_pulleyJoint: + { + b2PulleyJoint* pulley = (b2PulleyJoint*)joint; + b2Vec2 s1 = pulley->GetGroundAnchorA(); + b2Vec2 s2 = pulley->GetGroundAnchorB(); + m_debugDraw->DrawSegment(s1, p1, color); + m_debugDraw->DrawSegment(s2, p2, color); + m_debugDraw->DrawSegment(s1, s2, color); + } + break; + + case e_mouseJoint: + // don't draw this + break; + + default: + m_debugDraw->DrawSegment(x1, p1, color); + m_debugDraw->DrawSegment(p1, p2, color); + m_debugDraw->DrawSegment(x2, p2, color); + } +} + +void b2World::DrawDebugData() +{ + if (m_debugDraw == NULL) + { + return; + } + + uint32 flags = m_debugDraw->GetFlags(); + + if (flags & b2Draw::e_shapeBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + const b2Transform& xf = b->GetTransform(); + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + if (b->IsActive() == false) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); + } + else if (b->GetType() == b2_staticBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); + } + else if (b->GetType() == b2_kinematicBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); + } + else if (b->IsAwake() == false) + { + DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); + } + else + { + DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); + } + } + } + } + + if (flags & b2Draw::e_jointBit) + { + for (b2Joint* j = m_jointList; j; j = j->GetNext()) + { + DrawJoint(j); + } + } + + if (flags & b2Draw::e_pairBit) + { + b2Color color(0.3f, 0.9f, 0.9f); + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) + { + //b2Fixture* fixtureA = c->GetFixtureA(); + //b2Fixture* fixtureB = c->GetFixtureB(); + + //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); + //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); + + //m_debugDraw->DrawSegment(cA, cB, color); + } + } + + if (flags & b2Draw::e_aabbBit) + { + b2Color color(0.9f, 0.3f, 0.9f); + b2BroadPhase* bp = &m_contactManager.m_broadPhase; + + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + if (b->IsActive() == false) + { + continue; + } + + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + for (int32 i = 0; i < f->m_proxyCount; ++i) + { + b2FixtureProxy* proxy = f->m_proxies + i; + b2AABB aabb = bp->GetFatAABB(proxy->proxyId); + b2Vec2 vs[4]; + vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); + vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); + vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); + vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); + + m_debugDraw->DrawPolygon(vs, 4, color); + } + } + } + } + + if (flags & b2Draw::e_centerOfMassBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + b2Transform xf = b->GetTransform(); + xf.p = b->GetWorldCenter(); + m_debugDraw->DrawTransform(xf); + } + } +} + +int32 b2World::GetProxyCount() const +{ + return m_contactManager.m_broadPhase.GetProxyCount(); +} + +int32 b2World::GetTreeHeight() const +{ + return m_contactManager.m_broadPhase.GetTreeHeight(); +} + +int32 b2World::GetTreeBalance() const +{ + return m_contactManager.m_broadPhase.GetTreeBalance(); +} + +float32 b2World::GetTreeQuality() const +{ + return m_contactManager.m_broadPhase.GetTreeQuality(); +} + +void b2World::Dump() +{ + if ((m_flags & e_locked) == e_locked) + { + return; + } + + b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); + b2Log("m_world->SetGravity(g);\n"); + + b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); + b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); + int32 i = 0; + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_islandIndex = i; + b->Dump(); + ++i; + } + + i = 0; + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_index = i; + ++i; + } + + // First pass on joints, skip gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type == e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + // Second pass on joints, only gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type != e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + b2Log("b2Free(joints);\n"); + b2Log("b2Free(bodies);\n"); + b2Log("joints = NULL;\n"); + b2Log("bodies = NULL;\n"); +} diff --git a/external/box2d/Dynamics/b2World.h b/external/box2d/Dynamics/b2World.h new file mode 100644 index 0000000000..f207930511 --- /dev/null +++ b/external/box2d/Dynamics/b2World.h @@ -0,0 +1,349 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WORLD_H +#define B2_WORLD_H + +#include +#include +#include +#include +#include +#include + +struct b2AABB; +struct b2BodyDef; +struct b2Color; +struct b2JointDef; +class b2Body; +class b2Draw; +class b2Fixture; +class b2Joint; + +/// The world class manages all physics entities, dynamic simulation, +/// and asynchronous queries. The world also contains efficient memory +/// management facilities. +class b2World +{ +public: + /// Construct a world object. + /// @param gravity the world gravity vector. + b2World(const b2Vec2& gravity); + + /// Destruct the world. All physics entities are destroyed and all heap memory is released. + ~b2World(); + + /// Register a destruction listener. The listener is owned by you and must + /// remain in scope. + void SetDestructionListener(b2DestructionListener* listener); + + /// Register a contact filter to provide specific control over collision. + /// Otherwise the default filter is used (b2_defaultFilter). The listener is + /// owned by you and must remain in scope. + void SetContactFilter(b2ContactFilter* filter); + + /// Register a contact event listener. The listener is owned by you and must + /// remain in scope. + void SetContactListener(b2ContactListener* listener); + + /// Register a routine for debug drawing. The debug draw functions are called + /// inside with b2World::DrawDebugData method. The debug draw object is owned + /// by you and must remain in scope. + void SetDebugDraw(b2Draw* debugDraw); + + /// Create a rigid body given a definition. No reference to the definition + /// is retained. + /// @warning This function is locked during callbacks. + b2Body* CreateBody(const b2BodyDef* def); + + /// Destroy a rigid body given a definition. No reference to the definition + /// is retained. This function is locked during callbacks. + /// @warning This automatically deletes all associated shapes and joints. + /// @warning This function is locked during callbacks. + void DestroyBody(b2Body* body); + + /// Create a joint to constrain bodies together. No reference to the definition + /// is retained. This may cause the connected bodies to cease colliding. + /// @warning This function is locked during callbacks. + b2Joint* CreateJoint(const b2JointDef* def); + + /// Destroy a joint. This may cause the connected bodies to begin colliding. + /// @warning This function is locked during callbacks. + void DestroyJoint(b2Joint* joint); + + /// Take a time step. This performs collision detection, integration, + /// and constraint solution. + /// @param timeStep the amount of time to simulate, this should not vary. + /// @param velocityIterations for the velocity constraint solver. + /// @param positionIterations for the position constraint solver. + void Step( float32 timeStep, + int32 velocityIterations, + int32 positionIterations); + + /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically + /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. + /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain + /// a fixed sized time step under a variable frame-rate. + /// When you perform sub-stepping you will disable auto clearing of forces and instead call + /// ClearForces after all sub-steps are complete in one pass of your game loop. + /// @see SetAutoClearForces + void ClearForces(); + + /// Call this to draw shapes and other debug draw data. + void DrawDebugData(); + + /// Query the world for all fixtures that potentially overlap the + /// provided AABB. + /// @param callback a user implemented callback class. + /// @param aabb the query box. + void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; + + /// Ray-cast the world for all fixtures in the path of the ray. Your callback + /// controls whether you get the closest point, any point, or n-points. + /// The ray-cast ignores shapes that contain the starting point. + /// @param callback a user implemented callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point + void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; + + /// Get the world body list. With the returned body, use b2Body::GetNext to get + /// the next body in the world list. A NULL body indicates the end of the list. + /// @return the head of the world body list. + b2Body* GetBodyList(); + const b2Body* GetBodyList() const; + + /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get + /// the next joint in the world list. A NULL joint indicates the end of the list. + /// @return the head of the world joint list. + b2Joint* GetJointList(); + const b2Joint* GetJointList() const; + + /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get + /// the next contact in the world list. A NULL contact indicates the end of the list. + /// @return the head of the world contact list. + /// @warning contacts are created and destroyed in the middle of a time step. + /// Use b2ContactListener to avoid missing contacts. + b2Contact* GetContactList(); + const b2Contact* GetContactList() const; + + /// Enable/disable sleep. + void SetAllowSleeping(bool flag); + bool GetAllowSleeping() const { return m_allowSleep; } + + /// Enable/disable warm starting. For testing. + void SetWarmStarting(bool flag) { m_warmStarting = flag; } + bool GetWarmStarting() const { return m_warmStarting; } + + /// Enable/disable continuous physics. For testing. + void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + bool GetContinuousPhysics() const { return m_continuousPhysics; } + + /// Enable/disable single stepped continuous physics. For testing. + void SetSubStepping(bool flag) { m_subStepping = flag; } + bool GetSubStepping() const { return m_subStepping; } + + /// Get the number of broad-phase proxies. + int32 GetProxyCount() const; + + /// Get the number of bodies. + int32 GetBodyCount() const; + + /// Get the number of joints. + int32 GetJointCount() const; + + /// Get the number of contacts (each may have 0 or more contact points). + int32 GetContactCount() const; + + /// Get the height of the dynamic tree. + int32 GetTreeHeight() const; + + /// Get the balance of the dynamic tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the dynamic tree. The smaller the better. + /// The minimum is 1. + float32 GetTreeQuality() const; + + /// Change the global gravity vector. + void SetGravity(const b2Vec2& gravity); + + /// Get the global gravity vector. + b2Vec2 GetGravity() const; + + /// Is the world locked (in the middle of a time step). + bool IsLocked() const; + + /// Set flag to control automatic clearing of forces after each time step. + void SetAutoClearForces(bool flag); + + /// Get the flag that controls automatic clearing of forces after each time step. + bool GetAutoClearForces() const; + + /// Get the contact manager for testing. + const b2ContactManager& GetContactManager() const; + + /// Get the current profile. + const b2Profile& GetProfile() const; + + /// Dump the world into the log file. + /// @warning this should be called outside of a time step. + void Dump(); + +private: + + // m_flags + enum + { + e_newFixture = 0x0001, + e_locked = 0x0002, + e_clearForces = 0x0004 + }; + + friend class b2Body; + friend class b2Fixture; + friend class b2ContactManager; + friend class b2Controller; + + void Solve(const b2TimeStep& step); + void SolveTOI(const b2TimeStep& step); + + void DrawJoint(b2Joint* joint); + void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); + + b2BlockAllocator m_blockAllocator; + b2StackAllocator m_stackAllocator; + + int32 m_flags; + + b2ContactManager m_contactManager; + + b2Body* m_bodyList; + b2Joint* m_jointList; + + int32 m_bodyCount; + int32 m_jointCount; + + b2Vec2 m_gravity; + bool m_allowSleep; + + b2DestructionListener* m_destructionListener; + b2Draw* m_debugDraw; + + // This is used to compute the time step ratio to + // support a variable time step. + float32 m_inv_dt0; + + // These are for debugging the solver. + bool m_warmStarting; + bool m_continuousPhysics; + bool m_subStepping; + + bool m_stepComplete; + + b2Profile m_profile; +}; + +inline b2Body* b2World::GetBodyList() +{ + return m_bodyList; +} + +inline const b2Body* b2World::GetBodyList() const +{ + return m_bodyList; +} + +inline b2Joint* b2World::GetJointList() +{ + return m_jointList; +} + +inline const b2Joint* b2World::GetJointList() const +{ + return m_jointList; +} + +inline b2Contact* b2World::GetContactList() +{ + return m_contactManager.m_contactList; +} + +inline const b2Contact* b2World::GetContactList() const +{ + return m_contactManager.m_contactList; +} + +inline int32 b2World::GetBodyCount() const +{ + return m_bodyCount; +} + +inline int32 b2World::GetJointCount() const +{ + return m_jointCount; +} + +inline int32 b2World::GetContactCount() const +{ + return m_contactManager.m_contactCount; +} + +inline void b2World::SetGravity(const b2Vec2& gravity) +{ + m_gravity = gravity; +} + +inline b2Vec2 b2World::GetGravity() const +{ + return m_gravity; +} + +inline bool b2World::IsLocked() const +{ + return (m_flags & e_locked) == e_locked; +} + +inline void b2World::SetAutoClearForces(bool flag) +{ + if (flag) + { + m_flags |= e_clearForces; + } + else + { + m_flags &= ~e_clearForces; + } +} + +/// Get the flag that controls automatic clearing of forces after each time step. +inline bool b2World::GetAutoClearForces() const +{ + return (m_flags & e_clearForces) == e_clearForces; +} + +inline const b2ContactManager& b2World::GetContactManager() const +{ + return m_contactManager; +} + +inline const b2Profile& b2World::GetProfile() const +{ + return m_profile; +} + +#endif diff --git a/external/box2d/Dynamics/b2WorldCallbacks.cpp b/external/box2d/Dynamics/b2WorldCallbacks.cpp new file mode 100644 index 0000000000..48ad0cc46a --- /dev/null +++ b/external/box2d/Dynamics/b2WorldCallbacks.cpp @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +// Return true if contact calculations should be performed between these two shapes. +// If you implement your own collision filter you may want to build from this implementation. +bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) +{ + const b2Filter& filterA = fixtureA->GetFilterData(); + const b2Filter& filterB = fixtureB->GetFilterData(); + + if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) + { + return filterA.groupIndex > 0; + } + + bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; + return collide; +} diff --git a/external/box2d/Dynamics/b2WorldCallbacks.h b/external/box2d/Dynamics/b2WorldCallbacks.h new file mode 100644 index 0000000000..86c04e3e32 --- /dev/null +++ b/external/box2d/Dynamics/b2WorldCallbacks.h @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WORLD_CALLBACKS_H +#define B2_WORLD_CALLBACKS_H + +#include + +struct b2Vec2; +struct b2Transform; +class b2Fixture; +class b2Body; +class b2Joint; +class b2Contact; +struct b2ContactResult; +struct b2Manifold; + +/// Joints and fixtures are destroyed when their associated +/// body is destroyed. Implement this listener so that you +/// may nullify references to these joints and shapes. +class b2DestructionListener +{ +public: + virtual ~b2DestructionListener() {} + + /// Called when any joint is about to be destroyed due + /// to the destruction of one of its attached bodies. + virtual void SayGoodbye(b2Joint* joint) = 0; + + /// Called when any fixture is about to be destroyed due + /// to the destruction of its parent body. + virtual void SayGoodbye(b2Fixture* fixture) = 0; +}; + +/// Implement this class to provide collision filtering. In other words, you can implement +/// this class if you want finer control over contact creation. +class b2ContactFilter +{ +public: + virtual ~b2ContactFilter() {} + + /// Return true if contact calculations should be performed between these two shapes. + /// @warning for performance reasons this is only called when the AABBs begin to overlap. + virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); +}; + +/// Contact impulses for reporting. Impulses are used instead of forces because +/// sub-step forces may approach infinity for rigid body collisions. These +/// match up one-to-one with the contact points in b2Manifold. +struct b2ContactImpulse +{ + float32 normalImpulses[b2_maxManifoldPoints]; + float32 tangentImpulses[b2_maxManifoldPoints]; + int32 count; +}; + +/// Implement this class to get contact information. You can use these results for +/// things like sounds and game logic. You can also get contact results by +/// traversing the contact lists after the time step. However, you might miss +/// some contacts because continuous physics leads to sub-stepping. +/// Additionally you may receive multiple callbacks for the same contact in a +/// single time step. +/// You should strive to make your callbacks efficient because there may be +/// many callbacks per time step. +/// @warning You cannot create/destroy Box2D entities inside these callbacks. +class b2ContactListener +{ +public: + virtual ~b2ContactListener() {} + + /// Called when two fixtures begin to touch. + virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } + + /// Called when two fixtures cease to touch. + virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } + + /// This is called after a contact is updated. This allows you to inspect a + /// contact before it goes to the solver. If you are careful, you can modify the + /// contact manifold (e.g. disable contact). + /// A copy of the old manifold is provided so that you can detect changes. + /// Note: this is called only for awake bodies. + /// Note: this is called even when the number of contact points is zero. + /// Note: this is not called for sensors. + /// Note: if you set the number of contact points to zero, you will not + /// get an EndContact callback. However, you may get a BeginContact callback + /// the next step. + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + B2_NOT_USED(contact); + B2_NOT_USED(oldManifold); + } + + /// This lets you inspect a contact after the solver is finished. This is useful + /// for inspecting impulses. + /// Note: the contact manifold does not include time of impact impulses, which can be + /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly + /// in a separate data structure. + /// Note: this is only called for contacts that are touching, solid, and awake. + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } +}; + +/// Callback class for AABB queries. +/// See b2World::Query +class b2QueryCallback +{ +public: + virtual ~b2QueryCallback() {} + + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + virtual bool ReportFixture(b2Fixture* fixture) = 0; +}; + +/// Callback class for ray casts. +/// See b2World::RayCast +class b2RayCastCallback +{ +public: + virtual ~b2RayCastCallback() {} + + /// Called for each fixture found in the query. You control how the ray cast + /// proceeds by returning a float: + /// return -1: ignore this fixture and continue + /// return 0: terminate the ray cast + /// return fraction: clip the ray to this point + /// return 1: don't clip the ray and continue + /// @param fixture the fixture hit by the ray + /// @param point the point of initial intersection + /// @param normal the normal vector at the point of intersection + /// @return -1 to filter, 0 to terminate, fraction to clip the ray for + /// closest hit, 1 to continue + virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float32 fraction) = 0; +}; + +#endif diff --git a/external/box2d/Rope/b2Rope.cpp b/external/box2d/Rope/b2Rope.cpp new file mode 100644 index 0000000000..9bf671aec9 --- /dev/null +++ b/external/box2d/Rope/b2Rope.cpp @@ -0,0 +1,259 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Rope::b2Rope() +{ + m_count = 0; + m_ps = NULL; + m_p0s = NULL; + m_vs = NULL; + m_ims = NULL; + m_Ls = NULL; + m_as = NULL; + m_gravity.SetZero(); + m_k2 = 1.0f; + m_k3 = 0.1f; +} + +b2Rope::~b2Rope() +{ + b2Free(m_ps); + b2Free(m_p0s); + b2Free(m_vs); + b2Free(m_ims); + b2Free(m_Ls); + b2Free(m_as); +} + +void b2Rope::Initialize(const b2RopeDef* def) +{ + b2Assert(def->count >= 3); + m_count = def->count; + m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); + + for (int32 i = 0; i < m_count; ++i) + { + m_ps[i] = def->vertices[i]; + m_p0s[i] = def->vertices[i]; + m_vs[i].SetZero(); + + float32 m = def->masses[i]; + if (m > 0.0f) + { + m_ims[i] = 1.0f / m; + } + else + { + m_ims[i] = 0.0f; + } + } + + int32 count2 = m_count - 1; + int32 count3 = m_count - 2; + m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); + m_as = (float32*)b2Alloc(count3 * sizeof(float32)); + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i+1]; + m_Ls[i] = b2Distance(p1, p2); + } + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + m_as[i] = b2Atan2(a, b); + } + + m_gravity = def->gravity; + m_damping = def->damping; + m_k2 = def->k2; + m_k3 = def->k3; +} + +void b2Rope::Step(float32 h, int32 iterations) +{ + if (h == 0.0) + { + return; + } + + float32 d = expf(- h * m_damping); + + for (int32 i = 0; i < m_count; ++i) + { + m_p0s[i] = m_ps[i]; + if (m_ims[i] > 0.0f) + { + m_vs[i] += h * m_gravity; + } + m_vs[i] *= d; + m_ps[i] += h * m_vs[i]; + + } + + for (int32 i = 0; i < iterations; ++i) + { + SolveC2(); + SolveC3(); + SolveC2(); + } + + float32 inv_h = 1.0f / h; + for (int32 i = 0; i < m_count; ++i) + { + m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); + } +} + +void b2Rope::SolveC2() +{ + int32 count2 = m_count - 1; + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + + b2Vec2 d = p2 - p1; + float32 L = d.Normalize(); + + float32 im1 = m_ims[i]; + float32 im2 = m_ims[i + 1]; + + if (im1 + im2 == 0.0f) + { + continue; + } + + float32 s1 = im1 / (im1 + im2); + float32 s2 = im2 / (im1 + im2); + + p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; + p2 += m_k2 * s2 * (m_Ls[i] - L) * d; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + } +} + +void b2Rope::SetAngle(float32 angle) +{ + int32 count3 = m_count - 2; + for (int32 i = 0; i < count3; ++i) + { + m_as[i] = angle; + } +} + +void b2Rope::SolveC3() +{ + int32 count3 = m_count - 2; + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + float32 m1 = m_ims[i]; + float32 m2 = m_ims[i + 1]; + float32 m3 = m_ims[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 L1sqr = d1.LengthSquared(); + float32 L2sqr = d2.LengthSquared(); + + if (L1sqr * L2sqr == 0.0f) + { + continue; + } + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + float32 angle = b2Atan2(a, b); + + b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); + b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); + + b2Vec2 J1 = -Jd1; + b2Vec2 J2 = Jd1 - Jd2; + b2Vec2 J3 = Jd2; + + float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); + if (mass == 0.0f) + { + continue; + } + + mass = 1.0f / mass; + + float32 C = angle - m_as[i]; + + while (C > b2_pi) + { + angle -= 2 * b2_pi; + C = angle - m_as[i]; + } + + while (C < -b2_pi) + { + angle += 2.0f * b2_pi; + C = angle - m_as[i]; + } + + float32 impulse = - m_k3 * mass * C; + + p1 += (m1 * impulse) * J1; + p2 += (m2 * impulse) * J2; + p3 += (m3 * impulse) * J3; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + m_ps[i + 2] = p3; + } +} + +void b2Rope::Draw(b2Draw* draw) const +{ + b2Color c(0.4f, 0.5f, 0.7f); + + for (int32 i = 0; i < m_count - 1; ++i) + { + draw->DrawSegment(m_ps[i], m_ps[i+1], c); + } +} diff --git a/external/box2d/Rope/b2Rope.h b/external/box2d/Rope/b2Rope.h new file mode 100644 index 0000000000..b981dfd6c5 --- /dev/null +++ b/external/box2d/Rope/b2Rope.h @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_H +#define B2_ROPE_H + +#include + +class b2Draw; + +/// +struct b2RopeDef +{ + b2RopeDef() + { + vertices = NULL; + count = 0; + masses = NULL; + gravity.SetZero(); + damping = 0.1f; + k2 = 0.9f; + k3 = 0.1f; + } + + /// + b2Vec2* vertices; + + /// + int32 count; + + /// + float32* masses; + + /// + b2Vec2 gravity; + + /// + float32 damping; + + /// Stretching stiffness + float32 k2; + + /// Bending stiffness. Values above 0.5 can make the simulation blow up. + float32 k3; +}; + +/// +class b2Rope +{ +public: + b2Rope(); + ~b2Rope(); + + /// + void Initialize(const b2RopeDef* def); + + /// + void Step(float32 timeStep, int32 iterations); + + /// + int32 GetVertexCount() const + { + return m_count; + } + + /// + const b2Vec2* GetVertices() const + { + return m_ps; + } + + /// + void Draw(b2Draw* draw) const; + + /// + void SetAngle(float32 angle); + +private: + + void SolveC2(); + void SolveC3(); + + int32 m_count; + b2Vec2* m_ps; + b2Vec2* m_p0s; + b2Vec2* m_vs; + + float32* m_ims; + + float32* m_Ls; + float32* m_as; + + b2Vec2 m_gravity; + float32 m_damping; + + float32 m_k2; + float32 m_k3; +}; + +#endif diff --git a/external/box2d/proj.linux/.cproject b/external/box2d/proj.linux/.cproject new file mode 100644 index 0000000000..5aa092cac3 --- /dev/null +++ b/external/box2d/proj.linux/.cproject @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/box2d/proj.linux/.project b/external/box2d/proj.linux/.project new file mode 100644 index 0000000000..164d50f52a --- /dev/null +++ b/external/box2d/proj.linux/.project @@ -0,0 +1,110 @@ + + + libBox2D + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:/libBox2D/Debug} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + Box2D.h + 1 + PARENT-1-PROJECT_LOC/Box2D.h + + + Collision + 2 + PARENT-1-PROJECT_LOC/Collision + + + Common + 2 + PARENT-1-PROJECT_LOC/Common + + + Dynamics + 2 + PARENT-1-PROJECT_LOC/Dynamics + + + Rope + 2 + PARENT-1-PROJECT_LOC/Rope + + + diff --git a/external/box2d/proj.linux/Makefile b/external/box2d/proj.linux/Makefile new file mode 100644 index 0000000000..e430bc9883 --- /dev/null +++ b/external/box2d/proj.linux/Makefile @@ -0,0 +1,72 @@ +TARGET = libbox2d.a + +SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ +../Collision/Shapes/b2CircleShape.cpp \ +../Collision/Shapes/b2EdgeShape.cpp \ +../Collision/Shapes/b2PolygonShape.cpp \ +../Collision/b2BroadPhase.cpp \ +../Collision/b2CollideCircle.cpp \ +../Collision/b2CollideEdge.cpp \ +../Collision/b2CollidePolygon.cpp \ +../Collision/b2Collision.cpp \ +../Collision/b2Distance.cpp \ +../Collision/b2DynamicTree.cpp \ +../Collision/b2TimeOfImpact.cpp \ +../Common/b2BlockAllocator.cpp \ +../Common/b2Draw.cpp \ +../Common/b2Math.cpp \ +../Common/b2Settings.cpp \ +../Common/b2StackAllocator.cpp \ +../Common/b2Timer.cpp \ +../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +../Dynamics/Contacts/b2CircleContact.cpp \ +../Dynamics/Contacts/b2Contact.cpp \ +../Dynamics/Contacts/b2ContactSolver.cpp \ +../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +../Dynamics/Contacts/b2PolygonContact.cpp \ +../Dynamics/Joints/b2DistanceJoint.cpp \ +../Dynamics/Joints/b2FrictionJoint.cpp \ +../Dynamics/Joints/b2GearJoint.cpp \ +../Dynamics/Joints/b2Joint.cpp \ +../Dynamics/Joints/b2MouseJoint.cpp \ +../Dynamics/Joints/b2PrismaticJoint.cpp \ +../Dynamics/Joints/b2PulleyJoint.cpp \ +../Dynamics/Joints/b2RevoluteJoint.cpp \ +../Dynamics/Joints/b2RopeJoint.cpp \ +../Dynamics/Joints/b2WeldJoint.cpp \ +../Dynamics/Joints/b2WheelJoint.cpp \ +../Dynamics/b2Body.cpp \ +../Dynamics/b2ContactManager.cpp \ +../Dynamics/b2Fixture.cpp \ +../Dynamics/b2Island.cpp \ +../Dynamics/b2World.cpp \ +../Dynamics/b2WorldCallbacks.cpp \ +../Rope/b2Rope.cpp + +include ../../../cocos2dx/proj.linux/cocos2dx.mk + +INCLUDES = -I../.. + +# Cocos2d is not responsible for warnings in external projects +CXXFLAGS += -w + +ifeq ($(DEBUG), 1) +DEFINES = -D_DEBUG +else +DEFINES = +endif + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) + +$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/box2d/proj.linux/box2d.prf b/external/box2d/proj.linux/box2d.prf new file mode 100644 index 0000000000..434ad88406 --- /dev/null +++ b/external/box2d/proj.linux/box2d.prf @@ -0,0 +1,19 @@ +################################################################################ +# Do not include this file in your project: see cocos2dx.pri. +################################################################################ + +linux { + # We will compile box2d on demand using Makefile. + build_box2d.name = Build box2d static library + build_box2d.input = $$PWD/Makefile + build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a + build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a + build_box2d.CONFIG = no_link target_predeps + build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS + + QMAKE_EXTRA_COMPILERS += build_box2d + QMAKE_EXTRA_TARGETS += build_box2d + + PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a + LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic +} diff --git a/external/box2d/proj.win32/Box2D.vcxproj b/external/box2d/proj.win32/Box2D.vcxproj new file mode 100644 index 0000000000..cd4bd2086c --- /dev/null +++ b/external/box2d/proj.win32/Box2D.vcxproj @@ -0,0 +1,194 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + libBox2D + {929480E7-23C0-4DF6-8456-096D71547116} + Box2D.win32 + Win32Proj + + + + StaticLibrary + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + AllRules.ruleset + + + AllRules.ruleset + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + + Disabled + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + true + + + $(OutDir)$(ProjectName).lib + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + true + + + $(OutDir)$(ProjectName).lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/external/box2d/proj.win32/Box2D.vcxproj.filters b/external/box2d/proj.win32/Box2D.vcxproj.filters new file mode 100644 index 0000000000..e810cbb0cf --- /dev/null +++ b/external/box2d/proj.win32/Box2D.vcxproj.filters @@ -0,0 +1,301 @@ + + + + + {bdf099c5-cc32-468b-b53f-ec010d7f823f} + + + {92792f88-4e5c-46ee-8d87-002f3b2297ae} + + + {f41a6fa6-5ac1-4514-9ac0-6f3a38f35b4d} + + + {0b56913a-34b7-410a-b386-869d6f7a20be} + + + {f0e7b230-79cc-49b8-9ed7-9dbfa062f2a4} + + + {932f2008-afbe-42f5-993d-a1df0ec67756} + + + {f8937e09-93a4-49fa-8f3e-dfc36da764df} + + + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Rope + + + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Rope + + + + \ No newline at end of file diff --git a/external/box2d/proj.win32/Box2D.vcxproj.user b/external/box2d/proj.win32/Box2D.vcxproj.user new file mode 100644 index 0000000000..ace9a86acb --- /dev/null +++ b/external/box2d/proj.win32/Box2D.vcxproj.user @@ -0,0 +1,3 @@ + + + \ No newline at end of file From 31b92aacc4e2ec24734417e465fc191828e5a5a0 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 14:10:18 +0800 Subject: [PATCH 121/557] issue #2905: remove rpm, don't support qt5 temporaly --- rpm/cocos2d-x.spec | 81 ---------------------------------------------- 1 file changed, 81 deletions(-) delete mode 100644 rpm/cocos2d-x.spec diff --git a/rpm/cocos2d-x.spec b/rpm/cocos2d-x.spec deleted file mode 100644 index c997278f21..0000000000 --- a/rpm/cocos2d-x.spec +++ /dev/null @@ -1,81 +0,0 @@ -Name: cocos2d-x -Version: 1.0.0 -Release: 2 -Summary: Cocos2D-X Cross-Platform 2D Games Framework - -Group: System/GUI/Other -License: MIT -URL: http://cocos2d-x.org -Source: %{name}-%{version}.tar.bz2 -BuildRequires: pkgconfig(egl) -BuildRequires: pkgconfig(glesv2) -BuildRequires: pkgconfig(Qt5Core) -BuildRequires: pkgconfig(Qt5Gui) -BuildRequires: pkgconfig(Qt5Multimedia) -BuildRequires: pkgconfig(Qt5Sensors) -BuildRequires: pkgconfig(zlib) -BuildRequires: pkgconfig(fontconfig) -BuildRequires: pkgconfig(freetype2) -BuildRequires: pkgconfig(libpng) -BuildRequires: pkgconfig(libtiff-4) -BuildRequires: libjpeg-turbo-devel -BuildRequires: pkgconfig(libcurl) - -%description -cocos2d-x is a multi-platform 2D game framework in C++, -branched on cocos2d-iphone and licensed under MIT. - -%package tests -Summary: Cocos2D-X Test Applications -Group: Development/Libraries -Requires: %{name} = %{version} - -%description tests -cocos2d-x is a multi-platform 2D game framework in C++, -branched on cocos2d-iphone and licensed under MIT. - -This package contains test applications for Cocos2D-X. - -%package devel -Summary: Cocos2D-X Development Libraries -Group: Development/Libraries -Requires: %{name} = %{version} - -%description devel -cocos2d-x is a multi-platform 2D game framework in C++, -branched on cocos2d-iphone and licensed under MIT. - -This package contains development libraries for Cocos2D-X. - -%prep -%setup -q - -%build -%qmake5 -make - -%install -make INSTALL_ROOT=%{buildroot} install - -%post -/sbin/ldconfig - -%postun -/sbin/ldconfig - -%files -%defattr(-,root,root,-) -%doc README.mdown licenses -%{_libdir}/lib*.so.* - -%files tests -%defattr(-,root,root,-) -%doc README.mdown -/opt/cocos2dx_TestCpp/* -/usr/share/applications/*.desktop - -%files devel -%defattr(-,root,root,-) -%doc README.mdown AUTHORS CHANGELOG -%{_libdir}/lib*.so -#%{_includedir}/*/*.h From dfe85aa125535fafd3a40221c863dd692086fa0f Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 14:14:57 +0800 Subject: [PATCH 122/557] issue #2905:remove box2d --- external/box2d/Android.mk | 60 - external/box2d/Box2D.h | 67 - .../box2d/Collision/Shapes/b2ChainShape.cpp | 171 --- .../box2d/Collision/Shapes/b2ChainShape.h | 102 -- .../box2d/Collision/Shapes/b2CircleShape.cpp | 100 -- .../box2d/Collision/Shapes/b2CircleShape.h | 91 -- .../box2d/Collision/Shapes/b2EdgeShape.cpp | 139 -- external/box2d/Collision/Shapes/b2EdgeShape.h | 74 - .../box2d/Collision/Shapes/b2PolygonShape.cpp | 361 ----- .../box2d/Collision/Shapes/b2PolygonShape.h | 95 -- external/box2d/Collision/Shapes/b2Shape.h | 101 -- external/box2d/Collision/b2BroadPhase.cpp | 122 -- external/box2d/Collision/b2BroadPhase.h | 248 ---- external/box2d/Collision/b2CollideCircle.cpp | 154 -- external/box2d/Collision/b2CollideEdge.cpp | 698 --------- external/box2d/Collision/b2CollidePolygon.cpp | 317 ---- external/box2d/Collision/b2Collision.cpp | 249 ---- external/box2d/Collision/b2Collision.h | 276 ---- external/box2d/Collision/b2Distance.cpp | 603 -------- external/box2d/Collision/b2Distance.h | 141 -- external/box2d/Collision/b2DynamicTree.cpp | 775 ---------- external/box2d/Collision/b2DynamicTree.h | 284 ---- external/box2d/Collision/b2TimeOfImpact.cpp | 488 ------ external/box2d/Collision/b2TimeOfImpact.h | 58 - external/box2d/Common/b2BlockAllocator.cpp | 218 --- external/box2d/Common/b2BlockAllocator.h | 62 - external/box2d/Common/b2Draw.cpp | 44 - external/box2d/Common/b2Draw.h | 81 - external/box2d/Common/b2GrowableStack.h | 85 -- external/box2d/Common/b2Math.cpp | 94 -- external/box2d/Common/b2Math.h | 738 --------- external/box2d/Common/b2Settings.cpp | 61 - external/box2d/Common/b2Settings.h | 150 -- external/box2d/Common/b2StackAllocator.cpp | 83 -- external/box2d/Common/b2StackAllocator.h | 60 - external/box2d/Common/b2Timer.cpp | 100 -- external/box2d/Common/b2Timer.h | 45 - .../Contacts/b2ChainAndCircleContact.cpp | 54 - .../Contacts/b2ChainAndCircleContact.h | 39 - .../Contacts/b2ChainAndPolygonContact.cpp | 54 - .../Contacts/b2ChainAndPolygonContact.h | 39 - .../Dynamics/Contacts/b2CircleContact.cpp | 53 - .../box2d/Dynamics/Contacts/b2CircleContact.h | 39 - .../box2d/Dynamics/Contacts/b2Contact.cpp | 240 --- external/box2d/Dynamics/Contacts/b2Contact.h | 331 ----- .../Dynamics/Contacts/b2ContactSolver.cpp | 832 ----------- .../box2d/Dynamics/Contacts/b2ContactSolver.h | 94 -- .../Contacts/b2EdgeAndCircleContact.cpp | 50 - .../Contacts/b2EdgeAndCircleContact.h | 39 - .../Contacts/b2EdgeAndPolygonContact.cpp | 50 - .../Contacts/b2EdgeAndPolygonContact.h | 39 - .../Contacts/b2PolygonAndCircleContact.cpp | 50 - .../Contacts/b2PolygonAndCircleContact.h | 38 - .../Dynamics/Contacts/b2PolygonContact.cpp | 53 - .../Dynamics/Contacts/b2PolygonContact.h | 39 - .../box2d/Dynamics/Joints/b2DistanceJoint.cpp | 260 ---- .../box2d/Dynamics/Joints/b2DistanceJoint.h | 169 --- .../box2d/Dynamics/Joints/b2FrictionJoint.cpp | 251 ---- .../box2d/Dynamics/Joints/b2FrictionJoint.h | 119 -- .../box2d/Dynamics/Joints/b2GearJoint.cpp | 423 ------ external/box2d/Dynamics/Joints/b2GearJoint.h | 125 -- external/box2d/Dynamics/Joints/b2Joint.cpp | 199 --- external/box2d/Dynamics/Joints/b2Joint.h | 222 --- .../box2d/Dynamics/Joints/b2MouseJoint.cpp | 217 --- external/box2d/Dynamics/Joints/b2MouseJoint.h | 126 -- .../Dynamics/Joints/b2PrismaticJoint.cpp | 637 -------- .../box2d/Dynamics/Joints/b2PrismaticJoint.h | 196 --- .../box2d/Dynamics/Joints/b2PulleyJoint.cpp | 332 ----- .../box2d/Dynamics/Joints/b2PulleyJoint.h | 143 -- .../box2d/Dynamics/Joints/b2RevoluteJoint.cpp | 504 ------- .../box2d/Dynamics/Joints/b2RevoluteJoint.h | 204 --- .../box2d/Dynamics/Joints/b2RopeJoint.cpp | 241 --- external/box2d/Dynamics/Joints/b2RopeJoint.h | 114 -- .../box2d/Dynamics/Joints/b2WeldJoint.cpp | 330 ----- external/box2d/Dynamics/Joints/b2WeldJoint.h | 126 -- .../box2d/Dynamics/Joints/b2WheelJoint.cpp | 419 ------ external/box2d/Dynamics/Joints/b2WheelJoint.h | 213 --- external/box2d/Dynamics/b2Body.cpp | 514 ------- external/box2d/Dynamics/b2Body.h | 846 ----------- external/box2d/Dynamics/b2ContactManager.cpp | 293 ---- external/box2d/Dynamics/b2ContactManager.h | 52 - external/box2d/Dynamics/b2Fixture.cpp | 303 ---- external/box2d/Dynamics/b2Fixture.h | 345 ----- external/box2d/Dynamics/b2Island.cpp | 539 ------- external/box2d/Dynamics/b2Island.h | 93 -- external/box2d/Dynamics/b2TimeStep.h | 70 - external/box2d/Dynamics/b2World.cpp | 1316 ----------------- external/box2d/Dynamics/b2World.h | 349 ----- external/box2d/Dynamics/b2WorldCallbacks.cpp | 36 - external/box2d/Dynamics/b2WorldCallbacks.h | 155 -- external/box2d/Rope/b2Rope.cpp | 259 ---- external/box2d/Rope/b2Rope.h | 115 -- external/box2d/proj.linux/.cproject | 267 ---- external/box2d/proj.linux/.project | 110 -- external/box2d/proj.linux/Makefile | 72 - external/box2d/proj.linux/box2d.prf | 19 - external/box2d/proj.win32/Box2D.vcxproj | 194 --- .../box2d/proj.win32/Box2D.vcxproj.filters | 301 ---- external/box2d/proj.win32/Box2D.vcxproj.user | 3 - 99 files changed, 21549 deletions(-) delete mode 100644 external/box2d/Android.mk delete mode 100644 external/box2d/Box2D.h delete mode 100644 external/box2d/Collision/Shapes/b2ChainShape.cpp delete mode 100644 external/box2d/Collision/Shapes/b2ChainShape.h delete mode 100644 external/box2d/Collision/Shapes/b2CircleShape.cpp delete mode 100644 external/box2d/Collision/Shapes/b2CircleShape.h delete mode 100644 external/box2d/Collision/Shapes/b2EdgeShape.cpp delete mode 100644 external/box2d/Collision/Shapes/b2EdgeShape.h delete mode 100644 external/box2d/Collision/Shapes/b2PolygonShape.cpp delete mode 100644 external/box2d/Collision/Shapes/b2PolygonShape.h delete mode 100644 external/box2d/Collision/Shapes/b2Shape.h delete mode 100644 external/box2d/Collision/b2BroadPhase.cpp delete mode 100644 external/box2d/Collision/b2BroadPhase.h delete mode 100644 external/box2d/Collision/b2CollideCircle.cpp delete mode 100644 external/box2d/Collision/b2CollideEdge.cpp delete mode 100644 external/box2d/Collision/b2CollidePolygon.cpp delete mode 100644 external/box2d/Collision/b2Collision.cpp delete mode 100644 external/box2d/Collision/b2Collision.h delete mode 100644 external/box2d/Collision/b2Distance.cpp delete mode 100644 external/box2d/Collision/b2Distance.h delete mode 100644 external/box2d/Collision/b2DynamicTree.cpp delete mode 100644 external/box2d/Collision/b2DynamicTree.h delete mode 100644 external/box2d/Collision/b2TimeOfImpact.cpp delete mode 100644 external/box2d/Collision/b2TimeOfImpact.h delete mode 100644 external/box2d/Common/b2BlockAllocator.cpp delete mode 100644 external/box2d/Common/b2BlockAllocator.h delete mode 100644 external/box2d/Common/b2Draw.cpp delete mode 100644 external/box2d/Common/b2Draw.h delete mode 100644 external/box2d/Common/b2GrowableStack.h delete mode 100644 external/box2d/Common/b2Math.cpp delete mode 100644 external/box2d/Common/b2Math.h delete mode 100644 external/box2d/Common/b2Settings.cpp delete mode 100644 external/box2d/Common/b2Settings.h delete mode 100644 external/box2d/Common/b2StackAllocator.cpp delete mode 100644 external/box2d/Common/b2StackAllocator.h delete mode 100644 external/box2d/Common/b2Timer.cpp delete mode 100644 external/box2d/Common/b2Timer.h delete mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2CircleContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2CircleContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2Contact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2Contact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2ContactSolver.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2ContactSolver.h delete mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h delete mode 100644 external/box2d/Dynamics/Contacts/b2PolygonContact.cpp delete mode 100644 external/box2d/Dynamics/Contacts/b2PolygonContact.h delete mode 100644 external/box2d/Dynamics/Joints/b2DistanceJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2DistanceJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2FrictionJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2FrictionJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2GearJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2GearJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2Joint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2Joint.h delete mode 100644 external/box2d/Dynamics/Joints/b2MouseJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2MouseJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2PrismaticJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2PulleyJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2PulleyJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2RevoluteJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2RopeJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2RopeJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2WeldJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2WeldJoint.h delete mode 100644 external/box2d/Dynamics/Joints/b2WheelJoint.cpp delete mode 100644 external/box2d/Dynamics/Joints/b2WheelJoint.h delete mode 100644 external/box2d/Dynamics/b2Body.cpp delete mode 100644 external/box2d/Dynamics/b2Body.h delete mode 100644 external/box2d/Dynamics/b2ContactManager.cpp delete mode 100644 external/box2d/Dynamics/b2ContactManager.h delete mode 100644 external/box2d/Dynamics/b2Fixture.cpp delete mode 100644 external/box2d/Dynamics/b2Fixture.h delete mode 100644 external/box2d/Dynamics/b2Island.cpp delete mode 100644 external/box2d/Dynamics/b2Island.h delete mode 100644 external/box2d/Dynamics/b2TimeStep.h delete mode 100644 external/box2d/Dynamics/b2World.cpp delete mode 100644 external/box2d/Dynamics/b2World.h delete mode 100644 external/box2d/Dynamics/b2WorldCallbacks.cpp delete mode 100644 external/box2d/Dynamics/b2WorldCallbacks.h delete mode 100644 external/box2d/Rope/b2Rope.cpp delete mode 100644 external/box2d/Rope/b2Rope.h delete mode 100644 external/box2d/proj.linux/.cproject delete mode 100644 external/box2d/proj.linux/.project delete mode 100644 external/box2d/proj.linux/Makefile delete mode 100644 external/box2d/proj.linux/box2d.prf delete mode 100644 external/box2d/proj.win32/Box2D.vcxproj delete mode 100644 external/box2d/proj.win32/Box2D.vcxproj.filters delete mode 100644 external/box2d/proj.win32/Box2D.vcxproj.user diff --git a/external/box2d/Android.mk b/external/box2d/Android.mk deleted file mode 100644 index c366750c01..0000000000 --- a/external/box2d/Android.mk +++ /dev/null @@ -1,60 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := box2d_static - -LOCAL_MODULE_FILENAME := libbox2d - -LOCAL_SRC_FILES := \ -Collision/b2BroadPhase.cpp \ -Collision/b2CollideCircle.cpp \ -Collision/b2CollideEdge.cpp \ -Collision/b2CollidePolygon.cpp \ -Collision/b2Collision.cpp \ -Collision/b2Distance.cpp \ -Collision/b2DynamicTree.cpp \ -Collision/b2TimeOfImpact.cpp \ -Collision/Shapes/b2ChainShape.cpp \ -Collision/Shapes/b2CircleShape.cpp \ -Collision/Shapes/b2EdgeShape.cpp \ -Collision/Shapes/b2PolygonShape.cpp \ -Common/b2BlockAllocator.cpp \ -Common/b2Draw.cpp \ -Common/b2Math.cpp \ -Common/b2Settings.cpp \ -Common/b2StackAllocator.cpp \ -Common/b2Timer.cpp \ -Dynamics/b2Body.cpp \ -Dynamics/b2ContactManager.cpp \ -Dynamics/b2Fixture.cpp \ -Dynamics/b2Island.cpp \ -Dynamics/b2World.cpp \ -Dynamics/b2WorldCallbacks.cpp \ -Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -Dynamics/Contacts/b2CircleContact.cpp \ -Dynamics/Contacts/b2Contact.cpp \ -Dynamics/Contacts/b2ContactSolver.cpp \ -Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -Dynamics/Contacts/b2PolygonContact.cpp \ -Dynamics/Joints/b2DistanceJoint.cpp \ -Dynamics/Joints/b2FrictionJoint.cpp \ -Dynamics/Joints/b2GearJoint.cpp \ -Dynamics/Joints/b2Joint.cpp \ -Dynamics/Joints/b2MouseJoint.cpp \ -Dynamics/Joints/b2PrismaticJoint.cpp \ -Dynamics/Joints/b2PulleyJoint.cpp \ -Dynamics/Joints/b2RevoluteJoint.cpp \ -Dynamics/Joints/b2RopeJoint.cpp \ -Dynamics/Joints/b2WeldJoint.cpp \ -Dynamics/Joints/b2WheelJoint.cpp \ -Rope/b2Rope.cpp - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. - -include $(BUILD_STATIC_LIBRARY) diff --git a/external/box2d/Box2D.h b/external/box2d/Box2D.h deleted file mode 100644 index f674d82269..0000000000 --- a/external/box2d/Box2D.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BOX2D_H -#define BOX2D_H - -/** -\mainpage Box2D API Documentation - -\section intro_sec Getting Started - -For documentation please see http://box2d.org/documentation.html - -For discussion please visit http://box2d.org/forum -*/ - -// These include files constitute the main Box2D API - -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/external/box2d/Collision/Shapes/b2ChainShape.cpp b/external/box2d/Collision/Shapes/b2ChainShape.cpp deleted file mode 100644 index 79b4304b5b..0000000000 --- a/external/box2d/Collision/Shapes/b2ChainShape.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -using namespace std; - -b2ChainShape::~b2ChainShape() -{ - b2Free(m_vertices); - m_vertices = NULL; - m_count = 0; -} - -void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 3); - m_count = count + 1; - m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); - m_vertices[count] = m_vertices[0]; - m_prevVertex = m_vertices[m_count - 2]; - m_nextVertex = m_vertices[1]; - m_hasPrevVertex = true; - m_hasNextVertex = true; -} - -void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 2); - m_count = count; - m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); - m_hasPrevVertex = false; - m_hasNextVertex = false; -} - -void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) -{ - m_prevVertex = prevVertex; - m_hasPrevVertex = true; -} - -void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) -{ - m_nextVertex = nextVertex; - m_hasNextVertex = true; -} - -b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2ChainShape)); - b2ChainShape* clone = new (mem) b2ChainShape; - clone->CreateChain(m_vertices, m_count); - clone->m_prevVertex = m_prevVertex; - clone->m_nextVertex = m_nextVertex; - clone->m_hasPrevVertex = m_hasPrevVertex; - clone->m_hasNextVertex = m_hasNextVertex; - return clone; -} - -int32 b2ChainShape::GetChildCount() const -{ - // edge count = vertex count - 1 - return m_count - 1; -} - -void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const -{ - b2Assert(0 <= index && index < m_count - 1); - edge->m_type = b2Shape::e_edge; - edge->m_radius = m_radius; - - edge->m_vertex1 = m_vertices[index + 0]; - edge->m_vertex2 = m_vertices[index + 1]; - - if (index > 0) - { - edge->m_vertex0 = m_vertices[index - 1]; - edge->m_hasVertex0 = true; - } - else - { - edge->m_vertex0 = m_prevVertex; - edge->m_hasVertex0 = m_hasPrevVertex; - } - - if (index < m_count - 2) - { - edge->m_vertex3 = m_vertices[index + 2]; - edge->m_hasVertex3 = true; - } - else - { - edge->m_vertex3 = m_nextVertex; - edge->m_hasVertex3 = m_hasNextVertex; - } -} - -bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - b2EdgeShape edgeShape; - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - edgeShape.m_vertex1 = m_vertices[i1]; - edgeShape.m_vertex2 = m_vertices[i2]; - - return edgeShape.RayCast(output, input, xf, 0); -} - -void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); - b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); - - aabb->lowerBound = b2Min(v1, v2); - aabb->upperBound = b2Max(v1, v2); -} - -void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center.SetZero(); - massData->I = 0.0f; -} diff --git a/external/box2d/Collision/Shapes/b2ChainShape.h b/external/box2d/Collision/Shapes/b2ChainShape.h deleted file mode 100644 index 9c9a9eaa7d..0000000000 --- a/external/box2d/Collision/Shapes/b2ChainShape.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_SHAPE_H -#define B2_CHAIN_SHAPE_H - -#include - -class b2EdgeShape; - -/// A chain shape is a free form sequence of line segments. -/// The chain has two-sided collision, so you can use inside and outside collision. -/// Therefore, you may use any winding order. -/// Since there may be many vertices, they are allocated using b2Alloc. -/// Connectivity information is used to create smooth collisions. -/// WARNING: The chain will not collide properly if there are self-intersections. -class b2ChainShape : public b2Shape -{ -public: - b2ChainShape(); - - /// The destructor frees the vertices using b2Free. - ~b2ChainShape(); - - /// Create a loop. This automatically adjusts connectivity. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateLoop(const b2Vec2* vertices, int32 count); - - /// Create a chain with isolated end vertices. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateChain(const b2Vec2* vertices, int32 count); - - /// Establish connectivity to a vertex that precedes the first vertex. - /// Don't call this for loops. - void SetPrevVertex(const b2Vec2& prevVertex); - - /// Establish connectivity to a vertex that follows the last vertex. - /// Don't call this for loops. - void SetNextVertex(const b2Vec2& nextVertex); - - /// Implement b2Shape. Vertices are cloned using b2Alloc. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Get a child edge. - void GetChildEdge(b2EdgeShape* edge, int32 index) const; - - /// This always return false. - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// Chains have zero mass. - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// The vertices. Owned by this class. - b2Vec2* m_vertices; - - /// The vertex count. - int32 m_count; - - b2Vec2 m_prevVertex, m_nextVertex; - bool m_hasPrevVertex, m_hasNextVertex; -}; - -inline b2ChainShape::b2ChainShape() -{ - m_type = e_chain; - m_radius = b2_polygonRadius; - m_vertices = NULL; - m_count = 0; - m_hasPrevVertex = false; - m_hasNextVertex = false; -} - -#endif diff --git a/external/box2d/Collision/Shapes/b2CircleShape.cpp b/external/box2d/Collision/Shapes/b2CircleShape.cpp deleted file mode 100644 index 587ca960b2..0000000000 --- a/external/box2d/Collision/Shapes/b2CircleShape.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2CircleShape)); - b2CircleShape* clone = new (mem) b2CircleShape; - *clone = *this; - return clone; -} - -int32 b2CircleShape::GetChildCount() const -{ - return 1; -} - -bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const -{ - b2Vec2 center = transform.p + b2Mul(transform.q, m_p); - b2Vec2 d = p - center; - return b2Dot(d, d) <= m_radius * m_radius; -} - -// Collision Detection in Interactive 3D Environments by Gino van den Bergen -// From Section 3.1.2 -// x = s + a * r -// norm(x) = radius -bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 position = transform.p + b2Mul(transform.q, m_p); - b2Vec2 s = input.p1 - position; - float32 b = b2Dot(s, s) - m_radius * m_radius; - - // Solve quadratic equation. - b2Vec2 r = input.p2 - input.p1; - float32 c = b2Dot(s, r); - float32 rr = b2Dot(r, r); - float32 sigma = c * c - rr * b; - - // Check for negative discriminant and short segment. - if (sigma < 0.0f || rr < b2_epsilon) - { - return false; - } - - // Find the point of intersection of the line with the circle. - float32 a = -(c + b2Sqrt(sigma)); - - // Is the intersection point on the segment? - if (0.0f <= a && a <= input.maxFraction * rr) - { - a /= rr; - output->fraction = a; - output->normal = s + a * r; - output->normal.Normalize(); - return true; - } - - return false; -} - -void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 p = transform.p + b2Mul(transform.q, m_p); - aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); - aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); -} - -void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const -{ - massData->mass = density * b2_pi * m_radius * m_radius; - massData->center = m_p; - - // inertia about the local origin - massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); -} diff --git a/external/box2d/Collision/Shapes/b2CircleShape.h b/external/box2d/Collision/Shapes/b2CircleShape.h deleted file mode 100644 index c4e23a475b..0000000000 --- a/external/box2d/Collision/Shapes/b2CircleShape.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CIRCLE_SHAPE_H -#define B2_CIRCLE_SHAPE_H - -#include - -/// A circle shape. -class b2CircleShape : public b2Shape -{ -public: - b2CircleShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Implement b2Shape. - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - - /// Get the vertex count. - int32 GetVertexCount() const { return 1; } - - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; - - /// Position - b2Vec2 m_p; -}; - -inline b2CircleShape::b2CircleShape() -{ - m_type = e_circle; - m_radius = 0.0f; - m_p.SetZero(); -} - -inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const -{ - B2_NOT_USED(d); - return 0; -} - -inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const -{ - B2_NOT_USED(d); - return m_p; -} - -inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const -{ - B2_NOT_USED(index); - b2Assert(index == 0); - return m_p; -} - -#endif diff --git a/external/box2d/Collision/Shapes/b2EdgeShape.cpp b/external/box2d/Collision/Shapes/b2EdgeShape.cpp deleted file mode 100644 index 7b09e55bf4..0000000000 --- a/external/box2d/Collision/Shapes/b2EdgeShape.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) -{ - m_vertex1 = v1; - m_vertex2 = v2; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2EdgeShape)); - b2EdgeShape* clone = new (mem) b2EdgeShape; - *clone = *this; - return clone; -} - -int32 b2EdgeShape::GetChildCount() const -{ - return 1; -} - -bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -// p = p1 + t * d -// v = v1 + s * e -// p1 + t * d = v1 + s * e -// s * e - t * d = p1 - v1 -bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the edge's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - b2Vec2 v1 = m_vertex1; - b2Vec2 v2 = m_vertex2; - b2Vec2 e = v2 - v1; - b2Vec2 normal(e.y, -e.x); - normal.Normalize(); - - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float32 numerator = b2Dot(normal, v1 - p1); - float32 denominator = b2Dot(normal, d); - - if (denominator == 0.0f) - { - return false; - } - - float32 t = numerator / denominator; - if (t < 0.0f || input.maxFraction < t) - { - return false; - } - - b2Vec2 q = p1 + t * d; - - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - b2Vec2 r = v2 - v1; - float32 rr = b2Dot(r, r); - if (rr == 0.0f) - { - return false; - } - - float32 s = b2Dot(q - v1, r) / rr; - if (s < 0.0f || 1.0f < s) - { - return false; - } - - output->fraction = t; - if (numerator > 0.0f) - { - output->normal = -normal; - } - else - { - output->normal = normal; - } - return true; -} - -void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 v1 = b2Mul(xf, m_vertex1); - b2Vec2 v2 = b2Mul(xf, m_vertex2); - - b2Vec2 lower = b2Min(v1, v2); - b2Vec2 upper = b2Max(v1, v2); - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center = 0.5f * (m_vertex1 + m_vertex2); - massData->I = 0.0f; -} diff --git a/external/box2d/Collision/Shapes/b2EdgeShape.h b/external/box2d/Collision/Shapes/b2EdgeShape.h deleted file mode 100644 index 6163bcbf1c..0000000000 --- a/external/box2d/Collision/Shapes/b2EdgeShape.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_SHAPE_H -#define B2_EDGE_SHAPE_H - -#include - -/// A line segment (edge) shape. These can be connected in chains or loops -/// to other edge shapes. The connectivity information is used to ensure -/// correct contact normals. -class b2EdgeShape : public b2Shape -{ -public: - b2EdgeShape(); - - /// Set this as an isolated edge. - void Set(const b2Vec2& v1, const b2Vec2& v2); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// These are the edge vertices - b2Vec2 m_vertex1, m_vertex2; - - /// Optional adjacent vertices. These are used for smooth collision. - b2Vec2 m_vertex0, m_vertex3; - bool m_hasVertex0, m_hasVertex3; -}; - -inline b2EdgeShape::b2EdgeShape() -{ - m_type = e_edge; - m_radius = b2_polygonRadius; - m_vertex0.x = 0.0f; - m_vertex0.y = 0.0f; - m_vertex3.x = 0.0f; - m_vertex3.y = 0.0f; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -#endif diff --git a/external/box2d/Collision/Shapes/b2PolygonShape.cpp b/external/box2d/Collision/Shapes/b2PolygonShape.cpp deleted file mode 100644 index c04c1dc49b..0000000000 --- a/external/box2d/Collision/Shapes/b2PolygonShape.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2PolygonShape)); - b2PolygonShape* clone = new (mem) b2PolygonShape; - *clone = *this; - return clone; -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy) -{ - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid.SetZero(); -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) -{ - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid = center; - - b2Transform xf; - xf.p = center; - xf.q.Set(angle); - - // Transform vertices and normals. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = b2Mul(xf, m_vertices[i]); - m_normals[i] = b2Mul(xf.q, m_normals[i]); - } -} - -int32 b2PolygonShape::GetChildCount() const -{ - return 1; -} - -static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) -{ - b2Assert(count >= 3); - - b2Vec2 c; c.Set(0.0f, 0.0f); - float32 area = 0.0f; - - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < count; ++i) - { - pRef += vs[i]; - } - pRef *= 1.0f / count; -#endif - - const float32 inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < count; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = vs[i]; - b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - c += triangleArea * inv3 * (p1 + p2 + p3); - } - - // Centroid - b2Assert(area > b2_epsilon); - c *= 1.0f / area; - return c; -} - -void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) -{ - b2Assert(3 <= count && count <= b2_maxPolygonVertices); - m_vertexCount = count; - - // Copy vertices. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = vertices[i]; - } - - // Compute normals. Ensure the edges have non-zero length. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); - m_normals[i] = b2Cross(edge, 1.0f); - m_normals[i].Normalize(); - } - -#ifdef _DEBUG - // Ensure the polygon is convex and the interior - // is to the left of each edge. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - - for (int32 j = 0; j < m_vertexCount; ++j) - { - // Don't check vertices on the current edge. - if (j == i1 || j == i2) - { - continue; - } - - b2Vec2 r = m_vertices[j] - m_vertices[i1]; - - // If this crashes, your polygon is non-convex, has colinear edges, - // or the winding order is wrong. - float32 s = b2Cross(edge, r); - b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); - } - } -#endif - - // Compute the polygon centroid. - m_centroid = ComputeCentroid(m_vertices, m_vertexCount); -} - -bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); - - for (int32 i = 0; i < m_vertexCount; ++i) - { - float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); - if (dot > 0.0f) - { - return false; - } - } - - return true; -} - -bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the polygon's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - float32 lower = 0.0f, upper = input.maxFraction; - - int32 index = -1; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); - - if (denominator == 0.0f) - { - if (numerator < 0.0f) - { - return false; - } - } - else - { - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - } - - // The use of epsilon here causes the assert on lower to trip - // in some cases. Apparently the use of epsilon was to make edge - // shapes work, but now those are handled separately. - //if (upper < lower - b2_epsilon) - if (upper < lower) - { - return false; - } - } - - b2Assert(0.0f <= lower && lower <= input.maxFraction); - - if (index >= 0) - { - output->fraction = lower; - output->normal = b2Mul(xf.q, m_normals[index]); - return true; - } - - return false; -} - -void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 lower = b2Mul(xf, m_vertices[0]); - b2Vec2 upper = lower; - - for (int32 i = 1; i < m_vertexCount; ++i) - { - b2Vec2 v = b2Mul(xf, m_vertices[i]); - lower = b2Min(lower, v); - upper = b2Max(upper, v); - } - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const -{ - // Polygon mass, centroid, and inertia. - // Let rho be the polygon density in mass per unit area. - // Then: - // mass = rho * int(dA) - // centroid.x = (1/mass) * rho * int(x * dA) - // centroid.y = (1/mass) * rho * int(y * dA) - // I = rho * int((x*x + y*y) * dA) - // - // We can compute these integrals by summing all the integrals - // for each triangle of the polygon. To evaluate the integral - // for a single triangle, we make a change of variables to - // the (u,v) coordinates of the triangle: - // x = x0 + e1x * u + e2x * v - // y = y0 + e1y * u + e2y * v - // where 0 <= u && 0 <= v && u + v <= 1. - // - // We integrate u from [0,1-v] and then v from [0,1]. - // We also need to use the Jacobian of the transformation: - // D = cross(e1, e2) - // - // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) - // - // The rest of the derivation is handled by computer algebra. - - b2Assert(m_vertexCount >= 3); - - b2Vec2 center; center.Set(0.0f, 0.0f); - float32 area = 0.0f; - float32 I = 0.0f; - - // s is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 s(0.0f, 0.0f); - - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < m_vertexCount; ++i) - { - s += m_vertices[i]; - } - s *= 1.0f / m_vertexCount; - - const float32 k_inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < m_vertexCount; ++i) - { - // Triangle vertices. - b2Vec2 e1 = m_vertices[i] - s; - b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - center += triangleArea * k_inv3 * (e1 + e2); - - float32 ex1 = e1.x, ey1 = e1.y; - float32 ex2 = e2.x, ey2 = e2.y; - - float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; - float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; - - I += (0.25f * k_inv3 * D) * (intx2 + inty2); - } - - // Total mass - massData->mass = density * area; - - // Center of mass - b2Assert(area > b2_epsilon); - center *= 1.0f / area; - massData->center = center + s; - - // Inertia tensor relative to the local origin (point s). - massData->I = density * I; - - // Shift to center of mass then to original body origin. - massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); -} diff --git a/external/box2d/Collision/Shapes/b2PolygonShape.h b/external/box2d/Collision/Shapes/b2PolygonShape.h deleted file mode 100644 index 70daccb2ff..0000000000 --- a/external/box2d/Collision/Shapes/b2PolygonShape.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_SHAPE_H -#define B2_POLYGON_SHAPE_H - -#include - -/// A convex polygon. It is assumed that the interior of the polygon is to -/// the left of each edge. -/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. -/// In most cases you should not need many vertices for a convex polygon. -class b2PolygonShape : public b2Shape -{ -public: - b2PolygonShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; - - /// Copy vertices. This assumes the vertices define a convex polygon. - /// It is assumed that the exterior is the the right of each edge. - /// The count must be in the range [3, b2_maxPolygonVertices]. - void Set(const b2Vec2* vertices, int32 vertexCount); - - /// Build vertices to represent an axis-aligned box. - /// @param hx the half-width. - /// @param hy the half-height. - void SetAsBox(float32 hx, float32 hy); - - /// Build vertices to represent an oriented box. - /// @param hx the half-width. - /// @param hy the half-height. - /// @param center the center of the box in local coordinates. - /// @param angle the rotation of the box in local coordinates. - void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// Get the vertex count. - int32 GetVertexCount() const { return m_vertexCount; } - - /// Get a vertex by index. - const b2Vec2& GetVertex(int32 index) const; - - b2Vec2 m_centroid; - b2Vec2 m_vertices[b2_maxPolygonVertices]; - b2Vec2 m_normals[b2_maxPolygonVertices]; - int32 m_vertexCount; -}; - -inline b2PolygonShape::b2PolygonShape() -{ - m_type = e_polygon; - m_radius = b2_polygonRadius; - m_vertexCount = 0; - m_centroid.SetZero(); -} - -inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const -{ - b2Assert(0 <= index && index < m_vertexCount); - return m_vertices[index]; -} - -#endif diff --git a/external/box2d/Collision/Shapes/b2Shape.h b/external/box2d/Collision/Shapes/b2Shape.h deleted file mode 100644 index 2e2aedd14a..0000000000 --- a/external/box2d/Collision/Shapes/b2Shape.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_SHAPE_H -#define B2_SHAPE_H - -#include -#include -#include - -/// This holds the mass data computed for a shape. -struct b2MassData -{ - /// The mass of the shape, usually in kilograms. - float32 mass; - - /// The position of the shape's centroid relative to the shape's origin. - b2Vec2 center; - - /// The rotational inertia of the shape about the local origin. - float32 I; -}; - -/// A shape is used for collision detection. You can create a shape however you like. -/// Shapes used for simulation in b2World are created automatically when a b2Fixture -/// is created. Shapes may encapsulate a one or more child shapes. -class b2Shape -{ -public: - - enum Type - { - e_circle = 0, - e_edge = 1, - e_polygon = 2, - e_chain = 3, - e_typeCount = 4 - }; - - virtual ~b2Shape() {} - - /// Clone the concrete shape using the provided allocator. - virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; - - /// Get the type of this shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - Type GetType() const; - - /// Get the number of child primitives. - virtual int32 GetChildCount() const = 0; - - /// Test a point for containment in this shape. This only works for convex shapes. - /// @param xf the shape world transform. - /// @param p a point in world coordinates. - virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; - - /// Cast a ray against a child shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - /// @param transform the transform to be applied to the shape. - /// @param childIndex the child shape index - virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const = 0; - - /// Given a transform, compute the associated axis aligned bounding box for a child shape. - /// @param aabb returns the axis aligned box. - /// @param xf the world transform of the shape. - /// @param childIndex the child shape - virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; - - /// Compute the mass properties of this shape using its dimensions and density. - /// The inertia tensor is computed about the local origin. - /// @param massData returns the mass data for this shape. - /// @param density the density in kilograms per meter squared. - virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; - - Type m_type; - float32 m_radius; -}; - -inline b2Shape::Type b2Shape::GetType() const -{ - return m_type; -} - -#endif diff --git a/external/box2d/Collision/b2BroadPhase.cpp b/external/box2d/Collision/b2BroadPhase.cpp deleted file mode 100644 index 431f6de1ee..0000000000 --- a/external/box2d/Collision/b2BroadPhase.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -using namespace std; - -b2BroadPhase::b2BroadPhase() -{ - m_proxyCount = 0; - - m_pairCapacity = 16; - m_pairCount = 0; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - - m_moveCapacity = 16; - m_moveCount = 0; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); -} - -b2BroadPhase::~b2BroadPhase() -{ - b2Free(m_moveBuffer); - b2Free(m_pairBuffer); -} - -int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = m_tree.CreateProxy(aabb, userData); - ++m_proxyCount; - BufferMove(proxyId); - return proxyId; -} - -void b2BroadPhase::DestroyProxy(int32 proxyId) -{ - UnBufferMove(proxyId); - --m_proxyCount; - m_tree.DestroyProxy(proxyId); -} - -void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); - if (buffer) - { - BufferMove(proxyId); - } -} - -void b2BroadPhase::TouchProxy(int32 proxyId) -{ - BufferMove(proxyId); -} - -void b2BroadPhase::BufferMove(int32 proxyId) -{ - if (m_moveCount == m_moveCapacity) - { - int32* oldBuffer = m_moveBuffer; - m_moveCapacity *= 2; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); - memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); - b2Free(oldBuffer); - } - - m_moveBuffer[m_moveCount] = proxyId; - ++m_moveCount; -} - -void b2BroadPhase::UnBufferMove(int32 proxyId) -{ - for (int32 i = 0; i < m_moveCount; ++i) - { - if (m_moveBuffer[i] == proxyId) - { - m_moveBuffer[i] = e_nullProxy; - return; - } - } -} - -// This is called from b2DynamicTree::Query when we are gathering pairs. -bool b2BroadPhase::QueryCallback(int32 proxyId) -{ - // A proxy cannot form a pair with itself. - if (proxyId == m_queryProxyId) - { - return true; - } - - // Grow the pair buffer as needed. - if (m_pairCount == m_pairCapacity) - { - b2Pair* oldBuffer = m_pairBuffer; - m_pairCapacity *= 2; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); - b2Free(oldBuffer); - } - - m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); - m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); - ++m_pairCount; - - return true; -} diff --git a/external/box2d/Collision/b2BroadPhase.h b/external/box2d/Collision/b2BroadPhase.h deleted file mode 100644 index cf2414730a..0000000000 --- a/external/box2d/Collision/b2BroadPhase.h +++ /dev/null @@ -1,248 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BROAD_PHASE_H -#define B2_BROAD_PHASE_H - -#include -#include -#include -#include - -struct b2Pair -{ - int32 proxyIdA; - int32 proxyIdB; - int32 next; -}; - -/// The broad-phase is used for computing pairs and performing volume queries and ray casts. -/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. -/// It is up to the client to consume the new pairs and to track subsequent overlap. -class b2BroadPhase -{ -public: - - enum - { - e_nullProxy = -1 - }; - - b2BroadPhase(); - ~b2BroadPhase(); - - /// Create a proxy with an initial AABB. Pairs are not reported until - /// UpdatePairs is called. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. It is up to the client to remove any pairs. - void DestroyProxy(int32 proxyId); - - /// Call MoveProxy as many times as you like, then when you are done - /// call UpdatePairs to finalized the proxy pairs (for your time step). - void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); - - /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. - void TouchProxy(int32 proxyId); - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Get user data from a proxy. Returns NULL if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Test overlap of fat AABBs. - bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; - - /// Get the number of proxies. - int32 GetProxyCount() const; - - /// Update the pairs. This results in pair callbacks. This can only add pairs. - template - void UpdatePairs(T* callback); - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Get the height of the embedded tree. - int32 GetTreeHeight() const; - - /// Get the balance of the embedded tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the embedded tree. - float32 GetTreeQuality() const; - -private: - - friend class b2DynamicTree; - - void BufferMove(int32 proxyId); - void UnBufferMove(int32 proxyId); - - bool QueryCallback(int32 proxyId); - - b2DynamicTree m_tree; - - int32 m_proxyCount; - - int32* m_moveBuffer; - int32 m_moveCapacity; - int32 m_moveCount; - - b2Pair* m_pairBuffer; - int32 m_pairCapacity; - int32 m_pairCount; - - int32 m_queryProxyId; -}; - -/// This is used to sort pairs. -inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) -{ - if (pair1.proxyIdA < pair2.proxyIdA) - { - return true; - } - - if (pair1.proxyIdA == pair2.proxyIdA) - { - return pair1.proxyIdB < pair2.proxyIdB; - } - - return false; -} - -inline void* b2BroadPhase::GetUserData(int32 proxyId) const -{ - return m_tree.GetUserData(proxyId); -} - -inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const -{ - const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); - const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); - return b2TestOverlap(aabbA, aabbB); -} - -inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const -{ - return m_tree.GetFatAABB(proxyId); -} - -inline int32 b2BroadPhase::GetProxyCount() const -{ - return m_proxyCount; -} - -inline int32 b2BroadPhase::GetTreeHeight() const -{ - return m_tree.GetHeight(); -} - -inline int32 b2BroadPhase::GetTreeBalance() const -{ - return m_tree.GetMaxBalance(); -} - -inline float32 b2BroadPhase::GetTreeQuality() const -{ - return m_tree.GetAreaRatio(); -} - -template -void b2BroadPhase::UpdatePairs(T* callback) -{ - // Reset pair buffer - m_pairCount = 0; - - // Perform tree queries for all moving proxies. - for (int32 i = 0; i < m_moveCount; ++i) - { - m_queryProxyId = m_moveBuffer[i]; - if (m_queryProxyId == e_nullProxy) - { - continue; - } - - // We have to query the tree with the fat AABB so that - // we don't fail to create a pair that may touch later. - const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); - - // Query tree, create pairs and add them pair buffer. - m_tree.Query(this, fatAABB); - } - - // Reset move buffer - m_moveCount = 0; - - // Sort the pair buffer to expose duplicates. - std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); - - // Send the pairs back to the client. - int32 i = 0; - while (i < m_pairCount) - { - b2Pair* primaryPair = m_pairBuffer + i; - void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); - void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); - - callback->AddPair(userDataA, userDataB); - ++i; - - // Skip any duplicate pairs. - while (i < m_pairCount) - { - b2Pair* pair = m_pairBuffer + i; - if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) - { - break; - } - ++i; - } - } - - // Try to keep the tree balanced. - //m_tree.Rebalance(4); -} - -template -inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const -{ - m_tree.Query(callback, aabb); -} - -template -inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const -{ - m_tree.RayCast(callback, input); -} - -#endif diff --git a/external/box2d/Collision/b2CollideCircle.cpp b/external/box2d/Collision/b2CollideCircle.cpp deleted file mode 100644 index ed561eb04b..0000000000 --- a/external/box2d/Collision/b2CollideCircle.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -void b2CollideCircles( - b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - b2Vec2 pA = b2Mul(xfA, circleA->m_p); - b2Vec2 pB = b2Mul(xfB, circleB->m_p); - - b2Vec2 d = pB - pA; - float32 distSqr = b2Dot(d, d); - float32 rA = circleA->m_radius, rB = circleB->m_radius; - float32 radius = rA + rB; - if (distSqr > radius * radius) - { - return; - } - - manifold->type = b2Manifold::e_circles; - manifold->localPoint = circleA->m_p; - manifold->localNormal.SetZero(); - manifold->pointCount = 1; - - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; -} - -void b2CollidePolygonAndCircle( - b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle position in the frame of the polygon. - b2Vec2 c = b2Mul(xfB, circleB->m_p); - b2Vec2 cLocal = b2MulT(xfA, c); - - // Find the min separating edge. - int32 normalIndex = 0; - float32 separation = -b2_maxFloat; - float32 radius = polygonA->m_radius + circleB->m_radius; - int32 vertexCount = polygonA->m_vertexCount; - const b2Vec2* vertices = polygonA->m_vertices; - const b2Vec2* normals = polygonA->m_normals; - - for (int32 i = 0; i < vertexCount; ++i) - { - float32 s = b2Dot(normals[i], cLocal - vertices[i]); - - if (s > radius) - { - // Early out. - return; - } - - if (s > separation) - { - separation = s; - normalIndex = i; - } - } - - // Vertices that subtend the incident face. - int32 vertIndex1 = normalIndex; - int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; - b2Vec2 v1 = vertices[vertIndex1]; - b2Vec2 v2 = vertices[vertIndex2]; - - // If the center is inside the polygon ... - if (separation < b2_epsilon) - { - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[normalIndex]; - manifold->localPoint = 0.5f * (v1 + v2); - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - return; - } - - // Compute barycentric coordinates - float32 u1 = b2Dot(cLocal - v1, v2 - v1); - float32 u2 = b2Dot(cLocal - v2, v1 - v2); - if (u1 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v1) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v1; - manifold->localNormal.Normalize(); - manifold->localPoint = v1; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else if (u2 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v2) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v2; - manifold->localNormal.Normalize(); - manifold->localPoint = v2; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else - { - b2Vec2 faceCenter = 0.5f * (v1 + v2); - float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); - if (separation > radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[vertIndex1]; - manifold->localPoint = faceCenter; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } -} diff --git a/external/box2d/Collision/b2CollideEdge.cpp b/external/box2d/Collision/b2CollideEdge.cpp deleted file mode 100644 index 96ca71dccc..0000000000 --- a/external/box2d/Collision/b2CollideEdge.cpp +++ /dev/null @@ -1,698 +0,0 @@ -/* - * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ - -#include -#include -#include -#include - - -// Compute contact points for edge versus circle. -// This accounts for edge connectivity. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle in frame of edge - b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); - - b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; - b2Vec2 e = B - A; - - // Barycentric coordinates - float32 u = b2Dot(e, B - Q); - float32 v = b2Dot(e, Q - A); - - float32 radius = edgeA->m_radius + circleB->m_radius; - - b2ContactFeature cf; - cf.indexB = 0; - cf.typeB = b2ContactFeature::e_vertex; - - // Region A - if (v <= 0.0f) - { - b2Vec2 P = A; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to A? - if (edgeA->m_hasVertex0) - { - b2Vec2 A1 = edgeA->m_vertex0; - b2Vec2 B1 = A; - b2Vec2 e1 = B1 - A1; - float32 u1 = b2Dot(e1, B1 - Q); - - // Is the circle in Region AB of the previous edge? - if (u1 > 0.0f) - { - return; - } - } - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region B - if (u <= 0.0f) - { - b2Vec2 P = B; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to B? - if (edgeA->m_hasVertex3) - { - b2Vec2 B2 = edgeA->m_vertex3; - b2Vec2 A2 = B; - b2Vec2 e2 = B2 - A2; - float32 v2 = b2Dot(e2, Q - A2); - - // Is the circle in Region AB of the next edge? - if (v2 > 0.0f) - { - return; - } - } - - cf.indexA = 1; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region AB - float32 den = b2Dot(e, e); - b2Assert(den > 0.0f); - b2Vec2 P = (1.0f / den) * (u * A + v * B); - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - b2Vec2 n(-e.y, e.x); - if (b2Dot(n, Q - A) < 0.0f) - { - n.Set(-n.x, -n.y); - } - n.Normalize(); - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_face; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = n; - manifold->localPoint = A; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; -} - -// This structure is used to keep track of the best separating axis. -struct b2EPAxis -{ - enum Type - { - e_unknown, - e_edgeA, - e_edgeB - }; - - Type type; - int32 index; - float32 separation; -}; - -// This holds polygon B expressed in frame A. -struct b2TempPolygon -{ - b2Vec2 vertices[b2_maxPolygonVertices]; - b2Vec2 normals[b2_maxPolygonVertices]; - int32 count; -}; - -// Reference face used for clipping -struct b2ReferenceFace -{ - int32 i1, i2; - - b2Vec2 v1, v2; - - b2Vec2 normal; - - b2Vec2 sideNormal1; - float32 sideOffset1; - - b2Vec2 sideNormal2; - float32 sideOffset2; -}; - -// This class collides and edge and a polygon, taking into account edge adjacency. -struct b2EPCollider -{ - void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - b2EPAxis ComputeEdgeSeparation(); - b2EPAxis ComputePolygonSeparation(); - - enum VertexType - { - e_isolated, - e_concave, - e_convex - }; - - b2TempPolygon m_polygonB; - - b2Transform m_xf; - b2Vec2 m_centroidB; - b2Vec2 m_v0, m_v1, m_v2, m_v3; - b2Vec2 m_normal0, m_normal1, m_normal2; - b2Vec2 m_normal; - VertexType m_type1, m_type2; - b2Vec2 m_lowerLimit, m_upperLimit; - float32 m_radius; - bool m_front; -}; - -// Algorithm: -// 1. Classify v1 and v2 -// 2. Classify polygon centroid as front or back -// 3. Flip normal if necessary -// 4. Initialize normal range to [-pi, pi] about face normal -// 5. Adjust normal range according to adjacent edges -// 6. Visit each separating axes, only accept axes within the range -// 7. Return if _any_ axis indicates separation -// 8. Clip -void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - m_xf = b2MulT(xfA, xfB); - - m_centroidB = b2Mul(m_xf, polygonB->m_centroid); - - m_v0 = edgeA->m_vertex0; - m_v1 = edgeA->m_vertex1; - m_v2 = edgeA->m_vertex2; - m_v3 = edgeA->m_vertex3; - - bool hasVertex0 = edgeA->m_hasVertex0; - bool hasVertex3F = edgeA->m_hasVertex3; - - b2Vec2 edge1 = m_v2 - m_v1; - edge1.Normalize(); - m_normal1.Set(edge1.y, -edge1.x); - float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); - float32 offset0 = 0.0f, offset2 = 0.0f; - bool convex1 = false, convex2 = false; - - // Is there a preceding edge? - if (hasVertex0) - { - b2Vec2 edge0 = m_v1 - m_v0; - edge0.Normalize(); - m_normal0.Set(edge0.y, -edge0.x); - convex1 = b2Cross(edge0, edge1) >= 0.0f; - offset0 = b2Dot(m_normal0, m_centroidB - m_v0); - } - - // Is there a following edge? - if (hasVertex3F) - { - b2Vec2 edge2 = m_v3 - m_v2; - edge2.Normalize(); - m_normal2.Set(edge2.y, -edge2.x); - convex2 = b2Cross(edge1, edge2) > 0.0f; - offset2 = b2Dot(m_normal2, m_centroidB - m_v2); - } - - // Determine front or back collision. Determine collision normal limits. - if (hasVertex0 && hasVertex3F) - { - if (convex1 && convex2) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - } - else if (convex1) - { - m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal1; - } - } - else if (convex2) - { - m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal0; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex0) - { - if (convex1) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex3F) - { - if (convex2) - { - m_front = offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - } - else - { - m_front = offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = m_normal1; - } - } - } - else - { - m_front = offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - } - - // Get polygonB in frameA - m_polygonB.count = polygonB->m_vertexCount; - for (int32 i = 0; i < polygonB->m_vertexCount; ++i) - { - m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); - m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); - } - - m_radius = 2.0f * b2_polygonRadius; - - manifold->pointCount = 0; - - b2EPAxis edgeAxis = ComputeEdgeSeparation(); - - // If no valid normal can be found than this edge should not collide. - if (edgeAxis.type == b2EPAxis::e_unknown) - { - return; - } - - if (edgeAxis.separation > m_radius) - { - return; - } - - b2EPAxis polygonAxis = ComputePolygonSeparation(); - if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) - { - return; - } - - // Use hysteresis for jitter reduction. - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - b2EPAxis primaryAxis; - if (polygonAxis.type == b2EPAxis::e_unknown) - { - primaryAxis = edgeAxis; - } - else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) - { - primaryAxis = polygonAxis; - } - else - { - primaryAxis = edgeAxis; - } - - b2ClipVertex ie[2]; - b2ReferenceFace rf; - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->type = b2Manifold::e_faceA; - - // Search for the polygon normal that is most anti-parallel to the edge normal. - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); - for (int32 i = 1; i < m_polygonB.count; ++i) - { - float32 value = b2Dot(m_normal, m_polygonB.normals[i]); - if (value < bestValue) - { - bestValue = value; - bestIndex = i; - } - } - - int32 i1 = bestIndex; - int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; - - ie[0].v = m_polygonB.vertices[i1]; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = i1; - ie[0].id.cf.typeA = b2ContactFeature::e_face; - ie[0].id.cf.typeB = b2ContactFeature::e_vertex; - - ie[1].v = m_polygonB.vertices[i2]; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = i2; - ie[1].id.cf.typeA = b2ContactFeature::e_face; - ie[1].id.cf.typeB = b2ContactFeature::e_vertex; - - if (m_front) - { - rf.i1 = 0; - rf.i2 = 1; - rf.v1 = m_v1; - rf.v2 = m_v2; - rf.normal = m_normal1; - } - else - { - rf.i1 = 1; - rf.i2 = 0; - rf.v1 = m_v2; - rf.v2 = m_v1; - rf.normal = -m_normal1; - } - } - else - { - manifold->type = b2Manifold::e_faceB; - - ie[0].v = m_v1; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = primaryAxis.index; - ie[0].id.cf.typeA = b2ContactFeature::e_vertex; - ie[0].id.cf.typeB = b2ContactFeature::e_face; - - ie[1].v = m_v2; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = primaryAxis.index; - ie[1].id.cf.typeA = b2ContactFeature::e_vertex; - ie[1].id.cf.typeB = b2ContactFeature::e_face; - - rf.i1 = primaryAxis.index; - rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; - rf.v1 = m_polygonB.vertices[rf.i1]; - rf.v2 = m_polygonB.vertices[rf.i2]; - rf.normal = m_polygonB.normals[rf.i1]; - } - - rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); - rf.sideNormal2 = -rf.sideNormal1; - rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); - rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int32 np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Now clipPoints2 contains the clipped points. - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->localNormal = rf.normal; - manifold->localPoint = rf.v1; - } - else - { - manifold->localNormal = polygonB->m_normals[rf.i1]; - manifold->localPoint = polygonB->m_vertices[rf.i1]; - } - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation; - - separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); - - if (separation <= m_radius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - } - else - { - cp->localPoint = clipPoints2[i].v; - cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; - cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; - cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; - cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; - } - - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} - -b2EPAxis b2EPCollider::ComputeEdgeSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_edgeA; - axis.index = m_front ? 0 : 1; - axis.separation = FLT_MAX; - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); - if (s < axis.separation) - { - axis.separation = s; - } - } - - return axis; -} - -b2EPAxis b2EPCollider::ComputePolygonSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_unknown; - axis.index = -1; - axis.separation = -FLT_MAX; - - b2Vec2 perp(-m_normal.y, m_normal.x); - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - b2Vec2 n = -m_polygonB.normals[i]; - - float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); - float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); - float32 s = b2Min(s1, s2); - - if (s > m_radius) - { - // No collision - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - return axis; - } - - // Adjacency - if (b2Dot(n, perp) >= 0.0f) - { - if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - else - { - if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - - if (s > axis.separation) - { - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - } - } - - return axis; -} - -void b2CollideEdgeAndPolygon( b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - b2EPCollider collider; - collider.Collide(manifold, edgeA, xfA, polygonB, xfB); -} diff --git a/external/box2d/Collision/b2CollidePolygon.cpp b/external/box2d/Collision/b2CollidePolygon.cpp deleted file mode 100644 index be2518d966..0000000000 --- a/external/box2d/Collision/b2CollidePolygon.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -// Find the separation between poly1 and poly2 for a give edge normal on poly1. -static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* vertices1 = poly1->m_vertices; - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); - - // Convert normal from poly1's frame into poly2's frame. - b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); - b2Vec2 normal1 = b2MulT(xf2.q, normal1World); - - // Find support vertex on poly2 for -normal. - int32 index = 0; - float32 minDot = b2_maxFloat; - - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(vertices2[i], normal1); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]); - b2Vec2 v2 = b2Mul(xf2, vertices2[index]); - float32 separation = b2Dot(v2 - v1, normal1World); - return separation; -} - -// Find the max separation between poly1 and poly2 using edge normals from poly1. -static float32 b2FindMaxSeparation(int32* edgeIndex, - const b2PolygonShape* poly1, const b2Transform& xf1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - int32 count1 = poly1->m_vertexCount; - const b2Vec2* normals1 = poly1->m_normals; - - // Vector pointing from the centroid of poly1 to the centroid of poly2. - b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); - b2Vec2 dLocal1 = b2MulT(xf1.q, d); - - // Find edge normal on poly1 that has the largest projection onto d. - int32 edge = 0; - float32 maxDot = -b2_maxFloat; - for (int32 i = 0; i < count1; ++i) - { - float32 dot = b2Dot(normals1[i], dLocal1); - if (dot > maxDot) - { - maxDot = dot; - edge = i; - } - } - - // Get the separation for the edge normal. - float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); - - // Check the separation for the previous edge normal. - int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; - float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); - - // Check the separation for the next edge normal. - int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; - float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); - - // Find the best edge and the search direction. - int32 bestEdge; - float32 bestSeparation; - int32 increment; - if (sPrev > s && sPrev > sNext) - { - increment = -1; - bestEdge = prevEdge; - bestSeparation = sPrev; - } - else if (sNext > s) - { - increment = 1; - bestEdge = nextEdge; - bestSeparation = sNext; - } - else - { - *edgeIndex = edge; - return s; - } - - // Perform a local search for the best edge normal. - for ( ; ; ) - { - if (increment == -1) - edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1; - else - edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; - - s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); - - if (s > bestSeparation) - { - bestEdge = edge; - bestSeparation = s; - } - else - { - break; - } - } - - *edgeIndex = bestEdge; - return bestSeparation; -} - -static void b2FindIncidentEdge(b2ClipVertex c[2], - const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - const b2Vec2* normals2 = poly2->m_normals; - - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); - - // Get the normal of the reference edge in poly2's frame. - b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); - - // Find the incident edge on poly2. - int32 index = 0; - float32 minDot = b2_maxFloat; - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(normal1, normals2[i]); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - // Build the clip vertices for the incident edge. - int32 i1 = index; - int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; - - c[0].v = b2Mul(xf2, vertices2[i1]); - c[0].id.cf.indexA = (uint8)edge1; - c[0].id.cf.indexB = (uint8)i1; - c[0].id.cf.typeA = b2ContactFeature::e_face; - c[0].id.cf.typeB = b2ContactFeature::e_vertex; - - c[1].v = b2Mul(xf2, vertices2[i2]); - c[1].id.cf.indexA = (uint8)edge1; - c[1].id.cf.indexB = (uint8)i2; - c[1].id.cf.typeA = b2ContactFeature::e_face; - c[1].id.cf.typeB = b2ContactFeature::e_vertex; -} - -// Find edge normal of max separation on A - return if separating axis is found -// Find edge normal of max separation on B - return if separation axis is found -// Choose reference edge as min(minA, minB) -// Find incident edge -// Clip - -// The normal points from 1 to 2 -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polyA, const b2Transform& xfA, - const b2PolygonShape* polyB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - float32 totalRadius = polyA->m_radius + polyB->m_radius; - - int32 edgeA = 0; - float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); - if (separationA > totalRadius) - return; - - int32 edgeB = 0; - float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); - if (separationB > totalRadius) - return; - - const b2PolygonShape* poly1; // reference polygon - const b2PolygonShape* poly2; // incident polygon - b2Transform xf1, xf2; - int32 edge1; // reference edge - uint8 flip; - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - if (separationB > k_relativeTol * separationA + k_absoluteTol) - { - poly1 = polyB; - poly2 = polyA; - xf1 = xfB; - xf2 = xfA; - edge1 = edgeB; - manifold->type = b2Manifold::e_faceB; - flip = 1; - } - else - { - poly1 = polyA; - poly2 = polyB; - xf1 = xfA; - xf2 = xfB; - edge1 = edgeA; - manifold->type = b2Manifold::e_faceA; - flip = 0; - } - - b2ClipVertex incidentEdge[2]; - b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); - - int32 count1 = poly1->m_vertexCount; - const b2Vec2* vertices1 = poly1->m_vertices; - - int32 iv1 = edge1; - int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; - - b2Vec2 v11 = vertices1[iv1]; - b2Vec2 v12 = vertices1[iv2]; - - b2Vec2 localTangent = v12 - v11; - localTangent.Normalize(); - - b2Vec2 localNormal = b2Cross(localTangent, 1.0f); - b2Vec2 planePoint = 0.5f * (v11 + v12); - - b2Vec2 tangent = b2Mul(xf1.q, localTangent); - b2Vec2 normal = b2Cross(tangent, 1.0f); - - v11 = b2Mul(xf1, v11); - v12 = b2Mul(xf1, v12); - - // Face offset. - float32 frontOffset = b2Dot(normal, v11); - - // Side offsets, extended by polytope skin thickness. - float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; - float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); - - if (np < 2) - return; - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); - - if (np < 2) - { - return; - } - - // Now clipPoints2 contains the clipped points. - manifold->localNormal = localNormal; - manifold->localPoint = planePoint; - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; - - if (separation <= totalRadius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - cp->localPoint = b2MulT(xf2, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - if (flip) - { - // Swap features - b2ContactFeature cf = cp->id.cf; - cp->id.cf.indexA = cf.indexB; - cp->id.cf.indexB = cf.indexA; - cp->id.cf.typeA = cf.typeB; - cp->id.cf.typeB = cf.typeA; - } - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} diff --git a/external/box2d/Collision/b2Collision.cpp b/external/box2d/Collision/b2Collision.cpp deleted file mode 100644 index 2dd5ff0ab6..0000000000 --- a/external/box2d/Collision/b2Collision.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -void b2WorldManifold::Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB) -{ - if (manifold->pointCount == 0) - { - return; - } - - switch (manifold->type) - { - case b2Manifold::e_circles: - { - normal.Set(1.0f, 0.0f); - b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); - b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } - - b2Vec2 cA = pointA + radiusA * normal; - b2Vec2 cB = pointB - radiusB * normal; - points[0] = 0.5f * (cA + cB); - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); - b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cB = clipPoint - radiusB * normal; - points[i] = 0.5f * (cA + cB); - } - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); - b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cA = clipPoint - radiusA * normal; - points[i] = 0.5f * (cA + cB); - } - - // Ensure normal points from A to B. - normal = -normal; - } - break; - } -} - -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2) -{ - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - state1[i] = b2_nullState; - state2[i] = b2_nullState; - } - - // Detect persists and removes. - for (int32 i = 0; i < manifold1->pointCount; ++i) - { - b2ContactID id = manifold1->points[i].id; - - state1[i] = b2_removeState; - - for (int32 j = 0; j < manifold2->pointCount; ++j) - { - if (manifold2->points[j].id.key == id.key) - { - state1[i] = b2_persistState; - break; - } - } - } - - // Detect persists and adds. - for (int32 i = 0; i < manifold2->pointCount; ++i) - { - b2ContactID id = manifold2->points[i].id; - - state2[i] = b2_addState; - - for (int32 j = 0; j < manifold1->pointCount; ++j) - { - if (manifold1->points[j].id.key == id.key) - { - state2[i] = b2_persistState; - break; - } - } - } -} - -// From Real-time Collision Detection, p179. -bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const -{ - float32 tmin = -b2_maxFloat; - float32 tmax = b2_maxFloat; - - b2Vec2 p = input.p1; - b2Vec2 d = input.p2 - input.p1; - b2Vec2 absD = b2Abs(d); - - b2Vec2 normal; - - for (int32 i = 0; i < 2; ++i) - { - if (absD(i) < b2_epsilon) - { - // Parallel. - if (p(i) < lowerBound(i) || upperBound(i) < p(i)) - { - return false; - } - } - else - { - float32 inv_d = 1.0f / d(i); - float32 t1 = (lowerBound(i) - p(i)) * inv_d; - float32 t2 = (upperBound(i) - p(i)) * inv_d; - - // Sign of the normal vector. - float32 s = -1.0f; - - if (t1 > t2) - { - b2Swap(t1, t2); - s = 1.0f; - } - - // Push the min up - if (t1 > tmin) - { - normal.SetZero(); - normal(i) = s; - tmin = t1; - } - - // Pull the max down - tmax = b2Min(tmax, t2); - - if (tmin > tmax) - { - return false; - } - } - } - - // Does the ray start inside the box? - // Does the ray intersect beyond the max fraction? - if (tmin < 0.0f || input.maxFraction < tmin) - { - return false; - } - - // Intersection. - output->fraction = tmin; - output->normal = normal; - return true; -} - -// Sutherland-Hodgman clipping. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA) -{ - // Start with no output points - int32 numOut = 0; - - // Calculate the distance of end points to the line - float32 distance0 = b2Dot(normal, vIn[0].v) - offset; - float32 distance1 = b2Dot(normal, vIn[1].v) - offset; - - // If the points are behind the plane - if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; - if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; - - // If the points are on different sides of the plane - if (distance0 * distance1 < 0.0f) - { - // Find intersection point of edge and plane - float32 interp = distance0 / (distance0 - distance1); - vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - - // VertexA is hitting edgeB. - vOut[numOut].id.cf.indexA = vertexIndexA; - vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; - vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; - vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; - ++numOut; - } - - return numOut; -} - -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB) -{ - b2DistanceInput input; - input.proxyA.Set(shapeA, indexA); - input.proxyB.Set(shapeB, indexB); - input.transformA = xfA; - input.transformB = xfB; - input.useRadii = true; - - b2SimplexCache cache; - cache.count = 0; - - b2DistanceOutput output; - - b2Distance(&output, &cache, &input); - - return output.distance < 10.0f * b2_epsilon; -} diff --git a/external/box2d/Collision/b2Collision.h b/external/box2d/Collision/b2Collision.h deleted file mode 100644 index 2e7386232b..0000000000 --- a/external/box2d/Collision/b2Collision.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_COLLISION_H -#define B2_COLLISION_H - -#include -#include - -/// @file -/// Structures and functions used for computing contact points, distance -/// queries, and TOI queries. - -class b2Shape; -class b2CircleShape; -class b2EdgeShape; -class b2PolygonShape; - -const uint8 b2_nullFeature = UCHAR_MAX; - -/// The features that intersect to form the contact point -/// This must be 4 bytes or less. -struct b2ContactFeature -{ - enum Type - { - e_vertex = 0, - e_face = 1 - }; - - uint8 indexA; ///< Feature index on shapeA - uint8 indexB; ///< Feature index on shapeB - uint8 typeA; ///< The feature type on shapeA - uint8 typeB; ///< The feature type on shapeB -}; - -/// Contact ids to facilitate warm starting. -union b2ContactID -{ - b2ContactFeature cf; - uint32 key; ///< Used to quickly compare contact ids. -}; - -/// A manifold point is a contact point belonging to a contact -/// manifold. It holds details related to the geometry and dynamics -/// of the contact points. -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleB -/// -e_faceA: the local center of cirlceB or the clip point of polygonB -/// -e_faceB: the clip point of polygonA -/// This structure is stored across time steps, so we keep it small. -/// Note: the impulses are used for internal caching and may not -/// provide reliable contact forces, especially for high speed collisions. -struct b2ManifoldPoint -{ - b2Vec2 localPoint; ///< usage depends on manifold type - float32 normalImpulse; ///< the non-penetration impulse - float32 tangentImpulse; ///< the friction impulse - b2ContactID id; ///< uniquely identifies a contact point between two shapes -}; - -/// A manifold for two touching convex shapes. -/// Box2D supports multiple types of contact: -/// - clip point versus plane with radius -/// - point versus point with radius (circles) -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleA -/// -e_faceA: the center of faceA -/// -e_faceB: the center of faceB -/// Similarly the local normal usage: -/// -e_circles: not used -/// -e_faceA: the normal on polygonA -/// -e_faceB: the normal on polygonB -/// We store contacts in this way so that position correction can -/// account for movement, which is critical for continuous physics. -/// All contact scenarios must be expressed in one of these types. -/// This structure is stored across time steps, so we keep it small. -struct b2Manifold -{ - enum Type - { - e_circles, - e_faceA, - e_faceB - }; - - b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact - b2Vec2 localNormal; ///< not use for Type::e_points - b2Vec2 localPoint; ///< usage depends on manifold type - Type type; - int32 pointCount; ///< the number of manifold points -}; - -/// This is used to compute the current state of a contact manifold. -struct b2WorldManifold -{ - /// Evaluate the manifold with supplied transforms. This assumes - /// modest motion from the original state. This does not change the - /// point count, impulses, etc. The radii must come from the shapes - /// that generated the manifold. - void Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB); - - b2Vec2 normal; ///< world vector pointing from A to B - b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) -}; - -/// This is used for determining the state of contact points. -enum b2PointState -{ - b2_nullState, ///< point does not exist - b2_addState, ///< point was added in the update - b2_persistState, ///< point persisted across the update - b2_removeState ///< point was removed in the update -}; - -/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 -/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2); - -/// Used for computing contact manifolds. -struct b2ClipVertex -{ - b2Vec2 v; - b2ContactID id; -}; - -/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). -struct b2RayCastInput -{ - b2Vec2 p1, p2; - float32 maxFraction; -}; - -/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 -/// come from b2RayCastInput. -struct b2RayCastOutput -{ - b2Vec2 normal; - float32 fraction; -}; - -/// An axis aligned bounding box. -struct b2AABB -{ - /// Verify that the bounds are sorted. - bool IsValid() const; - - /// Get the center of the AABB. - b2Vec2 GetCenter() const - { - return 0.5f * (lowerBound + upperBound); - } - - /// Get the extents of the AABB (half-widths). - b2Vec2 GetExtents() const - { - return 0.5f * (upperBound - lowerBound); - } - - /// Get the perimeter length - float32 GetPerimeter() const - { - float32 wx = upperBound.x - lowerBound.x; - float32 wy = upperBound.y - lowerBound.y; - return 2.0f * (wx + wy); - } - - /// Combine an AABB into this one. - void Combine(const b2AABB& aabb) - { - lowerBound = b2Min(lowerBound, aabb.lowerBound); - upperBound = b2Max(upperBound, aabb.upperBound); - } - - /// Combine two AABBs into this one. - void Combine(const b2AABB& aabb1, const b2AABB& aabb2) - { - lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); - upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); - } - - /// Does this aabb contain the provided AABB. - bool Contains(const b2AABB& aabb) const - { - bool result = true; - result = result && lowerBound.x <= aabb.lowerBound.x; - result = result && lowerBound.y <= aabb.lowerBound.y; - result = result && aabb.upperBound.x <= upperBound.x; - result = result && aabb.upperBound.y <= upperBound.y; - return result; - } - - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; - - b2Vec2 lowerBound; ///< the lower vertex - b2Vec2 upperBound; ///< the upper vertex -}; - -/// Compute the collision manifold between two circles. -void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between a polygon and a circle. -void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between two polygons. -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndPolygon(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* circleB, const b2Transform& xfB); - -/// Clipping for contact manifolds. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA); - -/// Determine if two generic shapes overlap. -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB); - -// ---------------- Inline Functions ------------------------------------------ - -inline bool b2AABB::IsValid() const -{ - b2Vec2 d = upperBound - lowerBound; - bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && lowerBound.IsValid() && upperBound.IsValid(); - return valid; -} - -inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) -{ - b2Vec2 d1, d2; - d1 = b.lowerBound - a.upperBound; - d2 = a.lowerBound - b.upperBound; - - if (d1.x > 0.0f || d1.y > 0.0f) - return false; - - if (d2.x > 0.0f || d2.y > 0.0f) - return false; - - return true; -} - -#endif diff --git a/external/box2d/Collision/b2Distance.cpp b/external/box2d/Collision/b2Distance.cpp deleted file mode 100644 index ac67d3be43..0000000000 --- a/external/box2d/Collision/b2Distance.cpp +++ /dev/null @@ -1,603 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. -int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - -void b2DistanceProxy::Set(const b2Shape* shape, int32 index) -{ - switch (shape->GetType()) - { - case b2Shape::e_circle: - { - const b2CircleShape* circle = (b2CircleShape*)shape; - m_vertices = &circle->m_p; - m_count = 1; - m_radius = circle->m_radius; - } - break; - - case b2Shape::e_polygon: - { - const b2PolygonShape* polygon = (b2PolygonShape*)shape; - m_vertices = polygon->m_vertices; - m_count = polygon->m_vertexCount; - m_radius = polygon->m_radius; - } - break; - - case b2Shape::e_chain: - { - const b2ChainShape* chain = (b2ChainShape*)shape; - b2Assert(0 <= index && index < chain->m_count); - - m_buffer[0] = chain->m_vertices[index]; - if (index + 1 < chain->m_count) - { - m_buffer[1] = chain->m_vertices[index + 1]; - } - else - { - m_buffer[1] = chain->m_vertices[0]; - } - - m_vertices = m_buffer; - m_count = 2; - m_radius = chain->m_radius; - } - break; - - case b2Shape::e_edge: - { - const b2EdgeShape* edge = (b2EdgeShape*)shape; - m_vertices = &edge->m_vertex1; - m_count = 2; - m_radius = edge->m_radius; - } - break; - - default: - b2Assert(false); - } -} - - -struct b2SimplexVertex -{ - b2Vec2 wA; // support point in proxyA - b2Vec2 wB; // support point in proxyB - b2Vec2 w; // wB - wA - float32 a; // barycentric coordinate for closest point - int32 indexA; // wA index - int32 indexB; // wB index -}; - -struct b2Simplex -{ - void ReadCache( const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Transform& transformA, - const b2DistanceProxy* proxyB, const b2Transform& transformB) - { - b2Assert(cache->count <= 3); - - // Copy data from cache. - m_count = cache->count; - b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - b2SimplexVertex* v = vertices + i; - v->indexA = cache->indexA[i]; - v->indexB = cache->indexB[i]; - b2Vec2 wALocal = proxyA->GetVertex(v->indexA); - b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - v->a = 0.0f; - } - - // Compute the new simplex metric, if it is substantially different than - // old metric then flush the simplex. - if (m_count > 1) - { - float32 metric1 = cache->metric; - float32 metric2 = GetMetric(); - if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) - { - // Reset the simplex. - m_count = 0; - } - } - - // If the cache is empty or invalid ... - if (m_count == 0) - { - b2SimplexVertex* v = vertices + 0; - v->indexA = 0; - v->indexB = 0; - b2Vec2 wALocal = proxyA->GetVertex(0); - b2Vec2 wBLocal = proxyB->GetVertex(0); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - m_count = 1; - } - } - - void WriteCache(b2SimplexCache* cache) const - { - cache->metric = GetMetric(); - cache->count = uint16(m_count); - const b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - cache->indexA[i] = uint8(vertices[i].indexA); - cache->indexB[i] = uint8(vertices[i].indexB); - } - } - - b2Vec2 GetSearchDirection() const - { - switch (m_count) - { - case 1: - return -m_v1.w; - - case 2: - { - b2Vec2 e12 = m_v2.w - m_v1.w; - float32 sgn = b2Cross(e12, -m_v1.w); - if (sgn > 0.0f) - { - // Origin is left of e12. - return b2Cross(1.0f, e12); - } - else - { - // Origin is right of e12. - return b2Cross(e12, 1.0f); - } - } - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - b2Vec2 GetClosestPoint() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return b2Vec2_zero; - - case 1: - return m_v1.w; - - case 2: - return m_v1.a * m_v1.w + m_v2.a * m_v2.w; - - case 3: - return b2Vec2_zero; - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const - { - switch (m_count) - { - case 0: - b2Assert(false); - break; - - case 1: - *pA = m_v1.wA; - *pB = m_v1.wB; - break; - - case 2: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; - *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; - break; - - case 3: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; - *pB = *pA; - break; - - default: - b2Assert(false); - break; - } - } - - float32 GetMetric() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return 0.0; - - case 1: - return 0.0f; - - case 2: - return b2Distance(m_v1.w, m_v2.w); - - case 3: - return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); - - default: - b2Assert(false); - return 0.0f; - } - } - - void Solve2(); - void Solve3(); - - b2SimplexVertex m_v1, m_v2, m_v3; - int32 m_count; -}; - - -// Solve a line segment using barycentric coordinates. -// -// p = a1 * w1 + a2 * w2 -// a1 + a2 = 1 -// -// The vector from the origin to the closest point on the line is -// perpendicular to the line. -// e12 = w2 - w1 -// dot(p, e) = 0 -// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 -// -// 2-by-2 linear system -// [1 1 ][a1] = [1] -// [w1.e12 w2.e12][a2] = [0] -// -// Define -// d12_1 = dot(w2, e12) -// d12_2 = -dot(w1, e12) -// d12 = d12_1 + d12_2 -// -// Solution -// a1 = d12_1 / d12 -// a2 = d12_2 / d12 -void b2Simplex::Solve2() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 e12 = w2 - w1; - - // w1 region - float32 d12_2 = -b2Dot(w1, e12); - if (d12_2 <= 0.0f) - { - // a2 <= 0, so we clamp it to 0 - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // w2 region - float32 d12_1 = b2Dot(w2, e12); - if (d12_1 <= 0.0f) - { - // a1 <= 0, so we clamp it to 0 - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // Must be in e12 region. - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; -} - -// Possible regions: -// - points[2] -// - edge points[0]-points[2] -// - edge points[1]-points[2] -// - inside the triangle -void b2Simplex::Solve3() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 w3 = m_v3.w; - - // Edge12 - // [1 1 ][a1] = [1] - // [w1.e12 w2.e12][a2] = [0] - // a3 = 0 - b2Vec2 e12 = w2 - w1; - float32 w1e12 = b2Dot(w1, e12); - float32 w2e12 = b2Dot(w2, e12); - float32 d12_1 = w2e12; - float32 d12_2 = -w1e12; - - // Edge13 - // [1 1 ][a1] = [1] - // [w1.e13 w3.e13][a3] = [0] - // a2 = 0 - b2Vec2 e13 = w3 - w1; - float32 w1e13 = b2Dot(w1, e13); - float32 w3e13 = b2Dot(w3, e13); - float32 d13_1 = w3e13; - float32 d13_2 = -w1e13; - - // Edge23 - // [1 1 ][a2] = [1] - // [w2.e23 w3.e23][a3] = [0] - // a1 = 0 - b2Vec2 e23 = w3 - w2; - float32 w2e23 = b2Dot(w2, e23); - float32 w3e23 = b2Dot(w3, e23); - float32 d23_1 = w3e23; - float32 d23_2 = -w2e23; - - // Triangle123 - float32 n123 = b2Cross(e12, e13); - - float32 d123_1 = n123 * b2Cross(w2, w3); - float32 d123_2 = n123 * b2Cross(w3, w1); - float32 d123_3 = n123 * b2Cross(w1, w2); - - // w1 region - if (d12_2 <= 0.0f && d13_2 <= 0.0f) - { - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // e12 - if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) - { - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; - return; - } - - // e13 - if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) - { - float32 inv_d13 = 1.0f / (d13_1 + d13_2); - m_v1.a = d13_1 * inv_d13; - m_v3.a = d13_2 * inv_d13; - m_count = 2; - m_v2 = m_v3; - return; - } - - // w2 region - if (d12_1 <= 0.0f && d23_2 <= 0.0f) - { - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // w3 region - if (d13_1 <= 0.0f && d23_1 <= 0.0f) - { - m_v3.a = 1.0f; - m_count = 1; - m_v1 = m_v3; - return; - } - - // e23 - if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) - { - float32 inv_d23 = 1.0f / (d23_1 + d23_2); - m_v2.a = d23_1 * inv_d23; - m_v3.a = d23_2 * inv_d23; - m_count = 2; - m_v1 = m_v3; - return; - } - - // Must be in triangle123 - float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); - m_v1.a = d123_1 * inv_d123; - m_v2.a = d123_2 * inv_d123; - m_v3.a = d123_3 * inv_d123; - m_count = 3; -} - -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input) -{ - ++b2_gjkCalls; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Transform transformA = input->transformA; - b2Transform transformB = input->transformB; - - // Initialize the simplex. - b2Simplex simplex; - simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); - - // Get simplex vertices as an array. - b2SimplexVertex* vertices = &simplex.m_v1; - const int32 k_maxIters = 20; - - // These store the vertices of the last simplex so that we - // can check for duplicates and prevent cycling. - int32 saveA[3], saveB[3]; - int32 saveCount = 0; - - b2Vec2 closestPoint = simplex.GetClosestPoint(); - float32 distanceSqr1 = closestPoint.LengthSquared(); - float32 distanceSqr2 = distanceSqr1; - - // Main iteration loop. - int32 iter = 0; - while (iter < k_maxIters) - { - // Copy simplex so we can identify duplicates. - saveCount = simplex.m_count; - for (int32 i = 0; i < saveCount; ++i) - { - saveA[i] = vertices[i].indexA; - saveB[i] = vertices[i].indexB; - } - - switch (simplex.m_count) - { - case 1: - break; - - case 2: - simplex.Solve2(); - break; - - case 3: - simplex.Solve3(); - break; - - default: - b2Assert(false); - } - - // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.m_count == 3) - { - break; - } - - // Compute closest point. - b2Vec2 p = simplex.GetClosestPoint(); - distanceSqr2 = p.LengthSquared(); - - // Ensure progress - if (distanceSqr2 >= distanceSqr1) - { - //break; - } - distanceSqr1 = distanceSqr2; - - // Get search direction. - b2Vec2 d = simplex.GetSearchDirection(); - - // Ensure the search direction is numerically fit. - if (d.LengthSquared() < b2_epsilon * b2_epsilon) - { - // The origin is probably contained by a line segment - // or triangle. Thus the shapes are overlapped. - - // We can't return zero here even though there may be overlap. - // In case the simplex is a point, segment, or triangle it is difficult - // to determine if the origin is contained in the CSO or very close to it. - break; - } - - // Compute a tentative new simplex vertex using support points. - b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); - vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); - b2Vec2 wBLocal; - vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); - vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); - vertex->w = vertex->wB - vertex->wA; - - // Iteration count is equated to the number of support point calls. - ++iter; - ++b2_gjkIters; - - // Check for duplicate support points. This is the main termination criteria. - bool duplicate = false; - for (int32 i = 0; i < saveCount; ++i) - { - if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) - { - duplicate = true; - break; - } - } - - // If we found a duplicate support point we must exit to avoid cycling. - if (duplicate) - { - break; - } - - // New vertex is ok and needed. - ++simplex.m_count; - } - - b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); - - // Prepare output. - simplex.GetWitnessPoints(&output->pointA, &output->pointB); - output->distance = b2Distance(output->pointA, output->pointB); - output->iterations = iter; - - // Cache the simplex. - simplex.WriteCache(cache); - - // Apply radii if requested. - if (input->useRadii) - { - float32 rA = proxyA->m_radius; - float32 rB = proxyB->m_radius; - - if (output->distance > rA + rB && output->distance > b2_epsilon) - { - // Shapes are still no overlapped. - // Move the witness points to the outer surface. - output->distance -= rA + rB; - b2Vec2 normal = output->pointB - output->pointA; - normal.Normalize(); - output->pointA += rA * normal; - output->pointB -= rB * normal; - } - else - { - // Shapes are overlapped when radii are considered. - // Move the witness points to the middle. - b2Vec2 p = 0.5f * (output->pointA + output->pointB); - output->pointA = p; - output->pointB = p; - output->distance = 0.0f; - } - } -} diff --git a/external/box2d/Collision/b2Distance.h b/external/box2d/Collision/b2Distance.h deleted file mode 100644 index d598b7339d..0000000000 --- a/external/box2d/Collision/b2Distance.h +++ /dev/null @@ -1,141 +0,0 @@ - -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DISTANCE_H -#define B2_DISTANCE_H - -#include - -class b2Shape; - -/// A distance proxy is used by the GJK algorithm. -/// It encapsulates any shape. -struct b2DistanceProxy -{ - b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} - - /// Initialize the proxy using the given shape. The shape - /// must remain in scope while the proxy is in use. - void Set(const b2Shape* shape, int32 index); - - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - - /// Get the vertex count. - int32 GetVertexCount() const; - - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; - - b2Vec2 m_buffer[2]; - const b2Vec2* m_vertices; - int32 m_count; - float32 m_radius; -}; - -/// Used to warm start b2Distance. -/// Set count to zero on first call. -struct b2SimplexCache -{ - float32 metric; ///< length or area - uint16 count; - uint8 indexA[3]; ///< vertices on shape A - uint8 indexB[3]; ///< vertices on shape B -}; - -/// Input for b2Distance. -/// You have to option to use the shape radii -/// in the computation. Even -struct b2DistanceInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Transform transformA; - b2Transform transformB; - bool useRadii; -}; - -/// Output for b2Distance. -struct b2DistanceOutput -{ - b2Vec2 pointA; ///< closest point on shapeA - b2Vec2 pointB; ///< closest point on shapeB - float32 distance; - int32 iterations; ///< number of GJK iterations used -}; - -/// Compute the closest points between two shapes. Supports any combination of: -/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. -/// On the first call set b2SimplexCache.count to zero. -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input); - - -////////////////////////////////////////////////////////////////////////// - -inline int32 b2DistanceProxy::GetVertexCount() const -{ - return m_count; -} - -inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const -{ - b2Assert(0 <= index && index < m_count); - return m_vertices[index]; -} - -inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return bestIndex; -} - -inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return m_vertices[bestIndex]; -} - -#endif diff --git a/external/box2d/Collision/b2DynamicTree.cpp b/external/box2d/Collision/b2DynamicTree.cpp deleted file mode 100644 index d1d53297e2..0000000000 --- a/external/box2d/Collision/b2DynamicTree.cpp +++ /dev/null @@ -1,775 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#ifndef SHP -#include -#else -#include -#endif -using namespace std; - - -b2DynamicTree::b2DynamicTree() -{ - m_root = b2_nullNode; - - m_nodeCapacity = 16; - m_nodeCount = 0; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); - - // Build a linked list for the free list. - for (int32 i = 0; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = 0; - - m_path = 0; - - m_insertionCount = 0; -} - -b2DynamicTree::~b2DynamicTree() -{ - // This frees the entire tree in one shot. - b2Free(m_nodes); -} - -// Allocate a node from the pool. Grow the pool if necessary. -int32 b2DynamicTree::AllocateNode() -{ - // Expand the node pool as needed. - if (m_freeList == b2_nullNode) - { - b2Assert(m_nodeCount == m_nodeCapacity); - - // The free list is empty. Rebuild a bigger pool. - b2TreeNode* oldNodes = m_nodes; - m_nodeCapacity *= 2; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); - b2Free(oldNodes); - - // Build a linked list for the free list. The parent - // pointer becomes the "next" pointer. - for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = m_nodeCount; - } - - // Peel a node off the free list. - int32 nodeId = m_freeList; - m_freeList = m_nodes[nodeId].next; - m_nodes[nodeId].parent = b2_nullNode; - m_nodes[nodeId].child1 = b2_nullNode; - m_nodes[nodeId].child2 = b2_nullNode; - m_nodes[nodeId].height = 0; - m_nodes[nodeId].userData = NULL; - ++m_nodeCount; - return nodeId; -} - -// Return a node to the pool. -void b2DynamicTree::FreeNode(int32 nodeId) -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2Assert(0 < m_nodeCount); - m_nodes[nodeId].next = m_freeList; - m_nodes[nodeId].height = -1; - m_freeList = nodeId; - --m_nodeCount; -} - -// Create a proxy in the tree as a leaf node. We return the index -// of the node instead of a pointer so that we can grow -// the node pool. -int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = AllocateNode(); - - // Fatten the aabb. - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; - m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; - m_nodes[proxyId].userData = userData; - m_nodes[proxyId].height = 0; - - InsertLeaf(proxyId); - - return proxyId; -} - -void b2DynamicTree::DestroyProxy(int32 proxyId) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - b2Assert(m_nodes[proxyId].IsLeaf()); - - RemoveLeaf(proxyId); - FreeNode(proxyId); -} - -bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - - b2Assert(m_nodes[proxyId].IsLeaf()); - - if (m_nodes[proxyId].aabb.Contains(aabb)) - { - return false; - } - - RemoveLeaf(proxyId); - - // Extend AABB. - b2AABB b = aabb; - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - b.lowerBound = b.lowerBound - r; - b.upperBound = b.upperBound + r; - - // Predict AABB displacement. - b2Vec2 d = b2_aabbMultiplier * displacement; - - if (d.x < 0.0f) - { - b.lowerBound.x += d.x; - } - else - { - b.upperBound.x += d.x; - } - - if (d.y < 0.0f) - { - b.lowerBound.y += d.y; - } - else - { - b.upperBound.y += d.y; - } - - m_nodes[proxyId].aabb = b; - - InsertLeaf(proxyId); - return true; -} - -void b2DynamicTree::InsertLeaf(int32 leaf) -{ - ++m_insertionCount; - - if (m_root == b2_nullNode) - { - m_root = leaf; - m_nodes[m_root].parent = b2_nullNode; - return; - } - - // Find the best sibling for this node - b2AABB leafAABB = m_nodes[leaf].aabb; - int32 index = m_root; - while (m_nodes[index].IsLeaf() == false) - { - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - float32 area = m_nodes[index].aabb.GetPerimeter(); - - b2AABB combinedAABB; - combinedAABB.Combine(m_nodes[index].aabb, leafAABB); - float32 combinedArea = combinedAABB.GetPerimeter(); - - // Cost of creating a new parent for this node and the new leaf - float32 cost = 2.0f * combinedArea; - - // Minimum cost of pushing the leaf further down the tree - float32 inheritanceCost = 2.0f * (combinedArea - area); - - // Cost of descending into child1 - float32 cost1; - if (m_nodes[child1].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - cost1 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost1 = (newArea - oldArea) + inheritanceCost; - } - - // Cost of descending into child2 - float32 cost2; - if (m_nodes[child2].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - cost2 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost2 = newArea - oldArea + inheritanceCost; - } - - // Descend according to the minimum cost. - if (cost < cost1 && cost < cost2) - { - break; - } - - // Descend - if (cost1 < cost2) - { - index = child1; - } - else - { - index = child2; - } - } - - int32 sibling = index; - - // Create a new parent. - int32 oldParent = m_nodes[sibling].parent; - int32 newParent = AllocateNode(); - m_nodes[newParent].parent = oldParent; - m_nodes[newParent].userData = NULL; - m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); - m_nodes[newParent].height = m_nodes[sibling].height + 1; - - if (oldParent != b2_nullNode) - { - // The sibling was not the root. - if (m_nodes[oldParent].child1 == sibling) - { - m_nodes[oldParent].child1 = newParent; - } - else - { - m_nodes[oldParent].child2 = newParent; - } - - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - } - else - { - // The sibling was the root. - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - m_root = newParent; - } - - // Walk back up the tree fixing heights and AABBs - index = m_nodes[leaf].parent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - b2Assert(child1 != b2_nullNode); - b2Assert(child2 != b2_nullNode); - - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - index = m_nodes[index].parent; - } - - //Validate(); -} - -void b2DynamicTree::RemoveLeaf(int32 leaf) -{ - if (leaf == m_root) - { - m_root = b2_nullNode; - return; - } - - int32 parent = m_nodes[leaf].parent; - int32 grandParent = m_nodes[parent].parent; - int32 sibling; - if (m_nodes[parent].child1 == leaf) - { - sibling = m_nodes[parent].child2; - } - else - { - sibling = m_nodes[parent].child1; - } - - if (grandParent != b2_nullNode) - { - // Destroy parent and connect sibling to grandParent. - if (m_nodes[grandParent].child1 == parent) - { - m_nodes[grandParent].child1 = sibling; - } - else - { - m_nodes[grandParent].child2 = sibling; - } - m_nodes[sibling].parent = grandParent; - FreeNode(parent); - - // Adjust ancestor bounds. - int32 index = grandParent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - - index = m_nodes[index].parent; - } - } - else - { - m_root = sibling; - m_nodes[sibling].parent = b2_nullNode; - FreeNode(parent); - } - - //Validate(); -} - -// Perform a left or right rotation if node A is imbalanced. -// Returns the new root index. -int32 b2DynamicTree::Balance(int32 iA) -{ - b2Assert(iA != b2_nullNode); - - b2TreeNode* A = m_nodes + iA; - if (A->IsLeaf() || A->height < 2) - { - return iA; - } - - int32 iB = A->child1; - int32 iC = A->child2; - b2Assert(0 <= iB && iB < m_nodeCapacity); - b2Assert(0 <= iC && iC < m_nodeCapacity); - - b2TreeNode* B = m_nodes + iB; - b2TreeNode* C = m_nodes + iC; - - int32 balance = C->height - B->height; - - // Rotate C up - if (balance > 1) - { - int32 iF = C->child1; - int32 iG = C->child2; - b2TreeNode* F = m_nodes + iF; - b2TreeNode* G = m_nodes + iG; - b2Assert(0 <= iF && iF < m_nodeCapacity); - b2Assert(0 <= iG && iG < m_nodeCapacity); - - // Swap A and C - C->child1 = iA; - C->parent = A->parent; - A->parent = iC; - - // A's old parent should point to C - if (C->parent != b2_nullNode) - { - if (m_nodes[C->parent].child1 == iA) - { - m_nodes[C->parent].child1 = iC; - } - else - { - b2Assert(m_nodes[C->parent].child2 == iA); - m_nodes[C->parent].child2 = iC; - } - } - else - { - m_root = iC; - } - - // Rotate - if (F->height > G->height) - { - C->child2 = iF; - A->child2 = iG; - G->parent = iA; - A->aabb.Combine(B->aabb, G->aabb); - C->aabb.Combine(A->aabb, F->aabb); - - A->height = 1 + b2Max(B->height, G->height); - C->height = 1 + b2Max(A->height, F->height); - } - else - { - C->child2 = iG; - A->child2 = iF; - F->parent = iA; - A->aabb.Combine(B->aabb, F->aabb); - C->aabb.Combine(A->aabb, G->aabb); - - A->height = 1 + b2Max(B->height, F->height); - C->height = 1 + b2Max(A->height, G->height); - } - - return iC; - } - - // Rotate B up - if (balance < -1) - { - int32 iD = B->child1; - int32 iE = B->child2; - b2TreeNode* D = m_nodes + iD; - b2TreeNode* E = m_nodes + iE; - b2Assert(0 <= iD && iD < m_nodeCapacity); - b2Assert(0 <= iE && iE < m_nodeCapacity); - - // Swap A and B - B->child1 = iA; - B->parent = A->parent; - A->parent = iB; - - // A's old parent should point to B - if (B->parent != b2_nullNode) - { - if (m_nodes[B->parent].child1 == iA) - { - m_nodes[B->parent].child1 = iB; - } - else - { - b2Assert(m_nodes[B->parent].child2 == iA); - m_nodes[B->parent].child2 = iB; - } - } - else - { - m_root = iB; - } - - // Rotate - if (D->height > E->height) - { - B->child2 = iD; - A->child1 = iE; - E->parent = iA; - A->aabb.Combine(C->aabb, E->aabb); - B->aabb.Combine(A->aabb, D->aabb); - - A->height = 1 + b2Max(C->height, E->height); - B->height = 1 + b2Max(A->height, D->height); - } - else - { - B->child2 = iE; - A->child1 = iD; - D->parent = iA; - A->aabb.Combine(C->aabb, D->aabb); - B->aabb.Combine(A->aabb, E->aabb); - - A->height = 1 + b2Max(C->height, D->height); - B->height = 1 + b2Max(A->height, E->height); - } - - return iB; - } - - return iA; -} - -int32 b2DynamicTree::GetHeight() const -{ - if (m_root == b2_nullNode) - { - return 0; - } - - return m_nodes[m_root].height; -} - -// -float32 b2DynamicTree::GetAreaRatio() const -{ - if (m_root == b2_nullNode) - { - return 0.0f; - } - - const b2TreeNode* root = m_nodes + m_root; - float32 rootArea = root->aabb.GetPerimeter(); - - float32 totalArea = 0.0f; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height < 0) - { - // Free node in pool - continue; - } - - totalArea += node->aabb.GetPerimeter(); - } - - return totalArea / rootArea; -} - -// Compute the height of a sub-tree. -int32 b2DynamicTree::ComputeHeight(int32 nodeId) const -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2TreeNode* node = m_nodes + nodeId; - - if (node->IsLeaf()) - { - return 0; - } - - int32 height1 = ComputeHeight(node->child1); - int32 height2 = ComputeHeight(node->child2); - return 1 + b2Max(height1, height2); -} - -int32 b2DynamicTree::ComputeHeight() const -{ - int32 height = ComputeHeight(m_root); - return height; -} - -void b2DynamicTree::ValidateStructure(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - if (index == m_root) - { - b2Assert(m_nodes[index].parent == b2_nullNode); - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - b2Assert(m_nodes[child1].parent == index); - b2Assert(m_nodes[child2].parent == index); - - ValidateStructure(child1); - ValidateStructure(child2); -} - -void b2DynamicTree::ValidateMetrics(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - int32 height1 = m_nodes[child1].height; - int32 height2 = m_nodes[child2].height; - int32 height; - height = 1 + b2Max(height1, height2); - b2Assert(node->height == height); - - b2AABB aabb; - aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - b2Assert(aabb.lowerBound == node->aabb.lowerBound); - b2Assert(aabb.upperBound == node->aabb.upperBound); - - ValidateMetrics(child1); - ValidateMetrics(child2); -} - -void b2DynamicTree::Validate() const -{ - ValidateStructure(m_root); - ValidateMetrics(m_root); - - int32 freeCount = 0; - int32 freeIndex = m_freeList; - while (freeIndex != b2_nullNode) - { - b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); - freeIndex = m_nodes[freeIndex].next; - ++freeCount; - } - - b2Assert(GetHeight() == ComputeHeight()); - - b2Assert(m_nodeCount + freeCount == m_nodeCapacity); -} - -int32 b2DynamicTree::GetMaxBalance() const -{ - int32 maxBalance = 0; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height <= 1) - { - continue; - } - - b2Assert(node->IsLeaf() == false); - - int32 child1 = node->child1; - int32 child2 = node->child2; - int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); - maxBalance = b2Max(maxBalance, balance); - } - - return maxBalance; -} - -void b2DynamicTree::RebuildBottomUp() -{ - int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); - int32 count = 0; - - // Build array of leaves. Free the rest. - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - if (m_nodes[i].height < 0) - { - // free node in pool - continue; - } - - if (m_nodes[i].IsLeaf()) - { - m_nodes[i].parent = b2_nullNode; - nodes[count] = i; - ++count; - } - else - { - FreeNode(i); - } - } - - while (count > 1) - { - float32 minCost = b2_maxFloat; - int32 iMin = -1, jMin = -1; - for (int32 i = 0; i < count; ++i) - { - b2AABB aabbi = m_nodes[nodes[i]].aabb; - - for (int32 j = i + 1; j < count; ++j) - { - b2AABB aabbj = m_nodes[nodes[j]].aabb; - b2AABB b; - b.Combine(aabbi, aabbj); - float32 cost = b.GetPerimeter(); - if (cost < minCost) - { - iMin = i; - jMin = j; - minCost = cost; - } - } - } - - int32 index1 = nodes[iMin]; - int32 index2 = nodes[jMin]; - b2TreeNode* child1 = m_nodes + index1; - b2TreeNode* child2 = m_nodes + index2; - - int32 parentIndex = AllocateNode(); - b2TreeNode* parent = m_nodes + parentIndex; - parent->child1 = index1; - parent->child2 = index2; - parent->height = 1 + b2Max(child1->height, child2->height); - parent->aabb.Combine(child1->aabb, child2->aabb); - parent->parent = b2_nullNode; - - child1->parent = parentIndex; - child2->parent = parentIndex; - - nodes[jMin] = nodes[count-1]; - nodes[iMin] = parentIndex; - --count; - } - - m_root = nodes[0]; - b2Free(nodes); - - Validate(); -} diff --git a/external/box2d/Collision/b2DynamicTree.h b/external/box2d/Collision/b2DynamicTree.h deleted file mode 100644 index 33f16b0f32..0000000000 --- a/external/box2d/Collision/b2DynamicTree.h +++ /dev/null @@ -1,284 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DYNAMIC_TREE_H -#define B2_DYNAMIC_TREE_H - -#include -#include - -#define b2_nullNode (-1) - -/// A node in the dynamic tree. The client does not interact with this directly. -struct b2TreeNode -{ - bool IsLeaf() const - { - return child1 == b2_nullNode; - } - - /// Enlarged AABB - b2AABB aabb; - - void* userData; - - union - { - int32 parent; - int32 next; - }; - - int32 child1; - int32 child2; - - // leaf = 0, free node = -1 - int32 height; -}; - -/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. -/// A dynamic tree arranges data in a binary tree to accelerate -/// queries such as volume queries and ray casts. Leafs are proxies -/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor -/// so that the proxy AABB is bigger than the client object. This allows the client -/// object to move by small amounts without triggering a tree update. -/// -/// Nodes are pooled and relocatable, so we use node indices rather than pointers. -class b2DynamicTree -{ -public: - /// Constructing the tree initializes the node pool. - b2DynamicTree(); - - /// Destroy the tree, freeing the node pool. - ~b2DynamicTree(); - - /// Create a proxy. Provide a tight fitting AABB and a userData pointer. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. This asserts if the id is invalid. - void DestroyProxy(int32 proxyId); - - /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, - /// then the proxy is removed from the tree and re-inserted. Otherwise - /// the function returns immediately. - /// @return true if the proxy was re-inserted. - bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); - - /// Get proxy user data. - /// @return the proxy user data or 0 if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Validate this tree. For testing. - void Validate() const; - - /// Compute the height of the binary tree in O(N) time. Should not be - /// called often. - int32 GetHeight() const; - - /// Get the maximum balance of an node in the tree. The balance is the difference - /// in height of the two children of a node. - int32 GetMaxBalance() const; - - /// Get the ratio of the sum of the node areas to the root area. - float32 GetAreaRatio() const; - - /// Build an optimal tree. Very expensive. For testing. - void RebuildBottomUp(); - -private: - - int32 AllocateNode(); - void FreeNode(int32 node); - - void InsertLeaf(int32 node); - void RemoveLeaf(int32 node); - - int32 Balance(int32 index); - - int32 ComputeHeight() const; - int32 ComputeHeight(int32 nodeId) const; - - void ValidateStructure(int32 index) const; - void ValidateMetrics(int32 index) const; - - int32 m_root; - - b2TreeNode* m_nodes; - int32 m_nodeCount; - int32 m_nodeCapacity; - - int32 m_freeList; - - /// This is used to incrementally traverse the tree for re-balancing. - uint32 m_path; - - int32 m_insertionCount; -}; - -inline void* b2DynamicTree::GetUserData(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].userData; -} - -inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].aabb; -} - -template -inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const -{ - b2GrowableStack stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, aabb)) - { - if (node->IsLeaf()) - { - bool proceed = callback->QueryCallback(nodeId); - if (proceed == false) - { - return; - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } - } -} - -template -inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const -{ - b2Vec2 p1 = input.p1; - b2Vec2 p2 = input.p2; - b2Vec2 r = p2 - p1; - b2Assert(r.LengthSquared() > 0.0f); - r.Normalize(); - - // v is perpendicular to the segment. - b2Vec2 v = b2Cross(1.0f, r); - b2Vec2 abs_v = b2Abs(v); - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - - float32 maxFraction = input.maxFraction; - - // Build a bounding box for the segment. - b2AABB segmentAABB; - { - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - - b2GrowableStack stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, segmentAABB) == false) - { - continue; - } - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - b2Vec2 c = node->aabb.GetCenter(); - b2Vec2 h = node->aabb.GetExtents(); - float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); - if (separation > 0.0f) - { - continue; - } - - if (node->IsLeaf()) - { - b2RayCastInput subInput; - subInput.p1 = input.p1; - subInput.p2 = input.p2; - subInput.maxFraction = maxFraction; - - float32 value = callback->RayCastCallback(subInput, nodeId); - - if (value == 0.0f) - { - // The client has terminated the ray cast. - return; - } - - if (value > 0.0f) - { - // Update segment bounding box. - maxFraction = value; - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } -} - -#endif diff --git a/external/box2d/Collision/b2TimeOfImpact.cpp b/external/box2d/Collision/b2TimeOfImpact.cpp deleted file mode 100644 index 1d643addd8..0000000000 --- a/external/box2d/Collision/b2TimeOfImpact.cpp +++ /dev/null @@ -1,488 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#ifdef SHP -#include -#else -#include -#endif - -using namespace std; - -int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; -int32 b2_toiRootIters, b2_toiMaxRootIters; - -struct b2SeparationFunction -{ - enum Type - { - e_points, - e_faceA, - e_faceB - }; - - // TODO_ERIN might not need to return the separation - - float32 Initialize(const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Sweep& sweepA, - const b2DistanceProxy* proxyB, const b2Sweep& sweepB, - float32 t1) - { - m_proxyA = proxyA; - m_proxyB = proxyB; - int32 count = cache->count; - b2Assert(0 < count && count < 3); - - m_sweepA = sweepA; - m_sweepB = sweepB; - - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t1); - m_sweepB.GetTransform(&xfB, t1); - - if (count == 1) - { - m_type = e_points; - b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - m_axis = pointB - pointA; - float32 s = m_axis.Normalize(); - return s; - } - else if (cache->indexA[0] == cache->indexA[1]) - { - // Two points on B and one on A. - m_type = e_faceB; - b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); - b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); - - m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfB.q, m_axis); - - m_localPoint = 0.5f * (localPointB1 + localPointB2); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 s = b2Dot(pointA - pointB, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - else - { - // Two points on A and one or two points on B. - m_type = e_faceA; - b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); - - m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfA.q, m_axis); - - m_localPoint = 0.5f * (localPointA1 + localPointA2); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 s = b2Dot(pointB - pointA, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - } - - float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - - *indexA = m_proxyA->GetSupport(axisA); - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, m_axis); - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - *indexA = -1; - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 axisA = b2MulT(xfA.q, -normal); - - *indexB = -1; - *indexA = m_proxyA->GetSupport(axisA); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - *indexA = -1; - *indexB = -1; - return 0.0f; - } - } - - float32 Evaluate(int32 indexA, int32 indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, m_axis); - - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 axisA = b2MulT(xfA.q, -normal); - - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - return 0.0f; - } - } - - const b2DistanceProxy* m_proxyA; - const b2DistanceProxy* m_proxyB; - b2Sweep m_sweepA, m_sweepB; - Type m_type; - b2Vec2 m_localPoint; - b2Vec2 m_axis; -}; - -// CCD via the local separating axis method. This seeks progression -// by computing the largest time at which separation is maintained. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) -{ - ++b2_toiCalls; - - output->state = b2TOIOutput::e_unknown; - output->t = input->tMax; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Sweep sweepA = input->sweepA; - b2Sweep sweepB = input->sweepB; - - // Large rotations can make the root finder fail, so we normalize the - // sweep angles. - sweepA.Normalize(); - sweepB.Normalize(); - - float32 tMax = input->tMax; - - float32 totalRadius = proxyA->m_radius + proxyB->m_radius; - float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); - float32 tolerance = 0.25f * b2_linearSlop; - b2Assert(target > tolerance); - - float32 t1 = 0.0f; - const int32 k_maxIterations = 20; // TODO_ERIN b2Settings - int32 iter = 0; - - // Prepare input for distance query. - b2SimplexCache cache; - cache.count = 0; - b2DistanceInput distanceInput; - distanceInput.proxyA = input->proxyA; - distanceInput.proxyB = input->proxyB; - distanceInput.useRadii = false; - - // The outer loop progressively attempts to compute new separating axes. - // This loop terminates when an axis is repeated (no progress is made). - for(;;) - { - b2Transform xfA, xfB; - sweepA.GetTransform(&xfA, t1); - sweepB.GetTransform(&xfB, t1); - - // Get the distance between shapes. We can also use the results - // to get a separating axis. - distanceInput.transformA = xfA; - distanceInput.transformB = xfB; - b2DistanceOutput distanceOutput; - b2Distance(&distanceOutput, &cache, &distanceInput); - - // If the shapes are overlapped, we give up on continuous collision. - if (distanceOutput.distance <= 0.0f) - { - // Failure! - output->state = b2TOIOutput::e_overlapped; - output->t = 0.0f; - break; - } - - if (distanceOutput.distance < target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_touching; - output->t = t1; - break; - } - - // Initialize the separating axis. - b2SeparationFunction fcn; - fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); -#if 0 - // Dump the curve seen by the root finder - { - const int32 N = 100; - float32 dx = 1.0f / N; - float32 xs[N+1]; - float32 fs[N+1]; - - float32 x = 0.0f; - - for (int32 i = 0; i <= N; ++i) - { - sweepA.GetTransform(&xfA, x); - sweepB.GetTransform(&xfB, x); - float32 f = fcn.Evaluate(xfA, xfB) - target; - - printf("%g %g\n", x, f); - - xs[i] = x; - fs[i] = f; - - x += dx; - } - } -#endif - - // Compute the TOI on the separating axis. We do this by successively - // resolving the deepest point. This loop is bounded by the number of vertices. - bool done = false; - float32 t2 = tMax; - int32 pushBackIter = 0; - for (;;) - { - // Find the deepest point at t2. Store the witness point indices. - int32 indexA, indexB; - float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); - - // Is the final configuration separated? - if (s2 > target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_separated; - output->t = tMax; - done = true; - break; - } - - // Has the separation reached tolerance? - if (s2 > target - tolerance) - { - // Advance the sweeps - t1 = t2; - break; - } - - // Compute the initial separation of the witness points. - float32 s1 = fcn.Evaluate(indexA, indexB, t1); - - // Check for initial overlap. This might happen if the root finder - // runs out of iterations. - if (s1 < target - tolerance) - { - output->state = b2TOIOutput::e_failed; - output->t = t1; - done = true; - break; - } - - // Check for touching - if (s1 <= target + tolerance) - { - // Victory! t1 should hold the TOI (could be 0.0). - output->state = b2TOIOutput::e_touching; - output->t = t1; - done = true; - break; - } - - // Compute 1D root of: f(x) - target = 0 - int32 rootIterCount = 0; - float32 a1 = t1, a2 = t2; - for (;;) - { - // Use a mix of the secant rule and bisection. - float32 t; - if (rootIterCount & 1) - { - // Secant rule to improve convergence. - t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); - } - else - { - // Bisection to guarantee progress. - t = 0.5f * (a1 + a2); - } - - float32 s = fcn.Evaluate(indexA, indexB, t); - - if (b2Abs(s - target) < tolerance) - { - // t2 holds a tentative value for t1 - t2 = t; - break; - } - - // Ensure we continue to bracket the root. - if (s > target) - { - a1 = t; - s1 = s; - } - else - { - a2 = t; - s2 = s; - } - - ++rootIterCount; - ++b2_toiRootIters; - - if (rootIterCount == 50) - { - break; - } - } - - b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); - - ++pushBackIter; - - if (pushBackIter == b2_maxPolygonVertices) - { - break; - } - } - - ++iter; - ++b2_toiIters; - - if (done) - { - break; - } - - if (iter == k_maxIterations) - { - // Root finder got stuck. Semi-victory. - output->state = b2TOIOutput::e_failed; - output->t = t1; - break; - } - } - - b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); -} diff --git a/external/box2d/Collision/b2TimeOfImpact.h b/external/box2d/Collision/b2TimeOfImpact.h deleted file mode 100644 index 2e4f8228ff..0000000000 --- a/external/box2d/Collision/b2TimeOfImpact.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_TIME_OF_IMPACT_H -#define B2_TIME_OF_IMPACT_H - -#include -#include - -/// Input parameters for b2TimeOfImpact -struct b2TOIInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Sweep sweepA; - b2Sweep sweepB; - float32 tMax; // defines sweep interval [0, tMax] -}; - -// Output parameters for b2TimeOfImpact. -struct b2TOIOutput -{ - enum State - { - e_unknown, - e_failed, - e_overlapped, - e_touching, - e_separated - }; - - State state; - float32 t; -}; - -/// Compute the upper bound on time before two shapes penetrate. Time is represented as -/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, -/// non-tunneling collision. If you change the time interval, you should call this function -/// again. -/// Note: use b2Distance to compute the contact point and normal at the time of impact. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); - -#endif diff --git a/external/box2d/Common/b2BlockAllocator.cpp b/external/box2d/Common/b2BlockAllocator.cpp deleted file mode 100644 index 2e862091f9..0000000000 --- a/external/box2d/Common/b2BlockAllocator.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -using namespace std; - -int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = -{ - 16, // 0 - 32, // 1 - 64, // 2 - 96, // 3 - 128, // 4 - 160, // 5 - 192, // 6 - 224, // 7 - 256, // 8 - 320, // 9 - 384, // 10 - 448, // 11 - 512, // 12 - 640, // 13 -}; -uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; -bool b2BlockAllocator::s_blockSizeLookupInitialized; - -struct b2Chunk -{ - int32 blockSize; - b2Block* blocks; -}; - -struct b2Block -{ - b2Block* next; -}; - -b2BlockAllocator::b2BlockAllocator() -{ - b2Assert(b2_blockSizes < UCHAR_MAX); - - m_chunkSpace = b2_chunkArrayIncrement; - m_chunkCount = 0; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - memset(m_freeLists, 0, sizeof(m_freeLists)); - - if (s_blockSizeLookupInitialized == false) - { - int32 j = 0; - for (int32 i = 1; i <= b2_maxBlockSize; ++i) - { - b2Assert(j < b2_blockSizes); - if (i <= s_blockSizes[j]) - { - s_blockSizeLookup[i] = (uint8)j; - } - else - { - ++j; - s_blockSizeLookup[i] = (uint8)j; - } - } - - s_blockSizeLookupInitialized = true; - } -} - -b2BlockAllocator::~b2BlockAllocator() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - b2Free(m_chunks); -} - -void* b2BlockAllocator::Allocate(int32 size) -{ - if (size == 0) - return NULL; - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - return b2Alloc(size); - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - - if (m_freeLists[index]) - { - b2Block* block = m_freeLists[index]; - m_freeLists[index] = block->next; - return block; - } - else - { - if (m_chunkCount == m_chunkSpace) - { - b2Chunk* oldChunks = m_chunks; - m_chunkSpace += b2_chunkArrayIncrement; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); - memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); - b2Free(oldChunks); - } - - b2Chunk* chunk = m_chunks + m_chunkCount; - chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); -#if defined(_DEBUG) - memset(chunk->blocks, 0xcd, b2_chunkSize); -#endif - int32 blockSize = s_blockSizes[index]; - chunk->blockSize = blockSize; - int32 blockCount = b2_chunkSize / blockSize; - b2Assert(blockCount * blockSize <= b2_chunkSize); - for (int32 i = 0; i < blockCount - 1; ++i) - { - b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); - b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); - block->next = next; - } - b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); - last->next = NULL; - - m_freeLists[index] = chunk->blocks->next; - ++m_chunkCount; - - return chunk->blocks; - } -} - -void b2BlockAllocator::Free(void* p, int32 size) -{ - if (size == 0) - { - return; - } - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - b2Free(p); - return; - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - -#ifdef _DEBUG - // Verify the memory address and size is valid. - int32 blockSize = s_blockSizes[index]; - bool found = false; - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Chunk* chunk = m_chunks + i; - if (chunk->blockSize != blockSize) - { - b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || - (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); - } - else - { - if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) - { - found = true; - } - } - } - - b2Assert(found); - - memset(p, 0xfd, blockSize); -#endif - - b2Block* block = (b2Block*)p; - block->next = m_freeLists[index]; - m_freeLists[index] = block; -} - -void b2BlockAllocator::Clear() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - m_chunkCount = 0; - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - - memset(m_freeLists, 0, sizeof(m_freeLists)); -} diff --git a/external/box2d/Common/b2BlockAllocator.h b/external/box2d/Common/b2BlockAllocator.h deleted file mode 100644 index ec221fdf61..0000000000 --- a/external/box2d/Common/b2BlockAllocator.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BLOCK_ALLOCATOR_H -#define B2_BLOCK_ALLOCATOR_H - -#include - -const int32 b2_chunkSize = 16 * 1024; -const int32 b2_maxBlockSize = 640; -const int32 b2_blockSizes = 14; -const int32 b2_chunkArrayIncrement = 128; - -struct b2Block; -struct b2Chunk; - -/// This is a small object allocator used for allocating small -/// objects that persist for more than one time step. -/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp -class b2BlockAllocator -{ -public: - b2BlockAllocator(); - ~b2BlockAllocator(); - - /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. - void* Allocate(int32 size); - - /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. - void Free(void* p, int32 size); - - void Clear(); - -private: - - b2Chunk* m_chunks; - int32 m_chunkCount; - int32 m_chunkSpace; - - b2Block* m_freeLists[b2_blockSizes]; - - static int32 s_blockSizes[b2_blockSizes]; - static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; - static bool s_blockSizeLookupInitialized; -}; - -#endif diff --git a/external/box2d/Common/b2Draw.cpp b/external/box2d/Common/b2Draw.cpp deleted file mode 100644 index cb760025e9..0000000000 --- a/external/box2d/Common/b2Draw.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -b2Draw::b2Draw() -{ - m_drawFlags = 0; -} - -void b2Draw::SetFlags(uint32 flags) -{ - m_drawFlags = flags; -} - -uint32 b2Draw::GetFlags() const -{ - return m_drawFlags; -} - -void b2Draw::AppendFlags(uint32 flags) -{ - m_drawFlags |= flags; -} - -void b2Draw::ClearFlags(uint32 flags) -{ - m_drawFlags &= ~flags; -} diff --git a/external/box2d/Common/b2Draw.h b/external/box2d/Common/b2Draw.h deleted file mode 100644 index b33cd8d38f..0000000000 --- a/external/box2d/Common/b2Draw.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -/// Color for debug drawing. Each value has the range [0,1]. -struct b2Color -{ - b2Color() {} - b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} - void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } - float32 r, g, b; -}; - -/// Implement and register this class with a b2World to provide debug drawing of physics -/// entities in your game. -class b2Draw -{ -public: - b2Draw(); - - virtual ~b2Draw() {} - - enum - { - e_shapeBit = 0x0001, ///< draw shapes - e_jointBit = 0x0002, ///< draw joint connections - e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes - e_pairBit = 0x0008, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0010 ///< draw center of mass frame - }; - - /// Set the drawing flags. - void SetFlags(uint32 flags); - - /// Get the drawing flags. - uint32 GetFlags() const; - - /// Append flags to the current flags. - void AppendFlags(uint32 flags); - - /// Clear flags from the current flags. - void ClearFlags(uint32 flags); - - /// Draw a closed polygon provided in CCW order. - virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a solid closed polygon provided in CCW order. - virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a circle. - virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; - - /// Draw a solid circle. - virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; - - /// Draw a line segment. - virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; - - /// Draw a transform. Choose your own length scale. - /// @param xf a transform. - virtual void DrawTransform(const b2Transform& xf) = 0; - -protected: - uint32 m_drawFlags; -}; diff --git a/external/box2d/Common/b2GrowableStack.h b/external/box2d/Common/b2GrowableStack.h deleted file mode 100644 index 68809521f4..0000000000 --- a/external/box2d/Common/b2GrowableStack.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright (c) 2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_GROWABLE_STACK_H -#define B2_GROWABLE_STACK_H -#include -#include - -/// This is a growable LIFO stack with an initial capacity of N. -/// If the stack size exceeds the initial capacity, the heap is used -/// to increase the size of the stack. -template -class b2GrowableStack -{ -public: - b2GrowableStack() - { - m_stack = m_array; - m_count = 0; - m_capacity = N; - } - - ~b2GrowableStack() - { - if (m_stack != m_array) - { - b2Free(m_stack); - m_stack = NULL; - } - } - - void Push(const T& element) - { - if (m_count == m_capacity) - { - T* old = m_stack; - m_capacity *= 2; - m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); - std::memcpy(m_stack, old, m_count * sizeof(T)); - if (old != m_array) - { - b2Free(old); - } - } - - m_stack[m_count] = element; - ++m_count; - } - - T Pop() - { - b2Assert(m_count > 0); - --m_count; - return m_stack[m_count]; - } - - int32 GetCount() - { - return m_count; - } - -private: - T* m_stack; - T m_array[N]; - int32 m_count; - int32 m_capacity; -}; - - -#endif diff --git a/external/box2d/Common/b2Math.cpp b/external/box2d/Common/b2Math.cpp deleted file mode 100644 index 15d68fce96..0000000000 --- a/external/box2d/Common/b2Math.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -const b2Vec2 b2Vec2_zero(0.0f, 0.0f); - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec3 x; - x.x = det * b2Dot(b, b2Cross(ey, ez)); - x.y = det * b2Dot(ex, b2Cross(b, ez)); - x.z = det * b2Dot(ex, b2Cross(ey, b)); - return x; -} - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const -{ - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; -} - -/// -void b2Mat33::GetInverse22(b2Mat33* M) const -{ - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - - M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; - M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; - M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; -} - -/// Returns the zero matrix if singular. -void b2Mat33::GetSymInverse33(b2Mat33* M) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - - float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; - float32 a22 = ey.y, a23 = ez.y; - float32 a33 = ez.z; - - M->ex.x = det * (a22 * a33 - a23 * a23); - M->ex.y = det * (a13 * a23 - a12 * a33); - M->ex.z = det * (a12 * a23 - a13 * a22); - - M->ey.x = M->ex.y; - M->ey.y = det * (a11 * a33 - a13 * a13); - M->ey.z = det * (a13 * a12 - a11 * a23); - - M->ez.x = M->ex.z; - M->ez.y = M->ey.z; - M->ez.z = det * (a11 * a22 - a12 * a12); -} diff --git a/external/box2d/Common/b2Math.h b/external/box2d/Common/b2Math.h deleted file mode 100644 index a6be671139..0000000000 --- a/external/box2d/Common/b2Math.h +++ /dev/null @@ -1,738 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_MATH_H -#define B2_MATH_H - -#include - -#include -#ifndef SHP -#include -#else -#include -#endif -#include -#include - -using namespace std; - - -/// This function is used to ensure that a floating point number is -/// not a NaN or infinity. -inline bool b2IsValid(float32 x) -{ - if (x != x) - { - // NaN. - return false; - } - - float32 infinity = std::numeric_limits::infinity(); - return -infinity < x && x < infinity; -} - -/// This is a approximate yet fast inverse square-root. -inline float32 b2InvSqrt(float32 x) -{ - union - { - float32 x; - int32 i; - } convert; - - convert.x = x; - float32 xhalf = 0.5f * x; - convert.i = 0x5f3759df - (convert.i >> 1); - x = convert.x; - x = x * (1.5f - xhalf * x * x); - return x; -} - -#define b2Sqrt(x) std::sqrt(x) -#define b2Atan2(y, x) std::atan2(y, x) - -/// A 2D column vector. -struct b2Vec2 -{ - /// Default constructor does nothing (for performance). - b2Vec2() {} - - /// Construct using coordinates. - b2Vec2(float32 x, float32 y) : x(x), y(y) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_) { x = x_; y = y_; } - - /// Negate this vector. - b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } - - /// Read from and indexed element. - float32 operator () (int32 i) const - { - return (&x)[i]; - } - - /// Write to an indexed element. - float32& operator () (int32 i) - { - return (&x)[i]; - } - - /// Add a vector to this vector. - void operator += (const b2Vec2& v) - { - x += v.x; y += v.y; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec2& v) - { - x -= v.x; y -= v.y; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 a) - { - x *= a; y *= a; - } - - /// Get the length of this vector (the norm). - float32 Length() const - { - return b2Sqrt(x * x + y * y); - } - - /// Get the length squared. For performance, use this instead of - /// b2Vec2::Length (if possible). - float32 LengthSquared() const - { - return x * x + y * y; - } - - /// Convert this vector into a unit vector. Returns the length. - float32 Normalize() - { - float32 length = Length(); - if (length < b2_epsilon) - { - return 0.0f; - } - float32 invLength = 1.0f / length; - x *= invLength; - y *= invLength; - - return length; - } - - /// Does this vector contain finite coordinates? - bool IsValid() const - { - return b2IsValid(x) && b2IsValid(y); - } - - /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - b2Vec2 Skew() const - { - return b2Vec2(-y, x); - } - - float32 x, y; -}; - -/// A 2D column vector with 3 elements. -struct b2Vec3 -{ - /// Default constructor does nothing (for performance). - b2Vec3() {} - - /// Construct using coordinates. - b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } - - /// Negate this vector. - b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } - - /// Add a vector to this vector. - void operator += (const b2Vec3& v) - { - x += v.x; y += v.y; z += v.z; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec3& v) - { - x -= v.x; y -= v.y; z -= v.z; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 s) - { - x *= s; y *= s; z *= s; - } - - float32 x, y, z; -}; - -/// A 2-by-2 matrix. Stored in column-major order. -struct b2Mat22 -{ - /// The default constructor does nothing (for performance). - b2Mat22() {} - - /// Construct this matrix using columns. - b2Mat22(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Construct this matrix using scalars. - b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) - { - ex.x = a11; ex.y = a21; - ey.x = a12; ey.y = a22; - } - - /// Initialize this matrix using columns. - void Set(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Set this to the identity matrix. - void SetIdentity() - { - ex.x = 1.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 1.0f; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.x = 0.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 0.0f; - } - - b2Mat22 GetInverse() const - { - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - b2Mat22 B; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - B.ex.x = det * d; B.ey.x = -det * b; - B.ex.y = -det * c; B.ey.y = det * a; - return B; - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec2 Solve(const b2Vec2& b) const - { - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; - } - - b2Vec2 ex, ey; -}; - -/// A 3-by-3 matrix. Stored in column-major order. -struct b2Mat33 -{ - /// The default constructor does nothing (for performance). - b2Mat33() {} - - /// Construct this matrix using columns. - b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) - { - ex = c1; - ey = c2; - ez = c3; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.SetZero(); - ey.SetZero(); - ez.SetZero(); - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec3 Solve33(const b2Vec3& b) const; - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. Solve only the upper - /// 2-by-2 matrix equation. - b2Vec2 Solve22(const b2Vec2& b) const; - - /// Get the inverse of this matrix as a 2-by-2. - /// Returns the zero matrix if singular. - void GetInverse22(b2Mat33* M) const; - - /// Get the symmetric inverse of this matrix as a 3-by-3. - /// Returns the zero matrix if singular. - void GetSymInverse33(b2Mat33* M) const; - - b2Vec3 ex, ey, ez; -}; - -/// Rotation -struct b2Rot -{ - b2Rot() {} - - /// Initialize from an angle in radians - explicit b2Rot(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set using an angle in radians. - void Set(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set to the identity rotation - void SetIdentity() - { - s = 0.0f; - c = 1.0f; - } - - /// Get the angle in radians - float32 GetAngle() const - { - return b2Atan2(s, c); - } - - /// Get the x-axis - b2Vec2 GetXAxis() const - { - return b2Vec2(c, s); - } - - /// Get the u-axis - b2Vec2 GetYAxis() const - { - return b2Vec2(-s, c); - } - - /// Sine and cosine - float32 s, c; -}; - -/// A transform contains translation and rotation. It is used to represent -/// the position and orientation of rigid frames. -struct b2Transform -{ - /// The default constructor does nothing. - b2Transform() {} - - /// Initialize using a position vector and a rotation. - b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} - - /// Set this to the identity transform. - void SetIdentity() - { - p.SetZero(); - q.SetIdentity(); - } - - /// Set this based on the position and angle. - void Set(const b2Vec2& position, float32 angle) - { - p = position; - q.Set(angle); - } - - b2Vec2 p; - b2Rot q; -}; - -/// This describes the motion of a body/shape for TOI computation. -/// Shapes are defined with respect to the body origin, which may -/// no coincide with the center of mass. However, to support dynamics -/// we must interpolate the center of mass position. -struct b2Sweep -{ - /// Get the interpolated transform at a specific time. - /// @param beta is a factor in [0,1], where 0 indicates alpha0. - void GetTransform(b2Transform* xfb, float32 beta) const; - - /// Advance the sweep forward, yielding a new initial state. - /// @param alpha the new initial time. - void Advance(float32 alpha); - - /// Normalize the angles. - void Normalize(); - - b2Vec2 localCenter; ///< local center of mass position - b2Vec2 c0, c; ///< center world positions - float32 a0, a; ///< world angles - - /// Fraction of the current time step in the range [0,1] - /// c0 and a0 are the positions at alpha0. - float32 alpha0; -}; - -/// Useful constant -extern const b2Vec2 b2Vec2_zero; - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.x + a.y * b.y; -} - -/// Perform the cross product on two vectors. In 2D this produces a scalar. -inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.y - a.y * b.x; -} - -/// Perform the cross product on a vector and a scalar. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) -{ - return b2Vec2(s * a.y, -s * a.x); -} - -/// Perform the cross product on a scalar and a vector. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) -{ - return b2Vec2(-s * a.y, s * a.x); -} - -/// Multiply a matrix times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another. -inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply a matrix transpose times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another (inverse transform). -inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); -} - -/// Add two vectors component-wise. -inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x + b.x, a.y + b.y); -} - -/// Subtract two vectors component-wise. -inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x - b.x, a.y - b.y); -} - -inline b2Vec2 operator * (float32 s, const b2Vec2& a) -{ - return b2Vec2(s * a.x, s * a.y); -} - -inline bool operator == (const b2Vec2& a, const b2Vec2& b) -{ - return a.x == b.x && a.y == b.y; -} - -inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return c.Length(); -} - -inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return b2Dot(c, c); -} - -inline b2Vec3 operator * (float32 s, const b2Vec3& a) -{ - return b2Vec3(s * a.x, s * a.y, s * a.z); -} - -/// Add two vectors component-wise. -inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); -} - -/// Subtract two vectors component-wise. -inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); -} - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -/// Perform the cross product on two vectors. -inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); -} - -inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(A.ex + B.ex, A.ey + B.ey); -} - -// A * B -inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); -} - -// A^T * B -inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) -{ - b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); - b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); - return b2Mat22(c1, c2); -} - -/// Multiply a matrix times a vector. -inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) -{ - return v.x * A.ex + v.y * A.ey + v.z * A.ez; -} - -/// Multiply a matrix times a vector. -inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply two rotations: q * r -inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) -{ - // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] - // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] - // s = qs * rc + qc * rs - // c = qc * rc - qs * rs - b2Rot qr; - qr.s = q.s * r.c + q.c * r.s; - qr.c = q.c * r.c - q.s * r.s; - return qr; -} - -/// Transpose multiply two rotations: qT * r -inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) -{ - // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] - // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] - // s = qc * rs - qs * rc - // c = qc * rc + qs * rs - b2Rot qr; - qr.s = q.c * r.s - q.s * r.c; - qr.c = q.c * r.c + q.s * r.s; - return qr; -} - -/// Rotate a vector -inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); -} - -/// Inverse rotate a vector -inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); -} - -inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) -{ - float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; - float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; - - return b2Vec2(x, y); -} - -inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) -{ - float32 px = v.x - T.p.x; - float32 py = v.y - T.p.y; - float32 x = (T.q.c * px + T.q.s * py); - float32 y = (-T.q.s * px + T.q.c * py); - - return b2Vec2(x, y); -} - -// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p -// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p -inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2Mul(A.q, B.q); - C.p = b2Mul(A.q, B.p) + A.p; - return C; -} - -// v2 = A.q' * (B.q * v1 + B.p - A.p) -// = A.q' * B.q * v1 + A.q' * (B.p - A.p) -inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2MulT(A.q, B.q); - C.p = b2MulT(A.q, B.p - A.p); - return C; -} - -template -inline T b2Abs(T a) -{ - return a > T(0) ? a : -a; -} - -inline b2Vec2 b2Abs(const b2Vec2& a) -{ - return b2Vec2(b2Abs(a.x), b2Abs(a.y)); -} - -inline b2Mat22 b2Abs(const b2Mat22& A) -{ - return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); -} - -template -inline T b2Min(T a, T b) -{ - return a < b ? a : b; -} - -inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); -} - -template -inline T b2Max(T a, T b) -{ - return a > b ? a : b; -} - -inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); -} - -template -inline T b2Clamp(T a, T low, T high) -{ - return b2Max(low, b2Min(a, high)); -} - -inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) -{ - return b2Max(low, b2Min(a, high)); -} - -template inline void b2Swap(T& a, T& b) -{ - T tmp = a; - a = b; - b = tmp; -} - -/// "Next Largest Power of 2 -/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm -/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with -/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next -/// largest power of 2. For a 32-bit value:" -inline uint32 b2NextPowerOfTwo(uint32 x) -{ - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - return x + 1; -} - -inline bool b2IsPowerOfTwo(uint32 x) -{ - bool result = x > 0 && (x & (x - 1)) == 0; - return result; -} - -inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const -{ - xf->p = (1.0f - beta) * c0 + beta * c; - float32 angle = (1.0f - beta) * a0 + beta * a; - xf->q.Set(angle); - - // Shift to origin - xf->p -= b2Mul(xf->q, localCenter); -} - -inline void b2Sweep::Advance(float32 alpha) -{ - b2Assert(alpha0 < 1.0f); - float32 beta = (alpha - alpha0) / (1.0f - alpha0); - c0 = (1.0f - beta) * c0 + beta * c; - a0 = (1.0f - beta) * a0 + beta * a; - alpha0 = alpha; -} - -/// Normalize an angle in radians to be between -pi and pi -inline void b2Sweep::Normalize() -{ - float32 twoPi = 2.0f * b2_pi; - float32 d = twoPi * floorf(a0 / twoPi); - a0 -= d; - a -= d; -} - -#endif diff --git a/external/box2d/Common/b2Settings.cpp b/external/box2d/Common/b2Settings.cpp deleted file mode 100644 index 84d6f1d0e4..0000000000 --- a/external/box2d/Common/b2Settings.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#ifdef SHP -#include -#include -#include -#include -#else -#include -#include -#include -#endif - - -using namespace std; - - -b2Version b2_version = {2, 2, 1}; - -// Memory allocators. Modify these to use your own allocator. -void* b2Alloc(int32 size) -{ - return malloc(size); -} - -void b2Free(void* mem) -{ - free(mem); -} - -// You can modify this to use your logging facility. -void b2Log(const char* string, ...) -{ -#if defined(SHP) - #ifdef _DEBUG - __App_info(__PRETTY_FUNCTION__ , __LINE__, string); - #endif -#else - va_list args; - va_start(args, string); - vprintf(string, args); - va_end(args); -#endif -} diff --git a/external/box2d/Common/b2Settings.h b/external/box2d/Common/b2Settings.h deleted file mode 100644 index aaf4b12ccf..0000000000 --- a/external/box2d/Common/b2Settings.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_SETTINGS_H -#define B2_SETTINGS_H - -#include -#include - -#define B2_NOT_USED(x) ((void)(x)) -#define b2Assert(A) assert(A) - -typedef signed char int8; -typedef signed short int16; -typedef signed int int32; -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; -typedef float float32; -typedef double float64; - -#define b2_maxFloat FLT_MAX -#define b2_epsilon FLT_EPSILON -#define b2_pi 3.14159265359f - -/// @file -/// Global tuning constants based on meters-kilograms-seconds (MKS) units. -/// - -// Collision - -/// The maximum number of contact points between two convex shapes. Do -/// not change this value. -#define b2_maxManifoldPoints 2 - -/// The maximum number of vertices on a convex polygon. You cannot increase -/// this too much because b2BlockAllocator has a maximum object size. -#define b2_maxPolygonVertices 8 - -/// This is used to fatten AABBs in the dynamic tree. This allows proxies -/// to move by a small amount without triggering a tree adjustment. -/// This is in meters. -#define b2_aabbExtension 0.1f - -/// This is used to fatten AABBs in the dynamic tree. This is used to predict -/// the future position based on the current displacement. -/// This is a dimensionless multiplier. -#define b2_aabbMultiplier 2.0f - -/// A small length used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_linearSlop 0.005f - -/// A small angle used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_angularSlop (2.0f / 180.0f * b2_pi) - -/// The radius of the polygon/edge shape skin. This should not be modified. Making -/// this smaller means polygons will have an insufficient buffer for continuous collision. -/// Making it larger may create artifacts for vertex collision. -#define b2_polygonRadius (2.0f * b2_linearSlop) - -/// Maximum number of sub-steps per contact in continuous physics simulation. -#define b2_maxSubSteps 8 - - -// Dynamics - -/// Maximum number of contacts to be handled to solve a TOI impact. -#define b2_maxTOIContacts 32 - -/// A velocity threshold for elastic collisions. Any collision with a relative linear -/// velocity below this threshold will be treated as inelastic. -#define b2_velocityThreshold 1.0f - -/// The maximum linear position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxLinearCorrection 0.2f - -/// The maximum angular position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) - -/// The maximum linear velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxTranslation 2.0f -#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) - -/// The maximum angular velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxRotation (0.5f * b2_pi) -#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) - -/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so -/// that overlap is removed in one time step. However using values close to 1 often lead -/// to overshoot. -#define b2_baumgarte 0.2f -#define b2_toiBaugarte 0.75f - - -// Sleep - -/// The time that a body must be still before it will go to sleep. -#define b2_timeToSleep 0.5f - -/// A body cannot sleep if its linear velocity is above this tolerance. -#define b2_linearSleepTolerance 0.01f - -/// A body cannot sleep if its angular velocity is above this tolerance. -#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) - -// Memory Allocation - -/// Implement this function to use your own memory allocator. -void* b2Alloc(int32 size); - -/// If you implement b2Alloc, you should also implement this function. -void b2Free(void* mem); - -/// Logging function. -void b2Log(const char* string, ...); - -/// Version numbering scheme. -/// See http://en.wikipedia.org/wiki/Software_versioning -struct b2Version -{ - int32 major; ///< significant changes - int32 minor; ///< incremental changes - int32 revision; ///< bug fixes -}; - -/// Current version. -extern b2Version b2_version; - -#endif diff --git a/external/box2d/Common/b2StackAllocator.cpp b/external/box2d/Common/b2StackAllocator.cpp deleted file mode 100644 index 3caa5d9127..0000000000 --- a/external/box2d/Common/b2StackAllocator.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2StackAllocator::b2StackAllocator() -{ - m_index = 0; - m_allocation = 0; - m_maxAllocation = 0; - m_entryCount = 0; -} - -b2StackAllocator::~b2StackAllocator() -{ - b2Assert(m_index == 0); - b2Assert(m_entryCount == 0); -} - -void* b2StackAllocator::Allocate(int32 size) -{ - b2Assert(m_entryCount < b2_maxStackEntries); - - b2StackEntry* entry = m_entries + m_entryCount; - entry->size = size; - if (m_index + size > b2_stackSize) - { - entry->data = (char*)b2Alloc(size); - entry->usedMalloc = true; - } - else - { - entry->data = m_data + m_index; - entry->usedMalloc = false; - m_index += size; - } - - m_allocation += size; - m_maxAllocation = b2Max(m_maxAllocation, m_allocation); - ++m_entryCount; - - return entry->data; -} - -void b2StackAllocator::Free(void* p) -{ - b2Assert(m_entryCount > 0); - b2StackEntry* entry = m_entries + m_entryCount - 1; - b2Assert(p == entry->data); - if (entry->usedMalloc) - { - b2Free(p); - } - else - { - m_index -= entry->size; - } - m_allocation -= entry->size; - --m_entryCount; - - p = NULL; -} - -int32 b2StackAllocator::GetMaxAllocation() const -{ - return m_maxAllocation; -} diff --git a/external/box2d/Common/b2StackAllocator.h b/external/box2d/Common/b2StackAllocator.h deleted file mode 100644 index 6140d0d802..0000000000 --- a/external/box2d/Common/b2StackAllocator.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_STACK_ALLOCATOR_H -#define B2_STACK_ALLOCATOR_H - -#include - -const int32 b2_stackSize = 100 * 1024; // 100k -const int32 b2_maxStackEntries = 32; - -struct b2StackEntry -{ - char* data; - int32 size; - bool usedMalloc; -}; - -// This is a stack allocator used for fast per step allocations. -// You must nest allocate/free pairs. The code will assert -// if you try to interleave multiple allocate/free pairs. -class b2StackAllocator -{ -public: - b2StackAllocator(); - ~b2StackAllocator(); - - void* Allocate(int32 size); - void Free(void* p); - - int32 GetMaxAllocation() const; - -private: - - char m_data[b2_stackSize]; - int32 m_index; - - int32 m_allocation; - int32 m_maxAllocation; - - b2StackEntry m_entries[b2_maxStackEntries]; - int32 m_entryCount; -}; - -#endif diff --git a/external/box2d/Common/b2Timer.cpp b/external/box2d/Common/b2Timer.cpp deleted file mode 100644 index b2bee94513..0000000000 --- a/external/box2d/Common/b2Timer.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -#if defined(_WIN32) && !defined(SHP) - -float64 b2Timer::s_invFrequency = 0.0f; - -#include - -b2Timer::b2Timer() -{ - LARGE_INTEGER largeInteger; - - if (s_invFrequency == 0.0f) - { - QueryPerformanceFrequency(&largeInteger); - s_invFrequency = float64(largeInteger.QuadPart); - if (s_invFrequency > 0.0f) - { - s_invFrequency = 1000.0f / s_invFrequency; - } - } - - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -void b2Timer::Reset() -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -float32 b2Timer::GetMilliseconds() const -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - float64 count = float64(largeInteger.QuadPart); - float32 ms = float32(s_invFrequency * (count - m_start)); - return ms; -} - -#elif defined(__linux__) || defined (__APPLE__) - -#include - -b2Timer::b2Timer() -{ - Reset(); -} - -void b2Timer::Reset() -{ - timeval t; - gettimeofday(&t, 0); - m_start_sec = t.tv_sec; - m_start_msec = t.tv_usec * 0.001f; -} - -float32 b2Timer::GetMilliseconds() const -{ - timeval t; - gettimeofday(&t, 0); - return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; -} - -#else - -b2Timer::b2Timer() -{ -} - -void b2Timer::Reset() -{ -} - -float32 b2Timer::GetMilliseconds() const -{ - return 0.0f; -} - -#endif diff --git a/external/box2d/Common/b2Timer.h b/external/box2d/Common/b2Timer.h deleted file mode 100644 index 053a107a56..0000000000 --- a/external/box2d/Common/b2Timer.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -/// Timer for profiling. This has platform specific code and may -/// not work on every platform. -class b2Timer -{ -public: - - /// Constructor - b2Timer(); - - /// Reset the timer. - void Reset(); - - /// Get the time since construction or the last reset. - float32 GetMilliseconds() const; - -private: - -#if defined(_WIN32) - float64 m_start; - static float64 s_invFrequency; -#elif defined(__linux__) || defined (__APPLE__) - unsigned long m_start_sec; - unsigned long m_start_msec; -#endif -}; diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp deleted file mode 100644 index 4ae4c41cd3..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); - return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); - allocator->Free(contact, sizeof(b2ChainAndCircleContact)); -} - -b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndCircle( manifold, &edge, xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h deleted file mode 100644 index 1cf601a61f..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ChainAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H -#define B2_CHAIN_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2ChainAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp deleted file mode 100644 index 8116c34d1b..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); - return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); - allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); -} - -b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndPolygon( manifold, &edge, xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h b/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h deleted file mode 100644 index 381c49b844..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ChainAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H -#define B2_CHAIN_AND_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2ChainAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2CircleContact.cpp b/external/box2d/Dynamics/Contacts/b2CircleContact.cpp deleted file mode 100644 index 2436da5132..0000000000 --- a/external/box2d/Dynamics/Contacts/b2CircleContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2CircleContact)); - return new (mem) b2CircleContact(fixtureA, fixtureB); -} - -void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2CircleContact*)contact)->~b2CircleContact(); - allocator->Free(contact, sizeof(b2CircleContact)); -} - -b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideCircles(manifold, - (b2CircleShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2CircleContact.h b/external/box2d/Dynamics/Contacts/b2CircleContact.h deleted file mode 100644 index 6da056ae0d..0000000000 --- a/external/box2d/Dynamics/Contacts/b2CircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CIRCLE_CONTACT_H -#define B2_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2CircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2CircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2Contact.cpp b/external/box2d/Dynamics/Contacts/b2Contact.cpp deleted file mode 100644 index 2389af6434..0000000000 --- a/external/box2d/Dynamics/Contacts/b2Contact.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; -bool b2Contact::s_initialized = false; - -void b2Contact::InitializeRegisters() -{ - AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); - AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); - AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); - AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); - AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); - AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); - AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); -} - -void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, - b2Shape::Type type1, b2Shape::Type type2) -{ - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - s_registers[type1][type2].createFcn = createFcn; - s_registers[type1][type2].destroyFcn = destoryFcn; - s_registers[type1][type2].primary = true; - - if (type1 != type2) - { - s_registers[type2][type1].createFcn = createFcn; - s_registers[type2][type1].destroyFcn = destoryFcn; - s_registers[type2][type1].primary = false; - } -} - -b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - if (s_initialized == false) - { - InitializeRegisters(); - s_initialized = true; - } - - b2Shape::Type type1 = fixtureA->GetType(); - b2Shape::Type type2 = fixtureB->GetType(); - - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; - if (createFcn) - { - if (s_registers[type1][type2].primary) - { - return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); - } - else - { - return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); - } - } - else - { - return NULL; - } -} - -void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - b2Assert(s_initialized == true); - - if (contact->m_manifold.pointCount > 0) - { - contact->GetFixtureA()->GetBody()->SetAwake(true); - contact->GetFixtureB()->GetBody()->SetAwake(true); - } - - b2Shape::Type typeA = contact->GetFixtureA()->GetType(); - b2Shape::Type typeB = contact->GetFixtureB()->GetType(); - - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - - b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; - destroyFcn(contact, allocator); -} - -b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) -{ - m_flags = e_enabledFlag; - - m_fixtureA = fA; - m_fixtureB = fB; - - m_indexA = indexA; - m_indexB = indexB; - - m_manifold.pointCount = 0; - - m_prev = NULL; - m_next = NULL; - - m_nodeA.contact = NULL; - m_nodeA.prev = NULL; - m_nodeA.next = NULL; - m_nodeA.other = NULL; - - m_nodeB.contact = NULL; - m_nodeB.prev = NULL; - m_nodeB.next = NULL; - m_nodeB.other = NULL; - - m_toiCount = 0; - - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); -} - -// Update the contact manifold and touching status. -// Note: do not assume the fixture AABBs are overlapping or are valid. -void b2Contact::Update(b2ContactListener* listener) -{ - b2Manifold oldManifold = m_manifold; - - // Re-enable this contact. - m_flags |= e_enabledFlag; - - bool touching = false; - bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; - - bool sensorA = m_fixtureA->IsSensor(); - bool sensorB = m_fixtureB->IsSensor(); - bool sensor = sensorA || sensorB; - - b2Body* bodyA = m_fixtureA->GetBody(); - b2Body* bodyB = m_fixtureB->GetBody(); - const b2Transform& xfA = bodyA->GetTransform(); - const b2Transform& xfB = bodyB->GetTransform(); - - // Is this contact a sensor? - if (sensor) - { - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); - - // Sensors don't generate manifolds. - m_manifold.pointCount = 0; - } - else - { - Evaluate(&m_manifold, xfA, xfB); - touching = m_manifold.pointCount > 0; - - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp2 = m_manifold.points + i; - mp2->normalImpulse = 0.0f; - mp2->tangentImpulse = 0.0f; - b2ContactID id2 = mp2->id; - - for (int32 j = 0; j < oldManifold.pointCount; ++j) - { - b2ManifoldPoint* mp1 = oldManifold.points + j; - - if (mp1->id.key == id2.key) - { - mp2->normalImpulse = mp1->normalImpulse; - mp2->tangentImpulse = mp1->tangentImpulse; - break; - } - } - } - - if (touching != wasTouching) - { - bodyA->SetAwake(true); - bodyB->SetAwake(true); - } - } - - if (touching) - { - m_flags |= e_touchingFlag; - } - else - { - m_flags &= ~e_touchingFlag; - } - - if (wasTouching == false && touching == true && listener) - { - listener->BeginContact(this); - } - - if (wasTouching == true && touching == false && listener) - { - listener->EndContact(this); - } - - if (sensor == false && touching && listener) - { - listener->PreSolve(this, &oldManifold); - } -} diff --git a/external/box2d/Dynamics/Contacts/b2Contact.h b/external/box2d/Dynamics/Contacts/b2Contact.h deleted file mode 100644 index 20d9403ce7..0000000000 --- a/external/box2d/Dynamics/Contacts/b2Contact.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_H -#define B2_CONTACT_H - -#include -#include -#include -#include - -class b2Body; -class b2Contact; -class b2Fixture; -class b2World; -class b2BlockAllocator; -class b2StackAllocator; -class b2ContactListener; - -/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. -/// For example, anything slides on ice. -inline float32 b2MixFriction(float32 friction1, float32 friction2) -{ - return std::sqrt(friction1 * friction2); -} - -/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. -/// For example, a superball bounces on anything. -inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) -{ - return restitution1 > restitution2 ? restitution1 : restitution2; -} - -typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, - b2BlockAllocator* allocator); -typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); - -struct b2ContactRegister -{ - b2ContactCreateFcn* createFcn; - b2ContactDestroyFcn* destroyFcn; - bool primary; -}; - -/// A contact edge is used to connect bodies and contacts together -/// in a contact graph where each body is a node and each contact -/// is an edge. A contact edge belongs to a doubly linked list -/// maintained in each attached body. Each contact has two contact -/// nodes, one for each attached body. -struct b2ContactEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Contact* contact; ///< the contact - b2ContactEdge* prev; ///< the previous contact edge in the body's contact list - b2ContactEdge* next; ///< the next contact edge in the body's contact list -}; - -/// The class manages contact between two shapes. A contact exists for each overlapping -/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist -/// that has no contact points. -class b2Contact -{ -public: - - /// Get the contact manifold. Do not modify the manifold unless you understand the - /// internals of Box2D. - b2Manifold* GetManifold(); - const b2Manifold* GetManifold() const; - - /// Get the world manifold. - void GetWorldManifold(b2WorldManifold* worldManifold) const; - - /// Is this contact touching? - bool IsTouching() const; - - /// Enable/disable this contact. This can be used inside the pre-solve - /// contact listener. The contact is only disabled for the current - /// time step (or sub-step in continuous collisions). - void SetEnabled(bool flag); - - /// Has this contact been disabled? - bool IsEnabled() const; - - /// Get the next contact in the world's contact list. - b2Contact* GetNext(); - const b2Contact* GetNext() const; - - /// Get fixture A in this contact. - b2Fixture* GetFixtureA(); - const b2Fixture* GetFixtureA() const; - - /// Get the child primitive index for fixture A. - int32 GetChildIndexA() const; - - /// Get fixture B in this contact. - b2Fixture* GetFixtureB(); - const b2Fixture* GetFixtureB() const; - - /// Get the child primitive index for fixture B. - int32 GetChildIndexB() const; - - /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. - /// This value persists until set or reset. - void SetFriction(float32 friction); - - /// Get the friction. - float32 GetFriction() const; - - /// Reset the friction mixture to the default value. - void ResetFriction(); - - /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. - /// The value persists until you set or reset. - void SetRestitution(float32 restitution); - - /// Get the restitution. - float32 GetRestitution() const; - - /// Reset the restitution to the default value. - void ResetRestitution(); - - /// Evaluate this contact with your own manifold and transforms. - virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; - -protected: - friend class b2ContactManager; - friend class b2World; - friend class b2ContactSolver; - friend class b2Body; - friend class b2Fixture; - - // Flags stored in m_flags - enum - { - // Used when crawling contact graph when forming islands. - e_islandFlag = 0x0001, - - // Set when the shapes are touching. - e_touchingFlag = 0x0002, - - // This contact can be disabled (by user) - e_enabledFlag = 0x0004, - - // This contact needs filtering because a fixture filter was changed. - e_filterFlag = 0x0008, - - // This bullet contact had a TOI event - e_bulletHitFlag = 0x0010, - - // This contact has a valid TOI in m_toi - e_toiFlag = 0x0020 - }; - - /// Flag this contact for filtering. Filtering will occur the next time step. - void FlagForFiltering(); - - static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, - b2Shape::Type typeA, b2Shape::Type typeB); - static void InitializeRegisters(); - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} - b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - virtual ~b2Contact() {} - - void Update(b2ContactListener* listener); - - static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; - static bool s_initialized; - - uint32 m_flags; - - // World pool and list pointers. - b2Contact* m_prev; - b2Contact* m_next; - - // Nodes for connecting bodies. - b2ContactEdge m_nodeA; - b2ContactEdge m_nodeB; - - b2Fixture* m_fixtureA; - b2Fixture* m_fixtureB; - - int32 m_indexA; - int32 m_indexB; - - b2Manifold m_manifold; - - int32 m_toiCount; - float32 m_toi; - - float32 m_friction; - float32 m_restitution; -}; - -inline b2Manifold* b2Contact::GetManifold() -{ - return &m_manifold; -} - -inline const b2Manifold* b2Contact::GetManifold() const -{ - return &m_manifold; -} - -inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const -{ - const b2Body* bodyA = m_fixtureA->GetBody(); - const b2Body* bodyB = m_fixtureB->GetBody(); - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - - worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); -} - -inline void b2Contact::SetEnabled(bool flag) -{ - if (flag) - { - m_flags |= e_enabledFlag; - } - else - { - m_flags &= ~e_enabledFlag; - } -} - -inline bool b2Contact::IsEnabled() const -{ - return (m_flags & e_enabledFlag) == e_enabledFlag; -} - -inline bool b2Contact::IsTouching() const -{ - return (m_flags & e_touchingFlag) == e_touchingFlag; -} - -inline b2Contact* b2Contact::GetNext() -{ - return m_next; -} - -inline const b2Contact* b2Contact::GetNext() const -{ - return m_next; -} - -inline b2Fixture* b2Contact::GetFixtureA() -{ - return m_fixtureA; -} - -inline const b2Fixture* b2Contact::GetFixtureA() const -{ - return m_fixtureA; -} - -inline b2Fixture* b2Contact::GetFixtureB() -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexA() const -{ - return m_indexA; -} - -inline const b2Fixture* b2Contact::GetFixtureB() const -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexB() const -{ - return m_indexB; -} - -inline void b2Contact::FlagForFiltering() -{ - m_flags |= e_filterFlag; -} - -inline void b2Contact::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Contact::GetFriction() const -{ - return m_friction; -} - -inline void b2Contact::ResetFriction() -{ - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); -} - -inline void b2Contact::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline float32 b2Contact::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Contact::ResetRestitution() -{ - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); -} - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp b/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp deleted file mode 100644 index 0dc740342a..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ContactSolver.cpp +++ /dev/null @@ -1,832 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include - -#include -#include -#include -#include -#include - -#define B2_DEBUG_SOLVER 0 - -struct b2ContactPositionConstraint -{ - b2Vec2 localPoints[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - b2Vec2 localCenterA, localCenterB; - float32 invIA, invIB; - b2Manifold::Type type; - float32 radiusA, radiusB; - int32 pointCount; -}; - -b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) -{ - m_step = def->step; - m_allocator = def->allocator; - m_count = def->count; - m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); - m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); - m_positions = def->positions; - m_velocities = def->velocities; - m_contacts = def->contacts; - - // Initialize position independent portions of the constraints. - for (int32 i = 0; i < m_count; ++i) - { - b2Contact* contact = m_contacts[i]; - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - b2Shape* shapeA = fixtureA->GetShape(); - b2Shape* shapeB = fixtureB->GetShape(); - float32 radiusA = shapeA->m_radius; - float32 radiusB = shapeB->m_radius; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - b2Manifold* manifold = contact->GetManifold(); - - int32 pointCount = manifold->pointCount; - b2Assert(pointCount > 0); - - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - vc->friction = contact->m_friction; - vc->restitution = contact->m_restitution; - vc->indexA = bodyA->m_islandIndex; - vc->indexB = bodyB->m_islandIndex; - vc->invMassA = bodyA->m_invMass; - vc->invMassB = bodyB->m_invMass; - vc->invIA = bodyA->m_invI; - vc->invIB = bodyB->m_invI; - vc->contactIndex = i; - vc->pointCount = pointCount; - vc->K.SetZero(); - vc->normalMass.SetZero(); - - b2ContactPositionConstraint* pc = m_positionConstraints + i; - pc->indexA = bodyA->m_islandIndex; - pc->indexB = bodyB->m_islandIndex; - pc->invMassA = bodyA->m_invMass; - pc->invMassB = bodyB->m_invMass; - pc->localCenterA = bodyA->m_sweep.localCenter; - pc->localCenterB = bodyB->m_sweep.localCenter; - pc->invIA = bodyA->m_invI; - pc->invIB = bodyB->m_invI; - pc->localNormal = manifold->localNormal; - pc->localPoint = manifold->localPoint; - pc->pointCount = pointCount; - pc->radiusA = radiusA; - pc->radiusB = radiusB; - pc->type = manifold->type; - - for (int32 j = 0; j < pointCount; ++j) - { - b2ManifoldPoint* cp = manifold->points + j; - b2VelocityConstraintPoint* vcp = vc->points + j; - - if (m_step.warmStarting) - { - vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; - vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; - } - else - { - vcp->normalImpulse = 0.0f; - vcp->tangentImpulse = 0.0f; - } - - vcp->rA.SetZero(); - vcp->rB.SetZero(); - vcp->normalMass = 0.0f; - vcp->tangentMass = 0.0f; - vcp->velocityBias = 0.0f; - - pc->localPoints[j] = cp->localPoint; - } - } -} - -b2ContactSolver::~b2ContactSolver() -{ - m_allocator->Free(m_velocityConstraints); - m_allocator->Free(m_positionConstraints); -} - -// Initialize position dependent portions of the velocity constraints. -void b2ContactSolver::InitializeVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - float32 radiusA = pc->radiusA; - float32 radiusB = pc->radiusB; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - - float32 mA = vc->invMassA; - float32 mB = vc->invMassB; - float32 iA = vc->invIA; - float32 iB = vc->invIB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Assert(manifold->pointCount > 0); - - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2WorldManifold worldManifold; - worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); - - vc->normal = worldManifold.normal; - - int32 pointCount = vc->pointCount; - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - vcp->rA = worldManifold.points[j] - cA; - vcp->rB = worldManifold.points[j] - cB; - - float32 rnA = b2Cross(vcp->rA, vc->normal); - float32 rnB = b2Cross(vcp->rB, vc->normal); - - float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - - b2Vec2 tangent = b2Cross(vc->normal, 1.0f); - - float32 rtA = b2Cross(vcp->rA, tangent); - float32 rtB = b2Cross(vcp->rB, tangent); - - float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - - vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; - - // Setup a velocity bias for restitution. - vcp->velocityBias = 0.0f; - float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); - if (vRel < -b2_velocityThreshold) - { - vcp->velocityBias = -vc->restitution * vRel; - } - } - - // If we have two points, then prepare the block solver. - if (vc->pointCount == 2) - { - b2VelocityConstraintPoint* vcp1 = vc->points + 0; - b2VelocityConstraintPoint* vcp2 = vc->points + 1; - - float32 rn1A = b2Cross(vcp1->rA, vc->normal); - float32 rn1B = b2Cross(vcp1->rB, vc->normal); - float32 rn2A = b2Cross(vcp2->rA, vc->normal); - float32 rn2B = b2Cross(vcp2->rB, vc->normal); - - float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; - float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; - float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; - - // Ensure a reasonable condition number. - const float32 k_maxConditionNumber = 1000.0f; - if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) - { - // K is safe to invert. - vc->K.ex.Set(k11, k12); - vc->K.ey.Set(k12, k22); - vc->normalMass = vc->K.GetInverse(); - } - else - { - // The constraints are redundant, just use one. - // TODO_ERIN use deepest? - vc->pointCount = 1; - } - } - } -} - -void b2ContactSolver::WarmStart() -{ - // Warm start. - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; - wA -= iA * b2Cross(vcp->rA, P); - vA -= mA * P; - wB += iB * b2Cross(vcp->rB, P); - vB += mB * P; - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::SolveVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = vc->friction; - - b2Assert(pointCount == 1 || pointCount == 2); - - // Solve tangent constraints first because non-penetration is more important - // than friction. - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute tangent force - float32 vt = b2Dot(dv, tangent); - float32 lambda = vcp->tangentMass * (-vt); - - // b2Clamp the accumulated force - float32 maxFriction = friction * vcp->normalImpulse; - float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - vcp->tangentImpulse; - vcp->tangentImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * tangent; - - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - - // Solve normal constraints - if (vc->pointCount == 1) - { - b2VelocityConstraintPoint* vcp = vc->points + 0; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute normal impulse - float32 vn = b2Dot(dv, normal); - float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); - - // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - vcp->normalImpulse; - vcp->normalImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * normal; - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - else - { - // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). - // Build the mini LCP for this contact patch - // - // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 - // - // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) - // b = vn0 - velocityBias - // - // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i - // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases - // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid - // solution that satisfies the problem is chosen. - // - // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires - // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). - // - // Substitute: - // - // x = a + d - // - // a := old total impulse - // x := new total impulse - // d := incremental impulse - // - // For the current iteration we extend the formula for the incremental impulse - // to compute the new total impulse: - // - // vn = A * d + b - // = A * (x - a) + b - // = A * x + b - A * a - // = A * x + b' - // b' = b - A * a; - - b2VelocityConstraintPoint* cp1 = vc->points + 0; - b2VelocityConstraintPoint* cp2 = vc->points + 1; - - b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); - b2Assert(a.x >= 0.0f && a.y >= 0.0f); - - // Relative velocity at contact - b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - float32 vn1 = b2Dot(dv1, normal); - float32 vn2 = b2Dot(dv2, normal); - - b2Vec2 b; - b.x = vn1 - cp1->velocityBias; - b.y = vn2 - cp2->velocityBias; - - // Compute b' - b -= b2Mul(vc->K, a); - - const float32 k_errorTol = 1e-3f; - B2_NOT_USED(k_errorTol); - - for (;;) - { - // - // Case 1: vn = 0 - // - // 0 = A * x + b' - // - // Solve for x: - // - // x = - inv(A) * b' - // - b2Vec2 x = - b2Mul(vc->normalMass, b); - - if (x.x >= 0.0f && x.y >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 2: vn1 = 0 and x2 = 0 - // - // 0 = a11 * x1 + a12 * 0 + b1' - // vn2 = a21 * x1 + a22 * 0 + b2' - // - x.x = - cp1->normalMass * b.x; - x.y = 0.0f; - vn1 = 0.0f; - vn2 = vc->K.ex.y * x.x + b.y; - - if (x.x >= 0.0f && vn2 >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); -#endif - break; - } - - - // - // Case 3: vn2 = 0 and x1 = 0 - // - // vn1 = a11 * 0 + a12 * x2 + b1' - // 0 = a21 * 0 + a22 * x2 + b2' - // - x.x = 0.0f; - x.y = - cp2->normalMass * b.y; - vn1 = vc->K.ey.x * x.y + b.x; - vn2 = 0.0f; - - if (x.y >= 0.0f && vn1 >= 0.0f) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 4: x1 = 0 and x2 = 0 - // - // vn1 = b1 - // vn2 = b2; - x.x = 0.0f; - x.y = 0.0f; - vn1 = b.x; - vn2 = b.y; - - if (vn1 >= 0.0f && vn2 >= 0.0f ) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - - break; - } - - // No solution, give up. This is hit sometimes, but it doesn't seem to matter. - break; - } - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::StoreImpulses() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - for (int32 j = 0; j < vc->pointCount; ++j) - { - manifold->points[j].normalImpulse = vc->points[j].normalImpulse; - manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; - } - } -} - -struct b2PositionSolverManifold -{ - void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) - { - b2Assert(pc->pointCount > 0); - - switch (pc->type) - { - case b2Manifold::e_circles: - { - b2Vec2 pointA = b2Mul(xfA, pc->localPoint); - b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); - normal = pointB - pointA; - normal.Normalize(); - point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - - // Ensure normal points from A to B - normal = -normal; - } - break; - } - } - - b2Vec2 normal; - b2Vec2 point; - float32 separation; -}; - -// Sequential solver. -bool b2ContactSolver::SolvePositionConstraints() -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - float32 mA = pc->invMassA; - float32 iA = pc->invIA; - b2Vec2 localCenterB = pc->localCenterB; - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - int32 pointCount = pc->pointCount; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -3.0f * b2_linearSlop; -} - -// Sequential position solver for position constraints. -bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - int32 pointCount = pc->pointCount; - - float32 mA = 0.0f; - float32 iA = 0.0f; - if (indexA == toiIndexA || indexA == toiIndexB) - { - mA = pc->invMassA; - iA = pc->invIA; - } - - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - if (indexB == toiIndexA || indexB == toiIndexB) - { - mB = pc->invMassB; - iB = pc->invIB; - } - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; -} diff --git a/external/box2d/Dynamics/Contacts/b2ContactSolver.h b/external/box2d/Dynamics/Contacts/b2ContactSolver.h deleted file mode 100644 index aef1987a9e..0000000000 --- a/external/box2d/Dynamics/Contacts/b2ContactSolver.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_SOLVER_H -#define B2_CONTACT_SOLVER_H - -#include -#include -#include - -class b2Contact; -class b2Body; -class b2StackAllocator; -struct b2ContactPositionConstraint; - -struct b2VelocityConstraintPoint -{ - b2Vec2 rA; - b2Vec2 rB; - float32 normalImpulse; - float32 tangentImpulse; - float32 normalMass; - float32 tangentMass; - float32 velocityBias; -}; - -struct b2ContactVelocityConstraint -{ - b2VelocityConstraintPoint points[b2_maxManifoldPoints]; - b2Vec2 normal; - b2Mat22 normalMass; - b2Mat22 K; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - float32 invIA, invIB; - float32 friction; - float32 restitution; - int32 pointCount; - int32 contactIndex; -}; - -struct b2ContactSolverDef -{ - b2TimeStep step; - b2Contact** contacts; - int32 count; - b2Position* positions; - b2Velocity* velocities; - b2StackAllocator* allocator; -}; - -class b2ContactSolver -{ -public: - b2ContactSolver(b2ContactSolverDef* def); - ~b2ContactSolver(); - - void InitializeVelocityConstraints(); - - void WarmStart(); - void SolveVelocityConstraints(); - void StoreImpulses(); - - bool SolvePositionConstraints(); - bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); - - b2TimeStep m_step; - b2Position* m_positions; - b2Velocity* m_velocities; - b2StackAllocator* m_allocator; - b2ContactPositionConstraint* m_positionConstraints; - b2ContactVelocityConstraint* m_velocityConstraints; - b2Contact** m_contacts; - int m_count; -}; - -#endif - diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp deleted file mode 100644 index aade42880a..0000000000 --- a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); - return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); -} - -void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); - allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); -} - -b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndCircle( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h deleted file mode 100644 index 70771ec536..0000000000 --- a/external/box2d/Dynamics/Contacts/b2EdgeAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H -#define B2_EDGE_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2EdgeAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp deleted file mode 100644 index 04ce394107..0000000000 --- a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); - return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); -} - -void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); - allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); -} - -b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndPolygon( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h deleted file mode 100644 index f65f3acca9..0000000000 --- a/external/box2d/Dynamics/Contacts/b2EdgeAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_EDGE_AND_POLYGON_CONTACT_H -#define B2_EDGE_AND_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2EdgeAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp deleted file mode 100644 index 961b26f38a..0000000000 --- a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); - return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); -} - -void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); - allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); -} - -b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygonAndCircle( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h b/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h deleted file mode 100644 index 7b1a5288b4..0000000000 --- a/external/box2d/Dynamics/Contacts/b2PolygonAndCircleContact.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H -#define B2_POLYGON_AND_CIRCLE_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2PolygonAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp b/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp deleted file mode 100644 index a2884a440d..0000000000 --- a/external/box2d/Dynamics/Contacts/b2PolygonContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include - -#include -using namespace std; - -b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonContact)); - return new (mem) b2PolygonContact(fixtureA, fixtureB); -} - -void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonContact*)contact)->~b2PolygonContact(); - allocator->Free(contact, sizeof(b2PolygonContact)); -} - -b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygons( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/external/box2d/Dynamics/Contacts/b2PolygonContact.h b/external/box2d/Dynamics/Contacts/b2PolygonContact.h deleted file mode 100644 index 302684232a..0000000000 --- a/external/box2d/Dynamics/Contacts/b2PolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_POLYGON_CONTACT_H -#define B2_POLYGON_CONTACT_H - -#include - -class b2BlockAllocator; - -class b2PolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp b/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp deleted file mode 100644 index b2d4bd006c..0000000000 --- a/external/box2d/Dynamics/Joints/b2DistanceJoint.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// 1-D constrained system -// m (v2 - v1) = lambda -// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. -// x2 = x1 + h * v2 - -// 1-D mass-damper-spring system -// m (v2 - v1) + h * d * v2 + h * k * - -// C = norm(p2 - p1) - L -// u = (p2 - p1) / norm(p2 - p1) -// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// J = [-u -cross(r1, u) u cross(r2, u)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 - -void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, - const b2Vec2& anchor1, const b2Vec2& anchor2) -{ - bodyA = b1; - bodyB = b2; - localAnchorA = bodyA->GetLocalPoint(anchor1); - localAnchorB = bodyB->GetLocalPoint(anchor2); - b2Vec2 d = anchor2 - anchor1; - length = d.Length(); -} - -b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_length = def->length; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - m_impulse = 0.0f; - m_gamma = 0.0f; - m_bias = 0.0f; -} - -void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - // Handle singularity. - float32 length = m_u.Length(); - if (length > b2_linearSlop) - { - m_u *= 1.0f / length; - } - else - { - m_u.Set(0.0f, 0.0f); - } - - float32 crAu = b2Cross(m_rA, m_u); - float32 crBu = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; - - // Compute the effective mass matrix. - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (m_frequencyHz > 0.0f) - { - float32 C = length - m_length; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m_mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_mass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invMass += m_gamma; - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - } - else - { - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 Cdot = b2Dot(m_u, vpB - vpA); - - float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); - m_impulse += impulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) -{ - if (m_frequencyHz > 0.0f) - { - // There is no position correction for soft distance constraints. - return true; - } - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_length; - C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) < b2_linearSlop; -} - -b2Vec2 b2DistanceJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2DistanceJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -void b2DistanceJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2DistanceJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.length = %.15lef;\n", m_length); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2DistanceJoint.h b/external/box2d/Dynamics/Joints/b2DistanceJoint.h deleted file mode 100644 index fc11476ff9..0000000000 --- a/external/box2d/Dynamics/Joints/b2DistanceJoint.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_DISTANCE_JOINT_H -#define B2_DISTANCE_JOINT_H - -#include - -/// Distance joint definition. This requires defining an -/// anchor point on both bodies and the non-zero length of the -/// distance joint. The definition uses local anchor points -/// so that the initial configuration can violate the constraint -/// slightly. This helps when saving and loading a game. -/// @warning Do not use a zero or short length. -struct b2DistanceJointDef : public b2JointDef -{ - b2DistanceJointDef() - { - type = e_distanceJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - length = 1.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and length using the world - /// anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& anchorA, const b2Vec2& anchorB); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The natural length between the anchor points. - float32 length; - - /// The mass-spring-damper frequency in Hertz. A value of 0 - /// disables softness. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A distance joint constrains two points on two bodies -/// to remain at a fixed distance from each other. You can view -/// this as a massless, rigid rod. -class b2DistanceJoint : public b2Joint -{ -public: - - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Get the reaction torque given the inverse time step. - /// Unit is N*m. This is always zero for a distance joint. - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/get the natural length. - /// Manipulating the length can lead to non-physical behavior when the frequency is zero. - void SetLength(float32 length); - float32 GetLength() const; - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2DistanceJoint(const b2DistanceJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_gamma; - float32 m_impulse; - float32 m_length; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -inline void b2DistanceJoint::SetLength(float32 length) -{ - m_length = length; -} - -inline float32 b2DistanceJoint::GetLength() const -{ - return m_length; -} - -inline void b2DistanceJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2DistanceJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -inline void b2DistanceJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2DistanceJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp b/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp deleted file mode 100644 index 6e6018db10..0000000000 --- a/external/box2d/Dynamics/Joints/b2FrictionJoint.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); -} - -b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - - m_maxForce = def->maxForce; - m_maxTorque = def->maxTorque; -} - -void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective mass matrix. - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; - K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - - m_linearMass = K.GetInverse(); - - m_angularMass = iA + iB; - if (m_angularMass > 0.0f) - { - m_angularMass = 1.0f / m_angularMass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_linearImpulse *= data.step.dtRatio; - m_angularImpulse *= data.step.dtRatio; - - b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); - } - else - { - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - float32 h = data.step.dt; - - // Solve angular friction - { - float32 Cdot = wB - wA; - float32 impulse = -m_angularMass * Cdot; - - float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = h * m_maxTorque; - m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_angularImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve linear friction - { - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); - b2Vec2 oldImpulse = m_linearImpulse; - m_linearImpulse += impulse; - - float32 maxImpulse = h * m_maxForce; - - if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_linearImpulse.Normalize(); - m_linearImpulse *= maxImpulse; - } - - impulse = m_linearImpulse - oldImpulse; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - - return true; -} - -b2Vec2 b2FrictionJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2FrictionJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_linearImpulse; -} - -float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_angularImpulse; -} - -void b2FrictionJoint::SetMaxForce(float32 force) -{ - b2Assert(b2IsValid(force) && force >= 0.0f); - m_maxForce = force; -} - -float32 b2FrictionJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2FrictionJoint::SetMaxTorque(float32 torque) -{ - b2Assert(b2IsValid(torque) && torque >= 0.0f); - m_maxTorque = torque; -} - -float32 b2FrictionJoint::GetMaxTorque() const -{ - return m_maxTorque; -} - -void b2FrictionJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2FrictionJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); - b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2FrictionJoint.h b/external/box2d/Dynamics/Joints/b2FrictionJoint.h deleted file mode 100644 index 3ee40c6298..0000000000 --- a/external/box2d/Dynamics/Joints/b2FrictionJoint.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_FRICTION_JOINT_H -#define B2_FRICTION_JOINT_H - -#include - -/// Friction joint definition. -struct b2FrictionJointDef : public b2JointDef -{ - b2FrictionJointDef() - { - type = e_frictionJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - maxForce = 0.0f; - maxTorque = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum friction force in N. - float32 maxForce; - - /// The maximum friction torque in N-m. - float32 maxTorque; -}; - -/// Friction joint. This is used for top-down friction. -/// It provides 2D translational friction and angular friction. -class b2FrictionJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set the maximum friction force in N. - void SetMaxForce(float32 force); - - /// Get the maximum friction force in N. - float32 GetMaxForce() const; - - /// Set the maximum friction torque in N*m. - void SetMaxTorque(float32 torque); - - /// Get the maximum friction torque in N*m. - float32 GetMaxTorque() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - - b2FrictionJoint(const b2FrictionJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - - // Solver shared - b2Vec2 m_linearImpulse; - float32 m_angularImpulse; - float32 m_maxForce; - float32 m_maxTorque; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat22 m_linearMass; - float32 m_angularMass; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2GearJoint.cpp b/external/box2d/Dynamics/Joints/b2GearJoint.cpp deleted file mode 100644 index 9741cdd5a4..0000000000 --- a/external/box2d/Dynamics/Joints/b2GearJoint.cpp +++ /dev/null @@ -1,423 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -// Gear Joint: -// C0 = (coordinate1 + ratio * coordinate2)_initial -// C = (coordinate1 + ratio * coordinate2) - C0 = 0 -// J = [J1 ratio * J2] -// K = J * invM * JT -// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T -// -// Revolute: -// coordinate = rotation -// Cdot = angularVelocity -// J = [0 0 1] -// K = J * invM * JT = invI -// -// Prismatic: -// coordinate = dot(p - pg, ug) -// Cdot = dot(v + cross(w, r), ug) -// J = [ug cross(r, ug)] -// K = J * invM * JT = invMass + invI * cross(r, ug)^2 - -b2GearJoint::b2GearJoint(const b2GearJointDef* def) -: b2Joint(def) -{ - m_joint1 = def->joint1; - m_joint2 = def->joint2; - - m_typeA = m_joint1->GetType(); - m_typeB = m_joint2->GetType(); - - b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); - b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); - - float32 coordinateA, coordinateB; - - // TODO_ERIN there might be some problem with the joint edges in b2Joint. - - m_bodyC = m_joint1->GetBodyA(); - m_bodyA = m_joint1->GetBodyB(); - - // Get geometry of joint1 - b2Transform xfA = m_bodyA->m_xf; - float32 aA = m_bodyA->m_sweep.a; - b2Transform xfC = m_bodyC->m_xf; - float32 aC = m_bodyC->m_sweep.a; - - if (m_typeA == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; - m_localAnchorC = revolute->m_localAnchorA; - m_localAnchorA = revolute->m_localAnchorB; - m_referenceAngleA = revolute->m_referenceAngle; - m_localAxisC.SetZero(); - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; - m_localAnchorC = prismatic->m_localAnchorA; - m_localAnchorA = prismatic->m_localAnchorB; - m_referenceAngleA = prismatic->m_referenceAngle; - m_localAxisC = prismatic->m_localXAxisA; - - b2Vec2 pC = m_localAnchorC; - b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - m_bodyD = m_joint2->GetBodyA(); - m_bodyB = m_joint2->GetBodyB(); - - // Get geometry of joint2 - b2Transform xfB = m_bodyB->m_xf; - float32 aB = m_bodyB->m_sweep.a; - b2Transform xfD = m_bodyD->m_xf; - float32 aD = m_bodyD->m_sweep.a; - - if (m_typeB == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; - m_localAnchorD = revolute->m_localAnchorA; - m_localAnchorB = revolute->m_localAnchorB; - m_referenceAngleB = revolute->m_referenceAngle; - m_localAxisD.SetZero(); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; - m_localAnchorD = prismatic->m_localAnchorA; - m_localAnchorB = prismatic->m_localAnchorB; - m_referenceAngleB = prismatic->m_referenceAngle; - m_localAxisD = prismatic->m_localXAxisA; - - b2Vec2 pD = m_localAnchorD; - b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - m_ratio = def->ratio; - - m_constant = coordinateA + m_ratio * coordinateB; - - m_impulse = 0.0f; -} - -void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_indexC = m_bodyC->m_islandIndex; - m_indexD = m_bodyD->m_islandIndex; - m_lcA = m_bodyA->m_sweep.localCenter; - m_lcB = m_bodyB->m_sweep.localCenter; - m_lcC = m_bodyC->m_sweep.localCenter; - m_lcD = m_bodyD->m_sweep.localCenter; - m_mA = m_bodyA->m_invMass; - m_mB = m_bodyB->m_invMass; - m_mC = m_bodyC->m_invMass; - m_mD = m_bodyD->m_invMass; - m_iA = m_bodyA->m_invI; - m_iB = m_bodyB->m_invI; - m_iC = m_bodyC->m_invI; - m_iD = m_bodyD->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - m_mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - m_JvAC.SetZero(); - m_JwA = 1.0f; - m_JwC = 1.0f; - m_mass += m_iA + m_iC; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - m_JvAC = u; - m_JwC = b2Cross(rC, u); - m_JwA = b2Cross(rA, u); - m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; - } - - if (m_typeB == e_revoluteJoint) - { - m_JvBD.SetZero(); - m_JwB = m_ratio; - m_JwD = m_ratio; - m_mass += m_ratio * m_ratio * (m_iB + m_iD); - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - m_JvBD = m_ratio * u; - m_JwD = m_ratio * b2Cross(rD, u); - m_JwB = m_ratio * b2Cross(rB, u); - m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; - } - - // Compute effective mass. - m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; - - if (data.step.warmStarting) - { - vA += (m_mA * m_impulse) * m_JvAC; - wA += m_iA * m_impulse * m_JwA; - vB += (m_mB * m_impulse) * m_JvBD; - wB += m_iB * m_impulse * m_JwB; - vC -= (m_mC * m_impulse) * m_JvAC; - wC -= m_iC * m_impulse * m_JwC; - vD -= (m_mD * m_impulse) * m_JvBD; - wD -= m_iD * m_impulse * m_JwD; - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); - Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); - - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - vA += (m_mA * impulse) * m_JvAC; - wA += m_iA * impulse * m_JwA; - vB += (m_mB * impulse) * m_JvBD; - wB += m_iB * impulse * m_JwB; - vC -= (m_mC * impulse) * m_JvAC; - wC -= m_iC * impulse * m_JwC; - vD -= (m_mD * impulse) * m_JvBD; - wD -= m_iD * impulse * m_JwD; - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - float32 linearError = 0.0f; - - float32 coordinateA, coordinateB; - - b2Vec2 JvAC, JvBD; - float32 JwA, JwB, JwC, JwD; - float32 mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - JvAC.SetZero(); - JwA = 1.0f; - JwC = 1.0f; - mass += m_iA + m_iC; - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - JvAC = u; - JwC = b2Cross(rC, u); - JwA = b2Cross(rA, u); - mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; - - b2Vec2 pC = m_localAnchorC - m_lcC; - b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - if (m_typeB == e_revoluteJoint) - { - JvBD.SetZero(); - JwB = m_ratio; - JwD = m_ratio; - mass += m_ratio * m_ratio * (m_iB + m_iD); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - JvBD = m_ratio * u; - JwD = m_ratio * b2Cross(rD, u); - JwB = m_ratio * b2Cross(rB, u); - mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; - - b2Vec2 pD = m_localAnchorD - m_lcD; - b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; - - float32 impulse = 0.0f; - if (mass > 0.0f) - { - impulse = -C / mass; - } - - cA += m_mA * impulse * JvAC; - aA += m_iA * impulse * JwA; - cB += m_mB * impulse * JvBD; - aB += m_iB * impulse * JwB; - cC -= m_mC * impulse * JvAC; - aC -= m_iC * impulse * JwC; - cD -= m_mD * impulse * JvBD; - aD -= m_iD * impulse * JwD; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - data.positions[m_indexC].c = cC; - data.positions[m_indexC].a = aC; - data.positions[m_indexD].c = cD; - data.positions[m_indexD].a = aD; - - // TODO_ERIN not implemented - return linearError < b2_linearSlop; -} - -b2Vec2 b2GearJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2GearJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_JvAC; - return inv_dt * P; -} - -float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const -{ - float32 L = m_impulse * m_JwA; - return inv_dt * L; -} - -void b2GearJoint::SetRatio(float32 ratio) -{ - b2Assert(b2IsValid(ratio)); - m_ratio = ratio; -} - -float32 b2GearJoint::GetRatio() const -{ - return m_ratio; -} - -void b2GearJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - int32 index1 = m_joint1->m_index; - int32 index2 = m_joint2->m_index; - - b2Log(" b2GearJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.joint1 = joints[%d];\n", index1); - b2Log(" jd.joint2 = joints[%d];\n", index2); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2GearJoint.h b/external/box2d/Dynamics/Joints/b2GearJoint.h deleted file mode 100644 index f926bf6ef1..0000000000 --- a/external/box2d/Dynamics/Joints/b2GearJoint.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_GEAR_JOINT_H -#define B2_GEAR_JOINT_H - -#include - -/// Gear joint definition. This definition requires two existing -/// revolute or prismatic joints (any combination will work). -struct b2GearJointDef : public b2JointDef -{ - b2GearJointDef() - { - type = e_gearJoint; - joint1 = NULL; - joint2 = NULL; - ratio = 1.0f; - } - - /// The first revolute/prismatic joint attached to the gear joint. - b2Joint* joint1; - - /// The second revolute/prismatic joint attached to the gear joint. - b2Joint* joint2; - - /// The gear ratio. - /// @see b2GearJoint for explanation. - float32 ratio; -}; - -/// A gear joint is used to connect two joints together. Either joint -/// can be a revolute or prismatic joint. You specify a gear ratio -/// to bind the motions together: -/// coordinate1 + ratio * coordinate2 = constant -/// The ratio can be negative or positive. If one joint is a revolute joint -/// and the other joint is a prismatic joint, then the ratio will have units -/// of length or units of 1/length. -/// @warning You have to manually destroy the gear joint if joint1 or joint2 -/// is destroyed. -class b2GearJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the first joint. - b2Joint* GetJoint1() { return m_joint1; } - - /// Get the second joint. - b2Joint* GetJoint2() { return m_joint2; } - - /// Set/Get the gear ratio. - void SetRatio(float32 ratio); - float32 GetRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2GearJoint(const b2GearJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Joint* m_joint1; - b2Joint* m_joint2; - - b2JointType m_typeA; - b2JointType m_typeB; - - // Body A is connected to body C - // Body B is connected to body D - b2Body* m_bodyC; - b2Body* m_bodyD; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localAnchorC; - b2Vec2 m_localAnchorD; - - b2Vec2 m_localAxisC; - b2Vec2 m_localAxisD; - - float32 m_referenceAngleA; - float32 m_referenceAngleB; - - float32 m_constant; - float32 m_ratio; - - float32 m_impulse; - - // Solver temp - int32 m_indexA, m_indexB, m_indexC, m_indexD; - b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; - float32 m_mA, m_mB, m_mC, m_mD; - float32 m_iA, m_iB, m_iC, m_iD; - b2Vec2 m_JvAC, m_JvBD; - float32 m_JwA, m_JwB, m_JwC, m_JwD; - float32 m_mass; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2Joint.cpp b/external/box2d/Dynamics/Joints/b2Joint.cpp deleted file mode 100644 index 6853b09f0b..0000000000 --- a/external/box2d/Dynamics/Joints/b2Joint.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) -{ - b2Joint* joint = NULL; - - switch (def->type) - { - case e_distanceJoint: - { - void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); - joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def); - } - break; - - case e_mouseJoint: - { - void* mem = allocator->Allocate(sizeof(b2MouseJoint)); - joint = new (mem) b2MouseJoint((b2MouseJointDef*)def); - } - break; - - case e_prismaticJoint: - { - void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); - joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def); - } - break; - - case e_revoluteJoint: - { - void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); - joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def); - } - break; - - case e_pulleyJoint: - { - void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); - joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def); - } - break; - - case e_gearJoint: - { - void* mem = allocator->Allocate(sizeof(b2GearJoint)); - joint = new (mem) b2GearJoint((b2GearJointDef*)def); - } - break; - - case e_wheelJoint: - { - void* mem = allocator->Allocate(sizeof(b2WheelJoint)); - joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); - } - break; - - case e_weldJoint: - { - void* mem = allocator->Allocate(sizeof(b2WeldJoint)); - joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); - } - break; - - case e_frictionJoint: - { - void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); - joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); - } - break; - - case e_ropeJoint: - { - void* mem = allocator->Allocate(sizeof(b2RopeJoint)); - joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); - } - break; - - default: - b2Assert(false); - break; - } - - return joint; -} - -void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) -{ - joint->~b2Joint(); - switch (joint->m_type) - { - case e_distanceJoint: - allocator->Free(joint, sizeof(b2DistanceJoint)); - break; - - case e_mouseJoint: - allocator->Free(joint, sizeof(b2MouseJoint)); - break; - - case e_prismaticJoint: - allocator->Free(joint, sizeof(b2PrismaticJoint)); - break; - - case e_revoluteJoint: - allocator->Free(joint, sizeof(b2RevoluteJoint)); - break; - - case e_pulleyJoint: - allocator->Free(joint, sizeof(b2PulleyJoint)); - break; - - case e_gearJoint: - allocator->Free(joint, sizeof(b2GearJoint)); - break; - - case e_wheelJoint: - allocator->Free(joint, sizeof(b2WheelJoint)); - break; - - case e_weldJoint: - allocator->Free(joint, sizeof(b2WeldJoint)); - break; - - case e_frictionJoint: - allocator->Free(joint, sizeof(b2FrictionJoint)); - break; - - case e_ropeJoint: - allocator->Free(joint, sizeof(b2RopeJoint)); - break; - - default: - b2Assert(false); - break; - } -} - -b2Joint::b2Joint(const b2JointDef* def) -{ - b2Assert(def->bodyA != def->bodyB); - - m_type = def->type; - m_prev = NULL; - m_next = NULL; - m_bodyA = def->bodyA; - m_bodyB = def->bodyB; - m_index = 0; - m_collideConnected = def->collideConnected; - m_islandFlag = false; - m_userData = def->userData; - - m_edgeA.joint = NULL; - m_edgeA.other = NULL; - m_edgeA.prev = NULL; - m_edgeA.next = NULL; - - m_edgeB.joint = NULL; - m_edgeB.other = NULL; - m_edgeB.prev = NULL; - m_edgeB.next = NULL; -} - -bool b2Joint::IsActive() const -{ - return m_bodyA->IsActive() && m_bodyB->IsActive(); -} diff --git a/external/box2d/Dynamics/Joints/b2Joint.h b/external/box2d/Dynamics/Joints/b2Joint.h deleted file mode 100644 index b4ea576665..0000000000 --- a/external/box2d/Dynamics/Joints/b2Joint.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_JOINT_H -#define B2_JOINT_H - -#include - -class b2Body; -class b2Joint; -struct b2SolverData; -class b2BlockAllocator; - -enum b2JointType -{ - e_unknownJoint, - e_revoluteJoint, - e_prismaticJoint, - e_distanceJoint, - e_pulleyJoint, - e_mouseJoint, - e_gearJoint, - e_wheelJoint, - e_weldJoint, - e_frictionJoint, - e_ropeJoint -}; - -enum b2LimitState -{ - e_inactiveLimit, - e_atLowerLimit, - e_atUpperLimit, - e_equalLimits -}; - -struct b2Jacobian -{ - b2Vec2 linear; - float32 angularA; - float32 angularB; -}; - -/// A joint edge is used to connect bodies and joints together -/// in a joint graph where each body is a node and each joint -/// is an edge. A joint edge belongs to a doubly linked list -/// maintained in each attached body. Each joint has two joint -/// nodes, one for each attached body. -struct b2JointEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Joint* joint; ///< the joint - b2JointEdge* prev; ///< the previous joint edge in the body's joint list - b2JointEdge* next; ///< the next joint edge in the body's joint list -}; - -/// Joint definitions are used to construct joints. -struct b2JointDef -{ - b2JointDef() - { - type = e_unknownJoint; - userData = NULL; - bodyA = NULL; - bodyB = NULL; - collideConnected = false; - } - - /// The joint type is set automatically for concrete joint types. - b2JointType type; - - /// Use this to attach application specific data to your joints. - void* userData; - - /// The first attached body. - b2Body* bodyA; - - /// The second attached body. - b2Body* bodyB; - - /// Set this flag to true if the attached bodies should collide. - bool collideConnected; -}; - -/// The base joint class. Joints are used to constraint two bodies together in -/// various fashions. Some joints also feature limits and motors. -class b2Joint -{ -public: - - /// Get the type of the concrete joint. - b2JointType GetType() const; - - /// Get the first body attached to this joint. - b2Body* GetBodyA(); - - /// Get the second body attached to this joint. - b2Body* GetBodyB(); - - /// Get the anchor point on bodyA in world coordinates. - virtual b2Vec2 GetAnchorA() const = 0; - - /// Get the anchor point on bodyB in world coordinates. - virtual b2Vec2 GetAnchorB() const = 0; - - /// Get the reaction force on bodyB at the joint anchor in Newtons. - virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - - /// Get the reaction torque on bodyB in N*m. - virtual float32 GetReactionTorque(float32 inv_dt) const = 0; - - /// Get the next joint the world joint list. - b2Joint* GetNext(); - const b2Joint* GetNext() const; - - /// Get the user data pointer. - void* GetUserData() const; - - /// Set the user data pointer. - void SetUserData(void* data); - - /// Short-cut function to determine if either body is inactive. - bool IsActive() const; - - /// Get collide connected. - /// Note: modifying the collide connect flag won't work correctly because - /// the flag is only checked when fixture AABBs begin to overlap. - bool GetCollideConnected() const; - - /// Dump this joint to the log file. - virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } - -protected: - friend class b2World; - friend class b2Body; - friend class b2Island; - friend class b2GearJoint; - - static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); - static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); - - b2Joint(const b2JointDef* def); - virtual ~b2Joint() {} - - virtual void InitVelocityConstraints(const b2SolverData& data) = 0; - virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; - - // This returns true if the position errors are within tolerance. - virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; - - b2JointType m_type; - b2Joint* m_prev; - b2Joint* m_next; - b2JointEdge m_edgeA; - b2JointEdge m_edgeB; - b2Body* m_bodyA; - b2Body* m_bodyB; - - int32 m_index; - - bool m_islandFlag; - bool m_collideConnected; - - void* m_userData; -}; - -inline b2JointType b2Joint::GetType() const -{ - return m_type; -} - -inline b2Body* b2Joint::GetBodyA() -{ - return m_bodyA; -} - -inline b2Body* b2Joint::GetBodyB() -{ - return m_bodyB; -} - -inline b2Joint* b2Joint::GetNext() -{ - return m_next; -} - -inline const b2Joint* b2Joint::GetNext() const -{ - return m_next; -} - -inline void* b2Joint::GetUserData() const -{ - return m_userData; -} - -inline void b2Joint::SetUserData(void* data) -{ - m_userData = data; -} - -inline bool b2Joint::GetCollideConnected() const -{ - return m_collideConnected; -} - -#endif diff --git a/external/box2d/Dynamics/Joints/b2MouseJoint.cpp b/external/box2d/Dynamics/Joints/b2MouseJoint.cpp deleted file mode 100644 index 237d9d519a..0000000000 --- a/external/box2d/Dynamics/Joints/b2MouseJoint.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// p = attached point, m = mouse point -// C = p - m -// Cdot = v -// = v + cross(w, r) -// J = [I r_skew] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) -: b2Joint(def) -{ - b2Assert(def->target.IsValid()); - b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); - b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); - b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); - - m_targetA = def->target; - m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); - - m_maxForce = def->maxForce; - m_impulse.SetZero(); - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_beta = 0.0f; - m_gamma = 0.0f; -} - -void b2MouseJoint::SetTarget(const b2Vec2& target) -{ - if (m_bodyB->IsAwake() == false) - { - m_bodyB->SetAwake(true); - } - m_targetA = target; -} - -const b2Vec2& b2MouseJoint::GetTarget() const -{ - return m_targetA; -} - -void b2MouseJoint::SetMaxForce(float32 force) -{ - m_maxForce = force; -} - -float32 b2MouseJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2MouseJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -float32 b2MouseJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -void b2MouseJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -float32 b2MouseJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexB = m_bodyB->m_islandIndex; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassB = m_bodyB->m_invMass; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qB(aB); - - float32 mass = m_bodyB->GetMass(); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = mass * (omega * omega); - - // magic formulas - // gamma has units of inverse mass. - // beta has units of inverse time. - float32 h = data.step.dt; - b2Assert(d + h * k > b2_epsilon); - m_gamma = h * (d + h * k); - if (m_gamma != 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - m_beta = h * k * m_gamma; - - // Compute the effective mass matrix. - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - b2Mat22 K; - K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; - K.ex.y = -m_invIB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; - - m_mass = K.GetInverse(); - - m_C = cB + m_rB - m_targetA; - m_C *= m_beta; - - // Cheat with some damping - wB *= 0.98f; - - if (data.step.warmStarting) - { - m_impulse *= data.step.dtRatio; - vB += m_invMassB * m_impulse; - wB += m_invIB * b2Cross(m_rB, m_impulse); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = v + cross(w, r) - b2Vec2 Cdot = vB + b2Cross(wB, m_rB); - b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); - - b2Vec2 oldImpulse = m_impulse; - m_impulse += impulse; - float32 maxImpulse = data.step.dt * m_maxForce; - if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_impulse *= maxImpulse / m_impulse.Length(); - } - impulse = m_impulse - oldImpulse; - - vB += m_invMassB * impulse; - wB += m_invIB * b2Cross(m_rB, impulse); - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - return true; -} - -b2Vec2 b2MouseJoint::GetAnchorA() const -{ - return m_targetA; -} - -b2Vec2 b2MouseJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_impulse; -} - -float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * 0.0f; -} diff --git a/external/box2d/Dynamics/Joints/b2MouseJoint.h b/external/box2d/Dynamics/Joints/b2MouseJoint.h deleted file mode 100644 index 1bbc194f4c..0000000000 --- a/external/box2d/Dynamics/Joints/b2MouseJoint.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_MOUSE_JOINT_H -#define B2_MOUSE_JOINT_H - -#include - -/// Mouse joint definition. This requires a world target point, -/// tuning parameters, and the time step. -struct b2MouseJointDef : public b2JointDef -{ - b2MouseJointDef() - { - type = e_mouseJoint; - target.Set(0.0f, 0.0f); - maxForce = 0.0f; - frequencyHz = 5.0f; - dampingRatio = 0.7f; - } - - /// The initial world target point. This is assumed - /// to coincide with the body anchor initially. - b2Vec2 target; - - /// The maximum constraint force that can be exerted - /// to move the candidate body. Usually you will express - /// as some multiple of the weight (multiplier * mass * gravity). - float32 maxForce; - - /// The response speed. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A mouse joint is used to make a point on a body track a -/// specified world point. This a soft constraint with a maximum -/// force. This allows the constraint to stretch and without -/// applying huge forces. -/// NOTE: this joint is not documented in the manual because it was -/// developed to be used in the testbed. If you want to learn how to -/// use the mouse joint, look at the testbed. -class b2MouseJoint : public b2Joint -{ -public: - - /// Implements b2Joint. - b2Vec2 GetAnchorA() const; - - /// Implements b2Joint. - b2Vec2 GetAnchorB() const; - - /// Implements b2Joint. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Implements b2Joint. - float32 GetReactionTorque(float32 inv_dt) const; - - /// Use this to update the target point. - void SetTarget(const b2Vec2& target); - const b2Vec2& GetTarget() const; - - /// Set/get the maximum force in Newtons. - void SetMaxForce(float32 force); - float32 GetMaxForce() const; - - /// Set/get the frequency in Hertz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get the damping ratio (dimensionless). - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// The mouse joint does not support dumping. - void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } - -protected: - friend class b2Joint; - - b2MouseJoint(const b2MouseJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_localAnchorB; - b2Vec2 m_targetA; - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_beta; - - // Solver shared - b2Vec2 m_impulse; - float32 m_maxForce; - float32 m_gamma; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rB; - b2Vec2 m_localCenterB; - float32 m_invMassB; - float32 m_invIB; - b2Mat22 m_mass; - b2Vec2 m_C; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp b/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp deleted file mode 100644 index 4849f729f5..0000000000 --- a/external/box2d/Dynamics/Joints/b2PrismaticJoint.cpp +++ /dev/null @@ -1,637 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Linear constraint (point-to-line) -// d = p2 - p1 = x2 + r2 - x1 - r1 -// C = dot(perp, d) -// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) -// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] -// -// Angular constraint -// C = a2 - a1 + a_initial -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// -// K = J * invM * JT -// -// J = [-a -s1 a s2] -// [0 -1 0 1] -// a = perp -// s1 = cross(d + r1, a) = cross(p2 - x1, a) -// s2 = cross(r2, a) = cross(p2 - x2, a) - - -// Motor/Limit linear constraint -// C = dot(ax1, d) -// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) -// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] - -// Block Solver -// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even -// when the mass has poor distribution (leading to large torques about the joint anchor points). -// -// The Jacobian has 3 rows: -// J = [-uT -s1 uT s2] // linear -// [0 -1 0 1] // angular -// [-vT -a1 vT a2] // limit -// -// u = perp -// v = axis -// s1 = cross(d + r1, u), s2 = cross(r2, u) -// a1 = cross(d + r1, v), a2 = cross(r2, v) - -// M * (v2 - v1) = JT * df -// J * v2 = bias -// -// v2 = v1 + invM * JT * df -// J * (v1 + invM * JT * df) = bias -// K * df = bias - J * v1 = -Cdot -// K = J * invM * JT -// Cdot = J * v1 - bias -// -// Now solve for f2. -// df = f2 - f1 -// K * (f2 - f1) = -Cdot -// f2 = invK * (-Cdot) + f1 -// -// Clamp accumulated limit impulse. -// lower: f2(3) = max(f2(3), 0) -// upper: f2(3) = min(f2(3), 0) -// -// Solve for correct f2(1:2) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 -// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) -// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) -// -// Now compute impulse to be applied: -// df = f2 - f1 - -void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localXAxisA.Normalize(); - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = def->maxMotorForce; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; - - m_axis.SetZero(); - m_perp.SetZero(); -} - -void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute motor Jacobian and effective mass. - { - m_axis = b2Mul(qA, m_localXAxisA); - m_a1 = b2Cross(d + rA, m_axis); - m_a2 = b2Cross(rB, m_axis); - - m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - - // Prismatic constraint. - { - m_perp = b2Mul(qA, m_localYAxisA); - - m_s1 = b2Cross(d + rA, m_perp); - m_s2 = b2Cross(rB, m_perp); - - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; - float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For bodies with fixed rotation. - k22 = 1.0f; - } - float32 k23 = iA * m_a1 + iB * m_a2; - float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - - m_K.ex.Set(k11, k12, k13); - m_K.ey.Set(k12, k22, k23); - m_K.ez.Set(k13, k23, k33); - } - - // Compute motor and limit terms. - if (m_enableLimit) - { - float32 jointTranslation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitState = e_atLowerLimit; - m_impulse.z = 0.0f; - } - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitState = e_atUpperLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - - if (m_enableMotor == false) - { - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; - float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; - float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - float32 impulse = m_motorMass * (m_motorSpeed - Cdot); - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorForce; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - b2Vec2 P = impulse * m_axis; - float32 LA = impulse * m_a1; - float32 LB = impulse * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - b2Vec2 Cdot1; - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - // Solve prismatic and limit constraint in block form. - float32 Cdot2; - Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 f1 = m_impulse; - b2Vec3 df = m_K.Solve33(-Cdot); - m_impulse += df; - - if (m_limitState == e_atLowerLimit) - { - m_impulse.z = b2Max(m_impulse.z, 0.0f); - } - else if (m_limitState == e_atUpperLimit) - { - m_impulse.z = b2Min(m_impulse.z, 0.0f); - } - - // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) - b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); - b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); - m_impulse.x = f2r.x; - m_impulse.y = f2r.y; - - df = m_impulse - f1; - - b2Vec2 P = df.x * m_perp + df.z * m_axis; - float32 LA = df.x * m_s1 + df.y + df.z * m_a1; - float32 LB = df.x * m_s2 + df.y + df.z * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - // Limit is inactive, just solve the prismatic constraint in block form. - b2Vec2 df = m_K.Solve22(-Cdot1); - m_impulse.x += df.x; - m_impulse.y += df.y; - - b2Vec2 P = df.x * m_perp; - float32 LA = df.x * m_s1 + df.y; - float32 LB = df.x * m_s2 + df.y; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - - b2Vec2 Cdot10 = Cdot1; - - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) - { - b2Vec2 test = b2Mul22(m_K, df); - Cdot1.x += 0.0f; - } - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute fresh Jacobians - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - b2Vec2 axis = b2Mul(qA, m_localXAxisA); - float32 a1 = b2Cross(d + rA, axis); - float32 a2 = b2Cross(rB, axis); - b2Vec2 perp = b2Mul(qA, m_localYAxisA); - - float32 s1 = b2Cross(d + rA, perp); - float32 s2 = b2Cross(rB, perp); - - b2Vec3 impulse; - b2Vec2 C1; - C1.x = b2Dot(perp, d); - C1.y = aB - aA - m_referenceAngle; - - float32 linearError = b2Abs(C1.x); - float32 angularError = b2Abs(C1.y); - - bool active = false; - float32 C2 = 0.0f; - if (m_enableLimit) - { - float32 translation = b2Dot(axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - // Prevent large angular corrections - C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Max(linearError, b2Abs(translation)); - active = true; - } - else if (translation <= m_lowerTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = b2Max(linearError, m_lowerTranslation - translation); - active = true; - } - else if (translation >= m_upperTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = b2Max(linearError, translation - m_upperTranslation); - active = true; - } - } - - if (active) - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k13 = iA * s1 * a1 + iB * s2 * a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For fixed rotation - k22 = 1.0f; - } - float32 k23 = iA * a1 + iB * a2; - float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - - b2Mat33 K; - K.ex.Set(k11, k12, k13); - K.ey.Set(k12, k22, k23); - K.ez.Set(k13, k23, k33); - - b2Vec3 C; - C.x = C1.x; - C.y = C1.y; - C.z = C2; - - impulse = K.Solve33(-C); - } - else - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - k22 = 1.0f; - } - - b2Mat22 K; - K.ex.Set(k11, k12); - K.ey.Set(k12, k22); - - b2Vec2 impulse1 = K.Solve(-C1); - impulse.x = impulse1.x; - impulse.y = impulse1.y; - impulse.z = 0.0f; - } - - b2Vec2 P = impulse.x * perp + impulse.z * axis; - float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; - float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; - - cA -= mA * P; - aA -= iA * LA; - cB += mB * P; - aB += iB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2PrismaticJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PrismaticJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); -} - -float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.y; -} - -float32 b2PrismaticJoint::GetJointTranslation() const -{ - b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2PrismaticJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); - b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); - b2Vec2 p1 = bA->m_sweep.c + rA; - b2Vec2 p2 = bB->m_sweep.c + rB; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - - b2Vec2 vA = bA->m_linearVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - float32 wB = bB->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); - return speed; -} - -bool b2PrismaticJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2PrismaticJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2PrismaticJoint::GetLowerLimit() const -{ - return m_lowerTranslation; -} - -float32 b2PrismaticJoint::GetUpperLimit() const -{ - return m_upperTranslation; -} - -void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - if (lower != m_lowerTranslation || upper != m_upperTranslation) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; - m_impulse.z = 0.0f; - } -} - -bool b2PrismaticJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2PrismaticJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -void b2PrismaticJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2PrismaticJoint::SetMaxMotorForce(float32 force) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorForce = force; -} - -float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2PrismaticJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PrismaticJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); - b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2PrismaticJoint.h b/external/box2d/Dynamics/Joints/b2PrismaticJoint.h deleted file mode 100644 index aca2859b45..0000000000 --- a/external/box2d/Dynamics/Joints/b2PrismaticJoint.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_PRISMATIC_JOINT_H -#define B2_PRISMATIC_JOINT_H - -#include - -/// Prismatic joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2PrismaticJointDef : public b2JointDef -{ - b2PrismaticJointDef() - { - type = e_prismaticJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - referenceAngle = 0.0f; - enableLimit = false; - lowerTranslation = 0.0f; - upperTranslation = 0.0f; - enableMotor = false; - maxMotorForce = 0.0f; - motorSpeed = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and unit world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation unit axis in bodyA. - b2Vec2 localAxisA; - - /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. - float32 referenceAngle; - - /// Enable/disable the joint limit. - bool enableLimit; - - /// The lower translation limit, usually in meters. - float32 lowerTranslation; - - /// The upper translation limit, usually in meters. - float32 upperTranslation; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorForce; - - /// The desired motor speed in radians per second. - float32 motorSpeed; -}; - -/// A prismatic joint. This joint provides one degree of freedom: translation -/// along an axis fixed in bodyA. Relative rotation is prevented. You can -/// use a joint limit to restrict the range of motion and a joint motor to -/// drive the motion or to model joint friction. -class b2PrismaticJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit, usually in meters. - float32 GetLowerLimit() const; - - /// Get the upper joint limit, usually in meters. - float32 GetUpperLimit() const; - - /// Set the joint limits, usually in meters. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in meters per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in meters per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor force, usually in N. - void SetMaxMotorForce(float32 force); - float32 GetMaxMotorForce() const { return m_maxMotorForce; } - - /// Get the current motor force given the inverse time step, usually in N. - float32 GetMotorForce(float32 inv_dt) const; - - /// Dump to b2Log - void Dump(); - -protected: - friend class b2Joint; - friend class b2GearJoint; - b2PrismaticJoint(const b2PrismaticJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - float32 m_referenceAngle; - b2Vec3 m_impulse; - float32 m_motorImpulse; - float32 m_lowerTranslation; - float32 m_upperTranslation; - float32 m_maxMotorForce; - float32 m_motorSpeed; - bool m_enableLimit; - bool m_enableMotor; - b2LimitState m_limitState; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - b2Mat33 m_K; - float32 m_motorMass; -}; - -inline float32 b2PrismaticJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp b/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp deleted file mode 100644 index da30fae222..0000000000 --- a/external/box2d/Dynamics/Joints/b2PulleyJoint.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Pulley: -// length1 = norm(p1 - s1) -// length2 = norm(p2 - s2) -// C0 = (length1 + ratio * length2)_initial -// C = C0 - (length1 + ratio * length2) -// u1 = (p1 - s1) / norm(p1 - s1) -// u2 = (p2 - s2) / norm(p2 - s2) -// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) -// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) - -void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, - const b2Vec2& groundA, const b2Vec2& groundB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 r) -{ - bodyA = bA; - bodyB = bB; - groundAnchorA = groundA; - groundAnchorB = groundB; - localAnchorA = bodyA->GetLocalPoint(anchorA); - localAnchorB = bodyB->GetLocalPoint(anchorB); - b2Vec2 dA = anchorA - groundA; - lengthA = dA.Length(); - b2Vec2 dB = anchorB - groundB; - lengthB = dB.Length(); - ratio = r; - b2Assert(ratio > b2_epsilon); -} - -b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) -: b2Joint(def) -{ - m_groundAnchorA = def->groundAnchorA; - m_groundAnchorB = def->groundAnchorB; - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_lengthA = def->lengthA; - m_lengthB = def->lengthB; - - b2Assert(def->ratio != 0.0f); - m_ratio = def->ratio; - - m_constant = def->lengthA + m_ratio * def->lengthB; - - m_impulse = 0.0f; -} - -void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - m_uA = cA + m_rA - m_groundAnchorA; - m_uB = cB + m_rB - m_groundAnchorB; - - float32 lengthA = m_uA.Length(); - float32 lengthB = m_uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - m_uA *= 1.0f / lengthA; - } - else - { - m_uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - m_uB *= 1.0f / lengthB; - } - else - { - m_uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(m_rA, m_uA); - float32 ruB = b2Cross(m_rB, m_uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - m_mass = mA + m_ratio * m_ratio * mB; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support variable time steps. - m_impulse *= data.step.dtRatio; - - // Warm starting. - b2Vec2 PA = -(m_impulse) * m_uA; - b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; - - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - - float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 PA = -impulse * m_uA; - b2Vec2 PB = -m_ratio * impulse * m_uB; - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - b2Vec2 uA = cA + rA - m_groundAnchorA; - b2Vec2 uB = cB + rB - m_groundAnchorB; - - float32 lengthA = uA.Length(); - float32 lengthB = uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - uA *= 1.0f / lengthA; - } - else - { - uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - uB *= 1.0f / lengthB; - } - else - { - uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(rA, uA); - float32 ruB = b2Cross(rB, uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - float32 mass = mA + m_ratio * m_ratio * mB; - - if (mass > 0.0f) - { - mass = 1.0f / mass; - } - - float32 C = m_constant - lengthA - m_ratio * lengthB; - float32 linearError = b2Abs(C); - - float32 impulse = -mass * C; - - b2Vec2 PA = -impulse * uA; - b2Vec2 PB = -m_ratio * impulse * uB; - - cA += m_invMassA * PA; - aA += m_invIA * b2Cross(rA, PA); - cB += m_invMassB * PB; - aB += m_invIB * b2Cross(rB, PB); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError < b2_linearSlop; -} - -b2Vec2 b2PulleyJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PulleyJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_uB; - return inv_dt * P; -} - -float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorA() const -{ - return m_groundAnchorA; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorB() const -{ - return m_groundAnchorB; -} - -float32 b2PulleyJoint::GetLengthA() const -{ - b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 s = m_groundAnchorA; - b2Vec2 d = p - s; - return d.Length(); -} - -float32 b2PulleyJoint::GetLengthB() const -{ - b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 s = m_groundAnchorB; - b2Vec2 d = p - s; - return d.Length(); -} - -float32 b2PulleyJoint::GetRatio() const -{ - return m_ratio; -} - -void b2PulleyJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PulleyJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); - b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); - b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2PulleyJoint.h b/external/box2d/Dynamics/Joints/b2PulleyJoint.h deleted file mode 100644 index 2f6df4395c..0000000000 --- a/external/box2d/Dynamics/Joints/b2PulleyJoint.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_PULLEY_JOINT_H -#define B2_PULLEY_JOINT_H - -#include - -const float32 b2_minPulleyLength = 2.0f; - -/// Pulley joint definition. This requires two ground anchors, -/// two dynamic body anchor points, and a pulley ratio. -struct b2PulleyJointDef : public b2JointDef -{ - b2PulleyJointDef() - { - type = e_pulleyJoint; - groundAnchorA.Set(-1.0f, 1.0f); - groundAnchorB.Set(1.0f, 1.0f); - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - lengthA = 0.0f; - lengthB = 0.0f; - ratio = 1.0f; - collideConnected = true; - } - - /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 ratio); - - /// The first ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorA; - - /// The second ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorB; - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The a reference length for the segment attached to bodyA. - float32 lengthA; - - /// The a reference length for the segment attached to bodyB. - float32 lengthB; - - /// The pulley ratio, used to simulate a block-and-tackle. - float32 ratio; -}; - -/// The pulley joint is connected to two bodies and two fixed ground points. -/// The pulley supports a ratio such that: -/// length1 + ratio * length2 <= constant -/// Yes, the force transmitted is scaled by the ratio. -/// Warning: the pulley joint can get a bit squirrelly by itself. They often -/// work better when combined with prismatic joints. You should also cover the -/// the anchor points with static shapes to prevent one side from going to -/// zero length. -class b2PulleyJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the first ground anchor. - b2Vec2 GetGroundAnchorA() const; - - /// Get the second ground anchor. - b2Vec2 GetGroundAnchorB() const; - - /// Get the current length of the segment attached to bodyA. - float32 GetLengthA() const; - - /// Get the current length of the segment attached to bodyB. - float32 GetLengthB() const; - - /// Get the pulley ratio. - float32 GetRatio() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2PulleyJoint(const b2PulleyJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - b2Vec2 m_groundAnchorA; - b2Vec2 m_groundAnchorB; - float32 m_lengthA; - float32 m_lengthB; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_constant; - float32 m_ratio; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_uA; - b2Vec2 m_uB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp b/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp deleted file mode 100644 index e265d8192b..0000000000 --- a/external/box2d/Dynamics/Joints/b2RevoluteJoint.cpp +++ /dev/null @@ -1,504 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Motor constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - - m_lowerAngle = def->lowerAngle; - m_upperAngle = def->upperAngle; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; -} - -void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; - - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - - if (m_enableMotor == false || fixedRotation) - { - m_motorImpulse = 0.0f; - } - - if (m_enableLimit && fixedRotation == false) - { - float32 jointAngle = aB - aA - m_referenceAngle; - if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) - { - m_limitState = e_equalLimits; - } - else if (jointAngle <= m_lowerAngle) - { - if (m_limitState != e_atLowerLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointAngle >= m_upperAngle) - { - if (m_limitState != e_atUpperLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - // Solve motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -m_mass.Solve33(Cdot); - - if (m_limitState == e_equalLimits) - { - m_impulse += impulse; - } - else if (m_limitState == e_atLowerLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse < 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - else if (m_limitState == e_atUpperLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse > 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - else - { - // Solve point-to-point constraint - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse = m_mass.Solve22(-Cdot); - - m_impulse.x += impulse.x; - m_impulse.y += impulse.y; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 angularError = 0.0f; - float32 positionError = 0.0f; - - bool fixedRotation = (m_invIA + m_invIB == 0.0f); - - // Solve angular limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - float32 angle = aB - aA - m_referenceAngle; - float32 limitImpulse = 0.0f; - - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - angularError = b2Abs(C); - } - else if (m_limitState == e_atLowerLimit) - { - float32 C = angle - m_lowerAngle; - angularError = -C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); - limitImpulse = -m_motorMass * C; - } - else if (m_limitState == e_atUpperLimit) - { - float32 C = angle - m_upperAngle; - angularError = C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - } - - aA -= m_invIA * limitImpulse; - aB += m_invIB * limitImpulse; - } - - // Solve point-to-point constraint. - { - qA.Set(aA); - qB.Set(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - b2Vec2 C = cB + rB - cA - rA; - positionError = C.Length(); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; - K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; - - b2Vec2 impulse = -K.Solve(C); - - cA -= mA * impulse; - aA -= iA * b2Cross(rA, impulse); - - cB += mB * impulse; - aB += iB * b2Cross(rB, impulse); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2RevoluteJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RevoluteJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -float32 b2RevoluteJoint::GetJointAngle() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; -} - -float32 b2RevoluteJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_angularVelocity - bA->m_angularVelocity; -} - -bool b2RevoluteJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2RevoluteJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2RevoluteJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; -} - -bool b2RevoluteJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2RevoluteJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2RevoluteJoint::GetLowerLimit() const -{ - return m_lowerAngle; -} - -float32 b2RevoluteJoint::GetUpperLimit() const -{ - return m_upperAngle; -} - -void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - - if (lower != m_lowerAngle || upper != m_upperAngle) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_impulse.z = 0.0f; - m_lowerAngle = lower; - m_upperAngle = upper; - } -} - -void b2RevoluteJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RevoluteJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); - b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2RevoluteJoint.h b/external/box2d/Dynamics/Joints/b2RevoluteJoint.h deleted file mode 100644 index 978f16259a..0000000000 --- a/external/box2d/Dynamics/Joints/b2RevoluteJoint.h +++ /dev/null @@ -1,204 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_REVOLUTE_JOINT_H -#define B2_REVOLUTE_JOINT_H - -#include - -/// Revolute joint definition. This requires defining an -/// anchor point where the bodies are joined. The definition -/// uses local anchor points so that the initial configuration -/// can violate the constraint slightly. You also need to -/// specify the initial relative angle for joint limits. This -/// helps when saving and loading a game. -/// The local anchor points are measured from the body's origin -/// rather than the center of mass because: -/// 1. you might not know where the center of mass will be. -/// 2. if you add/remove shapes from a body and recompute the mass, -/// the joints will be broken. -struct b2RevoluteJointDef : public b2JointDef -{ - b2RevoluteJointDef() - { - type = e_revoluteJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - lowerAngle = 0.0f; - upperAngle = 0.0f; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - enableLimit = false; - enableMotor = false; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// A flag to enable joint limits. - bool enableLimit; - - /// The lower angle for the joint limit (radians). - float32 lowerAngle; - - /// The upper angle for the joint limit (radians). - float32 upperAngle; - - /// A flag to enable the joint motor. - bool enableMotor; - - /// The desired motor speed. Usually in radians per second. - float32 motorSpeed; - - /// The maximum motor torque used to achieve the desired motor speed. - /// Usually in N-m. - float32 maxMotorTorque; -}; - -/// A revolute joint constrains two bodies to share a common point while they -/// are free to rotate about the point. The relative rotation about the shared -/// point is the joint angle. You can limit the relative rotation with -/// a joint limit that specifies a lower and upper angle. You can use a motor -/// to drive the relative rotation about the shared point. A maximum motor torque -/// is provided so that infinite forces are not generated. -class b2RevoluteJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint angle in radians. - float32 GetJointAngle() const; - - /// Get the current joint angle speed in radians per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit in radians. - float32 GetLowerLimit() const; - - /// Get the upper joint limit in radians. - float32 GetUpperLimit() const; - - /// Set the joint limits in radians. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed in radians per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor torque, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; - - /// Get the reaction torque due to the joint limit given the inverse time step. - /// Unit is N*m. - float32 GetReactionTorque(float32 inv_dt) const; - - /// Get the current motor torque given the inverse time step. - /// Unit is N*m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Dump to b2Log. - void Dump(); - -protected: - - friend class b2Joint; - friend class b2GearJoint; - - b2RevoluteJoint(const b2RevoluteJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec3 m_impulse; - float32 m_motorImpulse; - - bool m_enableMotor; - float32 m_maxMotorTorque; - float32 m_motorSpeed; - - bool m_enableLimit; - float32 m_referenceAngle; - float32 m_lowerAngle; - float32 m_upperAngle; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; // effective mass for point-to-point constraint. - float32 m_motorMass; // effective mass for motor/limit angular constraint. - b2LimitState m_limitState; -}; - -inline float32 b2RevoluteJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/external/box2d/Dynamics/Joints/b2RopeJoint.cpp b/external/box2d/Dynamics/Joints/b2RopeJoint.cpp deleted file mode 100644 index 17a70d9230..0000000000 --- a/external/box2d/Dynamics/Joints/b2RopeJoint.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - - -// Limit: -// C = norm(pB - pA) - L -// u = (pB - pA) / norm(pB - pA) -// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) -// J = [-u -cross(rA, u) u cross(rB, u)] -// K = J * invM * JT -// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 - -b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_maxLength = def->maxLength; - - m_mass = 0.0f; - m_impulse = 0.0f; - m_state = e_inactiveLimit; - m_length = 0.0f; -} - -void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - m_length = m_u.Length(); - - float32 C = m_length - m_maxLength; - if (C > 0.0f) - { - m_state = e_atUpperLimit; - } - else - { - m_state = e_inactiveLimit; - } - - if (m_length > b2_linearSlop) - { - m_u *= 1.0f / m_length; - } - else - { - m_u.SetZero(); - m_mass = 0.0f; - m_impulse = 0.0f; - return; - } - - // Compute effective mass. - float32 crA = b2Cross(m_rA, m_u); - float32 crB = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; - - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 C = m_length - m_maxLength; - float32 Cdot = b2Dot(m_u, vpB - vpA); - - // Predictive constraint. - if (C < 0.0f) - { - Cdot += data.step.inv_dt * C; - } - - float32 impulse = -m_mass * Cdot; - float32 oldImpulse = m_impulse; - m_impulse = b2Min(0.0f, m_impulse + impulse); - impulse = m_impulse - oldImpulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_maxLength; - - C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return length - m_maxLength < b2_linearSlop; -} - -b2Vec2 b2RopeJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RopeJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -float32 b2RopeJoint::GetMaxLength() const -{ - return m_maxLength; -} - -b2LimitState b2RopeJoint::GetLimitState() const -{ - return m_state; -} - -void b2RopeJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RopeJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2RopeJoint.h b/external/box2d/Dynamics/Joints/b2RopeJoint.h deleted file mode 100644 index d7091b6650..0000000000 --- a/external/box2d/Dynamics/Joints/b2RopeJoint.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ROPE_JOINT_H -#define B2_ROPE_JOINT_H - -#include - -/// Rope joint definition. This requires two body anchor points and -/// a maximum lengths. -/// Note: by default the connected objects will not collide. -/// see collideConnected in b2JointDef. -struct b2RopeJointDef : public b2JointDef -{ - b2RopeJointDef() - { - type = e_ropeJoint; - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - maxLength = 0.0f; - } - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum length of the rope. - /// Warning: this must be larger than b2_linearSlop or - /// the joint will have no effect. - float32 maxLength; -}; - -/// A rope joint enforces a maximum distance between two points -/// on two bodies. It has no other effect. -/// Warning: if you attempt to change the maximum length during -/// the simulation you will get some non-physical behavior. -/// A model that would allow you to dynamically modify the length -/// would have some sponginess, so I chose not to implement it -/// that way. See b2DistanceJoint if you want to dynamically -/// control length. -class b2RopeJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/Get the maximum length of the rope. - void SetMaxLength(float32 length) { m_maxLength = length; } - float32 GetMaxLength() const; - - b2LimitState GetLimitState() const; - - /// Dump joint to dmLog - void Dump(); - -protected: - - friend class b2Joint; - b2RopeJoint(const b2RopeJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_maxLength; - float32 m_length; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; - b2LimitState m_state; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2WeldJoint.cpp b/external/box2d/Dynamics/Joints/b2WeldJoint.cpp deleted file mode 100644 index f50bdd6587..0000000000 --- a/external/box2d/Dynamics/Joints/b2WeldJoint.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// C = angle2 - angle1 - referenceAngle -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_impulse.SetZero(); -} - -void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat33 K; - K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - K.ez.x = -m_rA.y * iA - m_rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - K.ez.y = m_rA.x * iA + m_rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - K.GetInverse22(&m_mass); - - float32 invM = iA + iB; - float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; - - float32 C = aB - aA - m_referenceAngle; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invM += m_gamma; - m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; - } - else - { - K.GetSymInverse33(&m_mass); - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_impulse.z); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - if (m_frequencyHz > 0.0f) - { - float32 Cdot2 = wB - wA; - - float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); - m_impulse.z += impulse2; - - wA -= iA * impulse2; - wB += iB * impulse2; - - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); - m_impulse.x += impulse1.x; - m_impulse.y += impulse1.y; - - b2Vec2 P = impulse1; - - vA -= mA * P; - wA -= iA * b2Cross(m_rA, P); - - vB += mB * P; - wB += iB * b2Cross(m_rB, P); - } - else - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -b2Mul(m_mass, Cdot); - m_impulse += impulse; - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - float32 positionError, angularError; - - b2Mat33 K; - K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - K.ez.x = -rA.y * iA - rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - K.ez.y = rA.x * iA + rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - b2Vec2 C1 = cB + rB - cA - rA; - - positionError = C1.Length(); - angularError = 0.0f; - - b2Vec2 P = -K.Solve22(C1); - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - else - { - b2Vec2 C1 = cB + rB - cA - rA; - float32 C2 = aB - aA - m_referenceAngle; - - positionError = C1.Length(); - angularError = b2Abs(C2); - - b2Vec3 C(C1.x, C1.y, C2); - - b2Vec3 impulse = -K.Solve33(C); - b2Vec2 P(impulse.x, impulse.y); - - cA -= mA * P; - aA -= iA * (b2Cross(rA, P) + impulse.z); - - cB += mB * P; - aB += iB * (b2Cross(rB, P) + impulse.z); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2WeldJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WeldJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -void b2WeldJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WeldJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2WeldJoint.h b/external/box2d/Dynamics/Joints/b2WeldJoint.h deleted file mode 100644 index 751c6a8770..0000000000 --- a/external/box2d/Dynamics/Joints/b2WeldJoint.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WELD_JOINT_H -#define B2_WELD_JOINT_H - -#include - -/// Weld joint definition. You need to specify local anchor points -/// where they are attached and the relative body angle. The position -/// of the anchor points is important for computing the reaction torque. -struct b2WeldJointDef : public b2JointDef -{ - b2WeldJointDef() - { - type = e_weldJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// The mass-spring-damper frequency in Hertz. Rotation only. - /// Disable softness with a value of 0. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A weld joint essentially glues two bodies together. A weld joint may -/// distort somewhat because the island constraint solver is approximate. -class b2WeldJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz) { m_frequencyHz = hz; } - float32 GetFrequency() const { return m_frequencyHz; } - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } - float32 GetDampingRatio() const { return m_dampingRatio; } - - /// Dump to b2Log - void Dump(); - -protected: - - friend class b2Joint; - - b2WeldJoint(const b2WeldJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_referenceAngle; - float32 m_gamma; - b2Vec3 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; -}; - -#endif diff --git a/external/box2d/Dynamics/Joints/b2WheelJoint.cpp b/external/box2d/Dynamics/Joints/b2WheelJoint.cpp deleted file mode 100644 index 6253437706..0000000000 --- a/external/box2d/Dynamics/Joints/b2WheelJoint.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include - -// Linear constraint (point-to-line) -// d = pB - pA = xB + rB - xA - rA -// C = dot(ay, d) -// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) -// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) -// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] - -// Spring linear constraint -// C = dot(ax, d) -// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) -// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] - -// Motor rotational constraint -// Cdot = wB - wA -// J = [0 0 -1 0 0 1] - -void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); -} - -b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - - m_mass = 0.0f; - m_impulse = 0.0f; - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - m_springMass = 0.0f; - m_springImpulse = 0.0f; - - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableMotor = def->enableMotor; - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_bias = 0.0f; - m_gamma = 0.0f; - - m_ax.SetZero(); - m_ay.SetZero(); -} - -void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - // Point to line constraint - { - m_ay = b2Mul(qA, m_localYAxisA); - m_sAy = b2Cross(d + rA, m_ay); - m_sBy = b2Cross(rB, m_ay); - - m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - } - - // Spring constraint - m_springMass = 0.0f; - m_bias = 0.0f; - m_gamma = 0.0f; - if (m_frequencyHz > 0.0f) - { - m_ax = b2Mul(qA, m_localXAxisA); - m_sAx = b2Cross(d + rA, m_ax); - m_sBx = b2Cross(rB, m_ax); - - float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; - - if (invMass > 0.0f) - { - m_springMass = 1.0f / invMass; - - float32 C = b2Dot(d, m_ax); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m_springMass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_springMass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - if (m_gamma > 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - - m_bias = C * h * k * m_gamma; - - m_springMass = invMass + m_gamma; - if (m_springMass > 0.0f) - { - m_springMass = 1.0f / m_springMass; - } - } - } - else - { - m_springImpulse = 0.0f; - } - - // Rotational motor - if (m_enableMotor) - { - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - else - { - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_springImpulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; - float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; - float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; - - vA -= m_invMassA * P; - wA -= m_invIA * LA; - - vB += m_invMassB * P; - wB += m_invIB * LB; - } - else - { - m_impulse = 0.0f; - m_springImpulse = 0.0f; - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Solve spring constraint - { - float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; - float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); - m_springImpulse += impulse; - - b2Vec2 P = impulse * m_ax; - float32 LA = impulse * m_sAx; - float32 LB = impulse * m_sBx; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - // Solve rotational motor constraint - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve point to line constraint - { - float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 P = impulse * m_ay; - float32 LA = impulse * m_sAy; - float32 LB = impulse * m_sBy; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - b2Vec2 ay = b2Mul(qA, m_localYAxisA); - - float32 sAy = b2Cross(d + rA, ay); - float32 sBy = b2Cross(rB, ay); - - float32 C = b2Dot(d, ay); - - float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; - - float32 impulse; - if (k != 0.0f) - { - impulse = - C / k; - } - else - { - impulse = 0.0f; - } - - b2Vec2 P = impulse * ay; - float32 LA = impulse * sAy; - float32 LB = impulse * sBy; - - cA -= m_invMassA * P; - aA -= m_invIA * LA; - cB += m_invMassB * P; - aB += m_invIB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) <= b2_linearSlop; -} - -b2Vec2 b2WheelJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WheelJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); -} - -float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -float32 b2WheelJoint::GetJointTranslation() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2WheelJoint::GetJointSpeed() const -{ - float32 wA = m_bodyA->m_angularVelocity; - float32 wB = m_bodyB->m_angularVelocity; - return wB - wA; -} - -bool b2WheelJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2WheelJoint::EnableMotor(bool flag) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; -} - -void b2WheelJoint::SetMotorSpeed(float32 speed) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; -} - -void b2WheelJoint::SetMaxMotorTorque(float32 torque) -{ - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; -} - -float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2WheelJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WheelJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/external/box2d/Dynamics/Joints/b2WheelJoint.h b/external/box2d/Dynamics/Joints/b2WheelJoint.h deleted file mode 100644 index ede1b08b7c..0000000000 --- a/external/box2d/Dynamics/Joints/b2WheelJoint.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WHEEL_JOINT_H -#define B2_WHEEL_JOINT_H - -#include - -/// Wheel joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2WheelJointDef : public b2JointDef -{ - b2WheelJointDef() - { - type = e_wheelJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - enableMotor = false; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - frequencyHz = 2.0f; - dampingRatio = 0.7f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation axis in bodyA. - b2Vec2 localAxisA; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorTorque; - - /// The desired motor speed in radians per second. - float32 motorSpeed; - - /// Suspension frequency, zero indicates no suspension - float32 frequencyHz; - - /// Suspension damping ratio, one indicates critical damping - float32 dampingRatio; -}; - -/// A wheel joint. This joint provides two degrees of freedom: translation -/// along an axis fixed in bodyA and rotation in the plane. You can use a -/// joint limit to restrict the range of motion and a joint motor to drive -/// the rotation or to model rotational friction. -/// This joint is designed for vehicle suspensions. -class b2WheelJoint : public b2Joint -{ -public: - void GetDefinition(b2WheelJointDef* def) const; - - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; - - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in radians per second. - float32 GetMotorSpeed() const; - - /// Set/Get the maximum motor force, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const; - - /// Get the current motor torque given the inverse time step, usually in N-m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. - void SetSpringFrequencyHz(float32 hz); - float32 GetSpringFrequencyHz() const; - - /// Set/Get the spring damping ratio - void SetSpringDampingRatio(float32 ratio); - float32 GetSpringDampingRatio() const; - - /// Dump to b2Log - void Dump(); - -protected: - - friend class b2Joint; - b2WheelJoint(const b2WheelJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); - - float32 m_frequencyHz; - float32 m_dampingRatio; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - - float32 m_impulse; - float32 m_motorImpulse; - float32 m_springImpulse; - - float32 m_maxMotorTorque; - float32 m_motorSpeed; - bool m_enableMotor; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - - b2Vec2 m_ax, m_ay; - float32 m_sAx, m_sBx; - float32 m_sAy, m_sBy; - - float32 m_mass; - float32 m_motorMass; - float32 m_springMass; - - float32 m_bias; - float32 m_gamma; -}; - -inline float32 b2WheelJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -inline float32 b2WheelJoint::GetMaxMotorTorque() const -{ - return m_maxMotorTorque; -} - -inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2WheelJoint::GetSpringFrequencyHz() const -{ - return m_frequencyHz; -} - -inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2WheelJoint::GetSpringDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/external/box2d/Dynamics/b2Body.cpp b/external/box2d/Dynamics/b2Body.cpp deleted file mode 100644 index b22b574023..0000000000 --- a/external/box2d/Dynamics/b2Body.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -b2Body::b2Body(const b2BodyDef* bd, b2World* world) -{ - b2Assert(bd->position.IsValid()); - b2Assert(bd->linearVelocity.IsValid()); - b2Assert(b2IsValid(bd->angle)); - b2Assert(b2IsValid(bd->angularVelocity)); - b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); - b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); - - m_flags = 0; - - if (bd->bullet) - { - m_flags |= e_bulletFlag; - } - if (bd->fixedRotation) - { - m_flags |= e_fixedRotationFlag; - } - if (bd->allowSleep) - { - m_flags |= e_autoSleepFlag; - } - if (bd->awake) - { - m_flags |= e_awakeFlag; - } - if (bd->active) - { - m_flags |= e_activeFlag; - } - - m_world = world; - - m_xf.p = bd->position; - m_xf.q.Set(bd->angle); - - m_sweep.localCenter.SetZero(); - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = bd->angle; - m_sweep.a = bd->angle; - m_sweep.alpha0 = 0.0f; - - m_jointList = NULL; - m_contactList = NULL; - m_prev = NULL; - m_next = NULL; - - m_linearVelocity = bd->linearVelocity; - m_angularVelocity = bd->angularVelocity; - - m_linearDamping = bd->linearDamping; - m_angularDamping = bd->angularDamping; - m_gravityScale = bd->gravityScale; - - m_force.SetZero(); - m_torque = 0.0f; - - m_sleepTime = 0.0f; - - m_type = bd->type; - - if (m_type == b2_dynamicBody) - { - m_mass = 1.0f; - m_invMass = 1.0f; - } - else - { - m_mass = 0.0f; - m_invMass = 0.0f; - } - - m_I = 0.0f; - m_invI = 0.0f; - - m_userData = bd->userData; - - m_fixtureList = NULL; - m_fixtureCount = 0; -} - -b2Body::~b2Body() -{ - // shapes and joints are destroyed in b2World::Destroy -} - -void b2Body::SetType(b2BodyType type) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type == type) - { - return; - } - - m_type = type; - - ResetMassData(); - - if (m_type == b2_staticBody) - { - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_sweep.a0 = m_sweep.a; - m_sweep.c0 = m_sweep.c; - SynchronizeFixtures(); - } - - SetAwake(true); - - m_force.SetZero(); - m_torque = 0.0f; - - // Since the body type changed, we need to flag contacts for filtering. - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Refilter(); - } -} - -b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return NULL; - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - void* memory = allocator->Allocate(sizeof(b2Fixture)); - b2Fixture* fixture = new (memory) b2Fixture; - fixture->Create(allocator, this, def); - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->CreateProxies(broadPhase, m_xf); - } - - fixture->m_next = m_fixtureList; - m_fixtureList = fixture; - ++m_fixtureCount; - - fixture->m_body = this; - - // Adjust mass properties if needed. - if (fixture->m_density > 0.0f) - { - ResetMassData(); - } - - // Let the world know we have a new fixture. This will cause new contacts - // to be created at the beginning of the next time step. - m_world->m_flags |= b2World::e_newFixture; - - return fixture; -} - -b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) -{ - b2FixtureDef def; - def.shape = shape; - def.density = density; - - return CreateFixture(&def); -} - -void b2Body::DestroyFixture(b2Fixture* fixture) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - b2Assert(fixture->m_body == this); - - // Remove the fixture from this body's singly linked list. - b2Assert(m_fixtureCount > 0); - b2Fixture** node = &m_fixtureList; - bool found = false; - while (*node != NULL) - { - if (*node == fixture) - { - *node = fixture->m_next; - found = true; - break; - } - - node = &(*node)->m_next; - } - - // You tried to remove a shape that is not attached to this body. - b2Assert(found); - - // Destroy any contacts associated with the fixture. - b2ContactEdge* edge = m_contactList; - while (edge) - { - b2Contact* c = edge->contact; - edge = edge->next; - - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - - if (fixture == fixtureA || fixture == fixtureB) - { - // This destroys the contact and removes it from - // this body's contact list. - m_world->m_contactManager.Destroy(c); - } - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->DestroyProxies(broadPhase); - } - - fixture->Destroy(allocator); - fixture->m_body = NULL; - fixture->m_next = NULL; - fixture->~b2Fixture(); - allocator->Free(fixture, sizeof(b2Fixture)); - - --m_fixtureCount; - - // Reset the mass data. - ResetMassData(); -} - -void b2Body::ResetMassData() -{ - // Compute mass data from shapes. Each shape has its own density. - m_mass = 0.0f; - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - m_sweep.localCenter.SetZero(); - - // Static and kinematic bodies have zero mass. - if (m_type == b2_staticBody || m_type == b2_kinematicBody) - { - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = m_sweep.a; - return; - } - - b2Assert(m_type == b2_dynamicBody); - - // Accumulate mass over all fixtures. - b2Vec2 localCenter = b2Vec2_zero; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - if (f->m_density == 0.0f) - { - continue; - } - - b2MassData massData; - f->GetMassData(&massData); - m_mass += massData.mass; - localCenter += massData.mass * massData.center; - m_I += massData.I; - } - - // Compute center of mass. - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - localCenter *= m_invMass; - } - else - { - // Force all dynamic bodies to have a positive mass. - m_mass = 1.0f; - m_invMass = 1.0f; - } - - if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) - { - // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(localCenter, localCenter); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - - } - else - { - m_I = 0.0f; - m_invI = 0.0f; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = localCenter; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -void b2Body::SetMassData(const b2MassData* massData) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type != b2_dynamicBody) - { - return; - } - - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - m_mass = massData->mass; - if (m_mass <= 0.0f) - { - m_mass = 1.0f; - } - - m_invMass = 1.0f / m_mass; - - if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = massData->center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -bool b2Body::ShouldCollide(const b2Body* other) const -{ - // At least one body should be dynamic. - if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) - { - return false; - } - - // Does a joint prevent collision? - for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) - { - if (jn->other == other) - { - if (jn->joint->m_collideConnected == false) - { - return false; - } - } - } - - return true; -} - -void b2Body::SetTransform(const b2Vec2& position, float32 angle) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - m_xf.q.Set(angle); - m_xf.p = position; - - m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a = angle; - - m_sweep.c0 = m_sweep.c; - m_sweep.a0 = angle; - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, m_xf, m_xf); - } - - m_world->m_contactManager.FindNewContacts(); -} - -void b2Body::SynchronizeFixtures() -{ - b2Transform xf1; - xf1.q.Set(m_sweep.a0); - xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, xf1, m_xf); - } -} - -void b2Body::SetActive(bool flag) -{ - b2Assert(m_world->IsLocked() == false); - - if (flag == IsActive()) - { - return; - } - - if (flag) - { - m_flags |= e_activeFlag; - - // Create all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->CreateProxies(broadPhase, m_xf); - } - - // Contacts are created the next time step. - } - else - { - m_flags &= ~e_activeFlag; - - // Destroy all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->DestroyProxies(broadPhase); - } - - // Destroy the attached contacts. - b2ContactEdge* ce = m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_world->m_contactManager.Destroy(ce0->contact); - } - m_contactList = NULL; - } -} - -void b2Body::Dump() -{ - int32 bodyIndex = m_islandIndex; - - b2Log("{\n"); - b2Log(" b2BodyDef bd;\n"); - b2Log(" bd.type = b2BodyType(%d);\n", m_type); - b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); - b2Log(" bd.angle = %.15lef;\n", m_sweep.a); - b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); - b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); - b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); - b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); - b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); - b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); - b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); - b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); - b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); - b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); - b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); - b2Log("\n"); - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - b2Log(" {\n"); - f->Dump(bodyIndex); - b2Log(" }\n"); - } - b2Log("}\n"); -} \ No newline at end of file diff --git a/external/box2d/Dynamics/b2Body.h b/external/box2d/Dynamics/b2Body.h deleted file mode 100644 index e2d16bf630..0000000000 --- a/external/box2d/Dynamics/b2Body.h +++ /dev/null @@ -1,846 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_BODY_H -#define B2_BODY_H - -#include -#include -#include - -class b2Fixture; -class b2Joint; -class b2Contact; -class b2Controller; -class b2World; -struct b2FixtureDef; -struct b2JointEdge; -struct b2ContactEdge; - -/// The body type. -/// static: zero mass, zero velocity, may be manually moved -/// kinematic: zero mass, non-zero velocity set by user, moved by solver -/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver -enum b2BodyType -{ - b2_staticBody = 0, - b2_kinematicBody, - b2_dynamicBody - - // TODO_ERIN - //b2_bulletBody, -}; - -/// A body definition holds all the data needed to construct a rigid body. -/// You can safely re-use body definitions. Shapes are added to a body after construction. -struct b2BodyDef -{ - /// This constructor sets the body definition default values. - b2BodyDef() - { - userData = NULL; - position.Set(0.0f, 0.0f); - angle = 0.0f; - linearVelocity.Set(0.0f, 0.0f); - angularVelocity = 0.0f; - linearDamping = 0.0f; - angularDamping = 0.0f; - allowSleep = true; - awake = true; - fixedRotation = false; - bullet = false; - type = b2_staticBody; - active = true; - gravityScale = 1.0f; - } - - /// The body type: static, kinematic, or dynamic. - /// Note: if a dynamic body would have zero mass, the mass is set to one. - b2BodyType type; - - /// The world position of the body. Avoid creating bodies at the origin - /// since this can lead to many overlapping shapes. - b2Vec2 position; - - /// The world angle of the body in radians. - float32 angle; - - /// The linear velocity of the body's origin in world co-ordinates. - b2Vec2 linearVelocity; - - /// The angular velocity of the body. - float32 angularVelocity; - - /// Linear damping is use to reduce the linear velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 linearDamping; - - /// Angular damping is use to reduce the angular velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 angularDamping; - - /// Set this flag to false if this body should never fall asleep. Note that - /// this increases CPU usage. - bool allowSleep; - - /// Is this body initially awake or sleeping? - bool awake; - - /// Should this body be prevented from rotating? Useful for characters. - bool fixedRotation; - - /// Is this a fast moving body that should be prevented from tunneling through - /// other moving bodies? Note that all bodies are prevented from tunneling through - /// kinematic and static bodies. This setting is only considered on dynamic bodies. - /// @warning You should use this flag sparingly since it increases processing time. - bool bullet; - - /// Does this body start out active? - bool active; - - /// Use this to store application specific body data. - void* userData; - - /// Scale the gravity applied to this body. - float32 gravityScale; -}; - -/// A rigid body. These are created via b2World::CreateBody. -class b2Body -{ -public: - /// Creates a fixture and attach it to this body. Use this function if you need - /// to set some fixture parameters, like friction. Otherwise you can create the - /// fixture directly from a shape. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// Contacts are not created until the next time step. - /// @param def the fixture definition. - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2FixtureDef* def); - - /// Creates a fixture from a shape and attach it to this body. - /// This is a convenience function. Use b2FixtureDef if you need to set parameters - /// like friction, restitution, user data, or filtering. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// @param shape the shape to be cloned. - /// @param density the shape density (set to zero for static bodies). - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2Shape* shape, float32 density); - - /// Destroy a fixture. This removes the fixture from the broad-phase and - /// destroys all contacts associated with this fixture. This will - /// automatically adjust the mass of the body if the body is dynamic and the - /// fixture has positive density. - /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. - /// @param fixture the fixture to be removed. - /// @warning This function is locked during callbacks. - void DestroyFixture(b2Fixture* fixture); - - /// Set the position of the body's origin and rotation. - /// This breaks any contacts and wakes the other bodies. - /// Manipulating a body's transform may cause non-physical behavior. - /// @param position the world position of the body's local origin. - /// @param angle the world rotation in radians. - void SetTransform(const b2Vec2& position, float32 angle); - - /// Get the body transform for the body's origin. - /// @return the world transform of the body's origin. - const b2Transform& GetTransform() const; - - /// Get the world body origin position. - /// @return the world position of the body's origin. - const b2Vec2& GetPosition() const; - - /// Get the angle in radians. - /// @return the current world rotation angle in radians. - float32 GetAngle() const; - - /// Get the world position of the center of mass. - const b2Vec2& GetWorldCenter() const; - - /// Get the local position of the center of mass. - const b2Vec2& GetLocalCenter() const; - - /// Set the linear velocity of the center of mass. - /// @param v the new linear velocity of the center of mass. - void SetLinearVelocity(const b2Vec2& v); - - /// Get the linear velocity of the center of mass. - /// @return the linear velocity of the center of mass. - b2Vec2 GetLinearVelocity() const; - - /// Set the angular velocity. - /// @param omega the new angular velocity in radians/second. - void SetAngularVelocity(float32 omega); - - /// Get the angular velocity. - /// @return the angular velocity in radians/second. - float32 GetAngularVelocity() const; - - /// Apply a force at a world point. If the force is not - /// applied at the center of mass, it will generate a torque and - /// affect the angular velocity. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param point the world position of the point of application. - void ApplyForce(const b2Vec2& force, const b2Vec2& point); - - /// Apply a force to the center of mass. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - void ApplyForceToCenter(const b2Vec2& force); - - /// Apply a torque. This affects the angular velocity - /// without affecting the linear velocity of the center of mass. - /// This wakes up the body. - /// @param torque about the z-axis (out of the screen), usually in N-m. - void ApplyTorque(float32 torque); - - /// Apply an impulse at a point. This immediately modifies the velocity. - /// It also modifies the angular velocity if the point of application - /// is not at the center of mass. This wakes up the body. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param point the world position of the point of application. - void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); - - /// Apply an angular impulse. - /// @param impulse the angular impulse in units of kg*m*m/s - void ApplyAngularImpulse(float32 impulse); - - /// Get the total mass of the body. - /// @return the mass, usually in kilograms (kg). - float32 GetMass() const; - - /// Get the rotational inertia of the body about the local origin. - /// @return the rotational inertia, usually in kg-m^2. - float32 GetInertia() const; - - /// Get the mass data of the body. - /// @return a struct containing the mass, inertia and center of the body. - void GetMassData(b2MassData* data) const; - - /// Set the mass properties to override the mass properties of the fixtures. - /// Note that this changes the center of mass position. - /// Note that creating or destroying fixtures can also alter the mass. - /// This function has no effect if the body isn't dynamic. - /// @param massData the mass properties. - void SetMassData(const b2MassData* data); - - /// This resets the mass properties to the sum of the mass properties of the fixtures. - /// This normally does not need to be called unless you called SetMassData to override - /// the mass and you later want to reset the mass. - void ResetMassData(); - - /// Get the world coordinates of a point given the local coordinates. - /// @param localPoint a point on the body measured relative the the body's origin. - /// @return the same point expressed in world coordinates. - b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; - - /// Get the world coordinates of a vector given the local coordinates. - /// @param localVector a vector fixed in the body. - /// @return the same vector expressed in world coordinates. - b2Vec2 GetWorldVector(const b2Vec2& localVector) const; - - /// Gets a local point relative to the body's origin given a world point. - /// @param a point in world coordinates. - /// @return the corresponding local point relative to the body's origin. - b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; - - /// Gets a local vector given a world vector. - /// @param a vector in world coordinates. - /// @return the corresponding local vector. - b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; - - /// Get the world linear velocity of a world point attached to this body. - /// @param a point in world coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; - - /// Get the world velocity of a local point. - /// @param a point in local coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; - - /// Get the linear damping of the body. - float32 GetLinearDamping() const; - - /// Set the linear damping of the body. - void SetLinearDamping(float32 linearDamping); - - /// Get the angular damping of the body. - float32 GetAngularDamping() const; - - /// Set the angular damping of the body. - void SetAngularDamping(float32 angularDamping); - - /// Get the gravity scale of the body. - float32 GetGravityScale() const; - - /// Set the gravity scale of the body. - void SetGravityScale(float32 scale); - - /// Set the type of this body. This may alter the mass and velocity. - void SetType(b2BodyType type); - - /// Get the type of this body. - b2BodyType GetType() const; - - /// Should this body be treated like a bullet for continuous collision detection? - void SetBullet(bool flag); - - /// Is this body treated like a bullet for continuous collision detection? - bool IsBullet() const; - - /// You can disable sleeping on this body. If you disable sleeping, the - /// body will be woken. - void SetSleepingAllowed(bool flag); - - /// Is this body allowed to sleep - bool IsSleepingAllowed() const; - - /// Set the sleep state of the body. A sleeping body has very - /// low CPU cost. - /// @param flag set to true to put body to sleep, false to wake it. - void SetAwake(bool flag); - - /// Get the sleeping state of this body. - /// @return true if the body is sleeping. - bool IsAwake() const; - - /// Set the active state of the body. An inactive body is not - /// simulated and cannot be collided with or woken up. - /// If you pass a flag of true, all fixtures will be added to the - /// broad-phase. - /// If you pass a flag of false, all fixtures will be removed from - /// the broad-phase and all contacts will be destroyed. - /// Fixtures and joints are otherwise unaffected. You may continue - /// to create/destroy fixtures and joints on inactive bodies. - /// Fixtures on an inactive body are implicitly inactive and will - /// not participate in collisions, ray-casts, or queries. - /// Joints connected to an inactive body are implicitly inactive. - /// An inactive body is still owned by a b2World object and remains - /// in the body list. - void SetActive(bool flag); - - /// Get the active state of the body. - bool IsActive() const; - - /// Set this body to have fixed rotation. This causes the mass - /// to be reset. - void SetFixedRotation(bool flag); - - /// Does this body have fixed rotation? - bool IsFixedRotation() const; - - /// Get the list of all fixtures attached to this body. - b2Fixture* GetFixtureList(); - const b2Fixture* GetFixtureList() const; - - /// Get the list of all joints attached to this body. - b2JointEdge* GetJointList(); - const b2JointEdge* GetJointList() const; - - /// Get the list of all contacts attached to this body. - /// @warning this list changes during the time step and you may - /// miss some collisions if you don't use b2ContactListener. - b2ContactEdge* GetContactList(); - const b2ContactEdge* GetContactList() const; - - /// Get the next body in the world's body list. - b2Body* GetNext(); - const b2Body* GetNext() const; - - /// Get the user data pointer that was provided in the body definition. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Get the parent world of this body. - b2World* GetWorld(); - const b2World* GetWorld() const; - - /// Dump this body to a log file - void Dump(); - -private: - - friend class b2World; - friend class b2Island; - friend class b2ContactManager; - friend class b2ContactSolver; - friend class b2Contact; - - friend class b2DistanceJoint; - friend class b2GearJoint; - friend class b2WheelJoint; - friend class b2MouseJoint; - friend class b2PrismaticJoint; - friend class b2PulleyJoint; - friend class b2RevoluteJoint; - friend class b2WeldJoint; - friend class b2FrictionJoint; - friend class b2RopeJoint; - - // m_flags - enum - { - e_islandFlag = 0x0001, - e_awakeFlag = 0x0002, - e_autoSleepFlag = 0x0004, - e_bulletFlag = 0x0008, - e_fixedRotationFlag = 0x0010, - e_activeFlag = 0x0020, - e_toiFlag = 0x0040 - }; - - b2Body(const b2BodyDef* bd, b2World* world); - ~b2Body(); - - void SynchronizeFixtures(); - void SynchronizeTransform(); - - // This is used to prevent connected bodies from colliding. - // It may lie, depending on the collideConnected flag. - bool ShouldCollide(const b2Body* other) const; - - void Advance(float32 t); - - b2BodyType m_type; - - uint16 m_flags; - - int32 m_islandIndex; - - b2Transform m_xf; // the body origin transform - b2Sweep m_sweep; // the swept motion for CCD - - b2Vec2 m_linearVelocity; - float32 m_angularVelocity; - - b2Vec2 m_force; - float32 m_torque; - - b2World* m_world; - b2Body* m_prev; - b2Body* m_next; - - b2Fixture* m_fixtureList; - int32 m_fixtureCount; - - b2JointEdge* m_jointList; - b2ContactEdge* m_contactList; - - float32 m_mass, m_invMass; - - // Rotational inertia about the center of mass. - float32 m_I, m_invI; - - float32 m_linearDamping; - float32 m_angularDamping; - float32 m_gravityScale; - - float32 m_sleepTime; - - void* m_userData; -}; - -inline b2BodyType b2Body::GetType() const -{ - return m_type; -} - -inline const b2Transform& b2Body::GetTransform() const -{ - return m_xf; -} - -inline const b2Vec2& b2Body::GetPosition() const -{ - return m_xf.p; -} - -inline float32 b2Body::GetAngle() const -{ - return m_sweep.a; -} - -inline const b2Vec2& b2Body::GetWorldCenter() const -{ - return m_sweep.c; -} - -inline const b2Vec2& b2Body::GetLocalCenter() const -{ - return m_sweep.localCenter; -} - -inline void b2Body::SetLinearVelocity(const b2Vec2& v) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (b2Dot(v,v) > 0.0f) - { - SetAwake(true); - } - - m_linearVelocity = v; -} - -inline b2Vec2 b2Body::GetLinearVelocity() const -{ - return m_linearVelocity; -} - -inline void b2Body::SetAngularVelocity(float32 w) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (w * w > 0.0f) - { - SetAwake(true); - } - - m_angularVelocity = w; -} - -inline float32 b2Body::GetAngularVelocity() const -{ - return m_angularVelocity; -} - -inline float32 b2Body::GetMass() const -{ - return m_mass; -} - -inline float32 b2Body::GetInertia() const -{ - return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); -} - -inline void b2Body::GetMassData(b2MassData* data) const -{ - data->mass = m_mass; - data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); - data->center = m_sweep.localCenter; -} - -inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const -{ - return b2Mul(m_xf, localPoint); -} - -inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const -{ - return b2Mul(m_xf.q, localVector); -} - -inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const -{ - return b2MulT(m_xf, worldPoint); -} - -inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const -{ - return b2MulT(m_xf.q, worldVector); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const -{ - return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const -{ - return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); -} - -inline float32 b2Body::GetLinearDamping() const -{ - return m_linearDamping; -} - -inline void b2Body::SetLinearDamping(float32 linearDamping) -{ - m_linearDamping = linearDamping; -} - -inline float32 b2Body::GetAngularDamping() const -{ - return m_angularDamping; -} - -inline void b2Body::SetAngularDamping(float32 angularDamping) -{ - m_angularDamping = angularDamping; -} - -inline float32 b2Body::GetGravityScale() const -{ - return m_gravityScale; -} - -inline void b2Body::SetGravityScale(float32 scale) -{ - m_gravityScale = scale; -} - -inline void b2Body::SetBullet(bool flag) -{ - if (flag) - { - m_flags |= e_bulletFlag; - } - else - { - m_flags &= ~e_bulletFlag; - } -} - -inline bool b2Body::IsBullet() const -{ - return (m_flags & e_bulletFlag) == e_bulletFlag; -} - -inline void b2Body::SetAwake(bool flag) -{ - if (flag) - { - if ((m_flags & e_awakeFlag) == 0) - { - m_flags |= e_awakeFlag; - m_sleepTime = 0.0f; - } - } - else - { - m_flags &= ~e_awakeFlag; - m_sleepTime = 0.0f; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_force.SetZero(); - m_torque = 0.0f; - } -} - -inline bool b2Body::IsAwake() const -{ - return (m_flags & e_awakeFlag) == e_awakeFlag; -} - -inline bool b2Body::IsActive() const -{ - return (m_flags & e_activeFlag) == e_activeFlag; -} - -inline void b2Body::SetFixedRotation(bool flag) -{ - if (flag) - { - m_flags |= e_fixedRotationFlag; - } - else - { - m_flags &= ~e_fixedRotationFlag; - } - - ResetMassData(); -} - -inline bool b2Body::IsFixedRotation() const -{ - return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; -} - -inline void b2Body::SetSleepingAllowed(bool flag) -{ - if (flag) - { - m_flags |= e_autoSleepFlag; - } - else - { - m_flags &= ~e_autoSleepFlag; - SetAwake(true); - } -} - -inline bool b2Body::IsSleepingAllowed() const -{ - return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; -} - -inline b2Fixture* b2Body::GetFixtureList() -{ - return m_fixtureList; -} - -inline const b2Fixture* b2Body::GetFixtureList() const -{ - return m_fixtureList; -} - -inline b2JointEdge* b2Body::GetJointList() -{ - return m_jointList; -} - -inline const b2JointEdge* b2Body::GetJointList() const -{ - return m_jointList; -} - -inline b2ContactEdge* b2Body::GetContactList() -{ - return m_contactList; -} - -inline const b2ContactEdge* b2Body::GetContactList() const -{ - return m_contactList; -} - -inline b2Body* b2Body::GetNext() -{ - return m_next; -} - -inline const b2Body* b2Body::GetNext() const -{ - return m_next; -} - -inline void b2Body::SetUserData(void* data) -{ - m_userData = data; -} - -inline void* b2Body::GetUserData() const -{ - return m_userData; -} - -inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_force += force; - m_torque += b2Cross(point - m_sweep.c, force); -} - -inline void b2Body::ApplyForceToCenter(const b2Vec2& force) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_force += force; -} - -inline void b2Body::ApplyTorque(float32 torque) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - - m_torque += torque; -} - -inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - m_linearVelocity += m_invMass * impulse; - m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); -} - -inline void b2Body::ApplyAngularImpulse(float32 impulse) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (IsAwake() == false) - { - SetAwake(true); - } - m_angularVelocity += m_invI * impulse; -} - -inline void b2Body::SynchronizeTransform() -{ - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline void b2Body::Advance(float32 alpha) -{ - // Advance to the new safe time. This doesn't sync the broad-phase. - m_sweep.Advance(alpha); - m_sweep.c = m_sweep.c0; - m_sweep.a = m_sweep.a0; - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline b2World* b2Body::GetWorld() -{ - return m_world; -} - -inline const b2World* b2Body::GetWorld() const -{ - return m_world; -} - -#endif diff --git a/external/box2d/Dynamics/b2ContactManager.cpp b/external/box2d/Dynamics/b2ContactManager.cpp deleted file mode 100644 index c14cc4ce45..0000000000 --- a/external/box2d/Dynamics/b2ContactManager.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include - -b2ContactFilter b2_defaultFilter; -b2ContactListener b2_defaultListener; - -b2ContactManager::b2ContactManager() -{ - m_contactList = NULL; - m_contactCount = 0; - m_contactFilter = &b2_defaultFilter; - m_contactListener = &b2_defaultListener; - m_allocator = NULL; -} - -void b2ContactManager::Destroy(b2Contact* c) -{ - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - if (m_contactListener && c->IsTouching()) - { - m_contactListener->EndContact(c); - } - - // Remove from the world. - if (c->m_prev) - { - c->m_prev->m_next = c->m_next; - } - - if (c->m_next) - { - c->m_next->m_prev = c->m_prev; - } - - if (c == m_contactList) - { - m_contactList = c->m_next; - } - - // Remove from body 1 - if (c->m_nodeA.prev) - { - c->m_nodeA.prev->next = c->m_nodeA.next; - } - - if (c->m_nodeA.next) - { - c->m_nodeA.next->prev = c->m_nodeA.prev; - } - - if (&c->m_nodeA == bodyA->m_contactList) - { - bodyA->m_contactList = c->m_nodeA.next; - } - - // Remove from body 2 - if (c->m_nodeB.prev) - { - c->m_nodeB.prev->next = c->m_nodeB.next; - } - - if (c->m_nodeB.next) - { - c->m_nodeB.next->prev = c->m_nodeB.prev; - } - - if (&c->m_nodeB == bodyB->m_contactList) - { - bodyB->m_contactList = c->m_nodeB.next; - } - - // Call the factory. - b2Contact::Destroy(c, m_allocator); - --m_contactCount; -} - -// This is the top level collision call for the time step. Here -// all the narrow phase collision is processed for the world -// contact list. -void b2ContactManager::Collide() -{ - // Update awake contacts. - b2Contact* c = m_contactList; - while (c) - { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Is this contact flagged for filtering? - if (c->m_flags & b2Contact::e_filterFlag) - { - // Should these bodies collide? - if (bodyB->ShouldCollide(bodyA) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Clear the filtering flag. - c->m_flags &= ~b2Contact::e_filterFlag; - } - - bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; - bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - - // At least one body must be awake and it must be dynamic or kinematic. - if (activeA == false && activeB == false) - { - c = c->GetNext(); - continue; - } - - int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; - int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; - bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); - - // Here we destroy contacts that cease to overlap in the broad-phase. - if (overlap == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // The contact persists. - c->Update(m_contactListener); - c = c->GetNext(); - } -} - -void b2ContactManager::FindNewContacts() -{ - m_broadPhase.UpdatePairs(this); -} - -void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) -{ - b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; - b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; - - b2Fixture* fixtureA = proxyA->fixture; - b2Fixture* fixtureB = proxyB->fixture; - - int32 indexA = proxyA->childIndex; - int32 indexB = proxyB->childIndex; - - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Are the fixtures on the same body? - if (bodyA == bodyB) - { - return; - } - - // TODO_ERIN use a hash table to remove a potential bottleneck when both - // bodies have a lot of contacts. - // Does a contact already exist? - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - b2Fixture* fA = edge->contact->GetFixtureA(); - b2Fixture* fB = edge->contact->GetFixtureB(); - int32 iA = edge->contact->GetChildIndexA(); - int32 iB = edge->contact->GetChildIndexB(); - - if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) - { - // A contact already exists. - return; - } - - if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) - { - // A contact already exists. - return; - } - } - - edge = edge->next; - } - - // Does a joint override collision? Is at least one body dynamic? - if (bodyB->ShouldCollide(bodyA) == false) - { - return; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - return; - } - - // Call the factory. - b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); - if (c == NULL) - { - return; - } - - // Contact creation may swap fixtures. - fixtureA = c->GetFixtureA(); - fixtureB = c->GetFixtureB(); - indexA = c->GetChildIndexA(); - indexB = c->GetChildIndexB(); - bodyA = fixtureA->GetBody(); - bodyB = fixtureB->GetBody(); - - // Insert into the world. - c->m_prev = NULL; - c->m_next = m_contactList; - if (m_contactList != NULL) - { - m_contactList->m_prev = c; - } - m_contactList = c; - - // Connect to island graph. - - // Connect to body A - c->m_nodeA.contact = c; - c->m_nodeA.other = bodyB; - - c->m_nodeA.prev = NULL; - c->m_nodeA.next = bodyA->m_contactList; - if (bodyA->m_contactList != NULL) - { - bodyA->m_contactList->prev = &c->m_nodeA; - } - bodyA->m_contactList = &c->m_nodeA; - - // Connect to body B - c->m_nodeB.contact = c; - c->m_nodeB.other = bodyA; - - c->m_nodeB.prev = NULL; - c->m_nodeB.next = bodyB->m_contactList; - if (bodyB->m_contactList != NULL) - { - bodyB->m_contactList->prev = &c->m_nodeB; - } - bodyB->m_contactList = &c->m_nodeB; - - // Wake up the bodies - bodyA->SetAwake(true); - bodyB->SetAwake(true); - - ++m_contactCount; -} diff --git a/external/box2d/Dynamics/b2ContactManager.h b/external/box2d/Dynamics/b2ContactManager.h deleted file mode 100644 index 9cb5718145..0000000000 --- a/external/box2d/Dynamics/b2ContactManager.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_CONTACT_MANAGER_H -#define B2_CONTACT_MANAGER_H - -#include - -class b2Contact; -class b2ContactFilter; -class b2ContactListener; -class b2BlockAllocator; - -// Delegate of b2World. -class b2ContactManager -{ -public: - b2ContactManager(); - - // Broad-phase callback. - void AddPair(void* proxyUserDataA, void* proxyUserDataB); - - void FindNewContacts(); - - void Destroy(b2Contact* c); - - void Collide(); - - b2BroadPhase m_broadPhase; - b2Contact* m_contactList; - int32 m_contactCount; - b2ContactFilter* m_contactFilter; - b2ContactListener* m_contactListener; - b2BlockAllocator* m_allocator; -}; - -#endif diff --git a/external/box2d/Dynamics/b2Fixture.cpp b/external/box2d/Dynamics/b2Fixture.cpp deleted file mode 100644 index 774a78e5bb..0000000000 --- a/external/box2d/Dynamics/b2Fixture.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -b2Fixture::b2Fixture() -{ - m_userData = NULL; - m_body = NULL; - m_next = NULL; - m_proxies = NULL; - m_proxyCount = 0; - m_shape = NULL; - m_density = 0.0f; -} - -void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) -{ - m_userData = def->userData; - m_friction = def->friction; - m_restitution = def->restitution; - - m_body = body; - m_next = NULL; - - m_filter = def->filter; - - m_isSensor = def->isSensor; - - m_shape = def->shape->Clone(allocator); - - // Reserve proxy space - int32 childCount = m_shape->GetChildCount(); - m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); - for (int32 i = 0; i < childCount; ++i) - { - m_proxies[i].fixture = NULL; - m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; - } - m_proxyCount = 0; - - m_density = def->density; -} - -void b2Fixture::Destroy(b2BlockAllocator* allocator) -{ - // The proxies must be destroyed before calling this. - b2Assert(m_proxyCount == 0); - - // Free the proxy array. - int32 childCount = m_shape->GetChildCount(); - allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); - m_proxies = NULL; - - // Free the child shape. - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - s->~b2CircleShape(); - allocator->Free(s, sizeof(b2CircleShape)); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - s->~b2EdgeShape(); - allocator->Free(s, sizeof(b2EdgeShape)); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - s->~b2PolygonShape(); - allocator->Free(s, sizeof(b2PolygonShape)); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - s->~b2ChainShape(); - allocator->Free(s, sizeof(b2ChainShape)); - } - break; - - default: - b2Assert(false); - break; - } - - m_shape = NULL; -} - -void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) -{ - b2Assert(m_proxyCount == 0); - - // Create proxies in the broad-phase. - m_proxyCount = m_shape->GetChildCount(); - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - m_shape->ComputeAABB(&proxy->aabb, xf, i); - proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); - proxy->fixture = this; - proxy->childIndex = i; - } -} - -void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) -{ - // Destroy proxies in the broad-phase. - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - broadPhase->DestroyProxy(proxy->proxyId); - proxy->proxyId = b2BroadPhase::e_nullProxy; - } - - m_proxyCount = 0; -} - -void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) -{ - if (m_proxyCount == 0) - { - return; - } - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb1, aabb2; - m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); - m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); - - proxy->aabb.Combine(aabb1, aabb2); - - b2Vec2 displacement = transform2.p - transform1.p; - - broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); - } -} - -void b2Fixture::SetFilterData(const b2Filter& filter) -{ - m_filter = filter; - - Refilter(); -} - -void b2Fixture::Refilter() -{ - if (m_body == NULL) - { - return; - } - - // Flag associated contacts for filtering. - b2ContactEdge* edge = m_body->GetContactList(); - while (edge) - { - b2Contact* contact = edge->contact; - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == this || fixtureB == this) - { - contact->FlagForFiltering(); - } - - edge = edge->next; - } - - b2World* world = m_body->GetWorld(); - - if (world == NULL) - { - return; - } - - // Touch each proxy so that new pairs may be created - b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; - for (int32 i = 0; i < m_proxyCount; ++i) - { - broadPhase->TouchProxy(m_proxies[i].proxyId); - } -} - -void b2Fixture::SetSensor(bool sensor) -{ - if (sensor != m_isSensor) - { - m_body->SetAwake(true); - m_isSensor = sensor; - } -} - -void b2Fixture::Dump(int32 bodyIndex) -{ - b2Log(" b2FixtureDef fd;\n"); - b2Log(" fd.friction = %.15lef;\n", m_friction); - b2Log(" fd.restitution = %.15lef;\n", m_restitution); - b2Log(" fd.density = %.15lef;\n", m_density); - b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); - b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); - b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); - b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); - - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - b2Log(" b2CircleShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - b2Log(" b2EdgeShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); - b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); - b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); - b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); - b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); - b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - b2Log(" b2PolygonShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); - for (int32 i = 0; i < s->m_vertexCount; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - b2Log(" b2ChainShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", s->m_count); - for (int32 i = 0; i < s->m_count; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); - b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); - b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); - b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); - b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); - } - break; - - default: - return; - } - - b2Log("\n"); - b2Log(" fd.shape = &shape;\n"); - b2Log("\n"); - b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); -} diff --git a/external/box2d/Dynamics/b2Fixture.h b/external/box2d/Dynamics/b2Fixture.h deleted file mode 100644 index d390410b93..0000000000 --- a/external/box2d/Dynamics/b2Fixture.h +++ /dev/null @@ -1,345 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_FIXTURE_H -#define B2_FIXTURE_H - -#include -#include -#include - -class b2BlockAllocator; -class b2Body; -class b2BroadPhase; -class b2Fixture; - -/// This holds contact filtering data. -struct b2Filter -{ - b2Filter() - { - categoryBits = 0x0001; - maskBits = 0xFFFF; - groupIndex = 0; - } - - /// The collision category bits. Normally you would just set one bit. - uint16 categoryBits; - - /// The collision mask bits. This states the categories that this - /// shape would accept for collision. - uint16 maskBits; - - /// Collision groups allow a certain group of objects to never collide (negative) - /// or always collide (positive). Zero means no collision group. Non-zero group - /// filtering always wins against the mask bits. - int16 groupIndex; -}; - -/// A fixture definition is used to create a fixture. This class defines an -/// abstract fixture definition. You can reuse fixture definitions safely. -struct b2FixtureDef -{ - /// The constructor sets the default fixture definition values. - b2FixtureDef() - { - shape = NULL; - userData = NULL; - friction = 0.2f; - restitution = 0.0f; - density = 0.0f; - isSensor = false; - } - - /// The shape, this must be set. The shape will be cloned, so you - /// can create the shape on the stack. - const b2Shape* shape; - - /// Use this to store application specific fixture data. - void* userData; - - /// The friction coefficient, usually in the range [0,1]. - float32 friction; - - /// The restitution (elasticity) usually in the range [0,1]. - float32 restitution; - - /// The density, usually in kg/m^2. - float32 density; - - /// A sensor shape collects contact information but never generates a collision - /// response. - bool isSensor; - - /// Contact filtering data. - b2Filter filter; -}; - -/// This proxy is used internally to connect fixtures to the broad-phase. -struct b2FixtureProxy -{ - b2AABB aabb; - b2Fixture* fixture; - int32 childIndex; - int32 proxyId; -}; - -/// A fixture is used to attach a shape to a body for collision detection. A fixture -/// inherits its transform from its parent. Fixtures hold additional non-geometric data -/// such as friction, collision filters, etc. -/// Fixtures are created via b2Body::CreateFixture. -/// @warning you cannot reuse fixtures. -class b2Fixture -{ -public: - /// Get the type of the child shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - b2Shape::Type GetType() const; - - /// Get the child shape. You can modify the child shape, however you should not change the - /// number of vertices because this will crash some collision caching mechanisms. - /// Manipulating the shape may lead to non-physical behavior. - b2Shape* GetShape(); - const b2Shape* GetShape() const; - - /// Set if this fixture is a sensor. - void SetSensor(bool sensor); - - /// Is this fixture a sensor (non-solid)? - /// @return the true if the shape is a sensor. - bool IsSensor() const; - - /// Set the contact filtering data. This will not update contacts until the next time - /// step when either parent body is active and awake. - /// This automatically calls Refilter. - void SetFilterData(const b2Filter& filter); - - /// Get the contact filtering data. - const b2Filter& GetFilterData() const; - - /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. - void Refilter(); - - /// Get the parent body of this fixture. This is NULL if the fixture is not attached. - /// @return the parent body. - b2Body* GetBody(); - const b2Body* GetBody() const; - - /// Get the next fixture in the parent body's fixture list. - /// @return the next shape. - b2Fixture* GetNext(); - const b2Fixture* GetNext() const; - - /// Get the user data that was assigned in the fixture definition. Use this to - /// store your application specific data. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Test a point for containment in this fixture. - /// @param p a point in world coordinates. - bool TestPoint(const b2Vec2& p) const; - - /// Cast a ray against this shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; - - /// Get the mass data for this fixture. The mass data is based on the density and - /// the shape. The rotational inertia is about the shape's origin. This operation - /// may be expensive. - void GetMassData(b2MassData* massData) const; - - /// Set the density of this fixture. This will _not_ automatically adjust the mass - /// of the body. You must call b2Body::ResetMassData to update the body's mass. - void SetDensity(float32 density); - - /// Get the density of this fixture. - float32 GetDensity() const; - - /// Get the coefficient of friction. - float32 GetFriction() const; - - /// Set the coefficient of friction. This will _not_ change the friction of - /// existing contacts. - void SetFriction(float32 friction); - - /// Get the coefficient of restitution. - float32 GetRestitution() const; - - /// Set the coefficient of restitution. This will _not_ change the restitution of - /// existing contacts. - void SetRestitution(float32 restitution); - - /// Get the fixture's AABB. This AABB may be enlarge and/or stale. - /// If you need a more accurate AABB, compute it using the shape and - /// the body transform. - const b2AABB& GetAABB(int32 childIndex) const; - - /// Dump this fixture to the log file. - void Dump(int32 bodyIndex); - -protected: - - friend class b2Body; - friend class b2World; - friend class b2Contact; - friend class b2ContactManager; - - b2Fixture(); - - // We need separation create/destroy functions from the constructor/destructor because - // the destructor cannot access the allocator (no destructor arguments allowed by C++). - void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); - void Destroy(b2BlockAllocator* allocator); - - // These support body activation/deactivation. - void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); - void DestroyProxies(b2BroadPhase* broadPhase); - - void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); - - float32 m_density; - - b2Fixture* m_next; - b2Body* m_body; - - b2Shape* m_shape; - - float32 m_friction; - float32 m_restitution; - - b2FixtureProxy* m_proxies; - int32 m_proxyCount; - - b2Filter m_filter; - - bool m_isSensor; - - void* m_userData; -}; - -inline b2Shape::Type b2Fixture::GetType() const -{ - return m_shape->GetType(); -} - -inline b2Shape* b2Fixture::GetShape() -{ - return m_shape; -} - -inline const b2Shape* b2Fixture::GetShape() const -{ - return m_shape; -} - -inline bool b2Fixture::IsSensor() const -{ - return m_isSensor; -} - -inline const b2Filter& b2Fixture::GetFilterData() const -{ - return m_filter; -} - -inline void* b2Fixture::GetUserData() const -{ - return m_userData; -} - -inline void b2Fixture::SetUserData(void* data) -{ - m_userData = data; -} - -inline b2Body* b2Fixture::GetBody() -{ - return m_body; -} - -inline const b2Body* b2Fixture::GetBody() const -{ - return m_body; -} - -inline b2Fixture* b2Fixture::GetNext() -{ - return m_next; -} - -inline const b2Fixture* b2Fixture::GetNext() const -{ - return m_next; -} - -inline void b2Fixture::SetDensity(float32 density) -{ - b2Assert(b2IsValid(density) && density >= 0.0f); - m_density = density; -} - -inline float32 b2Fixture::GetDensity() const -{ - return m_density; -} - -inline float32 b2Fixture::GetFriction() const -{ - return m_friction; -} - -inline void b2Fixture::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Fixture::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Fixture::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline bool b2Fixture::TestPoint(const b2Vec2& p) const -{ - return m_shape->TestPoint(m_body->GetTransform(), p); -} - -inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const -{ - return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); -} - -inline void b2Fixture::GetMassData(b2MassData* massData) const -{ - m_shape->ComputeMass(massData, m_density); -} - -inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const -{ - b2Assert(0 <= childIndex && childIndex < m_proxyCount); - return m_proxies[childIndex].aabb; -} - -#endif diff --git a/external/box2d/Dynamics/b2Island.cpp b/external/box2d/Dynamics/b2Island.cpp deleted file mode 100644 index e767d383d5..0000000000 --- a/external/box2d/Dynamics/b2Island.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* -Position Correction Notes -========================= -I tried the several algorithms for position correction of the 2D revolute joint. -I looked at these systems: -- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. -- suspension bridge with 30 1m long planks of length 1m. -- multi-link chain with 30 1m long links. - -Here are the algorithms: - -Baumgarte - A fraction of the position error is added to the velocity error. There is no -separate position solver. - -Pseudo Velocities - After the velocity solver and position integration, -the position error, Jacobian, and effective mass are recomputed. Then -the velocity constraints are solved with pseudo velocities and a fraction -of the position error is added to the pseudo velocity error. The pseudo -velocities are initialized to zero and there is no warm-starting. After -the position solver, the pseudo velocities are added to the positions. -This is also called the First Order World method or the Position LCP method. - -Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the -position error is re-computed for each constraint and the positions are updated -after the constraint is solved. The radius vectors (aka Jacobians) are -re-computed too (otherwise the algorithm has horrible instability). The pseudo -velocity states are not needed because they are effectively zero at the beginning -of each iteration. Since we have the current position error, we allow the -iterations to terminate early if the error becomes smaller than b2_linearSlop. - -Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed -each time a constraint is solved. - -Here are the results: -Baumgarte - this is the cheapest algorithm but it has some stability problems, -especially with the bridge. The chain links separate easily close to the root -and they jitter as they struggle to pull together. This is one of the most common -methods in the field. The big drawback is that the position correction artificially -affects the momentum, thus leading to instabilities and false bounce. I used a -bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller -factor makes joints and contacts more spongy. - -Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is -stable. However, joints still separate with large angular velocities. Drag the -simple pendulum in a circle quickly and the joint will separate. The chain separates -easily and does not recover. I used a bias factor of 0.2. A larger value lead to -the bridge collapsing when a heavy cube drops on it. - -Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo -Velocities, but in other ways it is worse. The bridge and chain are much more -stable, but the simple pendulum goes unstable at high angular velocities. - -Full NGS - stable in all tests. The joints display good stiffness. The bridge -still sags, but this is better than infinite forces. - -Recommendations -Pseudo Velocities are not really worthwhile because the bridge and chain cannot -recover from joint separation. In other cases the benefit over Baumgarte is small. - -Modified NGS is not a robust method for the revolute joint due to the violent -instability seen in the simple pendulum. Perhaps it is viable with other constraint -types, especially scalar constraints where the effective mass is a scalar. - -This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities -and is very fast. I don't think we can escape Baumgarte, especially in highly -demanding cases where high constraint fidelity is not needed. - -Full NGS is robust and easy on the eyes. I recommend this as an option for -higher fidelity simulation and certainly for suspension bridges and long chains. -Full NGS might be a good choice for ragdolls, especially motorized ragdolls where -joint separation can be problematic. The number of NGS iterations can be reduced -for better performance without harming robustness much. - -Each joint in a can be handled differently in the position solver. So I recommend -a system where the user can select the algorithm on a per joint basis. I would -probably default to the slower Full NGS and let the user select the faster -Baumgarte method in performance critical scenarios. -*/ - -/* -Cache Performance - -The Box2D solvers are dominated by cache misses. Data structures are designed -to increase the number of cache hits. Much of misses are due to random access -to body data. The constraint structures are iterated over linearly, which leads -to few cache misses. - -The bodies are not accessed during iteration. Instead read only data, such as -the mass values are stored with the constraints. The mutable data are the constraint -impulses and the bodies velocities/positions. The impulses are held inside the -constraint structures. The body velocities/positions are held in compact, temporary -arrays to increase the number of cache hits. Linear and angular velocity are -stored in a single array since multiple arrays lead to multiple misses. -*/ - -/* -2D Rotation - -R = [cos(theta) -sin(theta)] - [sin(theta) cos(theta) ] - -thetaDot = omega - -Let q1 = cos(theta), q2 = sin(theta). -R = [q1 -q2] - [q2 q1] - -q1Dot = -thetaDot * q2 -q2Dot = thetaDot * q1 - -q1_new = q1_old - dt * w * q2 -q2_new = q2_old + dt * w * q1 -then normalize. - -This might be faster than computing sin+cos. -However, we can compute sin+cos of the same angle fast. -*/ - -b2Island::b2Island( - int32 bodyCapacity, - int32 contactCapacity, - int32 jointCapacity, - b2StackAllocator* allocator, - b2ContactListener* listener) -{ - m_bodyCapacity = bodyCapacity; - m_contactCapacity = contactCapacity; - m_jointCapacity = jointCapacity; - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - - m_allocator = allocator; - m_listener = listener; - - m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); - m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); - m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); - - m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); - m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); -} - -b2Island::~b2Island() -{ - // Warning: the order should reverse the constructor order. - m_allocator->Free(m_positions); - m_allocator->Free(m_velocities); - m_allocator->Free(m_joints); - m_allocator->Free(m_contacts); - m_allocator->Free(m_bodies); -} - -void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) -{ - b2Timer timer; - - float32 h = step.dt; - - // Integrate velocities and apply damping. Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - - b2Vec2 c = b->m_sweep.c; - float32 a = b->m_sweep.a; - b2Vec2 v = b->m_linearVelocity; - float32 w = b->m_angularVelocity; - - // Store positions for continuous collision. - b->m_sweep.c0 = b->m_sweep.c; - b->m_sweep.a0 = b->m_sweep.a; - - if (b->m_type == b2_dynamicBody) - { - // Integrate velocities. - v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); - w += h * b->m_invI * b->m_torque; - - // Apply damping. - // ODE: dv/dt + c * v = 0 - // Solution: v(t) = v0 * exp(-c * t) - // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) - // v2 = exp(-c * dt) * v1 - // Taylor expansion: - // v2 = (1.0f - c * dt) * v1 - v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); - w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); - } - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - timer.Reset(); - - // Solver data - b2SolverData solverData; - solverData.step = step; - solverData.positions = m_positions; - solverData.velocities = m_velocities; - - // Initialize velocity constraints. - b2ContactSolverDef contactSolverDef; - contactSolverDef.step = step; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - contactSolverDef.allocator = m_allocator; - - b2ContactSolver contactSolver(&contactSolverDef); - contactSolver.InitializeVelocityConstraints(); - - if (step.warmStarting) - { - contactSolver.WarmStart(); - } - - for (int32 i = 0; i < m_jointCount; ++i) - { - m_joints[i]->InitVelocityConstraints(solverData); - } - - profile->solveInit = timer.GetMilliseconds(); - - // Solve velocity constraints - timer.Reset(); - for (int32 i = 0; i < step.velocityIterations; ++i) - { - for (int32 j = 0; j < m_jointCount; ++j) - { - m_joints[j]->SolveVelocityConstraints(solverData); - } - - contactSolver.SolveVelocityConstraints(); - } - - // Store impulses for warm starting - contactSolver.StoreImpulses(); - profile->solveVelocity = timer.GetMilliseconds(); - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - // Solve position constraints - timer.Reset(); - bool positionSolved = false; - for (int32 i = 0; i < step.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolvePositionConstraints(); - - bool jointsOkay = true; - for (int32 i = 0; i < m_jointCount; ++i) - { - bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); - jointsOkay = jointsOkay && jointOkay; - } - - if (contactsOkay && jointsOkay) - { - // Exit early if the position errors are small. - positionSolved = true; - break; - } - } - - // Copy state buffers back to the bodies - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* body = m_bodies[i]; - body->m_sweep.c = m_positions[i].c; - body->m_sweep.a = m_positions[i].a; - body->m_linearVelocity = m_velocities[i].v; - body->m_angularVelocity = m_velocities[i].w; - body->SynchronizeTransform(); - } - - profile->solvePosition = timer.GetMilliseconds(); - - Report(contactSolver.m_velocityConstraints); - - if (allowSleep) - { - float32 minSleepTime = b2_maxFloat; - - const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; - const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; - - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - continue; - } - - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || - b->m_angularVelocity * b->m_angularVelocity > angTolSqr || - b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) - { - b->m_sleepTime = 0.0f; - minSleepTime = 0.0f; - } - else - { - b->m_sleepTime += h; - minSleepTime = b2Min(minSleepTime, b->m_sleepTime); - } - } - - if (minSleepTime >= b2_timeToSleep && positionSolved) - { - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - b->SetAwake(false); - } - } - } -} - -void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) -{ - b2Assert(toiIndexA < m_bodyCount); - b2Assert(toiIndexB < m_bodyCount); - - // Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - m_positions[i].c = b->m_sweep.c; - m_positions[i].a = b->m_sweep.a; - m_velocities[i].v = b->m_linearVelocity; - m_velocities[i].w = b->m_angularVelocity; - } - - b2ContactSolverDef contactSolverDef; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.allocator = m_allocator; - contactSolverDef.step = subStep; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - b2ContactSolver contactSolver(&contactSolverDef); - - // Solve position constraints. - for (int32 i = 0; i < subStep.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); - if (contactsOkay) - { - break; - } - } - -#if 0 - // Is the new position really safe? - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - b2DistanceInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.transformA = bA->GetTransform(); - input.transformB = bB->GetTransform(); - input.useRadii = false; - - b2DistanceOutput output; - b2SimplexCache cache; - cache.count = 0; - b2Distance(&output, &cache, &input); - - if (output.distance == 0 || cache.count == 3) - { - cache.count += 0; - } - } -#endif - - // Leap of faith to new safe state. - m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; - m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; - m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; - m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; - - // No warm starting is needed for TOI events because warm - // starting impulses were applied in the discrete solver. - contactSolver.InitializeVelocityConstraints(); - - // Solve velocity constraints. - for (int32 i = 0; i < subStep.velocityIterations; ++i) - { - contactSolver.SolveVelocityConstraints(); - } - - // Don't store the TOI contact forces for warm starting - // because they can be quite large. - - float32 h = subStep.dt; - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - - // Sync bodies - b2Body* body = m_bodies[i]; - body->m_sweep.c = c; - body->m_sweep.a = a; - body->m_linearVelocity = v; - body->m_angularVelocity = w; - body->SynchronizeTransform(); - } - - Report(contactSolver.m_velocityConstraints); -} - -void b2Island::Report(const b2ContactVelocityConstraint* constraints) -{ - if (m_listener == NULL) - { - return; - } - - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - - const b2ContactVelocityConstraint* vc = constraints + i; - - b2ContactImpulse impulse; - impulse.count = vc->pointCount; - for (int32 j = 0; j < vc->pointCount; ++j) - { - impulse.normalImpulses[j] = vc->points[j].normalImpulse; - impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; - } - - m_listener->PostSolve(c, &impulse); - } -} diff --git a/external/box2d/Dynamics/b2Island.h b/external/box2d/Dynamics/b2Island.h deleted file mode 100644 index e0a6e41fc3..0000000000 --- a/external/box2d/Dynamics/b2Island.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ISLAND_H -#define B2_ISLAND_H - -#include -#include -#include - -class b2Contact; -class b2Joint; -class b2StackAllocator; -class b2ContactListener; -struct b2ContactVelocityConstraint; -struct b2Profile; - -/// This is an internal class. -class b2Island -{ -public: - b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, - b2StackAllocator* allocator, b2ContactListener* listener); - ~b2Island(); - - void Clear() - { - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - } - - void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); - - void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); - - void Add(b2Body* body) - { - b2Assert(m_bodyCount < m_bodyCapacity); - body->m_islandIndex = m_bodyCount; - m_bodies[m_bodyCount] = body; - ++m_bodyCount; - } - - void Add(b2Contact* contact) - { - b2Assert(m_contactCount < m_contactCapacity); - m_contacts[m_contactCount++] = contact; - } - - void Add(b2Joint* joint) - { - b2Assert(m_jointCount < m_jointCapacity); - m_joints[m_jointCount++] = joint; - } - - void Report(const b2ContactVelocityConstraint* constraints); - - b2StackAllocator* m_allocator; - b2ContactListener* m_listener; - - b2Body** m_bodies; - b2Contact** m_contacts; - b2Joint** m_joints; - - b2Position* m_positions; - b2Velocity* m_velocities; - - int32 m_bodyCount; - int32 m_jointCount; - int32 m_contactCount; - - int32 m_bodyCapacity; - int32 m_contactCapacity; - int32 m_jointCapacity; -}; - -#endif diff --git a/external/box2d/Dynamics/b2TimeStep.h b/external/box2d/Dynamics/b2TimeStep.h deleted file mode 100644 index 30d723fcc3..0000000000 --- a/external/box2d/Dynamics/b2TimeStep.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_TIME_STEP_H -#define B2_TIME_STEP_H - -#include - -/// Profiling data. Times are in milliseconds. -struct b2Profile -{ - float32 step; - float32 collide; - float32 solve; - float32 solveInit; - float32 solveVelocity; - float32 solvePosition; - float32 broadphase; - float32 solveTOI; -}; - -/// This is an internal structure. -struct b2TimeStep -{ - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 velocityIterations; - int32 positionIterations; - bool warmStarting; -}; - -/// This is an internal structure. -struct b2Position -{ - b2Vec2 c; - float32 a; -}; - -/// This is an internal structure. -struct b2Velocity -{ - b2Vec2 v; - float32 w; -}; - -/// Solver Data -struct b2SolverData -{ - b2TimeStep step; - b2Position* positions; - b2Velocity* velocities; -}; - -#endif diff --git a/external/box2d/Dynamics/b2World.cpp b/external/box2d/Dynamics/b2World.cpp deleted file mode 100644 index 8a0aff5114..0000000000 --- a/external/box2d/Dynamics/b2World.cpp +++ /dev/null @@ -1,1316 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -b2World::b2World(const b2Vec2& gravity) -{ - m_destructionListener = NULL; - m_debugDraw = NULL; - - m_bodyList = NULL; - m_jointList = NULL; - - m_bodyCount = 0; - m_jointCount = 0; - - m_warmStarting = true; - m_continuousPhysics = true; - m_subStepping = false; - - m_stepComplete = true; - - m_allowSleep = true; - m_gravity = gravity; - - m_flags = e_clearForces; - - m_inv_dt0 = 0.0f; - - m_contactManager.m_allocator = &m_blockAllocator; - - memset(&m_profile, 0, sizeof(b2Profile)); -} - -b2World::~b2World() -{ - // Some shapes allocate using b2Alloc. - b2Body* b = m_bodyList; - while (b) - { - b2Body* bNext = b->m_next; - - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* fNext = f->m_next; - f->m_proxyCount = 0; - f->Destroy(&m_blockAllocator); - f = fNext; - } - - b = bNext; - } -} - -void b2World::SetDestructionListener(b2DestructionListener* listener) -{ - m_destructionListener = listener; -} - -void b2World::SetContactFilter(b2ContactFilter* filter) -{ - m_contactManager.m_contactFilter = filter; -} - -void b2World::SetContactListener(b2ContactListener* listener) -{ - m_contactManager.m_contactListener = listener; -} - -void b2World::SetDebugDraw(b2Draw* debugDraw) -{ - m_debugDraw = debugDraw; -} - -b2Body* b2World::CreateBody(const b2BodyDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } - - void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); - b2Body* b = new (mem) b2Body(def, this); - - // Add to world doubly linked list. - b->m_prev = NULL; - b->m_next = m_bodyList; - if (m_bodyList) - { - m_bodyList->m_prev = b; - } - m_bodyList = b; - ++m_bodyCount; - - return b; -} - -void b2World::DestroyBody(b2Body* b) -{ - b2Assert(m_bodyCount > 0); - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - // Delete the attached joints. - b2JointEdge* je = b->m_jointList; - while (je) - { - b2JointEdge* je0 = je; - je = je->next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(je0->joint); - } - - DestroyJoint(je0->joint); - - b->m_jointList = je; - } - b->m_jointList = NULL; - - // Delete the attached contacts. - b2ContactEdge* ce = b->m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_contactManager.Destroy(ce0->contact); - } - b->m_contactList = NULL; - - // Delete the attached fixtures. This destroys broad-phase proxies. - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* f0 = f; - f = f->m_next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(f0); - } - - f0->DestroyProxies(&m_contactManager.m_broadPhase); - f0->Destroy(&m_blockAllocator); - f0->~b2Fixture(); - m_blockAllocator.Free(f0, sizeof(b2Fixture)); - - b->m_fixtureList = f; - b->m_fixtureCount -= 1; - } - b->m_fixtureList = NULL; - b->m_fixtureCount = 0; - - // Remove world body list. - if (b->m_prev) - { - b->m_prev->m_next = b->m_next; - } - - if (b->m_next) - { - b->m_next->m_prev = b->m_prev; - } - - if (b == m_bodyList) - { - m_bodyList = b->m_next; - } - - --m_bodyCount; - b->~b2Body(); - m_blockAllocator.Free(b, sizeof(b2Body)); -} - -b2Joint* b2World::CreateJoint(const b2JointDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } - - b2Joint* j = b2Joint::Create(def, &m_blockAllocator); - - // Connect to the world list. - j->m_prev = NULL; - j->m_next = m_jointList; - if (m_jointList) - { - m_jointList->m_prev = j; - } - m_jointList = j; - ++m_jointCount; - - // Connect to the bodies' doubly linked lists. - j->m_edgeA.joint = j; - j->m_edgeA.other = j->m_bodyB; - j->m_edgeA.prev = NULL; - j->m_edgeA.next = j->m_bodyA->m_jointList; - if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; - j->m_bodyA->m_jointList = &j->m_edgeA; - - j->m_edgeB.joint = j; - j->m_edgeB.other = j->m_bodyA; - j->m_edgeB.prev = NULL; - j->m_edgeB.next = j->m_bodyB->m_jointList; - if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; - j->m_bodyB->m_jointList = &j->m_edgeB; - - b2Body* bodyA = def->bodyA; - b2Body* bodyB = def->bodyB; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (def->collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } - - // Note: creating a joint doesn't wake the bodies. - - return j; -} - -void b2World::DestroyJoint(b2Joint* j) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - bool collideConnected = j->m_collideConnected; - - // Remove from the doubly linked list. - if (j->m_prev) - { - j->m_prev->m_next = j->m_next; - } - - if (j->m_next) - { - j->m_next->m_prev = j->m_prev; - } - - if (j == m_jointList) - { - m_jointList = j->m_next; - } - - // Disconnect from island graph. - b2Body* bodyA = j->m_bodyA; - b2Body* bodyB = j->m_bodyB; - - // Wake up connected bodies. - bodyA->SetAwake(true); - bodyB->SetAwake(true); - - // Remove from body 1. - if (j->m_edgeA.prev) - { - j->m_edgeA.prev->next = j->m_edgeA.next; - } - - if (j->m_edgeA.next) - { - j->m_edgeA.next->prev = j->m_edgeA.prev; - } - - if (&j->m_edgeA == bodyA->m_jointList) - { - bodyA->m_jointList = j->m_edgeA.next; - } - - j->m_edgeA.prev = NULL; - j->m_edgeA.next = NULL; - - // Remove from body 2 - if (j->m_edgeB.prev) - { - j->m_edgeB.prev->next = j->m_edgeB.next; - } - - if (j->m_edgeB.next) - { - j->m_edgeB.next->prev = j->m_edgeB.prev; - } - - if (&j->m_edgeB == bodyB->m_jointList) - { - bodyB->m_jointList = j->m_edgeB.next; - } - - j->m_edgeB.prev = NULL; - j->m_edgeB.next = NULL; - - b2Joint::Destroy(j, &m_blockAllocator); - - b2Assert(m_jointCount > 0); - --m_jointCount; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } -} - -// -void b2World::SetAllowSleeping(bool flag) -{ - if (flag == m_allowSleep) - { - return; - } - - m_allowSleep = flag; - if (m_allowSleep == false) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->SetAwake(true); - } - } -} - -// Find islands, integrate and solve constraints, solve position constraints -void b2World::Solve(const b2TimeStep& step) -{ - m_profile.solveInit = 0.0f; - m_profile.solveVelocity = 0.0f; - m_profile.solvePosition = 0.0f; - - // Size the island for the worst case. - b2Island island(m_bodyCount, - m_contactManager.m_contactCount, - m_jointCount, - &m_stackAllocator, - m_contactManager.m_contactListener); - - // Clear all the island flags. - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - c->m_flags &= ~b2Contact::e_islandFlag; - } - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_islandFlag = false; - } - - // Build and simulate all awake islands. - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) - { - if (seed->m_flags & b2Body::e_islandFlag) - { - continue; - } - - if (seed->IsAwake() == false || seed->IsActive() == false) - { - continue; - } - - // The seed can be dynamic or kinematic. - if (seed->GetType() == b2_staticBody) - { - continue; - } - - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; - - // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - b2Assert(b->IsActive() == true); - island.Add(b); - - // Make sure the body is awake. - b->SetAwake(true); - - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Search all contacts connected to this body. - for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) - { - b2Contact* contact = ce->contact; - - // Has this contact already been added to an island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Is this contact solid and touching? - if (contact->IsEnabled() == false || - contact->IsTouching() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - island.Add(contact); - contact->m_flags |= b2Contact::e_islandFlag; - - b2Body* other = ce->other; - - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - - // Search all joints connect to this body. - for (b2JointEdge* je = b->m_jointList; je; je = je->next) - { - if (je->joint->m_islandFlag == true) - { - continue; - } - - b2Body* other = je->other; - - // Don't simulate joints connected to inactive bodies. - if (other->IsActive() == false) - { - continue; - } - - island.Add(je->joint); - je->joint->m_islandFlag = true; - - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } - - b2Profile profile; - island.Solve(&profile, step, m_gravity, m_allowSleep); - m_profile.solveInit += profile.solveInit; - m_profile.solveVelocity += profile.solveVelocity; - m_profile.solvePosition += profile.solvePosition; - - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow static bodies to participate in other islands. - b2Body* b = island.m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - } - } - - m_stackAllocator.Free(stack); - - { - b2Timer timer; - // Synchronize fixtures, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - // If a body was not in an island then it did not move. - if ((b->m_flags & b2Body::e_islandFlag) == 0) - { - continue; - } - - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Update fixtures (for broad-phase). - b->SynchronizeFixtures(); - } - - // Look for new contacts. - m_contactManager.FindNewContacts(); - m_profile.broadphase = timer.GetMilliseconds(); - } -} - -// Find TOI contacts and solve them. -void b2World::SolveTOI(const b2TimeStep& step) -{ - b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); - - if (m_stepComplete) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - b->m_sweep.alpha0 = 0.0f; - } - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Invalidate TOI - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - c->m_toiCount = 0; - c->m_toi = 1.0f; - } - } - - // Find TOI events and solve them. - for (;;) - { - // Find the first TOI. - b2Contact* minContact = NULL; - float32 minAlpha = 1.0f; - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Is this contact disabled? - if (c->IsEnabled() == false) - { - continue; - } - - // Prevent excessive sub-stepping. - if (c->m_toiCount > b2_maxSubSteps) - { - continue; - } - - float32 alpha = 1.0f; - if (c->m_flags & b2Contact::e_toiFlag) - { - // This contact has a valid cached TOI. - alpha = c->m_toi; - } - else - { - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - // Is there a sensor? - if (fA->IsSensor() || fB->IsSensor()) - { - continue; - } - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2BodyType typeA = bA->m_type; - b2BodyType typeB = bB->m_type; - b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); - - bool activeA = bA->IsAwake() && typeA != b2_staticBody; - bool activeB = bB->IsAwake() && typeB != b2_staticBody; - - // Is at least one body active (awake and dynamic or kinematic)? - if (activeA == false && activeB == false) - { - continue; - } - - bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; - bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; - - // Are these two non-bullet dynamic bodies? - if (collideA == false && collideB == false) - { - continue; - } - - // Compute the TOI for this contact. - // Put the sweeps onto the same time interval. - float32 alpha0 = bA->m_sweep.alpha0; - - if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) - { - alpha0 = bB->m_sweep.alpha0; - bA->m_sweep.Advance(alpha0); - } - else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) - { - alpha0 = bA->m_sweep.alpha0; - bB->m_sweep.Advance(alpha0); - } - - b2Assert(alpha0 < 1.0f); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - // Compute the time of impact in interval [0, minTOI] - b2TOIInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.sweepA = bA->m_sweep; - input.sweepB = bB->m_sweep; - input.tMax = 1.0f; - - b2TOIOutput output; - b2TimeOfImpact(&output, &input); - - // Beta is the fraction of the remaining portion of the . - float32 beta = output.t; - if (output.state == b2TOIOutput::e_touching) - { - alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); - } - else - { - alpha = 1.0f; - } - - c->m_toi = alpha; - c->m_flags |= b2Contact::e_toiFlag; - } - - if (alpha < minAlpha) - { - // This is the minimum TOI found so far. - minContact = c; - minAlpha = alpha; - } - } - - if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) - { - // No more TOI events. Done! - m_stepComplete = true; - break; - } - - // Advance the bodies to the TOI. - b2Fixture* fA = minContact->GetFixtureA(); - b2Fixture* fB = minContact->GetFixtureB(); - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2Sweep backup1 = bA->m_sweep; - b2Sweep backup2 = bB->m_sweep; - - bA->Advance(minAlpha); - bB->Advance(minAlpha); - - // The TOI contact likely has some new contact points. - minContact->Update(m_contactManager.m_contactListener); - minContact->m_flags &= ~b2Contact::e_toiFlag; - ++minContact->m_toiCount; - - // Is the contact solid? - if (minContact->IsEnabled() == false || minContact->IsTouching() == false) - { - // Restore the sweeps. - minContact->SetEnabled(false); - bA->m_sweep = backup1; - bB->m_sweep = backup2; - bA->SynchronizeTransform(); - bB->SynchronizeTransform(); - continue; - } - - bA->SetAwake(true); - bB->SetAwake(true); - - // Build the island - island.Clear(); - island.Add(bA); - island.Add(bB); - island.Add(minContact); - - bA->m_flags |= b2Body::e_islandFlag; - bB->m_flags |= b2Body::e_islandFlag; - minContact->m_flags |= b2Contact::e_islandFlag; - - // Get contacts on bodyA and bodyB. - b2Body* bodies[2] = {bA, bB}; - for (int32 i = 0; i < 2; ++i) - { - b2Body* body = bodies[i]; - if (body->m_type == b2_dynamicBody) - { - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - if (island.m_bodyCount == island.m_bodyCapacity) - { - break; - } - - if (island.m_contactCount == island.m_contactCapacity) - { - break; - } - - b2Contact* contact = ce->contact; - - // Has this contact already been added to the island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Only add static, kinematic, or bullet bodies. - b2Body* other = ce->other; - if (other->m_type == b2_dynamicBody && - body->IsBullet() == false && other->IsBullet() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - // Tentatively advance the body to the TOI. - b2Sweep backup = other->m_sweep; - if ((other->m_flags & b2Body::e_islandFlag) == 0) - { - other->Advance(minAlpha); - } - - // Update the contact points - contact->Update(m_contactManager.m_contactListener); - - // Was the contact disabled by the user? - if (contact->IsEnabled() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Are there contact points? - if (contact->IsTouching() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Add the contact to the island - contact->m_flags |= b2Contact::e_islandFlag; - island.Add(contact); - - // Has the other body already been added to the island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - // Add the other body to the island. - other->m_flags |= b2Body::e_islandFlag; - - if (other->m_type != b2_staticBody) - { - other->SetAwake(true); - } - - island.Add(other); - } - } - } - - b2TimeStep subStep; - subStep.dt = (1.0f - minAlpha) * step.dt; - subStep.inv_dt = 1.0f / subStep.dt; - subStep.dtRatio = 1.0f; - subStep.positionIterations = 20; - subStep.velocityIterations = step.velocityIterations; - subStep.warmStarting = false; - island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); - - // Reset island flags and synchronize broad-phase proxies. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - b2Body* body = island.m_bodies[i]; - body->m_flags &= ~b2Body::e_islandFlag; - - if (body->m_type != b2_dynamicBody) - { - continue; - } - - body->SynchronizeFixtures(); - - // Invalidate all contact TOIs on this displaced body. - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - } - - // Commit fixture proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_contactManager.FindNewContacts(); - - if (m_subStepping) - { - m_stepComplete = false; - break; - } - } -} - -void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) -{ - b2Timer stepTimer; - - // If new fixtures were added, we need to find the new contacts. - if (m_flags & e_newFixture) - { - m_contactManager.FindNewContacts(); - m_flags &= ~e_newFixture; - } - - m_flags |= e_locked; - - b2TimeStep step; - step.dt = dt; - step.velocityIterations = velocityIterations; - step.positionIterations = positionIterations; - if (dt > 0.0f) - { - step.inv_dt = 1.0f / dt; - } - else - { - step.inv_dt = 0.0f; - } - - step.dtRatio = m_inv_dt0 * dt; - - step.warmStarting = m_warmStarting; - - // Update contacts. This is where some contacts are destroyed. - { - b2Timer timer; - m_contactManager.Collide(); - m_profile.collide = timer.GetMilliseconds(); - } - - // Integrate velocities, solve velocity constraints, and integrate positions. - if (m_stepComplete && step.dt > 0.0f) - { - b2Timer timer; - Solve(step); - m_profile.solve = timer.GetMilliseconds(); - } - - // Handle TOI events. - if (m_continuousPhysics && step.dt > 0.0f) - { - b2Timer timer; - SolveTOI(step); - m_profile.solveTOI = timer.GetMilliseconds(); - } - - if (step.dt > 0.0f) - { - m_inv_dt0 = step.inv_dt; - } - - if (m_flags & e_clearForces) - { - ClearForces(); - } - - m_flags &= ~e_locked; - - m_profile.step = stepTimer.GetMilliseconds(); -} - -void b2World::ClearForces() -{ - for (b2Body* body = m_bodyList; body; body = body->GetNext()) - { - body->m_force.SetZero(); - body->m_torque = 0.0f; - } -} - -struct b2WorldQueryWrapper -{ - bool QueryCallback(int32 proxyId) - { - b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); - return callback->ReportFixture(proxy->fixture); - } - - const b2BroadPhase* broadPhase; - b2QueryCallback* callback; -}; - -void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const -{ - b2WorldQueryWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - m_contactManager.m_broadPhase.Query(&wrapper, aabb); -} - -struct b2WorldRayCastWrapper -{ - float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - void* userData = broadPhase->GetUserData(proxyId); - b2FixtureProxy* proxy = (b2FixtureProxy*)userData; - b2Fixture* fixture = proxy->fixture; - int32 index = proxy->childIndex; - b2RayCastOutput output; - bool hit = fixture->RayCast(&output, input, index); - - if (hit) - { - float32 fraction = output.fraction; - b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; - return callback->ReportFixture(fixture, point, output.normal, fraction); - } - - return input.maxFraction; - } - - const b2BroadPhase* broadPhase; - b2RayCastCallback* callback; -}; - -void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const -{ - b2WorldRayCastWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - b2RayCastInput input; - input.maxFraction = 1.0f; - input.p1 = point1; - input.p2 = point2; - m_contactManager.m_broadPhase.RayCast(&wrapper, input); -} - -void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) -{ - switch (fixture->GetType()) - { - case b2Shape::e_circle: - { - b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); - - b2Vec2 center = b2Mul(xf, circle->m_p); - float32 radius = circle->m_radius; - b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); - - m_debugDraw->DrawSolidCircle(center, radius, axis, color); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); - b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); - b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); - m_debugDraw->DrawSegment(v1, v2, color); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); - int32 count = chain->m_count; - const b2Vec2* vertices = chain->m_vertices; - - b2Vec2 v1 = b2Mul(xf, vertices[0]); - for (int32 i = 1; i < count; ++i) - { - b2Vec2 v2 = b2Mul(xf, vertices[i]); - m_debugDraw->DrawSegment(v1, v2, color); - m_debugDraw->DrawCircle(v1, 0.05f, color); - v1 = v2; - } - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); - int32 vertexCount = poly->m_vertexCount; - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; - - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, poly->m_vertices[i]); - } - - m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); - } - break; - - default: - break; - } -} - -void b2World::DrawJoint(b2Joint* joint) -{ - b2Body* bodyA = joint->GetBodyA(); - b2Body* bodyB = joint->GetBodyB(); - const b2Transform& xf1 = bodyA->GetTransform(); - const b2Transform& xf2 = bodyB->GetTransform(); - b2Vec2 x1 = xf1.p; - b2Vec2 x2 = xf2.p; - b2Vec2 p1 = joint->GetAnchorA(); - b2Vec2 p2 = joint->GetAnchorB(); - - b2Color color(0.5f, 0.8f, 0.8f); - - switch (joint->GetType()) - { - case e_distanceJoint: - m_debugDraw->DrawSegment(p1, p2, color); - break; - - case e_pulleyJoint: - { - b2PulleyJoint* pulley = (b2PulleyJoint*)joint; - b2Vec2 s1 = pulley->GetGroundAnchorA(); - b2Vec2 s2 = pulley->GetGroundAnchorB(); - m_debugDraw->DrawSegment(s1, p1, color); - m_debugDraw->DrawSegment(s2, p2, color); - m_debugDraw->DrawSegment(s1, s2, color); - } - break; - - case e_mouseJoint: - // don't draw this - break; - - default: - m_debugDraw->DrawSegment(x1, p1, color); - m_debugDraw->DrawSegment(p1, p2, color); - m_debugDraw->DrawSegment(x2, p2, color); - } -} - -void b2World::DrawDebugData() -{ - if (m_debugDraw == NULL) - { - return; - } - - uint32 flags = m_debugDraw->GetFlags(); - - if (flags & b2Draw::e_shapeBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2Transform& xf = b->GetTransform(); - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - if (b->IsActive() == false) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); - } - else if (b->GetType() == b2_staticBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); - } - else if (b->GetType() == b2_kinematicBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); - } - else if (b->IsAwake() == false) - { - DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); - } - else - { - DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); - } - } - } - } - - if (flags & b2Draw::e_jointBit) - { - for (b2Joint* j = m_jointList; j; j = j->GetNext()) - { - DrawJoint(j); - } - } - - if (flags & b2Draw::e_pairBit) - { - b2Color color(0.3f, 0.9f, 0.9f); - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) - { - //b2Fixture* fixtureA = c->GetFixtureA(); - //b2Fixture* fixtureB = c->GetFixtureB(); - - //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); - //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); - - //m_debugDraw->DrawSegment(cA, cB, color); - } - } - - if (flags & b2Draw::e_aabbBit) - { - b2Color color(0.9f, 0.3f, 0.9f); - b2BroadPhase* bp = &m_contactManager.m_broadPhase; - - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - if (b->IsActive() == false) - { - continue; - } - - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - for (int32 i = 0; i < f->m_proxyCount; ++i) - { - b2FixtureProxy* proxy = f->m_proxies + i; - b2AABB aabb = bp->GetFatAABB(proxy->proxyId); - b2Vec2 vs[4]; - vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); - vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); - vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); - vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); - - m_debugDraw->DrawPolygon(vs, 4, color); - } - } - } - } - - if (flags & b2Draw::e_centerOfMassBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - b2Transform xf = b->GetTransform(); - xf.p = b->GetWorldCenter(); - m_debugDraw->DrawTransform(xf); - } - } -} - -int32 b2World::GetProxyCount() const -{ - return m_contactManager.m_broadPhase.GetProxyCount(); -} - -int32 b2World::GetTreeHeight() const -{ - return m_contactManager.m_broadPhase.GetTreeHeight(); -} - -int32 b2World::GetTreeBalance() const -{ - return m_contactManager.m_broadPhase.GetTreeBalance(); -} - -float32 b2World::GetTreeQuality() const -{ - return m_contactManager.m_broadPhase.GetTreeQuality(); -} - -void b2World::Dump() -{ - if ((m_flags & e_locked) == e_locked) - { - return; - } - - b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); - b2Log("m_world->SetGravity(g);\n"); - - b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); - b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); - int32 i = 0; - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_islandIndex = i; - b->Dump(); - ++i; - } - - i = 0; - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_index = i; - ++i; - } - - // First pass on joints, skip gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type == e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - // Second pass on joints, only gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type != e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - b2Log("b2Free(joints);\n"); - b2Log("b2Free(bodies);\n"); - b2Log("joints = NULL;\n"); - b2Log("bodies = NULL;\n"); -} diff --git a/external/box2d/Dynamics/b2World.h b/external/box2d/Dynamics/b2World.h deleted file mode 100644 index f207930511..0000000000 --- a/external/box2d/Dynamics/b2World.h +++ /dev/null @@ -1,349 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WORLD_H -#define B2_WORLD_H - -#include -#include -#include -#include -#include -#include - -struct b2AABB; -struct b2BodyDef; -struct b2Color; -struct b2JointDef; -class b2Body; -class b2Draw; -class b2Fixture; -class b2Joint; - -/// The world class manages all physics entities, dynamic simulation, -/// and asynchronous queries. The world also contains efficient memory -/// management facilities. -class b2World -{ -public: - /// Construct a world object. - /// @param gravity the world gravity vector. - b2World(const b2Vec2& gravity); - - /// Destruct the world. All physics entities are destroyed and all heap memory is released. - ~b2World(); - - /// Register a destruction listener. The listener is owned by you and must - /// remain in scope. - void SetDestructionListener(b2DestructionListener* listener); - - /// Register a contact filter to provide specific control over collision. - /// Otherwise the default filter is used (b2_defaultFilter). The listener is - /// owned by you and must remain in scope. - void SetContactFilter(b2ContactFilter* filter); - - /// Register a contact event listener. The listener is owned by you and must - /// remain in scope. - void SetContactListener(b2ContactListener* listener); - - /// Register a routine for debug drawing. The debug draw functions are called - /// inside with b2World::DrawDebugData method. The debug draw object is owned - /// by you and must remain in scope. - void SetDebugDraw(b2Draw* debugDraw); - - /// Create a rigid body given a definition. No reference to the definition - /// is retained. - /// @warning This function is locked during callbacks. - b2Body* CreateBody(const b2BodyDef* def); - - /// Destroy a rigid body given a definition. No reference to the definition - /// is retained. This function is locked during callbacks. - /// @warning This automatically deletes all associated shapes and joints. - /// @warning This function is locked during callbacks. - void DestroyBody(b2Body* body); - - /// Create a joint to constrain bodies together. No reference to the definition - /// is retained. This may cause the connected bodies to cease colliding. - /// @warning This function is locked during callbacks. - b2Joint* CreateJoint(const b2JointDef* def); - - /// Destroy a joint. This may cause the connected bodies to begin colliding. - /// @warning This function is locked during callbacks. - void DestroyJoint(b2Joint* joint); - - /// Take a time step. This performs collision detection, integration, - /// and constraint solution. - /// @param timeStep the amount of time to simulate, this should not vary. - /// @param velocityIterations for the velocity constraint solver. - /// @param positionIterations for the position constraint solver. - void Step( float32 timeStep, - int32 velocityIterations, - int32 positionIterations); - - /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically - /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. - /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain - /// a fixed sized time step under a variable frame-rate. - /// When you perform sub-stepping you will disable auto clearing of forces and instead call - /// ClearForces after all sub-steps are complete in one pass of your game loop. - /// @see SetAutoClearForces - void ClearForces(); - - /// Call this to draw shapes and other debug draw data. - void DrawDebugData(); - - /// Query the world for all fixtures that potentially overlap the - /// provided AABB. - /// @param callback a user implemented callback class. - /// @param aabb the query box. - void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; - - /// Ray-cast the world for all fixtures in the path of the ray. Your callback - /// controls whether you get the closest point, any point, or n-points. - /// The ray-cast ignores shapes that contain the starting point. - /// @param callback a user implemented callback class. - /// @param point1 the ray starting point - /// @param point2 the ray ending point - void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; - - /// Get the world body list. With the returned body, use b2Body::GetNext to get - /// the next body in the world list. A NULL body indicates the end of the list. - /// @return the head of the world body list. - b2Body* GetBodyList(); - const b2Body* GetBodyList() const; - - /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get - /// the next joint in the world list. A NULL joint indicates the end of the list. - /// @return the head of the world joint list. - b2Joint* GetJointList(); - const b2Joint* GetJointList() const; - - /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get - /// the next contact in the world list. A NULL contact indicates the end of the list. - /// @return the head of the world contact list. - /// @warning contacts are created and destroyed in the middle of a time step. - /// Use b2ContactListener to avoid missing contacts. - b2Contact* GetContactList(); - const b2Contact* GetContactList() const; - - /// Enable/disable sleep. - void SetAllowSleeping(bool flag); - bool GetAllowSleeping() const { return m_allowSleep; } - - /// Enable/disable warm starting. For testing. - void SetWarmStarting(bool flag) { m_warmStarting = flag; } - bool GetWarmStarting() const { return m_warmStarting; } - - /// Enable/disable continuous physics. For testing. - void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } - bool GetContinuousPhysics() const { return m_continuousPhysics; } - - /// Enable/disable single stepped continuous physics. For testing. - void SetSubStepping(bool flag) { m_subStepping = flag; } - bool GetSubStepping() const { return m_subStepping; } - - /// Get the number of broad-phase proxies. - int32 GetProxyCount() const; - - /// Get the number of bodies. - int32 GetBodyCount() const; - - /// Get the number of joints. - int32 GetJointCount() const; - - /// Get the number of contacts (each may have 0 or more contact points). - int32 GetContactCount() const; - - /// Get the height of the dynamic tree. - int32 GetTreeHeight() const; - - /// Get the balance of the dynamic tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the dynamic tree. The smaller the better. - /// The minimum is 1. - float32 GetTreeQuality() const; - - /// Change the global gravity vector. - void SetGravity(const b2Vec2& gravity); - - /// Get the global gravity vector. - b2Vec2 GetGravity() const; - - /// Is the world locked (in the middle of a time step). - bool IsLocked() const; - - /// Set flag to control automatic clearing of forces after each time step. - void SetAutoClearForces(bool flag); - - /// Get the flag that controls automatic clearing of forces after each time step. - bool GetAutoClearForces() const; - - /// Get the contact manager for testing. - const b2ContactManager& GetContactManager() const; - - /// Get the current profile. - const b2Profile& GetProfile() const; - - /// Dump the world into the log file. - /// @warning this should be called outside of a time step. - void Dump(); - -private: - - // m_flags - enum - { - e_newFixture = 0x0001, - e_locked = 0x0002, - e_clearForces = 0x0004 - }; - - friend class b2Body; - friend class b2Fixture; - friend class b2ContactManager; - friend class b2Controller; - - void Solve(const b2TimeStep& step); - void SolveTOI(const b2TimeStep& step); - - void DrawJoint(b2Joint* joint); - void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); - - b2BlockAllocator m_blockAllocator; - b2StackAllocator m_stackAllocator; - - int32 m_flags; - - b2ContactManager m_contactManager; - - b2Body* m_bodyList; - b2Joint* m_jointList; - - int32 m_bodyCount; - int32 m_jointCount; - - b2Vec2 m_gravity; - bool m_allowSleep; - - b2DestructionListener* m_destructionListener; - b2Draw* m_debugDraw; - - // This is used to compute the time step ratio to - // support a variable time step. - float32 m_inv_dt0; - - // These are for debugging the solver. - bool m_warmStarting; - bool m_continuousPhysics; - bool m_subStepping; - - bool m_stepComplete; - - b2Profile m_profile; -}; - -inline b2Body* b2World::GetBodyList() -{ - return m_bodyList; -} - -inline const b2Body* b2World::GetBodyList() const -{ - return m_bodyList; -} - -inline b2Joint* b2World::GetJointList() -{ - return m_jointList; -} - -inline const b2Joint* b2World::GetJointList() const -{ - return m_jointList; -} - -inline b2Contact* b2World::GetContactList() -{ - return m_contactManager.m_contactList; -} - -inline const b2Contact* b2World::GetContactList() const -{ - return m_contactManager.m_contactList; -} - -inline int32 b2World::GetBodyCount() const -{ - return m_bodyCount; -} - -inline int32 b2World::GetJointCount() const -{ - return m_jointCount; -} - -inline int32 b2World::GetContactCount() const -{ - return m_contactManager.m_contactCount; -} - -inline void b2World::SetGravity(const b2Vec2& gravity) -{ - m_gravity = gravity; -} - -inline b2Vec2 b2World::GetGravity() const -{ - return m_gravity; -} - -inline bool b2World::IsLocked() const -{ - return (m_flags & e_locked) == e_locked; -} - -inline void b2World::SetAutoClearForces(bool flag) -{ - if (flag) - { - m_flags |= e_clearForces; - } - else - { - m_flags &= ~e_clearForces; - } -} - -/// Get the flag that controls automatic clearing of forces after each time step. -inline bool b2World::GetAutoClearForces() const -{ - return (m_flags & e_clearForces) == e_clearForces; -} - -inline const b2ContactManager& b2World::GetContactManager() const -{ - return m_contactManager; -} - -inline const b2Profile& b2World::GetProfile() const -{ - return m_profile; -} - -#endif diff --git a/external/box2d/Dynamics/b2WorldCallbacks.cpp b/external/box2d/Dynamics/b2WorldCallbacks.cpp deleted file mode 100644 index 48ad0cc46a..0000000000 --- a/external/box2d/Dynamics/b2WorldCallbacks.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -// Return true if contact calculations should be performed between these two shapes. -// If you implement your own collision filter you may want to build from this implementation. -bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) -{ - const b2Filter& filterA = fixtureA->GetFilterData(); - const b2Filter& filterB = fixtureB->GetFilterData(); - - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) - { - return filterA.groupIndex > 0; - } - - bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; - return collide; -} diff --git a/external/box2d/Dynamics/b2WorldCallbacks.h b/external/box2d/Dynamics/b2WorldCallbacks.h deleted file mode 100644 index 86c04e3e32..0000000000 --- a/external/box2d/Dynamics/b2WorldCallbacks.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_WORLD_CALLBACKS_H -#define B2_WORLD_CALLBACKS_H - -#include - -struct b2Vec2; -struct b2Transform; -class b2Fixture; -class b2Body; -class b2Joint; -class b2Contact; -struct b2ContactResult; -struct b2Manifold; - -/// Joints and fixtures are destroyed when their associated -/// body is destroyed. Implement this listener so that you -/// may nullify references to these joints and shapes. -class b2DestructionListener -{ -public: - virtual ~b2DestructionListener() {} - - /// Called when any joint is about to be destroyed due - /// to the destruction of one of its attached bodies. - virtual void SayGoodbye(b2Joint* joint) = 0; - - /// Called when any fixture is about to be destroyed due - /// to the destruction of its parent body. - virtual void SayGoodbye(b2Fixture* fixture) = 0; -}; - -/// Implement this class to provide collision filtering. In other words, you can implement -/// this class if you want finer control over contact creation. -class b2ContactFilter -{ -public: - virtual ~b2ContactFilter() {} - - /// Return true if contact calculations should be performed between these two shapes. - /// @warning for performance reasons this is only called when the AABBs begin to overlap. - virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); -}; - -/// Contact impulses for reporting. Impulses are used instead of forces because -/// sub-step forces may approach infinity for rigid body collisions. These -/// match up one-to-one with the contact points in b2Manifold. -struct b2ContactImpulse -{ - float32 normalImpulses[b2_maxManifoldPoints]; - float32 tangentImpulses[b2_maxManifoldPoints]; - int32 count; -}; - -/// Implement this class to get contact information. You can use these results for -/// things like sounds and game logic. You can also get contact results by -/// traversing the contact lists after the time step. However, you might miss -/// some contacts because continuous physics leads to sub-stepping. -/// Additionally you may receive multiple callbacks for the same contact in a -/// single time step. -/// You should strive to make your callbacks efficient because there may be -/// many callbacks per time step. -/// @warning You cannot create/destroy Box2D entities inside these callbacks. -class b2ContactListener -{ -public: - virtual ~b2ContactListener() {} - - /// Called when two fixtures begin to touch. - virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// Called when two fixtures cease to touch. - virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// This is called after a contact is updated. This allows you to inspect a - /// contact before it goes to the solver. If you are careful, you can modify the - /// contact manifold (e.g. disable contact). - /// A copy of the old manifold is provided so that you can detect changes. - /// Note: this is called only for awake bodies. - /// Note: this is called even when the number of contact points is zero. - /// Note: this is not called for sensors. - /// Note: if you set the number of contact points to zero, you will not - /// get an EndContact callback. However, you may get a BeginContact callback - /// the next step. - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) - { - B2_NOT_USED(contact); - B2_NOT_USED(oldManifold); - } - - /// This lets you inspect a contact after the solver is finished. This is useful - /// for inspecting impulses. - /// Note: the contact manifold does not include time of impact impulses, which can be - /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - /// in a separate data structure. - /// Note: this is only called for contacts that are touching, solid, and awake. - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } -}; - -/// Callback class for AABB queries. -/// See b2World::Query -class b2QueryCallback -{ -public: - virtual ~b2QueryCallback() {} - - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - virtual bool ReportFixture(b2Fixture* fixture) = 0; -}; - -/// Callback class for ray casts. -/// See b2World::RayCast -class b2RayCastCallback -{ -public: - virtual ~b2RayCastCallback() {} - - /// Called for each fixture found in the query. You control how the ray cast - /// proceeds by returning a float: - /// return -1: ignore this fixture and continue - /// return 0: terminate the ray cast - /// return fraction: clip the ray to this point - /// return 1: don't clip the ray and continue - /// @param fixture the fixture hit by the ray - /// @param point the point of initial intersection - /// @param normal the normal vector at the point of intersection - /// @return -1 to filter, 0 to terminate, fraction to clip the ray for - /// closest hit, 1 to continue - virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) = 0; -}; - -#endif diff --git a/external/box2d/Rope/b2Rope.cpp b/external/box2d/Rope/b2Rope.cpp deleted file mode 100644 index 9bf671aec9..0000000000 --- a/external/box2d/Rope/b2Rope.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#include -#include - -b2Rope::b2Rope() -{ - m_count = 0; - m_ps = NULL; - m_p0s = NULL; - m_vs = NULL; - m_ims = NULL; - m_Ls = NULL; - m_as = NULL; - m_gravity.SetZero(); - m_k2 = 1.0f; - m_k3 = 0.1f; -} - -b2Rope::~b2Rope() -{ - b2Free(m_ps); - b2Free(m_p0s); - b2Free(m_vs); - b2Free(m_ims); - b2Free(m_Ls); - b2Free(m_as); -} - -void b2Rope::Initialize(const b2RopeDef* def) -{ - b2Assert(def->count >= 3); - m_count = def->count; - m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); - - for (int32 i = 0; i < m_count; ++i) - { - m_ps[i] = def->vertices[i]; - m_p0s[i] = def->vertices[i]; - m_vs[i].SetZero(); - - float32 m = def->masses[i]; - if (m > 0.0f) - { - m_ims[i] = 1.0f / m; - } - else - { - m_ims[i] = 0.0f; - } - } - - int32 count2 = m_count - 1; - int32 count3 = m_count - 2; - m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); - m_as = (float32*)b2Alloc(count3 * sizeof(float32)); - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i+1]; - m_Ls[i] = b2Distance(p1, p2); - } - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - m_as[i] = b2Atan2(a, b); - } - - m_gravity = def->gravity; - m_damping = def->damping; - m_k2 = def->k2; - m_k3 = def->k3; -} - -void b2Rope::Step(float32 h, int32 iterations) -{ - if (h == 0.0) - { - return; - } - - float32 d = expf(- h * m_damping); - - for (int32 i = 0; i < m_count; ++i) - { - m_p0s[i] = m_ps[i]; - if (m_ims[i] > 0.0f) - { - m_vs[i] += h * m_gravity; - } - m_vs[i] *= d; - m_ps[i] += h * m_vs[i]; - - } - - for (int32 i = 0; i < iterations; ++i) - { - SolveC2(); - SolveC3(); - SolveC2(); - } - - float32 inv_h = 1.0f / h; - for (int32 i = 0; i < m_count; ++i) - { - m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); - } -} - -void b2Rope::SolveC2() -{ - int32 count2 = m_count - 1; - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - - b2Vec2 d = p2 - p1; - float32 L = d.Normalize(); - - float32 im1 = m_ims[i]; - float32 im2 = m_ims[i + 1]; - - if (im1 + im2 == 0.0f) - { - continue; - } - - float32 s1 = im1 / (im1 + im2); - float32 s2 = im2 / (im1 + im2); - - p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; - p2 += m_k2 * s2 * (m_Ls[i] - L) * d; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - } -} - -void b2Rope::SetAngle(float32 angle) -{ - int32 count3 = m_count - 2; - for (int32 i = 0; i < count3; ++i) - { - m_as[i] = angle; - } -} - -void b2Rope::SolveC3() -{ - int32 count3 = m_count - 2; - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - float32 m1 = m_ims[i]; - float32 m2 = m_ims[i + 1]; - float32 m3 = m_ims[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 L1sqr = d1.LengthSquared(); - float32 L2sqr = d2.LengthSquared(); - - if (L1sqr * L2sqr == 0.0f) - { - continue; - } - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - float32 angle = b2Atan2(a, b); - - b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); - b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); - - b2Vec2 J1 = -Jd1; - b2Vec2 J2 = Jd1 - Jd2; - b2Vec2 J3 = Jd2; - - float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); - if (mass == 0.0f) - { - continue; - } - - mass = 1.0f / mass; - - float32 C = angle - m_as[i]; - - while (C > b2_pi) - { - angle -= 2 * b2_pi; - C = angle - m_as[i]; - } - - while (C < -b2_pi) - { - angle += 2.0f * b2_pi; - C = angle - m_as[i]; - } - - float32 impulse = - m_k3 * mass * C; - - p1 += (m1 * impulse) * J1; - p2 += (m2 * impulse) * J2; - p3 += (m3 * impulse) * J3; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - m_ps[i + 2] = p3; - } -} - -void b2Rope::Draw(b2Draw* draw) const -{ - b2Color c(0.4f, 0.5f, 0.7f); - - for (int32 i = 0; i < m_count - 1; ++i) - { - draw->DrawSegment(m_ps[i], m_ps[i+1], c); - } -} diff --git a/external/box2d/Rope/b2Rope.h b/external/box2d/Rope/b2Rope.h deleted file mode 100644 index b981dfd6c5..0000000000 --- a/external/box2d/Rope/b2Rope.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://www.box2d.org -* -* This software is provided 'as-is', without any express or implied -* warranty. In no event will the authors be held liable for any damages -* arising from the use of this software. -* Permission is granted to anyone to use this software for any purpose, -* including commercial applications, and to alter it and redistribute it -* freely, subject to the following restrictions: -* 1. The origin of this software must not be misrepresented; you must not -* claim that you wrote the original software. If you use this software -* in a product, an acknowledgment in the product documentation would be -* appreciated but is not required. -* 2. Altered source versions must be plainly marked as such, and must not be -* misrepresented as being the original software. -* 3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef B2_ROPE_H -#define B2_ROPE_H - -#include - -class b2Draw; - -/// -struct b2RopeDef -{ - b2RopeDef() - { - vertices = NULL; - count = 0; - masses = NULL; - gravity.SetZero(); - damping = 0.1f; - k2 = 0.9f; - k3 = 0.1f; - } - - /// - b2Vec2* vertices; - - /// - int32 count; - - /// - float32* masses; - - /// - b2Vec2 gravity; - - /// - float32 damping; - - /// Stretching stiffness - float32 k2; - - /// Bending stiffness. Values above 0.5 can make the simulation blow up. - float32 k3; -}; - -/// -class b2Rope -{ -public: - b2Rope(); - ~b2Rope(); - - /// - void Initialize(const b2RopeDef* def); - - /// - void Step(float32 timeStep, int32 iterations); - - /// - int32 GetVertexCount() const - { - return m_count; - } - - /// - const b2Vec2* GetVertices() const - { - return m_ps; - } - - /// - void Draw(b2Draw* draw) const; - - /// - void SetAngle(float32 angle); - -private: - - void SolveC2(); - void SolveC3(); - - int32 m_count; - b2Vec2* m_ps; - b2Vec2* m_p0s; - b2Vec2* m_vs; - - float32* m_ims; - - float32* m_Ls; - float32* m_as; - - b2Vec2 m_gravity; - float32 m_damping; - - float32 m_k2; - float32 m_k3; -}; - -#endif diff --git a/external/box2d/proj.linux/.cproject b/external/box2d/proj.linux/.cproject deleted file mode 100644 index 5aa092cac3..0000000000 --- a/external/box2d/proj.linux/.cproject +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/box2d/proj.linux/.project b/external/box2d/proj.linux/.project deleted file mode 100644 index 164d50f52a..0000000000 --- a/external/box2d/proj.linux/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - libBox2D - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libBox2D/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Box2D.h - 1 - PARENT-1-PROJECT_LOC/Box2D.h - - - Collision - 2 - PARENT-1-PROJECT_LOC/Collision - - - Common - 2 - PARENT-1-PROJECT_LOC/Common - - - Dynamics - 2 - PARENT-1-PROJECT_LOC/Dynamics - - - Rope - 2 - PARENT-1-PROJECT_LOC/Rope - - - diff --git a/external/box2d/proj.linux/Makefile b/external/box2d/proj.linux/Makefile deleted file mode 100644 index e430bc9883..0000000000 --- a/external/box2d/proj.linux/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -TARGET = libbox2d.a - -SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ -../Collision/Shapes/b2CircleShape.cpp \ -../Collision/Shapes/b2EdgeShape.cpp \ -../Collision/Shapes/b2PolygonShape.cpp \ -../Collision/b2BroadPhase.cpp \ -../Collision/b2CollideCircle.cpp \ -../Collision/b2CollideEdge.cpp \ -../Collision/b2CollidePolygon.cpp \ -../Collision/b2Collision.cpp \ -../Collision/b2Distance.cpp \ -../Collision/b2DynamicTree.cpp \ -../Collision/b2TimeOfImpact.cpp \ -../Common/b2BlockAllocator.cpp \ -../Common/b2Draw.cpp \ -../Common/b2Math.cpp \ -../Common/b2Settings.cpp \ -../Common/b2StackAllocator.cpp \ -../Common/b2Timer.cpp \ -../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -../Dynamics/Contacts/b2CircleContact.cpp \ -../Dynamics/Contacts/b2Contact.cpp \ -../Dynamics/Contacts/b2ContactSolver.cpp \ -../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -../Dynamics/Contacts/b2PolygonContact.cpp \ -../Dynamics/Joints/b2DistanceJoint.cpp \ -../Dynamics/Joints/b2FrictionJoint.cpp \ -../Dynamics/Joints/b2GearJoint.cpp \ -../Dynamics/Joints/b2Joint.cpp \ -../Dynamics/Joints/b2MouseJoint.cpp \ -../Dynamics/Joints/b2PrismaticJoint.cpp \ -../Dynamics/Joints/b2PulleyJoint.cpp \ -../Dynamics/Joints/b2RevoluteJoint.cpp \ -../Dynamics/Joints/b2RopeJoint.cpp \ -../Dynamics/Joints/b2WeldJoint.cpp \ -../Dynamics/Joints/b2WheelJoint.cpp \ -../Dynamics/b2Body.cpp \ -../Dynamics/b2ContactManager.cpp \ -../Dynamics/b2Fixture.cpp \ -../Dynamics/b2Island.cpp \ -../Dynamics/b2World.cpp \ -../Dynamics/b2WorldCallbacks.cpp \ -../Rope/b2Rope.cpp - -include ../../../cocos2dx/proj.linux/cocos2dx.mk - -INCLUDES = -I../.. - -# Cocos2d is not responsible for warnings in external projects -CXXFLAGS += -w - -ifeq ($(DEBUG), 1) -DEFINES = -D_DEBUG -else -DEFINES = -endif - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/box2d/proj.linux/box2d.prf b/external/box2d/proj.linux/box2d.prf deleted file mode 100644 index 434ad88406..0000000000 --- a/external/box2d/proj.linux/box2d.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile box2d on demand using Makefile. - build_box2d.name = Build box2d static library - build_box2d.input = $$PWD/Makefile - build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.CONFIG = no_link target_predeps - build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_box2d - QMAKE_EXTRA_TARGETS += build_box2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a - LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic -} diff --git a/external/box2d/proj.win32/Box2D.vcxproj b/external/box2d/proj.win32/Box2D.vcxproj deleted file mode 100644 index cd4bd2086c..0000000000 --- a/external/box2d/proj.win32/Box2D.vcxproj +++ /dev/null @@ -1,194 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - libBox2D - {929480E7-23C0-4DF6-8456-096D71547116} - Box2D.win32 - Win32Proj - - - - StaticLibrary - Unicode - v100 - v110 - v110_xp - - - StaticLibrary - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - true - - - $(OutDir)$(ProjectName).lib - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - MultiThreadedDLL - - - Level3 - ProgramDatabase - true - - - $(OutDir)$(ProjectName).lib - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/external/box2d/proj.win32/Box2D.vcxproj.filters b/external/box2d/proj.win32/Box2D.vcxproj.filters deleted file mode 100644 index e810cbb0cf..0000000000 --- a/external/box2d/proj.win32/Box2D.vcxproj.filters +++ /dev/null @@ -1,301 +0,0 @@ - - - - - {bdf099c5-cc32-468b-b53f-ec010d7f823f} - - - {92792f88-4e5c-46ee-8d87-002f3b2297ae} - - - {f41a6fa6-5ac1-4514-9ac0-6f3a38f35b4d} - - - {0b56913a-34b7-410a-b386-869d6f7a20be} - - - {f0e7b230-79cc-49b8-9ed7-9dbfa062f2a4} - - - {932f2008-afbe-42f5-993d-a1df0ec67756} - - - {f8937e09-93a4-49fa-8f3e-dfc36da764df} - - - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Rope - - - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Collision\Shapes - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Common - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Contacts - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Dynamics\Joints - - - Rope - - - - \ No newline at end of file diff --git a/external/box2d/proj.win32/Box2D.vcxproj.user b/external/box2d/proj.win32/Box2D.vcxproj.user deleted file mode 100644 index ace9a86acb..0000000000 --- a/external/box2d/proj.win32/Box2D.vcxproj.user +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file From a96fc9dc16a84baca679449ab70b2ccb80c94742 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 14:15:32 +0800 Subject: [PATCH 123/557] issue #2905:add Box2D --- external/Box2D/Android.mk | 60 + external/Box2D/Box2D.h | 67 + .../Box2D/Collision/Shapes/b2ChainShape.cpp | 171 +++ .../Box2D/Collision/Shapes/b2ChainShape.h | 102 ++ .../Box2D/Collision/Shapes/b2CircleShape.cpp | 100 ++ .../Box2D/Collision/Shapes/b2CircleShape.h | 91 ++ .../Box2D/Collision/Shapes/b2EdgeShape.cpp | 139 ++ external/Box2D/Collision/Shapes/b2EdgeShape.h | 74 + .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 361 +++++ .../Box2D/Collision/Shapes/b2PolygonShape.h | 95 ++ external/Box2D/Collision/Shapes/b2Shape.h | 101 ++ external/Box2D/Collision/b2BroadPhase.cpp | 122 ++ external/Box2D/Collision/b2BroadPhase.h | 248 ++++ external/Box2D/Collision/b2CollideCircle.cpp | 154 ++ external/Box2D/Collision/b2CollideEdge.cpp | 698 +++++++++ external/Box2D/Collision/b2CollidePolygon.cpp | 317 ++++ external/Box2D/Collision/b2Collision.cpp | 249 ++++ external/Box2D/Collision/b2Collision.h | 276 ++++ external/Box2D/Collision/b2Distance.cpp | 603 ++++++++ external/Box2D/Collision/b2Distance.h | 141 ++ external/Box2D/Collision/b2DynamicTree.cpp | 775 ++++++++++ external/Box2D/Collision/b2DynamicTree.h | 284 ++++ external/Box2D/Collision/b2TimeOfImpact.cpp | 488 ++++++ external/Box2D/Collision/b2TimeOfImpact.h | 58 + external/Box2D/Common/b2BlockAllocator.cpp | 218 +++ external/Box2D/Common/b2BlockAllocator.h | 62 + external/Box2D/Common/b2Draw.cpp | 44 + external/Box2D/Common/b2Draw.h | 81 + external/Box2D/Common/b2GrowableStack.h | 85 ++ external/Box2D/Common/b2Math.cpp | 94 ++ external/Box2D/Common/b2Math.h | 738 +++++++++ external/Box2D/Common/b2Settings.cpp | 61 + external/Box2D/Common/b2Settings.h | 150 ++ external/Box2D/Common/b2StackAllocator.cpp | 83 ++ external/Box2D/Common/b2StackAllocator.h | 60 + external/Box2D/Common/b2Timer.cpp | 100 ++ external/Box2D/Common/b2Timer.h | 45 + .../Contacts/b2ChainAndCircleContact.cpp | 54 + .../Contacts/b2ChainAndCircleContact.h | 39 + .../Contacts/b2ChainAndPolygonContact.cpp | 54 + .../Contacts/b2ChainAndPolygonContact.h | 39 + .../Dynamics/Contacts/b2CircleContact.cpp | 53 + .../Box2D/Dynamics/Contacts/b2CircleContact.h | 39 + .../Box2D/Dynamics/Contacts/b2Contact.cpp | 240 +++ external/Box2D/Dynamics/Contacts/b2Contact.h | 331 +++++ .../Dynamics/Contacts/b2ContactSolver.cpp | 832 +++++++++++ .../Box2D/Dynamics/Contacts/b2ContactSolver.h | 94 ++ .../Contacts/b2EdgeAndCircleContact.cpp | 50 + .../Contacts/b2EdgeAndCircleContact.h | 39 + .../Contacts/b2EdgeAndPolygonContact.cpp | 50 + .../Contacts/b2EdgeAndPolygonContact.h | 39 + .../Contacts/b2PolygonAndCircleContact.cpp | 50 + .../Contacts/b2PolygonAndCircleContact.h | 38 + .../Dynamics/Contacts/b2PolygonContact.cpp | 53 + .../Dynamics/Contacts/b2PolygonContact.h | 39 + .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 260 ++++ .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 169 +++ .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 251 ++++ .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 119 ++ .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 423 ++++++ external/Box2D/Dynamics/Joints/b2GearJoint.h | 125 ++ external/Box2D/Dynamics/Joints/b2Joint.cpp | 199 +++ external/Box2D/Dynamics/Joints/b2Joint.h | 222 +++ .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 217 +++ external/Box2D/Dynamics/Joints/b2MouseJoint.h | 126 ++ .../Dynamics/Joints/b2PrismaticJoint.cpp | 637 ++++++++ .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 196 +++ .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 332 +++++ .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 143 ++ .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 504 +++++++ .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 204 +++ .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 241 +++ external/Box2D/Dynamics/Joints/b2RopeJoint.h | 114 ++ .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 330 +++++ external/Box2D/Dynamics/Joints/b2WeldJoint.h | 126 ++ .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 419 ++++++ external/Box2D/Dynamics/Joints/b2WheelJoint.h | 213 +++ external/Box2D/Dynamics/b2Body.cpp | 514 +++++++ external/Box2D/Dynamics/b2Body.h | 846 +++++++++++ external/Box2D/Dynamics/b2ContactManager.cpp | 293 ++++ external/Box2D/Dynamics/b2ContactManager.h | 52 + external/Box2D/Dynamics/b2Fixture.cpp | 303 ++++ external/Box2D/Dynamics/b2Fixture.h | 345 +++++ external/Box2D/Dynamics/b2Island.cpp | 539 +++++++ external/Box2D/Dynamics/b2Island.h | 93 ++ external/Box2D/Dynamics/b2TimeStep.h | 70 + external/Box2D/Dynamics/b2World.cpp | 1316 +++++++++++++++++ external/Box2D/Dynamics/b2World.h | 349 +++++ external/Box2D/Dynamics/b2WorldCallbacks.cpp | 36 + external/Box2D/Dynamics/b2WorldCallbacks.h | 155 ++ external/Box2D/Rope/b2Rope.cpp | 259 ++++ external/Box2D/Rope/b2Rope.h | 115 ++ external/Box2D/proj.linux/.cproject | 267 ++++ external/Box2D/proj.linux/.project | 110 ++ external/Box2D/proj.linux/Makefile | 72 + external/Box2D/proj.linux/box2d.prf | 19 + external/Box2D/proj.win32/Box2D.vcxproj | 194 +++ .../Box2D/proj.win32/Box2D.vcxproj.filters | 301 ++++ external/Box2D/proj.win32/Box2D.vcxproj.user | 3 + 99 files changed, 21549 insertions(+) create mode 100644 external/Box2D/Android.mk create mode 100644 external/Box2D/Box2D.h create mode 100644 external/Box2D/Collision/Shapes/b2ChainShape.cpp create mode 100644 external/Box2D/Collision/Shapes/b2ChainShape.h create mode 100644 external/Box2D/Collision/Shapes/b2CircleShape.cpp create mode 100644 external/Box2D/Collision/Shapes/b2CircleShape.h create mode 100644 external/Box2D/Collision/Shapes/b2EdgeShape.cpp create mode 100644 external/Box2D/Collision/Shapes/b2EdgeShape.h create mode 100644 external/Box2D/Collision/Shapes/b2PolygonShape.cpp create mode 100644 external/Box2D/Collision/Shapes/b2PolygonShape.h create mode 100644 external/Box2D/Collision/Shapes/b2Shape.h create mode 100644 external/Box2D/Collision/b2BroadPhase.cpp create mode 100644 external/Box2D/Collision/b2BroadPhase.h create mode 100644 external/Box2D/Collision/b2CollideCircle.cpp create mode 100644 external/Box2D/Collision/b2CollideEdge.cpp create mode 100644 external/Box2D/Collision/b2CollidePolygon.cpp create mode 100644 external/Box2D/Collision/b2Collision.cpp create mode 100644 external/Box2D/Collision/b2Collision.h create mode 100644 external/Box2D/Collision/b2Distance.cpp create mode 100644 external/Box2D/Collision/b2Distance.h create mode 100644 external/Box2D/Collision/b2DynamicTree.cpp create mode 100644 external/Box2D/Collision/b2DynamicTree.h create mode 100644 external/Box2D/Collision/b2TimeOfImpact.cpp create mode 100644 external/Box2D/Collision/b2TimeOfImpact.h create mode 100644 external/Box2D/Common/b2BlockAllocator.cpp create mode 100644 external/Box2D/Common/b2BlockAllocator.h create mode 100644 external/Box2D/Common/b2Draw.cpp create mode 100644 external/Box2D/Common/b2Draw.h create mode 100644 external/Box2D/Common/b2GrowableStack.h create mode 100644 external/Box2D/Common/b2Math.cpp create mode 100644 external/Box2D/Common/b2Math.h create mode 100644 external/Box2D/Common/b2Settings.cpp create mode 100644 external/Box2D/Common/b2Settings.h create mode 100644 external/Box2D/Common/b2StackAllocator.cpp create mode 100644 external/Box2D/Common/b2StackAllocator.h create mode 100644 external/Box2D/Common/b2Timer.cpp create mode 100644 external/Box2D/Common/b2Timer.h create mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2CircleContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2CircleContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2Contact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2Contact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2ContactSolver.h create mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h create mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp create mode 100644 external/Box2D/Dynamics/Contacts/b2PolygonContact.h create mode 100644 external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2DistanceJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2FrictionJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2GearJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2GearJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2Joint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2Joint.h create mode 100644 external/Box2D/Dynamics/Joints/b2MouseJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2MouseJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2PrismaticJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2PulleyJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2RevoluteJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2RopeJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2RopeJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2WeldJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2WeldJoint.h create mode 100644 external/Box2D/Dynamics/Joints/b2WheelJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2WheelJoint.h create mode 100644 external/Box2D/Dynamics/b2Body.cpp create mode 100644 external/Box2D/Dynamics/b2Body.h create mode 100644 external/Box2D/Dynamics/b2ContactManager.cpp create mode 100644 external/Box2D/Dynamics/b2ContactManager.h create mode 100644 external/Box2D/Dynamics/b2Fixture.cpp create mode 100644 external/Box2D/Dynamics/b2Fixture.h create mode 100644 external/Box2D/Dynamics/b2Island.cpp create mode 100644 external/Box2D/Dynamics/b2Island.h create mode 100644 external/Box2D/Dynamics/b2TimeStep.h create mode 100644 external/Box2D/Dynamics/b2World.cpp create mode 100644 external/Box2D/Dynamics/b2World.h create mode 100644 external/Box2D/Dynamics/b2WorldCallbacks.cpp create mode 100644 external/Box2D/Dynamics/b2WorldCallbacks.h create mode 100644 external/Box2D/Rope/b2Rope.cpp create mode 100644 external/Box2D/Rope/b2Rope.h create mode 100644 external/Box2D/proj.linux/.cproject create mode 100644 external/Box2D/proj.linux/.project create mode 100644 external/Box2D/proj.linux/Makefile create mode 100644 external/Box2D/proj.linux/box2d.prf create mode 100644 external/Box2D/proj.win32/Box2D.vcxproj create mode 100644 external/Box2D/proj.win32/Box2D.vcxproj.filters create mode 100644 external/Box2D/proj.win32/Box2D.vcxproj.user diff --git a/external/Box2D/Android.mk b/external/Box2D/Android.mk new file mode 100644 index 0000000000..c366750c01 --- /dev/null +++ b/external/Box2D/Android.mk @@ -0,0 +1,60 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := box2d_static + +LOCAL_MODULE_FILENAME := libbox2d + +LOCAL_SRC_FILES := \ +Collision/b2BroadPhase.cpp \ +Collision/b2CollideCircle.cpp \ +Collision/b2CollideEdge.cpp \ +Collision/b2CollidePolygon.cpp \ +Collision/b2Collision.cpp \ +Collision/b2Distance.cpp \ +Collision/b2DynamicTree.cpp \ +Collision/b2TimeOfImpact.cpp \ +Collision/Shapes/b2ChainShape.cpp \ +Collision/Shapes/b2CircleShape.cpp \ +Collision/Shapes/b2EdgeShape.cpp \ +Collision/Shapes/b2PolygonShape.cpp \ +Common/b2BlockAllocator.cpp \ +Common/b2Draw.cpp \ +Common/b2Math.cpp \ +Common/b2Settings.cpp \ +Common/b2StackAllocator.cpp \ +Common/b2Timer.cpp \ +Dynamics/b2Body.cpp \ +Dynamics/b2ContactManager.cpp \ +Dynamics/b2Fixture.cpp \ +Dynamics/b2Island.cpp \ +Dynamics/b2World.cpp \ +Dynamics/b2WorldCallbacks.cpp \ +Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +Dynamics/Contacts/b2CircleContact.cpp \ +Dynamics/Contacts/b2Contact.cpp \ +Dynamics/Contacts/b2ContactSolver.cpp \ +Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +Dynamics/Contacts/b2PolygonContact.cpp \ +Dynamics/Joints/b2DistanceJoint.cpp \ +Dynamics/Joints/b2FrictionJoint.cpp \ +Dynamics/Joints/b2GearJoint.cpp \ +Dynamics/Joints/b2Joint.cpp \ +Dynamics/Joints/b2MouseJoint.cpp \ +Dynamics/Joints/b2PrismaticJoint.cpp \ +Dynamics/Joints/b2PulleyJoint.cpp \ +Dynamics/Joints/b2RevoluteJoint.cpp \ +Dynamics/Joints/b2RopeJoint.cpp \ +Dynamics/Joints/b2WeldJoint.cpp \ +Dynamics/Joints/b2WheelJoint.cpp \ +Rope/b2Rope.cpp + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. + +include $(BUILD_STATIC_LIBRARY) diff --git a/external/Box2D/Box2D.h b/external/Box2D/Box2D.h new file mode 100644 index 0000000000..f674d82269 --- /dev/null +++ b/external/Box2D/Box2D.h @@ -0,0 +1,67 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef BOX2D_H +#define BOX2D_H + +/** +\mainpage Box2D API Documentation + +\section intro_sec Getting Started + +For documentation please see http://box2d.org/documentation.html + +For discussion please visit http://box2d.org/forum +*/ + +// These include files constitute the main Box2D API + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.cpp b/external/Box2D/Collision/Shapes/b2ChainShape.cpp new file mode 100644 index 0000000000..79b4304b5b --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2ChainShape.cpp @@ -0,0 +1,171 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +using namespace std; + +b2ChainShape::~b2ChainShape() +{ + b2Free(m_vertices); + m_vertices = NULL; + m_count = 0; +} + +void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 3); + m_count = count + 1; + m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); + m_vertices[count] = m_vertices[0]; + m_prevVertex = m_vertices[m_count - 2]; + m_nextVertex = m_vertices[1]; + m_hasPrevVertex = true; + m_hasNextVertex = true; +} + +void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) +{ + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 2); + m_count = count; + m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); + m_hasPrevVertex = false; + m_hasNextVertex = false; +} + +void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) +{ + m_prevVertex = prevVertex; + m_hasPrevVertex = true; +} + +void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) +{ + m_nextVertex = nextVertex; + m_hasNextVertex = true; +} + +b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2ChainShape)); + b2ChainShape* clone = new (mem) b2ChainShape; + clone->CreateChain(m_vertices, m_count); + clone->m_prevVertex = m_prevVertex; + clone->m_nextVertex = m_nextVertex; + clone->m_hasPrevVertex = m_hasPrevVertex; + clone->m_hasNextVertex = m_hasNextVertex; + return clone; +} + +int32 b2ChainShape::GetChildCount() const +{ + // edge count = vertex count - 1 + return m_count - 1; +} + +void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const +{ + b2Assert(0 <= index && index < m_count - 1); + edge->m_type = b2Shape::e_edge; + edge->m_radius = m_radius; + + edge->m_vertex1 = m_vertices[index + 0]; + edge->m_vertex2 = m_vertices[index + 1]; + + if (index > 0) + { + edge->m_vertex0 = m_vertices[index - 1]; + edge->m_hasVertex0 = true; + } + else + { + edge->m_vertex0 = m_prevVertex; + edge->m_hasVertex0 = m_hasPrevVertex; + } + + if (index < m_count - 2) + { + edge->m_vertex3 = m_vertices[index + 2]; + edge->m_hasVertex3 = true; + } + else + { + edge->m_vertex3 = m_nextVertex; + edge->m_hasVertex3 = m_hasNextVertex; + } +} + +bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + b2EdgeShape edgeShape; + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + edgeShape.m_vertex1 = m_vertices[i1]; + edgeShape.m_vertex2 = m_vertices[i2]; + + return edgeShape.RayCast(output, input, xf, 0); +} + +void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + b2Assert(childIndex < m_count); + + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } + + b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); + b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); + + aabb->lowerBound = b2Min(v1, v2); + aabb->upperBound = b2Max(v1, v2); +} + +void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center.SetZero(); + massData->I = 0.0f; +} diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.h b/external/Box2D/Collision/Shapes/b2ChainShape.h new file mode 100644 index 0000000000..9c9a9eaa7d --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2ChainShape.h @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_SHAPE_H +#define B2_CHAIN_SHAPE_H + +#include + +class b2EdgeShape; + +/// A chain shape is a free form sequence of line segments. +/// The chain has two-sided collision, so you can use inside and outside collision. +/// Therefore, you may use any winding order. +/// Since there may be many vertices, they are allocated using b2Alloc. +/// Connectivity information is used to create smooth collisions. +/// WARNING: The chain will not collide properly if there are self-intersections. +class b2ChainShape : public b2Shape +{ +public: + b2ChainShape(); + + /// The destructor frees the vertices using b2Free. + ~b2ChainShape(); + + /// Create a loop. This automatically adjusts connectivity. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateLoop(const b2Vec2* vertices, int32 count); + + /// Create a chain with isolated end vertices. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateChain(const b2Vec2* vertices, int32 count); + + /// Establish connectivity to a vertex that precedes the first vertex. + /// Don't call this for loops. + void SetPrevVertex(const b2Vec2& prevVertex); + + /// Establish connectivity to a vertex that follows the last vertex. + /// Don't call this for loops. + void SetNextVertex(const b2Vec2& nextVertex); + + /// Implement b2Shape. Vertices are cloned using b2Alloc. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Get a child edge. + void GetChildEdge(b2EdgeShape* edge, int32 index) const; + + /// This always return false. + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// Chains have zero mass. + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// The vertices. Owned by this class. + b2Vec2* m_vertices; + + /// The vertex count. + int32 m_count; + + b2Vec2 m_prevVertex, m_nextVertex; + bool m_hasPrevVertex, m_hasNextVertex; +}; + +inline b2ChainShape::b2ChainShape() +{ + m_type = e_chain; + m_radius = b2_polygonRadius; + m_vertices = NULL; + m_count = 0; + m_hasPrevVertex = false; + m_hasNextVertex = false; +} + +#endif diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.cpp b/external/Box2D/Collision/Shapes/b2CircleShape.cpp new file mode 100644 index 0000000000..587ca960b2 --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2CircleShape.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2CircleShape)); + b2CircleShape* clone = new (mem) b2CircleShape; + *clone = *this; + return clone; +} + +int32 b2CircleShape::GetChildCount() const +{ + return 1; +} + +bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const +{ + b2Vec2 center = transform.p + b2Mul(transform.q, m_p); + b2Vec2 d = p - center; + return b2Dot(d, d) <= m_radius * m_radius; +} + +// Collision Detection in Interactive 3D Environments by Gino van den Bergen +// From Section 3.1.2 +// x = s + a * r +// norm(x) = radius +bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 position = transform.p + b2Mul(transform.q, m_p); + b2Vec2 s = input.p1 - position; + float32 b = b2Dot(s, s) - m_radius * m_radius; + + // Solve quadratic equation. + b2Vec2 r = input.p2 - input.p1; + float32 c = b2Dot(s, r); + float32 rr = b2Dot(r, r); + float32 sigma = c * c - rr * b; + + // Check for negative discriminant and short segment. + if (sigma < 0.0f || rr < b2_epsilon) + { + return false; + } + + // Find the point of intersection of the line with the circle. + float32 a = -(c + b2Sqrt(sigma)); + + // Is the intersection point on the segment? + if (0.0f <= a && a <= input.maxFraction * rr) + { + a /= rr; + output->fraction = a; + output->normal = s + a * r; + output->normal.Normalize(); + return true; + } + + return false; +} + +void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 p = transform.p + b2Mul(transform.q, m_p); + aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); + aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); +} + +void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const +{ + massData->mass = density * b2_pi * m_radius * m_radius; + massData->center = m_p; + + // inertia about the local origin + massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); +} diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.h b/external/Box2D/Collision/Shapes/b2CircleShape.h new file mode 100644 index 0000000000..c4e23a475b --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2CircleShape.h @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CIRCLE_SHAPE_H +#define B2_CIRCLE_SHAPE_H + +#include + +/// A circle shape. +class b2CircleShape : public b2Shape +{ +public: + b2CircleShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Implement b2Shape. + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return 1; } + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + /// Position + b2Vec2 m_p; +}; + +inline b2CircleShape::b2CircleShape() +{ + m_type = e_circle; + m_radius = 0.0f; + m_p.SetZero(); +} + +inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return 0; +} + +inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const +{ + B2_NOT_USED(d); + return m_p; +} + +inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const +{ + B2_NOT_USED(index); + b2Assert(index == 0); + return m_p; +} + +#endif diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.cpp b/external/Box2D/Collision/Shapes/b2EdgeShape.cpp new file mode 100644 index 0000000000..7b09e55bf4 --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2EdgeShape.cpp @@ -0,0 +1,139 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) +{ + m_vertex1 = v1; + m_vertex2 = v2; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2EdgeShape)); + b2EdgeShape* clone = new (mem) b2EdgeShape; + *clone = *this; + return clone; +} + +int32 b2EdgeShape::GetChildCount() const +{ + return 1; +} + +bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; +} + +// p = p1 + t * d +// v = v1 + s * e +// p1 + t * d = v1 + s * e +// s * e - t * d = p1 - v1 +bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + // Put the ray into the edge's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; + + b2Vec2 v1 = m_vertex1; + b2Vec2 v2 = m_vertex2; + b2Vec2 e = v2 - v1; + b2Vec2 normal(e.y, -e.x); + normal.Normalize(); + + // q = p1 + t * d + // dot(normal, q - v1) = 0 + // dot(normal, p1 - v1) + t * dot(normal, d) = 0 + float32 numerator = b2Dot(normal, v1 - p1); + float32 denominator = b2Dot(normal, d); + + if (denominator == 0.0f) + { + return false; + } + + float32 t = numerator / denominator; + if (t < 0.0f || input.maxFraction < t) + { + return false; + } + + b2Vec2 q = p1 + t * d; + + // q = v1 + s * r + // s = dot(q - v1, r) / dot(r, r) + b2Vec2 r = v2 - v1; + float32 rr = b2Dot(r, r); + if (rr == 0.0f) + { + return false; + } + + float32 s = b2Dot(q - v1, r) / rr; + if (s < 0.0f || 1.0f < s) + { + return false; + } + + output->fraction = t; + if (numerator > 0.0f) + { + output->normal = -normal; + } + else + { + output->normal = normal; + } + return true; +} + +void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 v1 = b2Mul(xf, m_vertex1); + b2Vec2 v2 = b2Mul(xf, m_vertex2); + + b2Vec2 lower = b2Min(v1, v2); + b2Vec2 upper = b2Max(v1, v2); + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const +{ + B2_NOT_USED(density); + + massData->mass = 0.0f; + massData->center = 0.5f * (m_vertex1 + m_vertex2); + massData->I = 0.0f; +} diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.h b/external/Box2D/Collision/Shapes/b2EdgeShape.h new file mode 100644 index 0000000000..6163bcbf1c --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2EdgeShape.h @@ -0,0 +1,74 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_SHAPE_H +#define B2_EDGE_SHAPE_H + +#include + +/// A line segment (edge) shape. These can be connected in chains or loops +/// to other edge shapes. The connectivity information is used to ensure +/// correct contact normals. +class b2EdgeShape : public b2Shape +{ +public: + b2EdgeShape(); + + /// Set this as an isolated edge. + void Set(const b2Vec2& v1, const b2Vec2& v2); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// These are the edge vertices + b2Vec2 m_vertex1, m_vertex2; + + /// Optional adjacent vertices. These are used for smooth collision. + b2Vec2 m_vertex0, m_vertex3; + bool m_hasVertex0, m_hasVertex3; +}; + +inline b2EdgeShape::b2EdgeShape() +{ + m_type = e_edge; + m_radius = b2_polygonRadius; + m_vertex0.x = 0.0f; + m_vertex0.y = 0.0f; + m_vertex3.x = 0.0f; + m_vertex3.y = 0.0f; + m_hasVertex0 = false; + m_hasVertex3 = false; +} + +#endif diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.cpp b/external/Box2D/Collision/Shapes/b2PolygonShape.cpp new file mode 100644 index 0000000000..c04c1dc49b --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2PolygonShape.cpp @@ -0,0 +1,361 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const +{ + void* mem = allocator->Allocate(sizeof(b2PolygonShape)); + b2PolygonShape* clone = new (mem) b2PolygonShape; + *clone = *this; + return clone; +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid.SetZero(); +} + +void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) +{ + m_vertexCount = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid = center; + + b2Transform xf; + xf.p = center; + xf.q.Set(angle); + + // Transform vertices and normals. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = b2Mul(xf, m_vertices[i]); + m_normals[i] = b2Mul(xf.q, m_normals[i]); + } +} + +int32 b2PolygonShape::GetChildCount() const +{ + return 1; +} + +static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) +{ + b2Assert(count >= 3); + + b2Vec2 c; c.Set(0.0f, 0.0f); + float32 area = 0.0f; + + // pRef is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 pRef(0.0f, 0.0f); +#if 0 + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < count; ++i) + { + pRef += vs[i]; + } + pRef *= 1.0f / count; +#endif + + const float32 inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < count; ++i) + { + // Triangle vertices. + b2Vec2 p1 = pRef; + b2Vec2 p2 = vs[i]; + b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; + + b2Vec2 e1 = p2 - p1; + b2Vec2 e2 = p3 - p1; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + c += triangleArea * inv3 * (p1 + p2 + p3); + } + + // Centroid + b2Assert(area > b2_epsilon); + c *= 1.0f / area; + return c; +} + +void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) +{ + b2Assert(3 <= count && count <= b2_maxPolygonVertices); + m_vertexCount = count; + + // Copy vertices. + for (int32 i = 0; i < m_vertexCount; ++i) + { + m_vertices[i] = vertices[i]; + } + + // Compute normals. Ensure the edges have non-zero length. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); + m_normals[i] = b2Cross(edge, 1.0f); + m_normals[i].Normalize(); + } + +#ifdef _DEBUG + // Ensure the polygon is convex and the interior + // is to the left of each edge. + for (int32 i = 0; i < m_vertexCount; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + + for (int32 j = 0; j < m_vertexCount; ++j) + { + // Don't check vertices on the current edge. + if (j == i1 || j == i2) + { + continue; + } + + b2Vec2 r = m_vertices[j] - m_vertices[i1]; + + // If this crashes, your polygon is non-convex, has colinear edges, + // or the winding order is wrong. + float32 s = b2Cross(edge, r); + b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); + } + } +#endif + + // Compute the polygon centroid. + m_centroid = ComputeCentroid(m_vertices, m_vertexCount); +} + +bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const +{ + b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); + + for (int32 i = 0; i < m_vertexCount; ++i) + { + float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); + if (dot > 0.0f) + { + return false; + } + } + + return true; +} + +bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + // Put the ray into the polygon's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; + + float32 lower = 0.0f, upper = input.maxFraction; + + int32 index = -1; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // p = p1 + a * d + // dot(normal, p - v) = 0 + // dot(normal, p1 - v) + a * dot(normal, d) = 0 + float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); + float32 denominator = b2Dot(m_normals[i], d); + + if (denominator == 0.0f) + { + if (numerator < 0.0f) + { + return false; + } + } + else + { + // Note: we want this predicate without division: + // lower < numerator / denominator, where denominator < 0 + // Since denominator < 0, we have to flip the inequality: + // lower < numerator / denominator <==> denominator * lower > numerator. + if (denominator < 0.0f && numerator < lower * denominator) + { + // Increase lower. + // The segment enters this half-space. + lower = numerator / denominator; + index = i; + } + else if (denominator > 0.0f && numerator < upper * denominator) + { + // Decrease upper. + // The segment exits this half-space. + upper = numerator / denominator; + } + } + + // The use of epsilon here causes the assert on lower to trip + // in some cases. Apparently the use of epsilon was to make edge + // shapes work, but now those are handled separately. + //if (upper < lower - b2_epsilon) + if (upper < lower) + { + return false; + } + } + + b2Assert(0.0f <= lower && lower <= input.maxFraction); + + if (index >= 0) + { + output->fraction = lower; + output->normal = b2Mul(xf.q, m_normals[index]); + return true; + } + + return false; +} + +void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const +{ + B2_NOT_USED(childIndex); + + b2Vec2 lower = b2Mul(xf, m_vertices[0]); + b2Vec2 upper = lower; + + for (int32 i = 1; i < m_vertexCount; ++i) + { + b2Vec2 v = b2Mul(xf, m_vertices[i]); + lower = b2Min(lower, v); + upper = b2Max(upper, v); + } + + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; +} + +void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const +{ + // Polygon mass, centroid, and inertia. + // Let rho be the polygon density in mass per unit area. + // Then: + // mass = rho * int(dA) + // centroid.x = (1/mass) * rho * int(x * dA) + // centroid.y = (1/mass) * rho * int(y * dA) + // I = rho * int((x*x + y*y) * dA) + // + // We can compute these integrals by summing all the integrals + // for each triangle of the polygon. To evaluate the integral + // for a single triangle, we make a change of variables to + // the (u,v) coordinates of the triangle: + // x = x0 + e1x * u + e2x * v + // y = y0 + e1y * u + e2y * v + // where 0 <= u && 0 <= v && u + v <= 1. + // + // We integrate u from [0,1-v] and then v from [0,1]. + // We also need to use the Jacobian of the transformation: + // D = cross(e1, e2) + // + // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) + // + // The rest of the derivation is handled by computer algebra. + + b2Assert(m_vertexCount >= 3); + + b2Vec2 center; center.Set(0.0f, 0.0f); + float32 area = 0.0f; + float32 I = 0.0f; + + // s is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 s(0.0f, 0.0f); + + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < m_vertexCount; ++i) + { + s += m_vertices[i]; + } + s *= 1.0f / m_vertexCount; + + const float32 k_inv3 = 1.0f / 3.0f; + + for (int32 i = 0; i < m_vertexCount; ++i) + { + // Triangle vertices. + b2Vec2 e1 = m_vertices[i] - s; + b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; + + float32 D = b2Cross(e1, e2); + + float32 triangleArea = 0.5f * D; + area += triangleArea; + + // Area weighted centroid + center += triangleArea * k_inv3 * (e1 + e2); + + float32 ex1 = e1.x, ey1 = e1.y; + float32 ex2 = e2.x, ey2 = e2.y; + + float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; + float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; + + I += (0.25f * k_inv3 * D) * (intx2 + inty2); + } + + // Total mass + massData->mass = density * area; + + // Center of mass + b2Assert(area > b2_epsilon); + center *= 1.0f / area; + massData->center = center + s; + + // Inertia tensor relative to the local origin (point s). + massData->I = density * I; + + // Shift to center of mass then to original body origin. + massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); +} diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.h b/external/Box2D/Collision/Shapes/b2PolygonShape.h new file mode 100644 index 0000000000..70daccb2ff --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2PolygonShape.h @@ -0,0 +1,95 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_SHAPE_H +#define B2_POLYGON_SHAPE_H + +#include + +/// A convex polygon. It is assumed that the interior of the polygon is to +/// the left of each edge. +/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. +/// In most cases you should not need many vertices for a convex polygon. +class b2PolygonShape : public b2Shape +{ +public: + b2PolygonShape(); + + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; + + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; + + /// Copy vertices. This assumes the vertices define a convex polygon. + /// It is assumed that the exterior is the the right of each edge. + /// The count must be in the range [3, b2_maxPolygonVertices]. + void Set(const b2Vec2* vertices, int32 vertexCount); + + /// Build vertices to represent an axis-aligned box. + /// @param hx the half-width. + /// @param hy the half-height. + void SetAsBox(float32 hx, float32 hy); + + /// Build vertices to represent an oriented box. + /// @param hx the half-width. + /// @param hy the half-height. + /// @param center the center of the box in local coordinates. + /// @param angle the rotation of the box in local coordinates. + void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); + + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// Get the vertex count. + int32 GetVertexCount() const { return m_vertexCount; } + + /// Get a vertex by index. + const b2Vec2& GetVertex(int32 index) const; + + b2Vec2 m_centroid; + b2Vec2 m_vertices[b2_maxPolygonVertices]; + b2Vec2 m_normals[b2_maxPolygonVertices]; + int32 m_vertexCount; +}; + +inline b2PolygonShape::b2PolygonShape() +{ + m_type = e_polygon; + m_radius = b2_polygonRadius; + m_vertexCount = 0; + m_centroid.SetZero(); +} + +inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_vertexCount); + return m_vertices[index]; +} + +#endif diff --git a/external/Box2D/Collision/Shapes/b2Shape.h b/external/Box2D/Collision/Shapes/b2Shape.h new file mode 100644 index 0000000000..2e2aedd14a --- /dev/null +++ b/external/Box2D/Collision/Shapes/b2Shape.h @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_SHAPE_H +#define B2_SHAPE_H + +#include +#include +#include + +/// This holds the mass data computed for a shape. +struct b2MassData +{ + /// The mass of the shape, usually in kilograms. + float32 mass; + + /// The position of the shape's centroid relative to the shape's origin. + b2Vec2 center; + + /// The rotational inertia of the shape about the local origin. + float32 I; +}; + +/// A shape is used for collision detection. You can create a shape however you like. +/// Shapes used for simulation in b2World are created automatically when a b2Fixture +/// is created. Shapes may encapsulate a one or more child shapes. +class b2Shape +{ +public: + + enum Type + { + e_circle = 0, + e_edge = 1, + e_polygon = 2, + e_chain = 3, + e_typeCount = 4 + }; + + virtual ~b2Shape() {} + + /// Clone the concrete shape using the provided allocator. + virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; + + /// Get the type of this shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + Type GetType() const; + + /// Get the number of child primitives. + virtual int32 GetChildCount() const = 0; + + /// Test a point for containment in this shape. This only works for convex shapes. + /// @param xf the shape world transform. + /// @param p a point in world coordinates. + virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; + + /// Cast a ray against a child shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + /// @param transform the transform to be applied to the shape. + /// @param childIndex the child shape index + virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const = 0; + + /// Given a transform, compute the associated axis aligned bounding box for a child shape. + /// @param aabb returns the axis aligned box. + /// @param xf the world transform of the shape. + /// @param childIndex the child shape + virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; + + /// Compute the mass properties of this shape using its dimensions and density. + /// The inertia tensor is computed about the local origin. + /// @param massData returns the mass data for this shape. + /// @param density the density in kilograms per meter squared. + virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; + + Type m_type; + float32 m_radius; +}; + +inline b2Shape::Type b2Shape::GetType() const +{ + return m_type; +} + +#endif diff --git a/external/Box2D/Collision/b2BroadPhase.cpp b/external/Box2D/Collision/b2BroadPhase.cpp new file mode 100644 index 0000000000..431f6de1ee --- /dev/null +++ b/external/Box2D/Collision/b2BroadPhase.cpp @@ -0,0 +1,122 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +using namespace std; + +b2BroadPhase::b2BroadPhase() +{ + m_proxyCount = 0; + + m_pairCapacity = 16; + m_pairCount = 0; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + + m_moveCapacity = 16; + m_moveCount = 0; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); +} + +b2BroadPhase::~b2BroadPhase() +{ + b2Free(m_moveBuffer); + b2Free(m_pairBuffer); +} + +int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = m_tree.CreateProxy(aabb, userData); + ++m_proxyCount; + BufferMove(proxyId); + return proxyId; +} + +void b2BroadPhase::DestroyProxy(int32 proxyId) +{ + UnBufferMove(proxyId); + --m_proxyCount; + m_tree.DestroyProxy(proxyId); +} + +void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); + if (buffer) + { + BufferMove(proxyId); + } +} + +void b2BroadPhase::TouchProxy(int32 proxyId) +{ + BufferMove(proxyId); +} + +void b2BroadPhase::BufferMove(int32 proxyId) +{ + if (m_moveCount == m_moveCapacity) + { + int32* oldBuffer = m_moveBuffer; + m_moveCapacity *= 2; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); + memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); + b2Free(oldBuffer); + } + + m_moveBuffer[m_moveCount] = proxyId; + ++m_moveCount; +} + +void b2BroadPhase::UnBufferMove(int32 proxyId) +{ + for (int32 i = 0; i < m_moveCount; ++i) + { + if (m_moveBuffer[i] == proxyId) + { + m_moveBuffer[i] = e_nullProxy; + return; + } + } +} + +// This is called from b2DynamicTree::Query when we are gathering pairs. +bool b2BroadPhase::QueryCallback(int32 proxyId) +{ + // A proxy cannot form a pair with itself. + if (proxyId == m_queryProxyId) + { + return true; + } + + // Grow the pair buffer as needed. + if (m_pairCount == m_pairCapacity) + { + b2Pair* oldBuffer = m_pairBuffer; + m_pairCapacity *= 2; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); + b2Free(oldBuffer); + } + + m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); + m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); + ++m_pairCount; + + return true; +} diff --git a/external/Box2D/Collision/b2BroadPhase.h b/external/Box2D/Collision/b2BroadPhase.h new file mode 100644 index 0000000000..cf2414730a --- /dev/null +++ b/external/Box2D/Collision/b2BroadPhase.h @@ -0,0 +1,248 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BROAD_PHASE_H +#define B2_BROAD_PHASE_H + +#include +#include +#include +#include + +struct b2Pair +{ + int32 proxyIdA; + int32 proxyIdB; + int32 next; +}; + +/// The broad-phase is used for computing pairs and performing volume queries and ray casts. +/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. +/// It is up to the client to consume the new pairs and to track subsequent overlap. +class b2BroadPhase +{ +public: + + enum + { + e_nullProxy = -1 + }; + + b2BroadPhase(); + ~b2BroadPhase(); + + /// Create a proxy with an initial AABB. Pairs are not reported until + /// UpdatePairs is called. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. It is up to the client to remove any pairs. + void DestroyProxy(int32 proxyId); + + /// Call MoveProxy as many times as you like, then when you are done + /// call UpdatePairs to finalized the proxy pairs (for your time step). + void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); + + /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. + void TouchProxy(int32 proxyId); + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Get user data from a proxy. Returns NULL if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Test overlap of fat AABBs. + bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; + + /// Get the number of proxies. + int32 GetProxyCount() const; + + /// Update the pairs. This results in pair callbacks. This can only add pairs. + template + void UpdatePairs(T* callback); + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + + /// Get the height of the embedded tree. + int32 GetTreeHeight() const; + + /// Get the balance of the embedded tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the embedded tree. + float32 GetTreeQuality() const; + +private: + + friend class b2DynamicTree; + + void BufferMove(int32 proxyId); + void UnBufferMove(int32 proxyId); + + bool QueryCallback(int32 proxyId); + + b2DynamicTree m_tree; + + int32 m_proxyCount; + + int32* m_moveBuffer; + int32 m_moveCapacity; + int32 m_moveCount; + + b2Pair* m_pairBuffer; + int32 m_pairCapacity; + int32 m_pairCount; + + int32 m_queryProxyId; +}; + +/// This is used to sort pairs. +inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) +{ + if (pair1.proxyIdA < pair2.proxyIdA) + { + return true; + } + + if (pair1.proxyIdA == pair2.proxyIdA) + { + return pair1.proxyIdB < pair2.proxyIdB; + } + + return false; +} + +inline void* b2BroadPhase::GetUserData(int32 proxyId) const +{ + return m_tree.GetUserData(proxyId); +} + +inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const +{ + const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); + const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); + return b2TestOverlap(aabbA, aabbB); +} + +inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const +{ + return m_tree.GetFatAABB(proxyId); +} + +inline int32 b2BroadPhase::GetProxyCount() const +{ + return m_proxyCount; +} + +inline int32 b2BroadPhase::GetTreeHeight() const +{ + return m_tree.GetHeight(); +} + +inline int32 b2BroadPhase::GetTreeBalance() const +{ + return m_tree.GetMaxBalance(); +} + +inline float32 b2BroadPhase::GetTreeQuality() const +{ + return m_tree.GetAreaRatio(); +} + +template +void b2BroadPhase::UpdatePairs(T* callback) +{ + // Reset pair buffer + m_pairCount = 0; + + // Perform tree queries for all moving proxies. + for (int32 i = 0; i < m_moveCount; ++i) + { + m_queryProxyId = m_moveBuffer[i]; + if (m_queryProxyId == e_nullProxy) + { + continue; + } + + // We have to query the tree with the fat AABB so that + // we don't fail to create a pair that may touch later. + const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); + + // Query tree, create pairs and add them pair buffer. + m_tree.Query(this, fatAABB); + } + + // Reset move buffer + m_moveCount = 0; + + // Sort the pair buffer to expose duplicates. + std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); + + // Send the pairs back to the client. + int32 i = 0; + while (i < m_pairCount) + { + b2Pair* primaryPair = m_pairBuffer + i; + void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); + void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); + + callback->AddPair(userDataA, userDataB); + ++i; + + // Skip any duplicate pairs. + while (i < m_pairCount) + { + b2Pair* pair = m_pairBuffer + i; + if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) + { + break; + } + ++i; + } + } + + // Try to keep the tree balanced. + //m_tree.Rebalance(4); +} + +template +inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const +{ + m_tree.Query(callback, aabb); +} + +template +inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const +{ + m_tree.RayCast(callback, input); +} + +#endif diff --git a/external/Box2D/Collision/b2CollideCircle.cpp b/external/Box2D/Collision/b2CollideCircle.cpp new file mode 100644 index 0000000000..ed561eb04b --- /dev/null +++ b/external/Box2D/Collision/b2CollideCircle.cpp @@ -0,0 +1,154 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +void b2CollideCircles( + b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + b2Vec2 pA = b2Mul(xfA, circleA->m_p); + b2Vec2 pB = b2Mul(xfB, circleB->m_p); + + b2Vec2 d = pB - pA; + float32 distSqr = b2Dot(d, d); + float32 rA = circleA->m_radius, rB = circleB->m_radius; + float32 radius = rA + rB; + if (distSqr > radius * radius) + { + return; + } + + manifold->type = b2Manifold::e_circles; + manifold->localPoint = circleA->m_p; + manifold->localNormal.SetZero(); + manifold->pointCount = 1; + + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; +} + +void b2CollidePolygonAndCircle( + b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle position in the frame of the polygon. + b2Vec2 c = b2Mul(xfB, circleB->m_p); + b2Vec2 cLocal = b2MulT(xfA, c); + + // Find the min separating edge. + int32 normalIndex = 0; + float32 separation = -b2_maxFloat; + float32 radius = polygonA->m_radius + circleB->m_radius; + int32 vertexCount = polygonA->m_vertexCount; + const b2Vec2* vertices = polygonA->m_vertices; + const b2Vec2* normals = polygonA->m_normals; + + for (int32 i = 0; i < vertexCount; ++i) + { + float32 s = b2Dot(normals[i], cLocal - vertices[i]); + + if (s > radius) + { + // Early out. + return; + } + + if (s > separation) + { + separation = s; + normalIndex = i; + } + } + + // Vertices that subtend the incident face. + int32 vertIndex1 = normalIndex; + int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; + b2Vec2 v1 = vertices[vertIndex1]; + b2Vec2 v2 = vertices[vertIndex2]; + + // If the center is inside the polygon ... + if (separation < b2_epsilon) + { + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[normalIndex]; + manifold->localPoint = 0.5f * (v1 + v2); + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + return; + } + + // Compute barycentric coordinates + float32 u1 = b2Dot(cLocal - v1, v2 - v1); + float32 u2 = b2Dot(cLocal - v2, v1 - v2); + if (u1 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v1) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v1; + manifold->localNormal.Normalize(); + manifold->localPoint = v1; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else if (u2 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v2) > radius * radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v2; + manifold->localNormal.Normalize(); + manifold->localPoint = v2; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else + { + b2Vec2 faceCenter = 0.5f * (v1 + v2); + float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); + if (separation > radius) + { + return; + } + + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[vertIndex1]; + manifold->localPoint = faceCenter; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } +} diff --git a/external/Box2D/Collision/b2CollideEdge.cpp b/external/Box2D/Collision/b2CollideEdge.cpp new file mode 100644 index 0000000000..96ca71dccc --- /dev/null +++ b/external/Box2D/Collision/b2CollideEdge.cpp @@ -0,0 +1,698 @@ +/* + * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#include +#include +#include +#include + + +// Compute contact points for edge versus circle. +// This accounts for edge connectivity. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + + // Compute circle in frame of edge + b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); + + b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; + b2Vec2 e = B - A; + + // Barycentric coordinates + float32 u = b2Dot(e, B - Q); + float32 v = b2Dot(e, Q - A); + + float32 radius = edgeA->m_radius + circleB->m_radius; + + b2ContactFeature cf; + cf.indexB = 0; + cf.typeB = b2ContactFeature::e_vertex; + + // Region A + if (v <= 0.0f) + { + b2Vec2 P = A; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to A? + if (edgeA->m_hasVertex0) + { + b2Vec2 A1 = edgeA->m_vertex0; + b2Vec2 B1 = A; + b2Vec2 e1 = B1 - A1; + float32 u1 = b2Dot(e1, B1 - Q); + + // Is the circle in Region AB of the previous edge? + if (u1 > 0.0f) + { + return; + } + } + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region B + if (u <= 0.0f) + { + b2Vec2 P = B; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to B? + if (edgeA->m_hasVertex3) + { + b2Vec2 B2 = edgeA->m_vertex3; + b2Vec2 A2 = B; + b2Vec2 e2 = B2 - A2; + float32 v2 = b2Dot(e2, Q - A2); + + // Is the circle in Region AB of the next edge? + if (v2 > 0.0f) + { + return; + } + } + + cf.indexA = 1; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region AB + float32 den = b2Dot(e, e); + b2Assert(den > 0.0f); + b2Vec2 P = (1.0f / den) * (u * A + v * B); + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + b2Vec2 n(-e.y, e.x); + if (b2Dot(n, Q - A) < 0.0f) + { + n.Set(-n.x, -n.y); + } + n.Normalize(); + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_face; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = n; + manifold->localPoint = A; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; +} + +// This structure is used to keep track of the best separating axis. +struct b2EPAxis +{ + enum Type + { + e_unknown, + e_edgeA, + e_edgeB + }; + + Type type; + int32 index; + float32 separation; +}; + +// This holds polygon B expressed in frame A. +struct b2TempPolygon +{ + b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 normals[b2_maxPolygonVertices]; + int32 count; +}; + +// Reference face used for clipping +struct b2ReferenceFace +{ + int32 i1, i2; + + b2Vec2 v1, v2; + + b2Vec2 normal; + + b2Vec2 sideNormal1; + float32 sideOffset1; + + b2Vec2 sideNormal2; + float32 sideOffset2; +}; + +// This class collides and edge and a polygon, taking into account edge adjacency. +struct b2EPCollider +{ + void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + b2EPAxis ComputeEdgeSeparation(); + b2EPAxis ComputePolygonSeparation(); + + enum VertexType + { + e_isolated, + e_concave, + e_convex + }; + + b2TempPolygon m_polygonB; + + b2Transform m_xf; + b2Vec2 m_centroidB; + b2Vec2 m_v0, m_v1, m_v2, m_v3; + b2Vec2 m_normal0, m_normal1, m_normal2; + b2Vec2 m_normal; + VertexType m_type1, m_type2; + b2Vec2 m_lowerLimit, m_upperLimit; + float32 m_radius; + bool m_front; +}; + +// Algorithm: +// 1. Classify v1 and v2 +// 2. Classify polygon centroid as front or back +// 3. Flip normal if necessary +// 4. Initialize normal range to [-pi, pi] about face normal +// 5. Adjust normal range according to adjacent edges +// 6. Visit each separating axes, only accept axes within the range +// 7. Return if _any_ axis indicates separation +// 8. Clip +void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + m_xf = b2MulT(xfA, xfB); + + m_centroidB = b2Mul(m_xf, polygonB->m_centroid); + + m_v0 = edgeA->m_vertex0; + m_v1 = edgeA->m_vertex1; + m_v2 = edgeA->m_vertex2; + m_v3 = edgeA->m_vertex3; + + bool hasVertex0 = edgeA->m_hasVertex0; + bool hasVertex3F = edgeA->m_hasVertex3; + + b2Vec2 edge1 = m_v2 - m_v1; + edge1.Normalize(); + m_normal1.Set(edge1.y, -edge1.x); + float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); + float32 offset0 = 0.0f, offset2 = 0.0f; + bool convex1 = false, convex2 = false; + + // Is there a preceding edge? + if (hasVertex0) + { + b2Vec2 edge0 = m_v1 - m_v0; + edge0.Normalize(); + m_normal0.Set(edge0.y, -edge0.x); + convex1 = b2Cross(edge0, edge1) >= 0.0f; + offset0 = b2Dot(m_normal0, m_centroidB - m_v0); + } + + // Is there a following edge? + if (hasVertex3F) + { + b2Vec2 edge2 = m_v3 - m_v2; + edge2.Normalize(); + m_normal2.Set(edge2.y, -edge2.x); + convex2 = b2Cross(edge1, edge2) > 0.0f; + offset2 = b2Dot(m_normal2, m_centroidB - m_v2); + } + + // Determine front or back collision. Determine collision normal limits. + if (hasVertex0 && hasVertex3F) + { + if (convex1 && convex2) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + } + else if (convex1) + { + m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal1; + } + } + else if (convex2) + { + m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal0; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex0) + { + if (convex1) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex3F) + { + if (convex2) + { + m_front = offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + } + else + { + m_front = offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = m_normal1; + } + } + } + else + { + m_front = offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + } + + // Get polygonB in frameA + m_polygonB.count = polygonB->m_vertexCount; + for (int32 i = 0; i < polygonB->m_vertexCount; ++i) + { + m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); + m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); + } + + m_radius = 2.0f * b2_polygonRadius; + + manifold->pointCount = 0; + + b2EPAxis edgeAxis = ComputeEdgeSeparation(); + + // If no valid normal can be found than this edge should not collide. + if (edgeAxis.type == b2EPAxis::e_unknown) + { + return; + } + + if (edgeAxis.separation > m_radius) + { + return; + } + + b2EPAxis polygonAxis = ComputePolygonSeparation(); + if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) + { + return; + } + + // Use hysteresis for jitter reduction. + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + b2EPAxis primaryAxis; + if (polygonAxis.type == b2EPAxis::e_unknown) + { + primaryAxis = edgeAxis; + } + else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) + { + primaryAxis = polygonAxis; + } + else + { + primaryAxis = edgeAxis; + } + + b2ClipVertex ie[2]; + b2ReferenceFace rf; + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->type = b2Manifold::e_faceA; + + // Search for the polygon normal that is most anti-parallel to the edge normal. + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); + for (int32 i = 1; i < m_polygonB.count; ++i) + { + float32 value = b2Dot(m_normal, m_polygonB.normals[i]); + if (value < bestValue) + { + bestValue = value; + bestIndex = i; + } + } + + int32 i1 = bestIndex; + int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; + + ie[0].v = m_polygonB.vertices[i1]; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = i1; + ie[0].id.cf.typeA = b2ContactFeature::e_face; + ie[0].id.cf.typeB = b2ContactFeature::e_vertex; + + ie[1].v = m_polygonB.vertices[i2]; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = i2; + ie[1].id.cf.typeA = b2ContactFeature::e_face; + ie[1].id.cf.typeB = b2ContactFeature::e_vertex; + + if (m_front) + { + rf.i1 = 0; + rf.i2 = 1; + rf.v1 = m_v1; + rf.v2 = m_v2; + rf.normal = m_normal1; + } + else + { + rf.i1 = 1; + rf.i2 = 0; + rf.v1 = m_v2; + rf.v2 = m_v1; + rf.normal = -m_normal1; + } + } + else + { + manifold->type = b2Manifold::e_faceB; + + ie[0].v = m_v1; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = primaryAxis.index; + ie[0].id.cf.typeA = b2ContactFeature::e_vertex; + ie[0].id.cf.typeB = b2ContactFeature::e_face; + + ie[1].v = m_v2; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = primaryAxis.index; + ie[1].id.cf.typeA = b2ContactFeature::e_vertex; + ie[1].id.cf.typeB = b2ContactFeature::e_face; + + rf.i1 = primaryAxis.index; + rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; + rf.v1 = m_polygonB.vertices[rf.i1]; + rf.v2 = m_polygonB.vertices[rf.i2]; + rf.normal = m_polygonB.normals[rf.i1]; + } + + rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); + rf.sideNormal2 = -rf.sideNormal1; + rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); + rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int32 np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Now clipPoints2 contains the clipped points. + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->localNormal = rf.normal; + manifold->localPoint = rf.v1; + } + else + { + manifold->localNormal = polygonB->m_normals[rf.i1]; + manifold->localPoint = polygonB->m_vertices[rf.i1]; + } + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation; + + separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); + + if (separation <= m_radius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + } + else + { + cp->localPoint = clipPoints2[i].v; + cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; + cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; + cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; + cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; + } + + ++pointCount; + } + } + + manifold->pointCount = pointCount; +} + +b2EPAxis b2EPCollider::ComputeEdgeSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_edgeA; + axis.index = m_front ? 0 : 1; + axis.separation = FLT_MAX; + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); + if (s < axis.separation) + { + axis.separation = s; + } + } + + return axis; +} + +b2EPAxis b2EPCollider::ComputePolygonSeparation() +{ + b2EPAxis axis; + axis.type = b2EPAxis::e_unknown; + axis.index = -1; + axis.separation = -FLT_MAX; + + b2Vec2 perp(-m_normal.y, m_normal.x); + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + b2Vec2 n = -m_polygonB.normals[i]; + + float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); + float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); + float32 s = b2Min(s1, s2); + + if (s > m_radius) + { + // No collision + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + return axis; + } + + // Adjacency + if (b2Dot(n, perp) >= 0.0f) + { + if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + else + { + if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + + if (s > axis.separation) + { + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + } + } + + return axis; +} + +void b2CollideEdgeAndPolygon( b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) +{ + b2EPCollider collider; + collider.Collide(manifold, edgeA, xfA, polygonB, xfB); +} diff --git a/external/Box2D/Collision/b2CollidePolygon.cpp b/external/Box2D/Collision/b2CollidePolygon.cpp new file mode 100644 index 0000000000..be2518d966 --- /dev/null +++ b/external/Box2D/Collision/b2CollidePolygon.cpp @@ -0,0 +1,317 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +// Find the separation between poly1 and poly2 for a give edge normal on poly1. +static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + const b2Vec2* vertices1 = poly1->m_vertices; + const b2Vec2* normals1 = poly1->m_normals; + + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; + + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); + + // Convert normal from poly1's frame into poly2's frame. + b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); + b2Vec2 normal1 = b2MulT(xf2.q, normal1World); + + // Find support vertex on poly2 for -normal. + int32 index = 0; + float32 minDot = b2_maxFloat; + + for (int32 i = 0; i < count2; ++i) + { + float32 dot = b2Dot(vertices2[i], normal1); + if (dot < minDot) + { + minDot = dot; + index = i; + } + } + + b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]); + b2Vec2 v2 = b2Mul(xf2, vertices2[index]); + float32 separation = b2Dot(v2 - v1, normal1World); + return separation; +} + +// Find the max separation between poly1 and poly2 using edge normals from poly1. +static float32 b2FindMaxSeparation(int32* edgeIndex, + const b2PolygonShape* poly1, const b2Transform& xf1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + int32 count1 = poly1->m_vertexCount; + const b2Vec2* normals1 = poly1->m_normals; + + // Vector pointing from the centroid of poly1 to the centroid of poly2. + b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); + b2Vec2 dLocal1 = b2MulT(xf1.q, d); + + // Find edge normal on poly1 that has the largest projection onto d. + int32 edge = 0; + float32 maxDot = -b2_maxFloat; + for (int32 i = 0; i < count1; ++i) + { + float32 dot = b2Dot(normals1[i], dLocal1); + if (dot > maxDot) + { + maxDot = dot; + edge = i; + } + } + + // Get the separation for the edge normal. + float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); + + // Check the separation for the previous edge normal. + int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; + float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); + + // Check the separation for the next edge normal. + int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; + float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); + + // Find the best edge and the search direction. + int32 bestEdge; + float32 bestSeparation; + int32 increment; + if (sPrev > s && sPrev > sNext) + { + increment = -1; + bestEdge = prevEdge; + bestSeparation = sPrev; + } + else if (sNext > s) + { + increment = 1; + bestEdge = nextEdge; + bestSeparation = sNext; + } + else + { + *edgeIndex = edge; + return s; + } + + // Perform a local search for the best edge normal. + for ( ; ; ) + { + if (increment == -1) + edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1; + else + edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; + + s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); + + if (s > bestSeparation) + { + bestEdge = edge; + bestSeparation = s; + } + else + { + break; + } + } + + *edgeIndex = bestEdge; + return bestSeparation; +} + +static void b2FindIncidentEdge(b2ClipVertex c[2], + const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) +{ + const b2Vec2* normals1 = poly1->m_normals; + + int32 count2 = poly2->m_vertexCount; + const b2Vec2* vertices2 = poly2->m_vertices; + const b2Vec2* normals2 = poly2->m_normals; + + b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); + + // Get the normal of the reference edge in poly2's frame. + b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); + + // Find the incident edge on poly2. + int32 index = 0; + float32 minDot = b2_maxFloat; + for (int32 i = 0; i < count2; ++i) + { + float32 dot = b2Dot(normal1, normals2[i]); + if (dot < minDot) + { + minDot = dot; + index = i; + } + } + + // Build the clip vertices for the incident edge. + int32 i1 = index; + int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; + + c[0].v = b2Mul(xf2, vertices2[i1]); + c[0].id.cf.indexA = (uint8)edge1; + c[0].id.cf.indexB = (uint8)i1; + c[0].id.cf.typeA = b2ContactFeature::e_face; + c[0].id.cf.typeB = b2ContactFeature::e_vertex; + + c[1].v = b2Mul(xf2, vertices2[i2]); + c[1].id.cf.indexA = (uint8)edge1; + c[1].id.cf.indexB = (uint8)i2; + c[1].id.cf.typeA = b2ContactFeature::e_face; + c[1].id.cf.typeB = b2ContactFeature::e_vertex; +} + +// Find edge normal of max separation on A - return if separating axis is found +// Find edge normal of max separation on B - return if separation axis is found +// Choose reference edge as min(minA, minB) +// Find incident edge +// Clip + +// The normal points from 1 to 2 +void b2CollidePolygons(b2Manifold* manifold, + const b2PolygonShape* polyA, const b2Transform& xfA, + const b2PolygonShape* polyB, const b2Transform& xfB) +{ + manifold->pointCount = 0; + float32 totalRadius = polyA->m_radius + polyB->m_radius; + + int32 edgeA = 0; + float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); + if (separationA > totalRadius) + return; + + int32 edgeB = 0; + float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); + if (separationB > totalRadius) + return; + + const b2PolygonShape* poly1; // reference polygon + const b2PolygonShape* poly2; // incident polygon + b2Transform xf1, xf2; + int32 edge1; // reference edge + uint8 flip; + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + if (separationB > k_relativeTol * separationA + k_absoluteTol) + { + poly1 = polyB; + poly2 = polyA; + xf1 = xfB; + xf2 = xfA; + edge1 = edgeB; + manifold->type = b2Manifold::e_faceB; + flip = 1; + } + else + { + poly1 = polyA; + poly2 = polyB; + xf1 = xfA; + xf2 = xfB; + edge1 = edgeA; + manifold->type = b2Manifold::e_faceA; + flip = 0; + } + + b2ClipVertex incidentEdge[2]; + b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); + + int32 count1 = poly1->m_vertexCount; + const b2Vec2* vertices1 = poly1->m_vertices; + + int32 iv1 = edge1; + int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; + + b2Vec2 v11 = vertices1[iv1]; + b2Vec2 v12 = vertices1[iv2]; + + b2Vec2 localTangent = v12 - v11; + localTangent.Normalize(); + + b2Vec2 localNormal = b2Cross(localTangent, 1.0f); + b2Vec2 planePoint = 0.5f * (v11 + v12); + + b2Vec2 tangent = b2Mul(xf1.q, localTangent); + b2Vec2 normal = b2Cross(tangent, 1.0f); + + v11 = b2Mul(xf1, v11); + v12 = b2Mul(xf1, v12); + + // Face offset. + float32 frontOffset = b2Dot(normal, v11); + + // Side offsets, extended by polytope skin thickness. + float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; + float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); + + if (np < 2) + return; + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); + + if (np < 2) + { + return; + } + + // Now clipPoints2 contains the clipped points. + manifold->localNormal = localNormal; + manifold->localPoint = planePoint; + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; + + if (separation <= totalRadius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + cp->localPoint = b2MulT(xf2, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + if (flip) + { + // Swap features + b2ContactFeature cf = cp->id.cf; + cp->id.cf.indexA = cf.indexB; + cp->id.cf.indexB = cf.indexA; + cp->id.cf.typeA = cf.typeB; + cp->id.cf.typeB = cf.typeA; + } + ++pointCount; + } + } + + manifold->pointCount = pointCount; +} diff --git a/external/Box2D/Collision/b2Collision.cpp b/external/Box2D/Collision/b2Collision.cpp new file mode 100644 index 0000000000..2dd5ff0ab6 --- /dev/null +++ b/external/Box2D/Collision/b2Collision.cpp @@ -0,0 +1,249 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +void b2WorldManifold::Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB) +{ + if (manifold->pointCount == 0) + { + return; + } + + switch (manifold->type) + { + case b2Manifold::e_circles: + { + normal.Set(1.0f, 0.0f); + b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); + b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } + + b2Vec2 cA = pointA + radiusA * normal; + b2Vec2 cB = pointB - radiusB * normal; + points[0] = 0.5f * (cA + cB); + } + break; + + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); + b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cB = clipPoint - radiusB * normal; + points[i] = 0.5f * (cA + cB); + } + } + break; + + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); + b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cA = clipPoint - radiusA * normal; + points[i] = 0.5f * (cA + cB); + } + + // Ensure normal points from A to B. + normal = -normal; + } + break; + } +} + +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2) +{ + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + state1[i] = b2_nullState; + state2[i] = b2_nullState; + } + + // Detect persists and removes. + for (int32 i = 0; i < manifold1->pointCount; ++i) + { + b2ContactID id = manifold1->points[i].id; + + state1[i] = b2_removeState; + + for (int32 j = 0; j < manifold2->pointCount; ++j) + { + if (manifold2->points[j].id.key == id.key) + { + state1[i] = b2_persistState; + break; + } + } + } + + // Detect persists and adds. + for (int32 i = 0; i < manifold2->pointCount; ++i) + { + b2ContactID id = manifold2->points[i].id; + + state2[i] = b2_addState; + + for (int32 j = 0; j < manifold1->pointCount; ++j) + { + if (manifold1->points[j].id.key == id.key) + { + state2[i] = b2_persistState; + break; + } + } + } +} + +// From Real-time Collision Detection, p179. +bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const +{ + float32 tmin = -b2_maxFloat; + float32 tmax = b2_maxFloat; + + b2Vec2 p = input.p1; + b2Vec2 d = input.p2 - input.p1; + b2Vec2 absD = b2Abs(d); + + b2Vec2 normal; + + for (int32 i = 0; i < 2; ++i) + { + if (absD(i) < b2_epsilon) + { + // Parallel. + if (p(i) < lowerBound(i) || upperBound(i) < p(i)) + { + return false; + } + } + else + { + float32 inv_d = 1.0f / d(i); + float32 t1 = (lowerBound(i) - p(i)) * inv_d; + float32 t2 = (upperBound(i) - p(i)) * inv_d; + + // Sign of the normal vector. + float32 s = -1.0f; + + if (t1 > t2) + { + b2Swap(t1, t2); + s = 1.0f; + } + + // Push the min up + if (t1 > tmin) + { + normal.SetZero(); + normal(i) = s; + tmin = t1; + } + + // Pull the max down + tmax = b2Min(tmax, t2); + + if (tmin > tmax) + { + return false; + } + } + } + + // Does the ray start inside the box? + // Does the ray intersect beyond the max fraction? + if (tmin < 0.0f || input.maxFraction < tmin) + { + return false; + } + + // Intersection. + output->fraction = tmin; + output->normal = normal; + return true; +} + +// Sutherland-Hodgman clipping. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset, int32 vertexIndexA) +{ + // Start with no output points + int32 numOut = 0; + + // Calculate the distance of end points to the line + float32 distance0 = b2Dot(normal, vIn[0].v) - offset; + float32 distance1 = b2Dot(normal, vIn[1].v) - offset; + + // If the points are behind the plane + if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; + if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; + + // If the points are on different sides of the plane + if (distance0 * distance1 < 0.0f) + { + // Find intersection point of edge and plane + float32 interp = distance0 / (distance0 - distance1); + vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); + + // VertexA is hitting edgeB. + vOut[numOut].id.cf.indexA = vertexIndexA; + vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; + vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; + vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; + ++numOut; + } + + return numOut; +} + +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB) +{ + b2DistanceInput input; + input.proxyA.Set(shapeA, indexA); + input.proxyB.Set(shapeB, indexB); + input.transformA = xfA; + input.transformB = xfB; + input.useRadii = true; + + b2SimplexCache cache; + cache.count = 0; + + b2DistanceOutput output; + + b2Distance(&output, &cache, &input); + + return output.distance < 10.0f * b2_epsilon; +} diff --git a/external/Box2D/Collision/b2Collision.h b/external/Box2D/Collision/b2Collision.h new file mode 100644 index 0000000000..2e7386232b --- /dev/null +++ b/external/Box2D/Collision/b2Collision.h @@ -0,0 +1,276 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_COLLISION_H +#define B2_COLLISION_H + +#include +#include + +/// @file +/// Structures and functions used for computing contact points, distance +/// queries, and TOI queries. + +class b2Shape; +class b2CircleShape; +class b2EdgeShape; +class b2PolygonShape; + +const uint8 b2_nullFeature = UCHAR_MAX; + +/// The features that intersect to form the contact point +/// This must be 4 bytes or less. +struct b2ContactFeature +{ + enum Type + { + e_vertex = 0, + e_face = 1 + }; + + uint8 indexA; ///< Feature index on shapeA + uint8 indexB; ///< Feature index on shapeB + uint8 typeA; ///< The feature type on shapeA + uint8 typeB; ///< The feature type on shapeB +}; + +/// Contact ids to facilitate warm starting. +union b2ContactID +{ + b2ContactFeature cf; + uint32 key; ///< Used to quickly compare contact ids. +}; + +/// A manifold point is a contact point belonging to a contact +/// manifold. It holds details related to the geometry and dynamics +/// of the contact points. +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleB +/// -e_faceA: the local center of cirlceB or the clip point of polygonB +/// -e_faceB: the clip point of polygonA +/// This structure is stored across time steps, so we keep it small. +/// Note: the impulses are used for internal caching and may not +/// provide reliable contact forces, especially for high speed collisions. +struct b2ManifoldPoint +{ + b2Vec2 localPoint; ///< usage depends on manifold type + float32 normalImpulse; ///< the non-penetration impulse + float32 tangentImpulse; ///< the friction impulse + b2ContactID id; ///< uniquely identifies a contact point between two shapes +}; + +/// A manifold for two touching convex shapes. +/// Box2D supports multiple types of contact: +/// - clip point versus plane with radius +/// - point versus point with radius (circles) +/// The local point usage depends on the manifold type: +/// -e_circles: the local center of circleA +/// -e_faceA: the center of faceA +/// -e_faceB: the center of faceB +/// Similarly the local normal usage: +/// -e_circles: not used +/// -e_faceA: the normal on polygonA +/// -e_faceB: the normal on polygonB +/// We store contacts in this way so that position correction can +/// account for movement, which is critical for continuous physics. +/// All contact scenarios must be expressed in one of these types. +/// This structure is stored across time steps, so we keep it small. +struct b2Manifold +{ + enum Type + { + e_circles, + e_faceA, + e_faceB + }; + + b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact + b2Vec2 localNormal; ///< not use for Type::e_points + b2Vec2 localPoint; ///< usage depends on manifold type + Type type; + int32 pointCount; ///< the number of manifold points +}; + +/// This is used to compute the current state of a contact manifold. +struct b2WorldManifold +{ + /// Evaluate the manifold with supplied transforms. This assumes + /// modest motion from the original state. This does not change the + /// point count, impulses, etc. The radii must come from the shapes + /// that generated the manifold. + void Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB); + + b2Vec2 normal; ///< world vector pointing from A to B + b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) +}; + +/// This is used for determining the state of contact points. +enum b2PointState +{ + b2_nullState, ///< point does not exist + b2_addState, ///< point was added in the update + b2_persistState, ///< point persisted across the update + b2_removeState ///< point was removed in the update +}; + +/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 +/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. +void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], + const b2Manifold* manifold1, const b2Manifold* manifold2); + +/// Used for computing contact manifolds. +struct b2ClipVertex +{ + b2Vec2 v; + b2ContactID id; +}; + +/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). +struct b2RayCastInput +{ + b2Vec2 p1, p2; + float32 maxFraction; +}; + +/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 +/// come from b2RayCastInput. +struct b2RayCastOutput +{ + b2Vec2 normal; + float32 fraction; +}; + +/// An axis aligned bounding box. +struct b2AABB +{ + /// Verify that the bounds are sorted. + bool IsValid() const; + + /// Get the center of the AABB. + b2Vec2 GetCenter() const + { + return 0.5f * (lowerBound + upperBound); + } + + /// Get the extents of the AABB (half-widths). + b2Vec2 GetExtents() const + { + return 0.5f * (upperBound - lowerBound); + } + + /// Get the perimeter length + float32 GetPerimeter() const + { + float32 wx = upperBound.x - lowerBound.x; + float32 wy = upperBound.y - lowerBound.y; + return 2.0f * (wx + wy); + } + + /// Combine an AABB into this one. + void Combine(const b2AABB& aabb) + { + lowerBound = b2Min(lowerBound, aabb.lowerBound); + upperBound = b2Max(upperBound, aabb.upperBound); + } + + /// Combine two AABBs into this one. + void Combine(const b2AABB& aabb1, const b2AABB& aabb2) + { + lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); + upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); + } + + /// Does this aabb contain the provided AABB. + bool Contains(const b2AABB& aabb) const + { + bool result = true; + result = result && lowerBound.x <= aabb.lowerBound.x; + result = result && lowerBound.y <= aabb.lowerBound.y; + result = result && aabb.upperBound.x <= upperBound.x; + result = result && aabb.upperBound.y <= upperBound.y; + return result; + } + + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + + b2Vec2 lowerBound; ///< the lower vertex + b2Vec2 upperBound; ///< the upper vertex +}; + +/// Compute the collision manifold between two circles. +void b2CollideCircles(b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between a polygon and a circle. +void b2CollidePolygonAndCircle(b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between two polygons. +void b2CollidePolygons(b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndCircle(b2Manifold* manifold, + const b2EdgeShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); + +/// Compute the collision manifold between an edge and a circle. +void b2CollideEdgeAndPolygon(b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* circleB, const b2Transform& xfB); + +/// Clipping for contact manifolds. +int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], + const b2Vec2& normal, float32 offset, int32 vertexIndexA); + +/// Determine if two generic shapes overlap. +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB); + +// ---------------- Inline Functions ------------------------------------------ + +inline bool b2AABB::IsValid() const +{ + b2Vec2 d = upperBound - lowerBound; + bool valid = d.x >= 0.0f && d.y >= 0.0f; + valid = valid && lowerBound.IsValid() && upperBound.IsValid(); + return valid; +} + +inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) +{ + b2Vec2 d1, d2; + d1 = b.lowerBound - a.upperBound; + d2 = a.lowerBound - b.upperBound; + + if (d1.x > 0.0f || d1.y > 0.0f) + return false; + + if (d2.x > 0.0f || d2.y > 0.0f) + return false; + + return true; +} + +#endif diff --git a/external/Box2D/Collision/b2Distance.cpp b/external/Box2D/Collision/b2Distance.cpp new file mode 100644 index 0000000000..ac67d3be43 --- /dev/null +++ b/external/Box2D/Collision/b2Distance.cpp @@ -0,0 +1,603 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. +int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + +void b2DistanceProxy::Set(const b2Shape* shape, int32 index) +{ + switch (shape->GetType()) + { + case b2Shape::e_circle: + { + const b2CircleShape* circle = (b2CircleShape*)shape; + m_vertices = &circle->m_p; + m_count = 1; + m_radius = circle->m_radius; + } + break; + + case b2Shape::e_polygon: + { + const b2PolygonShape* polygon = (b2PolygonShape*)shape; + m_vertices = polygon->m_vertices; + m_count = polygon->m_vertexCount; + m_radius = polygon->m_radius; + } + break; + + case b2Shape::e_chain: + { + const b2ChainShape* chain = (b2ChainShape*)shape; + b2Assert(0 <= index && index < chain->m_count); + + m_buffer[0] = chain->m_vertices[index]; + if (index + 1 < chain->m_count) + { + m_buffer[1] = chain->m_vertices[index + 1]; + } + else + { + m_buffer[1] = chain->m_vertices[0]; + } + + m_vertices = m_buffer; + m_count = 2; + m_radius = chain->m_radius; + } + break; + + case b2Shape::e_edge: + { + const b2EdgeShape* edge = (b2EdgeShape*)shape; + m_vertices = &edge->m_vertex1; + m_count = 2; + m_radius = edge->m_radius; + } + break; + + default: + b2Assert(false); + } +} + + +struct b2SimplexVertex +{ + b2Vec2 wA; // support point in proxyA + b2Vec2 wB; // support point in proxyB + b2Vec2 w; // wB - wA + float32 a; // barycentric coordinate for closest point + int32 indexA; // wA index + int32 indexB; // wB index +}; + +struct b2Simplex +{ + void ReadCache( const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Transform& transformA, + const b2DistanceProxy* proxyB, const b2Transform& transformB) + { + b2Assert(cache->count <= 3); + + // Copy data from cache. + m_count = cache->count; + b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + b2SimplexVertex* v = vertices + i; + v->indexA = cache->indexA[i]; + v->indexB = cache->indexB[i]; + b2Vec2 wALocal = proxyA->GetVertex(v->indexA); + b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + v->a = 0.0f; + } + + // Compute the new simplex metric, if it is substantially different than + // old metric then flush the simplex. + if (m_count > 1) + { + float32 metric1 = cache->metric; + float32 metric2 = GetMetric(); + if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) + { + // Reset the simplex. + m_count = 0; + } + } + + // If the cache is empty or invalid ... + if (m_count == 0) + { + b2SimplexVertex* v = vertices + 0; + v->indexA = 0; + v->indexB = 0; + b2Vec2 wALocal = proxyA->GetVertex(0); + b2Vec2 wBLocal = proxyB->GetVertex(0); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + m_count = 1; + } + } + + void WriteCache(b2SimplexCache* cache) const + { + cache->metric = GetMetric(); + cache->count = uint16(m_count); + const b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + cache->indexA[i] = uint8(vertices[i].indexA); + cache->indexB[i] = uint8(vertices[i].indexB); + } + } + + b2Vec2 GetSearchDirection() const + { + switch (m_count) + { + case 1: + return -m_v1.w; + + case 2: + { + b2Vec2 e12 = m_v2.w - m_v1.w; + float32 sgn = b2Cross(e12, -m_v1.w); + if (sgn > 0.0f) + { + // Origin is left of e12. + return b2Cross(1.0f, e12); + } + else + { + // Origin is right of e12. + return b2Cross(e12, 1.0f); + } + } + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + b2Vec2 GetClosestPoint() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return b2Vec2_zero; + + case 1: + return m_v1.w; + + case 2: + return m_v1.a * m_v1.w + m_v2.a * m_v2.w; + + case 3: + return b2Vec2_zero; + + default: + b2Assert(false); + return b2Vec2_zero; + } + } + + void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const + { + switch (m_count) + { + case 0: + b2Assert(false); + break; + + case 1: + *pA = m_v1.wA; + *pB = m_v1.wB; + break; + + case 2: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; + *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; + break; + + case 3: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; + *pB = *pA; + break; + + default: + b2Assert(false); + break; + } + } + + float32 GetMetric() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return 0.0; + + case 1: + return 0.0f; + + case 2: + return b2Distance(m_v1.w, m_v2.w); + + case 3: + return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); + + default: + b2Assert(false); + return 0.0f; + } + } + + void Solve2(); + void Solve3(); + + b2SimplexVertex m_v1, m_v2, m_v3; + int32 m_count; +}; + + +// Solve a line segment using barycentric coordinates. +// +// p = a1 * w1 + a2 * w2 +// a1 + a2 = 1 +// +// The vector from the origin to the closest point on the line is +// perpendicular to the line. +// e12 = w2 - w1 +// dot(p, e) = 0 +// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 +// +// 2-by-2 linear system +// [1 1 ][a1] = [1] +// [w1.e12 w2.e12][a2] = [0] +// +// Define +// d12_1 = dot(w2, e12) +// d12_2 = -dot(w1, e12) +// d12 = d12_1 + d12_2 +// +// Solution +// a1 = d12_1 / d12 +// a2 = d12_2 / d12 +void b2Simplex::Solve2() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 e12 = w2 - w1; + + // w1 region + float32 d12_2 = -b2Dot(w1, e12); + if (d12_2 <= 0.0f) + { + // a2 <= 0, so we clamp it to 0 + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // w2 region + float32 d12_1 = b2Dot(w2, e12); + if (d12_1 <= 0.0f) + { + // a1 <= 0, so we clamp it to 0 + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // Must be in e12 region. + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; +} + +// Possible regions: +// - points[2] +// - edge points[0]-points[2] +// - edge points[1]-points[2] +// - inside the triangle +void b2Simplex::Solve3() +{ + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 w3 = m_v3.w; + + // Edge12 + // [1 1 ][a1] = [1] + // [w1.e12 w2.e12][a2] = [0] + // a3 = 0 + b2Vec2 e12 = w2 - w1; + float32 w1e12 = b2Dot(w1, e12); + float32 w2e12 = b2Dot(w2, e12); + float32 d12_1 = w2e12; + float32 d12_2 = -w1e12; + + // Edge13 + // [1 1 ][a1] = [1] + // [w1.e13 w3.e13][a3] = [0] + // a2 = 0 + b2Vec2 e13 = w3 - w1; + float32 w1e13 = b2Dot(w1, e13); + float32 w3e13 = b2Dot(w3, e13); + float32 d13_1 = w3e13; + float32 d13_2 = -w1e13; + + // Edge23 + // [1 1 ][a2] = [1] + // [w2.e23 w3.e23][a3] = [0] + // a1 = 0 + b2Vec2 e23 = w3 - w2; + float32 w2e23 = b2Dot(w2, e23); + float32 w3e23 = b2Dot(w3, e23); + float32 d23_1 = w3e23; + float32 d23_2 = -w2e23; + + // Triangle123 + float32 n123 = b2Cross(e12, e13); + + float32 d123_1 = n123 * b2Cross(w2, w3); + float32 d123_2 = n123 * b2Cross(w3, w1); + float32 d123_3 = n123 * b2Cross(w1, w2); + + // w1 region + if (d12_2 <= 0.0f && d13_2 <= 0.0f) + { + m_v1.a = 1.0f; + m_count = 1; + return; + } + + // e12 + if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) + { + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; + return; + } + + // e13 + if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) + { + float32 inv_d13 = 1.0f / (d13_1 + d13_2); + m_v1.a = d13_1 * inv_d13; + m_v3.a = d13_2 * inv_d13; + m_count = 2; + m_v2 = m_v3; + return; + } + + // w2 region + if (d12_1 <= 0.0f && d23_2 <= 0.0f) + { + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } + + // w3 region + if (d13_1 <= 0.0f && d23_1 <= 0.0f) + { + m_v3.a = 1.0f; + m_count = 1; + m_v1 = m_v3; + return; + } + + // e23 + if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) + { + float32 inv_d23 = 1.0f / (d23_1 + d23_2); + m_v2.a = d23_1 * inv_d23; + m_v3.a = d23_2 * inv_d23; + m_count = 2; + m_v1 = m_v3; + return; + } + + // Must be in triangle123 + float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); + m_v1.a = d123_1 * inv_d123; + m_v2.a = d123_2 * inv_d123; + m_v3.a = d123_3 * inv_d123; + m_count = 3; +} + +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input) +{ + ++b2_gjkCalls; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Transform transformA = input->transformA; + b2Transform transformB = input->transformB; + + // Initialize the simplex. + b2Simplex simplex; + simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); + + // Get simplex vertices as an array. + b2SimplexVertex* vertices = &simplex.m_v1; + const int32 k_maxIters = 20; + + // These store the vertices of the last simplex so that we + // can check for duplicates and prevent cycling. + int32 saveA[3], saveB[3]; + int32 saveCount = 0; + + b2Vec2 closestPoint = simplex.GetClosestPoint(); + float32 distanceSqr1 = closestPoint.LengthSquared(); + float32 distanceSqr2 = distanceSqr1; + + // Main iteration loop. + int32 iter = 0; + while (iter < k_maxIters) + { + // Copy simplex so we can identify duplicates. + saveCount = simplex.m_count; + for (int32 i = 0; i < saveCount; ++i) + { + saveA[i] = vertices[i].indexA; + saveB[i] = vertices[i].indexB; + } + + switch (simplex.m_count) + { + case 1: + break; + + case 2: + simplex.Solve2(); + break; + + case 3: + simplex.Solve3(); + break; + + default: + b2Assert(false); + } + + // If we have 3 points, then the origin is in the corresponding triangle. + if (simplex.m_count == 3) + { + break; + } + + // Compute closest point. + b2Vec2 p = simplex.GetClosestPoint(); + distanceSqr2 = p.LengthSquared(); + + // Ensure progress + if (distanceSqr2 >= distanceSqr1) + { + //break; + } + distanceSqr1 = distanceSqr2; + + // Get search direction. + b2Vec2 d = simplex.GetSearchDirection(); + + // Ensure the search direction is numerically fit. + if (d.LengthSquared() < b2_epsilon * b2_epsilon) + { + // The origin is probably contained by a line segment + // or triangle. Thus the shapes are overlapped. + + // We can't return zero here even though there may be overlap. + // In case the simplex is a point, segment, or triangle it is difficult + // to determine if the origin is contained in the CSO or very close to it. + break; + } + + // Compute a tentative new simplex vertex using support points. + b2SimplexVertex* vertex = vertices + simplex.m_count; + vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); + vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); + b2Vec2 wBLocal; + vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); + vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); + vertex->w = vertex->wB - vertex->wA; + + // Iteration count is equated to the number of support point calls. + ++iter; + ++b2_gjkIters; + + // Check for duplicate support points. This is the main termination criteria. + bool duplicate = false; + for (int32 i = 0; i < saveCount; ++i) + { + if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) + { + duplicate = true; + break; + } + } + + // If we found a duplicate support point we must exit to avoid cycling. + if (duplicate) + { + break; + } + + // New vertex is ok and needed. + ++simplex.m_count; + } + + b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); + + // Prepare output. + simplex.GetWitnessPoints(&output->pointA, &output->pointB); + output->distance = b2Distance(output->pointA, output->pointB); + output->iterations = iter; + + // Cache the simplex. + simplex.WriteCache(cache); + + // Apply radii if requested. + if (input->useRadii) + { + float32 rA = proxyA->m_radius; + float32 rB = proxyB->m_radius; + + if (output->distance > rA + rB && output->distance > b2_epsilon) + { + // Shapes are still no overlapped. + // Move the witness points to the outer surface. + output->distance -= rA + rB; + b2Vec2 normal = output->pointB - output->pointA; + normal.Normalize(); + output->pointA += rA * normal; + output->pointB -= rB * normal; + } + else + { + // Shapes are overlapped when radii are considered. + // Move the witness points to the middle. + b2Vec2 p = 0.5f * (output->pointA + output->pointB); + output->pointA = p; + output->pointB = p; + output->distance = 0.0f; + } + } +} diff --git a/external/Box2D/Collision/b2Distance.h b/external/Box2D/Collision/b2Distance.h new file mode 100644 index 0000000000..d598b7339d --- /dev/null +++ b/external/Box2D/Collision/b2Distance.h @@ -0,0 +1,141 @@ + +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DISTANCE_H +#define B2_DISTANCE_H + +#include + +class b2Shape; + +/// A distance proxy is used by the GJK algorithm. +/// It encapsulates any shape. +struct b2DistanceProxy +{ + b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} + + /// Initialize the proxy using the given shape. The shape + /// must remain in scope while the proxy is in use. + void Set(const b2Shape* shape, int32 index); + + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; + + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + + /// Get the vertex count. + int32 GetVertexCount() const; + + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; + + b2Vec2 m_buffer[2]; + const b2Vec2* m_vertices; + int32 m_count; + float32 m_radius; +}; + +/// Used to warm start b2Distance. +/// Set count to zero on first call. +struct b2SimplexCache +{ + float32 metric; ///< length or area + uint16 count; + uint8 indexA[3]; ///< vertices on shape A + uint8 indexB[3]; ///< vertices on shape B +}; + +/// Input for b2Distance. +/// You have to option to use the shape radii +/// in the computation. Even +struct b2DistanceInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Transform transformA; + b2Transform transformB; + bool useRadii; +}; + +/// Output for b2Distance. +struct b2DistanceOutput +{ + b2Vec2 pointA; ///< closest point on shapeA + b2Vec2 pointB; ///< closest point on shapeB + float32 distance; + int32 iterations; ///< number of GJK iterations used +}; + +/// Compute the closest points between two shapes. Supports any combination of: +/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. +/// On the first call set b2SimplexCache.count to zero. +void b2Distance(b2DistanceOutput* output, + b2SimplexCache* cache, + const b2DistanceInput* input); + + +////////////////////////////////////////////////////////////////////////// + +inline int32 b2DistanceProxy::GetVertexCount() const +{ + return m_count; +} + +inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const +{ + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; +} + +inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return bestIndex; +} + +inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const +{ + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } + + return m_vertices[bestIndex]; +} + +#endif diff --git a/external/Box2D/Collision/b2DynamicTree.cpp b/external/Box2D/Collision/b2DynamicTree.cpp new file mode 100644 index 0000000000..d1d53297e2 --- /dev/null +++ b/external/Box2D/Collision/b2DynamicTree.cpp @@ -0,0 +1,775 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#ifndef SHP +#include +#else +#include +#endif +using namespace std; + + +b2DynamicTree::b2DynamicTree() +{ + m_root = b2_nullNode; + + m_nodeCapacity = 16; + m_nodeCount = 0; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); + + // Build a linked list for the free list. + for (int32 i = 0; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = 0; + + m_path = 0; + + m_insertionCount = 0; +} + +b2DynamicTree::~b2DynamicTree() +{ + // This frees the entire tree in one shot. + b2Free(m_nodes); +} + +// Allocate a node from the pool. Grow the pool if necessary. +int32 b2DynamicTree::AllocateNode() +{ + // Expand the node pool as needed. + if (m_freeList == b2_nullNode) + { + b2Assert(m_nodeCount == m_nodeCapacity); + + // The free list is empty. Rebuild a bigger pool. + b2TreeNode* oldNodes = m_nodes; + m_nodeCapacity *= 2; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); + b2Free(oldNodes); + + // Build a linked list for the free list. The parent + // pointer becomes the "next" pointer. + for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = m_nodeCount; + } + + // Peel a node off the free list. + int32 nodeId = m_freeList; + m_freeList = m_nodes[nodeId].next; + m_nodes[nodeId].parent = b2_nullNode; + m_nodes[nodeId].child1 = b2_nullNode; + m_nodes[nodeId].child2 = b2_nullNode; + m_nodes[nodeId].height = 0; + m_nodes[nodeId].userData = NULL; + ++m_nodeCount; + return nodeId; +} + +// Return a node to the pool. +void b2DynamicTree::FreeNode(int32 nodeId) +{ + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2Assert(0 < m_nodeCount); + m_nodes[nodeId].next = m_freeList; + m_nodes[nodeId].height = -1; + m_freeList = nodeId; + --m_nodeCount; +} + +// Create a proxy in the tree as a leaf node. We return the index +// of the node instead of a pointer so that we can grow +// the node pool. +int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) +{ + int32 proxyId = AllocateNode(); + + // Fatten the aabb. + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; + m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; + m_nodes[proxyId].userData = userData; + m_nodes[proxyId].height = 0; + + InsertLeaf(proxyId); + + return proxyId; +} + +void b2DynamicTree::DestroyProxy(int32 proxyId) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + b2Assert(m_nodes[proxyId].IsLeaf()); + + RemoveLeaf(proxyId); + FreeNode(proxyId); +} + +bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + + b2Assert(m_nodes[proxyId].IsLeaf()); + + if (m_nodes[proxyId].aabb.Contains(aabb)) + { + return false; + } + + RemoveLeaf(proxyId); + + // Extend AABB. + b2AABB b = aabb; + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + b.lowerBound = b.lowerBound - r; + b.upperBound = b.upperBound + r; + + // Predict AABB displacement. + b2Vec2 d = b2_aabbMultiplier * displacement; + + if (d.x < 0.0f) + { + b.lowerBound.x += d.x; + } + else + { + b.upperBound.x += d.x; + } + + if (d.y < 0.0f) + { + b.lowerBound.y += d.y; + } + else + { + b.upperBound.y += d.y; + } + + m_nodes[proxyId].aabb = b; + + InsertLeaf(proxyId); + return true; +} + +void b2DynamicTree::InsertLeaf(int32 leaf) +{ + ++m_insertionCount; + + if (m_root == b2_nullNode) + { + m_root = leaf; + m_nodes[m_root].parent = b2_nullNode; + return; + } + + // Find the best sibling for this node + b2AABB leafAABB = m_nodes[leaf].aabb; + int32 index = m_root; + while (m_nodes[index].IsLeaf() == false) + { + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + float32 area = m_nodes[index].aabb.GetPerimeter(); + + b2AABB combinedAABB; + combinedAABB.Combine(m_nodes[index].aabb, leafAABB); + float32 combinedArea = combinedAABB.GetPerimeter(); + + // Cost of creating a new parent for this node and the new leaf + float32 cost = 2.0f * combinedArea; + + // Minimum cost of pushing the leaf further down the tree + float32 inheritanceCost = 2.0f * (combinedArea - area); + + // Cost of descending into child1 + float32 cost1; + if (m_nodes[child1].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + cost1 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost1 = (newArea - oldArea) + inheritanceCost; + } + + // Cost of descending into child2 + float32 cost2; + if (m_nodes[child2].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + cost2 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost2 = newArea - oldArea + inheritanceCost; + } + + // Descend according to the minimum cost. + if (cost < cost1 && cost < cost2) + { + break; + } + + // Descend + if (cost1 < cost2) + { + index = child1; + } + else + { + index = child2; + } + } + + int32 sibling = index; + + // Create a new parent. + int32 oldParent = m_nodes[sibling].parent; + int32 newParent = AllocateNode(); + m_nodes[newParent].parent = oldParent; + m_nodes[newParent].userData = NULL; + m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); + m_nodes[newParent].height = m_nodes[sibling].height + 1; + + if (oldParent != b2_nullNode) + { + // The sibling was not the root. + if (m_nodes[oldParent].child1 == sibling) + { + m_nodes[oldParent].child1 = newParent; + } + else + { + m_nodes[oldParent].child2 = newParent; + } + + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + } + else + { + // The sibling was the root. + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + m_root = newParent; + } + + // Walk back up the tree fixing heights and AABBs + index = m_nodes[leaf].parent; + while (index != b2_nullNode) + { + index = Balance(index); + + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + b2Assert(child1 != b2_nullNode); + b2Assert(child2 != b2_nullNode); + + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + index = m_nodes[index].parent; + } + + //Validate(); +} + +void b2DynamicTree::RemoveLeaf(int32 leaf) +{ + if (leaf == m_root) + { + m_root = b2_nullNode; + return; + } + + int32 parent = m_nodes[leaf].parent; + int32 grandParent = m_nodes[parent].parent; + int32 sibling; + if (m_nodes[parent].child1 == leaf) + { + sibling = m_nodes[parent].child2; + } + else + { + sibling = m_nodes[parent].child1; + } + + if (grandParent != b2_nullNode) + { + // Destroy parent and connect sibling to grandParent. + if (m_nodes[grandParent].child1 == parent) + { + m_nodes[grandParent].child1 = sibling; + } + else + { + m_nodes[grandParent].child2 = sibling; + } + m_nodes[sibling].parent = grandParent; + FreeNode(parent); + + // Adjust ancestor bounds. + int32 index = grandParent; + while (index != b2_nullNode) + { + index = Balance(index); + + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; + + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + + index = m_nodes[index].parent; + } + } + else + { + m_root = sibling; + m_nodes[sibling].parent = b2_nullNode; + FreeNode(parent); + } + + //Validate(); +} + +// Perform a left or right rotation if node A is imbalanced. +// Returns the new root index. +int32 b2DynamicTree::Balance(int32 iA) +{ + b2Assert(iA != b2_nullNode); + + b2TreeNode* A = m_nodes + iA; + if (A->IsLeaf() || A->height < 2) + { + return iA; + } + + int32 iB = A->child1; + int32 iC = A->child2; + b2Assert(0 <= iB && iB < m_nodeCapacity); + b2Assert(0 <= iC && iC < m_nodeCapacity); + + b2TreeNode* B = m_nodes + iB; + b2TreeNode* C = m_nodes + iC; + + int32 balance = C->height - B->height; + + // Rotate C up + if (balance > 1) + { + int32 iF = C->child1; + int32 iG = C->child2; + b2TreeNode* F = m_nodes + iF; + b2TreeNode* G = m_nodes + iG; + b2Assert(0 <= iF && iF < m_nodeCapacity); + b2Assert(0 <= iG && iG < m_nodeCapacity); + + // Swap A and C + C->child1 = iA; + C->parent = A->parent; + A->parent = iC; + + // A's old parent should point to C + if (C->parent != b2_nullNode) + { + if (m_nodes[C->parent].child1 == iA) + { + m_nodes[C->parent].child1 = iC; + } + else + { + b2Assert(m_nodes[C->parent].child2 == iA); + m_nodes[C->parent].child2 = iC; + } + } + else + { + m_root = iC; + } + + // Rotate + if (F->height > G->height) + { + C->child2 = iF; + A->child2 = iG; + G->parent = iA; + A->aabb.Combine(B->aabb, G->aabb); + C->aabb.Combine(A->aabb, F->aabb); + + A->height = 1 + b2Max(B->height, G->height); + C->height = 1 + b2Max(A->height, F->height); + } + else + { + C->child2 = iG; + A->child2 = iF; + F->parent = iA; + A->aabb.Combine(B->aabb, F->aabb); + C->aabb.Combine(A->aabb, G->aabb); + + A->height = 1 + b2Max(B->height, F->height); + C->height = 1 + b2Max(A->height, G->height); + } + + return iC; + } + + // Rotate B up + if (balance < -1) + { + int32 iD = B->child1; + int32 iE = B->child2; + b2TreeNode* D = m_nodes + iD; + b2TreeNode* E = m_nodes + iE; + b2Assert(0 <= iD && iD < m_nodeCapacity); + b2Assert(0 <= iE && iE < m_nodeCapacity); + + // Swap A and B + B->child1 = iA; + B->parent = A->parent; + A->parent = iB; + + // A's old parent should point to B + if (B->parent != b2_nullNode) + { + if (m_nodes[B->parent].child1 == iA) + { + m_nodes[B->parent].child1 = iB; + } + else + { + b2Assert(m_nodes[B->parent].child2 == iA); + m_nodes[B->parent].child2 = iB; + } + } + else + { + m_root = iB; + } + + // Rotate + if (D->height > E->height) + { + B->child2 = iD; + A->child1 = iE; + E->parent = iA; + A->aabb.Combine(C->aabb, E->aabb); + B->aabb.Combine(A->aabb, D->aabb); + + A->height = 1 + b2Max(C->height, E->height); + B->height = 1 + b2Max(A->height, D->height); + } + else + { + B->child2 = iE; + A->child1 = iD; + D->parent = iA; + A->aabb.Combine(C->aabb, D->aabb); + B->aabb.Combine(A->aabb, E->aabb); + + A->height = 1 + b2Max(C->height, D->height); + B->height = 1 + b2Max(A->height, E->height); + } + + return iB; + } + + return iA; +} + +int32 b2DynamicTree::GetHeight() const +{ + if (m_root == b2_nullNode) + { + return 0; + } + + return m_nodes[m_root].height; +} + +// +float32 b2DynamicTree::GetAreaRatio() const +{ + if (m_root == b2_nullNode) + { + return 0.0f; + } + + const b2TreeNode* root = m_nodes + m_root; + float32 rootArea = root->aabb.GetPerimeter(); + + float32 totalArea = 0.0f; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height < 0) + { + // Free node in pool + continue; + } + + totalArea += node->aabb.GetPerimeter(); + } + + return totalArea / rootArea; +} + +// Compute the height of a sub-tree. +int32 b2DynamicTree::ComputeHeight(int32 nodeId) const +{ + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2TreeNode* node = m_nodes + nodeId; + + if (node->IsLeaf()) + { + return 0; + } + + int32 height1 = ComputeHeight(node->child1); + int32 height2 = ComputeHeight(node->child2); + return 1 + b2Max(height1, height2); +} + +int32 b2DynamicTree::ComputeHeight() const +{ + int32 height = ComputeHeight(m_root); + return height; +} + +void b2DynamicTree::ValidateStructure(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + if (index == m_root) + { + b2Assert(m_nodes[index].parent == b2_nullNode); + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + b2Assert(m_nodes[child1].parent == index); + b2Assert(m_nodes[child2].parent == index); + + ValidateStructure(child1); + ValidateStructure(child2); +} + +void b2DynamicTree::ValidateMetrics(int32 index) const +{ + if (index == b2_nullNode) + { + return; + } + + const b2TreeNode* node = m_nodes + index; + + int32 child1 = node->child1; + int32 child2 = node->child2; + + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } + + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); + + int32 height1 = m_nodes[child1].height; + int32 height2 = m_nodes[child2].height; + int32 height; + height = 1 + b2Max(height1, height2); + b2Assert(node->height == height); + + b2AABB aabb; + aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + + b2Assert(aabb.lowerBound == node->aabb.lowerBound); + b2Assert(aabb.upperBound == node->aabb.upperBound); + + ValidateMetrics(child1); + ValidateMetrics(child2); +} + +void b2DynamicTree::Validate() const +{ + ValidateStructure(m_root); + ValidateMetrics(m_root); + + int32 freeCount = 0; + int32 freeIndex = m_freeList; + while (freeIndex != b2_nullNode) + { + b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); + freeIndex = m_nodes[freeIndex].next; + ++freeCount; + } + + b2Assert(GetHeight() == ComputeHeight()); + + b2Assert(m_nodeCount + freeCount == m_nodeCapacity); +} + +int32 b2DynamicTree::GetMaxBalance() const +{ + int32 maxBalance = 0; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height <= 1) + { + continue; + } + + b2Assert(node->IsLeaf() == false); + + int32 child1 = node->child1; + int32 child2 = node->child2; + int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); + maxBalance = b2Max(maxBalance, balance); + } + + return maxBalance; +} + +void b2DynamicTree::RebuildBottomUp() +{ + int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); + int32 count = 0; + + // Build array of leaves. Free the rest. + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + if (m_nodes[i].height < 0) + { + // free node in pool + continue; + } + + if (m_nodes[i].IsLeaf()) + { + m_nodes[i].parent = b2_nullNode; + nodes[count] = i; + ++count; + } + else + { + FreeNode(i); + } + } + + while (count > 1) + { + float32 minCost = b2_maxFloat; + int32 iMin = -1, jMin = -1; + for (int32 i = 0; i < count; ++i) + { + b2AABB aabbi = m_nodes[nodes[i]].aabb; + + for (int32 j = i + 1; j < count; ++j) + { + b2AABB aabbj = m_nodes[nodes[j]].aabb; + b2AABB b; + b.Combine(aabbi, aabbj); + float32 cost = b.GetPerimeter(); + if (cost < minCost) + { + iMin = i; + jMin = j; + minCost = cost; + } + } + } + + int32 index1 = nodes[iMin]; + int32 index2 = nodes[jMin]; + b2TreeNode* child1 = m_nodes + index1; + b2TreeNode* child2 = m_nodes + index2; + + int32 parentIndex = AllocateNode(); + b2TreeNode* parent = m_nodes + parentIndex; + parent->child1 = index1; + parent->child2 = index2; + parent->height = 1 + b2Max(child1->height, child2->height); + parent->aabb.Combine(child1->aabb, child2->aabb); + parent->parent = b2_nullNode; + + child1->parent = parentIndex; + child2->parent = parentIndex; + + nodes[jMin] = nodes[count-1]; + nodes[iMin] = parentIndex; + --count; + } + + m_root = nodes[0]; + b2Free(nodes); + + Validate(); +} diff --git a/external/Box2D/Collision/b2DynamicTree.h b/external/Box2D/Collision/b2DynamicTree.h new file mode 100644 index 0000000000..33f16b0f32 --- /dev/null +++ b/external/Box2D/Collision/b2DynamicTree.h @@ -0,0 +1,284 @@ +/* +* Copyright (c) 2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DYNAMIC_TREE_H +#define B2_DYNAMIC_TREE_H + +#include +#include + +#define b2_nullNode (-1) + +/// A node in the dynamic tree. The client does not interact with this directly. +struct b2TreeNode +{ + bool IsLeaf() const + { + return child1 == b2_nullNode; + } + + /// Enlarged AABB + b2AABB aabb; + + void* userData; + + union + { + int32 parent; + int32 next; + }; + + int32 child1; + int32 child2; + + // leaf = 0, free node = -1 + int32 height; +}; + +/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. +/// A dynamic tree arranges data in a binary tree to accelerate +/// queries such as volume queries and ray casts. Leafs are proxies +/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor +/// so that the proxy AABB is bigger than the client object. This allows the client +/// object to move by small amounts without triggering a tree update. +/// +/// Nodes are pooled and relocatable, so we use node indices rather than pointers. +class b2DynamicTree +{ +public: + /// Constructing the tree initializes the node pool. + b2DynamicTree(); + + /// Destroy the tree, freeing the node pool. + ~b2DynamicTree(); + + /// Create a proxy. Provide a tight fitting AABB and a userData pointer. + int32 CreateProxy(const b2AABB& aabb, void* userData); + + /// Destroy a proxy. This asserts if the id is invalid. + void DestroyProxy(int32 proxyId); + + /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, + /// then the proxy is removed from the tree and re-inserted. Otherwise + /// the function returns immediately. + /// @return true if the proxy was re-inserted. + bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); + + /// Get proxy user data. + /// @return the proxy user data or 0 if the id is invalid. + void* GetUserData(int32 proxyId) const; + + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; + + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; + + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; + + /// Validate this tree. For testing. + void Validate() const; + + /// Compute the height of the binary tree in O(N) time. Should not be + /// called often. + int32 GetHeight() const; + + /// Get the maximum balance of an node in the tree. The balance is the difference + /// in height of the two children of a node. + int32 GetMaxBalance() const; + + /// Get the ratio of the sum of the node areas to the root area. + float32 GetAreaRatio() const; + + /// Build an optimal tree. Very expensive. For testing. + void RebuildBottomUp(); + +private: + + int32 AllocateNode(); + void FreeNode(int32 node); + + void InsertLeaf(int32 node); + void RemoveLeaf(int32 node); + + int32 Balance(int32 index); + + int32 ComputeHeight() const; + int32 ComputeHeight(int32 nodeId) const; + + void ValidateStructure(int32 index) const; + void ValidateMetrics(int32 index) const; + + int32 m_root; + + b2TreeNode* m_nodes; + int32 m_nodeCount; + int32 m_nodeCapacity; + + int32 m_freeList; + + /// This is used to incrementally traverse the tree for re-balancing. + uint32 m_path; + + int32 m_insertionCount; +}; + +inline void* b2DynamicTree::GetUserData(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].userData; +} + +inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const +{ + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].aabb; +} + +template +inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const +{ + b2GrowableStack stack; + stack.Push(m_root); + + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } + + const b2TreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, aabb)) + { + if (node->IsLeaf()) + { + bool proceed = callback->QueryCallback(nodeId); + if (proceed == false) + { + return; + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } + } +} + +template +inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const +{ + b2Vec2 p1 = input.p1; + b2Vec2 p2 = input.p2; + b2Vec2 r = p2 - p1; + b2Assert(r.LengthSquared() > 0.0f); + r.Normalize(); + + // v is perpendicular to the segment. + b2Vec2 v = b2Cross(1.0f, r); + b2Vec2 abs_v = b2Abs(v); + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + + float32 maxFraction = input.maxFraction; + + // Build a bounding box for the segment. + b2AABB segmentAABB; + { + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + + b2GrowableStack stack; + stack.Push(m_root); + + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } + + const b2TreeNode* node = m_nodes + nodeId; + + if (b2TestOverlap(node->aabb, segmentAABB) == false) + { + continue; + } + + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + b2Vec2 c = node->aabb.GetCenter(); + b2Vec2 h = node->aabb.GetExtents(); + float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); + if (separation > 0.0f) + { + continue; + } + + if (node->IsLeaf()) + { + b2RayCastInput subInput; + subInput.p1 = input.p1; + subInput.p2 = input.p2; + subInput.maxFraction = maxFraction; + + float32 value = callback->RayCastCallback(subInput, nodeId); + + if (value == 0.0f) + { + // The client has terminated the ray cast. + return; + } + + if (value > 0.0f) + { + // Update segment bounding box. + maxFraction = value; + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } +} + +#endif diff --git a/external/Box2D/Collision/b2TimeOfImpact.cpp b/external/Box2D/Collision/b2TimeOfImpact.cpp new file mode 100644 index 0000000000..1d643addd8 --- /dev/null +++ b/external/Box2D/Collision/b2TimeOfImpact.cpp @@ -0,0 +1,488 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#ifdef SHP +#include +#else +#include +#endif + +using namespace std; + +int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; +int32 b2_toiRootIters, b2_toiMaxRootIters; + +struct b2SeparationFunction +{ + enum Type + { + e_points, + e_faceA, + e_faceB + }; + + // TODO_ERIN might not need to return the separation + + float32 Initialize(const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Sweep& sweepA, + const b2DistanceProxy* proxyB, const b2Sweep& sweepB, + float32 t1) + { + m_proxyA = proxyA; + m_proxyB = proxyB; + int32 count = cache->count; + b2Assert(0 < count && count < 3); + + m_sweepA = sweepA; + m_sweepB = sweepB; + + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t1); + m_sweepB.GetTransform(&xfB, t1); + + if (count == 1) + { + m_type = e_points; + b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + m_axis = pointB - pointA; + float32 s = m_axis.Normalize(); + return s; + } + else if (cache->indexA[0] == cache->indexA[1]) + { + // Two points on B and one on A. + m_type = e_faceB; + b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); + b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); + + m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfB.q, m_axis); + + m_localPoint = 0.5f * (localPointB1 + localPointB2); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 s = b2Dot(pointA - pointB, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + else + { + // Two points on A and one or two points on B. + m_type = e_faceA; + b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); + + m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfA.q, m_axis); + + m_localPoint = 0.5f * (localPointA1 + localPointA2); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 s = b2Dot(pointB - pointA, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + } + + float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + + *indexA = m_proxyA->GetSupport(axisA); + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, m_axis); + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.q, -normal); + + *indexA = -1; + *indexB = m_proxyB->GetSupport(axisB); + + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.q, -normal); + + *indexB = -1; + *indexA = m_proxyA->GetSupport(axisA); + + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + *indexA = -1; + *indexB = -1; + return 0.0f; + } + } + + float32 Evaluate(int32 indexA, int32 indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); + + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + float32 separation = b2Dot(pointB - pointA, m_axis); + + return separation; + } + + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); + + b2Vec2 axisB = b2MulT(xfB.q, -normal); + + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); + + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } + + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); + + b2Vec2 axisA = b2MulT(xfA.q, -normal); + + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); + + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } + + default: + b2Assert(false); + return 0.0f; + } + } + + const b2DistanceProxy* m_proxyA; + const b2DistanceProxy* m_proxyB; + b2Sweep m_sweepA, m_sweepB; + Type m_type; + b2Vec2 m_localPoint; + b2Vec2 m_axis; +}; + +// CCD via the local separating axis method. This seeks progression +// by computing the largest time at which separation is maintained. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) +{ + ++b2_toiCalls; + + output->state = b2TOIOutput::e_unknown; + output->t = input->tMax; + + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; + + b2Sweep sweepA = input->sweepA; + b2Sweep sweepB = input->sweepB; + + // Large rotations can make the root finder fail, so we normalize the + // sweep angles. + sweepA.Normalize(); + sweepB.Normalize(); + + float32 tMax = input->tMax; + + float32 totalRadius = proxyA->m_radius + proxyB->m_radius; + float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); + float32 tolerance = 0.25f * b2_linearSlop; + b2Assert(target > tolerance); + + float32 t1 = 0.0f; + const int32 k_maxIterations = 20; // TODO_ERIN b2Settings + int32 iter = 0; + + // Prepare input for distance query. + b2SimplexCache cache; + cache.count = 0; + b2DistanceInput distanceInput; + distanceInput.proxyA = input->proxyA; + distanceInput.proxyB = input->proxyB; + distanceInput.useRadii = false; + + // The outer loop progressively attempts to compute new separating axes. + // This loop terminates when an axis is repeated (no progress is made). + for(;;) + { + b2Transform xfA, xfB; + sweepA.GetTransform(&xfA, t1); + sweepB.GetTransform(&xfB, t1); + + // Get the distance between shapes. We can also use the results + // to get a separating axis. + distanceInput.transformA = xfA; + distanceInput.transformB = xfB; + b2DistanceOutput distanceOutput; + b2Distance(&distanceOutput, &cache, &distanceInput); + + // If the shapes are overlapped, we give up on continuous collision. + if (distanceOutput.distance <= 0.0f) + { + // Failure! + output->state = b2TOIOutput::e_overlapped; + output->t = 0.0f; + break; + } + + if (distanceOutput.distance < target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_touching; + output->t = t1; + break; + } + + // Initialize the separating axis. + b2SeparationFunction fcn; + fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); +#if 0 + // Dump the curve seen by the root finder + { + const int32 N = 100; + float32 dx = 1.0f / N; + float32 xs[N+1]; + float32 fs[N+1]; + + float32 x = 0.0f; + + for (int32 i = 0; i <= N; ++i) + { + sweepA.GetTransform(&xfA, x); + sweepB.GetTransform(&xfB, x); + float32 f = fcn.Evaluate(xfA, xfB) - target; + + printf("%g %g\n", x, f); + + xs[i] = x; + fs[i] = f; + + x += dx; + } + } +#endif + + // Compute the TOI on the separating axis. We do this by successively + // resolving the deepest point. This loop is bounded by the number of vertices. + bool done = false; + float32 t2 = tMax; + int32 pushBackIter = 0; + for (;;) + { + // Find the deepest point at t2. Store the witness point indices. + int32 indexA, indexB; + float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); + + // Is the final configuration separated? + if (s2 > target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_separated; + output->t = tMax; + done = true; + break; + } + + // Has the separation reached tolerance? + if (s2 > target - tolerance) + { + // Advance the sweeps + t1 = t2; + break; + } + + // Compute the initial separation of the witness points. + float32 s1 = fcn.Evaluate(indexA, indexB, t1); + + // Check for initial overlap. This might happen if the root finder + // runs out of iterations. + if (s1 < target - tolerance) + { + output->state = b2TOIOutput::e_failed; + output->t = t1; + done = true; + break; + } + + // Check for touching + if (s1 <= target + tolerance) + { + // Victory! t1 should hold the TOI (could be 0.0). + output->state = b2TOIOutput::e_touching; + output->t = t1; + done = true; + break; + } + + // Compute 1D root of: f(x) - target = 0 + int32 rootIterCount = 0; + float32 a1 = t1, a2 = t2; + for (;;) + { + // Use a mix of the secant rule and bisection. + float32 t; + if (rootIterCount & 1) + { + // Secant rule to improve convergence. + t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); + } + else + { + // Bisection to guarantee progress. + t = 0.5f * (a1 + a2); + } + + float32 s = fcn.Evaluate(indexA, indexB, t); + + if (b2Abs(s - target) < tolerance) + { + // t2 holds a tentative value for t1 + t2 = t; + break; + } + + // Ensure we continue to bracket the root. + if (s > target) + { + a1 = t; + s1 = s; + } + else + { + a2 = t; + s2 = s; + } + + ++rootIterCount; + ++b2_toiRootIters; + + if (rootIterCount == 50) + { + break; + } + } + + b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); + + ++pushBackIter; + + if (pushBackIter == b2_maxPolygonVertices) + { + break; + } + } + + ++iter; + ++b2_toiIters; + + if (done) + { + break; + } + + if (iter == k_maxIterations) + { + // Root finder got stuck. Semi-victory. + output->state = b2TOIOutput::e_failed; + output->t = t1; + break; + } + } + + b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); +} diff --git a/external/Box2D/Collision/b2TimeOfImpact.h b/external/Box2D/Collision/b2TimeOfImpact.h new file mode 100644 index 0000000000..2e4f8228ff --- /dev/null +++ b/external/Box2D/Collision/b2TimeOfImpact.h @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TIME_OF_IMPACT_H +#define B2_TIME_OF_IMPACT_H + +#include +#include + +/// Input parameters for b2TimeOfImpact +struct b2TOIInput +{ + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Sweep sweepA; + b2Sweep sweepB; + float32 tMax; // defines sweep interval [0, tMax] +}; + +// Output parameters for b2TimeOfImpact. +struct b2TOIOutput +{ + enum State + { + e_unknown, + e_failed, + e_overlapped, + e_touching, + e_separated + }; + + State state; + float32 t; +}; + +/// Compute the upper bound on time before two shapes penetrate. Time is represented as +/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, +/// non-tunneling collision. If you change the time interval, you should call this function +/// again. +/// Note: use b2Distance to compute the contact point and normal at the time of impact. +void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); + +#endif diff --git a/external/Box2D/Common/b2BlockAllocator.cpp b/external/Box2D/Common/b2BlockAllocator.cpp new file mode 100644 index 0000000000..2e862091f9 --- /dev/null +++ b/external/Box2D/Common/b2BlockAllocator.cpp @@ -0,0 +1,218 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +using namespace std; + +int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = +{ + 16, // 0 + 32, // 1 + 64, // 2 + 96, // 3 + 128, // 4 + 160, // 5 + 192, // 6 + 224, // 7 + 256, // 8 + 320, // 9 + 384, // 10 + 448, // 11 + 512, // 12 + 640, // 13 +}; +uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; +bool b2BlockAllocator::s_blockSizeLookupInitialized; + +struct b2Chunk +{ + int32 blockSize; + b2Block* blocks; +}; + +struct b2Block +{ + b2Block* next; +}; + +b2BlockAllocator::b2BlockAllocator() +{ + b2Assert(b2_blockSizes < UCHAR_MAX); + + m_chunkSpace = b2_chunkArrayIncrement; + m_chunkCount = 0; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + memset(m_freeLists, 0, sizeof(m_freeLists)); + + if (s_blockSizeLookupInitialized == false) + { + int32 j = 0; + for (int32 i = 1; i <= b2_maxBlockSize; ++i) + { + b2Assert(j < b2_blockSizes); + if (i <= s_blockSizes[j]) + { + s_blockSizeLookup[i] = (uint8)j; + } + else + { + ++j; + s_blockSizeLookup[i] = (uint8)j; + } + } + + s_blockSizeLookupInitialized = true; + } +} + +b2BlockAllocator::~b2BlockAllocator() +{ + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } + + b2Free(m_chunks); +} + +void* b2BlockAllocator::Allocate(int32 size) +{ + if (size == 0) + return NULL; + + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + return b2Alloc(size); + } + + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); + + if (m_freeLists[index]) + { + b2Block* block = m_freeLists[index]; + m_freeLists[index] = block->next; + return block; + } + else + { + if (m_chunkCount == m_chunkSpace) + { + b2Chunk* oldChunks = m_chunks; + m_chunkSpace += b2_chunkArrayIncrement; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); + memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); + b2Free(oldChunks); + } + + b2Chunk* chunk = m_chunks + m_chunkCount; + chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); +#if defined(_DEBUG) + memset(chunk->blocks, 0xcd, b2_chunkSize); +#endif + int32 blockSize = s_blockSizes[index]; + chunk->blockSize = blockSize; + int32 blockCount = b2_chunkSize / blockSize; + b2Assert(blockCount * blockSize <= b2_chunkSize); + for (int32 i = 0; i < blockCount - 1; ++i) + { + b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); + b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); + block->next = next; + } + b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); + last->next = NULL; + + m_freeLists[index] = chunk->blocks->next; + ++m_chunkCount; + + return chunk->blocks; + } +} + +void b2BlockAllocator::Free(void* p, int32 size) +{ + if (size == 0) + { + return; + } + + b2Assert(0 < size); + + if (size > b2_maxBlockSize) + { + b2Free(p); + return; + } + + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); + +#ifdef _DEBUG + // Verify the memory address and size is valid. + int32 blockSize = s_blockSizes[index]; + bool found = false; + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Chunk* chunk = m_chunks + i; + if (chunk->blockSize != blockSize) + { + b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || + (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); + } + else + { + if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) + { + found = true; + } + } + } + + b2Assert(found); + + memset(p, 0xfd, blockSize); +#endif + + b2Block* block = (b2Block*)p; + block->next = m_freeLists[index]; + m_freeLists[index] = block; +} + +void b2BlockAllocator::Clear() +{ + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } + + m_chunkCount = 0; + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + + memset(m_freeLists, 0, sizeof(m_freeLists)); +} diff --git a/external/Box2D/Common/b2BlockAllocator.h b/external/Box2D/Common/b2BlockAllocator.h new file mode 100644 index 0000000000..ec221fdf61 --- /dev/null +++ b/external/Box2D/Common/b2BlockAllocator.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BLOCK_ALLOCATOR_H +#define B2_BLOCK_ALLOCATOR_H + +#include + +const int32 b2_chunkSize = 16 * 1024; +const int32 b2_maxBlockSize = 640; +const int32 b2_blockSizes = 14; +const int32 b2_chunkArrayIncrement = 128; + +struct b2Block; +struct b2Chunk; + +/// This is a small object allocator used for allocating small +/// objects that persist for more than one time step. +/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp +class b2BlockAllocator +{ +public: + b2BlockAllocator(); + ~b2BlockAllocator(); + + /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. + void* Allocate(int32 size); + + /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. + void Free(void* p, int32 size); + + void Clear(); + +private: + + b2Chunk* m_chunks; + int32 m_chunkCount; + int32 m_chunkSpace; + + b2Block* m_freeLists[b2_blockSizes]; + + static int32 s_blockSizes[b2_blockSizes]; + static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; + static bool s_blockSizeLookupInitialized; +}; + +#endif diff --git a/external/Box2D/Common/b2Draw.cpp b/external/Box2D/Common/b2Draw.cpp new file mode 100644 index 0000000000..cb760025e9 --- /dev/null +++ b/external/Box2D/Common/b2Draw.cpp @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +b2Draw::b2Draw() +{ + m_drawFlags = 0; +} + +void b2Draw::SetFlags(uint32 flags) +{ + m_drawFlags = flags; +} + +uint32 b2Draw::GetFlags() const +{ + return m_drawFlags; +} + +void b2Draw::AppendFlags(uint32 flags) +{ + m_drawFlags |= flags; +} + +void b2Draw::ClearFlags(uint32 flags) +{ + m_drawFlags &= ~flags; +} diff --git a/external/Box2D/Common/b2Draw.h b/external/Box2D/Common/b2Draw.h new file mode 100644 index 0000000000..b33cd8d38f --- /dev/null +++ b/external/Box2D/Common/b2Draw.h @@ -0,0 +1,81 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +/// Color for debug drawing. Each value has the range [0,1]. +struct b2Color +{ + b2Color() {} + b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} + void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } + float32 r, g, b; +}; + +/// Implement and register this class with a b2World to provide debug drawing of physics +/// entities in your game. +class b2Draw +{ +public: + b2Draw(); + + virtual ~b2Draw() {} + + enum + { + e_shapeBit = 0x0001, ///< draw shapes + e_jointBit = 0x0002, ///< draw joint connections + e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes + e_pairBit = 0x0008, ///< draw broad-phase pairs + e_centerOfMassBit = 0x0010 ///< draw center of mass frame + }; + + /// Set the drawing flags. + void SetFlags(uint32 flags); + + /// Get the drawing flags. + uint32 GetFlags() const; + + /// Append flags to the current flags. + void AppendFlags(uint32 flags); + + /// Clear flags from the current flags. + void ClearFlags(uint32 flags); + + /// Draw a closed polygon provided in CCW order. + virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a solid closed polygon provided in CCW order. + virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + + /// Draw a circle. + virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; + + /// Draw a solid circle. + virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; + + /// Draw a line segment. + virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; + + /// Draw a transform. Choose your own length scale. + /// @param xf a transform. + virtual void DrawTransform(const b2Transform& xf) = 0; + +protected: + uint32 m_drawFlags; +}; diff --git a/external/Box2D/Common/b2GrowableStack.h b/external/Box2D/Common/b2GrowableStack.h new file mode 100644 index 0000000000..68809521f4 --- /dev/null +++ b/external/Box2D/Common/b2GrowableStack.h @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_GROWABLE_STACK_H +#define B2_GROWABLE_STACK_H +#include +#include + +/// This is a growable LIFO stack with an initial capacity of N. +/// If the stack size exceeds the initial capacity, the heap is used +/// to increase the size of the stack. +template +class b2GrowableStack +{ +public: + b2GrowableStack() + { + m_stack = m_array; + m_count = 0; + m_capacity = N; + } + + ~b2GrowableStack() + { + if (m_stack != m_array) + { + b2Free(m_stack); + m_stack = NULL; + } + } + + void Push(const T& element) + { + if (m_count == m_capacity) + { + T* old = m_stack; + m_capacity *= 2; + m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); + std::memcpy(m_stack, old, m_count * sizeof(T)); + if (old != m_array) + { + b2Free(old); + } + } + + m_stack[m_count] = element; + ++m_count; + } + + T Pop() + { + b2Assert(m_count > 0); + --m_count; + return m_stack[m_count]; + } + + int32 GetCount() + { + return m_count; + } + +private: + T* m_stack; + T m_array[N]; + int32 m_count; + int32 m_capacity; +}; + + +#endif diff --git a/external/Box2D/Common/b2Math.cpp b/external/Box2D/Common/b2Math.cpp new file mode 100644 index 0000000000..15d68fce96 --- /dev/null +++ b/external/Box2D/Common/b2Math.cpp @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +const b2Vec2 b2Vec2_zero(0.0f, 0.0f); + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const +{ + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec3 x; + x.x = det * b2Dot(b, b2Cross(ey, ez)); + x.y = det * b2Dot(ex, b2Cross(b, ez)); + x.z = det * b2Dot(ex, b2Cross(ey, b)); + return x; +} + +/// Solve A * x = b, where b is a column vector. This is more efficient +/// than computing the inverse in one-shot cases. +b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const +{ + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; +} + +/// +void b2Mat33::GetInverse22(b2Mat33* M) const +{ + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + + M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; + M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; + M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; +} + +/// Returns the zero matrix if singular. +void b2Mat33::GetSymInverse33(b2Mat33* M) const +{ + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + + float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; + float32 a22 = ey.y, a23 = ez.y; + float32 a33 = ez.z; + + M->ex.x = det * (a22 * a33 - a23 * a23); + M->ex.y = det * (a13 * a23 - a12 * a33); + M->ex.z = det * (a12 * a23 - a13 * a22); + + M->ey.x = M->ex.y; + M->ey.y = det * (a11 * a33 - a13 * a13); + M->ey.z = det * (a13 * a12 - a11 * a23); + + M->ez.x = M->ex.z; + M->ez.y = M->ey.z; + M->ez.z = det * (a11 * a22 - a12 * a12); +} diff --git a/external/Box2D/Common/b2Math.h b/external/Box2D/Common/b2Math.h new file mode 100644 index 0000000000..a6be671139 --- /dev/null +++ b/external/Box2D/Common/b2Math.h @@ -0,0 +1,738 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_MATH_H +#define B2_MATH_H + +#include + +#include +#ifndef SHP +#include +#else +#include +#endif +#include +#include + +using namespace std; + + +/// This function is used to ensure that a floating point number is +/// not a NaN or infinity. +inline bool b2IsValid(float32 x) +{ + if (x != x) + { + // NaN. + return false; + } + + float32 infinity = std::numeric_limits::infinity(); + return -infinity < x && x < infinity; +} + +/// This is a approximate yet fast inverse square-root. +inline float32 b2InvSqrt(float32 x) +{ + union + { + float32 x; + int32 i; + } convert; + + convert.x = x; + float32 xhalf = 0.5f * x; + convert.i = 0x5f3759df - (convert.i >> 1); + x = convert.x; + x = x * (1.5f - xhalf * x * x); + return x; +} + +#define b2Sqrt(x) std::sqrt(x) +#define b2Atan2(y, x) std::atan2(y, x) + +/// A 2D column vector. +struct b2Vec2 +{ + /// Default constructor does nothing (for performance). + b2Vec2() {} + + /// Construct using coordinates. + b2Vec2(float32 x, float32 y) : x(x), y(y) {} + + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; } + + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_) { x = x_; y = y_; } + + /// Negate this vector. + b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } + + /// Read from and indexed element. + float32 operator () (int32 i) const + { + return (&x)[i]; + } + + /// Write to an indexed element. + float32& operator () (int32 i) + { + return (&x)[i]; + } + + /// Add a vector to this vector. + void operator += (const b2Vec2& v) + { + x += v.x; y += v.y; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec2& v) + { + x -= v.x; y -= v.y; + } + + /// Multiply this vector by a scalar. + void operator *= (float32 a) + { + x *= a; y *= a; + } + + /// Get the length of this vector (the norm). + float32 Length() const + { + return b2Sqrt(x * x + y * y); + } + + /// Get the length squared. For performance, use this instead of + /// b2Vec2::Length (if possible). + float32 LengthSquared() const + { + return x * x + y * y; + } + + /// Convert this vector into a unit vector. Returns the length. + float32 Normalize() + { + float32 length = Length(); + if (length < b2_epsilon) + { + return 0.0f; + } + float32 invLength = 1.0f / length; + x *= invLength; + y *= invLength; + + return length; + } + + /// Does this vector contain finite coordinates? + bool IsValid() const + { + return b2IsValid(x) && b2IsValid(y); + } + + /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + b2Vec2 Skew() const + { + return b2Vec2(-y, x); + } + + float32 x, y; +}; + +/// A 2D column vector with 3 elements. +struct b2Vec3 +{ + /// Default constructor does nothing (for performance). + b2Vec3() {} + + /// Construct using coordinates. + b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} + + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } + + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } + + /// Negate this vector. + b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } + + /// Add a vector to this vector. + void operator += (const b2Vec3& v) + { + x += v.x; y += v.y; z += v.z; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec3& v) + { + x -= v.x; y -= v.y; z -= v.z; + } + + /// Multiply this vector by a scalar. + void operator *= (float32 s) + { + x *= s; y *= s; z *= s; + } + + float32 x, y, z; +}; + +/// A 2-by-2 matrix. Stored in column-major order. +struct b2Mat22 +{ + /// The default constructor does nothing (for performance). + b2Mat22() {} + + /// Construct this matrix using columns. + b2Mat22(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } + + /// Construct this matrix using scalars. + b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) + { + ex.x = a11; ex.y = a21; + ey.x = a12; ey.y = a22; + } + + /// Initialize this matrix using columns. + void Set(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } + + /// Set this to the identity matrix. + void SetIdentity() + { + ex.x = 1.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 1.0f; + } + + /// Set this matrix to all zeros. + void SetZero() + { + ex.x = 0.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 0.0f; + } + + b2Mat22 GetInverse() const + { + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + b2Mat22 B; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + B.ex.x = det * d; B.ey.x = -det * b; + B.ex.y = -det * c; B.ey.y = det * a; + return B; + } + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec2 Solve(const b2Vec2& b) const + { + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; + } + + b2Vec2 ex, ey; +}; + +/// A 3-by-3 matrix. Stored in column-major order. +struct b2Mat33 +{ + /// The default constructor does nothing (for performance). + b2Mat33() {} + + /// Construct this matrix using columns. + b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) + { + ex = c1; + ey = c2; + ez = c3; + } + + /// Set this matrix to all zeros. + void SetZero() + { + ex.SetZero(); + ey.SetZero(); + ez.SetZero(); + } + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec3 Solve33(const b2Vec3& b) const; + + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. Solve only the upper + /// 2-by-2 matrix equation. + b2Vec2 Solve22(const b2Vec2& b) const; + + /// Get the inverse of this matrix as a 2-by-2. + /// Returns the zero matrix if singular. + void GetInverse22(b2Mat33* M) const; + + /// Get the symmetric inverse of this matrix as a 3-by-3. + /// Returns the zero matrix if singular. + void GetSymInverse33(b2Mat33* M) const; + + b2Vec3 ex, ey, ez; +}; + +/// Rotation +struct b2Rot +{ + b2Rot() {} + + /// Initialize from an angle in radians + explicit b2Rot(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set using an angle in radians. + void Set(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } + + /// Set to the identity rotation + void SetIdentity() + { + s = 0.0f; + c = 1.0f; + } + + /// Get the angle in radians + float32 GetAngle() const + { + return b2Atan2(s, c); + } + + /// Get the x-axis + b2Vec2 GetXAxis() const + { + return b2Vec2(c, s); + } + + /// Get the u-axis + b2Vec2 GetYAxis() const + { + return b2Vec2(-s, c); + } + + /// Sine and cosine + float32 s, c; +}; + +/// A transform contains translation and rotation. It is used to represent +/// the position and orientation of rigid frames. +struct b2Transform +{ + /// The default constructor does nothing. + b2Transform() {} + + /// Initialize using a position vector and a rotation. + b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} + + /// Set this to the identity transform. + void SetIdentity() + { + p.SetZero(); + q.SetIdentity(); + } + + /// Set this based on the position and angle. + void Set(const b2Vec2& position, float32 angle) + { + p = position; + q.Set(angle); + } + + b2Vec2 p; + b2Rot q; +}; + +/// This describes the motion of a body/shape for TOI computation. +/// Shapes are defined with respect to the body origin, which may +/// no coincide with the center of mass. However, to support dynamics +/// we must interpolate the center of mass position. +struct b2Sweep +{ + /// Get the interpolated transform at a specific time. + /// @param beta is a factor in [0,1], where 0 indicates alpha0. + void GetTransform(b2Transform* xfb, float32 beta) const; + + /// Advance the sweep forward, yielding a new initial state. + /// @param alpha the new initial time. + void Advance(float32 alpha); + + /// Normalize the angles. + void Normalize(); + + b2Vec2 localCenter; ///< local center of mass position + b2Vec2 c0, c; ///< center world positions + float32 a0, a; ///< world angles + + /// Fraction of the current time step in the range [0,1] + /// c0 and a0 are the positions at alpha0. + float32 alpha0; +}; + +/// Useful constant +extern const b2Vec2 b2Vec2_zero; + +/// Perform the dot product on two vectors. +inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) +{ + return a.x * b.x + a.y * b.y; +} + +/// Perform the cross product on two vectors. In 2D this produces a scalar. +inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) +{ + return a.x * b.y - a.y * b.x; +} + +/// Perform the cross product on a vector and a scalar. In 2D this produces +/// a vector. +inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) +{ + return b2Vec2(s * a.y, -s * a.x); +} + +/// Perform the cross product on a scalar and a vector. In 2D this produces +/// a vector. +inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) +{ + return b2Vec2(-s * a.y, s * a.x); +} + +/// Multiply a matrix times a vector. If a rotation matrix is provided, +/// then this transforms the vector from one frame to another. +inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) +{ + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); +} + +/// Multiply a matrix transpose times a vector. If a rotation matrix is provided, +/// then this transforms the vector from one frame to another (inverse transform). +inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) +{ + return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); +} + +/// Add two vectors component-wise. +inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(a.x + b.x, a.y + b.y); +} + +/// Subtract two vectors component-wise. +inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(a.x - b.x, a.y - b.y); +} + +inline b2Vec2 operator * (float32 s, const b2Vec2& a) +{ + return b2Vec2(s * a.x, s * a.y); +} + +inline bool operator == (const b2Vec2& a, const b2Vec2& b) +{ + return a.x == b.x && a.y == b.y; +} + +inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) +{ + b2Vec2 c = a - b; + return c.Length(); +} + +inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) +{ + b2Vec2 c = a - b; + return b2Dot(c, c); +} + +inline b2Vec3 operator * (float32 s, const b2Vec3& a) +{ + return b2Vec3(s * a.x, s * a.y, s * a.z); +} + +/// Add two vectors component-wise. +inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); +} + +/// Subtract two vectors component-wise. +inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); +} + +/// Perform the dot product on two vectors. +inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +/// Perform the cross product on two vectors. +inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) +{ + return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); +} + +inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) +{ + return b2Mat22(A.ex + B.ex, A.ey + B.ey); +} + +// A * B +inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) +{ + return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); +} + +// A^T * B +inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) +{ + b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); + b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); + return b2Mat22(c1, c2); +} + +/// Multiply a matrix times a vector. +inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) +{ + return v.x * A.ex + v.y * A.ey + v.z * A.ez; +} + +/// Multiply a matrix times a vector. +inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) +{ + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); +} + +/// Multiply two rotations: q * r +inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) +{ + // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] + // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] + // s = qs * rc + qc * rs + // c = qc * rc - qs * rs + b2Rot qr; + qr.s = q.s * r.c + q.c * r.s; + qr.c = q.c * r.c - q.s * r.s; + return qr; +} + +/// Transpose multiply two rotations: qT * r +inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) +{ + // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] + // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] + // s = qc * rs - qs * rc + // c = qc * rc + qs * rs + b2Rot qr; + qr.s = q.c * r.s - q.s * r.c; + qr.c = q.c * r.c + q.s * r.s; + return qr; +} + +/// Rotate a vector +inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); +} + +/// Inverse rotate a vector +inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) +{ + return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); +} + +inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) +{ + float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; + float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; + + return b2Vec2(x, y); +} + +inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) +{ + float32 px = v.x - T.p.x; + float32 py = v.y - T.p.y; + float32 x = (T.q.c * px + T.q.s * py); + float32 y = (-T.q.s * px + T.q.c * py); + + return b2Vec2(x, y); +} + +// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p +// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p +inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2Mul(A.q, B.q); + C.p = b2Mul(A.q, B.p) + A.p; + return C; +} + +// v2 = A.q' * (B.q * v1 + B.p - A.p) +// = A.q' * B.q * v1 + A.q' * (B.p - A.p) +inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) +{ + b2Transform C; + C.q = b2MulT(A.q, B.q); + C.p = b2MulT(A.q, B.p - A.p); + return C; +} + +template +inline T b2Abs(T a) +{ + return a > T(0) ? a : -a; +} + +inline b2Vec2 b2Abs(const b2Vec2& a) +{ + return b2Vec2(b2Abs(a.x), b2Abs(a.y)); +} + +inline b2Mat22 b2Abs(const b2Mat22& A) +{ + return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); +} + +template +inline T b2Min(T a, T b) +{ + return a < b ? a : b; +} + +inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); +} + +template +inline T b2Max(T a, T b) +{ + return a > b ? a : b; +} + +inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) +{ + return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); +} + +template +inline T b2Clamp(T a, T low, T high) +{ + return b2Max(low, b2Min(a, high)); +} + +inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) +{ + return b2Max(low, b2Min(a, high)); +} + +template inline void b2Swap(T& a, T& b) +{ + T tmp = a; + a = b; + b = tmp; +} + +/// "Next Largest Power of 2 +/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm +/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with +/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next +/// largest power of 2. For a 32-bit value:" +inline uint32 b2NextPowerOfTwo(uint32 x) +{ + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x + 1; +} + +inline bool b2IsPowerOfTwo(uint32 x) +{ + bool result = x > 0 && (x & (x - 1)) == 0; + return result; +} + +inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const +{ + xf->p = (1.0f - beta) * c0 + beta * c; + float32 angle = (1.0f - beta) * a0 + beta * a; + xf->q.Set(angle); + + // Shift to origin + xf->p -= b2Mul(xf->q, localCenter); +} + +inline void b2Sweep::Advance(float32 alpha) +{ + b2Assert(alpha0 < 1.0f); + float32 beta = (alpha - alpha0) / (1.0f - alpha0); + c0 = (1.0f - beta) * c0 + beta * c; + a0 = (1.0f - beta) * a0 + beta * a; + alpha0 = alpha; +} + +/// Normalize an angle in radians to be between -pi and pi +inline void b2Sweep::Normalize() +{ + float32 twoPi = 2.0f * b2_pi; + float32 d = twoPi * floorf(a0 / twoPi); + a0 -= d; + a -= d; +} + +#endif diff --git a/external/Box2D/Common/b2Settings.cpp b/external/Box2D/Common/b2Settings.cpp new file mode 100644 index 0000000000..84d6f1d0e4 --- /dev/null +++ b/external/Box2D/Common/b2Settings.cpp @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#ifdef SHP +#include +#include +#include +#include +#else +#include +#include +#include +#endif + + +using namespace std; + + +b2Version b2_version = {2, 2, 1}; + +// Memory allocators. Modify these to use your own allocator. +void* b2Alloc(int32 size) +{ + return malloc(size); +} + +void b2Free(void* mem) +{ + free(mem); +} + +// You can modify this to use your logging facility. +void b2Log(const char* string, ...) +{ +#if defined(SHP) + #ifdef _DEBUG + __App_info(__PRETTY_FUNCTION__ , __LINE__, string); + #endif +#else + va_list args; + va_start(args, string); + vprintf(string, args); + va_end(args); +#endif +} diff --git a/external/Box2D/Common/b2Settings.h b/external/Box2D/Common/b2Settings.h new file mode 100644 index 0000000000..aaf4b12ccf --- /dev/null +++ b/external/Box2D/Common/b2Settings.h @@ -0,0 +1,150 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_SETTINGS_H +#define B2_SETTINGS_H + +#include +#include + +#define B2_NOT_USED(x) ((void)(x)) +#define b2Assert(A) assert(A) + +typedef signed char int8; +typedef signed short int16; +typedef signed int int32; +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint32; +typedef float float32; +typedef double float64; + +#define b2_maxFloat FLT_MAX +#define b2_epsilon FLT_EPSILON +#define b2_pi 3.14159265359f + +/// @file +/// Global tuning constants based on meters-kilograms-seconds (MKS) units. +/// + +// Collision + +/// The maximum number of contact points between two convex shapes. Do +/// not change this value. +#define b2_maxManifoldPoints 2 + +/// The maximum number of vertices on a convex polygon. You cannot increase +/// this too much because b2BlockAllocator has a maximum object size. +#define b2_maxPolygonVertices 8 + +/// This is used to fatten AABBs in the dynamic tree. This allows proxies +/// to move by a small amount without triggering a tree adjustment. +/// This is in meters. +#define b2_aabbExtension 0.1f + +/// This is used to fatten AABBs in the dynamic tree. This is used to predict +/// the future position based on the current displacement. +/// This is a dimensionless multiplier. +#define b2_aabbMultiplier 2.0f + +/// A small length used as a collision and constraint tolerance. Usually it is +/// chosen to be numerically significant, but visually insignificant. +#define b2_linearSlop 0.005f + +/// A small angle used as a collision and constraint tolerance. Usually it is +/// chosen to be numerically significant, but visually insignificant. +#define b2_angularSlop (2.0f / 180.0f * b2_pi) + +/// The radius of the polygon/edge shape skin. This should not be modified. Making +/// this smaller means polygons will have an insufficient buffer for continuous collision. +/// Making it larger may create artifacts for vertex collision. +#define b2_polygonRadius (2.0f * b2_linearSlop) + +/// Maximum number of sub-steps per contact in continuous physics simulation. +#define b2_maxSubSteps 8 + + +// Dynamics + +/// Maximum number of contacts to be handled to solve a TOI impact. +#define b2_maxTOIContacts 32 + +/// A velocity threshold for elastic collisions. Any collision with a relative linear +/// velocity below this threshold will be treated as inelastic. +#define b2_velocityThreshold 1.0f + +/// The maximum linear position correction used when solving constraints. This helps to +/// prevent overshoot. +#define b2_maxLinearCorrection 0.2f + +/// The maximum angular position correction used when solving constraints. This helps to +/// prevent overshoot. +#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) + +/// The maximum linear velocity of a body. This limit is very large and is used +/// to prevent numerical problems. You shouldn't need to adjust this. +#define b2_maxTranslation 2.0f +#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) + +/// The maximum angular velocity of a body. This limit is very large and is used +/// to prevent numerical problems. You shouldn't need to adjust this. +#define b2_maxRotation (0.5f * b2_pi) +#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) + +/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so +/// that overlap is removed in one time step. However using values close to 1 often lead +/// to overshoot. +#define b2_baumgarte 0.2f +#define b2_toiBaugarte 0.75f + + +// Sleep + +/// The time that a body must be still before it will go to sleep. +#define b2_timeToSleep 0.5f + +/// A body cannot sleep if its linear velocity is above this tolerance. +#define b2_linearSleepTolerance 0.01f + +/// A body cannot sleep if its angular velocity is above this tolerance. +#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) + +// Memory Allocation + +/// Implement this function to use your own memory allocator. +void* b2Alloc(int32 size); + +/// If you implement b2Alloc, you should also implement this function. +void b2Free(void* mem); + +/// Logging function. +void b2Log(const char* string, ...); + +/// Version numbering scheme. +/// See http://en.wikipedia.org/wiki/Software_versioning +struct b2Version +{ + int32 major; ///< significant changes + int32 minor; ///< incremental changes + int32 revision; ///< bug fixes +}; + +/// Current version. +extern b2Version b2_version; + +#endif diff --git a/external/Box2D/Common/b2StackAllocator.cpp b/external/Box2D/Common/b2StackAllocator.cpp new file mode 100644 index 0000000000..3caa5d9127 --- /dev/null +++ b/external/Box2D/Common/b2StackAllocator.cpp @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2StackAllocator::b2StackAllocator() +{ + m_index = 0; + m_allocation = 0; + m_maxAllocation = 0; + m_entryCount = 0; +} + +b2StackAllocator::~b2StackAllocator() +{ + b2Assert(m_index == 0); + b2Assert(m_entryCount == 0); +} + +void* b2StackAllocator::Allocate(int32 size) +{ + b2Assert(m_entryCount < b2_maxStackEntries); + + b2StackEntry* entry = m_entries + m_entryCount; + entry->size = size; + if (m_index + size > b2_stackSize) + { + entry->data = (char*)b2Alloc(size); + entry->usedMalloc = true; + } + else + { + entry->data = m_data + m_index; + entry->usedMalloc = false; + m_index += size; + } + + m_allocation += size; + m_maxAllocation = b2Max(m_maxAllocation, m_allocation); + ++m_entryCount; + + return entry->data; +} + +void b2StackAllocator::Free(void* p) +{ + b2Assert(m_entryCount > 0); + b2StackEntry* entry = m_entries + m_entryCount - 1; + b2Assert(p == entry->data); + if (entry->usedMalloc) + { + b2Free(p); + } + else + { + m_index -= entry->size; + } + m_allocation -= entry->size; + --m_entryCount; + + p = NULL; +} + +int32 b2StackAllocator::GetMaxAllocation() const +{ + return m_maxAllocation; +} diff --git a/external/Box2D/Common/b2StackAllocator.h b/external/Box2D/Common/b2StackAllocator.h new file mode 100644 index 0000000000..6140d0d802 --- /dev/null +++ b/external/Box2D/Common/b2StackAllocator.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_STACK_ALLOCATOR_H +#define B2_STACK_ALLOCATOR_H + +#include + +const int32 b2_stackSize = 100 * 1024; // 100k +const int32 b2_maxStackEntries = 32; + +struct b2StackEntry +{ + char* data; + int32 size; + bool usedMalloc; +}; + +// This is a stack allocator used for fast per step allocations. +// You must nest allocate/free pairs. The code will assert +// if you try to interleave multiple allocate/free pairs. +class b2StackAllocator +{ +public: + b2StackAllocator(); + ~b2StackAllocator(); + + void* Allocate(int32 size); + void Free(void* p); + + int32 GetMaxAllocation() const; + +private: + + char m_data[b2_stackSize]; + int32 m_index; + + int32 m_allocation; + int32 m_maxAllocation; + + b2StackEntry m_entries[b2_maxStackEntries]; + int32 m_entryCount; +}; + +#endif diff --git a/external/Box2D/Common/b2Timer.cpp b/external/Box2D/Common/b2Timer.cpp new file mode 100644 index 0000000000..b2bee94513 --- /dev/null +++ b/external/Box2D/Common/b2Timer.cpp @@ -0,0 +1,100 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +#if defined(_WIN32) && !defined(SHP) + +float64 b2Timer::s_invFrequency = 0.0f; + +#include + +b2Timer::b2Timer() +{ + LARGE_INTEGER largeInteger; + + if (s_invFrequency == 0.0f) + { + QueryPerformanceFrequency(&largeInteger); + s_invFrequency = float64(largeInteger.QuadPart); + if (s_invFrequency > 0.0f) + { + s_invFrequency = 1000.0f / s_invFrequency; + } + } + + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +void b2Timer::Reset() +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); +} + +float32 b2Timer::GetMilliseconds() const +{ + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + float64 count = float64(largeInteger.QuadPart); + float32 ms = float32(s_invFrequency * (count - m_start)); + return ms; +} + +#elif defined(__linux__) || defined (__APPLE__) + +#include + +b2Timer::b2Timer() +{ + Reset(); +} + +void b2Timer::Reset() +{ + timeval t; + gettimeofday(&t, 0); + m_start_sec = t.tv_sec; + m_start_msec = t.tv_usec * 0.001f; +} + +float32 b2Timer::GetMilliseconds() const +{ + timeval t; + gettimeofday(&t, 0); + return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; +} + +#else + +b2Timer::b2Timer() +{ +} + +void b2Timer::Reset() +{ +} + +float32 b2Timer::GetMilliseconds() const +{ + return 0.0f; +} + +#endif diff --git a/external/Box2D/Common/b2Timer.h b/external/Box2D/Common/b2Timer.h new file mode 100644 index 0000000000..053a107a56 --- /dev/null +++ b/external/Box2D/Common/b2Timer.h @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +/// Timer for profiling. This has platform specific code and may +/// not work on every platform. +class b2Timer +{ +public: + + /// Constructor + b2Timer(); + + /// Reset the timer. + void Reset(); + + /// Get the time since construction or the last reset. + float32 GetMilliseconds() const; + +private: + +#if defined(_WIN32) + float64 m_start; + static float64 s_invFrequency; +#elif defined(__linux__) || defined (__APPLE__) + unsigned long m_start_sec; + unsigned long m_start_msec; +#endif +}; diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp new file mode 100644 index 0000000000..4ae4c41cd3 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); + return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); + allocator->Free(contact, sizeof(b2ChainAndCircleContact)); +} + +b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndCircle( manifold, &edge, xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h new file mode 100644 index 0000000000..1cf601a61f --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H +#define B2_CHAIN_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp new file mode 100644 index 0000000000..8116c34d1b --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); + return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); +} + +void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); + allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); +} + +b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) +: b2Contact(fixtureA, indexA, fixtureB, indexB) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndPolygon( manifold, &edge, xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h new file mode 100644 index 0000000000..381c49b844 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H +#define B2_CHAIN_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2ChainAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp new file mode 100644 index 0000000000..2436da5132 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2CircleContact)); + return new (mem) b2CircleContact(fixtureA, fixtureB); +} + +void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2CircleContact*)contact)->~b2CircleContact(); + allocator->Free(contact, sizeof(b2CircleContact)); +} + +b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideCircles(manifold, + (b2CircleShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.h b/external/Box2D/Dynamics/Contacts/b2CircleContact.h new file mode 100644 index 0000000000..6da056ae0d --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2CircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CIRCLE_CONTACT_H +#define B2_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2CircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2CircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.cpp b/external/Box2D/Dynamics/Contacts/b2Contact.cpp new file mode 100644 index 0000000000..2389af6434 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2Contact.cpp @@ -0,0 +1,240 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; +bool b2Contact::s_initialized = false; + +void b2Contact::InitializeRegisters() +{ + AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); + AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); + AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); + AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); + AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); + AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); + AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); +} + +void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, + b2Shape::Type type1, b2Shape::Type type2) +{ + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + s_registers[type1][type2].createFcn = createFcn; + s_registers[type1][type2].destroyFcn = destoryFcn; + s_registers[type1][type2].primary = true; + + if (type1 != type2) + { + s_registers[type2][type1].createFcn = createFcn; + s_registers[type2][type1].destroyFcn = destoryFcn; + s_registers[type2][type1].primary = false; + } +} + +b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) +{ + if (s_initialized == false) + { + InitializeRegisters(); + s_initialized = true; + } + + b2Shape::Type type1 = fixtureA->GetType(); + b2Shape::Type type2 = fixtureB->GetType(); + + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; + if (createFcn) + { + if (s_registers[type1][type2].primary) + { + return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); + } + else + { + return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); + } + } + else + { + return NULL; + } +} + +void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + b2Assert(s_initialized == true); + + if (contact->m_manifold.pointCount > 0) + { + contact->GetFixtureA()->GetBody()->SetAwake(true); + contact->GetFixtureB()->GetBody()->SetAwake(true); + } + + b2Shape::Type typeA = contact->GetFixtureA()->GetType(); + b2Shape::Type typeB = contact->GetFixtureB()->GetType(); + + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + + b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; + destroyFcn(contact, allocator); +} + +b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) +{ + m_flags = e_enabledFlag; + + m_fixtureA = fA; + m_fixtureB = fB; + + m_indexA = indexA; + m_indexB = indexB; + + m_manifold.pointCount = 0; + + m_prev = NULL; + m_next = NULL; + + m_nodeA.contact = NULL; + m_nodeA.prev = NULL; + m_nodeA.next = NULL; + m_nodeA.other = NULL; + + m_nodeB.contact = NULL; + m_nodeB.prev = NULL; + m_nodeB.next = NULL; + m_nodeB.other = NULL; + + m_toiCount = 0; + + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + +// Update the contact manifold and touching status. +// Note: do not assume the fixture AABBs are overlapping or are valid. +void b2Contact::Update(b2ContactListener* listener) +{ + b2Manifold oldManifold = m_manifold; + + // Re-enable this contact. + m_flags |= e_enabledFlag; + + bool touching = false; + bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; + + bool sensorA = m_fixtureA->IsSensor(); + bool sensorB = m_fixtureB->IsSensor(); + bool sensor = sensorA || sensorB; + + b2Body* bodyA = m_fixtureA->GetBody(); + b2Body* bodyB = m_fixtureB->GetBody(); + const b2Transform& xfA = bodyA->GetTransform(); + const b2Transform& xfB = bodyB->GetTransform(); + + // Is this contact a sensor? + if (sensor) + { + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); + + // Sensors don't generate manifolds. + m_manifold.pointCount = 0; + } + else + { + Evaluate(&m_manifold, xfA, xfB); + touching = m_manifold.pointCount > 0; + + // Match old contact ids to new contact ids and copy the + // stored impulses to warm start the solver. + for (int32 i = 0; i < m_manifold.pointCount; ++i) + { + b2ManifoldPoint* mp2 = m_manifold.points + i; + mp2->normalImpulse = 0.0f; + mp2->tangentImpulse = 0.0f; + b2ContactID id2 = mp2->id; + + for (int32 j = 0; j < oldManifold.pointCount; ++j) + { + b2ManifoldPoint* mp1 = oldManifold.points + j; + + if (mp1->id.key == id2.key) + { + mp2->normalImpulse = mp1->normalImpulse; + mp2->tangentImpulse = mp1->tangentImpulse; + break; + } + } + } + + if (touching != wasTouching) + { + bodyA->SetAwake(true); + bodyB->SetAwake(true); + } + } + + if (touching) + { + m_flags |= e_touchingFlag; + } + else + { + m_flags &= ~e_touchingFlag; + } + + if (wasTouching == false && touching == true && listener) + { + listener->BeginContact(this); + } + + if (wasTouching == true && touching == false && listener) + { + listener->EndContact(this); + } + + if (sensor == false && touching && listener) + { + listener->PreSolve(this, &oldManifold); + } +} diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.h b/external/Box2D/Dynamics/Contacts/b2Contact.h new file mode 100644 index 0000000000..20d9403ce7 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2Contact.h @@ -0,0 +1,331 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_H +#define B2_CONTACT_H + +#include +#include +#include +#include + +class b2Body; +class b2Contact; +class b2Fixture; +class b2World; +class b2BlockAllocator; +class b2StackAllocator; +class b2ContactListener; + +/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. +/// For example, anything slides on ice. +inline float32 b2MixFriction(float32 friction1, float32 friction2) +{ + return std::sqrt(friction1 * friction2); +} + +/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. +/// For example, a superball bounces on anything. +inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) +{ + return restitution1 > restitution2 ? restitution1 : restitution2; +} + +typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, + b2BlockAllocator* allocator); +typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); + +struct b2ContactRegister +{ + b2ContactCreateFcn* createFcn; + b2ContactDestroyFcn* destroyFcn; + bool primary; +}; + +/// A contact edge is used to connect bodies and contacts together +/// in a contact graph where each body is a node and each contact +/// is an edge. A contact edge belongs to a doubly linked list +/// maintained in each attached body. Each contact has two contact +/// nodes, one for each attached body. +struct b2ContactEdge +{ + b2Body* other; ///< provides quick access to the other body attached. + b2Contact* contact; ///< the contact + b2ContactEdge* prev; ///< the previous contact edge in the body's contact list + b2ContactEdge* next; ///< the next contact edge in the body's contact list +}; + +/// The class manages contact between two shapes. A contact exists for each overlapping +/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist +/// that has no contact points. +class b2Contact +{ +public: + + /// Get the contact manifold. Do not modify the manifold unless you understand the + /// internals of Box2D. + b2Manifold* GetManifold(); + const b2Manifold* GetManifold() const; + + /// Get the world manifold. + void GetWorldManifold(b2WorldManifold* worldManifold) const; + + /// Is this contact touching? + bool IsTouching() const; + + /// Enable/disable this contact. This can be used inside the pre-solve + /// contact listener. The contact is only disabled for the current + /// time step (or sub-step in continuous collisions). + void SetEnabled(bool flag); + + /// Has this contact been disabled? + bool IsEnabled() const; + + /// Get the next contact in the world's contact list. + b2Contact* GetNext(); + const b2Contact* GetNext() const; + + /// Get fixture A in this contact. + b2Fixture* GetFixtureA(); + const b2Fixture* GetFixtureA() const; + + /// Get the child primitive index for fixture A. + int32 GetChildIndexA() const; + + /// Get fixture B in this contact. + b2Fixture* GetFixtureB(); + const b2Fixture* GetFixtureB() const; + + /// Get the child primitive index for fixture B. + int32 GetChildIndexB() const; + + /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. + /// This value persists until set or reset. + void SetFriction(float32 friction); + + /// Get the friction. + float32 GetFriction() const; + + /// Reset the friction mixture to the default value. + void ResetFriction(); + + /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. + /// The value persists until you set or reset. + void SetRestitution(float32 restitution); + + /// Get the restitution. + float32 GetRestitution() const; + + /// Reset the restitution to the default value. + void ResetRestitution(); + + /// Evaluate this contact with your own manifold and transforms. + virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; + +protected: + friend class b2ContactManager; + friend class b2World; + friend class b2ContactSolver; + friend class b2Body; + friend class b2Fixture; + + // Flags stored in m_flags + enum + { + // Used when crawling contact graph when forming islands. + e_islandFlag = 0x0001, + + // Set when the shapes are touching. + e_touchingFlag = 0x0002, + + // This contact can be disabled (by user) + e_enabledFlag = 0x0004, + + // This contact needs filtering because a fixture filter was changed. + e_filterFlag = 0x0008, + + // This bullet contact had a TOI event + e_bulletHitFlag = 0x0010, + + // This contact has a valid TOI in m_toi + e_toiFlag = 0x0020 + }; + + /// Flag this contact for filtering. Filtering will occur the next time step. + void FlagForFiltering(); + + static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, + b2Shape::Type typeA, b2Shape::Type typeB); + static void InitializeRegisters(); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} + b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + virtual ~b2Contact() {} + + void Update(b2ContactListener* listener); + + static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; + static bool s_initialized; + + uint32 m_flags; + + // World pool and list pointers. + b2Contact* m_prev; + b2Contact* m_next; + + // Nodes for connecting bodies. + b2ContactEdge m_nodeA; + b2ContactEdge m_nodeB; + + b2Fixture* m_fixtureA; + b2Fixture* m_fixtureB; + + int32 m_indexA; + int32 m_indexB; + + b2Manifold m_manifold; + + int32 m_toiCount; + float32 m_toi; + + float32 m_friction; + float32 m_restitution; +}; + +inline b2Manifold* b2Contact::GetManifold() +{ + return &m_manifold; +} + +inline const b2Manifold* b2Contact::GetManifold() const +{ + return &m_manifold; +} + +inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const +{ + const b2Body* bodyA = m_fixtureA->GetBody(); + const b2Body* bodyB = m_fixtureB->GetBody(); + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + + worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); +} + +inline void b2Contact::SetEnabled(bool flag) +{ + if (flag) + { + m_flags |= e_enabledFlag; + } + else + { + m_flags &= ~e_enabledFlag; + } +} + +inline bool b2Contact::IsEnabled() const +{ + return (m_flags & e_enabledFlag) == e_enabledFlag; +} + +inline bool b2Contact::IsTouching() const +{ + return (m_flags & e_touchingFlag) == e_touchingFlag; +} + +inline b2Contact* b2Contact::GetNext() +{ + return m_next; +} + +inline const b2Contact* b2Contact::GetNext() const +{ + return m_next; +} + +inline b2Fixture* b2Contact::GetFixtureA() +{ + return m_fixtureA; +} + +inline const b2Fixture* b2Contact::GetFixtureA() const +{ + return m_fixtureA; +} + +inline b2Fixture* b2Contact::GetFixtureB() +{ + return m_fixtureB; +} + +inline int32 b2Contact::GetChildIndexA() const +{ + return m_indexA; +} + +inline const b2Fixture* b2Contact::GetFixtureB() const +{ + return m_fixtureB; +} + +inline int32 b2Contact::GetChildIndexB() const +{ + return m_indexB; +} + +inline void b2Contact::FlagForFiltering() +{ + m_flags |= e_filterFlag; +} + +inline void b2Contact::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Contact::GetFriction() const +{ + return m_friction; +} + +inline void b2Contact::ResetFriction() +{ + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); +} + +inline void b2Contact::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline float32 b2Contact::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Contact::ResetRestitution() +{ + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp new file mode 100644 index 0000000000..0dc740342a --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp @@ -0,0 +1,832 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include + +#include +#include +#include +#include +#include + +#define B2_DEBUG_SOLVER 0 + +struct b2ContactPositionConstraint +{ + b2Vec2 localPoints[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + b2Vec2 localCenterA, localCenterB; + float32 invIA, invIB; + b2Manifold::Type type; + float32 radiusA, radiusB; + int32 pointCount; +}; + +b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) +{ + m_step = def->step; + m_allocator = def->allocator; + m_count = def->count; + m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); + m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); + m_positions = def->positions; + m_velocities = def->velocities; + m_contacts = def->contacts; + + // Initialize position independent portions of the constraints. + for (int32 i = 0; i < m_count; ++i) + { + b2Contact* contact = m_contacts[i]; + + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + b2Shape* shapeA = fixtureA->GetShape(); + b2Shape* shapeB = fixtureB->GetShape(); + float32 radiusA = shapeA->m_radius; + float32 radiusB = shapeB->m_radius; + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + b2Manifold* manifold = contact->GetManifold(); + + int32 pointCount = manifold->pointCount; + b2Assert(pointCount > 0); + + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + vc->friction = contact->m_friction; + vc->restitution = contact->m_restitution; + vc->indexA = bodyA->m_islandIndex; + vc->indexB = bodyB->m_islandIndex; + vc->invMassA = bodyA->m_invMass; + vc->invMassB = bodyB->m_invMass; + vc->invIA = bodyA->m_invI; + vc->invIB = bodyB->m_invI; + vc->contactIndex = i; + vc->pointCount = pointCount; + vc->K.SetZero(); + vc->normalMass.SetZero(); + + b2ContactPositionConstraint* pc = m_positionConstraints + i; + pc->indexA = bodyA->m_islandIndex; + pc->indexB = bodyB->m_islandIndex; + pc->invMassA = bodyA->m_invMass; + pc->invMassB = bodyB->m_invMass; + pc->localCenterA = bodyA->m_sweep.localCenter; + pc->localCenterB = bodyB->m_sweep.localCenter; + pc->invIA = bodyA->m_invI; + pc->invIB = bodyB->m_invI; + pc->localNormal = manifold->localNormal; + pc->localPoint = manifold->localPoint; + pc->pointCount = pointCount; + pc->radiusA = radiusA; + pc->radiusB = radiusB; + pc->type = manifold->type; + + for (int32 j = 0; j < pointCount; ++j) + { + b2ManifoldPoint* cp = manifold->points + j; + b2VelocityConstraintPoint* vcp = vc->points + j; + + if (m_step.warmStarting) + { + vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; + vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; + } + else + { + vcp->normalImpulse = 0.0f; + vcp->tangentImpulse = 0.0f; + } + + vcp->rA.SetZero(); + vcp->rB.SetZero(); + vcp->normalMass = 0.0f; + vcp->tangentMass = 0.0f; + vcp->velocityBias = 0.0f; + + pc->localPoints[j] = cp->localPoint; + } + } +} + +b2ContactSolver::~b2ContactSolver() +{ + m_allocator->Free(m_velocityConstraints); + m_allocator->Free(m_positionConstraints); +} + +// Initialize position dependent portions of the velocity constraints. +void b2ContactSolver::InitializeVelocityConstraints() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + float32 radiusA = pc->radiusA; + float32 radiusB = pc->radiusB; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + + float32 mA = vc->invMassA; + float32 mB = vc->invMassB; + float32 iA = vc->invIA; + float32 iB = vc->invIB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Assert(manifold->pointCount > 0); + + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2WorldManifold worldManifold; + worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); + + vc->normal = worldManifold.normal; + + int32 pointCount = vc->pointCount; + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + + vcp->rA = worldManifold.points[j] - cA; + vcp->rB = worldManifold.points[j] - cB; + + float32 rnA = b2Cross(vcp->rA, vc->normal); + float32 rnB = b2Cross(vcp->rB, vc->normal); + + float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + + b2Vec2 tangent = b2Cross(vc->normal, 1.0f); + + float32 rtA = b2Cross(vcp->rA, tangent); + float32 rtB = b2Cross(vcp->rB, tangent); + + float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; + + vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + + // Setup a velocity bias for restitution. + vcp->velocityBias = 0.0f; + float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); + if (vRel < -b2_velocityThreshold) + { + vcp->velocityBias = -vc->restitution * vRel; + } + } + + // If we have two points, then prepare the block solver. + if (vc->pointCount == 2) + { + b2VelocityConstraintPoint* vcp1 = vc->points + 0; + b2VelocityConstraintPoint* vcp2 = vc->points + 1; + + float32 rn1A = b2Cross(vcp1->rA, vc->normal); + float32 rn1B = b2Cross(vcp1->rB, vc->normal); + float32 rn2A = b2Cross(vcp2->rA, vc->normal); + float32 rn2B = b2Cross(vcp2->rB, vc->normal); + + float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; + float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; + float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; + + // Ensure a reasonable condition number. + const float32 k_maxConditionNumber = 1000.0f; + if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) + { + // K is safe to invert. + vc->K.ex.Set(k11, k12); + vc->K.ey.Set(k12, k22); + vc->normalMass = vc->K.GetInverse(); + } + else + { + // The constraints are redundant, just use one. + // TODO_ERIN use deepest? + vc->pointCount = 1; + } + } + } +} + +void b2ContactSolver::WarmStart() +{ + // Warm start. + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; + wA -= iA * b2Cross(vcp->rA, P); + vA -= mA * P; + wB += iB * b2Cross(vcp->rB, P); + vB += mB * P; + } + + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } +} + +void b2ContactSolver::SolveVelocityConstraints() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; + + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; + + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + float32 friction = vc->friction; + + b2Assert(pointCount == 1 || pointCount == 2); + + // Solve tangent constraints first because non-penetration is more important + // than friction. + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + + // Compute tangent force + float32 vt = b2Dot(dv, tangent); + float32 lambda = vcp->tangentMass * (-vt); + + // b2Clamp the accumulated force + float32 maxFriction = friction * vcp->normalImpulse; + float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); + lambda = newImpulse - vcp->tangentImpulse; + vcp->tangentImpulse = newImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * tangent; + + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); + + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } + + // Solve normal constraints + if (vc->pointCount == 1) + { + b2VelocityConstraintPoint* vcp = vc->points + 0; + + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + + // Compute normal impulse + float32 vn = b2Dot(dv, normal); + float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); + + // b2Clamp the accumulated impulse + float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); + lambda = newImpulse - vcp->normalImpulse; + vcp->normalImpulse = newImpulse; + + // Apply contact impulse + b2Vec2 P = lambda * normal; + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); + + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } + else + { + // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). + // Build the mini LCP for this contact patch + // + // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 + // + // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) + // b = vn0 - velocityBias + // + // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i + // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases + // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid + // solution that satisfies the problem is chosen. + // + // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires + // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). + // + // Substitute: + // + // x = a + d + // + // a := old total impulse + // x := new total impulse + // d := incremental impulse + // + // For the current iteration we extend the formula for the incremental impulse + // to compute the new total impulse: + // + // vn = A * d + b + // = A * (x - a) + b + // = A * x + b - A * a + // = A * x + b' + // b' = b - A * a; + + b2VelocityConstraintPoint* cp1 = vc->points + 0; + b2VelocityConstraintPoint* cp2 = vc->points + 1; + + b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); + b2Assert(a.x >= 0.0f && a.y >= 0.0f); + + // Relative velocity at contact + b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + float32 vn1 = b2Dot(dv1, normal); + float32 vn2 = b2Dot(dv2, normal); + + b2Vec2 b; + b.x = vn1 - cp1->velocityBias; + b.y = vn2 - cp2->velocityBias; + + // Compute b' + b -= b2Mul(vc->K, a); + + const float32 k_errorTol = 1e-3f; + B2_NOT_USED(k_errorTol); + + for (;;) + { + // + // Case 1: vn = 0 + // + // 0 = A * x + b' + // + // Solve for x: + // + // x = - inv(A) * b' + // + b2Vec2 x = - b2Mul(vc->normalMass, b); + + if (x.x >= 0.0f && x.y >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 2: vn1 = 0 and x2 = 0 + // + // 0 = a11 * x1 + a12 * 0 + b1' + // vn2 = a21 * x1 + a22 * 0 + b2' + // + x.x = - cp1->normalMass * b.x; + x.y = 0.0f; + vn1 = 0.0f; + vn2 = vc->K.ex.y * x.x + b.y; + + if (x.x >= 0.0f && vn2 >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); +#endif + break; + } + + + // + // Case 3: vn2 = 0 and x1 = 0 + // + // vn1 = a11 * 0 + a12 * x2 + b1' + // 0 = a21 * 0 + a22 * x2 + b2' + // + x.x = 0.0f; + x.y = - cp2->normalMass * b.y; + vn1 = vc->K.ey.x * x.y + b.x; + vn2 = 0.0f; + + if (x.y >= 0.0f && vn1 >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + +#if B2_DEBUG_SOLVER == 1 + // Postconditions + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + + // Compute normal velocity + vn2 = b2Dot(dv2, normal); + + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); +#endif + break; + } + + // + // Case 4: x1 = 0 and x2 = 0 + // + // vn1 = b1 + // vn2 = b2; + x.x = 0.0f; + x.y = 0.0f; + vn1 = b.x; + vn2 = b.y; + + if (vn1 >= 0.0f && vn2 >= 0.0f ) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; + + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; + + break; + } + + // No solution, give up. This is hit sometimes, but it doesn't seem to matter. + break; + } + } + + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } +} + +void b2ContactSolver::StoreImpulses() +{ + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + + for (int32 j = 0; j < vc->pointCount; ++j) + { + manifold->points[j].normalImpulse = vc->points[j].normalImpulse; + manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; + } + } +} + +struct b2PositionSolverManifold +{ + void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) + { + b2Assert(pc->pointCount > 0); + + switch (pc->type) + { + case b2Manifold::e_circles: + { + b2Vec2 pointA = b2Mul(xfA, pc->localPoint); + b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); + normal = pointB - pointA; + normal.Normalize(); + point = 0.5f * (pointA + pointB); + separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; + } + break; + + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); + + b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; + } + break; + + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); + + b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; + + // Ensure normal points from A to B + normal = -normal; + } + break; + } + } + + b2Vec2 normal; + b2Vec2 point; + float32 separation; +}; + +// Sequential solver. +bool b2ContactSolver::SolvePositionConstraints() +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + float32 mA = pc->invMassA; + float32 iA = pc->invIA; + b2Vec2 localCenterB = pc->localCenterB; + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + int32 pointCount = pc->pointCount; + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -3.0f * b2_linearSlop; +} + +// Sequential position solver for position constraints. +bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) +{ + float32 minSeparation = 0.0f; + + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; + + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + int32 pointCount = pc->pointCount; + + float32 mA = 0.0f; + float32 iA = 0.0f; + if (indexA == toiIndexA || indexA == toiIndexB) + { + mA = pc->invMassA; + iA = pc->invIA; + } + + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + if (indexB == toiIndexA || indexB == toiIndexB) + { + mB = pc->invMassB; + iB = pc->invIB; + } + + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); + + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; + + b2Vec2 point = psm.point; + float32 separation = psm.separation; + + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; + + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); + + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; + + b2Vec2 P = impulse * normal; + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; + + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } + + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -1.5f * b2_linearSlop; +} diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.h b/external/Box2D/Dynamics/Contacts/b2ContactSolver.h new file mode 100644 index 0000000000..aef1987a9e --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2ContactSolver.h @@ -0,0 +1,94 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_SOLVER_H +#define B2_CONTACT_SOLVER_H + +#include +#include +#include + +class b2Contact; +class b2Body; +class b2StackAllocator; +struct b2ContactPositionConstraint; + +struct b2VelocityConstraintPoint +{ + b2Vec2 rA; + b2Vec2 rB; + float32 normalImpulse; + float32 tangentImpulse; + float32 normalMass; + float32 tangentMass; + float32 velocityBias; +}; + +struct b2ContactVelocityConstraint +{ + b2VelocityConstraintPoint points[b2_maxManifoldPoints]; + b2Vec2 normal; + b2Mat22 normalMass; + b2Mat22 K; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + float32 invIA, invIB; + float32 friction; + float32 restitution; + int32 pointCount; + int32 contactIndex; +}; + +struct b2ContactSolverDef +{ + b2TimeStep step; + b2Contact** contacts; + int32 count; + b2Position* positions; + b2Velocity* velocities; + b2StackAllocator* allocator; +}; + +class b2ContactSolver +{ +public: + b2ContactSolver(b2ContactSolverDef* def); + ~b2ContactSolver(); + + void InitializeVelocityConstraints(); + + void WarmStart(); + void SolveVelocityConstraints(); + void StoreImpulses(); + + bool SolvePositionConstraints(); + bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); + + b2TimeStep m_step; + b2Position* m_positions; + b2Velocity* m_velocities; + b2StackAllocator* m_allocator; + b2ContactPositionConstraint* m_positionConstraints; + b2ContactVelocityConstraint* m_velocityConstraints; + b2Contact** m_contacts; + int m_count; +}; + +#endif + diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp new file mode 100644 index 0000000000..aade42880a --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); + return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); +} + +void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); + allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); +} + +b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndCircle( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h new file mode 100644 index 0000000000..70771ec536 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H +#define B2_EDGE_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp new file mode 100644 index 0000000000..04ce394107 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); + return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); +} + +void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); + allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); +} + +b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideEdgeAndPolygon( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h new file mode 100644 index 0000000000..f65f3acca9 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_EDGE_AND_POLYGON_CONTACT_H +#define B2_EDGE_AND_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2EdgeAndPolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndPolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp new file mode 100644 index 0000000000..961b26f38a --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); + return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); +} + +void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); + allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); +} + +b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) +: b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygonAndCircle( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h new file mode 100644 index 0000000000..7b1a5288b4 --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H +#define B2_POLYGON_AND_CIRCLE_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2PolygonAndCircleContact : public b2Contact +{ +public: + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonAndCircleContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp new file mode 100644 index 0000000000..a2884a440d --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include + +#include +using namespace std; + +b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2PolygonContact)); + return new (mem) b2PolygonContact(fixtureA, fixtureB); +} + +void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2PolygonContact*)contact)->~b2PolygonContact(); + allocator->Free(contact, sizeof(b2PolygonContact)); +} + +b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); +} + +void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollidePolygons( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonContact.h new file mode 100644 index 0000000000..302684232a --- /dev/null +++ b/external/Box2D/Dynamics/Contacts/b2PolygonContact.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_POLYGON_CONTACT_H +#define B2_POLYGON_CONTACT_H + +#include + +class b2BlockAllocator; + +class b2PolygonContact : public b2Contact +{ +public: + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + + b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonContact() {} + + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp new file mode 100644 index 0000000000..b2d4bd006c --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp @@ -0,0 +1,260 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// 1-D constrained system +// m (v2 - v1) = lambda +// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. +// x2 = x1 + h * v2 + +// 1-D mass-damper-spring system +// m (v2 - v1) + h * d * v2 + h * k * + +// C = norm(p2 - p1) - L +// u = (p2 - p1) / norm(p2 - p1) +// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// J = [-u -cross(r1, u) u cross(r2, u)] +// K = J * invM * JT +// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 + +void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, + const b2Vec2& anchor1, const b2Vec2& anchor2) +{ + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor1); + localAnchorB = bodyB->GetLocalPoint(anchor2); + b2Vec2 d = anchor2 - anchor1; + length = d.Length(); +} + +b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_length = def->length; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + m_impulse = 0.0f; + m_gamma = 0.0f; + m_bias = 0.0f; +} + +void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; + + // Handle singularity. + float32 length = m_u.Length(); + if (length > b2_linearSlop) + { + m_u *= 1.0f / length; + } + else + { + m_u.Set(0.0f, 0.0f); + } + + float32 crAu = b2Cross(m_rA, m_u); + float32 crBu = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; + + // Compute the effective mass matrix. + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + + if (m_frequencyHz > 0.0f) + { + float32 C = length - m_length; + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m_mass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m_mass * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; + + invMass += m_gamma; + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + } + else + { + m_gamma = 0.0f; + m_bias = 0.0f; + } + + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 Cdot = b2Dot(m_u, vpB - vpA); + + float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); + m_impulse += impulse; + + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) +{ + if (m_frequencyHz > 0.0f) + { + // There is no position correction for soft distance constraints. + return true; + } + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; + + float32 length = u.Normalize(); + float32 C = length - m_length; + C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); + + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; + + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return b2Abs(C) < b2_linearSlop; +} + +b2Vec2 b2DistanceJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2DistanceJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; +} + +float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +void b2DistanceJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2DistanceJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.length = %.15lef;\n", m_length); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.h b/external/Box2D/Dynamics/Joints/b2DistanceJoint.h new file mode 100644 index 0000000000..fc11476ff9 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2DistanceJoint.h @@ -0,0 +1,169 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_DISTANCE_JOINT_H +#define B2_DISTANCE_JOINT_H + +#include + +/// Distance joint definition. This requires defining an +/// anchor point on both bodies and the non-zero length of the +/// distance joint. The definition uses local anchor points +/// so that the initial configuration can violate the constraint +/// slightly. This helps when saving and loading a game. +/// @warning Do not use a zero or short length. +struct b2DistanceJointDef : public b2JointDef +{ + b2DistanceJointDef() + { + type = e_distanceJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + length = 1.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } + + /// Initialize the bodies, anchors, and length using the world + /// anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& anchorA, const b2Vec2& anchorB); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The natural length between the anchor points. + float32 length; + + /// The mass-spring-damper frequency in Hertz. A value of 0 + /// disables softness. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A distance joint constrains two points on two bodies +/// to remain at a fixed distance from each other. You can view +/// this as a massless, rigid rod. +class b2DistanceJoint : public b2Joint +{ +public: + + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque given the inverse time step. + /// Unit is N*m. This is always zero for a distance joint. + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set/get the natural length. + /// Manipulating the length can lead to non-physical behavior when the frequency is zero. + void SetLength(float32 length); + float32 GetLength() const; + + /// Set/get frequency in Hz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2DistanceJoint(const b2DistanceJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_gamma; + float32 m_impulse; + float32 m_length; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; +}; + +inline void b2DistanceJoint::SetLength(float32 length) +{ + m_length = length; +} + +inline float32 b2DistanceJoint::GetLength() const +{ + return m_length; +} + +inline void b2DistanceJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2DistanceJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +inline void b2DistanceJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2DistanceJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp new file mode 100644 index 0000000000..6e6018db10 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp @@ -0,0 +1,251 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); +} + +b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + + m_maxForce = def->maxForce; + m_maxTorque = def->maxTorque; +} + +void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective mass matrix. + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat22 K; + K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; + K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; + + m_linearMass = K.GetInverse(); + + m_angularMass = iA + iB; + if (m_angularMass > 0.0f) + { + m_angularMass = 1.0f / m_angularMass; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_linearImpulse *= data.step.dtRatio; + m_angularImpulse *= data.step.dtRatio; + + b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); + } + else + { + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + float32 h = data.step.dt; + + // Solve angular friction + { + float32 Cdot = wB - wA; + float32 impulse = -m_angularMass * Cdot; + + float32 oldImpulse = m_angularImpulse; + float32 maxImpulse = h * m_maxTorque; + m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_angularImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve linear friction + { + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + + b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); + b2Vec2 oldImpulse = m_linearImpulse; + m_linearImpulse += impulse; + + float32 maxImpulse = h * m_maxForce; + + if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_linearImpulse.Normalize(); + m_linearImpulse *= maxImpulse; + } + + impulse = m_linearImpulse - oldImpulse; + + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + + return true; +} + +b2Vec2 b2FrictionJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2FrictionJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_linearImpulse; +} + +float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_angularImpulse; +} + +void b2FrictionJoint::SetMaxForce(float32 force) +{ + b2Assert(b2IsValid(force) && force >= 0.0f); + m_maxForce = force; +} + +float32 b2FrictionJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2FrictionJoint::SetMaxTorque(float32 torque) +{ + b2Assert(b2IsValid(torque) && torque >= 0.0f); + m_maxTorque = torque; +} + +float32 b2FrictionJoint::GetMaxTorque() const +{ + return m_maxTorque; +} + +void b2FrictionJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2FrictionJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); + b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.h b/external/Box2D/Dynamics/Joints/b2FrictionJoint.h new file mode 100644 index 0000000000..3ee40c6298 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2FrictionJoint.h @@ -0,0 +1,119 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FRICTION_JOINT_H +#define B2_FRICTION_JOINT_H + +#include + +/// Friction joint definition. +struct b2FrictionJointDef : public b2JointDef +{ + b2FrictionJointDef() + { + type = e_frictionJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + maxForce = 0.0f; + maxTorque = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum friction force in N. + float32 maxForce; + + /// The maximum friction torque in N-m. + float32 maxTorque; +}; + +/// Friction joint. This is used for top-down friction. +/// It provides 2D translational friction and angular friction. +class b2FrictionJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set the maximum friction force in N. + void SetMaxForce(float32 force); + + /// Get the maximum friction force in N. + float32 GetMaxForce() const; + + /// Set the maximum friction torque in N*m. + void SetMaxTorque(float32 torque); + + /// Get the maximum friction torque in N*m. + float32 GetMaxTorque() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + + b2FrictionJoint(const b2FrictionJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + + // Solver shared + b2Vec2 m_linearImpulse; + float32 m_angularImpulse; + float32 m_maxForce; + float32 m_maxTorque; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat22 m_linearMass; + float32 m_angularMass; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.cpp b/external/Box2D/Dynamics/Joints/b2GearJoint.cpp new file mode 100644 index 0000000000..9741cdd5a4 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2GearJoint.cpp @@ -0,0 +1,423 @@ +/* +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +// Gear Joint: +// C0 = (coordinate1 + ratio * coordinate2)_initial +// C = (coordinate1 + ratio * coordinate2) - C0 = 0 +// J = [J1 ratio * J2] +// K = J * invM * JT +// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T +// +// Revolute: +// coordinate = rotation +// Cdot = angularVelocity +// J = [0 0 1] +// K = J * invM * JT = invI +// +// Prismatic: +// coordinate = dot(p - pg, ug) +// Cdot = dot(v + cross(w, r), ug) +// J = [ug cross(r, ug)] +// K = J * invM * JT = invMass + invI * cross(r, ug)^2 + +b2GearJoint::b2GearJoint(const b2GearJointDef* def) +: b2Joint(def) +{ + m_joint1 = def->joint1; + m_joint2 = def->joint2; + + m_typeA = m_joint1->GetType(); + m_typeB = m_joint2->GetType(); + + b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); + b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); + + float32 coordinateA, coordinateB; + + // TODO_ERIN there might be some problem with the joint edges in b2Joint. + + m_bodyC = m_joint1->GetBodyA(); + m_bodyA = m_joint1->GetBodyB(); + + // Get geometry of joint1 + b2Transform xfA = m_bodyA->m_xf; + float32 aA = m_bodyA->m_sweep.a; + b2Transform xfC = m_bodyC->m_xf; + float32 aC = m_bodyC->m_sweep.a; + + if (m_typeA == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; + m_localAnchorC = revolute->m_localAnchorA; + m_localAnchorA = revolute->m_localAnchorB; + m_referenceAngleA = revolute->m_referenceAngle; + m_localAxisC.SetZero(); + + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; + m_localAnchorC = prismatic->m_localAnchorA; + m_localAnchorA = prismatic->m_localAnchorB; + m_referenceAngleA = prismatic->m_referenceAngle; + m_localAxisC = prismatic->m_localXAxisA; + + b2Vec2 pC = m_localAnchorC; + b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } + + m_bodyD = m_joint2->GetBodyA(); + m_bodyB = m_joint2->GetBodyB(); + + // Get geometry of joint2 + b2Transform xfB = m_bodyB->m_xf; + float32 aB = m_bodyB->m_sweep.a; + b2Transform xfD = m_bodyD->m_xf; + float32 aD = m_bodyD->m_sweep.a; + + if (m_typeB == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; + m_localAnchorD = revolute->m_localAnchorA; + m_localAnchorB = revolute->m_localAnchorB; + m_referenceAngleB = revolute->m_referenceAngle; + m_localAxisD.SetZero(); + + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; + m_localAnchorD = prismatic->m_localAnchorA; + m_localAnchorB = prismatic->m_localAnchorB; + m_referenceAngleB = prismatic->m_referenceAngle; + m_localAxisD = prismatic->m_localXAxisA; + + b2Vec2 pD = m_localAnchorD; + b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } + + m_ratio = def->ratio; + + m_constant = coordinateA + m_ratio * coordinateB; + + m_impulse = 0.0f; +} + +void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_indexC = m_bodyC->m_islandIndex; + m_indexD = m_bodyD->m_islandIndex; + m_lcA = m_bodyA->m_sweep.localCenter; + m_lcB = m_bodyB->m_sweep.localCenter; + m_lcC = m_bodyC->m_sweep.localCenter; + m_lcD = m_bodyD->m_sweep.localCenter; + m_mA = m_bodyA->m_invMass; + m_mB = m_bodyB->m_invMass; + m_mC = m_bodyC->m_invMass; + m_mD = m_bodyD->m_invMass; + m_iA = m_bodyA->m_invI; + m_iB = m_bodyB->m_invI; + m_iC = m_bodyC->m_invI; + m_iD = m_bodyD->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + + m_mass = 0.0f; + + if (m_typeA == e_revoluteJoint) + { + m_JvAC.SetZero(); + m_JwA = 1.0f; + m_JwC = 1.0f; + m_mass += m_iA + m_iC; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + m_JvAC = u; + m_JwC = b2Cross(rC, u); + m_JwA = b2Cross(rA, u); + m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; + } + + if (m_typeB == e_revoluteJoint) + { + m_JvBD.SetZero(); + m_JwB = m_ratio; + m_JwD = m_ratio; + m_mass += m_ratio * m_ratio * (m_iB + m_iD); + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + m_JvBD = m_ratio * u; + m_JwD = m_ratio * b2Cross(rD, u); + m_JwB = m_ratio * b2Cross(rB, u); + m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; + } + + // Compute effective mass. + m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; + + if (data.step.warmStarting) + { + vA += (m_mA * m_impulse) * m_JvAC; + wA += m_iA * m_impulse * m_JwA; + vB += (m_mB * m_impulse) * m_JvBD; + wB += m_iB * m_impulse * m_JwB; + vC -= (m_mC * m_impulse) * m_JvAC; + wC -= m_iC * m_impulse * m_JwC; + vD -= (m_mD * m_impulse) * m_JvBD; + wD -= m_iD * m_impulse * m_JwD; + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; +} + +void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; + + float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); + Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); + + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + vA += (m_mA * impulse) * m_JvAC; + wA += m_iA * impulse * m_JwA; + vB += (m_mB * impulse) * m_JvBD; + wB += m_iB * impulse * m_JwB; + vC -= (m_mC * impulse) * m_JvAC; + wC -= m_iC * impulse * m_JwC; + vD -= (m_mD * impulse) * m_JvBD; + wD -= m_iD * impulse * m_JwD; + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; +} + +bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; + + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + + float32 linearError = 0.0f; + + float32 coordinateA, coordinateB; + + b2Vec2 JvAC, JvBD; + float32 JwA, JwB, JwC, JwD; + float32 mass = 0.0f; + + if (m_typeA == e_revoluteJoint) + { + JvAC.SetZero(); + JwA = 1.0f; + JwC = 1.0f; + mass += m_iA + m_iC; + + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + JvAC = u; + JwC = b2Cross(rC, u); + JwA = b2Cross(rA, u); + mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; + + b2Vec2 pC = m_localAnchorC - m_lcC; + b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } + + if (m_typeB == e_revoluteJoint) + { + JvBD.SetZero(); + JwB = m_ratio; + JwD = m_ratio; + mass += m_ratio * m_ratio * (m_iB + m_iD); + + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + JvBD = m_ratio * u; + JwD = m_ratio * b2Cross(rD, u); + JwB = m_ratio * b2Cross(rB, u); + mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; + + b2Vec2 pD = m_localAnchorD - m_lcD; + b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } + + float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; + + float32 impulse = 0.0f; + if (mass > 0.0f) + { + impulse = -C / mass; + } + + cA += m_mA * impulse * JvAC; + aA += m_iA * impulse * JwA; + cB += m_mB * impulse * JvBD; + aB += m_iB * impulse * JwB; + cC -= m_mC * impulse * JvAC; + aC -= m_iC * impulse * JwC; + cD -= m_mD * impulse * JvBD; + aD -= m_iD * impulse * JwD; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + data.positions[m_indexC].c = cC; + data.positions[m_indexC].a = aC; + data.positions[m_indexD].c = cD; + data.positions[m_indexD].a = aD; + + // TODO_ERIN not implemented + return linearError < b2_linearSlop; +} + +b2Vec2 b2GearJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2GearJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P = m_impulse * m_JvAC; + return inv_dt * P; +} + +float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const +{ + float32 L = m_impulse * m_JwA; + return inv_dt * L; +} + +void b2GearJoint::SetRatio(float32 ratio) +{ + b2Assert(b2IsValid(ratio)); + m_ratio = ratio; +} + +float32 b2GearJoint::GetRatio() const +{ + return m_ratio; +} + +void b2GearJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + int32 index1 = m_joint1->m_index; + int32 index2 = m_joint2->m_index; + + b2Log(" b2GearJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.joint1 = joints[%d];\n", index1); + b2Log(" jd.joint2 = joints[%d];\n", index2); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.h b/external/Box2D/Dynamics/Joints/b2GearJoint.h new file mode 100644 index 0000000000..f926bf6ef1 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2GearJoint.h @@ -0,0 +1,125 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_GEAR_JOINT_H +#define B2_GEAR_JOINT_H + +#include + +/// Gear joint definition. This definition requires two existing +/// revolute or prismatic joints (any combination will work). +struct b2GearJointDef : public b2JointDef +{ + b2GearJointDef() + { + type = e_gearJoint; + joint1 = NULL; + joint2 = NULL; + ratio = 1.0f; + } + + /// The first revolute/prismatic joint attached to the gear joint. + b2Joint* joint1; + + /// The second revolute/prismatic joint attached to the gear joint. + b2Joint* joint2; + + /// The gear ratio. + /// @see b2GearJoint for explanation. + float32 ratio; +}; + +/// A gear joint is used to connect two joints together. Either joint +/// can be a revolute or prismatic joint. You specify a gear ratio +/// to bind the motions together: +/// coordinate1 + ratio * coordinate2 = constant +/// The ratio can be negative or positive. If one joint is a revolute joint +/// and the other joint is a prismatic joint, then the ratio will have units +/// of length or units of 1/length. +/// @warning You have to manually destroy the gear joint if joint1 or joint2 +/// is destroyed. +class b2GearJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the first joint. + b2Joint* GetJoint1() { return m_joint1; } + + /// Get the second joint. + b2Joint* GetJoint2() { return m_joint2; } + + /// Set/Get the gear ratio. + void SetRatio(float32 ratio); + float32 GetRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2GearJoint(const b2GearJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Joint* m_joint1; + b2Joint* m_joint2; + + b2JointType m_typeA; + b2JointType m_typeB; + + // Body A is connected to body C + // Body B is connected to body D + b2Body* m_bodyC; + b2Body* m_bodyD; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localAnchorC; + b2Vec2 m_localAnchorD; + + b2Vec2 m_localAxisC; + b2Vec2 m_localAxisD; + + float32 m_referenceAngleA; + float32 m_referenceAngleB; + + float32 m_constant; + float32 m_ratio; + + float32 m_impulse; + + // Solver temp + int32 m_indexA, m_indexB, m_indexC, m_indexD; + b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; + float32 m_mA, m_mB, m_mC, m_mD; + float32 m_iA, m_iB, m_iC, m_iD; + b2Vec2 m_JvAC, m_JvBD; + float32 m_JwA, m_JwB, m_JwC, m_JwD; + float32 m_mass; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2Joint.cpp b/external/Box2D/Dynamics/Joints/b2Joint.cpp new file mode 100644 index 0000000000..6853b09f0b --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2Joint.cpp @@ -0,0 +1,199 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) +{ + b2Joint* joint = NULL; + + switch (def->type) + { + case e_distanceJoint: + { + void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); + joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def); + } + break; + + case e_mouseJoint: + { + void* mem = allocator->Allocate(sizeof(b2MouseJoint)); + joint = new (mem) b2MouseJoint((b2MouseJointDef*)def); + } + break; + + case e_prismaticJoint: + { + void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); + joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def); + } + break; + + case e_revoluteJoint: + { + void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); + joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def); + } + break; + + case e_pulleyJoint: + { + void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); + joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def); + } + break; + + case e_gearJoint: + { + void* mem = allocator->Allocate(sizeof(b2GearJoint)); + joint = new (mem) b2GearJoint((b2GearJointDef*)def); + } + break; + + case e_wheelJoint: + { + void* mem = allocator->Allocate(sizeof(b2WheelJoint)); + joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); + } + break; + + case e_weldJoint: + { + void* mem = allocator->Allocate(sizeof(b2WeldJoint)); + joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); + } + break; + + case e_frictionJoint: + { + void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); + joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); + } + break; + + case e_ropeJoint: + { + void* mem = allocator->Allocate(sizeof(b2RopeJoint)); + joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); + } + break; + + default: + b2Assert(false); + break; + } + + return joint; +} + +void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) +{ + joint->~b2Joint(); + switch (joint->m_type) + { + case e_distanceJoint: + allocator->Free(joint, sizeof(b2DistanceJoint)); + break; + + case e_mouseJoint: + allocator->Free(joint, sizeof(b2MouseJoint)); + break; + + case e_prismaticJoint: + allocator->Free(joint, sizeof(b2PrismaticJoint)); + break; + + case e_revoluteJoint: + allocator->Free(joint, sizeof(b2RevoluteJoint)); + break; + + case e_pulleyJoint: + allocator->Free(joint, sizeof(b2PulleyJoint)); + break; + + case e_gearJoint: + allocator->Free(joint, sizeof(b2GearJoint)); + break; + + case e_wheelJoint: + allocator->Free(joint, sizeof(b2WheelJoint)); + break; + + case e_weldJoint: + allocator->Free(joint, sizeof(b2WeldJoint)); + break; + + case e_frictionJoint: + allocator->Free(joint, sizeof(b2FrictionJoint)); + break; + + case e_ropeJoint: + allocator->Free(joint, sizeof(b2RopeJoint)); + break; + + default: + b2Assert(false); + break; + } +} + +b2Joint::b2Joint(const b2JointDef* def) +{ + b2Assert(def->bodyA != def->bodyB); + + m_type = def->type; + m_prev = NULL; + m_next = NULL; + m_bodyA = def->bodyA; + m_bodyB = def->bodyB; + m_index = 0; + m_collideConnected = def->collideConnected; + m_islandFlag = false; + m_userData = def->userData; + + m_edgeA.joint = NULL; + m_edgeA.other = NULL; + m_edgeA.prev = NULL; + m_edgeA.next = NULL; + + m_edgeB.joint = NULL; + m_edgeB.other = NULL; + m_edgeB.prev = NULL; + m_edgeB.next = NULL; +} + +bool b2Joint::IsActive() const +{ + return m_bodyA->IsActive() && m_bodyB->IsActive(); +} diff --git a/external/Box2D/Dynamics/Joints/b2Joint.h b/external/Box2D/Dynamics/Joints/b2Joint.h new file mode 100644 index 0000000000..b4ea576665 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2Joint.h @@ -0,0 +1,222 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_JOINT_H +#define B2_JOINT_H + +#include + +class b2Body; +class b2Joint; +struct b2SolverData; +class b2BlockAllocator; + +enum b2JointType +{ + e_unknownJoint, + e_revoluteJoint, + e_prismaticJoint, + e_distanceJoint, + e_pulleyJoint, + e_mouseJoint, + e_gearJoint, + e_wheelJoint, + e_weldJoint, + e_frictionJoint, + e_ropeJoint +}; + +enum b2LimitState +{ + e_inactiveLimit, + e_atLowerLimit, + e_atUpperLimit, + e_equalLimits +}; + +struct b2Jacobian +{ + b2Vec2 linear; + float32 angularA; + float32 angularB; +}; + +/// A joint edge is used to connect bodies and joints together +/// in a joint graph where each body is a node and each joint +/// is an edge. A joint edge belongs to a doubly linked list +/// maintained in each attached body. Each joint has two joint +/// nodes, one for each attached body. +struct b2JointEdge +{ + b2Body* other; ///< provides quick access to the other body attached. + b2Joint* joint; ///< the joint + b2JointEdge* prev; ///< the previous joint edge in the body's joint list + b2JointEdge* next; ///< the next joint edge in the body's joint list +}; + +/// Joint definitions are used to construct joints. +struct b2JointDef +{ + b2JointDef() + { + type = e_unknownJoint; + userData = NULL; + bodyA = NULL; + bodyB = NULL; + collideConnected = false; + } + + /// The joint type is set automatically for concrete joint types. + b2JointType type; + + /// Use this to attach application specific data to your joints. + void* userData; + + /// The first attached body. + b2Body* bodyA; + + /// The second attached body. + b2Body* bodyB; + + /// Set this flag to true if the attached bodies should collide. + bool collideConnected; +}; + +/// The base joint class. Joints are used to constraint two bodies together in +/// various fashions. Some joints also feature limits and motors. +class b2Joint +{ +public: + + /// Get the type of the concrete joint. + b2JointType GetType() const; + + /// Get the first body attached to this joint. + b2Body* GetBodyA(); + + /// Get the second body attached to this joint. + b2Body* GetBodyB(); + + /// Get the anchor point on bodyA in world coordinates. + virtual b2Vec2 GetAnchorA() const = 0; + + /// Get the anchor point on bodyB in world coordinates. + virtual b2Vec2 GetAnchorB() const = 0; + + /// Get the reaction force on bodyB at the joint anchor in Newtons. + virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; + + /// Get the reaction torque on bodyB in N*m. + virtual float32 GetReactionTorque(float32 inv_dt) const = 0; + + /// Get the next joint the world joint list. + b2Joint* GetNext(); + const b2Joint* GetNext() const; + + /// Get the user data pointer. + void* GetUserData() const; + + /// Set the user data pointer. + void SetUserData(void* data); + + /// Short-cut function to determine if either body is inactive. + bool IsActive() const; + + /// Get collide connected. + /// Note: modifying the collide connect flag won't work correctly because + /// the flag is only checked when fixture AABBs begin to overlap. + bool GetCollideConnected() const; + + /// Dump this joint to the log file. + virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } + +protected: + friend class b2World; + friend class b2Body; + friend class b2Island; + friend class b2GearJoint; + + static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); + static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); + + b2Joint(const b2JointDef* def); + virtual ~b2Joint() {} + + virtual void InitVelocityConstraints(const b2SolverData& data) = 0; + virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; + + // This returns true if the position errors are within tolerance. + virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; + + b2JointType m_type; + b2Joint* m_prev; + b2Joint* m_next; + b2JointEdge m_edgeA; + b2JointEdge m_edgeB; + b2Body* m_bodyA; + b2Body* m_bodyB; + + int32 m_index; + + bool m_islandFlag; + bool m_collideConnected; + + void* m_userData; +}; + +inline b2JointType b2Joint::GetType() const +{ + return m_type; +} + +inline b2Body* b2Joint::GetBodyA() +{ + return m_bodyA; +} + +inline b2Body* b2Joint::GetBodyB() +{ + return m_bodyB; +} + +inline b2Joint* b2Joint::GetNext() +{ + return m_next; +} + +inline const b2Joint* b2Joint::GetNext() const +{ + return m_next; +} + +inline void* b2Joint::GetUserData() const +{ + return m_userData; +} + +inline void b2Joint::SetUserData(void* data) +{ + m_userData = data; +} + +inline bool b2Joint::GetCollideConnected() const +{ + return m_collideConnected; +} + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp new file mode 100644 index 0000000000..237d9d519a --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp @@ -0,0 +1,217 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// p = attached point, m = mouse point +// C = p - m +// Cdot = v +// = v + cross(w, r) +// J = [I r_skew] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) +: b2Joint(def) +{ + b2Assert(def->target.IsValid()); + b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); + b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); + b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); + + m_targetA = def->target; + m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); + + m_maxForce = def->maxForce; + m_impulse.SetZero(); + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_beta = 0.0f; + m_gamma = 0.0f; +} + +void b2MouseJoint::SetTarget(const b2Vec2& target) +{ + if (m_bodyB->IsAwake() == false) + { + m_bodyB->SetAwake(true); + } + m_targetA = target; +} + +const b2Vec2& b2MouseJoint::GetTarget() const +{ + return m_targetA; +} + +void b2MouseJoint::SetMaxForce(float32 force) +{ + m_maxForce = force; +} + +float32 b2MouseJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2MouseJoint::SetFrequency(float32 hz) +{ + m_frequencyHz = hz; +} + +float32 b2MouseJoint::GetFrequency() const +{ + return m_frequencyHz; +} + +void b2MouseJoint::SetDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +float32 b2MouseJoint::GetDampingRatio() const +{ + return m_dampingRatio; +} + +void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexB = m_bodyB->m_islandIndex; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassB = m_bodyB->m_invMass; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qB(aB); + + float32 mass = m_bodyB->GetMass(); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * mass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = mass * (omega * omega); + + // magic formulas + // gamma has units of inverse mass. + // beta has units of inverse time. + float32 h = data.step.dt; + b2Assert(d + h * k > b2_epsilon); + m_gamma = h * (d + h * k); + if (m_gamma != 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + m_beta = h * k * m_gamma; + + // Compute the effective mass matrix. + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] + // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] + b2Mat22 K; + K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; + K.ex.y = -m_invIB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; + + m_mass = K.GetInverse(); + + m_C = cB + m_rB - m_targetA; + m_C *= m_beta; + + // Cheat with some damping + wB *= 0.98f; + + if (data.step.warmStarting) + { + m_impulse *= data.step.dtRatio; + vB += m_invMassB * m_impulse; + wB += m_invIB * b2Cross(m_rB, m_impulse); + } + else + { + m_impulse.SetZero(); + } + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = v + cross(w, r) + b2Vec2 Cdot = vB + b2Cross(wB, m_rB); + b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); + + b2Vec2 oldImpulse = m_impulse; + m_impulse += impulse; + float32 maxImpulse = data.step.dt * m_maxForce; + if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_impulse *= maxImpulse / m_impulse.Length(); + } + impulse = m_impulse - oldImpulse; + + vB += m_invMassB * impulse; + wB += m_invIB * b2Cross(m_rB, impulse); + + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + return true; +} + +b2Vec2 b2MouseJoint::GetAnchorA() const +{ + return m_targetA; +} + +b2Vec2 b2MouseJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_impulse; +} + +float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * 0.0f; +} diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.h b/external/Box2D/Dynamics/Joints/b2MouseJoint.h new file mode 100644 index 0000000000..1bbc194f4c --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2MouseJoint.h @@ -0,0 +1,126 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_MOUSE_JOINT_H +#define B2_MOUSE_JOINT_H + +#include + +/// Mouse joint definition. This requires a world target point, +/// tuning parameters, and the time step. +struct b2MouseJointDef : public b2JointDef +{ + b2MouseJointDef() + { + type = e_mouseJoint; + target.Set(0.0f, 0.0f); + maxForce = 0.0f; + frequencyHz = 5.0f; + dampingRatio = 0.7f; + } + + /// The initial world target point. This is assumed + /// to coincide with the body anchor initially. + b2Vec2 target; + + /// The maximum constraint force that can be exerted + /// to move the candidate body. Usually you will express + /// as some multiple of the weight (multiplier * mass * gravity). + float32 maxForce; + + /// The response speed. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A mouse joint is used to make a point on a body track a +/// specified world point. This a soft constraint with a maximum +/// force. This allows the constraint to stretch and without +/// applying huge forces. +/// NOTE: this joint is not documented in the manual because it was +/// developed to be used in the testbed. If you want to learn how to +/// use the mouse joint, look at the testbed. +class b2MouseJoint : public b2Joint +{ +public: + + /// Implements b2Joint. + b2Vec2 GetAnchorA() const; + + /// Implements b2Joint. + b2Vec2 GetAnchorB() const; + + /// Implements b2Joint. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Implements b2Joint. + float32 GetReactionTorque(float32 inv_dt) const; + + /// Use this to update the target point. + void SetTarget(const b2Vec2& target); + const b2Vec2& GetTarget() const; + + /// Set/get the maximum force in Newtons. + void SetMaxForce(float32 force); + float32 GetMaxForce() const; + + /// Set/get the frequency in Hertz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; + + /// Set/get the damping ratio (dimensionless). + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; + + /// The mouse joint does not support dumping. + void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } + +protected: + friend class b2Joint; + + b2MouseJoint(const b2MouseJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_localAnchorB; + b2Vec2 m_targetA; + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_beta; + + // Solver shared + b2Vec2 m_impulse; + float32 m_maxForce; + float32 m_gamma; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rB; + b2Vec2 m_localCenterB; + float32 m_invMassB; + float32 m_invIB; + b2Mat22 m_mass; + b2Vec2 m_C; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp new file mode 100644 index 0000000000..4849f729f5 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp @@ -0,0 +1,637 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = p2 - p1 = x2 + r2 - x1 - r1 +// C = dot(perp, d) +// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) +// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) +// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] +// +// Angular constraint +// C = a2 - a1 + a_initial +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// +// K = J * invM * JT +// +// J = [-a -s1 a s2] +// [0 -1 0 1] +// a = perp +// s1 = cross(d + r1, a) = cross(p2 - x1, a) +// s2 = cross(r2, a) = cross(p2 - x2, a) + + +// Motor/Limit linear constraint +// C = dot(ax1, d) +// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) +// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] + +// Block Solver +// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even +// when the mass has poor distribution (leading to large torques about the joint anchor points). +// +// The Jacobian has 3 rows: +// J = [-uT -s1 uT s2] // linear +// [0 -1 0 1] // angular +// [-vT -a1 vT a2] // limit +// +// u = perp +// v = axis +// s1 = cross(d + r1, u), s2 = cross(r2, u) +// a1 = cross(d + r1, v), a2 = cross(r2, v) + +// M * (v2 - v1) = JT * df +// J * v2 = bias +// +// v2 = v1 + invM * JT * df +// J * (v1 + invM * JT * df) = bias +// K * df = bias - J * v1 = -Cdot +// K = J * invM * JT +// Cdot = J * v1 - bias +// +// Now solve for f2. +// df = f2 - f1 +// K * (f2 - f1) = -Cdot +// f2 = invK * (-Cdot) + f1 +// +// Clamp accumulated limit impulse. +// lower: f2(3) = max(f2(3), 0) +// upper: f2(3) = min(f2(3), 0) +// +// Solve for correct f2(1:2) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 +// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) +// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) +// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) +// +// Now compute impulse to be applied: +// df = f2 - f1 + +void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localXAxisA.Normalize(); + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + + m_lowerTranslation = def->lowerTranslation; + m_upperTranslation = def->upperTranslation; + m_maxMotorForce = def->maxMotorForce; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; + + m_axis.SetZero(); + m_perp.SetZero(); +} + +void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Compute motor Jacobian and effective mass. + { + m_axis = b2Mul(qA, m_localXAxisA); + m_a1 = b2Cross(d + rA, m_axis); + m_a2 = b2Cross(rB, m_axis); + + m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + + // Prismatic constraint. + { + m_perp = b2Mul(qA, m_localYAxisA); + + m_s1 = b2Cross(d + rA, m_perp); + m_s2 = b2Cross(rB, m_perp); + + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For bodies with fixed rotation. + k22 = 1.0f; + } + float32 k23 = iA * m_a1 + iB * m_a2; + float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + + m_K.ex.Set(k11, k12, k13); + m_K.ey.Set(k12, k22, k23); + m_K.ez.Set(k13, k23, k33); + } + + // Compute motor and limit terms. + if (m_enableLimit) + { + float32 jointTranslation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + m_limitState = e_equalLimits; + } + else if (jointTranslation <= m_lowerTranslation) + { + if (m_limitState != e_atLowerLimit) + { + m_limitState = e_atLowerLimit; + m_impulse.z = 0.0f; + } + } + else if (jointTranslation >= m_upperTranslation) + { + if (m_limitState != e_atUpperLimit) + { + m_limitState = e_atUpperLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } + + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; + float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; + float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Solve linear motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + float32 impulse = m_motorMass * (m_motorSpeed - Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorForce; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + b2Vec2 P = impulse * m_axis; + float32 LA = impulse * m_a1; + float32 LB = impulse * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + b2Vec2 Cdot1; + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; + + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + // Solve prismatic and limit constraint in block form. + float32 Cdot2; + Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 f1 = m_impulse; + b2Vec3 df = m_K.Solve33(-Cdot); + m_impulse += df; + + if (m_limitState == e_atLowerLimit) + { + m_impulse.z = b2Max(m_impulse.z, 0.0f); + } + else if (m_limitState == e_atUpperLimit) + { + m_impulse.z = b2Min(m_impulse.z, 0.0f); + } + + // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) + b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); + b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); + m_impulse.x = f2r.x; + m_impulse.y = f2r.y; + + df = m_impulse - f1; + + b2Vec2 P = df.x * m_perp + df.z * m_axis; + float32 LA = df.x * m_s1 + df.y + df.z * m_a1; + float32 LB = df.x * m_s2 + df.y + df.z * m_a2; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + else + { + // Limit is inactive, just solve the prismatic constraint in block form. + b2Vec2 df = m_K.Solve22(-Cdot1); + m_impulse.x += df.x; + m_impulse.y += df.y; + + b2Vec2 P = df.x * m_perp; + float32 LA = df.x * m_s1 + df.y; + float32 LB = df.x * m_s2 + df.y; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + + b2Vec2 Cdot10 = Cdot1; + + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; + + if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) + { + b2Vec2 test = b2Mul22(m_K, df); + Cdot1.x += 0.0f; + } + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + // Compute fresh Jacobians + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + b2Vec2 axis = b2Mul(qA, m_localXAxisA); + float32 a1 = b2Cross(d + rA, axis); + float32 a2 = b2Cross(rB, axis); + b2Vec2 perp = b2Mul(qA, m_localYAxisA); + + float32 s1 = b2Cross(d + rA, perp); + float32 s2 = b2Cross(rB, perp); + + b2Vec3 impulse; + b2Vec2 C1; + C1.x = b2Dot(perp, d); + C1.y = aB - aA - m_referenceAngle; + + float32 linearError = b2Abs(C1.x); + float32 angularError = b2Abs(C1.y); + + bool active = false; + float32 C2 = 0.0f; + if (m_enableLimit) + { + float32 translation = b2Dot(axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + // Prevent large angular corrections + C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); + linearError = b2Max(linearError, b2Abs(translation)); + active = true; + } + else if (translation <= m_lowerTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); + linearError = b2Max(linearError, m_lowerTranslation - translation); + active = true; + } + else if (translation >= m_upperTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); + linearError = b2Max(linearError, translation - m_upperTranslation); + active = true; + } + } + + if (active) + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k13 = iA * s1 * a1 + iB * s2 * a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For fixed rotation + k22 = 1.0f; + } + float32 k23 = iA * a1 + iB * a2; + float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; + + b2Mat33 K; + K.ex.Set(k11, k12, k13); + K.ey.Set(k12, k22, k23); + K.ez.Set(k13, k23, k33); + + b2Vec3 C; + C.x = C1.x; + C.y = C1.y; + C.z = C2; + + impulse = K.Solve33(-C); + } + else + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + k22 = 1.0f; + } + + b2Mat22 K; + K.ex.Set(k11, k12); + K.ey.Set(k12, k22); + + b2Vec2 impulse1 = K.Solve(-C1); + impulse.x = impulse1.x; + impulse.y = impulse1.y; + impulse.z = 0.0f; + } + + b2Vec2 P = impulse.x * perp + impulse.z * axis; + float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; + float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; + + cA -= mA * P; + aA -= iA * LA; + cB += mB * P; + aB += iB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return linearError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2PrismaticJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2PrismaticJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); +} + +float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.y; +} + +float32 b2PrismaticJoint::GetJointTranslation() const +{ + b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2PrismaticJoint::GetJointSpeed() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); + b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); + b2Vec2 p1 = bA->m_sweep.c + rA; + b2Vec2 p2 = bB->m_sweep.c + rB; + b2Vec2 d = p2 - p1; + b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); + + b2Vec2 vA = bA->m_linearVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + float32 wB = bB->m_angularVelocity; + + float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); + return speed; +} + +bool b2PrismaticJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2PrismaticJoint::EnableLimit(bool flag) +{ + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } +} + +float32 b2PrismaticJoint::GetLowerLimit() const +{ + return m_lowerTranslation; +} + +float32 b2PrismaticJoint::GetUpperLimit() const +{ + return m_upperTranslation; +} + +void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + if (lower != m_lowerTranslation || upper != m_upperTranslation) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; + m_impulse.z = 0.0f; + } +} + +bool b2PrismaticJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2PrismaticJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2PrismaticJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2PrismaticJoint::SetMaxMotorForce(float32 force) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorForce = force; +} + +float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2PrismaticJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PrismaticJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); + b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h new file mode 100644 index 0000000000..aca2859b45 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h @@ -0,0 +1,196 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_PRISMATIC_JOINT_H +#define B2_PRISMATIC_JOINT_H + +#include + +/// Prismatic joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2PrismaticJointDef : public b2JointDef +{ + b2PrismaticJointDef() + { + type = e_prismaticJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + referenceAngle = 0.0f; + enableLimit = false; + lowerTranslation = 0.0f; + upperTranslation = 0.0f; + enableMotor = false; + maxMotorForce = 0.0f; + motorSpeed = 0.0f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and unit world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The local translation unit axis in bodyA. + b2Vec2 localAxisA; + + /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. + float32 referenceAngle; + + /// Enable/disable the joint limit. + bool enableLimit; + + /// The lower translation limit, usually in meters. + float32 lowerTranslation; + + /// The upper translation limit, usually in meters. + float32 upperTranslation; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorForce; + + /// The desired motor speed in radians per second. + float32 motorSpeed; +}; + +/// A prismatic joint. This joint provides one degree of freedom: translation +/// along an axis fixed in bodyA. Relative rotation is prevented. You can +/// use a joint limit to restrict the range of motion and a joint motor to +/// drive the motion or to model joint friction. +class b2PrismaticJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint limit enabled? + bool IsLimitEnabled() const; + + /// Enable/disable the joint limit. + void EnableLimit(bool flag); + + /// Get the lower joint limit, usually in meters. + float32 GetLowerLimit() const; + + /// Get the upper joint limit, usually in meters. + float32 GetUpperLimit() const; + + /// Set the joint limits, usually in meters. + void SetLimits(float32 lower, float32 upper); + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in meters per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in meters per second. + float32 GetMotorSpeed() const; + + /// Set the maximum motor force, usually in N. + void SetMaxMotorForce(float32 force); + float32 GetMaxMotorForce() const { return m_maxMotorForce; } + + /// Get the current motor force given the inverse time step, usually in N. + float32 GetMotorForce(float32 inv_dt) const; + + /// Dump to b2Log + void Dump(); + +protected: + friend class b2Joint; + friend class b2GearJoint; + b2PrismaticJoint(const b2PrismaticJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + float32 m_referenceAngle; + b2Vec3 m_impulse; + float32 m_motorImpulse; + float32 m_lowerTranslation; + float32 m_upperTranslation; + float32 m_maxMotorForce; + float32 m_motorSpeed; + bool m_enableLimit; + bool m_enableMotor; + b2LimitState m_limitState; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + b2Mat33 m_K; + float32 m_motorMass; +}; + +inline float32 b2PrismaticJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp new file mode 100644 index 0000000000..da30fae222 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp @@ -0,0 +1,332 @@ +/* +* Copyright (c) 2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Pulley: +// length1 = norm(p1 - s1) +// length2 = norm(p2 - s2) +// C0 = (length1 + ratio * length2)_initial +// C = C0 - (length1 + ratio * length2) +// u1 = (p1 - s1) / norm(p1 - s1) +// u2 = (p2 - s2) / norm(p2 - s2) +// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) +// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] +// K = J * invM * JT +// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) + +void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, + const b2Vec2& groundA, const b2Vec2& groundB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 r) +{ + bodyA = bA; + bodyB = bB; + groundAnchorA = groundA; + groundAnchorB = groundB; + localAnchorA = bodyA->GetLocalPoint(anchorA); + localAnchorB = bodyB->GetLocalPoint(anchorB); + b2Vec2 dA = anchorA - groundA; + lengthA = dA.Length(); + b2Vec2 dB = anchorB - groundB; + lengthB = dB.Length(); + ratio = r; + b2Assert(ratio > b2_epsilon); +} + +b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) +: b2Joint(def) +{ + m_groundAnchorA = def->groundAnchorA; + m_groundAnchorB = def->groundAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_lengthA = def->lengthA; + m_lengthB = def->lengthB; + + b2Assert(def->ratio != 0.0f); + m_ratio = def->ratio; + + m_constant = def->lengthA + m_ratio * def->lengthB; + + m_impulse = 0.0f; +} + +void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // Get the pulley axes. + m_uA = cA + m_rA - m_groundAnchorA; + m_uB = cB + m_rB - m_groundAnchorB; + + float32 lengthA = m_uA.Length(); + float32 lengthB = m_uB.Length(); + + if (lengthA > 10.0f * b2_linearSlop) + { + m_uA *= 1.0f / lengthA; + } + else + { + m_uA.SetZero(); + } + + if (lengthB > 10.0f * b2_linearSlop) + { + m_uB *= 1.0f / lengthB; + } + else + { + m_uB.SetZero(); + } + + // Compute effective mass. + float32 ruA = b2Cross(m_rA, m_uA); + float32 ruB = b2Cross(m_rB, m_uB); + + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; + + m_mass = mA + m_ratio * m_ratio * mB; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + + if (data.step.warmStarting) + { + // Scale impulses to support variable time steps. + m_impulse *= data.step.dtRatio; + + // Warm starting. + b2Vec2 PA = -(m_impulse) * m_uA; + b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; + + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + + float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + b2Vec2 PA = -impulse * m_uA; + b2Vec2 PB = -m_ratio * impulse * m_uB; + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // Get the pulley axes. + b2Vec2 uA = cA + rA - m_groundAnchorA; + b2Vec2 uB = cB + rB - m_groundAnchorB; + + float32 lengthA = uA.Length(); + float32 lengthB = uB.Length(); + + if (lengthA > 10.0f * b2_linearSlop) + { + uA *= 1.0f / lengthA; + } + else + { + uA.SetZero(); + } + + if (lengthB > 10.0f * b2_linearSlop) + { + uB *= 1.0f / lengthB; + } + else + { + uB.SetZero(); + } + + // Compute effective mass. + float32 ruA = b2Cross(rA, uA); + float32 ruB = b2Cross(rB, uB); + + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; + + float32 mass = mA + m_ratio * m_ratio * mB; + + if (mass > 0.0f) + { + mass = 1.0f / mass; + } + + float32 C = m_constant - lengthA - m_ratio * lengthB; + float32 linearError = b2Abs(C); + + float32 impulse = -mass * C; + + b2Vec2 PA = -impulse * uA; + b2Vec2 PB = -m_ratio * impulse * uB; + + cA += m_invMassA * PA; + aA += m_invIA * b2Cross(rA, PA); + cB += m_invMassB * PB; + aB += m_invIB * b2Cross(rB, PB); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return linearError < b2_linearSlop; +} + +b2Vec2 b2PulleyJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2PulleyJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P = m_impulse * m_uB; + return inv_dt * P; +} + +float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +b2Vec2 b2PulleyJoint::GetGroundAnchorA() const +{ + return m_groundAnchorA; +} + +b2Vec2 b2PulleyJoint::GetGroundAnchorB() const +{ + return m_groundAnchorB; +} + +float32 b2PulleyJoint::GetLengthA() const +{ + b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 s = m_groundAnchorA; + b2Vec2 d = p - s; + return d.Length(); +} + +float32 b2PulleyJoint::GetLengthB() const +{ + b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 s = m_groundAnchorB; + b2Vec2 d = p - s; + return d.Length(); +} + +float32 b2PulleyJoint::GetRatio() const +{ + return m_ratio; +} + +void b2PulleyJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2PulleyJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); + b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); + b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.h b/external/Box2D/Dynamics/Joints/b2PulleyJoint.h new file mode 100644 index 0000000000..2f6df4395c --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2PulleyJoint.h @@ -0,0 +1,143 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_PULLEY_JOINT_H +#define B2_PULLEY_JOINT_H + +#include + +const float32 b2_minPulleyLength = 2.0f; + +/// Pulley joint definition. This requires two ground anchors, +/// two dynamic body anchor points, and a pulley ratio. +struct b2PulleyJointDef : public b2JointDef +{ + b2PulleyJointDef() + { + type = e_pulleyJoint; + groundAnchorA.Set(-1.0f, 1.0f); + groundAnchorB.Set(1.0f, 1.0f); + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + lengthA = 0.0f; + lengthB = 0.0f; + ratio = 1.0f; + collideConnected = true; + } + + /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 ratio); + + /// The first ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorA; + + /// The second ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorB; + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The a reference length for the segment attached to bodyA. + float32 lengthA; + + /// The a reference length for the segment attached to bodyB. + float32 lengthB; + + /// The pulley ratio, used to simulate a block-and-tackle. + float32 ratio; +}; + +/// The pulley joint is connected to two bodies and two fixed ground points. +/// The pulley supports a ratio such that: +/// length1 + ratio * length2 <= constant +/// Yes, the force transmitted is scaled by the ratio. +/// Warning: the pulley joint can get a bit squirrelly by itself. They often +/// work better when combined with prismatic joints. You should also cover the +/// the anchor points with static shapes to prevent one side from going to +/// zero length. +class b2PulleyJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the first ground anchor. + b2Vec2 GetGroundAnchorA() const; + + /// Get the second ground anchor. + b2Vec2 GetGroundAnchorB() const; + + /// Get the current length of the segment attached to bodyA. + float32 GetLengthA() const; + + /// Get the current length of the segment attached to bodyB. + float32 GetLengthB() const; + + /// Get the pulley ratio. + float32 GetRatio() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2PulleyJoint(const b2PulleyJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + b2Vec2 m_groundAnchorA; + b2Vec2 m_groundAnchorB; + float32 m_lengthA; + float32 m_lengthB; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_constant; + float32 m_ratio; + float32 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_uA; + b2Vec2 m_uB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp new file mode 100644 index 0000000000..e265d8192b --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp @@ -0,0 +1,504 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Motor constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + + m_lowerAngle = def->lowerAngle; + m_upperAngle = def->upperAngle; + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; +} + +void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + bool fixedRotation = (iA + iB == 0.0f); + + m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; + + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + + if (m_enableMotor == false || fixedRotation) + { + m_motorImpulse = 0.0f; + } + + if (m_enableLimit && fixedRotation == false) + { + float32 jointAngle = aB - aA - m_referenceAngle; + if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) + { + m_limitState = e_equalLimits; + } + else if (jointAngle <= m_lowerAngle) + { + if (m_limitState != e_atLowerLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atLowerLimit; + } + else if (jointAngle >= m_upperAngle) + { + if (m_limitState != e_atUpperLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atUpperLimit; + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + bool fixedRotation = (iA + iB == 0.0f); + + // Solve motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = -m_mass.Solve33(Cdot); + + if (m_limitState == e_equalLimits) + { + m_impulse += impulse; + } + else if (m_limitState == e_atLowerLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse < 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } + else if (m_limitState == e_atUpperLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse > 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } + else + { + // Solve point-to-point constraint + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + b2Vec2 impulse = m_mass.Solve22(-Cdot); + + m_impulse.x += impulse.x; + m_impulse.y += impulse.y; + + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 angularError = 0.0f; + float32 positionError = 0.0f; + + bool fixedRotation = (m_invIA + m_invIB == 0.0f); + + // Solve angular limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + float32 angle = aB - aA - m_referenceAngle; + float32 limitImpulse = 0.0f; + + if (m_limitState == e_equalLimits) + { + // Prevent large angular corrections + float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + angularError = b2Abs(C); + } + else if (m_limitState == e_atLowerLimit) + { + float32 C = angle - m_lowerAngle; + angularError = -C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); + limitImpulse = -m_motorMass * C; + } + else if (m_limitState == e_atUpperLimit) + { + float32 C = angle - m_upperAngle; + angularError = C; + + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + } + + aA -= m_invIA * limitImpulse; + aB += m_invIB * limitImpulse; + } + + // Solve point-to-point constraint. + { + qA.Set(aA); + qB.Set(aB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + b2Vec2 C = cB + rB - cA - rA; + positionError = C.Length(); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat22 K; + K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; + K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; + + b2Vec2 impulse = -K.Solve(C); + + cA -= mA * impulse; + aA -= iA * b2Cross(rA, impulse); + + cB += mB * impulse; + aB += iB * b2Cross(rB, impulse); + } + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2RevoluteJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2RevoluteJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} + +float32 b2RevoluteJoint::GetJointAngle() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; +} + +float32 b2RevoluteJoint::GetJointSpeed() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_angularVelocity - bA->m_angularVelocity; +} + +bool b2RevoluteJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2RevoluteJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2RevoluteJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +bool b2RevoluteJoint::IsLimitEnabled() const +{ + return m_enableLimit; +} + +void b2RevoluteJoint::EnableLimit(bool flag) +{ + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } +} + +float32 b2RevoluteJoint::GetLowerLimit() const +{ + return m_lowerAngle; +} + +float32 b2RevoluteJoint::GetUpperLimit() const +{ + return m_upperAngle; +} + +void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) +{ + b2Assert(lower <= upper); + + if (lower != m_lowerAngle || upper != m_upperAngle) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_impulse.z = 0.0f; + m_lowerAngle = lower; + m_upperAngle = upper; + } +} + +void b2RevoluteJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RevoluteJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); + b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h new file mode 100644 index 0000000000..978f16259a --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h @@ -0,0 +1,204 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_REVOLUTE_JOINT_H +#define B2_REVOLUTE_JOINT_H + +#include + +/// Revolute joint definition. This requires defining an +/// anchor point where the bodies are joined. The definition +/// uses local anchor points so that the initial configuration +/// can violate the constraint slightly. You also need to +/// specify the initial relative angle for joint limits. This +/// helps when saving and loading a game. +/// The local anchor points are measured from the body's origin +/// rather than the center of mass because: +/// 1. you might not know where the center of mass will be. +/// 2. if you add/remove shapes from a body and recompute the mass, +/// the joints will be broken. +struct b2RevoluteJointDef : public b2JointDef +{ + b2RevoluteJointDef() + { + type = e_revoluteJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + lowerAngle = 0.0f; + upperAngle = 0.0f; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + enableLimit = false; + enableMotor = false; + } + + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; + + /// A flag to enable joint limits. + bool enableLimit; + + /// The lower angle for the joint limit (radians). + float32 lowerAngle; + + /// The upper angle for the joint limit (radians). + float32 upperAngle; + + /// A flag to enable the joint motor. + bool enableMotor; + + /// The desired motor speed. Usually in radians per second. + float32 motorSpeed; + + /// The maximum motor torque used to achieve the desired motor speed. + /// Usually in N-m. + float32 maxMotorTorque; +}; + +/// A revolute joint constrains two bodies to share a common point while they +/// are free to rotate about the point. The relative rotation about the shared +/// point is the joint angle. You can limit the relative rotation with +/// a joint limit that specifies a lower and upper angle. You can use a motor +/// to drive the relative rotation about the shared point. A maximum motor torque +/// is provided so that infinite forces are not generated. +class b2RevoluteJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Get the current joint angle in radians. + float32 GetJointAngle() const; + + /// Get the current joint angle speed in radians per second. + float32 GetJointSpeed() const; + + /// Is the joint limit enabled? + bool IsLimitEnabled() const; + + /// Enable/disable the joint limit. + void EnableLimit(bool flag); + + /// Get the lower joint limit in radians. + float32 GetLowerLimit() const; + + /// Get the upper joint limit in radians. + float32 GetUpperLimit() const; + + /// Set the joint limits in radians. + void SetLimits(float32 lower, float32 upper); + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed in radians per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed in radians per second. + float32 GetMotorSpeed() const; + + /// Set the maximum motor torque, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } + + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; + + /// Get the reaction torque due to the joint limit given the inverse time step. + /// Unit is N*m. + float32 GetReactionTorque(float32 inv_dt) const; + + /// Get the current motor torque given the inverse time step. + /// Unit is N*m. + float32 GetMotorTorque(float32 inv_dt) const; + + /// Dump to b2Log. + void Dump(); + +protected: + + friend class b2Joint; + friend class b2GearJoint; + + b2RevoluteJoint(const b2RevoluteJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec3 m_impulse; + float32 m_motorImpulse; + + bool m_enableMotor; + float32 m_maxMotorTorque; + float32 m_motorSpeed; + + bool m_enableLimit; + float32 m_referenceAngle; + float32 m_lowerAngle; + float32 m_upperAngle; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; // effective mass for point-to-point constraint. + float32 m_motorMass; // effective mass for motor/limit angular constraint. + b2LimitState m_limitState; +}; + +inline float32 b2RevoluteJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp new file mode 100644 index 0000000000..17a70d9230 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp @@ -0,0 +1,241 @@ +/* +* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + + +// Limit: +// C = norm(pB - pA) - L +// u = (pB - pA) / norm(pB - pA) +// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) +// J = [-u -cross(rA, u) u cross(rB, u)] +// K = J * invM * JT +// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 + +b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + + m_maxLength = def->maxLength; + + m_mass = 0.0f; + m_impulse = 0.0f; + m_state = e_inactiveLimit; + m_length = 0.0f; +} + +void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; + + m_length = m_u.Length(); + + float32 C = m_length - m_maxLength; + if (C > 0.0f) + { + m_state = e_atUpperLimit; + } + else + { + m_state = e_inactiveLimit; + } + + if (m_length > b2_linearSlop) + { + m_u *= 1.0f / m_length; + } + else + { + m_u.SetZero(); + m_mass = 0.0f; + m_impulse = 0.0f; + return; + } + + // Compute effective mass. + float32 crA = b2Cross(m_rA, m_u); + float32 crB = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; + + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 C = m_length - m_maxLength; + float32 Cdot = b2Dot(m_u, vpB - vpA); + + // Predictive constraint. + if (C < 0.0f) + { + Cdot += data.step.inv_dt * C; + } + + float32 impulse = -m_mass * Cdot; + float32 oldImpulse = m_impulse; + m_impulse = b2Min(0.0f, m_impulse + impulse); + impulse = m_impulse - oldImpulse; + + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; + + float32 length = u.Normalize(); + float32 C = length - m_maxLength; + + C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); + + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; + + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return length - m_maxLength < b2_linearSlop; +} + +b2Vec2 b2RopeJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2RopeJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; +} + +float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const +{ + B2_NOT_USED(inv_dt); + return 0.0f; +} + +float32 b2RopeJoint::GetMaxLength() const +{ + return m_maxLength; +} + +b2LimitState b2RopeJoint::GetLimitState() const +{ + return m_state; +} + +void b2RopeJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2RopeJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.h b/external/Box2D/Dynamics/Joints/b2RopeJoint.h new file mode 100644 index 0000000000..d7091b6650 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2RopeJoint.h @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_JOINT_H +#define B2_ROPE_JOINT_H + +#include + +/// Rope joint definition. This requires two body anchor points and +/// a maximum lengths. +/// Note: by default the connected objects will not collide. +/// see collideConnected in b2JointDef. +struct b2RopeJointDef : public b2JointDef +{ + b2RopeJointDef() + { + type = e_ropeJoint; + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + maxLength = 0.0f; + } + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The maximum length of the rope. + /// Warning: this must be larger than b2_linearSlop or + /// the joint will have no effect. + float32 maxLength; +}; + +/// A rope joint enforces a maximum distance between two points +/// on two bodies. It has no other effect. +/// Warning: if you attempt to change the maximum length during +/// the simulation you will get some non-physical behavior. +/// A model that would allow you to dynamically modify the length +/// would have some sponginess, so I chose not to implement it +/// that way. See b2DistanceJoint if you want to dynamically +/// control length. +class b2RopeJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Set/Get the maximum length of the rope. + void SetMaxLength(float32 length) { m_maxLength = length; } + float32 GetMaxLength() const; + + b2LimitState GetLimitState() const; + + /// Dump joint to dmLog + void Dump(); + +protected: + + friend class b2Joint; + b2RopeJoint(const b2RopeJointDef* data); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_maxLength; + float32 m_length; + float32 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; + b2LimitState m_state; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp new file mode 100644 index 0000000000..f50bdd6587 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp @@ -0,0 +1,330 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// C = p2 - p1 +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// C = angle2 - angle1 - referenceAngle +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); +} + +b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_impulse.SetZero(); +} + +void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat33 K; + K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + K.ez.x = -m_rA.y * iA - m_rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + K.ez.y = m_rA.x * iA + m_rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; + + if (m_frequencyHz > 0.0f) + { + K.GetInverse22(&m_mass); + + float32 invM = iA + iB; + float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; + + float32 C = aB - aA - m_referenceAngle; + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; + + invM += m_gamma; + m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; + } + else + { + K.GetSymInverse33(&m_mass); + m_gamma = 0.0f; + m_bias = 0.0f; + } + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; + + b2Vec2 P(m_impulse.x, m_impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_impulse.z); + } + else + { + m_impulse.SetZero(); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + if (m_frequencyHz > 0.0f) + { + float32 Cdot2 = wB - wA; + + float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); + m_impulse.z += impulse2; + + wA -= iA * impulse2; + wB += iB * impulse2; + + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + + b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); + m_impulse.x += impulse1.x; + m_impulse.y += impulse1.y; + + b2Vec2 P = impulse1; + + vA -= mA * P; + wA -= iA * b2Cross(m_rA, P); + + vB += mB * P; + wB += iB * b2Cross(m_rB, P); + } + else + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + + b2Vec3 impulse = -b2Mul(m_mass, Cdot); + m_impulse += impulse; + + b2Vec2 P(impulse.x, impulse.y); + + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); + + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + + float32 positionError, angularError; + + b2Mat33 K; + K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + K.ez.x = -rA.y * iA - rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + K.ez.y = rA.x * iA + rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; + + if (m_frequencyHz > 0.0f) + { + b2Vec2 C1 = cB + rB - cA - rA; + + positionError = C1.Length(); + angularError = 0.0f; + + b2Vec2 P = -K.Solve22(C1); + + cA -= mA * P; + aA -= iA * b2Cross(rA, P); + + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + else + { + b2Vec2 C1 = cB + rB - cA - rA; + float32 C2 = aB - aA - m_referenceAngle; + + positionError = C1.Length(); + angularError = b2Abs(C2); + + b2Vec3 C(C1.x, C1.y, C2); + + b2Vec3 impulse = -K.Solve33(C); + b2Vec2 P(impulse.x, impulse.y); + + cA -= mA * P; + aA -= iA * (b2Cross(rA, P) + impulse.z); + + cB += mB * P; + aB += iB * (b2Cross(rB, P) + impulse.z); + } + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; +} + +b2Vec2 b2WeldJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WeldJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const +{ + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; +} + +float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_impulse.z; +} + +void b2WeldJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2WeldJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.h b/external/Box2D/Dynamics/Joints/b2WeldJoint.h new file mode 100644 index 0000000000..751c6a8770 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2WeldJoint.h @@ -0,0 +1,126 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WELD_JOINT_H +#define B2_WELD_JOINT_H + +#include + +/// Weld joint definition. You need to specify local anchor points +/// where they are attached and the relative body angle. The position +/// of the anchor points is important for computing the reaction torque. +struct b2WeldJointDef : public b2JointDef +{ + b2WeldJointDef() + { + type = e_weldJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } + + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; + + /// The mass-spring-damper frequency in Hertz. Rotation only. + /// Disable softness with a value of 0. + float32 frequencyHz; + + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; +}; + +/// A weld joint essentially glues two bodies together. A weld joint may +/// distort somewhat because the island constraint solver is approximate. +class b2WeldJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } + + /// Set/get frequency in Hz. + void SetFrequency(float32 hz) { m_frequencyHz = hz; } + float32 GetFrequency() const { return m_frequencyHz; } + + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } + float32 GetDampingRatio() const { return m_dampingRatio; } + + /// Dump to b2Log + void Dump(); + +protected: + + friend class b2Joint; + + b2WeldJoint(const b2WeldJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_referenceAngle; + float32 m_gamma; + b2Vec3 m_impulse; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp new file mode 100644 index 0000000000..6253437706 --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp @@ -0,0 +1,419 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Linear constraint (point-to-line) +// d = pB - pA = xB + rB - xA - rA +// C = dot(ay, d) +// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) +// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) +// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] + +// Spring linear constraint +// C = dot(ax, d) +// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) +// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] + +// Motor rotational constraint +// Cdot = wB - wA +// J = [0 0 -1 0 0 1] + +void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) +{ + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); +} + +b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) +: b2Joint(def) +{ + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + + m_mass = 0.0f; + m_impulse = 0.0f; + m_motorMass = 0.0; + m_motorImpulse = 0.0f; + m_springMass = 0.0f; + m_springImpulse = 0.0f; + + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableMotor = def->enableMotor; + + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + + m_bias = 0.0f; + m_gamma = 0.0f; + + m_ax.SetZero(); + m_ay.SetZero(); +} + +void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; + + // Point to line constraint + { + m_ay = b2Mul(qA, m_localYAxisA); + m_sAy = b2Cross(d + rA, m_ay); + m_sBy = b2Cross(rB, m_ay); + + m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; + + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + } + + // Spring constraint + m_springMass = 0.0f; + m_bias = 0.0f; + m_gamma = 0.0f; + if (m_frequencyHz > 0.0f) + { + m_ax = b2Mul(qA, m_localXAxisA); + m_sAx = b2Cross(d + rA, m_ax); + m_sBx = b2Cross(rB, m_ax); + + float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; + + if (invMass > 0.0f) + { + m_springMass = 1.0f / invMass; + + float32 C = b2Dot(d, m_ax); + + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; + + // Damping coefficient + float32 d = 2.0f * m_springMass * m_dampingRatio * omega; + + // Spring stiffness + float32 k = m_springMass * omega * omega; + + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + if (m_gamma > 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + + m_bias = C * h * k * m_gamma; + + m_springMass = invMass + m_gamma; + if (m_springMass > 0.0f) + { + m_springMass = 1.0f / m_springMass; + } + } + } + else + { + m_springImpulse = 0.0f; + } + + // Rotational motor + if (m_enableMotor) + { + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + else + { + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; + } + + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_springImpulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; + + b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; + float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; + float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; + + vA -= m_invMassA * P; + wA -= m_invIA * LA; + + vB += m_invMassB * P; + wB += m_invIB * LB; + } + else + { + m_impulse = 0.0f; + m_springImpulse = 0.0f; + m_motorImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + // Solve spring constraint + { + float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; + float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); + m_springImpulse += impulse; + + b2Vec2 P = impulse * m_ax; + float32 LA = impulse * m_sAx; + float32 LB = impulse * m_sBx; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + // Solve rotational motor constraint + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve point to line constraint + { + float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; + + b2Vec2 P = impulse * m_ay; + float32 LA = impulse * m_sAy; + float32 LB = impulse * m_sBy; + + vA -= mA * P; + wA -= iA * LA; + + vB += mB * P; + wB += iB * LB; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) +{ + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + + b2Rot qA(aA), qB(aB); + + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; + + b2Vec2 ay = b2Mul(qA, m_localYAxisA); + + float32 sAy = b2Cross(d + rA, ay); + float32 sBy = b2Cross(rB, ay); + + float32 C = b2Dot(d, ay); + + float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; + + float32 impulse; + if (k != 0.0f) + { + impulse = - C / k; + } + else + { + impulse = 0.0f; + } + + b2Vec2 P = impulse * ay; + float32 LA = impulse * sAy; + float32 LB = impulse * sBy; + + cA -= m_invMassA * P; + aA -= m_invIA * LA; + cB += m_invMassB * P; + aB += m_invIB * LB; + + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return b2Abs(C) <= b2_linearSlop; +} + +b2Vec2 b2WheelJoint::GetAnchorA() const +{ + return m_bodyA->GetWorldPoint(m_localAnchorA); +} + +b2Vec2 b2WheelJoint::GetAnchorB() const +{ + return m_bodyB->GetWorldPoint(m_localAnchorB); +} + +b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); +} + +float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +float32 b2WheelJoint::GetJointTranslation() const +{ + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + + b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); + + float32 translation = b2Dot(d, axis); + return translation; +} + +float32 b2WheelJoint::GetJointSpeed() const +{ + float32 wA = m_bodyA->m_angularVelocity; + float32 wB = m_bodyB->m_angularVelocity; + return wB - wA; +} + +bool b2WheelJoint::IsMotorEnabled() const +{ + return m_enableMotor; +} + +void b2WheelJoint::EnableMotor(bool flag) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; +} + +void b2WheelJoint::SetMotorSpeed(float32 speed) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; +} + +void b2WheelJoint::SetMaxMotorTorque(float32 torque) +{ + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; +} + +float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const +{ + return inv_dt * m_motorImpulse; +} + +void b2WheelJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2WheelJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.h b/external/Box2D/Dynamics/Joints/b2WheelJoint.h new file mode 100644 index 0000000000..ede1b08b7c --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2WheelJoint.h @@ -0,0 +1,213 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WHEEL_JOINT_H +#define B2_WHEEL_JOINT_H + +#include + +/// Wheel joint definition. This requires defining a line of +/// motion using an axis and an anchor point. The definition uses local +/// anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero +/// when the local anchor points coincide in world space. Using local +/// anchors and a local axis helps when saving and loading a game. +struct b2WheelJointDef : public b2JointDef +{ + b2WheelJointDef() + { + type = e_wheelJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + enableMotor = false; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + frequencyHz = 2.0f; + dampingRatio = 0.7f; + } + + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; + + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; + + /// The local translation axis in bodyA. + b2Vec2 localAxisA; + + /// Enable/disable the joint motor. + bool enableMotor; + + /// The maximum motor torque, usually in N-m. + float32 maxMotorTorque; + + /// The desired motor speed in radians per second. + float32 motorSpeed; + + /// Suspension frequency, zero indicates no suspension + float32 frequencyHz; + + /// Suspension damping ratio, one indicates critical damping + float32 dampingRatio; +}; + +/// A wheel joint. This joint provides two degrees of freedom: translation +/// along an axis fixed in bodyA and rotation in the plane. You can use a +/// joint limit to restrict the range of motion and a joint motor to drive +/// the rotation or to model rotational friction. +/// This joint is designed for vehicle suspensions. +class b2WheelJoint : public b2Joint +{ +public: + void GetDefinition(b2WheelJointDef* def) const; + + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; + + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; + + /// Is the joint motor enabled? + bool IsMotorEnabled() const; + + /// Enable/disable the joint motor. + void EnableMotor(bool flag); + + /// Set the motor speed, usually in radians per second. + void SetMotorSpeed(float32 speed); + + /// Get the motor speed, usually in radians per second. + float32 GetMotorSpeed() const; + + /// Set/Get the maximum motor force, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const; + + /// Get the current motor torque given the inverse time step, usually in N-m. + float32 GetMotorTorque(float32 inv_dt) const; + + /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. + void SetSpringFrequencyHz(float32 hz); + float32 GetSpringFrequencyHz() const; + + /// Set/Get the spring damping ratio + void SetSpringDampingRatio(float32 ratio); + float32 GetSpringDampingRatio() const; + + /// Dump to b2Log + void Dump(); + +protected: + + friend class b2Joint; + b2WheelJoint(const b2WheelJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + float32 m_frequencyHz; + float32 m_dampingRatio; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + + float32 m_impulse; + float32 m_motorImpulse; + float32 m_springImpulse; + + float32 m_maxMotorTorque; + float32 m_motorSpeed; + bool m_enableMotor; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + + b2Vec2 m_ax, m_ay; + float32 m_sAx, m_sBx; + float32 m_sAy, m_sBy; + + float32 m_mass; + float32 m_motorMass; + float32 m_springMass; + + float32 m_bias; + float32 m_gamma; +}; + +inline float32 b2WheelJoint::GetMotorSpeed() const +{ + return m_motorSpeed; +} + +inline float32 b2WheelJoint::GetMaxMotorTorque() const +{ + return m_maxMotorTorque; +} + +inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) +{ + m_frequencyHz = hz; +} + +inline float32 b2WheelJoint::GetSpringFrequencyHz() const +{ + return m_frequencyHz; +} + +inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) +{ + m_dampingRatio = ratio; +} + +inline float32 b2WheelJoint::GetSpringDampingRatio() const +{ + return m_dampingRatio; +} + +#endif diff --git a/external/Box2D/Dynamics/b2Body.cpp b/external/Box2D/Dynamics/b2Body.cpp new file mode 100644 index 0000000000..b22b574023 --- /dev/null +++ b/external/Box2D/Dynamics/b2Body.cpp @@ -0,0 +1,514 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2Body::b2Body(const b2BodyDef* bd, b2World* world) +{ + b2Assert(bd->position.IsValid()); + b2Assert(bd->linearVelocity.IsValid()); + b2Assert(b2IsValid(bd->angle)); + b2Assert(b2IsValid(bd->angularVelocity)); + b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); + b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); + + m_flags = 0; + + if (bd->bullet) + { + m_flags |= e_bulletFlag; + } + if (bd->fixedRotation) + { + m_flags |= e_fixedRotationFlag; + } + if (bd->allowSleep) + { + m_flags |= e_autoSleepFlag; + } + if (bd->awake) + { + m_flags |= e_awakeFlag; + } + if (bd->active) + { + m_flags |= e_activeFlag; + } + + m_world = world; + + m_xf.p = bd->position; + m_xf.q.Set(bd->angle); + + m_sweep.localCenter.SetZero(); + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = bd->angle; + m_sweep.a = bd->angle; + m_sweep.alpha0 = 0.0f; + + m_jointList = NULL; + m_contactList = NULL; + m_prev = NULL; + m_next = NULL; + + m_linearVelocity = bd->linearVelocity; + m_angularVelocity = bd->angularVelocity; + + m_linearDamping = bd->linearDamping; + m_angularDamping = bd->angularDamping; + m_gravityScale = bd->gravityScale; + + m_force.SetZero(); + m_torque = 0.0f; + + m_sleepTime = 0.0f; + + m_type = bd->type; + + if (m_type == b2_dynamicBody) + { + m_mass = 1.0f; + m_invMass = 1.0f; + } + else + { + m_mass = 0.0f; + m_invMass = 0.0f; + } + + m_I = 0.0f; + m_invI = 0.0f; + + m_userData = bd->userData; + + m_fixtureList = NULL; + m_fixtureCount = 0; +} + +b2Body::~b2Body() +{ + // shapes and joints are destroyed in b2World::Destroy +} + +void b2Body::SetType(b2BodyType type) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + if (m_type == type) + { + return; + } + + m_type = type; + + ResetMassData(); + + if (m_type == b2_staticBody) + { + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_sweep.a0 = m_sweep.a; + m_sweep.c0 = m_sweep.c; + SynchronizeFixtures(); + } + + SetAwake(true); + + m_force.SetZero(); + m_torque = 0.0f; + + // Since the body type changed, we need to flag contacts for filtering. + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Refilter(); + } +} + +b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return NULL; + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + void* memory = allocator->Allocate(sizeof(b2Fixture)); + b2Fixture* fixture = new (memory) b2Fixture; + fixture->Create(allocator, this, def); + + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->CreateProxies(broadPhase, m_xf); + } + + fixture->m_next = m_fixtureList; + m_fixtureList = fixture; + ++m_fixtureCount; + + fixture->m_body = this; + + // Adjust mass properties if needed. + if (fixture->m_density > 0.0f) + { + ResetMassData(); + } + + // Let the world know we have a new fixture. This will cause new contacts + // to be created at the beginning of the next time step. + m_world->m_flags |= b2World::e_newFixture; + + return fixture; +} + +b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) +{ + b2FixtureDef def; + def.shape = shape; + def.density = density; + + return CreateFixture(&def); +} + +void b2Body::DestroyFixture(b2Fixture* fixture) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + b2Assert(fixture->m_body == this); + + // Remove the fixture from this body's singly linked list. + b2Assert(m_fixtureCount > 0); + b2Fixture** node = &m_fixtureList; + bool found = false; + while (*node != NULL) + { + if (*node == fixture) + { + *node = fixture->m_next; + found = true; + break; + } + + node = &(*node)->m_next; + } + + // You tried to remove a shape that is not attached to this body. + b2Assert(found); + + // Destroy any contacts associated with the fixture. + b2ContactEdge* edge = m_contactList; + while (edge) + { + b2Contact* c = edge->contact; + edge = edge->next; + + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + + if (fixture == fixtureA || fixture == fixtureB) + { + // This destroys the contact and removes it from + // this body's contact list. + m_world->m_contactManager.Destroy(c); + } + } + + b2BlockAllocator* allocator = &m_world->m_blockAllocator; + + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->DestroyProxies(broadPhase); + } + + fixture->Destroy(allocator); + fixture->m_body = NULL; + fixture->m_next = NULL; + fixture->~b2Fixture(); + allocator->Free(fixture, sizeof(b2Fixture)); + + --m_fixtureCount; + + // Reset the mass data. + ResetMassData(); +} + +void b2Body::ResetMassData() +{ + // Compute mass data from shapes. Each shape has its own density. + m_mass = 0.0f; + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + m_sweep.localCenter.SetZero(); + + // Static and kinematic bodies have zero mass. + if (m_type == b2_staticBody || m_type == b2_kinematicBody) + { + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = m_sweep.a; + return; + } + + b2Assert(m_type == b2_dynamicBody); + + // Accumulate mass over all fixtures. + b2Vec2 localCenter = b2Vec2_zero; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + if (f->m_density == 0.0f) + { + continue; + } + + b2MassData massData; + f->GetMassData(&massData); + m_mass += massData.mass; + localCenter += massData.mass * massData.center; + m_I += massData.I; + } + + // Compute center of mass. + if (m_mass > 0.0f) + { + m_invMass = 1.0f / m_mass; + localCenter *= m_invMass; + } + else + { + // Force all dynamic bodies to have a positive mass. + m_mass = 1.0f; + m_invMass = 1.0f; + } + + if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) + { + // Center the inertia about the center of mass. + m_I -= m_mass * b2Dot(localCenter, localCenter); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + + } + else + { + m_I = 0.0f; + m_invI = 0.0f; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = localCenter; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +void b2Body::SetMassData(const b2MassData* massData) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + if (m_type != b2_dynamicBody) + { + return; + } + + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + + m_mass = massData->mass; + if (m_mass <= 0.0f) + { + m_mass = 1.0f; + } + + m_invMass = 1.0f / m_mass; + + if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) + { + m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + } + + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = massData->center; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); +} + +bool b2Body::ShouldCollide(const b2Body* other) const +{ + // At least one body should be dynamic. + if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) + { + return false; + } + + // Does a joint prevent collision? + for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) + { + if (jn->other == other) + { + if (jn->joint->m_collideConnected == false) + { + return false; + } + } + } + + return true; +} + +void b2Body::SetTransform(const b2Vec2& position, float32 angle) +{ + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } + + m_xf.q.Set(angle); + m_xf.p = position; + + m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.a = angle; + + m_sweep.c0 = m_sweep.c; + m_sweep.a0 = angle; + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, m_xf, m_xf); + } + + m_world->m_contactManager.FindNewContacts(); +} + +void b2Body::SynchronizeFixtures() +{ + b2Transform xf1; + xf1.q.Set(m_sweep.a0); + xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); + + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, xf1, m_xf); + } +} + +void b2Body::SetActive(bool flag) +{ + b2Assert(m_world->IsLocked() == false); + + if (flag == IsActive()) + { + return; + } + + if (flag) + { + m_flags |= e_activeFlag; + + // Create all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->CreateProxies(broadPhase, m_xf); + } + + // Contacts are created the next time step. + } + else + { + m_flags &= ~e_activeFlag; + + // Destroy all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->DestroyProxies(broadPhase); + } + + // Destroy the attached contacts. + b2ContactEdge* ce = m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_world->m_contactManager.Destroy(ce0->contact); + } + m_contactList = NULL; + } +} + +void b2Body::Dump() +{ + int32 bodyIndex = m_islandIndex; + + b2Log("{\n"); + b2Log(" b2BodyDef bd;\n"); + b2Log(" bd.type = b2BodyType(%d);\n", m_type); + b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); + b2Log(" bd.angle = %.15lef;\n", m_sweep.a); + b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); + b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); + b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); + b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); + b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); + b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); + b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); + b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); + b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); + b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); + b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); + b2Log("\n"); + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + b2Log(" {\n"); + f->Dump(bodyIndex); + b2Log(" }\n"); + } + b2Log("}\n"); +} \ No newline at end of file diff --git a/external/Box2D/Dynamics/b2Body.h b/external/Box2D/Dynamics/b2Body.h new file mode 100644 index 0000000000..e2d16bf630 --- /dev/null +++ b/external/Box2D/Dynamics/b2Body.h @@ -0,0 +1,846 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_BODY_H +#define B2_BODY_H + +#include +#include +#include + +class b2Fixture; +class b2Joint; +class b2Contact; +class b2Controller; +class b2World; +struct b2FixtureDef; +struct b2JointEdge; +struct b2ContactEdge; + +/// The body type. +/// static: zero mass, zero velocity, may be manually moved +/// kinematic: zero mass, non-zero velocity set by user, moved by solver +/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver +enum b2BodyType +{ + b2_staticBody = 0, + b2_kinematicBody, + b2_dynamicBody + + // TODO_ERIN + //b2_bulletBody, +}; + +/// A body definition holds all the data needed to construct a rigid body. +/// You can safely re-use body definitions. Shapes are added to a body after construction. +struct b2BodyDef +{ + /// This constructor sets the body definition default values. + b2BodyDef() + { + userData = NULL; + position.Set(0.0f, 0.0f); + angle = 0.0f; + linearVelocity.Set(0.0f, 0.0f); + angularVelocity = 0.0f; + linearDamping = 0.0f; + angularDamping = 0.0f; + allowSleep = true; + awake = true; + fixedRotation = false; + bullet = false; + type = b2_staticBody; + active = true; + gravityScale = 1.0f; + } + + /// The body type: static, kinematic, or dynamic. + /// Note: if a dynamic body would have zero mass, the mass is set to one. + b2BodyType type; + + /// The world position of the body. Avoid creating bodies at the origin + /// since this can lead to many overlapping shapes. + b2Vec2 position; + + /// The world angle of the body in radians. + float32 angle; + + /// The linear velocity of the body's origin in world co-ordinates. + b2Vec2 linearVelocity; + + /// The angular velocity of the body. + float32 angularVelocity; + + /// Linear damping is use to reduce the linear velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 linearDamping; + + /// Angular damping is use to reduce the angular velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 angularDamping; + + /// Set this flag to false if this body should never fall asleep. Note that + /// this increases CPU usage. + bool allowSleep; + + /// Is this body initially awake or sleeping? + bool awake; + + /// Should this body be prevented from rotating? Useful for characters. + bool fixedRotation; + + /// Is this a fast moving body that should be prevented from tunneling through + /// other moving bodies? Note that all bodies are prevented from tunneling through + /// kinematic and static bodies. This setting is only considered on dynamic bodies. + /// @warning You should use this flag sparingly since it increases processing time. + bool bullet; + + /// Does this body start out active? + bool active; + + /// Use this to store application specific body data. + void* userData; + + /// Scale the gravity applied to this body. + float32 gravityScale; +}; + +/// A rigid body. These are created via b2World::CreateBody. +class b2Body +{ +public: + /// Creates a fixture and attach it to this body. Use this function if you need + /// to set some fixture parameters, like friction. Otherwise you can create the + /// fixture directly from a shape. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// Contacts are not created until the next time step. + /// @param def the fixture definition. + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2FixtureDef* def); + + /// Creates a fixture from a shape and attach it to this body. + /// This is a convenience function. Use b2FixtureDef if you need to set parameters + /// like friction, restitution, user data, or filtering. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// @param shape the shape to be cloned. + /// @param density the shape density (set to zero for static bodies). + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2Shape* shape, float32 density); + + /// Destroy a fixture. This removes the fixture from the broad-phase and + /// destroys all contacts associated with this fixture. This will + /// automatically adjust the mass of the body if the body is dynamic and the + /// fixture has positive density. + /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. + /// @param fixture the fixture to be removed. + /// @warning This function is locked during callbacks. + void DestroyFixture(b2Fixture* fixture); + + /// Set the position of the body's origin and rotation. + /// This breaks any contacts and wakes the other bodies. + /// Manipulating a body's transform may cause non-physical behavior. + /// @param position the world position of the body's local origin. + /// @param angle the world rotation in radians. + void SetTransform(const b2Vec2& position, float32 angle); + + /// Get the body transform for the body's origin. + /// @return the world transform of the body's origin. + const b2Transform& GetTransform() const; + + /// Get the world body origin position. + /// @return the world position of the body's origin. + const b2Vec2& GetPosition() const; + + /// Get the angle in radians. + /// @return the current world rotation angle in radians. + float32 GetAngle() const; + + /// Get the world position of the center of mass. + const b2Vec2& GetWorldCenter() const; + + /// Get the local position of the center of mass. + const b2Vec2& GetLocalCenter() const; + + /// Set the linear velocity of the center of mass. + /// @param v the new linear velocity of the center of mass. + void SetLinearVelocity(const b2Vec2& v); + + /// Get the linear velocity of the center of mass. + /// @return the linear velocity of the center of mass. + b2Vec2 GetLinearVelocity() const; + + /// Set the angular velocity. + /// @param omega the new angular velocity in radians/second. + void SetAngularVelocity(float32 omega); + + /// Get the angular velocity. + /// @return the angular velocity in radians/second. + float32 GetAngularVelocity() const; + + /// Apply a force at a world point. If the force is not + /// applied at the center of mass, it will generate a torque and + /// affect the angular velocity. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + /// @param point the world position of the point of application. + void ApplyForce(const b2Vec2& force, const b2Vec2& point); + + /// Apply a force to the center of mass. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + void ApplyForceToCenter(const b2Vec2& force); + + /// Apply a torque. This affects the angular velocity + /// without affecting the linear velocity of the center of mass. + /// This wakes up the body. + /// @param torque about the z-axis (out of the screen), usually in N-m. + void ApplyTorque(float32 torque); + + /// Apply an impulse at a point. This immediately modifies the velocity. + /// It also modifies the angular velocity if the point of application + /// is not at the center of mass. This wakes up the body. + /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. + /// @param point the world position of the point of application. + void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); + + /// Apply an angular impulse. + /// @param impulse the angular impulse in units of kg*m*m/s + void ApplyAngularImpulse(float32 impulse); + + /// Get the total mass of the body. + /// @return the mass, usually in kilograms (kg). + float32 GetMass() const; + + /// Get the rotational inertia of the body about the local origin. + /// @return the rotational inertia, usually in kg-m^2. + float32 GetInertia() const; + + /// Get the mass data of the body. + /// @return a struct containing the mass, inertia and center of the body. + void GetMassData(b2MassData* data) const; + + /// Set the mass properties to override the mass properties of the fixtures. + /// Note that this changes the center of mass position. + /// Note that creating or destroying fixtures can also alter the mass. + /// This function has no effect if the body isn't dynamic. + /// @param massData the mass properties. + void SetMassData(const b2MassData* data); + + /// This resets the mass properties to the sum of the mass properties of the fixtures. + /// This normally does not need to be called unless you called SetMassData to override + /// the mass and you later want to reset the mass. + void ResetMassData(); + + /// Get the world coordinates of a point given the local coordinates. + /// @param localPoint a point on the body measured relative the the body's origin. + /// @return the same point expressed in world coordinates. + b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; + + /// Get the world coordinates of a vector given the local coordinates. + /// @param localVector a vector fixed in the body. + /// @return the same vector expressed in world coordinates. + b2Vec2 GetWorldVector(const b2Vec2& localVector) const; + + /// Gets a local point relative to the body's origin given a world point. + /// @param a point in world coordinates. + /// @return the corresponding local point relative to the body's origin. + b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; + + /// Gets a local vector given a world vector. + /// @param a vector in world coordinates. + /// @return the corresponding local vector. + b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; + + /// Get the world linear velocity of a world point attached to this body. + /// @param a point in world coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; + + /// Get the world velocity of a local point. + /// @param a point in local coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; + + /// Get the linear damping of the body. + float32 GetLinearDamping() const; + + /// Set the linear damping of the body. + void SetLinearDamping(float32 linearDamping); + + /// Get the angular damping of the body. + float32 GetAngularDamping() const; + + /// Set the angular damping of the body. + void SetAngularDamping(float32 angularDamping); + + /// Get the gravity scale of the body. + float32 GetGravityScale() const; + + /// Set the gravity scale of the body. + void SetGravityScale(float32 scale); + + /// Set the type of this body. This may alter the mass and velocity. + void SetType(b2BodyType type); + + /// Get the type of this body. + b2BodyType GetType() const; + + /// Should this body be treated like a bullet for continuous collision detection? + void SetBullet(bool flag); + + /// Is this body treated like a bullet for continuous collision detection? + bool IsBullet() const; + + /// You can disable sleeping on this body. If you disable sleeping, the + /// body will be woken. + void SetSleepingAllowed(bool flag); + + /// Is this body allowed to sleep + bool IsSleepingAllowed() const; + + /// Set the sleep state of the body. A sleeping body has very + /// low CPU cost. + /// @param flag set to true to put body to sleep, false to wake it. + void SetAwake(bool flag); + + /// Get the sleeping state of this body. + /// @return true if the body is sleeping. + bool IsAwake() const; + + /// Set the active state of the body. An inactive body is not + /// simulated and cannot be collided with or woken up. + /// If you pass a flag of true, all fixtures will be added to the + /// broad-phase. + /// If you pass a flag of false, all fixtures will be removed from + /// the broad-phase and all contacts will be destroyed. + /// Fixtures and joints are otherwise unaffected. You may continue + /// to create/destroy fixtures and joints on inactive bodies. + /// Fixtures on an inactive body are implicitly inactive and will + /// not participate in collisions, ray-casts, or queries. + /// Joints connected to an inactive body are implicitly inactive. + /// An inactive body is still owned by a b2World object and remains + /// in the body list. + void SetActive(bool flag); + + /// Get the active state of the body. + bool IsActive() const; + + /// Set this body to have fixed rotation. This causes the mass + /// to be reset. + void SetFixedRotation(bool flag); + + /// Does this body have fixed rotation? + bool IsFixedRotation() const; + + /// Get the list of all fixtures attached to this body. + b2Fixture* GetFixtureList(); + const b2Fixture* GetFixtureList() const; + + /// Get the list of all joints attached to this body. + b2JointEdge* GetJointList(); + const b2JointEdge* GetJointList() const; + + /// Get the list of all contacts attached to this body. + /// @warning this list changes during the time step and you may + /// miss some collisions if you don't use b2ContactListener. + b2ContactEdge* GetContactList(); + const b2ContactEdge* GetContactList() const; + + /// Get the next body in the world's body list. + b2Body* GetNext(); + const b2Body* GetNext() const; + + /// Get the user data pointer that was provided in the body definition. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Get the parent world of this body. + b2World* GetWorld(); + const b2World* GetWorld() const; + + /// Dump this body to a log file + void Dump(); + +private: + + friend class b2World; + friend class b2Island; + friend class b2ContactManager; + friend class b2ContactSolver; + friend class b2Contact; + + friend class b2DistanceJoint; + friend class b2GearJoint; + friend class b2WheelJoint; + friend class b2MouseJoint; + friend class b2PrismaticJoint; + friend class b2PulleyJoint; + friend class b2RevoluteJoint; + friend class b2WeldJoint; + friend class b2FrictionJoint; + friend class b2RopeJoint; + + // m_flags + enum + { + e_islandFlag = 0x0001, + e_awakeFlag = 0x0002, + e_autoSleepFlag = 0x0004, + e_bulletFlag = 0x0008, + e_fixedRotationFlag = 0x0010, + e_activeFlag = 0x0020, + e_toiFlag = 0x0040 + }; + + b2Body(const b2BodyDef* bd, b2World* world); + ~b2Body(); + + void SynchronizeFixtures(); + void SynchronizeTransform(); + + // This is used to prevent connected bodies from colliding. + // It may lie, depending on the collideConnected flag. + bool ShouldCollide(const b2Body* other) const; + + void Advance(float32 t); + + b2BodyType m_type; + + uint16 m_flags; + + int32 m_islandIndex; + + b2Transform m_xf; // the body origin transform + b2Sweep m_sweep; // the swept motion for CCD + + b2Vec2 m_linearVelocity; + float32 m_angularVelocity; + + b2Vec2 m_force; + float32 m_torque; + + b2World* m_world; + b2Body* m_prev; + b2Body* m_next; + + b2Fixture* m_fixtureList; + int32 m_fixtureCount; + + b2JointEdge* m_jointList; + b2ContactEdge* m_contactList; + + float32 m_mass, m_invMass; + + // Rotational inertia about the center of mass. + float32 m_I, m_invI; + + float32 m_linearDamping; + float32 m_angularDamping; + float32 m_gravityScale; + + float32 m_sleepTime; + + void* m_userData; +}; + +inline b2BodyType b2Body::GetType() const +{ + return m_type; +} + +inline const b2Transform& b2Body::GetTransform() const +{ + return m_xf; +} + +inline const b2Vec2& b2Body::GetPosition() const +{ + return m_xf.p; +} + +inline float32 b2Body::GetAngle() const +{ + return m_sweep.a; +} + +inline const b2Vec2& b2Body::GetWorldCenter() const +{ + return m_sweep.c; +} + +inline const b2Vec2& b2Body::GetLocalCenter() const +{ + return m_sweep.localCenter; +} + +inline void b2Body::SetLinearVelocity(const b2Vec2& v) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (b2Dot(v,v) > 0.0f) + { + SetAwake(true); + } + + m_linearVelocity = v; +} + +inline b2Vec2 b2Body::GetLinearVelocity() const +{ + return m_linearVelocity; +} + +inline void b2Body::SetAngularVelocity(float32 w) +{ + if (m_type == b2_staticBody) + { + return; + } + + if (w * w > 0.0f) + { + SetAwake(true); + } + + m_angularVelocity = w; +} + +inline float32 b2Body::GetAngularVelocity() const +{ + return m_angularVelocity; +} + +inline float32 b2Body::GetMass() const +{ + return m_mass; +} + +inline float32 b2Body::GetInertia() const +{ + return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); +} + +inline void b2Body::GetMassData(b2MassData* data) const +{ + data->mass = m_mass; + data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); + data->center = m_sweep.localCenter; +} + +inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const +{ + return b2Mul(m_xf, localPoint); +} + +inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const +{ + return b2Mul(m_xf.q, localVector); +} + +inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const +{ + return b2MulT(m_xf, worldPoint); +} + +inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const +{ + return b2MulT(m_xf.q, worldVector); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const +{ + return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); +} + +inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const +{ + return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); +} + +inline float32 b2Body::GetLinearDamping() const +{ + return m_linearDamping; +} + +inline void b2Body::SetLinearDamping(float32 linearDamping) +{ + m_linearDamping = linearDamping; +} + +inline float32 b2Body::GetAngularDamping() const +{ + return m_angularDamping; +} + +inline void b2Body::SetAngularDamping(float32 angularDamping) +{ + m_angularDamping = angularDamping; +} + +inline float32 b2Body::GetGravityScale() const +{ + return m_gravityScale; +} + +inline void b2Body::SetGravityScale(float32 scale) +{ + m_gravityScale = scale; +} + +inline void b2Body::SetBullet(bool flag) +{ + if (flag) + { + m_flags |= e_bulletFlag; + } + else + { + m_flags &= ~e_bulletFlag; + } +} + +inline bool b2Body::IsBullet() const +{ + return (m_flags & e_bulletFlag) == e_bulletFlag; +} + +inline void b2Body::SetAwake(bool flag) +{ + if (flag) + { + if ((m_flags & e_awakeFlag) == 0) + { + m_flags |= e_awakeFlag; + m_sleepTime = 0.0f; + } + } + else + { + m_flags &= ~e_awakeFlag; + m_sleepTime = 0.0f; + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; + } +} + +inline bool b2Body::IsAwake() const +{ + return (m_flags & e_awakeFlag) == e_awakeFlag; +} + +inline bool b2Body::IsActive() const +{ + return (m_flags & e_activeFlag) == e_activeFlag; +} + +inline void b2Body::SetFixedRotation(bool flag) +{ + if (flag) + { + m_flags |= e_fixedRotationFlag; + } + else + { + m_flags &= ~e_fixedRotationFlag; + } + + ResetMassData(); +} + +inline bool b2Body::IsFixedRotation() const +{ + return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; +} + +inline void b2Body::SetSleepingAllowed(bool flag) +{ + if (flag) + { + m_flags |= e_autoSleepFlag; + } + else + { + m_flags &= ~e_autoSleepFlag; + SetAwake(true); + } +} + +inline bool b2Body::IsSleepingAllowed() const +{ + return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; +} + +inline b2Fixture* b2Body::GetFixtureList() +{ + return m_fixtureList; +} + +inline const b2Fixture* b2Body::GetFixtureList() const +{ + return m_fixtureList; +} + +inline b2JointEdge* b2Body::GetJointList() +{ + return m_jointList; +} + +inline const b2JointEdge* b2Body::GetJointList() const +{ + return m_jointList; +} + +inline b2ContactEdge* b2Body::GetContactList() +{ + return m_contactList; +} + +inline const b2ContactEdge* b2Body::GetContactList() const +{ + return m_contactList; +} + +inline b2Body* b2Body::GetNext() +{ + return m_next; +} + +inline const b2Body* b2Body::GetNext() const +{ + return m_next; +} + +inline void b2Body::SetUserData(void* data) +{ + m_userData = data; +} + +inline void* b2Body::GetUserData() const +{ + return m_userData; +} + +inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; + m_torque += b2Cross(point - m_sweep.c, force); +} + +inline void b2Body::ApplyForceToCenter(const b2Vec2& force) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_force += force; +} + +inline void b2Body::ApplyTorque(float32 torque) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + + m_torque += torque; +} + +inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_linearVelocity += m_invMass * impulse; + m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); +} + +inline void b2Body::ApplyAngularImpulse(float32 impulse) +{ + if (m_type != b2_dynamicBody) + { + return; + } + + if (IsAwake() == false) + { + SetAwake(true); + } + m_angularVelocity += m_invI * impulse; +} + +inline void b2Body::SynchronizeTransform() +{ + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); +} + +inline void b2Body::Advance(float32 alpha) +{ + // Advance to the new safe time. This doesn't sync the broad-phase. + m_sweep.Advance(alpha); + m_sweep.c = m_sweep.c0; + m_sweep.a = m_sweep.a0; + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); +} + +inline b2World* b2Body::GetWorld() +{ + return m_world; +} + +inline const b2World* b2Body::GetWorld() const +{ + return m_world; +} + +#endif diff --git a/external/Box2D/Dynamics/b2ContactManager.cpp b/external/Box2D/Dynamics/b2ContactManager.cpp new file mode 100644 index 0000000000..c14cc4ce45 --- /dev/null +++ b/external/Box2D/Dynamics/b2ContactManager.cpp @@ -0,0 +1,293 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include + +b2ContactFilter b2_defaultFilter; +b2ContactListener b2_defaultListener; + +b2ContactManager::b2ContactManager() +{ + m_contactList = NULL; + m_contactCount = 0; + m_contactFilter = &b2_defaultFilter; + m_contactListener = &b2_defaultListener; + m_allocator = NULL; +} + +void b2ContactManager::Destroy(b2Contact* c) +{ + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + if (m_contactListener && c->IsTouching()) + { + m_contactListener->EndContact(c); + } + + // Remove from the world. + if (c->m_prev) + { + c->m_prev->m_next = c->m_next; + } + + if (c->m_next) + { + c->m_next->m_prev = c->m_prev; + } + + if (c == m_contactList) + { + m_contactList = c->m_next; + } + + // Remove from body 1 + if (c->m_nodeA.prev) + { + c->m_nodeA.prev->next = c->m_nodeA.next; + } + + if (c->m_nodeA.next) + { + c->m_nodeA.next->prev = c->m_nodeA.prev; + } + + if (&c->m_nodeA == bodyA->m_contactList) + { + bodyA->m_contactList = c->m_nodeA.next; + } + + // Remove from body 2 + if (c->m_nodeB.prev) + { + c->m_nodeB.prev->next = c->m_nodeB.next; + } + + if (c->m_nodeB.next) + { + c->m_nodeB.next->prev = c->m_nodeB.prev; + } + + if (&c->m_nodeB == bodyB->m_contactList) + { + bodyB->m_contactList = c->m_nodeB.next; + } + + // Call the factory. + b2Contact::Destroy(c, m_allocator); + --m_contactCount; +} + +// This is the top level collision call for the time step. Here +// all the narrow phase collision is processed for the world +// contact list. +void b2ContactManager::Collide() +{ + // Update awake contacts. + b2Contact* c = m_contactList; + while (c) + { + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Is this contact flagged for filtering? + if (c->m_flags & b2Contact::e_filterFlag) + { + // Should these bodies collide? + if (bodyB->ShouldCollide(bodyA) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // Clear the filtering flag. + c->m_flags &= ~b2Contact::e_filterFlag; + } + + bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; + bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; + + // At least one body must be awake and it must be dynamic or kinematic. + if (activeA == false && activeB == false) + { + c = c->GetNext(); + continue; + } + + int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; + int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; + bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); + + // Here we destroy contacts that cease to overlap in the broad-phase. + if (overlap == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } + + // The contact persists. + c->Update(m_contactListener); + c = c->GetNext(); + } +} + +void b2ContactManager::FindNewContacts() +{ + m_broadPhase.UpdatePairs(this); +} + +void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) +{ + b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; + b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; + + b2Fixture* fixtureA = proxyA->fixture; + b2Fixture* fixtureB = proxyB->fixture; + + int32 indexA = proxyA->childIndex; + int32 indexB = proxyB->childIndex; + + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Are the fixtures on the same body? + if (bodyA == bodyB) + { + return; + } + + // TODO_ERIN use a hash table to remove a potential bottleneck when both + // bodies have a lot of contacts. + // Does a contact already exist? + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + b2Fixture* fA = edge->contact->GetFixtureA(); + b2Fixture* fB = edge->contact->GetFixtureB(); + int32 iA = edge->contact->GetChildIndexA(); + int32 iB = edge->contact->GetChildIndexB(); + + if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) + { + // A contact already exists. + return; + } + + if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) + { + // A contact already exists. + return; + } + } + + edge = edge->next; + } + + // Does a joint override collision? Is at least one body dynamic? + if (bodyB->ShouldCollide(bodyA) == false) + { + return; + } + + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + return; + } + + // Call the factory. + b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); + if (c == NULL) + { + return; + } + + // Contact creation may swap fixtures. + fixtureA = c->GetFixtureA(); + fixtureB = c->GetFixtureB(); + indexA = c->GetChildIndexA(); + indexB = c->GetChildIndexB(); + bodyA = fixtureA->GetBody(); + bodyB = fixtureB->GetBody(); + + // Insert into the world. + c->m_prev = NULL; + c->m_next = m_contactList; + if (m_contactList != NULL) + { + m_contactList->m_prev = c; + } + m_contactList = c; + + // Connect to island graph. + + // Connect to body A + c->m_nodeA.contact = c; + c->m_nodeA.other = bodyB; + + c->m_nodeA.prev = NULL; + c->m_nodeA.next = bodyA->m_contactList; + if (bodyA->m_contactList != NULL) + { + bodyA->m_contactList->prev = &c->m_nodeA; + } + bodyA->m_contactList = &c->m_nodeA; + + // Connect to body B + c->m_nodeB.contact = c; + c->m_nodeB.other = bodyA; + + c->m_nodeB.prev = NULL; + c->m_nodeB.next = bodyB->m_contactList; + if (bodyB->m_contactList != NULL) + { + bodyB->m_contactList->prev = &c->m_nodeB; + } + bodyB->m_contactList = &c->m_nodeB; + + // Wake up the bodies + bodyA->SetAwake(true); + bodyB->SetAwake(true); + + ++m_contactCount; +} diff --git a/external/Box2D/Dynamics/b2ContactManager.h b/external/Box2D/Dynamics/b2ContactManager.h new file mode 100644 index 0000000000..9cb5718145 --- /dev/null +++ b/external/Box2D/Dynamics/b2ContactManager.h @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_CONTACT_MANAGER_H +#define B2_CONTACT_MANAGER_H + +#include + +class b2Contact; +class b2ContactFilter; +class b2ContactListener; +class b2BlockAllocator; + +// Delegate of b2World. +class b2ContactManager +{ +public: + b2ContactManager(); + + // Broad-phase callback. + void AddPair(void* proxyUserDataA, void* proxyUserDataB); + + void FindNewContacts(); + + void Destroy(b2Contact* c); + + void Collide(); + + b2BroadPhase m_broadPhase; + b2Contact* m_contactList; + int32 m_contactCount; + b2ContactFilter* m_contactFilter; + b2ContactListener* m_contactListener; + b2BlockAllocator* m_allocator; +}; + +#endif diff --git a/external/Box2D/Dynamics/b2Fixture.cpp b/external/Box2D/Dynamics/b2Fixture.cpp new file mode 100644 index 0000000000..774a78e5bb --- /dev/null +++ b/external/Box2D/Dynamics/b2Fixture.cpp @@ -0,0 +1,303 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +b2Fixture::b2Fixture() +{ + m_userData = NULL; + m_body = NULL; + m_next = NULL; + m_proxies = NULL; + m_proxyCount = 0; + m_shape = NULL; + m_density = 0.0f; +} + +void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) +{ + m_userData = def->userData; + m_friction = def->friction; + m_restitution = def->restitution; + + m_body = body; + m_next = NULL; + + m_filter = def->filter; + + m_isSensor = def->isSensor; + + m_shape = def->shape->Clone(allocator); + + // Reserve proxy space + int32 childCount = m_shape->GetChildCount(); + m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); + for (int32 i = 0; i < childCount; ++i) + { + m_proxies[i].fixture = NULL; + m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; + } + m_proxyCount = 0; + + m_density = def->density; +} + +void b2Fixture::Destroy(b2BlockAllocator* allocator) +{ + // The proxies must be destroyed before calling this. + b2Assert(m_proxyCount == 0); + + // Free the proxy array. + int32 childCount = m_shape->GetChildCount(); + allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); + m_proxies = NULL; + + // Free the child shape. + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + s->~b2CircleShape(); + allocator->Free(s, sizeof(b2CircleShape)); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + s->~b2EdgeShape(); + allocator->Free(s, sizeof(b2EdgeShape)); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + s->~b2PolygonShape(); + allocator->Free(s, sizeof(b2PolygonShape)); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + s->~b2ChainShape(); + allocator->Free(s, sizeof(b2ChainShape)); + } + break; + + default: + b2Assert(false); + break; + } + + m_shape = NULL; +} + +void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) +{ + b2Assert(m_proxyCount == 0); + + // Create proxies in the broad-phase. + m_proxyCount = m_shape->GetChildCount(); + + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + m_shape->ComputeAABB(&proxy->aabb, xf, i); + proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); + proxy->fixture = this; + proxy->childIndex = i; + } +} + +void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) +{ + // Destroy proxies in the broad-phase. + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + broadPhase->DestroyProxy(proxy->proxyId); + proxy->proxyId = b2BroadPhase::e_nullProxy; + } + + m_proxyCount = 0; +} + +void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) +{ + if (m_proxyCount == 0) + { + return; + } + + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + + // Compute an AABB that covers the swept shape (may miss some rotation effect). + b2AABB aabb1, aabb2; + m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); + m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); + + proxy->aabb.Combine(aabb1, aabb2); + + b2Vec2 displacement = transform2.p - transform1.p; + + broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); + } +} + +void b2Fixture::SetFilterData(const b2Filter& filter) +{ + m_filter = filter; + + Refilter(); +} + +void b2Fixture::Refilter() +{ + if (m_body == NULL) + { + return; + } + + // Flag associated contacts for filtering. + b2ContactEdge* edge = m_body->GetContactList(); + while (edge) + { + b2Contact* contact = edge->contact; + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + if (fixtureA == this || fixtureB == this) + { + contact->FlagForFiltering(); + } + + edge = edge->next; + } + + b2World* world = m_body->GetWorld(); + + if (world == NULL) + { + return; + } + + // Touch each proxy so that new pairs may be created + b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; + for (int32 i = 0; i < m_proxyCount; ++i) + { + broadPhase->TouchProxy(m_proxies[i].proxyId); + } +} + +void b2Fixture::SetSensor(bool sensor) +{ + if (sensor != m_isSensor) + { + m_body->SetAwake(true); + m_isSensor = sensor; + } +} + +void b2Fixture::Dump(int32 bodyIndex) +{ + b2Log(" b2FixtureDef fd;\n"); + b2Log(" fd.friction = %.15lef;\n", m_friction); + b2Log(" fd.restitution = %.15lef;\n", m_restitution); + b2Log(" fd.density = %.15lef;\n", m_density); + b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); + b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); + b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); + b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); + + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + b2Log(" b2CircleShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + b2Log(" b2EdgeShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); + b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); + b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); + b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); + b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); + b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + b2Log(" b2PolygonShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); + for (int32 i = 0; i < s->m_vertexCount; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + b2Log(" b2ChainShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", s->m_count); + for (int32 i = 0; i < s->m_count; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); + b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); + b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); + b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); + b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); + } + break; + + default: + return; + } + + b2Log("\n"); + b2Log(" fd.shape = &shape;\n"); + b2Log("\n"); + b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); +} diff --git a/external/Box2D/Dynamics/b2Fixture.h b/external/Box2D/Dynamics/b2Fixture.h new file mode 100644 index 0000000000..d390410b93 --- /dev/null +++ b/external/Box2D/Dynamics/b2Fixture.h @@ -0,0 +1,345 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_FIXTURE_H +#define B2_FIXTURE_H + +#include +#include +#include + +class b2BlockAllocator; +class b2Body; +class b2BroadPhase; +class b2Fixture; + +/// This holds contact filtering data. +struct b2Filter +{ + b2Filter() + { + categoryBits = 0x0001; + maskBits = 0xFFFF; + groupIndex = 0; + } + + /// The collision category bits. Normally you would just set one bit. + uint16 categoryBits; + + /// The collision mask bits. This states the categories that this + /// shape would accept for collision. + uint16 maskBits; + + /// Collision groups allow a certain group of objects to never collide (negative) + /// or always collide (positive). Zero means no collision group. Non-zero group + /// filtering always wins against the mask bits. + int16 groupIndex; +}; + +/// A fixture definition is used to create a fixture. This class defines an +/// abstract fixture definition. You can reuse fixture definitions safely. +struct b2FixtureDef +{ + /// The constructor sets the default fixture definition values. + b2FixtureDef() + { + shape = NULL; + userData = NULL; + friction = 0.2f; + restitution = 0.0f; + density = 0.0f; + isSensor = false; + } + + /// The shape, this must be set. The shape will be cloned, so you + /// can create the shape on the stack. + const b2Shape* shape; + + /// Use this to store application specific fixture data. + void* userData; + + /// The friction coefficient, usually in the range [0,1]. + float32 friction; + + /// The restitution (elasticity) usually in the range [0,1]. + float32 restitution; + + /// The density, usually in kg/m^2. + float32 density; + + /// A sensor shape collects contact information but never generates a collision + /// response. + bool isSensor; + + /// Contact filtering data. + b2Filter filter; +}; + +/// This proxy is used internally to connect fixtures to the broad-phase. +struct b2FixtureProxy +{ + b2AABB aabb; + b2Fixture* fixture; + int32 childIndex; + int32 proxyId; +}; + +/// A fixture is used to attach a shape to a body for collision detection. A fixture +/// inherits its transform from its parent. Fixtures hold additional non-geometric data +/// such as friction, collision filters, etc. +/// Fixtures are created via b2Body::CreateFixture. +/// @warning you cannot reuse fixtures. +class b2Fixture +{ +public: + /// Get the type of the child shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + b2Shape::Type GetType() const; + + /// Get the child shape. You can modify the child shape, however you should not change the + /// number of vertices because this will crash some collision caching mechanisms. + /// Manipulating the shape may lead to non-physical behavior. + b2Shape* GetShape(); + const b2Shape* GetShape() const; + + /// Set if this fixture is a sensor. + void SetSensor(bool sensor); + + /// Is this fixture a sensor (non-solid)? + /// @return the true if the shape is a sensor. + bool IsSensor() const; + + /// Set the contact filtering data. This will not update contacts until the next time + /// step when either parent body is active and awake. + /// This automatically calls Refilter. + void SetFilterData(const b2Filter& filter); + + /// Get the contact filtering data. + const b2Filter& GetFilterData() const; + + /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. + void Refilter(); + + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. + /// @return the parent body. + b2Body* GetBody(); + const b2Body* GetBody() const; + + /// Get the next fixture in the parent body's fixture list. + /// @return the next shape. + b2Fixture* GetNext(); + const b2Fixture* GetNext() const; + + /// Get the user data that was assigned in the fixture definition. Use this to + /// store your application specific data. + void* GetUserData() const; + + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); + + /// Test a point for containment in this fixture. + /// @param p a point in world coordinates. + bool TestPoint(const b2Vec2& p) const; + + /// Cast a ray against this shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; + + /// Get the mass data for this fixture. The mass data is based on the density and + /// the shape. The rotational inertia is about the shape's origin. This operation + /// may be expensive. + void GetMassData(b2MassData* massData) const; + + /// Set the density of this fixture. This will _not_ automatically adjust the mass + /// of the body. You must call b2Body::ResetMassData to update the body's mass. + void SetDensity(float32 density); + + /// Get the density of this fixture. + float32 GetDensity() const; + + /// Get the coefficient of friction. + float32 GetFriction() const; + + /// Set the coefficient of friction. This will _not_ change the friction of + /// existing contacts. + void SetFriction(float32 friction); + + /// Get the coefficient of restitution. + float32 GetRestitution() const; + + /// Set the coefficient of restitution. This will _not_ change the restitution of + /// existing contacts. + void SetRestitution(float32 restitution); + + /// Get the fixture's AABB. This AABB may be enlarge and/or stale. + /// If you need a more accurate AABB, compute it using the shape and + /// the body transform. + const b2AABB& GetAABB(int32 childIndex) const; + + /// Dump this fixture to the log file. + void Dump(int32 bodyIndex); + +protected: + + friend class b2Body; + friend class b2World; + friend class b2Contact; + friend class b2ContactManager; + + b2Fixture(); + + // We need separation create/destroy functions from the constructor/destructor because + // the destructor cannot access the allocator (no destructor arguments allowed by C++). + void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); + void Destroy(b2BlockAllocator* allocator); + + // These support body activation/deactivation. + void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); + void DestroyProxies(b2BroadPhase* broadPhase); + + void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); + + float32 m_density; + + b2Fixture* m_next; + b2Body* m_body; + + b2Shape* m_shape; + + float32 m_friction; + float32 m_restitution; + + b2FixtureProxy* m_proxies; + int32 m_proxyCount; + + b2Filter m_filter; + + bool m_isSensor; + + void* m_userData; +}; + +inline b2Shape::Type b2Fixture::GetType() const +{ + return m_shape->GetType(); +} + +inline b2Shape* b2Fixture::GetShape() +{ + return m_shape; +} + +inline const b2Shape* b2Fixture::GetShape() const +{ + return m_shape; +} + +inline bool b2Fixture::IsSensor() const +{ + return m_isSensor; +} + +inline const b2Filter& b2Fixture::GetFilterData() const +{ + return m_filter; +} + +inline void* b2Fixture::GetUserData() const +{ + return m_userData; +} + +inline void b2Fixture::SetUserData(void* data) +{ + m_userData = data; +} + +inline b2Body* b2Fixture::GetBody() +{ + return m_body; +} + +inline const b2Body* b2Fixture::GetBody() const +{ + return m_body; +} + +inline b2Fixture* b2Fixture::GetNext() +{ + return m_next; +} + +inline const b2Fixture* b2Fixture::GetNext() const +{ + return m_next; +} + +inline void b2Fixture::SetDensity(float32 density) +{ + b2Assert(b2IsValid(density) && density >= 0.0f); + m_density = density; +} + +inline float32 b2Fixture::GetDensity() const +{ + return m_density; +} + +inline float32 b2Fixture::GetFriction() const +{ + return m_friction; +} + +inline void b2Fixture::SetFriction(float32 friction) +{ + m_friction = friction; +} + +inline float32 b2Fixture::GetRestitution() const +{ + return m_restitution; +} + +inline void b2Fixture::SetRestitution(float32 restitution) +{ + m_restitution = restitution; +} + +inline bool b2Fixture::TestPoint(const b2Vec2& p) const +{ + return m_shape->TestPoint(m_body->GetTransform(), p); +} + +inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const +{ + return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); +} + +inline void b2Fixture::GetMassData(b2MassData* massData) const +{ + m_shape->ComputeMass(massData, m_density); +} + +inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const +{ + b2Assert(0 <= childIndex && childIndex < m_proxyCount); + return m_proxies[childIndex].aabb; +} + +#endif diff --git a/external/Box2D/Dynamics/b2Island.cpp b/external/Box2D/Dynamics/b2Island.cpp new file mode 100644 index 0000000000..e767d383d5 --- /dev/null +++ b/external/Box2D/Dynamics/b2Island.cpp @@ -0,0 +1,539 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +Position Correction Notes +========================= +I tried the several algorithms for position correction of the 2D revolute joint. +I looked at these systems: +- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. +- suspension bridge with 30 1m long planks of length 1m. +- multi-link chain with 30 1m long links. + +Here are the algorithms: + +Baumgarte - A fraction of the position error is added to the velocity error. There is no +separate position solver. + +Pseudo Velocities - After the velocity solver and position integration, +the position error, Jacobian, and effective mass are recomputed. Then +the velocity constraints are solved with pseudo velocities and a fraction +of the position error is added to the pseudo velocity error. The pseudo +velocities are initialized to zero and there is no warm-starting. After +the position solver, the pseudo velocities are added to the positions. +This is also called the First Order World method or the Position LCP method. + +Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the +position error is re-computed for each constraint and the positions are updated +after the constraint is solved. The radius vectors (aka Jacobians) are +re-computed too (otherwise the algorithm has horrible instability). The pseudo +velocity states are not needed because they are effectively zero at the beginning +of each iteration. Since we have the current position error, we allow the +iterations to terminate early if the error becomes smaller than b2_linearSlop. + +Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed +each time a constraint is solved. + +Here are the results: +Baumgarte - this is the cheapest algorithm but it has some stability problems, +especially with the bridge. The chain links separate easily close to the root +and they jitter as they struggle to pull together. This is one of the most common +methods in the field. The big drawback is that the position correction artificially +affects the momentum, thus leading to instabilities and false bounce. I used a +bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller +factor makes joints and contacts more spongy. + +Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is +stable. However, joints still separate with large angular velocities. Drag the +simple pendulum in a circle quickly and the joint will separate. The chain separates +easily and does not recover. I used a bias factor of 0.2. A larger value lead to +the bridge collapsing when a heavy cube drops on it. + +Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo +Velocities, but in other ways it is worse. The bridge and chain are much more +stable, but the simple pendulum goes unstable at high angular velocities. + +Full NGS - stable in all tests. The joints display good stiffness. The bridge +still sags, but this is better than infinite forces. + +Recommendations +Pseudo Velocities are not really worthwhile because the bridge and chain cannot +recover from joint separation. In other cases the benefit over Baumgarte is small. + +Modified NGS is not a robust method for the revolute joint due to the violent +instability seen in the simple pendulum. Perhaps it is viable with other constraint +types, especially scalar constraints where the effective mass is a scalar. + +This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities +and is very fast. I don't think we can escape Baumgarte, especially in highly +demanding cases where high constraint fidelity is not needed. + +Full NGS is robust and easy on the eyes. I recommend this as an option for +higher fidelity simulation and certainly for suspension bridges and long chains. +Full NGS might be a good choice for ragdolls, especially motorized ragdolls where +joint separation can be problematic. The number of NGS iterations can be reduced +for better performance without harming robustness much. + +Each joint in a can be handled differently in the position solver. So I recommend +a system where the user can select the algorithm on a per joint basis. I would +probably default to the slower Full NGS and let the user select the faster +Baumgarte method in performance critical scenarios. +*/ + +/* +Cache Performance + +The Box2D solvers are dominated by cache misses. Data structures are designed +to increase the number of cache hits. Much of misses are due to random access +to body data. The constraint structures are iterated over linearly, which leads +to few cache misses. + +The bodies are not accessed during iteration. Instead read only data, such as +the mass values are stored with the constraints. The mutable data are the constraint +impulses and the bodies velocities/positions. The impulses are held inside the +constraint structures. The body velocities/positions are held in compact, temporary +arrays to increase the number of cache hits. Linear and angular velocity are +stored in a single array since multiple arrays lead to multiple misses. +*/ + +/* +2D Rotation + +R = [cos(theta) -sin(theta)] + [sin(theta) cos(theta) ] + +thetaDot = omega + +Let q1 = cos(theta), q2 = sin(theta). +R = [q1 -q2] + [q2 q1] + +q1Dot = -thetaDot * q2 +q2Dot = thetaDot * q1 + +q1_new = q1_old - dt * w * q2 +q2_new = q2_old + dt * w * q1 +then normalize. + +This might be faster than computing sin+cos. +However, we can compute sin+cos of the same angle fast. +*/ + +b2Island::b2Island( + int32 bodyCapacity, + int32 contactCapacity, + int32 jointCapacity, + b2StackAllocator* allocator, + b2ContactListener* listener) +{ + m_bodyCapacity = bodyCapacity; + m_contactCapacity = contactCapacity; + m_jointCapacity = jointCapacity; + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; + + m_allocator = allocator; + m_listener = listener; + + m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); + m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); + m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); + + m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); + m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); +} + +b2Island::~b2Island() +{ + // Warning: the order should reverse the constructor order. + m_allocator->Free(m_positions); + m_allocator->Free(m_velocities); + m_allocator->Free(m_joints); + m_allocator->Free(m_contacts); + m_allocator->Free(m_bodies); +} + +void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) +{ + b2Timer timer; + + float32 h = step.dt; + + // Integrate velocities and apply damping. Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + + b2Vec2 c = b->m_sweep.c; + float32 a = b->m_sweep.a; + b2Vec2 v = b->m_linearVelocity; + float32 w = b->m_angularVelocity; + + // Store positions for continuous collision. + b->m_sweep.c0 = b->m_sweep.c; + b->m_sweep.a0 = b->m_sweep.a; + + if (b->m_type == b2_dynamicBody) + { + // Integrate velocities. + v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); + w += h * b->m_invI * b->m_torque; + + // Apply damping. + // ODE: dv/dt + c * v = 0 + // Solution: v(t) = v0 * exp(-c * t) + // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) + // v2 = exp(-c * dt) * v1 + // Taylor expansion: + // v2 = (1.0f - c * dt) * v1 + v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); + w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); + } + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } + + timer.Reset(); + + // Solver data + b2SolverData solverData; + solverData.step = step; + solverData.positions = m_positions; + solverData.velocities = m_velocities; + + // Initialize velocity constraints. + b2ContactSolverDef contactSolverDef; + contactSolverDef.step = step; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + contactSolverDef.allocator = m_allocator; + + b2ContactSolver contactSolver(&contactSolverDef); + contactSolver.InitializeVelocityConstraints(); + + if (step.warmStarting) + { + contactSolver.WarmStart(); + } + + for (int32 i = 0; i < m_jointCount; ++i) + { + m_joints[i]->InitVelocityConstraints(solverData); + } + + profile->solveInit = timer.GetMilliseconds(); + + // Solve velocity constraints + timer.Reset(); + for (int32 i = 0; i < step.velocityIterations; ++i) + { + for (int32 j = 0; j < m_jointCount; ++j) + { + m_joints[j]->SolveVelocityConstraints(solverData); + } + + contactSolver.SolveVelocityConstraints(); + } + + // Store impulses for warm starting + contactSolver.StoreImpulses(); + profile->solveVelocity = timer.GetMilliseconds(); + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } + + // Solve position constraints + timer.Reset(); + bool positionSolved = false; + for (int32 i = 0; i < step.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolvePositionConstraints(); + + bool jointsOkay = true; + for (int32 i = 0; i < m_jointCount; ++i) + { + bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); + jointsOkay = jointsOkay && jointOkay; + } + + if (contactsOkay && jointsOkay) + { + // Exit early if the position errors are small. + positionSolved = true; + break; + } + } + + // Copy state buffers back to the bodies + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* body = m_bodies[i]; + body->m_sweep.c = m_positions[i].c; + body->m_sweep.a = m_positions[i].a; + body->m_linearVelocity = m_velocities[i].v; + body->m_angularVelocity = m_velocities[i].w; + body->SynchronizeTransform(); + } + + profile->solvePosition = timer.GetMilliseconds(); + + Report(contactSolver.m_velocityConstraints); + + if (allowSleep) + { + float32 minSleepTime = b2_maxFloat; + + const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; + const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; + + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + continue; + } + + if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || + b->m_angularVelocity * b->m_angularVelocity > angTolSqr || + b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) + { + b->m_sleepTime = 0.0f; + minSleepTime = 0.0f; + } + else + { + b->m_sleepTime += h; + minSleepTime = b2Min(minSleepTime, b->m_sleepTime); + } + } + + if (minSleepTime >= b2_timeToSleep && positionSolved) + { + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + b->SetAwake(false); + } + } + } +} + +void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) +{ + b2Assert(toiIndexA < m_bodyCount); + b2Assert(toiIndexB < m_bodyCount); + + // Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + m_positions[i].c = b->m_sweep.c; + m_positions[i].a = b->m_sweep.a; + m_velocities[i].v = b->m_linearVelocity; + m_velocities[i].w = b->m_angularVelocity; + } + + b2ContactSolverDef contactSolverDef; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.allocator = m_allocator; + contactSolverDef.step = subStep; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + b2ContactSolver contactSolver(&contactSolverDef); + + // Solve position constraints. + for (int32 i = 0; i < subStep.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); + if (contactsOkay) + { + break; + } + } + +#if 0 + // Is the new position really safe? + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + b2DistanceInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.transformA = bA->GetTransform(); + input.transformB = bB->GetTransform(); + input.useRadii = false; + + b2DistanceOutput output; + b2SimplexCache cache; + cache.count = 0; + b2Distance(&output, &cache, &input); + + if (output.distance == 0 || cache.count == 3) + { + cache.count += 0; + } + } +#endif + + // Leap of faith to new safe state. + m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; + m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; + m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; + m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; + + // No warm starting is needed for TOI events because warm + // starting impulses were applied in the discrete solver. + contactSolver.InitializeVelocityConstraints(); + + // Solve velocity constraints. + for (int32 i = 0; i < subStep.velocityIterations; ++i) + { + contactSolver.SolveVelocityConstraints(); + } + + // Don't store the TOI contact forces for warm starting + // because they can be quite large. + + float32 h = subStep.dt; + + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; + + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } + + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } + + // Integrate + c += h * v; + a += h * w; + + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + + // Sync bodies + b2Body* body = m_bodies[i]; + body->m_sweep.c = c; + body->m_sweep.a = a; + body->m_linearVelocity = v; + body->m_angularVelocity = w; + body->SynchronizeTransform(); + } + + Report(contactSolver.m_velocityConstraints); +} + +void b2Island::Report(const b2ContactVelocityConstraint* constraints) +{ + if (m_listener == NULL) + { + return; + } + + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + + const b2ContactVelocityConstraint* vc = constraints + i; + + b2ContactImpulse impulse; + impulse.count = vc->pointCount; + for (int32 j = 0; j < vc->pointCount; ++j) + { + impulse.normalImpulses[j] = vc->points[j].normalImpulse; + impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; + } + + m_listener->PostSolve(c, &impulse); + } +} diff --git a/external/Box2D/Dynamics/b2Island.h b/external/Box2D/Dynamics/b2Island.h new file mode 100644 index 0000000000..e0a6e41fc3 --- /dev/null +++ b/external/Box2D/Dynamics/b2Island.h @@ -0,0 +1,93 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ISLAND_H +#define B2_ISLAND_H + +#include +#include +#include + +class b2Contact; +class b2Joint; +class b2StackAllocator; +class b2ContactListener; +struct b2ContactVelocityConstraint; +struct b2Profile; + +/// This is an internal class. +class b2Island +{ +public: + b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, + b2StackAllocator* allocator, b2ContactListener* listener); + ~b2Island(); + + void Clear() + { + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; + } + + void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); + + void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); + + void Add(b2Body* body) + { + b2Assert(m_bodyCount < m_bodyCapacity); + body->m_islandIndex = m_bodyCount; + m_bodies[m_bodyCount] = body; + ++m_bodyCount; + } + + void Add(b2Contact* contact) + { + b2Assert(m_contactCount < m_contactCapacity); + m_contacts[m_contactCount++] = contact; + } + + void Add(b2Joint* joint) + { + b2Assert(m_jointCount < m_jointCapacity); + m_joints[m_jointCount++] = joint; + } + + void Report(const b2ContactVelocityConstraint* constraints); + + b2StackAllocator* m_allocator; + b2ContactListener* m_listener; + + b2Body** m_bodies; + b2Contact** m_contacts; + b2Joint** m_joints; + + b2Position* m_positions; + b2Velocity* m_velocities; + + int32 m_bodyCount; + int32 m_jointCount; + int32 m_contactCount; + + int32 m_bodyCapacity; + int32 m_contactCapacity; + int32 m_jointCapacity; +}; + +#endif diff --git a/external/Box2D/Dynamics/b2TimeStep.h b/external/Box2D/Dynamics/b2TimeStep.h new file mode 100644 index 0000000000..30d723fcc3 --- /dev/null +++ b/external/Box2D/Dynamics/b2TimeStep.h @@ -0,0 +1,70 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_TIME_STEP_H +#define B2_TIME_STEP_H + +#include + +/// Profiling data. Times are in milliseconds. +struct b2Profile +{ + float32 step; + float32 collide; + float32 solve; + float32 solveInit; + float32 solveVelocity; + float32 solvePosition; + float32 broadphase; + float32 solveTOI; +}; + +/// This is an internal structure. +struct b2TimeStep +{ + float32 dt; // time step + float32 inv_dt; // inverse time step (0 if dt == 0). + float32 dtRatio; // dt * inv_dt0 + int32 velocityIterations; + int32 positionIterations; + bool warmStarting; +}; + +/// This is an internal structure. +struct b2Position +{ + b2Vec2 c; + float32 a; +}; + +/// This is an internal structure. +struct b2Velocity +{ + b2Vec2 v; + float32 w; +}; + +/// Solver Data +struct b2SolverData +{ + b2TimeStep step; + b2Position* positions; + b2Velocity* velocities; +}; + +#endif diff --git a/external/Box2D/Dynamics/b2World.cpp b/external/Box2D/Dynamics/b2World.cpp new file mode 100644 index 0000000000..8a0aff5114 --- /dev/null +++ b/external/Box2D/Dynamics/b2World.cpp @@ -0,0 +1,1316 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +b2World::b2World(const b2Vec2& gravity) +{ + m_destructionListener = NULL; + m_debugDraw = NULL; + + m_bodyList = NULL; + m_jointList = NULL; + + m_bodyCount = 0; + m_jointCount = 0; + + m_warmStarting = true; + m_continuousPhysics = true; + m_subStepping = false; + + m_stepComplete = true; + + m_allowSleep = true; + m_gravity = gravity; + + m_flags = e_clearForces; + + m_inv_dt0 = 0.0f; + + m_contactManager.m_allocator = &m_blockAllocator; + + memset(&m_profile, 0, sizeof(b2Profile)); +} + +b2World::~b2World() +{ + // Some shapes allocate using b2Alloc. + b2Body* b = m_bodyList; + while (b) + { + b2Body* bNext = b->m_next; + + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* fNext = f->m_next; + f->m_proxyCount = 0; + f->Destroy(&m_blockAllocator); + f = fNext; + } + + b = bNext; + } +} + +void b2World::SetDestructionListener(b2DestructionListener* listener) +{ + m_destructionListener = listener; +} + +void b2World::SetContactFilter(b2ContactFilter* filter) +{ + m_contactManager.m_contactFilter = filter; +} + +void b2World::SetContactListener(b2ContactListener* listener) +{ + m_contactManager.m_contactListener = listener; +} + +void b2World::SetDebugDraw(b2Draw* debugDraw) +{ + m_debugDraw = debugDraw; +} + +b2Body* b2World::CreateBody(const b2BodyDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); + b2Body* b = new (mem) b2Body(def, this); + + // Add to world doubly linked list. + b->m_prev = NULL; + b->m_next = m_bodyList; + if (m_bodyList) + { + m_bodyList->m_prev = b; + } + m_bodyList = b; + ++m_bodyCount; + + return b; +} + +void b2World::DestroyBody(b2Body* b) +{ + b2Assert(m_bodyCount > 0); + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + // Delete the attached joints. + b2JointEdge* je = b->m_jointList; + while (je) + { + b2JointEdge* je0 = je; + je = je->next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(je0->joint); + } + + DestroyJoint(je0->joint); + + b->m_jointList = je; + } + b->m_jointList = NULL; + + // Delete the attached contacts. + b2ContactEdge* ce = b->m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_contactManager.Destroy(ce0->contact); + } + b->m_contactList = NULL; + + // Delete the attached fixtures. This destroys broad-phase proxies. + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* f0 = f; + f = f->m_next; + + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(f0); + } + + f0->DestroyProxies(&m_contactManager.m_broadPhase); + f0->Destroy(&m_blockAllocator); + f0->~b2Fixture(); + m_blockAllocator.Free(f0, sizeof(b2Fixture)); + + b->m_fixtureList = f; + b->m_fixtureCount -= 1; + } + b->m_fixtureList = NULL; + b->m_fixtureCount = 0; + + // Remove world body list. + if (b->m_prev) + { + b->m_prev->m_next = b->m_next; + } + + if (b->m_next) + { + b->m_next->m_prev = b->m_prev; + } + + if (b == m_bodyList) + { + m_bodyList = b->m_next; + } + + --m_bodyCount; + b->~b2Body(); + m_blockAllocator.Free(b, sizeof(b2Body)); +} + +b2Joint* b2World::CreateJoint(const b2JointDef* def) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } + + b2Joint* j = b2Joint::Create(def, &m_blockAllocator); + + // Connect to the world list. + j->m_prev = NULL; + j->m_next = m_jointList; + if (m_jointList) + { + m_jointList->m_prev = j; + } + m_jointList = j; + ++m_jointCount; + + // Connect to the bodies' doubly linked lists. + j->m_edgeA.joint = j; + j->m_edgeA.other = j->m_bodyB; + j->m_edgeA.prev = NULL; + j->m_edgeA.next = j->m_bodyA->m_jointList; + if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; + j->m_bodyA->m_jointList = &j->m_edgeA; + + j->m_edgeB.joint = j; + j->m_edgeB.other = j->m_bodyA; + j->m_edgeB.prev = NULL; + j->m_edgeB.next = j->m_bodyB->m_jointList; + if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; + j->m_bodyB->m_jointList = &j->m_edgeB; + + b2Body* bodyA = def->bodyA; + b2Body* bodyB = def->bodyB; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (def->collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } + + // Note: creating a joint doesn't wake the bodies. + + return j; +} + +void b2World::DestroyJoint(b2Joint* j) +{ + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } + + bool collideConnected = j->m_collideConnected; + + // Remove from the doubly linked list. + if (j->m_prev) + { + j->m_prev->m_next = j->m_next; + } + + if (j->m_next) + { + j->m_next->m_prev = j->m_prev; + } + + if (j == m_jointList) + { + m_jointList = j->m_next; + } + + // Disconnect from island graph. + b2Body* bodyA = j->m_bodyA; + b2Body* bodyB = j->m_bodyB; + + // Wake up connected bodies. + bodyA->SetAwake(true); + bodyB->SetAwake(true); + + // Remove from body 1. + if (j->m_edgeA.prev) + { + j->m_edgeA.prev->next = j->m_edgeA.next; + } + + if (j->m_edgeA.next) + { + j->m_edgeA.next->prev = j->m_edgeA.prev; + } + + if (&j->m_edgeA == bodyA->m_jointList) + { + bodyA->m_jointList = j->m_edgeA.next; + } + + j->m_edgeA.prev = NULL; + j->m_edgeA.next = NULL; + + // Remove from body 2 + if (j->m_edgeB.prev) + { + j->m_edgeB.prev->next = j->m_edgeB.next; + } + + if (j->m_edgeB.next) + { + j->m_edgeB.next->prev = j->m_edgeB.prev; + } + + if (&j->m_edgeB == bodyB->m_jointList) + { + bodyB->m_jointList = j->m_edgeB.next; + } + + j->m_edgeB.prev = NULL; + j->m_edgeB.next = NULL; + + b2Joint::Destroy(j, &m_blockAllocator); + + b2Assert(m_jointCount > 0); + --m_jointCount; + + // If the joint prevents collisions, then flag any contacts for filtering. + if (collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } + + edge = edge->next; + } + } +} + +// +void b2World::SetAllowSleeping(bool flag) +{ + if (flag == m_allowSleep) + { + return; + } + + m_allowSleep = flag; + if (m_allowSleep == false) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->SetAwake(true); + } + } +} + +// Find islands, integrate and solve constraints, solve position constraints +void b2World::Solve(const b2TimeStep& step) +{ + m_profile.solveInit = 0.0f; + m_profile.solveVelocity = 0.0f; + m_profile.solvePosition = 0.0f; + + // Size the island for the worst case. + b2Island island(m_bodyCount, + m_contactManager.m_contactCount, + m_jointCount, + &m_stackAllocator, + m_contactManager.m_contactListener); + + // Clear all the island flags. + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + c->m_flags &= ~b2Contact::e_islandFlag; + } + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_islandFlag = false; + } + + // Build and simulate all awake islands. + int32 stackSize = m_bodyCount; + b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); + for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) + { + if (seed->m_flags & b2Body::e_islandFlag) + { + continue; + } + + if (seed->IsAwake() == false || seed->IsActive() == false) + { + continue; + } + + // The seed can be dynamic or kinematic. + if (seed->GetType() == b2_staticBody) + { + continue; + } + + // Reset island and stack. + island.Clear(); + int32 stackCount = 0; + stack[stackCount++] = seed; + seed->m_flags |= b2Body::e_islandFlag; + + // Perform a depth first search (DFS) on the constraint graph. + while (stackCount > 0) + { + // Grab the next body off the stack and add it to the island. + b2Body* b = stack[--stackCount]; + b2Assert(b->IsActive() == true); + island.Add(b); + + // Make sure the body is awake. + b->SetAwake(true); + + // To keep islands as small as possible, we don't + // propagate islands across static bodies. + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Search all contacts connected to this body. + for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) + { + b2Contact* contact = ce->contact; + + // Has this contact already been added to an island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Is this contact solid and touching? + if (contact->IsEnabled() == false || + contact->IsTouching() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + island.Add(contact); + contact->m_flags |= b2Contact::e_islandFlag; + + b2Body* other = ce->other; + + // Was the other body already added to this island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + + // Search all joints connect to this body. + for (b2JointEdge* je = b->m_jointList; je; je = je->next) + { + if (je->joint->m_islandFlag == true) + { + continue; + } + + b2Body* other = je->other; + + // Don't simulate joints connected to inactive bodies. + if (other->IsActive() == false) + { + continue; + } + + island.Add(je->joint); + je->joint->m_islandFlag = true; + + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + } + + b2Profile profile; + island.Solve(&profile, step, m_gravity, m_allowSleep); + m_profile.solveInit += profile.solveInit; + m_profile.solveVelocity += profile.solveVelocity; + m_profile.solvePosition += profile.solvePosition; + + // Post solve cleanup. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + // Allow static bodies to participate in other islands. + b2Body* b = island.m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + } + } + + m_stackAllocator.Free(stack); + + { + b2Timer timer; + // Synchronize fixtures, check for out of range bodies. + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + // If a body was not in an island then it did not move. + if ((b->m_flags & b2Body::e_islandFlag) == 0) + { + continue; + } + + if (b->GetType() == b2_staticBody) + { + continue; + } + + // Update fixtures (for broad-phase). + b->SynchronizeFixtures(); + } + + // Look for new contacts. + m_contactManager.FindNewContacts(); + m_profile.broadphase = timer.GetMilliseconds(); + } +} + +// Find TOI contacts and solve them. +void b2World::SolveTOI(const b2TimeStep& step) +{ + b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); + + if (m_stepComplete) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + b->m_sweep.alpha0 = 0.0f; + } + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Invalidate TOI + c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + c->m_toiCount = 0; + c->m_toi = 1.0f; + } + } + + // Find TOI events and solve them. + for (;;) + { + // Find the first TOI. + b2Contact* minContact = NULL; + float32 minAlpha = 1.0f; + + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Is this contact disabled? + if (c->IsEnabled() == false) + { + continue; + } + + // Prevent excessive sub-stepping. + if (c->m_toiCount > b2_maxSubSteps) + { + continue; + } + + float32 alpha = 1.0f; + if (c->m_flags & b2Contact::e_toiFlag) + { + // This contact has a valid cached TOI. + alpha = c->m_toi; + } + else + { + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); + + // Is there a sensor? + if (fA->IsSensor() || fB->IsSensor()) + { + continue; + } + + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + b2BodyType typeA = bA->m_type; + b2BodyType typeB = bB->m_type; + b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); + + bool activeA = bA->IsAwake() && typeA != b2_staticBody; + bool activeB = bB->IsAwake() && typeB != b2_staticBody; + + // Is at least one body active (awake and dynamic or kinematic)? + if (activeA == false && activeB == false) + { + continue; + } + + bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; + bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; + + // Are these two non-bullet dynamic bodies? + if (collideA == false && collideB == false) + { + continue; + } + + // Compute the TOI for this contact. + // Put the sweeps onto the same time interval. + float32 alpha0 = bA->m_sweep.alpha0; + + if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) + { + alpha0 = bB->m_sweep.alpha0; + bA->m_sweep.Advance(alpha0); + } + else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) + { + alpha0 = bA->m_sweep.alpha0; + bB->m_sweep.Advance(alpha0); + } + + b2Assert(alpha0 < 1.0f); + + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + + // Compute the time of impact in interval [0, minTOI] + b2TOIInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.sweepA = bA->m_sweep; + input.sweepB = bB->m_sweep; + input.tMax = 1.0f; + + b2TOIOutput output; + b2TimeOfImpact(&output, &input); + + // Beta is the fraction of the remaining portion of the . + float32 beta = output.t; + if (output.state == b2TOIOutput::e_touching) + { + alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); + } + else + { + alpha = 1.0f; + } + + c->m_toi = alpha; + c->m_flags |= b2Contact::e_toiFlag; + } + + if (alpha < minAlpha) + { + // This is the minimum TOI found so far. + minContact = c; + minAlpha = alpha; + } + } + + if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) + { + // No more TOI events. Done! + m_stepComplete = true; + break; + } + + // Advance the bodies to the TOI. + b2Fixture* fA = minContact->GetFixtureA(); + b2Fixture* fB = minContact->GetFixtureB(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); + + b2Sweep backup1 = bA->m_sweep; + b2Sweep backup2 = bB->m_sweep; + + bA->Advance(minAlpha); + bB->Advance(minAlpha); + + // The TOI contact likely has some new contact points. + minContact->Update(m_contactManager.m_contactListener); + minContact->m_flags &= ~b2Contact::e_toiFlag; + ++minContact->m_toiCount; + + // Is the contact solid? + if (minContact->IsEnabled() == false || minContact->IsTouching() == false) + { + // Restore the sweeps. + minContact->SetEnabled(false); + bA->m_sweep = backup1; + bB->m_sweep = backup2; + bA->SynchronizeTransform(); + bB->SynchronizeTransform(); + continue; + } + + bA->SetAwake(true); + bB->SetAwake(true); + + // Build the island + island.Clear(); + island.Add(bA); + island.Add(bB); + island.Add(minContact); + + bA->m_flags |= b2Body::e_islandFlag; + bB->m_flags |= b2Body::e_islandFlag; + minContact->m_flags |= b2Contact::e_islandFlag; + + // Get contacts on bodyA and bodyB. + b2Body* bodies[2] = {bA, bB}; + for (int32 i = 0; i < 2; ++i) + { + b2Body* body = bodies[i]; + if (body->m_type == b2_dynamicBody) + { + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + if (island.m_bodyCount == island.m_bodyCapacity) + { + break; + } + + if (island.m_contactCount == island.m_contactCapacity) + { + break; + } + + b2Contact* contact = ce->contact; + + // Has this contact already been added to the island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } + + // Only add static, kinematic, or bullet bodies. + b2Body* other = ce->other; + if (other->m_type == b2_dynamicBody && + body->IsBullet() == false && other->IsBullet() == false) + { + continue; + } + + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } + + // Tentatively advance the body to the TOI. + b2Sweep backup = other->m_sweep; + if ((other->m_flags & b2Body::e_islandFlag) == 0) + { + other->Advance(minAlpha); + } + + // Update the contact points + contact->Update(m_contactManager.m_contactListener); + + // Was the contact disabled by the user? + if (contact->IsEnabled() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Are there contact points? + if (contact->IsTouching() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } + + // Add the contact to the island + contact->m_flags |= b2Contact::e_islandFlag; + island.Add(contact); + + // Has the other body already been added to the island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + // Add the other body to the island. + other->m_flags |= b2Body::e_islandFlag; + + if (other->m_type != b2_staticBody) + { + other->SetAwake(true); + } + + island.Add(other); + } + } + } + + b2TimeStep subStep; + subStep.dt = (1.0f - minAlpha) * step.dt; + subStep.inv_dt = 1.0f / subStep.dt; + subStep.dtRatio = 1.0f; + subStep.positionIterations = 20; + subStep.velocityIterations = step.velocityIterations; + subStep.warmStarting = false; + island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); + + // Reset island flags and synchronize broad-phase proxies. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + b2Body* body = island.m_bodies[i]; + body->m_flags &= ~b2Body::e_islandFlag; + + if (body->m_type != b2_dynamicBody) + { + continue; + } + + body->SynchronizeFixtures(); + + // Invalidate all contact TOIs on this displaced body. + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + } + } + + // Commit fixture proxy movements to the broad-phase so that new contacts are created. + // Also, some contacts can be destroyed. + m_contactManager.FindNewContacts(); + + if (m_subStepping) + { + m_stepComplete = false; + break; + } + } +} + +void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) +{ + b2Timer stepTimer; + + // If new fixtures were added, we need to find the new contacts. + if (m_flags & e_newFixture) + { + m_contactManager.FindNewContacts(); + m_flags &= ~e_newFixture; + } + + m_flags |= e_locked; + + b2TimeStep step; + step.dt = dt; + step.velocityIterations = velocityIterations; + step.positionIterations = positionIterations; + if (dt > 0.0f) + { + step.inv_dt = 1.0f / dt; + } + else + { + step.inv_dt = 0.0f; + } + + step.dtRatio = m_inv_dt0 * dt; + + step.warmStarting = m_warmStarting; + + // Update contacts. This is where some contacts are destroyed. + { + b2Timer timer; + m_contactManager.Collide(); + m_profile.collide = timer.GetMilliseconds(); + } + + // Integrate velocities, solve velocity constraints, and integrate positions. + if (m_stepComplete && step.dt > 0.0f) + { + b2Timer timer; + Solve(step); + m_profile.solve = timer.GetMilliseconds(); + } + + // Handle TOI events. + if (m_continuousPhysics && step.dt > 0.0f) + { + b2Timer timer; + SolveTOI(step); + m_profile.solveTOI = timer.GetMilliseconds(); + } + + if (step.dt > 0.0f) + { + m_inv_dt0 = step.inv_dt; + } + + if (m_flags & e_clearForces) + { + ClearForces(); + } + + m_flags &= ~e_locked; + + m_profile.step = stepTimer.GetMilliseconds(); +} + +void b2World::ClearForces() +{ + for (b2Body* body = m_bodyList; body; body = body->GetNext()) + { + body->m_force.SetZero(); + body->m_torque = 0.0f; + } +} + +struct b2WorldQueryWrapper +{ + bool QueryCallback(int32 proxyId) + { + b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); + return callback->ReportFixture(proxy->fixture); + } + + const b2BroadPhase* broadPhase; + b2QueryCallback* callback; +}; + +void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const +{ + b2WorldQueryWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + m_contactManager.m_broadPhase.Query(&wrapper, aabb); +} + +struct b2WorldRayCastWrapper +{ + float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + void* userData = broadPhase->GetUserData(proxyId); + b2FixtureProxy* proxy = (b2FixtureProxy*)userData; + b2Fixture* fixture = proxy->fixture; + int32 index = proxy->childIndex; + b2RayCastOutput output; + bool hit = fixture->RayCast(&output, input, index); + + if (hit) + { + float32 fraction = output.fraction; + b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; + return callback->ReportFixture(fixture, point, output.normal, fraction); + } + + return input.maxFraction; + } + + const b2BroadPhase* broadPhase; + b2RayCastCallback* callback; +}; + +void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const +{ + b2WorldRayCastWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + b2RayCastInput input; + input.maxFraction = 1.0f; + input.p1 = point1; + input.p2 = point2; + m_contactManager.m_broadPhase.RayCast(&wrapper, input); +} + +void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) +{ + switch (fixture->GetType()) + { + case b2Shape::e_circle: + { + b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); + + b2Vec2 center = b2Mul(xf, circle->m_p); + float32 radius = circle->m_radius; + b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); + + m_debugDraw->DrawSolidCircle(center, radius, axis, color); + } + break; + + case b2Shape::e_edge: + { + b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); + b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); + b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); + m_debugDraw->DrawSegment(v1, v2, color); + } + break; + + case b2Shape::e_chain: + { + b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); + int32 count = chain->m_count; + const b2Vec2* vertices = chain->m_vertices; + + b2Vec2 v1 = b2Mul(xf, vertices[0]); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v2 = b2Mul(xf, vertices[i]); + m_debugDraw->DrawSegment(v1, v2, color); + m_debugDraw->DrawCircle(v1, 0.05f, color); + v1 = v2; + } + } + break; + + case b2Shape::e_polygon: + { + b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); + int32 vertexCount = poly->m_vertexCount; + b2Assert(vertexCount <= b2_maxPolygonVertices); + b2Vec2 vertices[b2_maxPolygonVertices]; + + for (int32 i = 0; i < vertexCount; ++i) + { + vertices[i] = b2Mul(xf, poly->m_vertices[i]); + } + + m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); + } + break; + + default: + break; + } +} + +void b2World::DrawJoint(b2Joint* joint) +{ + b2Body* bodyA = joint->GetBodyA(); + b2Body* bodyB = joint->GetBodyB(); + const b2Transform& xf1 = bodyA->GetTransform(); + const b2Transform& xf2 = bodyB->GetTransform(); + b2Vec2 x1 = xf1.p; + b2Vec2 x2 = xf2.p; + b2Vec2 p1 = joint->GetAnchorA(); + b2Vec2 p2 = joint->GetAnchorB(); + + b2Color color(0.5f, 0.8f, 0.8f); + + switch (joint->GetType()) + { + case e_distanceJoint: + m_debugDraw->DrawSegment(p1, p2, color); + break; + + case e_pulleyJoint: + { + b2PulleyJoint* pulley = (b2PulleyJoint*)joint; + b2Vec2 s1 = pulley->GetGroundAnchorA(); + b2Vec2 s2 = pulley->GetGroundAnchorB(); + m_debugDraw->DrawSegment(s1, p1, color); + m_debugDraw->DrawSegment(s2, p2, color); + m_debugDraw->DrawSegment(s1, s2, color); + } + break; + + case e_mouseJoint: + // don't draw this + break; + + default: + m_debugDraw->DrawSegment(x1, p1, color); + m_debugDraw->DrawSegment(p1, p2, color); + m_debugDraw->DrawSegment(x2, p2, color); + } +} + +void b2World::DrawDebugData() +{ + if (m_debugDraw == NULL) + { + return; + } + + uint32 flags = m_debugDraw->GetFlags(); + + if (flags & b2Draw::e_shapeBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + const b2Transform& xf = b->GetTransform(); + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + if (b->IsActive() == false) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); + } + else if (b->GetType() == b2_staticBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); + } + else if (b->GetType() == b2_kinematicBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); + } + else if (b->IsAwake() == false) + { + DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); + } + else + { + DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); + } + } + } + } + + if (flags & b2Draw::e_jointBit) + { + for (b2Joint* j = m_jointList; j; j = j->GetNext()) + { + DrawJoint(j); + } + } + + if (flags & b2Draw::e_pairBit) + { + b2Color color(0.3f, 0.9f, 0.9f); + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) + { + //b2Fixture* fixtureA = c->GetFixtureA(); + //b2Fixture* fixtureB = c->GetFixtureB(); + + //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); + //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); + + //m_debugDraw->DrawSegment(cA, cB, color); + } + } + + if (flags & b2Draw::e_aabbBit) + { + b2Color color(0.9f, 0.3f, 0.9f); + b2BroadPhase* bp = &m_contactManager.m_broadPhase; + + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + if (b->IsActive() == false) + { + continue; + } + + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + for (int32 i = 0; i < f->m_proxyCount; ++i) + { + b2FixtureProxy* proxy = f->m_proxies + i; + b2AABB aabb = bp->GetFatAABB(proxy->proxyId); + b2Vec2 vs[4]; + vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); + vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); + vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); + vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); + + m_debugDraw->DrawPolygon(vs, 4, color); + } + } + } + } + + if (flags & b2Draw::e_centerOfMassBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + b2Transform xf = b->GetTransform(); + xf.p = b->GetWorldCenter(); + m_debugDraw->DrawTransform(xf); + } + } +} + +int32 b2World::GetProxyCount() const +{ + return m_contactManager.m_broadPhase.GetProxyCount(); +} + +int32 b2World::GetTreeHeight() const +{ + return m_contactManager.m_broadPhase.GetTreeHeight(); +} + +int32 b2World::GetTreeBalance() const +{ + return m_contactManager.m_broadPhase.GetTreeBalance(); +} + +float32 b2World::GetTreeQuality() const +{ + return m_contactManager.m_broadPhase.GetTreeQuality(); +} + +void b2World::Dump() +{ + if ((m_flags & e_locked) == e_locked) + { + return; + } + + b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); + b2Log("m_world->SetGravity(g);\n"); + + b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); + b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); + int32 i = 0; + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_islandIndex = i; + b->Dump(); + ++i; + } + + i = 0; + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_index = i; + ++i; + } + + // First pass on joints, skip gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type == e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + // Second pass on joints, only gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type != e_gearJoint) + { + continue; + } + + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } + + b2Log("b2Free(joints);\n"); + b2Log("b2Free(bodies);\n"); + b2Log("joints = NULL;\n"); + b2Log("bodies = NULL;\n"); +} diff --git a/external/Box2D/Dynamics/b2World.h b/external/Box2D/Dynamics/b2World.h new file mode 100644 index 0000000000..f207930511 --- /dev/null +++ b/external/Box2D/Dynamics/b2World.h @@ -0,0 +1,349 @@ +/* +* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WORLD_H +#define B2_WORLD_H + +#include +#include +#include +#include +#include +#include + +struct b2AABB; +struct b2BodyDef; +struct b2Color; +struct b2JointDef; +class b2Body; +class b2Draw; +class b2Fixture; +class b2Joint; + +/// The world class manages all physics entities, dynamic simulation, +/// and asynchronous queries. The world also contains efficient memory +/// management facilities. +class b2World +{ +public: + /// Construct a world object. + /// @param gravity the world gravity vector. + b2World(const b2Vec2& gravity); + + /// Destruct the world. All physics entities are destroyed and all heap memory is released. + ~b2World(); + + /// Register a destruction listener. The listener is owned by you and must + /// remain in scope. + void SetDestructionListener(b2DestructionListener* listener); + + /// Register a contact filter to provide specific control over collision. + /// Otherwise the default filter is used (b2_defaultFilter). The listener is + /// owned by you and must remain in scope. + void SetContactFilter(b2ContactFilter* filter); + + /// Register a contact event listener. The listener is owned by you and must + /// remain in scope. + void SetContactListener(b2ContactListener* listener); + + /// Register a routine for debug drawing. The debug draw functions are called + /// inside with b2World::DrawDebugData method. The debug draw object is owned + /// by you and must remain in scope. + void SetDebugDraw(b2Draw* debugDraw); + + /// Create a rigid body given a definition. No reference to the definition + /// is retained. + /// @warning This function is locked during callbacks. + b2Body* CreateBody(const b2BodyDef* def); + + /// Destroy a rigid body given a definition. No reference to the definition + /// is retained. This function is locked during callbacks. + /// @warning This automatically deletes all associated shapes and joints. + /// @warning This function is locked during callbacks. + void DestroyBody(b2Body* body); + + /// Create a joint to constrain bodies together. No reference to the definition + /// is retained. This may cause the connected bodies to cease colliding. + /// @warning This function is locked during callbacks. + b2Joint* CreateJoint(const b2JointDef* def); + + /// Destroy a joint. This may cause the connected bodies to begin colliding. + /// @warning This function is locked during callbacks. + void DestroyJoint(b2Joint* joint); + + /// Take a time step. This performs collision detection, integration, + /// and constraint solution. + /// @param timeStep the amount of time to simulate, this should not vary. + /// @param velocityIterations for the velocity constraint solver. + /// @param positionIterations for the position constraint solver. + void Step( float32 timeStep, + int32 velocityIterations, + int32 positionIterations); + + /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically + /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. + /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain + /// a fixed sized time step under a variable frame-rate. + /// When you perform sub-stepping you will disable auto clearing of forces and instead call + /// ClearForces after all sub-steps are complete in one pass of your game loop. + /// @see SetAutoClearForces + void ClearForces(); + + /// Call this to draw shapes and other debug draw data. + void DrawDebugData(); + + /// Query the world for all fixtures that potentially overlap the + /// provided AABB. + /// @param callback a user implemented callback class. + /// @param aabb the query box. + void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; + + /// Ray-cast the world for all fixtures in the path of the ray. Your callback + /// controls whether you get the closest point, any point, or n-points. + /// The ray-cast ignores shapes that contain the starting point. + /// @param callback a user implemented callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point + void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; + + /// Get the world body list. With the returned body, use b2Body::GetNext to get + /// the next body in the world list. A NULL body indicates the end of the list. + /// @return the head of the world body list. + b2Body* GetBodyList(); + const b2Body* GetBodyList() const; + + /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get + /// the next joint in the world list. A NULL joint indicates the end of the list. + /// @return the head of the world joint list. + b2Joint* GetJointList(); + const b2Joint* GetJointList() const; + + /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get + /// the next contact in the world list. A NULL contact indicates the end of the list. + /// @return the head of the world contact list. + /// @warning contacts are created and destroyed in the middle of a time step. + /// Use b2ContactListener to avoid missing contacts. + b2Contact* GetContactList(); + const b2Contact* GetContactList() const; + + /// Enable/disable sleep. + void SetAllowSleeping(bool flag); + bool GetAllowSleeping() const { return m_allowSleep; } + + /// Enable/disable warm starting. For testing. + void SetWarmStarting(bool flag) { m_warmStarting = flag; } + bool GetWarmStarting() const { return m_warmStarting; } + + /// Enable/disable continuous physics. For testing. + void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + bool GetContinuousPhysics() const { return m_continuousPhysics; } + + /// Enable/disable single stepped continuous physics. For testing. + void SetSubStepping(bool flag) { m_subStepping = flag; } + bool GetSubStepping() const { return m_subStepping; } + + /// Get the number of broad-phase proxies. + int32 GetProxyCount() const; + + /// Get the number of bodies. + int32 GetBodyCount() const; + + /// Get the number of joints. + int32 GetJointCount() const; + + /// Get the number of contacts (each may have 0 or more contact points). + int32 GetContactCount() const; + + /// Get the height of the dynamic tree. + int32 GetTreeHeight() const; + + /// Get the balance of the dynamic tree. + int32 GetTreeBalance() const; + + /// Get the quality metric of the dynamic tree. The smaller the better. + /// The minimum is 1. + float32 GetTreeQuality() const; + + /// Change the global gravity vector. + void SetGravity(const b2Vec2& gravity); + + /// Get the global gravity vector. + b2Vec2 GetGravity() const; + + /// Is the world locked (in the middle of a time step). + bool IsLocked() const; + + /// Set flag to control automatic clearing of forces after each time step. + void SetAutoClearForces(bool flag); + + /// Get the flag that controls automatic clearing of forces after each time step. + bool GetAutoClearForces() const; + + /// Get the contact manager for testing. + const b2ContactManager& GetContactManager() const; + + /// Get the current profile. + const b2Profile& GetProfile() const; + + /// Dump the world into the log file. + /// @warning this should be called outside of a time step. + void Dump(); + +private: + + // m_flags + enum + { + e_newFixture = 0x0001, + e_locked = 0x0002, + e_clearForces = 0x0004 + }; + + friend class b2Body; + friend class b2Fixture; + friend class b2ContactManager; + friend class b2Controller; + + void Solve(const b2TimeStep& step); + void SolveTOI(const b2TimeStep& step); + + void DrawJoint(b2Joint* joint); + void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); + + b2BlockAllocator m_blockAllocator; + b2StackAllocator m_stackAllocator; + + int32 m_flags; + + b2ContactManager m_contactManager; + + b2Body* m_bodyList; + b2Joint* m_jointList; + + int32 m_bodyCount; + int32 m_jointCount; + + b2Vec2 m_gravity; + bool m_allowSleep; + + b2DestructionListener* m_destructionListener; + b2Draw* m_debugDraw; + + // This is used to compute the time step ratio to + // support a variable time step. + float32 m_inv_dt0; + + // These are for debugging the solver. + bool m_warmStarting; + bool m_continuousPhysics; + bool m_subStepping; + + bool m_stepComplete; + + b2Profile m_profile; +}; + +inline b2Body* b2World::GetBodyList() +{ + return m_bodyList; +} + +inline const b2Body* b2World::GetBodyList() const +{ + return m_bodyList; +} + +inline b2Joint* b2World::GetJointList() +{ + return m_jointList; +} + +inline const b2Joint* b2World::GetJointList() const +{ + return m_jointList; +} + +inline b2Contact* b2World::GetContactList() +{ + return m_contactManager.m_contactList; +} + +inline const b2Contact* b2World::GetContactList() const +{ + return m_contactManager.m_contactList; +} + +inline int32 b2World::GetBodyCount() const +{ + return m_bodyCount; +} + +inline int32 b2World::GetJointCount() const +{ + return m_jointCount; +} + +inline int32 b2World::GetContactCount() const +{ + return m_contactManager.m_contactCount; +} + +inline void b2World::SetGravity(const b2Vec2& gravity) +{ + m_gravity = gravity; +} + +inline b2Vec2 b2World::GetGravity() const +{ + return m_gravity; +} + +inline bool b2World::IsLocked() const +{ + return (m_flags & e_locked) == e_locked; +} + +inline void b2World::SetAutoClearForces(bool flag) +{ + if (flag) + { + m_flags |= e_clearForces; + } + else + { + m_flags &= ~e_clearForces; + } +} + +/// Get the flag that controls automatic clearing of forces after each time step. +inline bool b2World::GetAutoClearForces() const +{ + return (m_flags & e_clearForces) == e_clearForces; +} + +inline const b2ContactManager& b2World::GetContactManager() const +{ + return m_contactManager; +} + +inline const b2Profile& b2World::GetProfile() const +{ + return m_profile; +} + +#endif diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.cpp b/external/Box2D/Dynamics/b2WorldCallbacks.cpp new file mode 100644 index 0000000000..48ad0cc46a --- /dev/null +++ b/external/Box2D/Dynamics/b2WorldCallbacks.cpp @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +// Return true if contact calculations should be performed between these two shapes. +// If you implement your own collision filter you may want to build from this implementation. +bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) +{ + const b2Filter& filterA = fixtureA->GetFilterData(); + const b2Filter& filterB = fixtureB->GetFilterData(); + + if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) + { + return filterA.groupIndex > 0; + } + + bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; + return collide; +} diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.h b/external/Box2D/Dynamics/b2WorldCallbacks.h new file mode 100644 index 0000000000..86c04e3e32 --- /dev/null +++ b/external/Box2D/Dynamics/b2WorldCallbacks.h @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_WORLD_CALLBACKS_H +#define B2_WORLD_CALLBACKS_H + +#include + +struct b2Vec2; +struct b2Transform; +class b2Fixture; +class b2Body; +class b2Joint; +class b2Contact; +struct b2ContactResult; +struct b2Manifold; + +/// Joints and fixtures are destroyed when their associated +/// body is destroyed. Implement this listener so that you +/// may nullify references to these joints and shapes. +class b2DestructionListener +{ +public: + virtual ~b2DestructionListener() {} + + /// Called when any joint is about to be destroyed due + /// to the destruction of one of its attached bodies. + virtual void SayGoodbye(b2Joint* joint) = 0; + + /// Called when any fixture is about to be destroyed due + /// to the destruction of its parent body. + virtual void SayGoodbye(b2Fixture* fixture) = 0; +}; + +/// Implement this class to provide collision filtering. In other words, you can implement +/// this class if you want finer control over contact creation. +class b2ContactFilter +{ +public: + virtual ~b2ContactFilter() {} + + /// Return true if contact calculations should be performed between these two shapes. + /// @warning for performance reasons this is only called when the AABBs begin to overlap. + virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); +}; + +/// Contact impulses for reporting. Impulses are used instead of forces because +/// sub-step forces may approach infinity for rigid body collisions. These +/// match up one-to-one with the contact points in b2Manifold. +struct b2ContactImpulse +{ + float32 normalImpulses[b2_maxManifoldPoints]; + float32 tangentImpulses[b2_maxManifoldPoints]; + int32 count; +}; + +/// Implement this class to get contact information. You can use these results for +/// things like sounds and game logic. You can also get contact results by +/// traversing the contact lists after the time step. However, you might miss +/// some contacts because continuous physics leads to sub-stepping. +/// Additionally you may receive multiple callbacks for the same contact in a +/// single time step. +/// You should strive to make your callbacks efficient because there may be +/// many callbacks per time step. +/// @warning You cannot create/destroy Box2D entities inside these callbacks. +class b2ContactListener +{ +public: + virtual ~b2ContactListener() {} + + /// Called when two fixtures begin to touch. + virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } + + /// Called when two fixtures cease to touch. + virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } + + /// This is called after a contact is updated. This allows you to inspect a + /// contact before it goes to the solver. If you are careful, you can modify the + /// contact manifold (e.g. disable contact). + /// A copy of the old manifold is provided so that you can detect changes. + /// Note: this is called only for awake bodies. + /// Note: this is called even when the number of contact points is zero. + /// Note: this is not called for sensors. + /// Note: if you set the number of contact points to zero, you will not + /// get an EndContact callback. However, you may get a BeginContact callback + /// the next step. + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + B2_NOT_USED(contact); + B2_NOT_USED(oldManifold); + } + + /// This lets you inspect a contact after the solver is finished. This is useful + /// for inspecting impulses. + /// Note: the contact manifold does not include time of impact impulses, which can be + /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly + /// in a separate data structure. + /// Note: this is only called for contacts that are touching, solid, and awake. + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } +}; + +/// Callback class for AABB queries. +/// See b2World::Query +class b2QueryCallback +{ +public: + virtual ~b2QueryCallback() {} + + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + virtual bool ReportFixture(b2Fixture* fixture) = 0; +}; + +/// Callback class for ray casts. +/// See b2World::RayCast +class b2RayCastCallback +{ +public: + virtual ~b2RayCastCallback() {} + + /// Called for each fixture found in the query. You control how the ray cast + /// proceeds by returning a float: + /// return -1: ignore this fixture and continue + /// return 0: terminate the ray cast + /// return fraction: clip the ray to this point + /// return 1: don't clip the ray and continue + /// @param fixture the fixture hit by the ray + /// @param point the point of initial intersection + /// @param normal the normal vector at the point of intersection + /// @return -1 to filter, 0 to terminate, fraction to clip the ray for + /// closest hit, 1 to continue + virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float32 fraction) = 0; +}; + +#endif diff --git a/external/Box2D/Rope/b2Rope.cpp b/external/Box2D/Rope/b2Rope.cpp new file mode 100644 index 0000000000..9bf671aec9 --- /dev/null +++ b/external/Box2D/Rope/b2Rope.cpp @@ -0,0 +1,259 @@ +/* +* Copyright (c) 2011 Erin Catto http://box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include + +b2Rope::b2Rope() +{ + m_count = 0; + m_ps = NULL; + m_p0s = NULL; + m_vs = NULL; + m_ims = NULL; + m_Ls = NULL; + m_as = NULL; + m_gravity.SetZero(); + m_k2 = 1.0f; + m_k3 = 0.1f; +} + +b2Rope::~b2Rope() +{ + b2Free(m_ps); + b2Free(m_p0s); + b2Free(m_vs); + b2Free(m_ims); + b2Free(m_Ls); + b2Free(m_as); +} + +void b2Rope::Initialize(const b2RopeDef* def) +{ + b2Assert(def->count >= 3); + m_count = def->count; + m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); + + for (int32 i = 0; i < m_count; ++i) + { + m_ps[i] = def->vertices[i]; + m_p0s[i] = def->vertices[i]; + m_vs[i].SetZero(); + + float32 m = def->masses[i]; + if (m > 0.0f) + { + m_ims[i] = 1.0f / m; + } + else + { + m_ims[i] = 0.0f; + } + } + + int32 count2 = m_count - 1; + int32 count3 = m_count - 2; + m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); + m_as = (float32*)b2Alloc(count3 * sizeof(float32)); + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i+1]; + m_Ls[i] = b2Distance(p1, p2); + } + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + m_as[i] = b2Atan2(a, b); + } + + m_gravity = def->gravity; + m_damping = def->damping; + m_k2 = def->k2; + m_k3 = def->k3; +} + +void b2Rope::Step(float32 h, int32 iterations) +{ + if (h == 0.0) + { + return; + } + + float32 d = expf(- h * m_damping); + + for (int32 i = 0; i < m_count; ++i) + { + m_p0s[i] = m_ps[i]; + if (m_ims[i] > 0.0f) + { + m_vs[i] += h * m_gravity; + } + m_vs[i] *= d; + m_ps[i] += h * m_vs[i]; + + } + + for (int32 i = 0; i < iterations; ++i) + { + SolveC2(); + SolveC3(); + SolveC2(); + } + + float32 inv_h = 1.0f / h; + for (int32 i = 0; i < m_count; ++i) + { + m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); + } +} + +void b2Rope::SolveC2() +{ + int32 count2 = m_count - 1; + + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + + b2Vec2 d = p2 - p1; + float32 L = d.Normalize(); + + float32 im1 = m_ims[i]; + float32 im2 = m_ims[i + 1]; + + if (im1 + im2 == 0.0f) + { + continue; + } + + float32 s1 = im1 / (im1 + im2); + float32 s2 = im2 / (im1 + im2); + + p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; + p2 += m_k2 * s2 * (m_Ls[i] - L) * d; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + } +} + +void b2Rope::SetAngle(float32 angle) +{ + int32 count3 = m_count - 2; + for (int32 i = 0; i < count3; ++i) + { + m_as[i] = angle; + } +} + +void b2Rope::SolveC3() +{ + int32 count3 = m_count - 2; + + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; + + float32 m1 = m_ims[i]; + float32 m2 = m_ims[i + 1]; + float32 m3 = m_ims[i + 2]; + + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; + + float32 L1sqr = d1.LengthSquared(); + float32 L2sqr = d2.LengthSquared(); + + if (L1sqr * L2sqr == 0.0f) + { + continue; + } + + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); + + float32 angle = b2Atan2(a, b); + + b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); + b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); + + b2Vec2 J1 = -Jd1; + b2Vec2 J2 = Jd1 - Jd2; + b2Vec2 J3 = Jd2; + + float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); + if (mass == 0.0f) + { + continue; + } + + mass = 1.0f / mass; + + float32 C = angle - m_as[i]; + + while (C > b2_pi) + { + angle -= 2 * b2_pi; + C = angle - m_as[i]; + } + + while (C < -b2_pi) + { + angle += 2.0f * b2_pi; + C = angle - m_as[i]; + } + + float32 impulse = - m_k3 * mass * C; + + p1 += (m1 * impulse) * J1; + p2 += (m2 * impulse) * J2; + p3 += (m3 * impulse) * J3; + + m_ps[i] = p1; + m_ps[i + 1] = p2; + m_ps[i + 2] = p3; + } +} + +void b2Rope::Draw(b2Draw* draw) const +{ + b2Color c(0.4f, 0.5f, 0.7f); + + for (int32 i = 0; i < m_count - 1; ++i) + { + draw->DrawSegment(m_ps[i], m_ps[i+1], c); + } +} diff --git a/external/Box2D/Rope/b2Rope.h b/external/Box2D/Rope/b2Rope.h new file mode 100644 index 0000000000..b981dfd6c5 --- /dev/null +++ b/external/Box2D/Rope/b2Rope.h @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_ROPE_H +#define B2_ROPE_H + +#include + +class b2Draw; + +/// +struct b2RopeDef +{ + b2RopeDef() + { + vertices = NULL; + count = 0; + masses = NULL; + gravity.SetZero(); + damping = 0.1f; + k2 = 0.9f; + k3 = 0.1f; + } + + /// + b2Vec2* vertices; + + /// + int32 count; + + /// + float32* masses; + + /// + b2Vec2 gravity; + + /// + float32 damping; + + /// Stretching stiffness + float32 k2; + + /// Bending stiffness. Values above 0.5 can make the simulation blow up. + float32 k3; +}; + +/// +class b2Rope +{ +public: + b2Rope(); + ~b2Rope(); + + /// + void Initialize(const b2RopeDef* def); + + /// + void Step(float32 timeStep, int32 iterations); + + /// + int32 GetVertexCount() const + { + return m_count; + } + + /// + const b2Vec2* GetVertices() const + { + return m_ps; + } + + /// + void Draw(b2Draw* draw) const; + + /// + void SetAngle(float32 angle); + +private: + + void SolveC2(); + void SolveC3(); + + int32 m_count; + b2Vec2* m_ps; + b2Vec2* m_p0s; + b2Vec2* m_vs; + + float32* m_ims; + + float32* m_Ls; + float32* m_as; + + b2Vec2 m_gravity; + float32 m_damping; + + float32 m_k2; + float32 m_k3; +}; + +#endif diff --git a/external/Box2D/proj.linux/.cproject b/external/Box2D/proj.linux/.cproject new file mode 100644 index 0000000000..5aa092cac3 --- /dev/null +++ b/external/Box2D/proj.linux/.cproject @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/Box2D/proj.linux/.project b/external/Box2D/proj.linux/.project new file mode 100644 index 0000000000..164d50f52a --- /dev/null +++ b/external/Box2D/proj.linux/.project @@ -0,0 +1,110 @@ + + + libBox2D + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:/libBox2D/Debug} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + Box2D.h + 1 + PARENT-1-PROJECT_LOC/Box2D.h + + + Collision + 2 + PARENT-1-PROJECT_LOC/Collision + + + Common + 2 + PARENT-1-PROJECT_LOC/Common + + + Dynamics + 2 + PARENT-1-PROJECT_LOC/Dynamics + + + Rope + 2 + PARENT-1-PROJECT_LOC/Rope + + + diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile new file mode 100644 index 0000000000..e430bc9883 --- /dev/null +++ b/external/Box2D/proj.linux/Makefile @@ -0,0 +1,72 @@ +TARGET = libbox2d.a + +SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ +../Collision/Shapes/b2CircleShape.cpp \ +../Collision/Shapes/b2EdgeShape.cpp \ +../Collision/Shapes/b2PolygonShape.cpp \ +../Collision/b2BroadPhase.cpp \ +../Collision/b2CollideCircle.cpp \ +../Collision/b2CollideEdge.cpp \ +../Collision/b2CollidePolygon.cpp \ +../Collision/b2Collision.cpp \ +../Collision/b2Distance.cpp \ +../Collision/b2DynamicTree.cpp \ +../Collision/b2TimeOfImpact.cpp \ +../Common/b2BlockAllocator.cpp \ +../Common/b2Draw.cpp \ +../Common/b2Math.cpp \ +../Common/b2Settings.cpp \ +../Common/b2StackAllocator.cpp \ +../Common/b2Timer.cpp \ +../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +../Dynamics/Contacts/b2CircleContact.cpp \ +../Dynamics/Contacts/b2Contact.cpp \ +../Dynamics/Contacts/b2ContactSolver.cpp \ +../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +../Dynamics/Contacts/b2PolygonContact.cpp \ +../Dynamics/Joints/b2DistanceJoint.cpp \ +../Dynamics/Joints/b2FrictionJoint.cpp \ +../Dynamics/Joints/b2GearJoint.cpp \ +../Dynamics/Joints/b2Joint.cpp \ +../Dynamics/Joints/b2MouseJoint.cpp \ +../Dynamics/Joints/b2PrismaticJoint.cpp \ +../Dynamics/Joints/b2PulleyJoint.cpp \ +../Dynamics/Joints/b2RevoluteJoint.cpp \ +../Dynamics/Joints/b2RopeJoint.cpp \ +../Dynamics/Joints/b2WeldJoint.cpp \ +../Dynamics/Joints/b2WheelJoint.cpp \ +../Dynamics/b2Body.cpp \ +../Dynamics/b2ContactManager.cpp \ +../Dynamics/b2Fixture.cpp \ +../Dynamics/b2Island.cpp \ +../Dynamics/b2World.cpp \ +../Dynamics/b2WorldCallbacks.cpp \ +../Rope/b2Rope.cpp + +include ../../../cocos2dx/proj.linux/cocos2dx.mk + +INCLUDES = -I../.. + +# Cocos2d is not responsible for warnings in external projects +CXXFLAGS += -w + +ifeq ($(DEBUG), 1) +DEFINES = -D_DEBUG +else +DEFINES = +endif + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) + +$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/box2d.prf b/external/Box2D/proj.linux/box2d.prf new file mode 100644 index 0000000000..434ad88406 --- /dev/null +++ b/external/Box2D/proj.linux/box2d.prf @@ -0,0 +1,19 @@ +################################################################################ +# Do not include this file in your project: see cocos2dx.pri. +################################################################################ + +linux { + # We will compile box2d on demand using Makefile. + build_box2d.name = Build box2d static library + build_box2d.input = $$PWD/Makefile + build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a + build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a + build_box2d.CONFIG = no_link target_predeps + build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS + + QMAKE_EXTRA_COMPILERS += build_box2d + QMAKE_EXTRA_TARGETS += build_box2d + + PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a + LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic +} diff --git a/external/Box2D/proj.win32/Box2D.vcxproj b/external/Box2D/proj.win32/Box2D.vcxproj new file mode 100644 index 0000000000..cd4bd2086c --- /dev/null +++ b/external/Box2D/proj.win32/Box2D.vcxproj @@ -0,0 +1,194 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + libBox2D + {929480E7-23C0-4DF6-8456-096D71547116} + Box2D.win32 + Win32Proj + + + + StaticLibrary + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + AllRules.ruleset + + + AllRules.ruleset + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + + Disabled + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + true + + + $(OutDir)$(ProjectName).lib + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;../../;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + true + + + $(OutDir)$(ProjectName).lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/external/Box2D/proj.win32/Box2D.vcxproj.filters b/external/Box2D/proj.win32/Box2D.vcxproj.filters new file mode 100644 index 0000000000..e810cbb0cf --- /dev/null +++ b/external/Box2D/proj.win32/Box2D.vcxproj.filters @@ -0,0 +1,301 @@ + + + + + {bdf099c5-cc32-468b-b53f-ec010d7f823f} + + + {92792f88-4e5c-46ee-8d87-002f3b2297ae} + + + {f41a6fa6-5ac1-4514-9ac0-6f3a38f35b4d} + + + {0b56913a-34b7-410a-b386-869d6f7a20be} + + + {f0e7b230-79cc-49b8-9ed7-9dbfa062f2a4} + + + {932f2008-afbe-42f5-993d-a1df0ec67756} + + + {f8937e09-93a4-49fa-8f3e-dfc36da764df} + + + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Rope + + + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Collision\Shapes + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Common + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Contacts + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Dynamics\Joints + + + Rope + + + + \ No newline at end of file diff --git a/external/Box2D/proj.win32/Box2D.vcxproj.user b/external/Box2D/proj.win32/Box2D.vcxproj.user new file mode 100644 index 0000000000..ace9a86acb --- /dev/null +++ b/external/Box2D/proj.win32/Box2D.vcxproj.user @@ -0,0 +1,3 @@ + + + \ No newline at end of file From 7de6646213901c3d887923e1969cb0630f4e028e Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 12 Oct 2013 14:56:40 +0800 Subject: [PATCH 124/557] Don't ignore (D|d)ebugXXX folders or files. And move scripting/javascript/bindings/js to 'scripting/javascript/script/' folder. --- .gitignore | 4 ++-- .../{bindings/js => script}/debugger/DevToolsUtils.js | 0 .../javascript/{bindings/js => script}/debugger/README.md | 0 .../{bindings/js => script}/debugger/actors/root.js | 0 .../{bindings/js => script}/debugger/actors/script.js | 0 .../{bindings/js => script}/debugger/core/promise.js | 0 .../javascript/{bindings/js => script}/debugger/main.js | 0 .../javascript/{bindings/js => script}/debugger/transport.js | 0 cocos/scripting/javascript/{bindings/js => script}/jsb.js | 0 .../javascript/{bindings/js => script}/jsb_chipmunk.js | 0 .../{bindings/js => script}/jsb_chipmunk_constants.js | 0 .../javascript/{bindings/js => script}/jsb_cocos2d.js | 0 .../{bindings/js => script}/jsb_cocos2d_constants.js | 0 .../{bindings/js => script}/jsb_cocos2d_extension.js | 0 .../javascript/{bindings/js => script}/jsb_cocosbuilder.js | 0 .../javascript/{bindings/js => script}/jsb_debugger.js | 0 .../javascript/{bindings/js => script}/jsb_deprecated.js | 0 .../javascript/{bindings/js => script}/jsb_opengl.js | 0 .../{bindings/js => script}/jsb_opengl_constants.js | 0 cocos/scripting/javascript/{bindings/js => script}/jsb_sys.js | 0 20 files changed, 2 insertions(+), 2 deletions(-) rename cocos/scripting/javascript/{bindings/js => script}/debugger/DevToolsUtils.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/README.md (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/actors/root.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/actors/script.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/core/promise.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/main.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/debugger/transport.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_chipmunk.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_chipmunk_constants.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_cocos2d.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_cocos2d_constants.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_cocos2d_extension.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_cocosbuilder.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_debugger.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_deprecated.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_opengl.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_opengl_constants.js (100%) rename cocos/scripting/javascript/{bindings/js => script}/jsb_sys.js (100%) diff --git a/.gitignore b/.gitignore index 14845a8164..d6bae12eb7 100644 --- a/.gitignore +++ b/.gitignore @@ -21,11 +21,11 @@ Thumbs.db *.ilk *.log [Bb]in -[Dd]ebug*/ +[Dd]ebug/ *.sbr *.sdf obj/ -[Rr]elease*/ +[Rr]elease/ _ReSharper*/ [Tt]est[Rr]esult* ipch/ diff --git a/cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js b/cocos/scripting/javascript/script/debugger/DevToolsUtils.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/DevToolsUtils.js rename to cocos/scripting/javascript/script/debugger/DevToolsUtils.js diff --git a/cocos/scripting/javascript/bindings/js/debugger/README.md b/cocos/scripting/javascript/script/debugger/README.md similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/README.md rename to cocos/scripting/javascript/script/debugger/README.md diff --git a/cocos/scripting/javascript/bindings/js/debugger/actors/root.js b/cocos/scripting/javascript/script/debugger/actors/root.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/actors/root.js rename to cocos/scripting/javascript/script/debugger/actors/root.js diff --git a/cocos/scripting/javascript/bindings/js/debugger/actors/script.js b/cocos/scripting/javascript/script/debugger/actors/script.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/actors/script.js rename to cocos/scripting/javascript/script/debugger/actors/script.js diff --git a/cocos/scripting/javascript/bindings/js/debugger/core/promise.js b/cocos/scripting/javascript/script/debugger/core/promise.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/core/promise.js rename to cocos/scripting/javascript/script/debugger/core/promise.js diff --git a/cocos/scripting/javascript/bindings/js/debugger/main.js b/cocos/scripting/javascript/script/debugger/main.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/main.js rename to cocos/scripting/javascript/script/debugger/main.js diff --git a/cocos/scripting/javascript/bindings/js/debugger/transport.js b/cocos/scripting/javascript/script/debugger/transport.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/debugger/transport.js rename to cocos/scripting/javascript/script/debugger/transport.js diff --git a/cocos/scripting/javascript/bindings/js/jsb.js b/cocos/scripting/javascript/script/jsb.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb.js rename to cocos/scripting/javascript/script/jsb.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_chipmunk.js b/cocos/scripting/javascript/script/jsb_chipmunk.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_chipmunk.js rename to cocos/scripting/javascript/script/jsb_chipmunk.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_chipmunk_constants.js b/cocos/scripting/javascript/script/jsb_chipmunk_constants.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_chipmunk_constants.js rename to cocos/scripting/javascript/script/jsb_chipmunk_constants.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_cocos2d.js rename to cocos/scripting/javascript/script/jsb_cocos2d.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_cocos2d_constants.js b/cocos/scripting/javascript/script/jsb_cocos2d_constants.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_cocos2d_constants.js rename to cocos/scripting/javascript/script/jsb_cocos2d_constants.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_cocos2d_extension.js b/cocos/scripting/javascript/script/jsb_cocos2d_extension.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_cocos2d_extension.js rename to cocos/scripting/javascript/script/jsb_cocos2d_extension.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_cocosbuilder.js b/cocos/scripting/javascript/script/jsb_cocosbuilder.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_cocosbuilder.js rename to cocos/scripting/javascript/script/jsb_cocosbuilder.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_debugger.js b/cocos/scripting/javascript/script/jsb_debugger.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_debugger.js rename to cocos/scripting/javascript/script/jsb_debugger.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_deprecated.js b/cocos/scripting/javascript/script/jsb_deprecated.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_deprecated.js rename to cocos/scripting/javascript/script/jsb_deprecated.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_opengl.js b/cocos/scripting/javascript/script/jsb_opengl.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_opengl.js rename to cocos/scripting/javascript/script/jsb_opengl.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_opengl_constants.js b/cocos/scripting/javascript/script/jsb_opengl_constants.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_opengl_constants.js rename to cocos/scripting/javascript/script/jsb_opengl_constants.js diff --git a/cocos/scripting/javascript/bindings/js/jsb_sys.js b/cocos/scripting/javascript/script/jsb_sys.js similarity index 100% rename from cocos/scripting/javascript/bindings/js/jsb_sys.js rename to cocos/scripting/javascript/script/jsb_sys.js From f6275667bfbb3990f8728a6d6113ad60b9d1a220 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 12 Oct 2013 15:02:28 +0800 Subject: [PATCH 125/557] Removing unused ios projects. --- .../bindings/proj.ios/jsbindings-Prefix.pch | 7 - .../jsbindings.xcodeproj/project.pbxproj | 673 ------------------ .../bindings/proj.mac/jsbindings-Prefix.pch | 7 - .../jsbindings.xcodeproj/project.pbxproj | 651 ----------------- .../luabindings.xcodeproj/project.pbxproj | 453 ------------ .../HelloLua.xcodeproj/project.pbxproj | 491 ------------- .../TestLua.xcodeproj/project.pbxproj | 573 --------------- 7 files changed, 2855 deletions(-) delete mode 100644 cocos/scripting/javascript/bindings/proj.ios/jsbindings-Prefix.pch delete mode 100644 cocos/scripting/javascript/bindings/proj.ios/jsbindings.xcodeproj/project.pbxproj delete mode 100644 cocos/scripting/javascript/bindings/proj.mac/jsbindings-Prefix.pch delete mode 100644 cocos/scripting/javascript/bindings/proj.mac/jsbindings.xcodeproj/project.pbxproj delete mode 100644 cocos/scripting/lua/proj.ios/luabindings.xcodeproj/project.pbxproj delete mode 100644 samples/Lua/HelloLua/proj.ios/HelloLua.xcodeproj/project.pbxproj delete mode 100644 samples/Lua/TestLua/proj.ios/TestLua.xcodeproj/project.pbxproj diff --git a/cocos/scripting/javascript/bindings/proj.ios/jsbindings-Prefix.pch b/cocos/scripting/javascript/bindings/proj.ios/jsbindings-Prefix.pch deleted file mode 100644 index af8c4a19d5..0000000000 --- a/cocos/scripting/javascript/bindings/proj.ios/jsbindings-Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'jsbindings' target in the 'jsbindings' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/cocos/scripting/javascript/bindings/proj.ios/jsbindings.xcodeproj/project.pbxproj b/cocos/scripting/javascript/bindings/proj.ios/jsbindings.xcodeproj/project.pbxproj deleted file mode 100644 index cb9d02ae01..0000000000 --- a/cocos/scripting/javascript/bindings/proj.ios/jsbindings.xcodeproj/project.pbxproj +++ /dev/null @@ -1,673 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1A0C0E8B1778088700838530 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A0C0E8A1778088700838530 /* Foundation.framework */; }; - 1A0C0EDA1778095000838530 /* cocos2d_specifics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */; }; - 1A0C0EDB1778095000838530 /* cocosjs_manual_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */; }; - 1A0C0EDC1778095000838530 /* jsb_cocos2dx_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */; }; - 1A0C0EEC1778095000838530 /* js_bindings_ccbreader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */; }; - 1A0C0EED1778095000838530 /* js_bindings_chipmunk_auto_classes.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */; }; - 1A0C0EEE1778095000838530 /* js_bindings_chipmunk_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */; }; - 1A0C0EEF1778095000838530 /* js_bindings_chipmunk_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */; }; - 1A0C0EF01778095000838530 /* js_bindings_chipmunk_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */; }; - 1A0C0EF11778095000838530 /* js_bindings_core.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */; }; - 1A0C0EF21778095000838530 /* js_bindings_opengl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */; }; - 1A0C0EF31778095000838530 /* js_bindings_system_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */; }; - 1A0C0EF41778095000838530 /* js_bindings_system_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */; }; - 1A0C0EF51778095000838530 /* js_manual_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */; }; - 1A0C0EF61778095000838530 /* jsb_cocos2dx_extension_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */; }; - 1A0C0EF71778095000838530 /* jsb_opengl_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */; }; - 1A0C0EF81778095000838530 /* jsb_opengl_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */; }; - 1A0C0EF91778095000838530 /* jsb_opengl_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */; }; - 1A0C0EFA1778095000838530 /* jsb_websocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED31778095000838530 /* jsb_websocket.cpp */; }; - 1A0C0EFB1778095000838530 /* ScriptingCore.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED51778095000838530 /* ScriptingCore.cpp */; }; - 1A0C0EFC1778095000838530 /* XMLHTTPRequest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */; }; - 1A0C0F4917780A9700838530 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A0C0F4817780A9700838530 /* libjs_static.a */; }; - 1A6E46D51778162E0055514D /* jsb_cocos2dx_extension_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 1A0C0E851778088700838530 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 16; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1A0C0E871778088700838530 /* libjsbindings.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libjsbindings.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A0C0E8A1778088700838530 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocos2d_specifics.cpp; path = ../cocos2d_specifics.cpp; sourceTree = ""; }; - 1A0C0E9A1778095000838530 /* cocos2d_specifics.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = cocos2d_specifics.hpp; path = ../cocos2d_specifics.hpp; sourceTree = ""; }; - 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocosjs_manual_conversions.cpp; path = ../cocosjs_manual_conversions.cpp; sourceTree = ""; }; - 1A0C0E9C1778095000838530 /* cocosjs_manual_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cocosjs_manual_conversions.h; path = ../cocosjs_manual_conversions.h; sourceTree = ""; }; - 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_auto.cpp; sourceTree = ""; }; - 1A0C0E9F1778095000838530 /* jsb_cocos2dx_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_auto.hpp; sourceTree = ""; }; - 1A0C0EA01778095000838530 /* jsb_cocos2dx_auto_api.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2dx_auto_api.js; sourceTree = ""; }; - 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_extension_auto.cpp; sourceTree = ""; }; - 1A0C0EA21778095000838530 /* jsb_cocos2dx_extension_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_extension_auto.hpp; sourceTree = ""; }; - 1A0C0EA31778095000838530 /* jsb_cocos2dx_extension_auto_api.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2dx_extension_auto_api.js; sourceTree = ""; }; - 1A0C0EA41778095000838530 /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = ""; }; - 1A0C0EA61778095000838530 /* jsb.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb.js; sourceTree = ""; }; - 1A0C0EA71778095000838530 /* jsb_chipmunk.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_chipmunk.js; sourceTree = ""; }; - 1A0C0EA81778095000838530 /* jsb_chipmunk_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_chipmunk_constants.js; sourceTree = ""; }; - 1A0C0EA91778095000838530 /* jsb_cocos2d.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d.js; sourceTree = ""; }; - 1A0C0EAA1778095000838530 /* jsb_cocos2d_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d_constants.js; sourceTree = ""; }; - 1A0C0EAB1778095000838530 /* jsb_cocos2d_extension.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d_extension.js; sourceTree = ""; }; - 1A0C0EAC1778095000838530 /* jsb_cocosbuilder.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocosbuilder.js; sourceTree = ""; }; - 1A0C0EAD1778095000838530 /* jsb_debugger.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_debugger.js; sourceTree = ""; }; - 1A0C0EAE1778095000838530 /* jsb_opengl.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_opengl.js; sourceTree = ""; }; - 1A0C0EAF1778095000838530 /* jsb_opengl_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_opengl_constants.js; sourceTree = ""; }; - 1A0C0EB01778095000838530 /* jsb_sys.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_sys.js; sourceTree = ""; }; - 1A0C0EB11778095000838530 /* main.debug.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = main.debug.js; sourceTree = ""; }; - 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_ccbreader.cpp; path = ../js_bindings_ccbreader.cpp; sourceTree = ""; }; - 1A0C0EB31778095000838530 /* js_bindings_ccbreader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_ccbreader.h; path = ../js_bindings_ccbreader.h; sourceTree = ""; }; - 1A0C0EB41778095000838530 /* js_bindings_chipmunk_auto_classes_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_auto_classes_registration.h; path = ../js_bindings_chipmunk_auto_classes_registration.h; sourceTree = ""; }; - 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_auto_classes.cpp; path = ../js_bindings_chipmunk_auto_classes.cpp; sourceTree = ""; }; - 1A0C0EB61778095000838530 /* js_bindings_chipmunk_auto_classes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_auto_classes.h; path = ../js_bindings_chipmunk_auto_classes.h; sourceTree = ""; }; - 1A0C0EB71778095000838530 /* js_bindings_chipmunk_functions_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_functions_registration.h; path = ../js_bindings_chipmunk_functions_registration.h; sourceTree = ""; }; - 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_functions.cpp; path = ../js_bindings_chipmunk_functions.cpp; sourceTree = ""; }; - 1A0C0EB91778095000838530 /* js_bindings_chipmunk_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_functions.h; path = ../js_bindings_chipmunk_functions.h; sourceTree = ""; }; - 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_manual.cpp; path = ../js_bindings_chipmunk_manual.cpp; sourceTree = ""; }; - 1A0C0EBB1778095000838530 /* js_bindings_chipmunk_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_manual.h; path = ../js_bindings_chipmunk_manual.h; sourceTree = ""; }; - 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_registration.cpp; path = ../js_bindings_chipmunk_registration.cpp; sourceTree = ""; }; - 1A0C0EBD1778095000838530 /* js_bindings_chipmunk_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_registration.h; path = ../js_bindings_chipmunk_registration.h; sourceTree = ""; }; - 1A0C0EBE1778095000838530 /* js_bindings_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_config.h; path = ../js_bindings_config.h; sourceTree = ""; }; - 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_core.cpp; path = ../js_bindings_core.cpp; sourceTree = ""; }; - 1A0C0EC01778095000838530 /* js_bindings_core.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_core.h; path = ../js_bindings_core.h; sourceTree = ""; }; - 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_opengl.cpp; path = ../js_bindings_opengl.cpp; sourceTree = ""; }; - 1A0C0EC21778095000838530 /* js_bindings_opengl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_opengl.h; path = ../js_bindings_opengl.h; sourceTree = ""; }; - 1A0C0EC31778095000838530 /* js_bindings_system_functions_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_functions_registration.h; path = ../js_bindings_system_functions_registration.h; sourceTree = ""; }; - 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_system_functions.cpp; path = ../js_bindings_system_functions.cpp; sourceTree = ""; }; - 1A0C0EC51778095000838530 /* js_bindings_system_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_functions.h; path = ../js_bindings_system_functions.h; sourceTree = ""; }; - 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_system_registration.cpp; path = ../js_bindings_system_registration.cpp; sourceTree = ""; }; - 1A0C0EC71778095000838530 /* js_bindings_system_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_registration.h; path = ../js_bindings_system_registration.h; sourceTree = ""; }; - 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_manual_conversions.cpp; path = ../js_manual_conversions.cpp; sourceTree = ""; }; - 1A0C0EC91778095000838530 /* js_manual_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_manual_conversions.h; path = ../js_manual_conversions.h; sourceTree = ""; }; - 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_cocos2dx_extension_manual.cpp; path = ../jsb_cocos2dx_extension_manual.cpp; sourceTree = ""; }; - 1A0C0ECB1778095000838530 /* jsb_cocos2dx_extension_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_cocos2dx_extension_manual.h; path = ../jsb_cocos2dx_extension_manual.h; sourceTree = ""; }; - 1A0C0ECC1778095000838530 /* jsb_helper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_helper.h; path = ../jsb_helper.h; sourceTree = ""; }; - 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_functions.cpp; path = ../jsb_opengl_functions.cpp; sourceTree = ""; }; - 1A0C0ECE1778095000838530 /* jsb_opengl_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_functions.h; path = ../jsb_opengl_functions.h; sourceTree = ""; }; - 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_manual.cpp; path = ../jsb_opengl_manual.cpp; sourceTree = ""; }; - 1A0C0ED01778095000838530 /* jsb_opengl_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_manual.h; path = ../jsb_opengl_manual.h; sourceTree = ""; }; - 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_registration.cpp; path = ../jsb_opengl_registration.cpp; sourceTree = ""; }; - 1A0C0ED21778095000838530 /* jsb_opengl_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_registration.h; path = ../jsb_opengl_registration.h; sourceTree = ""; }; - 1A0C0ED31778095000838530 /* jsb_websocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_websocket.cpp; path = ../jsb_websocket.cpp; sourceTree = ""; }; - 1A0C0ED41778095000838530 /* jsb_websocket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_websocket.h; path = ../jsb_websocket.h; sourceTree = ""; }; - 1A0C0ED51778095000838530 /* ScriptingCore.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ScriptingCore.cpp; path = ../ScriptingCore.cpp; sourceTree = ""; }; - 1A0C0ED61778095000838530 /* ScriptingCore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ScriptingCore.h; path = ../ScriptingCore.h; sourceTree = ""; }; - 1A0C0ED71778095000838530 /* spidermonkey_specifics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = spidermonkey_specifics.h; path = ../spidermonkey_specifics.h; sourceTree = ""; }; - 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = XMLHTTPRequest.cpp; path = ../XMLHTTPRequest.cpp; sourceTree = ""; }; - 1A0C0ED91778095000838530 /* XMLHTTPRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = XMLHTTPRequest.h; path = ../XMLHTTPRequest.h; sourceTree = ""; }; - 1A0C0F0017780A9700838530 /* BitArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitArray.h; sourceTree = ""; }; - 1A0C0F0217780A9700838530 /* Root.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Root.h; sourceTree = ""; }; - 1A0C0F0417780A9700838530 /* Anchor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Anchor.h; sourceTree = ""; }; - 1A0C0F0517780A9700838530 /* CharacterEncoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CharacterEncoding.h; sourceTree = ""; }; - 1A0C0F0617780A9700838530 /* GCAPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCAPI.h; sourceTree = ""; }; - 1A0C0F0717780A9700838530 /* HashTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HashTable.h; sourceTree = ""; }; - 1A0C0F0817780A9700838530 /* HeapAPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HeapAPI.h; sourceTree = ""; }; - 1A0C0F0917780A9700838530 /* LegacyIntTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LegacyIntTypes.h; sourceTree = ""; }; - 1A0C0F0A17780A9700838530 /* MemoryMetrics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryMetrics.h; sourceTree = ""; }; - 1A0C0F0B17780A9700838530 /* PropertyKey.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PropertyKey.h; sourceTree = ""; }; - 1A0C0F0C17780A9700838530 /* RequiredDefines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RequiredDefines.h; sourceTree = ""; }; - 1A0C0F0D17780A9700838530 /* TemplateLib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TemplateLib.h; sourceTree = ""; }; - 1A0C0F0E17780A9700838530 /* Utility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Utility.h; sourceTree = ""; }; - 1A0C0F0F17780A9700838530 /* Value.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Value.h; sourceTree = ""; }; - 1A0C0F1017780A9700838530 /* Vector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Vector.h; sourceTree = ""; }; - 1A0C0F1117780A9700838530 /* js-config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "js-config.h"; sourceTree = ""; }; - 1A0C0F1217780A9700838530 /* js.msg */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = js.msg; sourceTree = ""; }; - 1A0C0F1317780A9700838530 /* jsalloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsalloc.h; sourceTree = ""; }; - 1A0C0F1417780A9700838530 /* jsapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsapi.h; sourceTree = ""; }; - 1A0C0F1517780A9700838530 /* jsclass.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsclass.h; sourceTree = ""; }; - 1A0C0F1617780A9700838530 /* jsclist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsclist.h; sourceTree = ""; }; - 1A0C0F1717780A9700838530 /* jscpucfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jscpucfg.h; sourceTree = ""; }; - 1A0C0F1817780A9700838530 /* jsdbgapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsdbgapi.h; sourceTree = ""; }; - 1A0C0F1917780A9700838530 /* jsdhash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsdhash.h; sourceTree = ""; }; - 1A0C0F1A17780A9700838530 /* jsfriendapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsfriendapi.h; sourceTree = ""; }; - 1A0C0F1B17780A9700838530 /* jslock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jslock.h; sourceTree = ""; }; - 1A0C0F1C17780A9700838530 /* json.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = json.h; sourceTree = ""; }; - 1A0C0F1D17780A9700838530 /* jsperf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsperf.h; sourceTree = ""; }; - 1A0C0F1E17780A9700838530 /* jsprf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprf.h; sourceTree = ""; }; - 1A0C0F1F17780A9700838530 /* jsprototypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprototypes.h; sourceTree = ""; }; - 1A0C0F2017780A9700838530 /* jsproxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsproxy.h; sourceTree = ""; }; - 1A0C0F2117780A9700838530 /* jsprvtd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprvtd.h; sourceTree = ""; }; - 1A0C0F2217780A9700838530 /* jspubtd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jspubtd.h; sourceTree = ""; }; - 1A0C0F2317780A9700838530 /* jstypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jstypes.h; sourceTree = ""; }; - 1A0C0F2417780A9700838530 /* jsutil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsutil.h; sourceTree = ""; }; - 1A0C0F2517780A9700838530 /* jsversion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsversion.h; sourceTree = ""; }; - 1A0C0F2617780A9700838530 /* jswrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jswrapper.h; sourceTree = ""; }; - 1A0C0F2817780A9700838530 /* Assertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Assertions.h; sourceTree = ""; }; - 1A0C0F2917780A9700838530 /* Attributes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Attributes.h; sourceTree = ""; }; - 1A0C0F2A17780A9700838530 /* BloomFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BloomFilter.h; sourceTree = ""; }; - 1A0C0F2B17780A9700838530 /* Char16.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Char16.h; sourceTree = ""; }; - 1A0C0F2C17780A9700838530 /* CheckedInt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CheckedInt.h; sourceTree = ""; }; - 1A0C0F2D17780A9700838530 /* Compiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Compiler.h; sourceTree = ""; }; - 1A0C0F2E17780A9700838530 /* Constants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Constants.h; sourceTree = ""; }; - 1A0C0F2F17780A9700838530 /* DebugOnly.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DebugOnly.h; sourceTree = ""; }; - 1A0C0F3017780A9700838530 /* EnumSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EnumSet.h; sourceTree = ""; }; - 1A0C0F3117780A9700838530 /* FloatingPoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FloatingPoint.h; sourceTree = ""; }; - 1A0C0F3217780A9700838530 /* GuardObjects.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GuardObjects.h; sourceTree = ""; }; - 1A0C0F3317780A9700838530 /* HashFunctions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HashFunctions.h; sourceTree = ""; }; - 1A0C0F3417780A9700838530 /* Likely.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Likely.h; sourceTree = ""; }; - 1A0C0F3517780A9700838530 /* LinkedList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkedList.h; sourceTree = ""; }; - 1A0C0F3617780A9700838530 /* MathAlgorithms.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MathAlgorithms.h; sourceTree = ""; }; - 1A0C0F3717780A9700838530 /* MemoryChecking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryChecking.h; sourceTree = ""; }; - 1A0C0F3817780A9700838530 /* MSStdInt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MSStdInt.h; sourceTree = ""; }; - 1A0C0F3917780A9700838530 /* NullPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NullPtr.h; sourceTree = ""; }; - 1A0C0F3A17780A9700838530 /* Range.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Range.h; sourceTree = ""; }; - 1A0C0F3B17780A9700838530 /* RangedPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RangedPtr.h; sourceTree = ""; }; - 1A0C0F3C17780A9700838530 /* RefPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RefPtr.h; sourceTree = ""; }; - 1A0C0F3D17780A9700838530 /* Scoped.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Scoped.h; sourceTree = ""; }; - 1A0C0F3E17780A9700838530 /* SHA1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SHA1.h; sourceTree = ""; }; - 1A0C0F3F17780A9700838530 /* SplayTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SplayTree.h; sourceTree = ""; }; - 1A0C0F4017780A9700838530 /* StandardInteger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StandardInteger.h; sourceTree = ""; }; - 1A0C0F4117780A9700838530 /* ThreadLocal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ThreadLocal.h; sourceTree = ""; }; - 1A0C0F4217780A9700838530 /* TypedEnum.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypedEnum.h; sourceTree = ""; }; - 1A0C0F4317780A9700838530 /* Types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Types.h; sourceTree = ""; }; - 1A0C0F4417780A9700838530 /* TypeTraits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypeTraits.h; sourceTree = ""; }; - 1A0C0F4517780A9700838530 /* Util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Util.h; sourceTree = ""; }; - 1A0C0F4617780A9700838530 /* WeakPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WeakPtr.h; sourceTree = ""; }; - 1A0C0F4817780A9700838530 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libjs_static.a; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 1A0C0E841778088700838530 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A0C0E8B1778088700838530 /* Foundation.framework in Frameworks */, - 1A0C0F4917780A9700838530 /* libjs_static.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 1A0C0E7E1778088700838530 = { - isa = PBXGroup; - children = ( - 1A0C0E981778093E00838530 /* bindings */, - 1A0C0E891778088700838530 /* Frameworks */, - 1A0C0E881778088700838530 /* Products */, - ); - sourceTree = ""; - }; - 1A0C0E881778088700838530 /* Products */ = { - isa = PBXGroup; - children = ( - 1A0C0E871778088700838530 /* libjsbindings.a */, - ); - name = Products; - sourceTree = ""; - }; - 1A0C0E891778088700838530 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1A0C0EFD17780A9700838530 /* spidermonkey-ios */, - 1A0C0E8A1778088700838530 /* Foundation.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 1A0C0E981778093E00838530 /* bindings */ = { - isa = PBXGroup; - children = ( - 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */, - 1A0C0E9A1778095000838530 /* cocos2d_specifics.hpp */, - 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */, - 1A0C0E9C1778095000838530 /* cocosjs_manual_conversions.h */, - 1A0C0E9D1778095000838530 /* generated */, - 1A0C0EA51778095000838530 /* js */, - 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */, - 1A0C0EB31778095000838530 /* js_bindings_ccbreader.h */, - 1A0C0EB41778095000838530 /* js_bindings_chipmunk_auto_classes_registration.h */, - 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */, - 1A0C0EB61778095000838530 /* js_bindings_chipmunk_auto_classes.h */, - 1A0C0EB71778095000838530 /* js_bindings_chipmunk_functions_registration.h */, - 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */, - 1A0C0EB91778095000838530 /* js_bindings_chipmunk_functions.h */, - 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */, - 1A0C0EBB1778095000838530 /* js_bindings_chipmunk_manual.h */, - 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */, - 1A0C0EBD1778095000838530 /* js_bindings_chipmunk_registration.h */, - 1A0C0EBE1778095000838530 /* js_bindings_config.h */, - 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */, - 1A0C0EC01778095000838530 /* js_bindings_core.h */, - 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */, - 1A0C0EC21778095000838530 /* js_bindings_opengl.h */, - 1A0C0EC31778095000838530 /* js_bindings_system_functions_registration.h */, - 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */, - 1A0C0EC51778095000838530 /* js_bindings_system_functions.h */, - 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */, - 1A0C0EC71778095000838530 /* js_bindings_system_registration.h */, - 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */, - 1A0C0EC91778095000838530 /* js_manual_conversions.h */, - 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */, - 1A0C0ECB1778095000838530 /* jsb_cocos2dx_extension_manual.h */, - 1A0C0ECC1778095000838530 /* jsb_helper.h */, - 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */, - 1A0C0ECE1778095000838530 /* jsb_opengl_functions.h */, - 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */, - 1A0C0ED01778095000838530 /* jsb_opengl_manual.h */, - 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */, - 1A0C0ED21778095000838530 /* jsb_opengl_registration.h */, - 1A0C0ED31778095000838530 /* jsb_websocket.cpp */, - 1A0C0ED41778095000838530 /* jsb_websocket.h */, - 1A0C0ED51778095000838530 /* ScriptingCore.cpp */, - 1A0C0ED61778095000838530 /* ScriptingCore.h */, - 1A0C0ED71778095000838530 /* spidermonkey_specifics.h */, - 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */, - 1A0C0ED91778095000838530 /* XMLHTTPRequest.h */, - ); - name = bindings; - sourceTree = ""; - }; - 1A0C0E9D1778095000838530 /* generated */ = { - isa = PBXGroup; - children = ( - 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */, - 1A0C0E9F1778095000838530 /* jsb_cocos2dx_auto.hpp */, - 1A0C0EA01778095000838530 /* jsb_cocos2dx_auto_api.js */, - 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */, - 1A0C0EA21778095000838530 /* jsb_cocos2dx_extension_auto.hpp */, - 1A0C0EA31778095000838530 /* jsb_cocos2dx_extension_auto_api.js */, - 1A0C0EA41778095000838530 /* README */, - ); - name = generated; - path = ../generated; - sourceTree = ""; - }; - 1A0C0EA51778095000838530 /* js */ = { - isa = PBXGroup; - children = ( - 1A0C0EA61778095000838530 /* jsb.js */, - 1A0C0EA71778095000838530 /* jsb_chipmunk.js */, - 1A0C0EA81778095000838530 /* jsb_chipmunk_constants.js */, - 1A0C0EA91778095000838530 /* jsb_cocos2d.js */, - 1A0C0EAA1778095000838530 /* jsb_cocos2d_constants.js */, - 1A0C0EAB1778095000838530 /* jsb_cocos2d_extension.js */, - 1A0C0EAC1778095000838530 /* jsb_cocosbuilder.js */, - 1A0C0EAD1778095000838530 /* jsb_debugger.js */, - 1A0C0EAE1778095000838530 /* jsb_opengl.js */, - 1A0C0EAF1778095000838530 /* jsb_opengl_constants.js */, - 1A0C0EB01778095000838530 /* jsb_sys.js */, - 1A0C0EB11778095000838530 /* main.debug.js */, - ); - name = js; - path = ../js; - sourceTree = ""; - }; - 1A0C0EFD17780A9700838530 /* spidermonkey-ios */ = { - isa = PBXGroup; - children = ( - 1A0C0EFE17780A9700838530 /* include */, - 1A0C0F4717780A9700838530 /* lib */, - ); - name = "spidermonkey-ios"; - path = "../../spidermonkey-ios"; - sourceTree = ""; - }; - 1A0C0EFE17780A9700838530 /* include */ = { - isa = PBXGroup; - children = ( - 1A0C0EFF17780A9700838530 /* ds */, - 1A0C0F0117780A9700838530 /* gc */, - 1A0C0F0317780A9700838530 /* js */, - 1A0C0F1117780A9700838530 /* js-config.h */, - 1A0C0F1217780A9700838530 /* js.msg */, - 1A0C0F1317780A9700838530 /* jsalloc.h */, - 1A0C0F1417780A9700838530 /* jsapi.h */, - 1A0C0F1517780A9700838530 /* jsclass.h */, - 1A0C0F1617780A9700838530 /* jsclist.h */, - 1A0C0F1717780A9700838530 /* jscpucfg.h */, - 1A0C0F1817780A9700838530 /* jsdbgapi.h */, - 1A0C0F1917780A9700838530 /* jsdhash.h */, - 1A0C0F1A17780A9700838530 /* jsfriendapi.h */, - 1A0C0F1B17780A9700838530 /* jslock.h */, - 1A0C0F1C17780A9700838530 /* json.h */, - 1A0C0F1D17780A9700838530 /* jsperf.h */, - 1A0C0F1E17780A9700838530 /* jsprf.h */, - 1A0C0F1F17780A9700838530 /* jsprototypes.h */, - 1A0C0F2017780A9700838530 /* jsproxy.h */, - 1A0C0F2117780A9700838530 /* jsprvtd.h */, - 1A0C0F2217780A9700838530 /* jspubtd.h */, - 1A0C0F2317780A9700838530 /* jstypes.h */, - 1A0C0F2417780A9700838530 /* jsutil.h */, - 1A0C0F2517780A9700838530 /* jsversion.h */, - 1A0C0F2617780A9700838530 /* jswrapper.h */, - 1A0C0F2717780A9700838530 /* mozilla */, - ); - path = include; - sourceTree = ""; - }; - 1A0C0EFF17780A9700838530 /* ds */ = { - isa = PBXGroup; - children = ( - 1A0C0F0017780A9700838530 /* BitArray.h */, - ); - path = ds; - sourceTree = ""; - }; - 1A0C0F0117780A9700838530 /* gc */ = { - isa = PBXGroup; - children = ( - 1A0C0F0217780A9700838530 /* Root.h */, - ); - path = gc; - sourceTree = ""; - }; - 1A0C0F0317780A9700838530 /* js */ = { - isa = PBXGroup; - children = ( - 1A0C0F0417780A9700838530 /* Anchor.h */, - 1A0C0F0517780A9700838530 /* CharacterEncoding.h */, - 1A0C0F0617780A9700838530 /* GCAPI.h */, - 1A0C0F0717780A9700838530 /* HashTable.h */, - 1A0C0F0817780A9700838530 /* HeapAPI.h */, - 1A0C0F0917780A9700838530 /* LegacyIntTypes.h */, - 1A0C0F0A17780A9700838530 /* MemoryMetrics.h */, - 1A0C0F0B17780A9700838530 /* PropertyKey.h */, - 1A0C0F0C17780A9700838530 /* RequiredDefines.h */, - 1A0C0F0D17780A9700838530 /* TemplateLib.h */, - 1A0C0F0E17780A9700838530 /* Utility.h */, - 1A0C0F0F17780A9700838530 /* Value.h */, - 1A0C0F1017780A9700838530 /* Vector.h */, - ); - path = js; - sourceTree = ""; - }; - 1A0C0F2717780A9700838530 /* mozilla */ = { - isa = PBXGroup; - children = ( - 1A0C0F2817780A9700838530 /* Assertions.h */, - 1A0C0F2917780A9700838530 /* Attributes.h */, - 1A0C0F2A17780A9700838530 /* BloomFilter.h */, - 1A0C0F2B17780A9700838530 /* Char16.h */, - 1A0C0F2C17780A9700838530 /* CheckedInt.h */, - 1A0C0F2D17780A9700838530 /* Compiler.h */, - 1A0C0F2E17780A9700838530 /* Constants.h */, - 1A0C0F2F17780A9700838530 /* DebugOnly.h */, - 1A0C0F3017780A9700838530 /* EnumSet.h */, - 1A0C0F3117780A9700838530 /* FloatingPoint.h */, - 1A0C0F3217780A9700838530 /* GuardObjects.h */, - 1A0C0F3317780A9700838530 /* HashFunctions.h */, - 1A0C0F3417780A9700838530 /* Likely.h */, - 1A0C0F3517780A9700838530 /* LinkedList.h */, - 1A0C0F3617780A9700838530 /* MathAlgorithms.h */, - 1A0C0F3717780A9700838530 /* MemoryChecking.h */, - 1A0C0F3817780A9700838530 /* MSStdInt.h */, - 1A0C0F3917780A9700838530 /* NullPtr.h */, - 1A0C0F3A17780A9700838530 /* Range.h */, - 1A0C0F3B17780A9700838530 /* RangedPtr.h */, - 1A0C0F3C17780A9700838530 /* RefPtr.h */, - 1A0C0F3D17780A9700838530 /* Scoped.h */, - 1A0C0F3E17780A9700838530 /* SHA1.h */, - 1A0C0F3F17780A9700838530 /* SplayTree.h */, - 1A0C0F4017780A9700838530 /* StandardInteger.h */, - 1A0C0F4117780A9700838530 /* ThreadLocal.h */, - 1A0C0F4217780A9700838530 /* TypedEnum.h */, - 1A0C0F4317780A9700838530 /* Types.h */, - 1A0C0F4417780A9700838530 /* TypeTraits.h */, - 1A0C0F4517780A9700838530 /* Util.h */, - 1A0C0F4617780A9700838530 /* WeakPtr.h */, - ); - path = mozilla; - sourceTree = ""; - }; - 1A0C0F4717780A9700838530 /* lib */ = { - isa = PBXGroup; - children = ( - 1A0C0F4817780A9700838530 /* libjs_static.a */, - ); - path = lib; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 1A0C0E861778088700838530 /* jsbindings */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1A0C0E951778088700838530 /* Build configuration list for PBXNativeTarget "jsbindings" */; - buildPhases = ( - 1A0C0E831778088700838530 /* Sources */, - 1A0C0E841778088700838530 /* Frameworks */, - 1A0C0E851778088700838530 /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = jsbindings; - productName = jsbindings; - productReference = 1A0C0E871778088700838530 /* libjsbindings.a */; - productType = "com.apple.product-type.library.static"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 1A0C0E7F1778088700838530 /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0460; - }; - buildConfigurationList = 1A0C0E821778088700838530 /* Build configuration list for PBXProject "jsbindings" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 1A0C0E7E1778088700838530; - productRefGroup = 1A0C0E881778088700838530 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1A0C0E861778088700838530 /* jsbindings */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - 1A0C0E831778088700838530 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E46D51778162E0055514D /* jsb_cocos2dx_extension_auto.cpp in Sources */, - 1A0C0EDA1778095000838530 /* cocos2d_specifics.cpp in Sources */, - 1A0C0EDB1778095000838530 /* cocosjs_manual_conversions.cpp in Sources */, - 1A0C0EDC1778095000838530 /* jsb_cocos2dx_auto.cpp in Sources */, - 1A0C0EEC1778095000838530 /* js_bindings_ccbreader.cpp in Sources */, - 1A0C0EED1778095000838530 /* js_bindings_chipmunk_auto_classes.cpp in Sources */, - 1A0C0EEE1778095000838530 /* js_bindings_chipmunk_functions.cpp in Sources */, - 1A0C0EEF1778095000838530 /* js_bindings_chipmunk_manual.cpp in Sources */, - 1A0C0EF01778095000838530 /* js_bindings_chipmunk_registration.cpp in Sources */, - 1A0C0EF11778095000838530 /* js_bindings_core.cpp in Sources */, - 1A0C0EF21778095000838530 /* js_bindings_opengl.cpp in Sources */, - 1A0C0EF31778095000838530 /* js_bindings_system_functions.cpp in Sources */, - 1A0C0EF41778095000838530 /* js_bindings_system_registration.cpp in Sources */, - 1A0C0EF51778095000838530 /* js_manual_conversions.cpp in Sources */, - 1A0C0EF61778095000838530 /* jsb_cocos2dx_extension_manual.cpp in Sources */, - 1A0C0EF71778095000838530 /* jsb_opengl_functions.cpp in Sources */, - 1A0C0EF81778095000838530 /* jsb_opengl_manual.cpp in Sources */, - 1A0C0EF91778095000838530 /* jsb_opengl_registration.cpp in Sources */, - 1A0C0EFA1778095000838530 /* jsb_websocket.cpp in Sources */, - 1A0C0EFB1778095000838530 /* ScriptingCore.cpp in Sources */, - 1A0C0EFC1778095000838530 /* XMLHTTPRequest.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1A0C0E931778088700838530 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 6.1; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 1A0C0E941778088700838530 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 6.1; - SDKROOT = iphoneos; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 1A0C0E961778088700838530 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - DSTROOT = /tmp/jsbindings.dst; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "jsbindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - CC_TARGET_OS_IPHONE, - "COCOS2D_DEBUG=1", - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - "$(inherited)", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../../external/libwebsockets/ios/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../external\"", - "\"$(SRCROOT)/../../../../extensions\"", - "\"$(SRCROOT)/../../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../../extensions/network\"", - "\"$(SRCROOT)/../../../../cocos2dx\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios/Simulation\"", - "\"$(SRCROOT)/../../spidermonkey-ios/include\"", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../spidermonkey-ios/lib\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 1A0C0E971778088700838530 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - DSTROOT = /tmp/jsbindings.dst; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "jsbindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - CC_TARGET_OS_IPHONE, - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../../external/libwebsockets/ios/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../external\"", - "\"$(SRCROOT)/../../../../extensions\"", - "\"$(SRCROOT)/../../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../../extensions/network\"", - "\"$(SRCROOT)/../../../../cocos2dx\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios/Simulation\"", - "\"$(SRCROOT)/../../spidermonkey-ios/include\"", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../spidermonkey-ios/lib\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1A0C0E821778088700838530 /* Build configuration list for PBXProject "jsbindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A0C0E931778088700838530 /* Debug */, - 1A0C0E941778088700838530 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1A0C0E951778088700838530 /* Build configuration list for PBXNativeTarget "jsbindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A0C0E961778088700838530 /* Debug */, - 1A0C0E971778088700838530 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 1A0C0E7F1778088700838530 /* Project object */; -} diff --git a/cocos/scripting/javascript/bindings/proj.mac/jsbindings-Prefix.pch b/cocos/scripting/javascript/bindings/proj.mac/jsbindings-Prefix.pch deleted file mode 100644 index af8c4a19d5..0000000000 --- a/cocos/scripting/javascript/bindings/proj.mac/jsbindings-Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'jsbindings' target in the 'jsbindings' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/cocos/scripting/javascript/bindings/proj.mac/jsbindings.xcodeproj/project.pbxproj b/cocos/scripting/javascript/bindings/proj.mac/jsbindings.xcodeproj/project.pbxproj deleted file mode 100644 index fd51d91ed6..0000000000 --- a/cocos/scripting/javascript/bindings/proj.mac/jsbindings.xcodeproj/project.pbxproj +++ /dev/null @@ -1,651 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1A0C0E8B1778088700838530 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A0C0E8A1778088700838530 /* Foundation.framework */; }; - 1A0C0EDA1778095000838530 /* cocos2d_specifics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */; }; - 1A0C0EDB1778095000838530 /* cocosjs_manual_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */; }; - 1A0C0EDC1778095000838530 /* jsb_cocos2dx_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */; }; - 1A0C0EEC1778095000838530 /* js_bindings_ccbreader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */; }; - 1A0C0EED1778095000838530 /* js_bindings_chipmunk_auto_classes.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */; }; - 1A0C0EEE1778095000838530 /* js_bindings_chipmunk_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */; }; - 1A0C0EEF1778095000838530 /* js_bindings_chipmunk_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */; }; - 1A0C0EF01778095000838530 /* js_bindings_chipmunk_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */; }; - 1A0C0EF11778095000838530 /* js_bindings_core.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */; }; - 1A0C0EF21778095000838530 /* js_bindings_opengl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */; }; - 1A0C0EF31778095000838530 /* js_bindings_system_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */; }; - 1A0C0EF41778095000838530 /* js_bindings_system_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */; }; - 1A0C0EF51778095000838530 /* js_manual_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */; }; - 1A0C0EF61778095000838530 /* jsb_cocos2dx_extension_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */; }; - 1A0C0EF71778095000838530 /* jsb_opengl_functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */; }; - 1A0C0EF81778095000838530 /* jsb_opengl_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */; }; - 1A0C0EF91778095000838530 /* jsb_opengl_registration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */; }; - 1A0C0EFA1778095000838530 /* jsb_websocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED31778095000838530 /* jsb_websocket.cpp */; }; - 1A0C0EFB1778095000838530 /* ScriptingCore.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED51778095000838530 /* ScriptingCore.cpp */; }; - 1A0C0EFC1778095000838530 /* XMLHTTPRequest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */; }; - 1A6E46D51778162E0055514D /* jsb_cocos2dx_extension_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */; }; - A00B437317795C5C00480238 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A00B437217795C5C00480238 /* libjs_static.a */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 1A0C0E851778088700838530 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 16; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1A0C0E871778088700838530 /* libjsbindings.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libjsbindings.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A0C0E8A1778088700838530 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocos2d_specifics.cpp; path = ../cocos2d_specifics.cpp; sourceTree = ""; }; - 1A0C0E9A1778095000838530 /* cocos2d_specifics.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = cocos2d_specifics.hpp; path = ../cocos2d_specifics.hpp; sourceTree = ""; }; - 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocosjs_manual_conversions.cpp; path = ../cocosjs_manual_conversions.cpp; sourceTree = ""; }; - 1A0C0E9C1778095000838530 /* cocosjs_manual_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cocosjs_manual_conversions.h; path = ../cocosjs_manual_conversions.h; sourceTree = ""; }; - 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_auto.cpp; sourceTree = ""; }; - 1A0C0E9F1778095000838530 /* jsb_cocos2dx_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_auto.hpp; sourceTree = ""; }; - 1A0C0EA01778095000838530 /* jsb_cocos2dx_auto_api.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2dx_auto_api.js; sourceTree = ""; }; - 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_extension_auto.cpp; sourceTree = ""; }; - 1A0C0EA21778095000838530 /* jsb_cocos2dx_extension_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_extension_auto.hpp; sourceTree = ""; }; - 1A0C0EA31778095000838530 /* jsb_cocos2dx_extension_auto_api.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2dx_extension_auto_api.js; sourceTree = ""; }; - 1A0C0EA41778095000838530 /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = ""; }; - 1A0C0EA61778095000838530 /* jsb.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb.js; sourceTree = ""; }; - 1A0C0EA71778095000838530 /* jsb_chipmunk.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_chipmunk.js; sourceTree = ""; }; - 1A0C0EA81778095000838530 /* jsb_chipmunk_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_chipmunk_constants.js; sourceTree = ""; }; - 1A0C0EA91778095000838530 /* jsb_cocos2d.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d.js; sourceTree = ""; }; - 1A0C0EAA1778095000838530 /* jsb_cocos2d_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d_constants.js; sourceTree = ""; }; - 1A0C0EAB1778095000838530 /* jsb_cocos2d_extension.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocos2d_extension.js; sourceTree = ""; }; - 1A0C0EAC1778095000838530 /* jsb_cocosbuilder.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_cocosbuilder.js; sourceTree = ""; }; - 1A0C0EAD1778095000838530 /* jsb_debugger.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_debugger.js; sourceTree = ""; }; - 1A0C0EAE1778095000838530 /* jsb_opengl.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_opengl.js; sourceTree = ""; }; - 1A0C0EAF1778095000838530 /* jsb_opengl_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_opengl_constants.js; sourceTree = ""; }; - 1A0C0EB01778095000838530 /* jsb_sys.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = jsb_sys.js; sourceTree = ""; }; - 1A0C0EB11778095000838530 /* main.debug.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = main.debug.js; sourceTree = ""; }; - 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_ccbreader.cpp; path = ../js_bindings_ccbreader.cpp; sourceTree = ""; }; - 1A0C0EB31778095000838530 /* js_bindings_ccbreader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_ccbreader.h; path = ../js_bindings_ccbreader.h; sourceTree = ""; }; - 1A0C0EB41778095000838530 /* js_bindings_chipmunk_auto_classes_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_auto_classes_registration.h; path = ../js_bindings_chipmunk_auto_classes_registration.h; sourceTree = ""; }; - 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_auto_classes.cpp; path = ../js_bindings_chipmunk_auto_classes.cpp; sourceTree = ""; }; - 1A0C0EB61778095000838530 /* js_bindings_chipmunk_auto_classes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_auto_classes.h; path = ../js_bindings_chipmunk_auto_classes.h; sourceTree = ""; }; - 1A0C0EB71778095000838530 /* js_bindings_chipmunk_functions_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_functions_registration.h; path = ../js_bindings_chipmunk_functions_registration.h; sourceTree = ""; }; - 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_functions.cpp; path = ../js_bindings_chipmunk_functions.cpp; sourceTree = ""; }; - 1A0C0EB91778095000838530 /* js_bindings_chipmunk_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_functions.h; path = ../js_bindings_chipmunk_functions.h; sourceTree = ""; }; - 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_manual.cpp; path = ../js_bindings_chipmunk_manual.cpp; sourceTree = ""; }; - 1A0C0EBB1778095000838530 /* js_bindings_chipmunk_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_manual.h; path = ../js_bindings_chipmunk_manual.h; sourceTree = ""; }; - 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_chipmunk_registration.cpp; path = ../js_bindings_chipmunk_registration.cpp; sourceTree = ""; }; - 1A0C0EBD1778095000838530 /* js_bindings_chipmunk_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_chipmunk_registration.h; path = ../js_bindings_chipmunk_registration.h; sourceTree = ""; }; - 1A0C0EBE1778095000838530 /* js_bindings_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_config.h; path = ../js_bindings_config.h; sourceTree = ""; }; - 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_core.cpp; path = ../js_bindings_core.cpp; sourceTree = ""; }; - 1A0C0EC01778095000838530 /* js_bindings_core.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_core.h; path = ../js_bindings_core.h; sourceTree = ""; }; - 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_opengl.cpp; path = ../js_bindings_opengl.cpp; sourceTree = ""; }; - 1A0C0EC21778095000838530 /* js_bindings_opengl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_opengl.h; path = ../js_bindings_opengl.h; sourceTree = ""; }; - 1A0C0EC31778095000838530 /* js_bindings_system_functions_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_functions_registration.h; path = ../js_bindings_system_functions_registration.h; sourceTree = ""; }; - 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_system_functions.cpp; path = ../js_bindings_system_functions.cpp; sourceTree = ""; }; - 1A0C0EC51778095000838530 /* js_bindings_system_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_functions.h; path = ../js_bindings_system_functions.h; sourceTree = ""; }; - 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_bindings_system_registration.cpp; path = ../js_bindings_system_registration.cpp; sourceTree = ""; }; - 1A0C0EC71778095000838530 /* js_bindings_system_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_bindings_system_registration.h; path = ../js_bindings_system_registration.h; sourceTree = ""; }; - 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = js_manual_conversions.cpp; path = ../js_manual_conversions.cpp; sourceTree = ""; }; - 1A0C0EC91778095000838530 /* js_manual_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = js_manual_conversions.h; path = ../js_manual_conversions.h; sourceTree = ""; }; - 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_cocos2dx_extension_manual.cpp; path = ../jsb_cocos2dx_extension_manual.cpp; sourceTree = ""; }; - 1A0C0ECB1778095000838530 /* jsb_cocos2dx_extension_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_cocos2dx_extension_manual.h; path = ../jsb_cocos2dx_extension_manual.h; sourceTree = ""; }; - 1A0C0ECC1778095000838530 /* jsb_helper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_helper.h; path = ../jsb_helper.h; sourceTree = ""; }; - 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_functions.cpp; path = ../jsb_opengl_functions.cpp; sourceTree = ""; }; - 1A0C0ECE1778095000838530 /* jsb_opengl_functions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_functions.h; path = ../jsb_opengl_functions.h; sourceTree = ""; }; - 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_manual.cpp; path = ../jsb_opengl_manual.cpp; sourceTree = ""; }; - 1A0C0ED01778095000838530 /* jsb_opengl_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_manual.h; path = ../jsb_opengl_manual.h; sourceTree = ""; }; - 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_opengl_registration.cpp; path = ../jsb_opengl_registration.cpp; sourceTree = ""; }; - 1A0C0ED21778095000838530 /* jsb_opengl_registration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_opengl_registration.h; path = ../jsb_opengl_registration.h; sourceTree = ""; }; - 1A0C0ED31778095000838530 /* jsb_websocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = jsb_websocket.cpp; path = ../jsb_websocket.cpp; sourceTree = ""; }; - 1A0C0ED41778095000838530 /* jsb_websocket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = jsb_websocket.h; path = ../jsb_websocket.h; sourceTree = ""; }; - 1A0C0ED51778095000838530 /* ScriptingCore.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ScriptingCore.cpp; path = ../ScriptingCore.cpp; sourceTree = ""; }; - 1A0C0ED61778095000838530 /* ScriptingCore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ScriptingCore.h; path = ../ScriptingCore.h; sourceTree = ""; }; - 1A0C0ED71778095000838530 /* spidermonkey_specifics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = spidermonkey_specifics.h; path = ../spidermonkey_specifics.h; sourceTree = ""; }; - 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = XMLHTTPRequest.cpp; path = ../XMLHTTPRequest.cpp; sourceTree = ""; }; - 1A0C0ED91778095000838530 /* XMLHTTPRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = XMLHTTPRequest.h; path = ../XMLHTTPRequest.h; sourceTree = ""; }; - A00B437217795C5C00480238 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libjs_static.a; sourceTree = ""; }; - A05FCAF5177D12D900BE600E /* Anchor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Anchor.h; sourceTree = ""; }; - A05FCAF6177D12D900BE600E /* CallArgs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CallArgs.h; sourceTree = ""; }; - A05FCAF7177D12D900BE600E /* CharacterEncoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CharacterEncoding.h; sourceTree = ""; }; - A05FCAF8177D12D900BE600E /* GCAPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCAPI.h; sourceTree = ""; }; - A05FCAF9177D12D900BE600E /* HashTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HashTable.h; sourceTree = ""; }; - A05FCAFA177D12D900BE600E /* HeapAPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HeapAPI.h; sourceTree = ""; }; - A05FCAFB177D12D900BE600E /* LegacyIntTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LegacyIntTypes.h; sourceTree = ""; }; - A05FCAFC177D12D900BE600E /* MemoryMetrics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryMetrics.h; sourceTree = ""; }; - A05FCAFD177D12D900BE600E /* PropertyKey.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PropertyKey.h; sourceTree = ""; }; - A05FCAFE177D12D900BE600E /* RequiredDefines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RequiredDefines.h; sourceTree = ""; }; - A05FCAFF177D12D900BE600E /* RootingAPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootingAPI.h; sourceTree = ""; }; - A05FCB00177D12D900BE600E /* TemplateLib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TemplateLib.h; sourceTree = ""; }; - A05FCB01177D12D900BE600E /* Utility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Utility.h; sourceTree = ""; }; - A05FCB02177D12D900BE600E /* Value.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Value.h; sourceTree = ""; }; - A05FCB03177D12D900BE600E /* Vector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Vector.h; sourceTree = ""; }; - A05FCB04177D12D900BE600E /* js-config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "js-config.h"; sourceTree = ""; }; - A05FCB05177D12D900BE600E /* js.msg */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = js.msg; sourceTree = ""; }; - A05FCB06177D12D900BE600E /* jsalloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsalloc.h; sourceTree = ""; }; - A05FCB07177D12D900BE600E /* jsapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsapi.h; sourceTree = ""; }; - A05FCB08177D12D900BE600E /* jsclass.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsclass.h; sourceTree = ""; }; - A05FCB09177D12D900BE600E /* jsclist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsclist.h; sourceTree = ""; }; - A05FCB0A177D12D900BE600E /* jscpucfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jscpucfg.h; sourceTree = ""; }; - A05FCB0B177D12D900BE600E /* jsdbgapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsdbgapi.h; sourceTree = ""; }; - A05FCB0C177D12D900BE600E /* jsdhash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsdhash.h; sourceTree = ""; }; - A05FCB0D177D12D900BE600E /* jsfriendapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsfriendapi.h; sourceTree = ""; }; - A05FCB0E177D12D900BE600E /* jslock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jslock.h; sourceTree = ""; }; - A05FCB0F177D12D900BE600E /* json.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = json.h; sourceTree = ""; }; - A05FCB10177D12D900BE600E /* jsperf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsperf.h; sourceTree = ""; }; - A05FCB11177D12D900BE600E /* jsprf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprf.h; sourceTree = ""; }; - A05FCB12177D12D900BE600E /* jsprototypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprototypes.h; sourceTree = ""; }; - A05FCB13177D12D900BE600E /* jsproxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsproxy.h; sourceTree = ""; }; - A05FCB14177D12D900BE600E /* jsprvtd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsprvtd.h; sourceTree = ""; }; - A05FCB15177D12D900BE600E /* jspubtd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jspubtd.h; sourceTree = ""; }; - A05FCB16177D12D900BE600E /* jstypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jstypes.h; sourceTree = ""; }; - A05FCB17177D12D900BE600E /* jsutil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsutil.h; sourceTree = ""; }; - A05FCB18177D12D900BE600E /* jsversion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsversion.h; sourceTree = ""; }; - A05FCB19177D12D900BE600E /* jswrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jswrapper.h; sourceTree = ""; }; - A05FCB1B177D12D900BE600E /* Assertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Assertions.h; sourceTree = ""; }; - A05FCB1C177D12D900BE600E /* Attributes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Attributes.h; sourceTree = ""; }; - A05FCB1D177D12D900BE600E /* BloomFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BloomFilter.h; sourceTree = ""; }; - A05FCB1E177D12D900BE600E /* Char16.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Char16.h; sourceTree = ""; }; - A05FCB1F177D12D900BE600E /* CheckedInt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CheckedInt.h; sourceTree = ""; }; - A05FCB20177D12D900BE600E /* Compiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Compiler.h; sourceTree = ""; }; - A05FCB21177D12D900BE600E /* Constants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Constants.h; sourceTree = ""; }; - A05FCB22177D12D900BE600E /* DebugOnly.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DebugOnly.h; sourceTree = ""; }; - A05FCB23177D12D900BE600E /* EnumSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EnumSet.h; sourceTree = ""; }; - A05FCB24177D12D900BE600E /* FloatingPoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FloatingPoint.h; sourceTree = ""; }; - A05FCB25177D12D900BE600E /* GuardObjects.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GuardObjects.h; sourceTree = ""; }; - A05FCB26177D12D900BE600E /* HashFunctions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HashFunctions.h; sourceTree = ""; }; - A05FCB27177D12D900BE600E /* Likely.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Likely.h; sourceTree = ""; }; - A05FCB28177D12D900BE600E /* LinkedList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkedList.h; sourceTree = ""; }; - A05FCB29177D12D900BE600E /* MathAlgorithms.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MathAlgorithms.h; sourceTree = ""; }; - A05FCB2A177D12D900BE600E /* MemoryChecking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryChecking.h; sourceTree = ""; }; - A05FCB2B177D12D900BE600E /* MSStdInt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MSStdInt.h; sourceTree = ""; }; - A05FCB2C177D12D900BE600E /* NullPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NullPtr.h; sourceTree = ""; }; - A05FCB2D177D12D900BE600E /* Range.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Range.h; sourceTree = ""; }; - A05FCB2E177D12D900BE600E /* RangedPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RangedPtr.h; sourceTree = ""; }; - A05FCB2F177D12D900BE600E /* RefPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RefPtr.h; sourceTree = ""; }; - A05FCB30177D12D900BE600E /* Scoped.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Scoped.h; sourceTree = ""; }; - A05FCB31177D12D900BE600E /* SHA1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SHA1.h; sourceTree = ""; }; - A05FCB32177D12D900BE600E /* SplayTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SplayTree.h; sourceTree = ""; }; - A05FCB33177D12D900BE600E /* StandardInteger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StandardInteger.h; sourceTree = ""; }; - A05FCB34177D12D900BE600E /* ThreadLocal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ThreadLocal.h; sourceTree = ""; }; - A05FCB35177D12D900BE600E /* TypedEnum.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypedEnum.h; sourceTree = ""; }; - A05FCB36177D12D900BE600E /* Types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Types.h; sourceTree = ""; }; - A05FCB37177D12D900BE600E /* TypeTraits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypeTraits.h; sourceTree = ""; }; - A05FCB38177D12D900BE600E /* Util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Util.h; sourceTree = ""; }; - A05FCB39177D12D900BE600E /* WeakPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WeakPtr.h; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 1A0C0E841778088700838530 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A0C0E8B1778088700838530 /* Foundation.framework in Frameworks */, - A00B437317795C5C00480238 /* libjs_static.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 1A0C0E7E1778088700838530 = { - isa = PBXGroup; - children = ( - 1A0C0E981778093E00838530 /* bindings */, - 1A0C0E891778088700838530 /* Frameworks */, - 1A0C0E881778088700838530 /* Products */, - ); - sourceTree = ""; - }; - 1A0C0E881778088700838530 /* Products */ = { - isa = PBXGroup; - children = ( - 1A0C0E871778088700838530 /* libjsbindings.a */, - ); - name = Products; - sourceTree = ""; - }; - 1A0C0E891778088700838530 /* Frameworks */ = { - isa = PBXGroup; - children = ( - A00B432717795C5C00480238 /* spidermonkey-mac */, - 1A0C0E8A1778088700838530 /* Foundation.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 1A0C0E981778093E00838530 /* bindings */ = { - isa = PBXGroup; - children = ( - 1A0C0E991778095000838530 /* cocos2d_specifics.cpp */, - 1A0C0E9A1778095000838530 /* cocos2d_specifics.hpp */, - 1A0C0E9B1778095000838530 /* cocosjs_manual_conversions.cpp */, - 1A0C0E9C1778095000838530 /* cocosjs_manual_conversions.h */, - 1A0C0E9D1778095000838530 /* generated */, - 1A0C0EA51778095000838530 /* js */, - 1A0C0EB21778095000838530 /* js_bindings_ccbreader.cpp */, - 1A0C0EB31778095000838530 /* js_bindings_ccbreader.h */, - 1A0C0EB41778095000838530 /* js_bindings_chipmunk_auto_classes_registration.h */, - 1A0C0EB51778095000838530 /* js_bindings_chipmunk_auto_classes.cpp */, - 1A0C0EB61778095000838530 /* js_bindings_chipmunk_auto_classes.h */, - 1A0C0EB71778095000838530 /* js_bindings_chipmunk_functions_registration.h */, - 1A0C0EB81778095000838530 /* js_bindings_chipmunk_functions.cpp */, - 1A0C0EB91778095000838530 /* js_bindings_chipmunk_functions.h */, - 1A0C0EBA1778095000838530 /* js_bindings_chipmunk_manual.cpp */, - 1A0C0EBB1778095000838530 /* js_bindings_chipmunk_manual.h */, - 1A0C0EBC1778095000838530 /* js_bindings_chipmunk_registration.cpp */, - 1A0C0EBD1778095000838530 /* js_bindings_chipmunk_registration.h */, - 1A0C0EBE1778095000838530 /* js_bindings_config.h */, - 1A0C0EBF1778095000838530 /* js_bindings_core.cpp */, - 1A0C0EC01778095000838530 /* js_bindings_core.h */, - 1A0C0EC11778095000838530 /* js_bindings_opengl.cpp */, - 1A0C0EC21778095000838530 /* js_bindings_opengl.h */, - 1A0C0EC31778095000838530 /* js_bindings_system_functions_registration.h */, - 1A0C0EC41778095000838530 /* js_bindings_system_functions.cpp */, - 1A0C0EC51778095000838530 /* js_bindings_system_functions.h */, - 1A0C0EC61778095000838530 /* js_bindings_system_registration.cpp */, - 1A0C0EC71778095000838530 /* js_bindings_system_registration.h */, - 1A0C0EC81778095000838530 /* js_manual_conversions.cpp */, - 1A0C0EC91778095000838530 /* js_manual_conversions.h */, - 1A0C0ECA1778095000838530 /* jsb_cocos2dx_extension_manual.cpp */, - 1A0C0ECB1778095000838530 /* jsb_cocos2dx_extension_manual.h */, - 1A0C0ECC1778095000838530 /* jsb_helper.h */, - 1A0C0ECD1778095000838530 /* jsb_opengl_functions.cpp */, - 1A0C0ECE1778095000838530 /* jsb_opengl_functions.h */, - 1A0C0ECF1778095000838530 /* jsb_opengl_manual.cpp */, - 1A0C0ED01778095000838530 /* jsb_opengl_manual.h */, - 1A0C0ED11778095000838530 /* jsb_opengl_registration.cpp */, - 1A0C0ED21778095000838530 /* jsb_opengl_registration.h */, - 1A0C0ED31778095000838530 /* jsb_websocket.cpp */, - 1A0C0ED41778095000838530 /* jsb_websocket.h */, - 1A0C0ED51778095000838530 /* ScriptingCore.cpp */, - 1A0C0ED61778095000838530 /* ScriptingCore.h */, - 1A0C0ED71778095000838530 /* spidermonkey_specifics.h */, - 1A0C0ED81778095000838530 /* XMLHTTPRequest.cpp */, - 1A0C0ED91778095000838530 /* XMLHTTPRequest.h */, - ); - name = bindings; - sourceTree = ""; - }; - 1A0C0E9D1778095000838530 /* generated */ = { - isa = PBXGroup; - children = ( - 1A0C0E9E1778095000838530 /* jsb_cocos2dx_auto.cpp */, - 1A0C0E9F1778095000838530 /* jsb_cocos2dx_auto.hpp */, - 1A0C0EA01778095000838530 /* jsb_cocos2dx_auto_api.js */, - 1A0C0EA11778095000838530 /* jsb_cocos2dx_extension_auto.cpp */, - 1A0C0EA21778095000838530 /* jsb_cocos2dx_extension_auto.hpp */, - 1A0C0EA31778095000838530 /* jsb_cocos2dx_extension_auto_api.js */, - 1A0C0EA41778095000838530 /* README */, - ); - name = generated; - path = ../generated; - sourceTree = ""; - }; - 1A0C0EA51778095000838530 /* js */ = { - isa = PBXGroup; - children = ( - 1A0C0EA61778095000838530 /* jsb.js */, - 1A0C0EA71778095000838530 /* jsb_chipmunk.js */, - 1A0C0EA81778095000838530 /* jsb_chipmunk_constants.js */, - 1A0C0EA91778095000838530 /* jsb_cocos2d.js */, - 1A0C0EAA1778095000838530 /* jsb_cocos2d_constants.js */, - 1A0C0EAB1778095000838530 /* jsb_cocos2d_extension.js */, - 1A0C0EAC1778095000838530 /* jsb_cocosbuilder.js */, - 1A0C0EAD1778095000838530 /* jsb_debugger.js */, - 1A0C0EAE1778095000838530 /* jsb_opengl.js */, - 1A0C0EAF1778095000838530 /* jsb_opengl_constants.js */, - 1A0C0EB01778095000838530 /* jsb_sys.js */, - 1A0C0EB11778095000838530 /* main.debug.js */, - ); - name = js; - path = ../js; - sourceTree = ""; - }; - A00B432717795C5C00480238 /* spidermonkey-mac */ = { - isa = PBXGroup; - children = ( - A00B432817795C5C00480238 /* include */, - A00B437117795C5C00480238 /* lib */, - ); - name = "spidermonkey-mac"; - path = "../../spidermonkey-mac"; - sourceTree = ""; - }; - A00B432817795C5C00480238 /* include */ = { - isa = PBXGroup; - children = ( - A05FCAF4177D12D900BE600E /* js */, - A05FCB04177D12D900BE600E /* js-config.h */, - A05FCB05177D12D900BE600E /* js.msg */, - A05FCB06177D12D900BE600E /* jsalloc.h */, - A05FCB07177D12D900BE600E /* jsapi.h */, - A05FCB08177D12D900BE600E /* jsclass.h */, - A05FCB09177D12D900BE600E /* jsclist.h */, - A05FCB0A177D12D900BE600E /* jscpucfg.h */, - A05FCB0B177D12D900BE600E /* jsdbgapi.h */, - A05FCB0C177D12D900BE600E /* jsdhash.h */, - A05FCB0D177D12D900BE600E /* jsfriendapi.h */, - A05FCB0E177D12D900BE600E /* jslock.h */, - A05FCB0F177D12D900BE600E /* json.h */, - A05FCB10177D12D900BE600E /* jsperf.h */, - A05FCB11177D12D900BE600E /* jsprf.h */, - A05FCB12177D12D900BE600E /* jsprototypes.h */, - A05FCB13177D12D900BE600E /* jsproxy.h */, - A05FCB14177D12D900BE600E /* jsprvtd.h */, - A05FCB15177D12D900BE600E /* jspubtd.h */, - A05FCB16177D12D900BE600E /* jstypes.h */, - A05FCB17177D12D900BE600E /* jsutil.h */, - A05FCB18177D12D900BE600E /* jsversion.h */, - A05FCB19177D12D900BE600E /* jswrapper.h */, - A05FCB1A177D12D900BE600E /* mozilla */, - ); - path = include; - sourceTree = ""; - }; - A00B437117795C5C00480238 /* lib */ = { - isa = PBXGroup; - children = ( - A00B437217795C5C00480238 /* libjs_static.a */, - ); - path = lib; - sourceTree = ""; - }; - A05FCAF4177D12D900BE600E /* js */ = { - isa = PBXGroup; - children = ( - A05FCAF5177D12D900BE600E /* Anchor.h */, - A05FCAF6177D12D900BE600E /* CallArgs.h */, - A05FCAF7177D12D900BE600E /* CharacterEncoding.h */, - A05FCAF8177D12D900BE600E /* GCAPI.h */, - A05FCAF9177D12D900BE600E /* HashTable.h */, - A05FCAFA177D12D900BE600E /* HeapAPI.h */, - A05FCAFB177D12D900BE600E /* LegacyIntTypes.h */, - A05FCAFC177D12D900BE600E /* MemoryMetrics.h */, - A05FCAFD177D12D900BE600E /* PropertyKey.h */, - A05FCAFE177D12D900BE600E /* RequiredDefines.h */, - A05FCAFF177D12D900BE600E /* RootingAPI.h */, - A05FCB00177D12D900BE600E /* TemplateLib.h */, - A05FCB01177D12D900BE600E /* Utility.h */, - A05FCB02177D12D900BE600E /* Value.h */, - A05FCB03177D12D900BE600E /* Vector.h */, - ); - path = js; - sourceTree = ""; - }; - A05FCB1A177D12D900BE600E /* mozilla */ = { - isa = PBXGroup; - children = ( - A05FCB1B177D12D900BE600E /* Assertions.h */, - A05FCB1C177D12D900BE600E /* Attributes.h */, - A05FCB1D177D12D900BE600E /* BloomFilter.h */, - A05FCB1E177D12D900BE600E /* Char16.h */, - A05FCB1F177D12D900BE600E /* CheckedInt.h */, - A05FCB20177D12D900BE600E /* Compiler.h */, - A05FCB21177D12D900BE600E /* Constants.h */, - A05FCB22177D12D900BE600E /* DebugOnly.h */, - A05FCB23177D12D900BE600E /* EnumSet.h */, - A05FCB24177D12D900BE600E /* FloatingPoint.h */, - A05FCB25177D12D900BE600E /* GuardObjects.h */, - A05FCB26177D12D900BE600E /* HashFunctions.h */, - A05FCB27177D12D900BE600E /* Likely.h */, - A05FCB28177D12D900BE600E /* LinkedList.h */, - A05FCB29177D12D900BE600E /* MathAlgorithms.h */, - A05FCB2A177D12D900BE600E /* MemoryChecking.h */, - A05FCB2B177D12D900BE600E /* MSStdInt.h */, - A05FCB2C177D12D900BE600E /* NullPtr.h */, - A05FCB2D177D12D900BE600E /* Range.h */, - A05FCB2E177D12D900BE600E /* RangedPtr.h */, - A05FCB2F177D12D900BE600E /* RefPtr.h */, - A05FCB30177D12D900BE600E /* Scoped.h */, - A05FCB31177D12D900BE600E /* SHA1.h */, - A05FCB32177D12D900BE600E /* SplayTree.h */, - A05FCB33177D12D900BE600E /* StandardInteger.h */, - A05FCB34177D12D900BE600E /* ThreadLocal.h */, - A05FCB35177D12D900BE600E /* TypedEnum.h */, - A05FCB36177D12D900BE600E /* Types.h */, - A05FCB37177D12D900BE600E /* TypeTraits.h */, - A05FCB38177D12D900BE600E /* Util.h */, - A05FCB39177D12D900BE600E /* WeakPtr.h */, - ); - path = mozilla; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 1A0C0E861778088700838530 /* jsbindings */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1A0C0E951778088700838530 /* Build configuration list for PBXNativeTarget "jsbindings" */; - buildPhases = ( - 1A0C0E831778088700838530 /* Sources */, - 1A0C0E841778088700838530 /* Frameworks */, - 1A0C0E851778088700838530 /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = jsbindings; - productName = jsbindings; - productReference = 1A0C0E871778088700838530 /* libjsbindings.a */; - productType = "com.apple.product-type.library.static"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 1A0C0E7F1778088700838530 /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0460; - }; - buildConfigurationList = 1A0C0E821778088700838530 /* Build configuration list for PBXProject "jsbindings" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 1A0C0E7E1778088700838530; - productRefGroup = 1A0C0E881778088700838530 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1A0C0E861778088700838530 /* jsbindings */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - 1A0C0E831778088700838530 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E46D51778162E0055514D /* jsb_cocos2dx_extension_auto.cpp in Sources */, - 1A0C0EDA1778095000838530 /* cocos2d_specifics.cpp in Sources */, - 1A0C0EDB1778095000838530 /* cocosjs_manual_conversions.cpp in Sources */, - 1A0C0EDC1778095000838530 /* jsb_cocos2dx_auto.cpp in Sources */, - 1A0C0EEC1778095000838530 /* js_bindings_ccbreader.cpp in Sources */, - 1A0C0EED1778095000838530 /* js_bindings_chipmunk_auto_classes.cpp in Sources */, - 1A0C0EEE1778095000838530 /* js_bindings_chipmunk_functions.cpp in Sources */, - 1A0C0EEF1778095000838530 /* js_bindings_chipmunk_manual.cpp in Sources */, - 1A0C0EF01778095000838530 /* js_bindings_chipmunk_registration.cpp in Sources */, - 1A0C0EF11778095000838530 /* js_bindings_core.cpp in Sources */, - 1A0C0EF21778095000838530 /* js_bindings_opengl.cpp in Sources */, - 1A0C0EF31778095000838530 /* js_bindings_system_functions.cpp in Sources */, - 1A0C0EF41778095000838530 /* js_bindings_system_registration.cpp in Sources */, - 1A0C0EF51778095000838530 /* js_manual_conversions.cpp in Sources */, - 1A0C0EF61778095000838530 /* jsb_cocos2dx_extension_manual.cpp in Sources */, - 1A0C0EF71778095000838530 /* jsb_opengl_functions.cpp in Sources */, - 1A0C0EF81778095000838530 /* jsb_opengl_manual.cpp in Sources */, - 1A0C0EF91778095000838530 /* jsb_opengl_registration.cpp in Sources */, - 1A0C0EFA1778095000838530 /* jsb_websocket.cpp in Sources */, - 1A0C0EFB1778095000838530 /* ScriptingCore.cpp in Sources */, - 1A0C0EFC1778095000838530 /* XMLHTTPRequest.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1A0C0E931778088700838530 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - CC_TARGET_OS_MAC, - CC_KEYBOARD_SUPPORT, - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - }; - name = Debug; - }; - 1A0C0E941778088700838530 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = YES; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PREPROCESSOR_DEFINITIONS = ( - NDEBUG, - CC_TARGET_OS_MAC, - CC_KEYBOARD_SUPPORT, - ); - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - SDKROOT = macosx; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 1A0C0E961778088700838530 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DSTROOT = /tmp/jsbindings.dst; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "jsbindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "$(inherited)", - "COCOS2D_DEBUG=1", - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../../external/libwebsockets/mac/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../external\"", - "\"$(SRCROOT)/../../../../extensions\"", - "\"$(SRCROOT)/../../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../../extensions/network\"", - "\"$(SRCROOT)/../../../../cocos2dx\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/mac\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/mac\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/mac/Simulation\"", - "\"$(SRCROOT)/../../spidermonkey-mac/include\"", - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../spidermonkey-mac/lib\"", - ); - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - }; - name = Debug; - }; - 1A0C0E971778088700838530 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DSTROOT = /tmp/jsbindings.dst; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "jsbindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "$(inherited)", - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../../external/libwebsockets/mac/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../external\"", - "\"$(SRCROOT)/../../../../extensions\"", - "\"$(SRCROOT)/../../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../../extensions/network\"", - "\"$(SRCROOT)/../../../../cocos2dx\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/mac\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/mac\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/mac/Simulation\"", - "\"$(SRCROOT)/../../spidermonkey-mac/include\"", - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../spidermonkey-mac/lib\"", - ); - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1A0C0E821778088700838530 /* Build configuration list for PBXProject "jsbindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A0C0E931778088700838530 /* Debug */, - 1A0C0E941778088700838530 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1A0C0E951778088700838530 /* Build configuration list for PBXNativeTarget "jsbindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A0C0E961778088700838530 /* Debug */, - 1A0C0E971778088700838530 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 1A0C0E7F1778088700838530 /* Project object */; -} diff --git a/cocos/scripting/lua/proj.ios/luabindings.xcodeproj/project.pbxproj b/cocos/scripting/lua/proj.ios/luabindings.xcodeproj/project.pbxproj deleted file mode 100644 index 0bc70a8e36..0000000000 --- a/cocos/scripting/lua/proj.ios/luabindings.xcodeproj/project.pbxproj +++ /dev/null @@ -1,453 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1A6E476E17781A660055514D /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E476D17781A660055514D /* Foundation.framework */; }; - 1A6E487E17781AB00055514D /* CCBProxy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E477C17781AB00055514D /* CCBProxy.cpp */; }; - 1A6E487F17781AB00055514D /* CCLuaBridge.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E477E17781AB00055514D /* CCLuaBridge.cpp */; }; - 1A6E488017781AB00055514D /* CCLuaEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478017781AB00055514D /* CCLuaEngine.cpp */; }; - 1A6E488117781AB00055514D /* CCLuaStack.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478217781AB00055514D /* CCLuaStack.cpp */; }; - 1A6E488217781AB00055514D /* CCLuaValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478417781AB00055514D /* CCLuaValue.cpp */; }; - 1A6E488317781AB00055514D /* Cocos2dxLuaLoader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478617781AB00055514D /* Cocos2dxLuaLoader.cpp */; }; - 1A6E488417781AB00055514D /* Lua_extensions_CCB.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478817781AB00055514D /* Lua_extensions_CCB.cpp */; }; - 1A6E488517781AB00055514D /* Lua_web_socket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478A17781AB00055514D /* Lua_web_socket.cpp */; }; - 1A6E488617781AB00055514D /* LuaCocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478C17781AB00055514D /* LuaCocos2d.cpp */; }; - 1A6E488717781AB00055514D /* LuaOpengl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E478E17781AB00055514D /* LuaOpengl.cpp */; }; - 1A6E488817781AB00055514D /* LuaScrollView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E479017781AB00055514D /* LuaScrollView.cpp */; }; - 1A6E488917781AB00055514D /* CCLuaObjcBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E479517781AB00055514D /* CCLuaObjcBridge.mm */; }; - 1A6E488A17781AB00055514D /* tolua_fix.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E479617781AB00055514D /* tolua_fix.c */; }; - 1A6E488E17781AB00055514D /* libluajit.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E47AA17781AB00055514D /* libluajit.a */; }; - 1A6E48D717781AB00055514D /* tolua_event.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E487817781AB00055514D /* tolua_event.c */; }; - 1A6E48D817781AB00055514D /* tolua_is.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E487A17781AB00055514D /* tolua_is.c */; }; - 1A6E48D917781AB00055514D /* tolua_map.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E487B17781AB00055514D /* tolua_map.c */; }; - 1A6E48DA17781AB00055514D /* tolua_push.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E487C17781AB00055514D /* tolua_push.c */; }; - 1A6E48DB17781AB00055514D /* tolua_to.c in Sources */ = {isa = PBXBuildFile; fileRef = 1A6E487D17781AB00055514D /* tolua_to.c */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 1A6E476817781A660055514D /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = "include/${PRODUCT_NAME}"; - dstSubfolderSpec = 16; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1A6E476A17781A660055514D /* libluabindings.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libluabindings.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E476D17781A660055514D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 1A6E477C17781AB00055514D /* CCBProxy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBProxy.cpp; sourceTree = ""; }; - 1A6E477D17781AB00055514D /* CCBProxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBProxy.h; sourceTree = ""; }; - 1A6E477E17781AB00055514D /* CCLuaBridge.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCLuaBridge.cpp; sourceTree = ""; }; - 1A6E477F17781AB00055514D /* CCLuaBridge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaBridge.h; sourceTree = ""; }; - 1A6E478017781AB00055514D /* CCLuaEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCLuaEngine.cpp; sourceTree = ""; }; - 1A6E478117781AB00055514D /* CCLuaEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaEngine.h; sourceTree = ""; }; - 1A6E478217781AB00055514D /* CCLuaStack.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCLuaStack.cpp; sourceTree = ""; }; - 1A6E478317781AB00055514D /* CCLuaStack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaStack.h; sourceTree = ""; }; - 1A6E478417781AB00055514D /* CCLuaValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCLuaValue.cpp; sourceTree = ""; }; - 1A6E478517781AB00055514D /* CCLuaValue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaValue.h; sourceTree = ""; }; - 1A6E478617781AB00055514D /* Cocos2dxLuaLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Cocos2dxLuaLoader.cpp; sourceTree = ""; }; - 1A6E478717781AB00055514D /* Cocos2dxLuaLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Cocos2dxLuaLoader.h; sourceTree = ""; }; - 1A6E478817781AB00055514D /* Lua_extensions_CCB.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lua_extensions_CCB.cpp; sourceTree = ""; }; - 1A6E478917781AB00055514D /* Lua_extensions_CCB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Lua_extensions_CCB.h; sourceTree = ""; }; - 1A6E478A17781AB00055514D /* Lua_web_socket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lua_web_socket.cpp; sourceTree = ""; }; - 1A6E478B17781AB00055514D /* Lua_web_socket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Lua_web_socket.h; sourceTree = ""; }; - 1A6E478C17781AB00055514D /* LuaCocos2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LuaCocos2d.cpp; sourceTree = ""; }; - 1A6E478D17781AB00055514D /* LuaCocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LuaCocos2d.h; sourceTree = ""; }; - 1A6E478E17781AB00055514D /* LuaOpengl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LuaOpengl.cpp; sourceTree = ""; }; - 1A6E478F17781AB00055514D /* LuaOpengl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LuaOpengl.h; sourceTree = ""; }; - 1A6E479017781AB00055514D /* LuaScrollView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LuaScrollView.cpp; sourceTree = ""; }; - 1A6E479117781AB00055514D /* LuaScrollView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LuaScrollView.h; sourceTree = ""; }; - 1A6E479417781AB00055514D /* CCLuaObjcBridge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaObjcBridge.h; sourceTree = ""; }; - 1A6E479517781AB00055514D /* CCLuaObjcBridge.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CCLuaObjcBridge.mm; sourceTree = ""; }; - 1A6E479617781AB00055514D /* tolua_fix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_fix.c; sourceTree = ""; }; - 1A6E479717781AB00055514D /* tolua_fix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tolua_fix.h; sourceTree = ""; }; - 1A6E47A517781AB00055514D /* lauxlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lauxlib.h; sourceTree = ""; }; - 1A6E47A617781AB00055514D /* lua.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lua.h; sourceTree = ""; }; - 1A6E47A717781AB00055514D /* luaconf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = luaconf.h; sourceTree = ""; }; - 1A6E47A817781AB00055514D /* lualib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lualib.h; sourceTree = ""; }; - 1A6E47AA17781AB00055514D /* libluajit.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libluajit.a; sourceTree = ""; }; - 1A6E487717781AB00055514D /* tolua++.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "tolua++.h"; sourceTree = ""; }; - 1A6E487817781AB00055514D /* tolua_event.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_event.c; sourceTree = ""; }; - 1A6E487917781AB00055514D /* tolua_event.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tolua_event.h; sourceTree = ""; }; - 1A6E487A17781AB00055514D /* tolua_is.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_is.c; sourceTree = ""; }; - 1A6E487B17781AB00055514D /* tolua_map.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_map.c; sourceTree = ""; }; - 1A6E487C17781AB00055514D /* tolua_push.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_push.c; sourceTree = ""; }; - 1A6E487D17781AB00055514D /* tolua_to.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_to.c; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 1A6E476717781A660055514D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E476E17781A660055514D /* Foundation.framework in Frameworks */, - 1A6E488E17781AB00055514D /* libluajit.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 1A6E476117781A660055514D = { - isa = PBXGroup; - children = ( - 1A6E477B17781AB00055514D /* cocos2dx_support */, - 1A6E479817781AB00055514D /* luajit */, - 1A6E487617781AB00055514D /* tolua */, - 1A6E476C17781A660055514D /* Frameworks */, - 1A6E476B17781A660055514D /* Products */, - ); - sourceTree = ""; - }; - 1A6E476B17781A660055514D /* Products */ = { - isa = PBXGroup; - children = ( - 1A6E476A17781A660055514D /* libluabindings.a */, - ); - name = Products; - sourceTree = ""; - }; - 1A6E476C17781A660055514D /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1A6E476D17781A660055514D /* Foundation.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 1A6E477B17781AB00055514D /* cocos2dx_support */ = { - isa = PBXGroup; - children = ( - 1A6E477C17781AB00055514D /* CCBProxy.cpp */, - 1A6E477D17781AB00055514D /* CCBProxy.h */, - 1A6E477E17781AB00055514D /* CCLuaBridge.cpp */, - 1A6E477F17781AB00055514D /* CCLuaBridge.h */, - 1A6E478017781AB00055514D /* CCLuaEngine.cpp */, - 1A6E478117781AB00055514D /* CCLuaEngine.h */, - 1A6E478217781AB00055514D /* CCLuaStack.cpp */, - 1A6E478317781AB00055514D /* CCLuaStack.h */, - 1A6E478417781AB00055514D /* CCLuaValue.cpp */, - 1A6E478517781AB00055514D /* CCLuaValue.h */, - 1A6E478617781AB00055514D /* Cocos2dxLuaLoader.cpp */, - 1A6E478717781AB00055514D /* Cocos2dxLuaLoader.h */, - 1A6E478817781AB00055514D /* Lua_extensions_CCB.cpp */, - 1A6E478917781AB00055514D /* Lua_extensions_CCB.h */, - 1A6E478A17781AB00055514D /* Lua_web_socket.cpp */, - 1A6E478B17781AB00055514D /* Lua_web_socket.h */, - 1A6E478C17781AB00055514D /* LuaCocos2d.cpp */, - 1A6E478D17781AB00055514D /* LuaCocos2d.h */, - 1A6E478E17781AB00055514D /* LuaOpengl.cpp */, - 1A6E478F17781AB00055514D /* LuaOpengl.h */, - 1A6E479017781AB00055514D /* LuaScrollView.cpp */, - 1A6E479117781AB00055514D /* LuaScrollView.h */, - 1A6E479217781AB00055514D /* platform */, - 1A6E479617781AB00055514D /* tolua_fix.c */, - 1A6E479717781AB00055514D /* tolua_fix.h */, - ); - name = cocos2dx_support; - path = ../cocos2dx_support; - sourceTree = ""; - }; - 1A6E479217781AB00055514D /* platform */ = { - isa = PBXGroup; - children = ( - 1A6E479317781AB00055514D /* ios */, - ); - path = platform; - sourceTree = ""; - }; - 1A6E479317781AB00055514D /* ios */ = { - isa = PBXGroup; - children = ( - 1A6E479417781AB00055514D /* CCLuaObjcBridge.h */, - 1A6E479517781AB00055514D /* CCLuaObjcBridge.mm */, - ); - path = ios; - sourceTree = ""; - }; - 1A6E479817781AB00055514D /* luajit */ = { - isa = PBXGroup; - children = ( - 1A6E47A417781AB00055514D /* include */, - 1A6E47A917781AB00055514D /* ios */, - ); - name = luajit; - path = ../luajit; - sourceTree = ""; - }; - 1A6E47A417781AB00055514D /* include */ = { - isa = PBXGroup; - children = ( - 1A6E47A517781AB00055514D /* lauxlib.h */, - 1A6E47A617781AB00055514D /* lua.h */, - 1A6E47A717781AB00055514D /* luaconf.h */, - 1A6E47A817781AB00055514D /* lualib.h */, - ); - path = include; - sourceTree = ""; - }; - 1A6E47A917781AB00055514D /* ios */ = { - isa = PBXGroup; - children = ( - 1A6E47AA17781AB00055514D /* libluajit.a */, - ); - path = ios; - sourceTree = ""; - }; - 1A6E487617781AB00055514D /* tolua */ = { - isa = PBXGroup; - children = ( - 1A6E487717781AB00055514D /* tolua++.h */, - 1A6E487817781AB00055514D /* tolua_event.c */, - 1A6E487917781AB00055514D /* tolua_event.h */, - 1A6E487A17781AB00055514D /* tolua_is.c */, - 1A6E487B17781AB00055514D /* tolua_map.c */, - 1A6E487C17781AB00055514D /* tolua_push.c */, - 1A6E487D17781AB00055514D /* tolua_to.c */, - ); - name = tolua; - path = ../tolua; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 1A6E476917781A660055514D /* luabindings */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1A6E477817781A660055514D /* Build configuration list for PBXNativeTarget "luabindings" */; - buildPhases = ( - 1A6E476617781A660055514D /* Sources */, - 1A6E476717781A660055514D /* Frameworks */, - 1A6E476817781A660055514D /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = luabindings; - productName = luabindings; - productReference = 1A6E476A17781A660055514D /* libluabindings.a */; - productType = "com.apple.product-type.library.static"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 1A6E476217781A660055514D /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0460; - }; - buildConfigurationList = 1A6E476517781A660055514D /* Build configuration list for PBXProject "luabindings" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 1A6E476117781A660055514D; - productRefGroup = 1A6E476B17781A660055514D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1A6E476917781A660055514D /* luabindings */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - 1A6E476617781A660055514D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E487E17781AB00055514D /* CCBProxy.cpp in Sources */, - 1A6E487F17781AB00055514D /* CCLuaBridge.cpp in Sources */, - 1A6E488017781AB00055514D /* CCLuaEngine.cpp in Sources */, - 1A6E488117781AB00055514D /* CCLuaStack.cpp in Sources */, - 1A6E488217781AB00055514D /* CCLuaValue.cpp in Sources */, - 1A6E488317781AB00055514D /* Cocos2dxLuaLoader.cpp in Sources */, - 1A6E488417781AB00055514D /* Lua_extensions_CCB.cpp in Sources */, - 1A6E488517781AB00055514D /* Lua_web_socket.cpp in Sources */, - 1A6E488617781AB00055514D /* LuaCocos2d.cpp in Sources */, - 1A6E488717781AB00055514D /* LuaOpengl.cpp in Sources */, - 1A6E488817781AB00055514D /* LuaScrollView.cpp in Sources */, - 1A6E488917781AB00055514D /* CCLuaObjcBridge.mm in Sources */, - 1A6E488A17781AB00055514D /* tolua_fix.c in Sources */, - 1A6E48D717781AB00055514D /* tolua_event.c in Sources */, - 1A6E48D817781AB00055514D /* tolua_is.c in Sources */, - 1A6E48D917781AB00055514D /* tolua_map.c in Sources */, - 1A6E48DA17781AB00055514D /* tolua_push.c in Sources */, - 1A6E48DB17781AB00055514D /* tolua_to.c in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1A6E477617781A660055514D /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 6.1; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 1A6E477717781A660055514D /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 6.1; - SDKROOT = iphoneos; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 1A6E477917781A660055514D /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - DSTROOT = /tmp/luabindings.dst; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "luabindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - CC_TARGET_OS_IPHONE, - "COCOS2D_DEBUG=1", - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - "$(inherited)", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/include\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../extensions/network\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios/Simulation\"", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../luajit/ios\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 1A6E477A17781A660055514D /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - DSTROOT = /tmp/luabindings.dst; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "luabindings-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - CC_TARGET_OS_IPHONE, - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/include\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../extensions/LocalStorage\"", - "\"$(SRCROOT)/../../../extensions/network\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios/Simulation\"", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../luajit/ios\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-ObjC"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1A6E476517781A660055514D /* Build configuration list for PBXProject "luabindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A6E477617781A660055514D /* Debug */, - 1A6E477717781A660055514D /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1A6E477817781A660055514D /* Build configuration list for PBXNativeTarget "luabindings" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1A6E477917781A660055514D /* Debug */, - 1A6E477A17781A660055514D /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 1A6E476217781A660055514D /* Project object */; -} diff --git a/samples/Lua/HelloLua/proj.ios/HelloLua.xcodeproj/project.pbxproj b/samples/Lua/HelloLua/proj.ios/HelloLua.xcodeproj/project.pbxproj deleted file mode 100644 index 1531215d78..0000000000 --- a/samples/Lua/HelloLua/proj.ios/HelloLua.xcodeproj/project.pbxproj +++ /dev/null @@ -1,491 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1A6E48DF17781C0F0055514D /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48DC17781C0F0055514D /* libcocos2dx.a */; }; - 1A6E48E017781C0F0055514D /* libCocosDenshion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48DD17781C0F0055514D /* libCocosDenshion.a */; }; - 1A6E48E117781C0F0055514D /* libluabindings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48DE17781C0F0055514D /* libluabindings.a */; }; - 1A6E48F017781D600055514D /* libchipmunk.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48EE17781D600055514D /* libchipmunk.a */; }; - 1A6E48F317781D920055514D /* libBox2D.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48F217781D920055514D /* libBox2D.a */; }; - 1A6E4902177821FB0055514D /* libextensions.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E4901177821FB0055514D /* libextensions.a */; }; - 1A6E49081778251B0055514D /* AudioEngine.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E49041778251B0055514D /* AudioEngine.lua */; }; - 1A6E49091778251B0055514D /* CCBReaderLoad.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E49051778251B0055514D /* CCBReaderLoad.lua */; }; - 1A6E490A1778251B0055514D /* Cocos2dConstants.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E49061778251B0055514D /* Cocos2dConstants.lua */; }; - 1A6E490B1778251B0055514D /* OpenglConstants.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E49071778251B0055514D /* OpenglConstants.lua */; }; - 506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */; }; - 78947C6D14EBB9B100DBD5A6 /* background.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 78947C5E14EBB9B000DBD5A6 /* background.mp3 */; }; - 78947C6E14EBB9B100DBD5A6 /* crop.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C5F14EBB9B000DBD5A6 /* crop.png */; }; - 78947C7014EBB9B100DBD5A6 /* dog.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6114EBB9B000DBD5A6 /* dog.png */; }; - 78947C7114EBB9B100DBD5A6 /* effect1.wav in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6214EBB9B000DBD5A6 /* effect1.wav */; }; - 78947C7214EBB9B100DBD5A6 /* farm.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6314EBB9B000DBD5A6 /* farm.jpg */; }; - 78947C7414EBB9B100DBD5A6 /* hello.lua in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6614EBB9B000DBD5A6 /* hello.lua */; }; - 78947C7514EBB9B100DBD5A6 /* hello2.lua in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6714EBB9B000DBD5A6 /* hello2.lua */; }; - 78947C7714EBB9B100DBD5A6 /* land.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6914EBB9B000DBD5A6 /* land.png */; }; - 78947C7814EBB9B100DBD5A6 /* menu1.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6A14EBB9B000DBD5A6 /* menu1.png */; }; - 78947C7914EBB9B100DBD5A6 /* menu2.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6B14EBB9B000DBD5A6 /* menu2.png */; }; - 78DC4C9A15490B9500317402 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 78DC4C9815490B9500317402 /* Default.png */; }; - BF82F41713A864D700616D55 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF82F41513A864D700616D55 /* AppDelegate.cpp */; }; - BF82F42113A8652A00616D55 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF82F41F13A8652A00616D55 /* AppController.mm */; }; - BF82F42213A8652A00616D55 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = BF82F42013A8652A00616D55 /* main.m */; }; - D41A0AA2160F13F8004552AE /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = D41A0AA1160F13F8004552AE /* Default-568h@2x.png */; }; - D446FD3B16102085000ADA7B /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = D446FD3A16102085000ADA7B /* Default@2x.png */; }; - D4CEAD7913B4634300780515 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = D4CEAD7713B4634300780515 /* RootViewController.mm */; }; - D4EF94D715BD311700D803EB /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94D615BD311700D803EB /* Icon-57.png */; }; - D4EF94D915BD311A00D803EB /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94D815BD311A00D803EB /* Icon-114.png */; }; - D4EF94DB15BD311E00D803EB /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94DA15BD311E00D803EB /* Icon-72.png */; }; - D4EF94DD15BD312100D803EB /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94DC15BD312100D803EB /* Icon-144.png */; }; - DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */; }; - DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640040F83B3EA000B3E49 /* OpenAL.framework */; }; - DCCBF1B70F6022AE0040855A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */; }; - DCCBF1B90F6022AE0040855A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1B80F6022AE0040855A /* Foundation.framework */; }; - DCCBF1BB0F6022AE0040855A /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */; }; - DCCBF1BD0F6022AE0040855A /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */; }; - DCCBF1BF0F6022AE0040855A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BE0F6022AE0040855A /* UIKit.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 1A6E48DC17781C0F0055514D /* libcocos2dx.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libcocos2dx.a; path = "libcocos2dx.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48DD17781C0F0055514D /* libCocosDenshion.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libCocosDenshion.a; path = "libCocosDenshion.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48DE17781C0F0055514D /* libluabindings.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libluabindings.a; path = "libluabindings.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48EE17781D600055514D /* libchipmunk.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libchipmunk.a; path = "libchipmunk.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48F217781D920055514D /* libBox2D.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libBox2D.a; path = "libBox2D.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E4901177821FB0055514D /* libextensions.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libextensions.a; path = "libextensions.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E49041778251B0055514D /* AudioEngine.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = AudioEngine.lua; sourceTree = ""; }; - 1A6E49051778251B0055514D /* CCBReaderLoad.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CCBReaderLoad.lua; sourceTree = ""; }; - 1A6E49061778251B0055514D /* Cocos2dConstants.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Cocos2dConstants.lua; sourceTree = ""; }; - 1A6E49071778251B0055514D /* OpenglConstants.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = OpenglConstants.lua; sourceTree = ""; }; - 1D6058910D05DD3D006BFB54 /* HelloLua.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloLua.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; - 78947C5E14EBB9B000DBD5A6 /* background.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = background.mp3; sourceTree = ""; }; - 78947C5F14EBB9B000DBD5A6 /* crop.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = crop.png; sourceTree = ""; }; - 78947C6114EBB9B000DBD5A6 /* dog.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = dog.png; sourceTree = ""; }; - 78947C6214EBB9B000DBD5A6 /* effect1.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = effect1.wav; sourceTree = ""; }; - 78947C6314EBB9B000DBD5A6 /* farm.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = farm.jpg; sourceTree = ""; }; - 78947C6614EBB9B000DBD5A6 /* hello.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = hello.lua; sourceTree = ""; }; - 78947C6714EBB9B000DBD5A6 /* hello2.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = hello2.lua; sourceTree = ""; }; - 78947C6914EBB9B000DBD5A6 /* land.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = land.png; sourceTree = ""; }; - 78947C6A14EBB9B000DBD5A6 /* menu1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = menu1.png; sourceTree = ""; }; - 78947C6B14EBB9B000DBD5A6 /* menu2.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = menu2.png; sourceTree = ""; }; - 78DC4C9815490B9500317402 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = SOURCE_ROOT; }; - BF82F41513A864D700616D55 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AppDelegate.cpp; path = ../Classes/AppDelegate.cpp; sourceTree = SOURCE_ROOT; }; - BF82F41613A864D700616D55 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ../Classes/AppDelegate.h; sourceTree = SOURCE_ROOT; }; - BF82F41E13A8652A00616D55 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = ""; }; - BF82F41F13A8652A00616D55 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = ""; }; - BF82F42013A8652A00616D55 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - BF82F42313A8654600616D55 /* HelloLua_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloLua_Prefix.pch; sourceTree = ""; }; - D41A0AA1160F13F8004552AE /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Default-568h@2x.png"; path = "../proj.ios/Default-568h@2x.png"; sourceTree = ""; }; - D446FD3A16102085000ADA7B /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Default@2x.png"; path = "../proj.ios/Default@2x.png"; sourceTree = ""; }; - D4CEAD7713B4634300780515 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = ""; }; - D4CEAD7813B4634300780515 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = ""; }; - D4EF94D615BD311700D803EB /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-57.png"; path = "../proj.ios/Icon-57.png"; sourceTree = ""; }; - D4EF94D815BD311A00D803EB /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-114.png"; path = "../proj.ios/Icon-114.png"; sourceTree = ""; }; - D4EF94DA15BD311E00D803EB /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-72.png"; path = "../proj.ios/Icon-72.png"; sourceTree = ""; }; - D4EF94DC15BD312100D803EB /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-144.png"; path = "../proj.ios/Icon-144.png"; sourceTree = ""; }; - DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; - DC6640040F83B3EA000B3E49 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; - DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; - DCCBF1B80F6022AE0040855A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; - DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; - DCCBF1BE0F6022AE0040855A /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E4902177821FB0055514D /* libextensions.a in Frameworks */, - 1A6E48F317781D920055514D /* libBox2D.a in Frameworks */, - 1A6E48F017781D600055514D /* libchipmunk.a in Frameworks */, - 1A6E48DF17781C0F0055514D /* libcocos2dx.a in Frameworks */, - 1A6E48E017781C0F0055514D /* libCocosDenshion.a in Frameworks */, - 1A6E48E117781C0F0055514D /* libluabindings.a in Frameworks */, - DCCBF1B70F6022AE0040855A /* CoreGraphics.framework in Frameworks */, - DCCBF1B90F6022AE0040855A /* Foundation.framework in Frameworks */, - DCCBF1BB0F6022AE0040855A /* OpenGLES.framework in Frameworks */, - DCCBF1BD0F6022AE0040855A /* QuartzCore.framework in Frameworks */, - DCCBF1BF0F6022AE0040855A /* UIKit.framework in Frameworks */, - DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */, - DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */, - 506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 19C28FACFE9D520D11CA2CBB /* Products */ = { - isa = PBXGroup; - children = ( - 1D6058910D05DD3D006BFB54 /* HelloLua.app */, - ); - name = Products; - sourceTree = ""; - }; - 1A6E49031778251B0055514D /* script */ = { - isa = PBXGroup; - children = ( - 1A6E49041778251B0055514D /* AudioEngine.lua */, - 1A6E49051778251B0055514D /* CCBReaderLoad.lua */, - 1A6E49061778251B0055514D /* Cocos2dConstants.lua */, - 1A6E49071778251B0055514D /* OpenglConstants.lua */, - ); - name = script; - path = ../../../../scripting/lua/script; - sourceTree = ""; - }; - 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { - isa = PBXGroup; - children = ( - BF82F41413A864B000616D55 /* Classes */, - 29B97323FDCFA39411CA2CEA /* Frameworks */, - 29B97315FDCFA39411CA2CEA /* Other Sources */, - 19C28FACFE9D520D11CA2CBB /* Products */, - 78947C5C14EBB9B000DBD5A6 /* Resources */, - ); - name = CustomTemplate; - sourceTree = ""; - }; - 29B97315FDCFA39411CA2CEA /* Other Sources */ = { - isa = PBXGroup; - children = ( - D4CEAD7713B4634300780515 /* RootViewController.mm */, - D4CEAD7813B4634300780515 /* RootViewController.h */, - BF82F42313A8654600616D55 /* HelloLua_Prefix.pch */, - BF82F41E13A8652A00616D55 /* AppController.h */, - BF82F41F13A8652A00616D55 /* AppController.mm */, - BF82F42013A8652A00616D55 /* main.m */, - ); - name = "Other Sources"; - sourceTree = ""; - }; - 29B97323FDCFA39411CA2CEA /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1A6E48F217781D920055514D /* libBox2D.a */, - 1A6E48EE17781D600055514D /* libchipmunk.a */, - 1A6E48DC17781C0F0055514D /* libcocos2dx.a */, - 1A6E48DD17781C0F0055514D /* libCocosDenshion.a */, - 1A6E4901177821FB0055514D /* libextensions.a */, - 1A6E48DE17781C0F0055514D /* libluabindings.a */, - DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */, - DCCBF1B80F6022AE0040855A /* Foundation.framework */, - DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */, - DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */, - DCCBF1BE0F6022AE0040855A /* UIKit.framework */, - DC6640040F83B3EA000B3E49 /* OpenAL.framework */, - DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */, - 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 78947C5C14EBB9B000DBD5A6 /* Resources */ = { - isa = PBXGroup; - children = ( - 1A6E49031778251B0055514D /* script */, - D4EF94DC15BD312100D803EB /* Icon-144.png */, - D4EF94DA15BD311E00D803EB /* Icon-72.png */, - D4EF94D815BD311A00D803EB /* Icon-114.png */, - D4EF94D615BD311700D803EB /* Icon-57.png */, - 78947C5E14EBB9B000DBD5A6 /* background.mp3 */, - 78947C5F14EBB9B000DBD5A6 /* crop.png */, - 78947C6114EBB9B000DBD5A6 /* dog.png */, - 78947C6214EBB9B000DBD5A6 /* effect1.wav */, - 78947C6314EBB9B000DBD5A6 /* farm.jpg */, - 78947C6614EBB9B000DBD5A6 /* hello.lua */, - 78947C6714EBB9B000DBD5A6 /* hello2.lua */, - 78947C6914EBB9B000DBD5A6 /* land.png */, - 78947C6A14EBB9B000DBD5A6 /* menu1.png */, - 78947C6B14EBB9B000DBD5A6 /* menu2.png */, - 78DC4C9815490B9500317402 /* Default.png */, - D446FD3A16102085000ADA7B /* Default@2x.png */, - D41A0AA1160F13F8004552AE /* Default-568h@2x.png */, - ); - name = Resources; - path = ../Resources; - sourceTree = ""; - }; - BF82F41413A864B000616D55 /* Classes */ = { - isa = PBXGroup; - children = ( - BF82F41513A864D700616D55 /* AppDelegate.cpp */, - BF82F41613A864D700616D55 /* AppDelegate.h */, - ); - name = Classes; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 1D6058900D05DD3D006BFB54 /* HelloLua */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloLua" */; - buildPhases = ( - 1D60588D0D05DD3D006BFB54 /* Resources */, - 1D60588E0D05DD3D006BFB54 /* Sources */, - 1D60588F0D05DD3D006BFB54 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = HelloLua; - productName = HelloLua; - productReference = 1D6058910D05DD3D006BFB54 /* HelloLua.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 29B97313FDCFA39411CA2CEA /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0430; - }; - buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloLua" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - English, - Japanese, - French, - German, - ); - mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1D6058900D05DD3D006BFB54 /* HelloLua */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 1D60588D0D05DD3D006BFB54 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 78947C6D14EBB9B100DBD5A6 /* background.mp3 in Resources */, - 78947C6E14EBB9B100DBD5A6 /* crop.png in Resources */, - 78947C7014EBB9B100DBD5A6 /* dog.png in Resources */, - 78947C7114EBB9B100DBD5A6 /* effect1.wav in Resources */, - 78947C7214EBB9B100DBD5A6 /* farm.jpg in Resources */, - 78947C7414EBB9B100DBD5A6 /* hello.lua in Resources */, - 78947C7514EBB9B100DBD5A6 /* hello2.lua in Resources */, - 78947C7714EBB9B100DBD5A6 /* land.png in Resources */, - 78947C7814EBB9B100DBD5A6 /* menu1.png in Resources */, - 78947C7914EBB9B100DBD5A6 /* menu2.png in Resources */, - 78DC4C9A15490B9500317402 /* Default.png in Resources */, - D4EF94D715BD311700D803EB /* Icon-57.png in Resources */, - D4EF94D915BD311A00D803EB /* Icon-114.png in Resources */, - D4EF94DB15BD311E00D803EB /* Icon-72.png in Resources */, - D4EF94DD15BD312100D803EB /* Icon-144.png in Resources */, - D41A0AA2160F13F8004552AE /* Default-568h@2x.png in Resources */, - D446FD3B16102085000ADA7B /* Default@2x.png in Resources */, - 1A6E49081778251B0055514D /* AudioEngine.lua in Resources */, - 1A6E49091778251B0055514D /* CCBReaderLoad.lua in Resources */, - 1A6E490A1778251B0055514D /* Cocos2dConstants.lua in Resources */, - 1A6E490B1778251B0055514D /* OpenglConstants.lua in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 1D60588E0D05DD3D006BFB54 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - BF82F41713A864D700616D55 /* AppDelegate.cpp in Sources */, - BF82F42113A8652A00616D55 /* AppController.mm in Sources */, - BF82F42213A8652A00616D55 /* main.m in Sources */, - D4CEAD7913B4634300780515 /* RootViewController.mm in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1D6058940D05DD3E006BFB54 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_DYNAMIC_NO_PIC = NO; - GCC_FAST_OBJC_DISPATCH = YES; - GCC_INLINES_ARE_PRIVATE_EXTERN = NO; - GCC_OBJC_CALL_CXX_CDTORS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = HelloLua_Prefix.pch; - GCC_PREPROCESSOR_DEFINITIONS = ( - USE_FILE32API, - CC_TARGET_OS_IPHONE, - "COCOS2D_DEBUG=1", - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_VERSION = ""; - GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO; - HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../CocosDenshion/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/cocos2dx_support\"", - "\"$(SRCROOT)/../../../../scripting/lua/luajit/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/tolua\"", - ); - INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios/libraries\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-lz"; - PRODUCT_NAME = HelloLua; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = NO; - VALID_ARCHS = "armv7 armv7s"; - WARNING_CFLAGS = ""; - }; - name = Debug; - }; - 1D6058950D05DD3E006BFB54 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_FAST_OBJC_DISPATCH = YES; - GCC_INLINES_ARE_PRIVATE_EXTERN = NO; - GCC_OBJC_CALL_CXX_CDTORS = YES; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = HelloLua_Prefix.pch; - GCC_PREPROCESSOR_DEFINITIONS = ( - USE_FILE32API, - CC_TARGET_OS_IPHONE, - "CC_ENABLE_CHIPMUNK_INTEGRATION=1", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_VERSION = ""; - GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO; - HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../CocosDenshion/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/cocos2dx_support\"", - "\"$(SRCROOT)/../../../../scripting/lua/luajit/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/tolua\"", - ); - INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios/libraries\"", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-lz"; - PRODUCT_NAME = HelloLua; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = NO; - VALID_ARCHS = "armv7 armv7s"; - WARNING_CFLAGS = ""; - }; - name = Release; - }; - C01FCF4F08A954540054247B /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PREPROCESSOR_DEFINITIONS = ( - DEBUG, - "COCOS2D_DEBUG=1", - "CD_DEBUG=1", - ); - "GCC_THUMB_SUPPORT[arch=armv6]" = NO; - "GCC_THUMB_SUPPORT[arch=armv7]" = YES; - GCC_VERSION = ""; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 4.0; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALID_ARCHS = "armv6 armv7 i386"; - }; - name = Debug; - }; - C01FCF5008A954540054247B /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = c99; - "GCC_THUMB_SUPPORT[arch=armv6]" = NO; - "GCC_THUMB_SUPPORT[arch=armv7]" = YES; - GCC_UNROLL_LOOPS = YES; - GCC_VERSION = ""; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 4.0; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALID_ARCHS = "armv6 armv7 i386"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloLua" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1D6058940D05DD3E006BFB54 /* Debug */, - 1D6058950D05DD3E006BFB54 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloLua" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C01FCF4F08A954540054247B /* Debug */, - C01FCF5008A954540054247B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; -} diff --git a/samples/Lua/TestLua/proj.ios/TestLua.xcodeproj/project.pbxproj b/samples/Lua/TestLua/proj.ios/TestLua.xcodeproj/project.pbxproj deleted file mode 100644 index 7d60946d93..0000000000 --- a/samples/Lua/TestLua/proj.ios/TestLua.xcodeproj/project.pbxproj +++ /dev/null @@ -1,573 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 159B8A28175D9A930005B47D /* cocosbuilderRes in Resources */ = {isa = PBXBuildFile; fileRef = 159B8A27175D9A930005B47D /* cocosbuilderRes */; }; - 15C156981683138E00D239F2 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156911683138E00D239F2 /* Default-568h@2x.png */; }; - 15C156991683138E00D239F2 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156921683138E00D239F2 /* Default.png */; }; - 15C1569A1683138E00D239F2 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156931683138E00D239F2 /* Default@2x.png */; }; - 15C1569B1683138E00D239F2 /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156941683138E00D239F2 /* Icon-57.png */; }; - 15C1569C1683138E00D239F2 /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156951683138E00D239F2 /* Icon-72.png */; }; - 15C1569D1683138E00D239F2 /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156961683138E00D239F2 /* Icon-114.png */; }; - 15C1569E1683138E00D239F2 /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = 15C156971683138E00D239F2 /* Icon-144.png */; }; - 1A6E48E817781C2B0055514D /* libBox2D.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48E217781C2B0055514D /* libBox2D.a */; }; - 1A6E48E917781C2B0055514D /* libchipmunk.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48E317781C2B0055514D /* libchipmunk.a */; }; - 1A6E48EA17781C2B0055514D /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48E417781C2B0055514D /* libcocos2dx.a */; }; - 1A6E48EB17781C2B0055514D /* libCocosDenshion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48E517781C2B0055514D /* libCocosDenshion.a */; }; - 1A6E48ED17781C2B0055514D /* libluabindings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48E717781C2B0055514D /* libluabindings.a */; }; - 1A6E48FB17781F9F0055514D /* AudioEngine.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E48F717781F9F0055514D /* AudioEngine.lua */; }; - 1A6E48FC17781F9F0055514D /* CCBReaderLoad.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E48F817781F9F0055514D /* CCBReaderLoad.lua */; }; - 1A6E48FD17781F9F0055514D /* Cocos2dConstants.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E48F917781F9F0055514D /* Cocos2dConstants.lua */; }; - 1A6E48FE17781F9F0055514D /* OpenglConstants.lua in Resources */ = {isa = PBXBuildFile; fileRef = 1A6E48FA17781F9F0055514D /* OpenglConstants.lua */; }; - 1A6E4900177821AF0055514D /* libextensions.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A6E48FF177821AF0055514D /* libextensions.a */; }; - 1AD263A2168350490089000C /* luaScript in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A1168350490089000C /* luaScript */; }; - 1AD263BB1683506D0089000C /* animations in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A31683506C0089000C /* animations */; }; - 1AD263BC1683506D0089000C /* app.icf in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A41683506C0089000C /* app.icf */; }; - 1AD263BD1683506D0089000C /* background.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A51683506C0089000C /* background.mp3 */; }; - 1AD263BE1683506D0089000C /* background.ogg in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A61683506C0089000C /* background.ogg */; }; - 1AD263BF1683506D0089000C /* ccb in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A71683506C0089000C /* ccb */; }; - 1AD263C01683506D0089000C /* CocosBuilderExample.ccbproj in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A81683506C0089000C /* CocosBuilderExample.ccbproj */; }; - 1AD263C11683506D0089000C /* CocosBuilderExample.ccbresourcelog in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263A91683506C0089000C /* CocosBuilderExample.ccbresourcelog */; }; - 1AD263C21683506D0089000C /* development.icf in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AA1683506C0089000C /* development.icf */; }; - 1AD263C31683506D0089000C /* effect1.raw in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AB1683506C0089000C /* effect1.raw */; }; - 1AD263C41683506D0089000C /* effect1.wav in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AC1683506C0089000C /* effect1.wav */; }; - 1AD263C51683506D0089000C /* effect2.ogg in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AD1683506C0089000C /* effect2.ogg */; }; - 1AD263C61683506D0089000C /* extensions in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AE1683506C0089000C /* extensions */; }; - 1AD263C71683506D0089000C /* fonts in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263AF1683506C0089000C /* fonts */; }; - 1AD263C81683506D0089000C /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B01683506C0089000C /* fps_images.png */; }; - 1AD263C91683506D0089000C /* hd in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B11683506C0089000C /* hd */; }; - 1AD263CA1683506D0089000C /* Hello.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B21683506C0089000C /* Hello.png */; }; - 1AD263CB1683506D0089000C /* Images in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B31683506C0089000C /* Images */; }; - 1AD263CC1683506D0089000C /* ipad in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B41683506C0089000C /* ipad */; }; - 1AD263CD1683506D0089000C /* ipadhd in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B51683506C0089000C /* ipadhd */; }; - 1AD263CE1683506D0089000C /* music.mid in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B61683506C0089000C /* music.mid */; }; - 1AD263CF1683506D0089000C /* Particles in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B71683506C0089000C /* Particles */; }; - 1AD263D01683506D0089000C /* Shaders in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B81683506C0089000C /* Shaders */; }; - 1AD263D11683506D0089000C /* TileMaps in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263B91683506C0089000C /* TileMaps */; }; - 1AD263D21683506D0089000C /* zwoptex in Resources */ = {isa = PBXBuildFile; fileRef = 1AD263BA1683506C0089000C /* zwoptex */; }; - F293B3CD15EB7BE500256477 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3CC15EB7BE500256477 /* QuartzCore.framework */; }; - F293B3CF15EB7BE500256477 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3CE15EB7BE500256477 /* OpenGLES.framework */; }; - F293B3D115EB7BE500256477 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D015EB7BE500256477 /* OpenAL.framework */; }; - F293B3D315EB7BE500256477 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D215EB7BE500256477 /* AudioToolbox.framework */; }; - F293B3D515EB7BE500256477 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D415EB7BE500256477 /* AVFoundation.framework */; }; - F293B3D715EB7BE500256477 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D615EB7BE500256477 /* UIKit.framework */; }; - F293B3D915EB7BE500256477 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3D815EB7BE500256477 /* Foundation.framework */; }; - F293B3DB15EB7BE500256477 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F293B3DA15EB7BE500256477 /* CoreGraphics.framework */; }; - F293B6FC15EB823D00256477 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = F293B6F715EB823D00256477 /* AppController.mm */; }; - F293B6FD15EB823D00256477 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F293B6F815EB823D00256477 /* main.m */; }; - F293B6FE15EB823D00256477 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = F293B6FA15EB823D00256477 /* RootViewController.mm */; }; - F293BB9C15EB831F00256477 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F293BB7E15EB831F00256477 /* AppDelegate.cpp */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 159B8A27175D9A930005B47D /* cocosbuilderRes */ = {isa = PBXFileReference; lastKnownFileType = folder; name = cocosbuilderRes; path = ../../../Lua/TestLua/Resources/cocosbuilderRes; sourceTree = ""; }; - 15C156911683138E00D239F2 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = SOURCE_ROOT; }; - 15C156921683138E00D239F2 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = SOURCE_ROOT; }; - 15C156931683138E00D239F2 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = SOURCE_ROOT; }; - 15C156941683138E00D239F2 /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-57.png"; sourceTree = SOURCE_ROOT; }; - 15C156951683138E00D239F2 /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-72.png"; sourceTree = SOURCE_ROOT; }; - 15C156961683138E00D239F2 /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-114.png"; sourceTree = SOURCE_ROOT; }; - 15C156971683138E00D239F2 /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-144.png"; sourceTree = SOURCE_ROOT; }; - 1A6E48E217781C2B0055514D /* libBox2D.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libBox2D.a; path = "libBox2D.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48E317781C2B0055514D /* libchipmunk.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libchipmunk.a; path = "libchipmunk.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48E417781C2B0055514D /* libcocos2dx.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libcocos2dx.a; path = "libcocos2dx.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48E517781C2B0055514D /* libCocosDenshion.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libCocosDenshion.a; path = "libCocosDenshion.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48E717781C2B0055514D /* libluabindings.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libluabindings.a; path = "libluabindings.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1A6E48F717781F9F0055514D /* AudioEngine.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = AudioEngine.lua; sourceTree = ""; }; - 1A6E48F817781F9F0055514D /* CCBReaderLoad.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CCBReaderLoad.lua; sourceTree = ""; }; - 1A6E48F917781F9F0055514D /* Cocos2dConstants.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Cocos2dConstants.lua; sourceTree = ""; }; - 1A6E48FA17781F9F0055514D /* OpenglConstants.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = OpenglConstants.lua; sourceTree = ""; }; - 1A6E48FF177821AF0055514D /* libextensions.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; name = libextensions.a; path = "libextensions.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AD263A1168350490089000C /* luaScript */ = {isa = PBXFileReference; lastKnownFileType = folder; name = luaScript; path = ../../../Lua/TestLua/Resources/luaScript; sourceTree = ""; }; - 1AD263A31683506C0089000C /* animations */ = {isa = PBXFileReference; lastKnownFileType = folder; path = animations; sourceTree = ""; }; - 1AD263A41683506C0089000C /* app.icf */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = app.icf; sourceTree = ""; }; - 1AD263A51683506C0089000C /* background.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = background.mp3; sourceTree = ""; }; - 1AD263A61683506C0089000C /* background.ogg */ = {isa = PBXFileReference; lastKnownFileType = file; path = background.ogg; sourceTree = ""; }; - 1AD263A71683506C0089000C /* ccb */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ccb; sourceTree = ""; }; - 1AD263A81683506C0089000C /* CocosBuilderExample.ccbproj */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = CocosBuilderExample.ccbproj; sourceTree = ""; }; - 1AD263A91683506C0089000C /* CocosBuilderExample.ccbresourcelog */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CocosBuilderExample.ccbresourcelog; sourceTree = ""; }; - 1AD263AA1683506C0089000C /* development.icf */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = development.icf; sourceTree = ""; }; - 1AD263AB1683506C0089000C /* effect1.raw */ = {isa = PBXFileReference; lastKnownFileType = file; path = effect1.raw; sourceTree = ""; }; - 1AD263AC1683506C0089000C /* effect1.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = effect1.wav; sourceTree = ""; }; - 1AD263AD1683506C0089000C /* effect2.ogg */ = {isa = PBXFileReference; lastKnownFileType = file; path = effect2.ogg; sourceTree = ""; }; - 1AD263AE1683506C0089000C /* extensions */ = {isa = PBXFileReference; lastKnownFileType = folder; path = extensions; sourceTree = ""; }; - 1AD263AF1683506C0089000C /* fonts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = fonts; sourceTree = ""; }; - 1AD263B01683506C0089000C /* fps_images.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = fps_images.png; sourceTree = ""; }; - 1AD263B11683506C0089000C /* hd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = hd; sourceTree = ""; }; - 1AD263B21683506C0089000C /* Hello.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Hello.png; sourceTree = ""; }; - 1AD263B31683506C0089000C /* Images */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Images; sourceTree = ""; }; - 1AD263B41683506C0089000C /* ipad */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ipad; sourceTree = ""; }; - 1AD263B51683506C0089000C /* ipadhd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ipadhd; sourceTree = ""; }; - 1AD263B61683506C0089000C /* music.mid */ = {isa = PBXFileReference; lastKnownFileType = audio.midi; path = music.mid; sourceTree = ""; }; - 1AD263B71683506C0089000C /* Particles */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Particles; sourceTree = ""; }; - 1AD263B81683506C0089000C /* Shaders */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Shaders; sourceTree = ""; }; - 1AD263B91683506C0089000C /* TileMaps */ = {isa = PBXFileReference; lastKnownFileType = folder; path = TileMaps; sourceTree = ""; }; - 1AD263BA1683506C0089000C /* zwoptex */ = {isa = PBXFileReference; lastKnownFileType = folder; path = zwoptex; sourceTree = ""; }; - F293B3C815EB7BE500256477 /* TestLua.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TestLua.app; sourceTree = BUILT_PRODUCTS_DIR; }; - F293B3CC15EB7BE500256477 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; - F293B3CE15EB7BE500256477 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; - F293B3D015EB7BE500256477 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; - F293B3D215EB7BE500256477 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; - F293B3D415EB7BE500256477 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; - F293B3D615EB7BE500256477 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; - F293B3D815EB7BE500256477 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - F293B3DA15EB7BE500256477 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; - F293B6F615EB823D00256477 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = ""; }; - F293B6F715EB823D00256477 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = ""; }; - F293B6F815EB823D00256477 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - F293B6F915EB823D00256477 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = ""; }; - F293B6FA15EB823D00256477 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = ""; }; - F293B6FB15EB823D00256477 /* TestLua_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TestLua_Prefix.pch; sourceTree = ""; }; - F293BB7E15EB831F00256477 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AppDelegate.cpp; path = ../Classes/AppDelegate.cpp; sourceTree = ""; }; - F293BB7F15EB831F00256477 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ../Classes/AppDelegate.h; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - F293B3C515EB7BE500256477 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1A6E48E817781C2B0055514D /* libBox2D.a in Frameworks */, - 1A6E48E917781C2B0055514D /* libchipmunk.a in Frameworks */, - 1A6E48EA17781C2B0055514D /* libcocos2dx.a in Frameworks */, - 1A6E48EB17781C2B0055514D /* libCocosDenshion.a in Frameworks */, - 1A6E4900177821AF0055514D /* libextensions.a in Frameworks */, - 1A6E48ED17781C2B0055514D /* libluabindings.a in Frameworks */, - F293B3CD15EB7BE500256477 /* QuartzCore.framework in Frameworks */, - F293B3CF15EB7BE500256477 /* OpenGLES.framework in Frameworks */, - F293B3D115EB7BE500256477 /* OpenAL.framework in Frameworks */, - F293B3D315EB7BE500256477 /* AudioToolbox.framework in Frameworks */, - F293B3D515EB7BE500256477 /* AVFoundation.framework in Frameworks */, - F293B3D715EB7BE500256477 /* UIKit.framework in Frameworks */, - F293B3D915EB7BE500256477 /* Foundation.framework in Frameworks */, - F293B3DB15EB7BE500256477 /* CoreGraphics.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 1A6E48F617781F9F0055514D /* script */ = { - isa = PBXGroup; - children = ( - 1A6E48F717781F9F0055514D /* AudioEngine.lua */, - 1A6E48F817781F9F0055514D /* CCBReaderLoad.lua */, - 1A6E48F917781F9F0055514D /* Cocos2dConstants.lua */, - 1A6E48FA17781F9F0055514D /* OpenglConstants.lua */, - ); - name = script; - path = ../../../../scripting/lua/script; - sourceTree = ""; - }; - F293B3BD15EB7BE500256477 = { - isa = PBXGroup; - children = ( - F293BB7C15EB830F00256477 /* Classes */, - F293B3CB15EB7BE500256477 /* Frameworks */, - F293B6E815EB807E00256477 /* Other Sources */, - F293B3C915EB7BE500256477 /* Products */, - F293BC4615EB859D00256477 /* Resources */, - ); - sourceTree = ""; - }; - F293B3C915EB7BE500256477 /* Products */ = { - isa = PBXGroup; - children = ( - F293B3C815EB7BE500256477 /* TestLua.app */, - ); - name = Products; - sourceTree = ""; - }; - F293B3CB15EB7BE500256477 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1A6E48E217781C2B0055514D /* libBox2D.a */, - 1A6E48E317781C2B0055514D /* libchipmunk.a */, - 1A6E48E417781C2B0055514D /* libcocos2dx.a */, - 1A6E48E517781C2B0055514D /* libCocosDenshion.a */, - 1A6E48FF177821AF0055514D /* libextensions.a */, - 1A6E48E717781C2B0055514D /* libluabindings.a */, - F293B3CC15EB7BE500256477 /* QuartzCore.framework */, - F293B3CE15EB7BE500256477 /* OpenGLES.framework */, - F293B3D015EB7BE500256477 /* OpenAL.framework */, - F293B3D215EB7BE500256477 /* AudioToolbox.framework */, - F293B3D415EB7BE500256477 /* AVFoundation.framework */, - F293B3D615EB7BE500256477 /* UIKit.framework */, - F293B3D815EB7BE500256477 /* Foundation.framework */, - F293B3DA15EB7BE500256477 /* CoreGraphics.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - F293B6E815EB807E00256477 /* Other Sources */ = { - isa = PBXGroup; - children = ( - F293B6F615EB823D00256477 /* AppController.h */, - F293B6F715EB823D00256477 /* AppController.mm */, - F293B6F815EB823D00256477 /* main.m */, - F293B6F915EB823D00256477 /* RootViewController.h */, - F293B6FA15EB823D00256477 /* RootViewController.mm */, - F293B6FB15EB823D00256477 /* TestLua_Prefix.pch */, - ); - name = "Other Sources"; - sourceTree = ""; - }; - F293BB7C15EB830F00256477 /* Classes */ = { - isa = PBXGroup; - children = ( - F293BB7E15EB831F00256477 /* AppDelegate.cpp */, - F293BB7F15EB831F00256477 /* AppDelegate.h */, - ); - name = Classes; - sourceTree = ""; - }; - F293BC4615EB859D00256477 /* Resources */ = { - isa = PBXGroup; - children = ( - 1A6E48F617781F9F0055514D /* script */, - 159B8A27175D9A930005B47D /* cocosbuilderRes */, - 1AD263A31683506C0089000C /* animations */, - 1AD263A41683506C0089000C /* app.icf */, - 1AD263A51683506C0089000C /* background.mp3 */, - 1AD263A61683506C0089000C /* background.ogg */, - 1AD263A71683506C0089000C /* ccb */, - 1AD263A81683506C0089000C /* CocosBuilderExample.ccbproj */, - 1AD263A91683506C0089000C /* CocosBuilderExample.ccbresourcelog */, - 1AD263AA1683506C0089000C /* development.icf */, - 1AD263AB1683506C0089000C /* effect1.raw */, - 1AD263AC1683506C0089000C /* effect1.wav */, - 1AD263AD1683506C0089000C /* effect2.ogg */, - 1AD263AE1683506C0089000C /* extensions */, - 1AD263AF1683506C0089000C /* fonts */, - 1AD263B01683506C0089000C /* fps_images.png */, - 1AD263B11683506C0089000C /* hd */, - 1AD263B21683506C0089000C /* Hello.png */, - 1AD263B31683506C0089000C /* Images */, - 1AD263B41683506C0089000C /* ipad */, - 1AD263B51683506C0089000C /* ipadhd */, - 1AD263B61683506C0089000C /* music.mid */, - 1AD263B71683506C0089000C /* Particles */, - 1AD263B81683506C0089000C /* Shaders */, - 1AD263B91683506C0089000C /* TileMaps */, - 1AD263BA1683506C0089000C /* zwoptex */, - 1AD263A1168350490089000C /* luaScript */, - 15C156911683138E00D239F2 /* Default-568h@2x.png */, - 15C156921683138E00D239F2 /* Default.png */, - 15C156931683138E00D239F2 /* Default@2x.png */, - 15C156941683138E00D239F2 /* Icon-57.png */, - 15C156951683138E00D239F2 /* Icon-72.png */, - 15C156961683138E00D239F2 /* Icon-114.png */, - 15C156971683138E00D239F2 /* Icon-144.png */, - ); - name = Resources; - path = ../../../Cpp/TestCpp/Resources; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - F293B3C715EB7BE500256477 /* TestLua */ = { - isa = PBXNativeTarget; - buildConfigurationList = F293B6C415EB7BEA00256477 /* Build configuration list for PBXNativeTarget "TestLua" */; - buildPhases = ( - F293B3C415EB7BE500256477 /* Sources */, - F293B3C515EB7BE500256477 /* Frameworks */, - F293B3C615EB7BE500256477 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = TestLua; - productName = TestLua; - productReference = F293B3C815EB7BE500256477 /* TestLua.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - F293B3BF15EB7BE500256477 /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0430; - }; - buildConfigurationList = F293B3C215EB7BE500256477 /* Build configuration list for PBXProject "TestLua" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = F293B3BD15EB7BE500256477; - productRefGroup = F293B3C915EB7BE500256477 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - F293B3C715EB7BE500256477 /* TestLua */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - F293B3C615EB7BE500256477 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 15C156981683138E00D239F2 /* Default-568h@2x.png in Resources */, - 15C156991683138E00D239F2 /* Default.png in Resources */, - 15C1569A1683138E00D239F2 /* Default@2x.png in Resources */, - 15C1569B1683138E00D239F2 /* Icon-57.png in Resources */, - 15C1569C1683138E00D239F2 /* Icon-72.png in Resources */, - 15C1569D1683138E00D239F2 /* Icon-114.png in Resources */, - 15C1569E1683138E00D239F2 /* Icon-144.png in Resources */, - 1AD263A2168350490089000C /* luaScript in Resources */, - 1AD263BB1683506D0089000C /* animations in Resources */, - 1AD263BC1683506D0089000C /* app.icf in Resources */, - 1AD263BD1683506D0089000C /* background.mp3 in Resources */, - 1AD263BE1683506D0089000C /* background.ogg in Resources */, - 1AD263BF1683506D0089000C /* ccb in Resources */, - 1AD263C01683506D0089000C /* CocosBuilderExample.ccbproj in Resources */, - 1AD263C11683506D0089000C /* CocosBuilderExample.ccbresourcelog in Resources */, - 1AD263C21683506D0089000C /* development.icf in Resources */, - 1AD263C31683506D0089000C /* effect1.raw in Resources */, - 1AD263C41683506D0089000C /* effect1.wav in Resources */, - 1AD263C51683506D0089000C /* effect2.ogg in Resources */, - 1AD263C61683506D0089000C /* extensions in Resources */, - 1AD263C71683506D0089000C /* fonts in Resources */, - 1AD263C81683506D0089000C /* fps_images.png in Resources */, - 1AD263C91683506D0089000C /* hd in Resources */, - 1AD263CA1683506D0089000C /* Hello.png in Resources */, - 1AD263CB1683506D0089000C /* Images in Resources */, - 1AD263CC1683506D0089000C /* ipad in Resources */, - 1AD263CD1683506D0089000C /* ipadhd in Resources */, - 1AD263CE1683506D0089000C /* music.mid in Resources */, - 1AD263CF1683506D0089000C /* Particles in Resources */, - 1AD263D01683506D0089000C /* Shaders in Resources */, - 1AD263D11683506D0089000C /* TileMaps in Resources */, - 1AD263D21683506D0089000C /* zwoptex in Resources */, - 159B8A28175D9A930005B47D /* cocosbuilderRes in Resources */, - 1A6E48FB17781F9F0055514D /* AudioEngine.lua in Resources */, - 1A6E48FC17781F9F0055514D /* CCBReaderLoad.lua in Resources */, - 1A6E48FD17781F9F0055514D /* Cocos2dConstants.lua in Resources */, - 1A6E48FE17781F9F0055514D /* OpenglConstants.lua in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - F293B3C415EB7BE500256477 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - F293B6FC15EB823D00256477 /* AppController.mm in Sources */, - F293B6FD15EB823D00256477 /* main.m in Sources */, - F293B6FE15EB823D00256477 /* RootViewController.mm in Sources */, - F293BB9C15EB831F00256477 /* AppDelegate.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - F293B6C215EB7BEA00256477 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - DEBUG, - "COCOS2D_DEBUG=1", - USE_FILE32API, - TARGET_OS_IPHONE, - "CC_LUA_ENGINE_ENABLED=1", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "\"$(PROJECT_NAME)/libs/cocos2dx/kazmath/include\"", - "\"$(PROJECT_NAME)/libs/cocos2dx\"", - "\"$(PROJECT_NAME)/libs/CocosDenshion/include\"", - "\"$(SDKROOT)/usr/include/libxml2\"", - "\"$(SRCROOT)/../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external/lua/tolua\"", - "\"$(SRCROOT)/../../../external/lua/src\"", - "$(SRCROOT)/../../../external/lua/cocos2dx_support", - "$(SRCROOT)/../../../cocos2dx/platform/ios", - "$(SRCROOT)/../../../cocos2dx/include", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.1; - PROVISIONING_PROFILE = ""; - "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; - SDKROOT = iphoneos; - }; - name = Debug; - }; - F293B6C315EB7BEA00256477 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_PREPROCESSOR_DEFINITIONS = ( - NDEBUG, - USE_FILE32API, - TARGET_OS_IPHONE, - "CC_LUA_ENGINE_ENABLED=1", - ); - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "\"$(PROJECT_NAME)/libs/cocos2dx/kazmath/include\"", - "\"$(PROJECT_NAME)/libs/cocos2dx\"", - "\"$(PROJECT_NAME)/libs/CocosDenshion/include\"", - "\"$(SDKROOT)/usr/include/libxml2\"", - "\"$(SRCROOT)/../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external/lua/tolua\"", - "\"$(SRCROOT)/../../../external/lua/src\"", - "$(SRCROOT)/../../../external/lua/cocos2dx_support", - "$(SRCROOT)/../../../cocos2dx/platform/ios", - "$(SRCROOT)/../../../cocos2dx/include", - ); - IPHONEOS_DEPLOYMENT_TARGET = 5.1; - OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; - PROVISIONING_PROFILE = ""; - "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; - SDKROOT = iphoneos; - }; - name = Release; - }; - F293B6C515EB7BEA00256477 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = TestLua_Prefix.pch; - GCC_PREPROCESSOR_DEFINITIONS = ( - DEBUG, - "COCOS2D_DEBUG=1", - USE_FILE32API, - CC_TARGET_OS_IPHONE, - "CC_LUA_ENGINE_ENABLED=1", - "CC_ENABLE_BOX2D_INTEGRATION=1", - ); - "GCC_THUMB_SUPPORT[arch=armv6]" = ""; - HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../CocosDenshion/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/cocos2dx_support\"", - "\"$(SRCROOT)/../../../../scripting/lua/luajit/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/tolua\"", - ); - INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios/libraries", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-lz"; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE = ""; - "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; - TARGETED_DEVICE_FAMILY = "1,2"; - WRAPPER_EXTENSION = app; - }; - name = Debug; - }; - F293B6C615EB7BEA00256477 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = YES; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = TestLua_Prefix.pch; - GCC_PREPROCESSOR_DEFINITIONS = ( - NDEBUG, - USE_FILE32API, - CC_TARGET_OS_IPHONE, - "CC_LUA_ENGINE_ENABLED=1", - "CC_ENABLE_BOX2D_INTEGRATION=1", - ); - "GCC_THUMB_SUPPORT[arch=armv6]" = ""; - HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../../cocos2dx/\"", - "\"$(SRCROOT)/../../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../../CocosDenshion/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/cocos2dx_support\"", - "\"$(SRCROOT)/../../../../scripting/lua/luajit/include\"", - "\"$(SRCROOT)/../../../../scripting/lua/tolua\"", - ); - INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(SRCROOT)/../../../../cocos2dx/platform/third_party/ios/libraries", - ); - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = "-lz"; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE = ""; - "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - WRAPPER_EXTENSION = app; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - F293B3C215EB7BE500256477 /* Build configuration list for PBXProject "TestLua" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F293B6C215EB7BEA00256477 /* Debug */, - F293B6C315EB7BEA00256477 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F293B6C415EB7BEA00256477 /* Build configuration list for PBXNativeTarget "TestLua" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F293B6C515EB7BEA00256477 /* Debug */, - F293B6C615EB7BEA00256477 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = F293B3BF15EB7BE500256477 /* Project object */; -} From 8eeb911e8f4df475d041341f35d94c30204751fe Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 15:25:45 +0800 Subject: [PATCH 126/557] issue #2905: adjust folder structure --- cocos/base/CCPlatformConfig.h | 140 ++ cocos/base/CCPlatformMacros.h | 301 ++++ cocos/base/atitc/atitc.cpp | 195 +++ cocos/base/atitc/atitc.h | 48 + cocos/base/cocoa/CCAffineTransform.cpp | 132 ++ cocos/base/cocoa/CCAffineTransform.h | 63 + cocos/base/cocoa/CCArray.cpp | 754 +++++++++ cocos/base/cocoa/CCArray.h | 557 ++++++ cocos/base/cocoa/CCAutoreleasePool.cpp | 204 +++ cocos/base/cocoa/CCAutoreleasePool.h | 181 ++ cocos/base/cocoa/CCBool.h | 70 + cocos/base/cocoa/CCData.cpp | 61 + cocos/base/cocoa/CCData.h | 88 + cocos/base/cocoa/CCDataVisitor.cpp | 240 +++ cocos/base/cocoa/CCDataVisitor.h | 117 ++ cocos/base/cocoa/CCDictionary.cpp | 454 +++++ cocos/base/cocoa/CCDictionary.h | 458 +++++ cocos/base/cocoa/CCDouble.h | 70 + cocos/base/cocoa/CCFloat.h | 71 + cocos/base/cocoa/CCGeometry.cpp | 463 +++++ cocos/base/cocoa/CCGeometry.h | 564 +++++++ cocos/base/cocoa/CCInteger.h | 79 + cocos/base/cocoa/CCNS.cpp | 185 ++ cocos/base/cocoa/CCNS.h | 80 + cocos/base/cocoa/CCObject.cpp | 93 + cocos/base/cocoa/CCObject.h | 216 +++ cocos/base/cocoa/CCSet.cpp | 166 ++ cocos/base/cocoa/CCSet.h | 119 ++ cocos/base/cocoa/CCString.cpp | 277 +++ cocos/base/cocoa/CCString.h | 210 +++ cocos/base/etc1/etc1.cpp | 670 ++++++++ cocos/base/etc1/etc1.h | 106 ++ cocos/base/s3tc/s3tc.cpp | 182 ++ cocos/base/s3tc/s3tc.h | 48 + external/tinyxml2/tinyxml2.cpp | 2101 +++++++++++++++++++++++ external/tinyxml2/tinyxml2.h | 1914 +++++++++++++++++++++ external/unzip/ioapi.cpp | 245 +++ external/unzip/ioapi.h | 201 +++ external/unzip/unzip.cpp | 2161 ++++++++++++++++++++++++ external/unzip/unzip.h | 455 +++++ 40 files changed, 14739 insertions(+) create mode 100644 cocos/base/CCPlatformConfig.h create mode 100644 cocos/base/CCPlatformMacros.h create mode 100644 cocos/base/atitc/atitc.cpp create mode 100644 cocos/base/atitc/atitc.h create mode 100644 cocos/base/cocoa/CCAffineTransform.cpp create mode 100644 cocos/base/cocoa/CCAffineTransform.h create mode 100644 cocos/base/cocoa/CCArray.cpp create mode 100644 cocos/base/cocoa/CCArray.h create mode 100644 cocos/base/cocoa/CCAutoreleasePool.cpp create mode 100644 cocos/base/cocoa/CCAutoreleasePool.h create mode 100644 cocos/base/cocoa/CCBool.h create mode 100644 cocos/base/cocoa/CCData.cpp create mode 100644 cocos/base/cocoa/CCData.h create mode 100644 cocos/base/cocoa/CCDataVisitor.cpp create mode 100644 cocos/base/cocoa/CCDataVisitor.h create mode 100644 cocos/base/cocoa/CCDictionary.cpp create mode 100644 cocos/base/cocoa/CCDictionary.h create mode 100644 cocos/base/cocoa/CCDouble.h create mode 100644 cocos/base/cocoa/CCFloat.h create mode 100644 cocos/base/cocoa/CCGeometry.cpp create mode 100644 cocos/base/cocoa/CCGeometry.h create mode 100644 cocos/base/cocoa/CCInteger.h create mode 100644 cocos/base/cocoa/CCNS.cpp create mode 100644 cocos/base/cocoa/CCNS.h create mode 100644 cocos/base/cocoa/CCObject.cpp create mode 100644 cocos/base/cocoa/CCObject.h create mode 100644 cocos/base/cocoa/CCSet.cpp create mode 100644 cocos/base/cocoa/CCSet.h create mode 100644 cocos/base/cocoa/CCString.cpp create mode 100644 cocos/base/cocoa/CCString.h create mode 100644 cocos/base/etc1/etc1.cpp create mode 100644 cocos/base/etc1/etc1.h create mode 100644 cocos/base/s3tc/s3tc.cpp create mode 100644 cocos/base/s3tc/s3tc.h create mode 100644 external/tinyxml2/tinyxml2.cpp create mode 100644 external/tinyxml2/tinyxml2.h create mode 100644 external/unzip/ioapi.cpp create mode 100644 external/unzip/ioapi.h create mode 100644 external/unzip/unzip.cpp create mode 100644 external/unzip/unzip.h diff --git a/cocos/base/CCPlatformConfig.h b/cocos/base/CCPlatformConfig.h new file mode 100644 index 0000000000..5ba0757dac --- /dev/null +++ b/cocos/base/CCPlatformConfig.h @@ -0,0 +1,140 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __CC_PLATFORM_CONFIG_H__ +#define __CC_PLATFORM_CONFIG_H__ + +/** +Config of cocos2d-x project, per target platform. +*/ + +////////////////////////////////////////////////////////////////////////// +// pre configure +////////////////////////////////////////////////////////////////////////// + +// define supported target platform macro which CC uses. +#define CC_PLATFORM_UNKNOWN 0 +#define CC_PLATFORM_IOS 1 +#define CC_PLATFORM_ANDROID 2 +#define CC_PLATFORM_WIN32 3 +#define CC_PLATFORM_MARMALADE 4 +#define CC_PLATFORM_LINUX 5 +#define CC_PLATFORM_BADA 6 +#define CC_PLATFORM_BLACKBERRY 7 +#define CC_PLATFORM_MAC 8 +#define CC_PLATFORM_NACL 9 +#define CC_PLATFORM_EMSCRIPTEN 10 +#define CC_PLATFORM_TIZEN 11 +#define CC_PLATFORM_QT5 12 + +// Determine target platform by compile environment macro. +#define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN + +// mac +#if defined(CC_TARGET_OS_MAC) +#undef CC_TARGET_PLATFORM +#define CC_TARGET_PLATFORM CC_PLATFORM_MAC +#endif + +// iphone +#if defined(CC_TARGET_OS_IPHONE) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_IOS +#endif + +// android +#if defined(ANDROID) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID +#endif + +// win32 +#if defined(WIN32) && defined(_WINDOWS) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_WIN32 +#endif + +// linux +#if defined(LINUX) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_LINUX +#endif + +// marmalade +#if defined(MARMALADE) +#undef CC_TARGET_PLATFORM +#define CC_TARGET_PLATFORM CC_PLATFORM_MARMALADE +#endif + +// bada +#if defined(SHP) +#undef CC_TARGET_PLATFORM +#define CC_TARGET_PLATFORM CC_PLATFORM_BADA +#endif + +// qnx +#if defined(__QNX__) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_BLACKBERRY +#endif + +// native client +#if defined(__native_client__) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_NACL +#endif + +// Emscripten +#if defined(EMSCRIPTEN) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_EMSCRIPTEN +#endif + +// tizen +#if defined(TIZEN) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_TIZEN +#endif + +// qt5 +#if defined(CC_TARGET_QT5) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_QT5 +#endif + +////////////////////////////////////////////////////////////////////////// +// post configure +////////////////////////////////////////////////////////////////////////// + +// check user set platform +#if ! CC_TARGET_PLATFORM + #error "Cannot recognize the target platform; are you targeting an unsupported platform?" +#endif + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +#pragma warning (disable:4127) +#endif // CC_PLATFORM_WIN32 + +#endif // __CC_PLATFORM_CONFIG_H__ + diff --git a/cocos/base/CCPlatformMacros.h b/cocos/base/CCPlatformMacros.h new file mode 100644 index 0000000000..fca1255c0d --- /dev/null +++ b/cocos/base/CCPlatformMacros.h @@ -0,0 +1,301 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#ifndef __CC_PLATFORM_MACROS_H__ +#define __CC_PLATFORM_MACROS_H__ + +/** + * define some platform specific macros + */ +#include "ccConfig.h" +#include "CCPlatformConfig.h" +#include "CCPlatformDefine.h" + +/** + * define a create function for a specific type, such as Layer + * @param \__TYPE__ class type to add create(), such as Layer + */ +#define CREATE_FUNC(__TYPE__) \ +static __TYPE__* create() \ +{ \ + __TYPE__ *pRet = new __TYPE__(); \ + if (pRet && pRet->init()) \ + { \ + pRet->autorelease(); \ + return pRet; \ + } \ + else \ + { \ + delete pRet; \ + pRet = NULL; \ + return NULL; \ + } \ +} + +/** + * define a node function for a specific type, such as Layer + * @param \__TYPE__ class type to add node(), such as Layer + * @deprecated This interface will be deprecated sooner or later. + */ +#define NODE_FUNC(__TYPE__) \ +CC_DEPRECATED_ATTRIBUTE static __TYPE__* node() \ +{ \ + __TYPE__ *pRet = new __TYPE__(); \ + if (pRet && pRet->init()) \ + { \ + pRet->autorelease(); \ + return pRet; \ + } \ + else \ + { \ + delete pRet; \ + pRet = NULL; \ + return NULL; \ + } \ +} + +/** @def CC_ENABLE_CACHE_TEXTURE_DATA +Enable it if you want to cache the texture data. +Not enabling for Emscripten any more -- doesn't seem necessary and don't want +to be different from other platforms unless there's a good reason. + +It's new in cocos2d-x since v0.99.5 +*/ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + #define CC_ENABLE_CACHE_TEXTURE_DATA 1 +#else + #define CC_ENABLE_CACHE_TEXTURE_DATA 0 +#endif + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) + /* Application will crash in glDrawElements function on some win32 computers and some android devices. + Indices should be bound again while drawing to avoid this bug. + */ + #define CC_REBIND_INDICES_BUFFER 1 +#else + #define CC_REBIND_INDICES_BUFFER 0 +#endif + +// generic macros + +// namespace cocos2d {} +#ifdef __cplusplus + #define NS_CC_BEGIN namespace cocos2d { + #define NS_CC_END } + #define USING_NS_CC using namespace cocos2d +#else + #define NS_CC_BEGIN + #define NS_CC_END + #define USING_NS_CC +#endif + +/** CC_PROPERTY_READONLY is used to declare a protected variable. + We can use getter to read the variable. + @param varType the type of variable. + @param varName variable name. + @param funName "get + funName" will be the name of the getter. + @warning The getter is a public virtual function, you should rewrite it first. + The variables and methods declared after CC_PROPERTY_READONLY are all public. + If you need protected or private, please declare. + */ +#define CC_PROPERTY_READONLY(varType, varName, funName)\ +protected: varType varName;\ +public: virtual varType get##funName(void) const; + +#define CC_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName)\ +protected: varType varName;\ +public: virtual const varType& get##funName(void) const; + +/** CC_PROPERTY is used to declare a protected variable. + We can use getter to read the variable, and use the setter to change the variable. + @param varType the type of variable. + @param varName variable name. + @param funName "get + funName" will be the name of the getter. + "set + funName" will be the name of the setter. + @warning The getter and setter are public virtual functions, you should rewrite them first. + The variables and methods declared after CC_PROPERTY are all public. + If you need protected or private, please declare. + */ +#define CC_PROPERTY(varType, varName, funName)\ +protected: varType varName;\ +public: virtual varType get##funName(void);\ +public: virtual void set##funName(varType var); + +#define CC_PROPERTY_PASS_BY_REF(varType, varName, funName)\ +protected: varType varName;\ +public: virtual const varType& get##funName(void) const;\ +public: virtual void set##funName(const varType& var); + +/** CC_SYNTHESIZE_READONLY is used to declare a protected variable. + We can use getter to read the variable. + @param varType the type of variable. + @param varName variable name. + @param funName "get + funName" will be the name of the getter. + @warning The getter is a public inline function. + The variables and methods declared after CC_SYNTHESIZE_READONLY are all public. + If you need protected or private, please declare. + */ +#define CC_SYNTHESIZE_READONLY(varType, varName, funName)\ +protected: varType varName;\ +public: virtual varType get##funName(void) const { return varName; } + +#define CC_SYNTHESIZE_READONLY_PASS_BY_REF(varType, varName, funName)\ +protected: varType varName;\ +public: virtual const varType& get##funName(void) const { return varName; } + +/** CC_SYNTHESIZE is used to declare a protected variable. + We can use getter to read the variable, and use the setter to change the variable. + @param varType the type of variable. + @param varName variable name. + @param funName "get + funName" will be the name of the getter. + "set + funName" will be the name of the setter. + @warning The getter and setter are public inline functions. + The variables and methods declared after CC_SYNTHESIZE are all public. + If you need protected or private, please declare. + */ +#define CC_SYNTHESIZE(varType, varName, funName)\ +protected: varType varName;\ +public: virtual varType get##funName(void) const { return varName; }\ +public: virtual void set##funName(varType var){ varName = var; } + +#define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\ +protected: varType varName;\ +public: virtual const varType& get##funName(void) const { return varName; }\ +public: virtual void set##funName(const varType& var){ varName = var; } + +#define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \ +private: varType varName; \ +public: virtual varType get##funName(void) const { return varName; } \ +public: virtual void set##funName(varType var) \ +{ \ + if (varName != var) \ + { \ + CC_SAFE_RETAIN(var); \ + CC_SAFE_RELEASE(varName); \ + varName = var; \ + } \ +} + +#define CC_SAFE_DELETE(p) do { delete (p); (p) = nullptr; } while(0) +#define CC_SAFE_DELETE_ARRAY(p) do { if(p) { delete[] (p); (p) = nullptr; } } while(0) +#define CC_SAFE_FREE(p) do { if(p) { free(p); (p) = nullptr; } } while(0) +#define CC_SAFE_RELEASE(p) do { if(p) { (p)->release(); } } while(0) +#define CC_SAFE_RELEASE_NULL(p) do { if(p) { (p)->release(); (p) = nullptr; } } while(0) +#define CC_SAFE_RETAIN(p) do { if(p) { (p)->retain(); } } while(0) +#define CC_BREAK_IF(cond) if(cond) break + +#define __CCLOGWITHFUNCTION(s, ...) \ + log("%s : %s",__FUNCTION__, String::createWithFormat(s, ##__VA_ARGS__)->getCString()) + +// cocos2d debug +#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 +#define CCLOG(...) do {} while (0) +#define CCLOGINFO(...) do {} while (0) +#define CCLOGERROR(...) do {} while (0) +#define CCLOGWARN(...) do {} while (0) + +#elif COCOS2D_DEBUG == 1 +#define CCLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) +#define CCLOGERROR(format,...) cocos2d::log(format, ##__VA_ARGS__) +#define CCLOGINFO(format,...) do {} while (0) +#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) + +#elif COCOS2D_DEBUG > 1 +#define CCLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) +#define CCLOGERROR(format,...) cocos2d::log(format, ##__VA_ARGS__) +#define CCLOGINFO(format,...) cocos2d::log(format, ##__VA_ARGS__) +#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) +#endif // COCOS2D_DEBUG + +// Lua engine debug +#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 || CC_LUA_ENGINE_DEBUG == 0 +#define LUALOG(...) +#else +#define LUALOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) +#endif // Lua engine debug + +#if defined(__GNUC__) && ((__GNUC__ >= 5) || ((__GNUG__ == 4) && (__GNUC_MINOR__ >= 4))) \ + || (defined(__clang__) && (__clang_major__ >= 3)) +#define CC_DISABLE_COPY(Class) \ +private: \ + Class(const Class &) = delete; \ + Class &operator =(const Class &) = delete; +#else +#define CC_DISABLE_COPY(Class) \ +private: \ + Class(const Class &); \ + Class &operator =(const Class &); +#endif + +/* + * only certain compilers support __attribute__((deprecated)) + */ +#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) + #define CC_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#elif _MSC_VER >= 1400 //vs 2005 or higher + #define CC_DEPRECATED_ATTRIBUTE __declspec(deprecated) +#else + #define CC_DEPRECATED_ATTRIBUTE +#endif + +/* + * only certain compiler support __attribute__((format)) + * formatPos - 1-based position of format string argument + * argPos - 1-based position of first format-dependent argument + */ +#if defined(__GNUC__) && (__GNUC__ >= 4) +#define CC_FORMAT_PRINTF(formatPos, argPos) __attribute__((__format__(printf, formatPos, argPos))) +#elif defined(__has_attribute) + #if __has_attribute(format) + #define CC_FORMAT_PRINTF(formatPos, argPos) __attribute__((__format__(printf, formatPos, argPos))) + #endif // __has_attribute(format) +#else +#define CC_FORMAT_PRINTF(formatPos, argPos) +#endif + +#if defined(_MSC_VER) +#define CC_FORMAT_PRINTF_SIZE_T "%08lX" +#else +#define CC_FORMAT_PRINTF_SIZE_T "%08zX" +#endif + +#ifdef __GNUC__ +#define CC_UNUSED __attribute__ ((unused)) +#else +#define CC_UNUSED +#endif + +// +// CC_REQUIRES_NULL_TERMINATION +// +#if !defined(CC_REQUIRES_NULL_TERMINATION) + #if defined(__APPLE_CC__) && (__APPLE_CC__ >= 5549) + #define CC_REQUIRES_NULL_TERMINATION __attribute__((sentinel(0,1))) + #elif defined(__GNUC__) + #define CC_REQUIRES_NULL_TERMINATION __attribute__((sentinel)) + #else + #define CC_REQUIRES_NULL_TERMINATION + #endif +#endif + +#endif // __CC_PLATFORM_MACROS_H__ diff --git a/cocos/base/atitc/atitc.cpp b/cocos/base/atitc/atitc.cpp new file mode 100644 index 0000000000..3a60d6d2f7 --- /dev/null +++ b/cocos/base/atitc/atitc.cpp @@ -0,0 +1,195 @@ +/**************************************************************************** + 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 "atitc.h" + +//Decode ATITC encode block to 4x4 RGB32 pixels +static void atitc_decode_block(uint8_t **blockData, + uint32_t *decodeBlockData, + unsigned int stride, + bool oneBitAlphaFlag, + uint64_t alpha, + ATITCDecodeFlag decodeFlag) +{ + unsigned int colorValue0 = 0 , colorValue1 = 0, initAlpha = (!oneBitAlphaFlag * 255u) << 24; + unsigned int rb0 = 0, rb1 = 0, rb2 = 0, rb3 = 0, g0 = 0, g1 = 0, g2 = 0, g3 = 0; + bool msb = 0; + + uint32_t colors[4], pixelsIndex = 0; + + /* load the two color values*/ + memcpy((void *)&colorValue0, *blockData, 2); + (*blockData) += 2; + + memcpy((void *)&colorValue1, *blockData, 2); + (*blockData) += 2; + + //extract the msb flag + msb = (colorValue0 & 0x8000) != 0; + + /* the channel is r5g6b5 , 16 bits */ + rb0 = (colorValue0 << 3 | colorValue0 << 9) & 0xf800f8; + rb1 = (colorValue1 << 3 | colorValue1 << 8) & 0xf800f8; + g0 = (colorValue0 << 6) & 0x00fc00; + g1 = (colorValue1 << 5) & 0x00fc00; + g0 += (g0 >> 6) & 0x000300; + g1 += (g1 >> 6) & 0x000300; + + /* interpolate the other two color values */ + if (!msb) + { + colors[0] = rb0 + g0 + initAlpha; + colors[3] = rb1 + g1 + initAlpha; + + rb2 = (((2*rb0 + rb1) * 21) >> 6) & 0xff00ff; + rb3 = (((2*rb1 + rb0) * 21) >> 6) & 0xff00ff; + g2 = (((2*g0 + g1 ) * 21) >> 6) & 0x00ff00; + g3 = (((2*g1 + g0 ) * 21) >> 6) & 0x00ff00; + + colors[2] = rb3 + g3 + initAlpha; + colors[1] = rb2 + g2 + initAlpha; + } + else + { + colors[2] = rb0 + g0 + initAlpha; + colors[3] = rb1 + g1 + initAlpha; + + rb2 = (rb0 - (rb1 >> 2)) & 0xff00ff; + g2 = (g0 - (g1 >> 2)) & 0x00ff00; + colors[0] = 0 ; + + colors[1] = rb2 + g2 + initAlpha; + } + + /*read the pixelsIndex , 2bits per pixel, 4 bytes */ + memcpy((void*)&pixelsIndex, *blockData, 4); + (*blockData) += 4; + + if (ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA == decodeFlag) + { + // atitc_interpolated_alpha use interpolate alpha + // 8-Alpha block: derive the other six alphas. + // Bit code 000 = alpha0, 001 = alpha1, other are interpolated. + + unsigned int alphaArray[8]; + + alphaArray[0] = (alpha ) & 0xff ; + alphaArray[1] = (alpha >> 8) & 0xff ; + + if (alphaArray[0] >= alphaArray[1]) + { + alphaArray[2] = (alphaArray[0]*6 + alphaArray[1]*1) / 7; + alphaArray[3] = (alphaArray[0]*5 + alphaArray[1]*2) / 7; + alphaArray[4] = (alphaArray[0]*4 + alphaArray[1]*3) / 7; + alphaArray[5] = (alphaArray[0]*3 + alphaArray[1]*4) / 7; + alphaArray[6] = (alphaArray[0]*2 + alphaArray[1]*5) / 7; + alphaArray[7] = (alphaArray[0]*1 + alphaArray[1]*6) / 7; + } + else if (alphaArray[0] < alphaArray[1]) + { + alphaArray[2] = (alphaArray[0]*4 + alphaArray[1]*1) / 5; + alphaArray[3] = (alphaArray[0]*3 + alphaArray[1]*2) / 5; + alphaArray[4] = (alphaArray[0]*2 + alphaArray[1]*3) / 5; + alphaArray[5] = (alphaArray[0]*1 + alphaArray[1]*4) / 5; + alphaArray[6] = 0; + alphaArray[7] = 255; + } + + // read the flowing 48bit indices (16*3) + alpha >>= 16; + + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 4; ++x) + { + decodeBlockData[x] = (alphaArray[alpha & 5] << 24) + colors[pixelsIndex & 3]; + pixelsIndex >>= 2; + alpha >>= 3; + } + decodeBlockData += stride; + } + } //if (atc_interpolated_alpha == comFlag) + else + { + /* atc_rgb atc_explicit_alpha use explicit alpha */ + + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 4; ++x) + { + initAlpha = (alpha & 0x0f) << 28; + initAlpha += initAlpha >> 4; + decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; + pixelsIndex >>= 2; + alpha >>= 4; + } + decodeBlockData += stride; + } + } +} + +//Decode ATITC encode data to RGB32 +void atitc_decode(uint8_t *encodeData, //in_data + uint8_t *decodeData, //out_data + const int pixelsWidth, + const int pixelsHeight, + ATITCDecodeFlag decodeFlag) +{ + uint32_t *decodeBlockData = (uint32_t *)decodeData; + + for (int block_y = 0; block_y < pixelsHeight / 4; ++block_y, decodeBlockData += 3 * pixelsWidth) //stride = 3*width + { + for (int block_x = 0; block_x < pixelsWidth / 4; ++block_x, decodeBlockData += 4) //skip 4 pixels + { + uint64_t blockAlpha = 0; + + switch (decodeFlag) + { + case ATITCDecodeFlag::ATC_RGB: + { + atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 0, 0LL, ATITCDecodeFlag::ATC_RGB); + } + break; + case ATITCDecodeFlag::ATC_EXPLICIT_ALPHA: + { + memcpy((void *)&blockAlpha, encodeData, 8); + encodeData += 8; + atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA); + } + break; + case ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA: + { + memcpy((void *)&blockAlpha, encodeData, 8); + encodeData += 8; + atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA); + } + break; + default: + break; + }//switch + }//for block_x + }//for block_y +} + + diff --git a/cocos/base/atitc/atitc.h b/cocos/base/atitc/atitc.h new file mode 100644 index 0000000000..72bfd32a8c --- /dev/null +++ b/cocos/base/atitc/atitc.h @@ -0,0 +1,48 @@ +/**************************************************************************** + 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 COCOS2DX_PLATFORM_THIRDPARTY_ATITC_ +#define COCOS2DX_PLATFORM_THIRDPARTY_ATITC_ + +#include "CCStdC.h" + +enum class ATITCDecodeFlag +{ + ATC_RGB = 1, + ATC_EXPLICIT_ALPHA = 3, + ATC_INTERPOLATED_ALPHA = 5, +}; + +//Decode ATITC encode data to RGB32 +void atitc_decode(uint8_t *encode_data, + uint8_t *decode_data, + const int pixelsWidth, + const int pixelsHeight, + ATITCDecodeFlag decodeFlag + ); + + +#endif /* defined(COCOS2DX_PLATFORM_THIRDPARTY_ATITC_) */ + diff --git a/cocos/base/cocoa/CCAffineTransform.cpp b/cocos/base/cocoa/CCAffineTransform.cpp new file mode 100644 index 0000000000..2e39f344cc --- /dev/null +++ b/cocos/base/cocoa/CCAffineTransform.cpp @@ -0,0 +1,132 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "CCAffineTransform.h" +#include +#include + +using namespace std; + + +NS_CC_BEGIN + +AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty) +{ + AffineTransform t; + t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty; + return t; +} + +Point __CCPointApplyAffineTransform(const Point& point, const AffineTransform& t) +{ + Point p; + p.x = (float)((double)t.a * point.x + (double)t.c * point.y + t.tx); + p.y = (float)((double)t.b * point.x + (double)t.d * point.y + t.ty); + return p; +} + +Size __CCSizeApplyAffineTransform(const Size& size, const AffineTransform& t) +{ + Size s; + s.width = (float)((double)t.a * size.width + (double)t.c * size.height); + s.height = (float)((double)t.b * size.width + (double)t.d * size.height); + return s; +} + + +AffineTransform AffineTransformMakeIdentity() +{ + return __CCAffineTransformMake(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); +} + +extern const AffineTransform AffineTransformIdentity = AffineTransformMakeIdentity(); +const AffineTransform AffineTransform::IDENTITY = AffineTransformMakeIdentity(); + +Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform) +{ + float top = rect.getMinY(); + float left = rect.getMinX(); + float right = rect.getMaxX(); + float bottom = rect.getMaxY(); + + Point topLeft = PointApplyAffineTransform(Point(left, top), anAffineTransform); + Point topRight = PointApplyAffineTransform(Point(right, top), anAffineTransform); + Point bottomLeft = PointApplyAffineTransform(Point(left, bottom), anAffineTransform); + Point bottomRight = PointApplyAffineTransform(Point(right, bottom), anAffineTransform); + + float minX = min(min(topLeft.x, topRight.x), min(bottomLeft.x, bottomRight.x)); + float maxX = max(max(topLeft.x, topRight.x), max(bottomLeft.x, bottomRight.x)); + float minY = min(min(topLeft.y, topRight.y), min(bottomLeft.y, bottomRight.y)); + float maxY = max(max(topLeft.y, topRight.y), max(bottomLeft.y, bottomRight.y)); + + return Rect(minX, minY, (maxX - minX), (maxY - minY)); +} + +AffineTransform AffineTransformTranslate(const AffineTransform& t, float tx, float ty) +{ + return __CCAffineTransformMake(t.a, t.b, t.c, t.d, t.tx + t.a * tx + t.c * ty, t.ty + t.b * tx + t.d * ty); +} + +AffineTransform AffineTransformScale(const AffineTransform& t, float sx, float sy) +{ + return __CCAffineTransformMake(t.a * sx, t.b * sx, t.c * sy, t.d * sy, t.tx, t.ty); +} + +AffineTransform AffineTransformRotate(const AffineTransform& t, float anAngle) +{ + float sine = sinf(anAngle); + float cosine = cosf(anAngle); + + return __CCAffineTransformMake( t.a * cosine + t.c * sine, + t.b * cosine + t.d * sine, + t.c * cosine - t.a * sine, + t.d * cosine - t.b * sine, + t.tx, + t.ty); +} + +/* Concatenate `t2' to `t1' and return the result: + t' = t1 * t2 */ +AffineTransform AffineTransformConcat(const AffineTransform& t1, const AffineTransform& t2) +{ + return __CCAffineTransformMake( t1.a * t2.a + t1.b * t2.c, t1.a * t2.b + t1.b * t2.d, //a,b + t1.c * t2.a + t1.d * t2.c, t1.c * t2.b + t1.d * t2.d, //c,d + t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx + t1.tx * t2.b + t1.ty * t2.d + t2.ty); //ty +} + +/* Return true if `t1' and `t2' are equal, false otherwise. */ +bool AffineTransformEqualToTransform(const AffineTransform& t1, const AffineTransform& t2) +{ + return (t1.a == t2.a && t1.b == t2.b && t1.c == t2.c && t1.d == t2.d && t1.tx == t2.tx && t1.ty == t2.ty); +} + +AffineTransform AffineTransformInvert(const AffineTransform& t) +{ + float determinant = 1 / (t.a * t.d - t.b * t.c); + + return __CCAffineTransformMake(determinant * t.d, -determinant * t.b, -determinant * t.c, determinant * t.a, + determinant * (t.c * t.ty - t.d * t.tx), determinant * (t.b * t.tx - t.a * t.ty) ); +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCAffineTransform.h b/cocos/base/cocoa/CCAffineTransform.h new file mode 100644 index 0000000000..667b5d9b46 --- /dev/null +++ b/cocos/base/cocoa/CCAffineTransform.h @@ -0,0 +1,63 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __COCOA_CGAFFINETRANSFORM_H__ +#define __COCOA_CGAFFINETRANSFORM_H__ + +#include "CCGeometry.h" +#include "platform/CCPlatformMacros.h" + +NS_CC_BEGIN + +struct AffineTransform { + float a, b, c, d; + float tx, ty; + + static const AffineTransform IDENTITY; +}; + +CC_DLL AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty); +#define AffineTransformMake __CCAffineTransformMake + +CC_DLL Point __CCPointApplyAffineTransform(const Point& point, const AffineTransform& t); +#define PointApplyAffineTransform __CCPointApplyAffineTransform + +CC_DLL Size __CCSizeApplyAffineTransform(const Size& size, const AffineTransform& t); +#define SizeApplyAffineTransform __CCSizeApplyAffineTransform + +CC_DLL AffineTransform AffineTransformMakeIdentity(); +CC_DLL Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform); + +CC_DLL AffineTransform AffineTransformTranslate(const AffineTransform& t, float tx, float ty); +CC_DLL AffineTransform AffineTransformRotate(const AffineTransform& aTransform, float anAngle); +CC_DLL AffineTransform AffineTransformScale(const AffineTransform& t, float sx, float sy); +CC_DLL AffineTransform AffineTransformConcat(const AffineTransform& t1, const AffineTransform& t2); +CC_DLL bool AffineTransformEqualToTransform(const AffineTransform& t1, const AffineTransform& t2); +CC_DLL AffineTransform AffineTransformInvert(const AffineTransform& t); + +extern CC_DLL const AffineTransform AffineTransformIdentity; + +NS_CC_END + +#endif // __COCOA_CGAFFINETRANSFORM_H__ diff --git a/cocos/base/cocoa/CCArray.cpp b/cocos/base/cocoa/CCArray.cpp new file mode 100644 index 0000000000..3a55d6050d --- /dev/null +++ b/cocos/base/cocoa/CCArray.cpp @@ -0,0 +1,754 @@ +/**************************************************************************** +Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "CCArray.h" +#include "CCString.h" +#include "platform/CCFileUtils.h" + +NS_CC_BEGIN + + +#if CC_USE_ARRAY_VECTOR + +// ---------------------------------------------------------------------------------- +// std::vector implementation +// ---------------------------------------------------------------------------------- + +Array::Array() +: data(NULL) +{ + init(); +} + +Array* Array::create() +{ + Array* array = new Array(); + + if (array && array->initWithCapacity(7)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::createWithObject(Object* object) +{ + Array* array = new Array(); + + if (array && array->initWithObject(object)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::create(Object* object, ...) +{ + va_list args; + va_start(args,object); + + Array* array = create(); + if (array && object) + { + array->addObject(object); + Object *i = va_arg(args, Object*); + while (i) + { + array->addObject(i); + i = va_arg(args, Object*); + } + } + else + { + CC_SAFE_DELETE(array); + } + + va_end(args); + + return array; +} + +Array* Array::createWithArray(Array* otherArray) +{ + return otherArray->clone(); +} + +Array* Array::createWithCapacity(int capacity) +{ + CCASSERT(capacity>=0, "Invalid capacity"); + + Array* array = new Array(); + + if (array && array->initWithCapacity(capacity)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::createWithContentsOfFile(const char* fileName) +{ + Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + if (ret != nullptr) + { + ret->autorelease(); + } + return ret; +} + +Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +{ + return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); +} + +bool Array::init() +{ + return initWithCapacity(7); +} + +bool Array::initWithObject(Object* object) +{ + bool ret = initWithCapacity(7); + if (ret) + { + addObject(object); + } + return ret; +} + +/** Initializes an array with some objects */ +bool Array::initWithObjects(Object* object, ...) +{ + bool ret = false; + do + { + CC_BREAK_IF(object == nullptr); + + va_list args; + va_start(args, object); + + if (object) + { + this->addObject(object); + Object* i = va_arg(args, Object*); + while (i) + { + this->addObject(i); + i = va_arg(args, Object*); + } + ret = true; + } + va_end(args); + + } while (false); + + return ret; +} + +bool Array::initWithCapacity(int capacity) +{ + CCASSERT(capacity>=0, "Invalid capacity"); + + data.reserve(capacity); + return true; +} + +bool Array::initWithArray(Array* otherArray) +{ + data = otherArray->data; + return true; +} + +int Array::getIndexOfObject(Object* object) const +{ + auto it = data.begin(); + + for (int i = 0; it != data.end(); ++it, ++i) + { + if (it->get() == object) + { + return i; + } + } + + return -1; +} + +Object* Array::getRandomObject() +{ + if (data.size()==0) + { + return nullptr; + } + + float r = CCRANDOM_0_1(); + + if (r == 1) // to prevent from accessing data-arr[data->num], out of range. + { + r = 0; + } + + r *= data.size(); + + return data[r].get(); +} + +bool Array::containsObject(Object* object) const +{ + int i = this->getIndexOfObject(object); + return (i >=0); +} + +bool Array::isEqualToArray(Array* otherArray) +{ + for (int i = 0; i< this->count(); i++) + { + if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) + { + return false; + } + } + return true; +} + +void Array::addObject(Object* object) +{ + data.push_back( RCPtr(object) ); +} + +void Array::addObjectsFromArray(Array* otherArray) +{ + data.insert(data.end(), otherArray->data.begin(), otherArray->data.end()); +} + +void Array::insertObject(Object* object, int index) +{ + data.insert( std::begin(data) + index, RCPtr(object) ); +} + +void Array::setObject(Object* object, int index) +{ + data[index] = RCPtr(object); +} + +void Array::removeLastObject(bool releaseObj) +{ + CCASSERT(data.size(), "no objects added"); + data.pop_back(); +} + +void Array::removeObject(Object* object, bool releaseObj /* ignored */) +{ + data.erase( std::remove( data.begin(), data.end(), object ) ); +} + +void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) +{ + auto obj = data[index]; + data.erase( data.begin() + index ); +} + +void Array::removeObjectsInArray(Array* otherArray) +{ + CCASSERT(false, "not implemented"); +} + +void Array::removeAllObjects() +{ + data.erase(std::begin(data), std::end(data)); +} + +void Array::fastRemoveObjectAtIndex(int index) +{ + removeObjectAtIndex(index); +} + +void Array::fastRemoveObject(Object* object) +{ + removeObject(object); +} + +void Array::exchangeObject(Object* object1, Object* object2) +{ + int idx1 = getIndexOfObject(object1); + int idx2 = getIndexOfObject(object2); + + CCASSERT(idx1>=0 && idx2>=2, "invalid object index"); + + std::swap( data[idx1], data[idx2] ); +} + +void Array::exchangeObjectAtIndex(int index1, int index2) +{ + std::swap( data[index1], data[index2] ); +} + +void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) +{ + data[index] = object; +} + +void Array::reverseObjects() +{ + std::reverse( std::begin(data), std::end(data) ); +} + +void Array::reduceMemoryFootprint() +{ + // N/A +} + +Array::~Array() +{ + CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); +} + +Array* Array::clone() const +{ + Array* ret = new Array(); + ret->autorelease(); + ret->initWithCapacity(this->data.size() > 0 ? this->data.size() : 1); + + Object* obj = nullptr; + Object* tmpObj = nullptr; + Clonable* clonable = nullptr; + CCARRAY_FOREACH(this, obj) + { + clonable = dynamic_cast(obj); + if (clonable) + { + tmpObj = dynamic_cast(clonable->clone()); + if (tmpObj) + { + ret->addObject(tmpObj); + } + } + else + { + CCLOGWARN("%s isn't clonable.", typeid(*obj).name()); + } + } + return ret; +} + +void Array::acceptVisitor(DataVisitor &visitor) +{ + visitor.visit(this); +} + +// ---------------------------------------------------------------------------------- +// ccArray implementation +// ---------------------------------------------------------------------------------- + +#else + +Array::Array() +: data(nullptr) +{ +// init(); +} + +Array* Array::create() +{ + Array* array = new Array(); + + if (array && array->initWithCapacity(7)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::createWithObject(Object* object) +{ + Array* array = new Array(); + + if (array && array->initWithObject(object)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::create(Object* object, ...) +{ + va_list args; + va_start(args,object); + + Array* array = create(); + if (array && object) + { + array->addObject(object); + Object *i = va_arg(args, Object*); + while (i) + { + array->addObject(i); + i = va_arg(args, Object*); + } + } + else + { + CC_SAFE_DELETE(array); + } + + va_end(args); + + return array; +} + +Array* Array::createWithArray(Array* otherArray) +{ + return otherArray->clone(); +} + +Array* Array::createWithCapacity(int capacity) +{ + CCASSERT(capacity>=0, "Invalid capacity"); + + Array* array = new Array(); + + if (array && array->initWithCapacity(capacity)) + { + array->autorelease(); + } + else + { + CC_SAFE_DELETE(array); + } + + return array; +} + +Array* Array::createWithContentsOfFile(const char* fileName) +{ + Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + if (ret != nullptr) + { + ret->autorelease(); + } + return ret; +} + +Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +{ + return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); +} + +bool Array::init() +{ + CCASSERT(!data, "Array cannot be re-initialized"); + + return initWithCapacity(7); +} + +bool Array::initWithObject(Object* object) +{ + CCASSERT(!data, "Array cannot be re-initialized"); + + bool ret = initWithCapacity(7); + if (ret) + { + addObject(object); + } + return ret; +} + +/** Initializes an array with some objects */ +bool Array::initWithObjects(Object* object, ...) +{ + CCASSERT(!data, "Array cannot be re-initialized"); + + bool ret = false; + do + { + CC_BREAK_IF(object == nullptr); + + va_list args; + va_start(args, object); + + if (object) + { + this->addObject(object); + Object* i = va_arg(args, Object*); + while (i) + { + this->addObject(i); + i = va_arg(args, Object*); + } + ret = true; + } + va_end(args); + + } while (false); + + return ret; +} + +bool Array::initWithCapacity(int capacity) +{ + CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); + + data = ccArrayNew(capacity); + return true; +} + +bool Array::initWithArray(Array* otherArray) +{ + CCASSERT(!data, "Array cannot be re-initialized"); + + bool ret = false; + do + { + CC_BREAK_IF(! initWithCapacity(otherArray->data->num)); + + addObjectsFromArray(otherArray); + ret = true; + } while (0); + + return ret; +} + +int Array::getIndexOfObject(Object* object) const +{ + return ccArrayGetIndexOfObject(data, object); +} + +Object* Array::getRandomObject() +{ + if (data->num == 0) + { + return nullptr; + } + + float r = CCRANDOM_0_1(); + + if (r == 1) // to prevent from accessing data-arr[data->num], out of range. + { + r = 0; + } + + return data->arr[(int)(data->num * r)]; +} + +bool Array::containsObject(Object* object) const +{ + return ccArrayContainsObject(data, object); +} + +bool Array::isEqualToArray(Array* otherArray) +{ + for (int i = 0; i< this->count(); i++) + { + if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) + { + return false; + } + } + return true; +} + +void Array::addObject(Object* object) +{ + CCASSERT(data, "Array not initialized"); + ccArrayAppendObjectWithResize(data, object); +} + +void Array::addObjectsFromArray(Array* otherArray) +{ + CCASSERT(data, "Array not initialized"); + ccArrayAppendArrayWithResize(data, otherArray->data); +} + +void Array::insertObject(Object* object, int index) +{ + CCASSERT(data, "Array not initialized"); + ccArrayInsertObjectAtIndex(data, object, index); +} + +void Array::setObject(Object* object, int index) +{ + CCASSERT(index>=0 && index < count(), "Invalid index"); + + if (object != data->arr[index]) + { + data->arr[index]->release(); + data->arr[index] = object; + object->retain(); + } +} + +void Array::removeLastObject(bool releaseObj) +{ + CCASSERT(data->num, "no objects added"); + ccArrayRemoveObjectAtIndex(data, data->num-1, releaseObj); +} + +void Array::removeObject(Object* object, bool releaseObj/* = true*/) +{ + ccArrayRemoveObject(data, object, releaseObj); +} + +void Array::removeObjectAtIndex(int index, bool releaseObj) +{ + ccArrayRemoveObjectAtIndex(data, index, releaseObj); +} + +void Array::removeObjectsInArray(Array* otherArray) +{ + ccArrayRemoveArray(data, otherArray->data); +} + +void Array::removeAllObjects() +{ + ccArrayRemoveAllObjects(data); +} + +void Array::fastRemoveObjectAtIndex(int index) +{ + ccArrayFastRemoveObjectAtIndex(data, index); +} + +void Array::fastRemoveObject(Object* object) +{ + ccArrayFastRemoveObject(data, object); +} + +void Array::exchangeObject(Object* object1, Object* object2) +{ + int index1 = ccArrayGetIndexOfObject(data, object1); + if (index1 == UINT_MAX) + { + return; + } + + int index2 = ccArrayGetIndexOfObject(data, object2); + if (index2 == UINT_MAX) + { + return; + } + + ccArraySwapObjectsAtIndexes(data, index1, index2); +} + +void Array::exchangeObjectAtIndex(int index1, int index2) +{ + ccArraySwapObjectsAtIndexes(data, index1, index2); +} + +void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) +{ + ccArrayInsertObjectAtIndex(data, object, index); + ccArrayRemoveObjectAtIndex(data, index+1); +} + +void Array::reverseObjects() +{ + if (data->num > 1) + { + // floorf(), since in the case of an even number, the number of swaps stays the same + int count = (int) floorf(data->num/2.f); + int maxIndex = data->num - 1; + + for (int i = 0; i < count ; i++) + { + ccArraySwapObjectsAtIndexes(data, i, maxIndex); + --maxIndex; + } + } +} + +void Array::reduceMemoryFootprint() +{ + ccArrayShrink(data); +} + +Array::~Array() +{ + CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); + + ccArrayFree(data); +} + +Array* Array::clone() const +{ + Array* ret = new Array(); + ret->autorelease(); + ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1); + + Object* obj = nullptr; + Object* tmpObj = nullptr; + Clonable* clonable = nullptr; + CCARRAY_FOREACH(this, obj) + { + clonable = dynamic_cast(obj); + if (clonable) + { + tmpObj = dynamic_cast(clonable->clone()); + if (tmpObj) + { + ret->addObject(tmpObj); + } + } + else + { + CCLOGWARN("%s isn't clonable.", typeid(*obj).name()); + } + } + return ret; +} + +void Array::acceptVisitor(DataVisitor &visitor) +{ + visitor.visit(this); +} + +#endif // uses ccArray + +NS_CC_END diff --git a/cocos/base/cocoa/CCArray.h b/cocos/base/cocoa/CCArray.h new file mode 100644 index 0000000000..4f5beea501 --- /dev/null +++ b/cocos/base/cocoa/CCArray.h @@ -0,0 +1,557 @@ +/**************************************************************************** +Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#ifndef __CCARRAY_H__ +#define __CCARRAY_H__ + +#define CC_USE_ARRAY_VECTOR 0 + +#if CC_USE_ARRAY_VECTOR +#include +#include +#include "cocoa/CCObject.h" +#include "ccMacros.h" +#else +#include "support/data_support/ccCArray.h" +#endif + + +#if CC_USE_ARRAY_VECTOR +/** + * A reference counting-managed pointer for classes derived from RCBase which can + * be used as C pointer + * Original code: http://www.codeproject.com/Articles/64111/Building-a-Quick-and-Handy-Reference-Counting-Clas + * License: http://www.codeproject.com/info/cpol10.aspx + */ +template < class T > +class RCPtr +{ +public: + //Construct using a C pointer + //e.g. RCPtr< T > x = new T(); + RCPtr(T* ptr = nullptr) + : _ptr(ptr) + { + if(ptr != nullptr) {ptr->retain();} + } + + //Copy constructor + RCPtr(const RCPtr &ptr) + : _ptr(ptr._ptr) + { +// printf("Array: copy constructor: %p\n", this); + if(_ptr != NULL) {_ptr->retain();} + } + + //Move constructor + RCPtr(RCPtr &&ptr) + : _ptr(ptr._ptr) + { +// printf("Array: Move Constructor: %p\n", this); + ptr._ptr = nullptr; + } + + ~RCPtr() + { +// printf("Array: Destructor: %p\n", this); + if(_ptr != nullptr) {_ptr->release();} + } + + //Assign a pointer + //e.g. x = new T(); + RCPtr &operator=(T* ptr) + { +// printf("Array: operator= T*: %p\n", this); + + //The following grab and release operations have to be performed + //in that order to handle the case where ptr == _ptr + //(See comment below by David Garlisch) + if(ptr != nullptr) {ptr->retain();} + if(_ptr != nullptr) {_ptr->release();} + _ptr = ptr; + return (*this); + } + + //Assign another RCPtr + RCPtr &operator=(const RCPtr &ptr) + { +// printf("Array: operator= const&: %p\n", this); + return (*this) = ptr._ptr; + } + + //Retrieve actual pointer + T* get() const + { + return _ptr; + } + + //Some overloaded operators to facilitate dealing with an RCPtr + //as a conventional C pointer. + //Without these operators, one can still use the less transparent + //get() method to access the pointer. + T* operator->() const {return _ptr;} //x->member + T &operator*() const {return *_ptr;} //*x, (*x).member + explicit operator T*() const {return _ptr;} //T* y = x; + explicit operator bool() const {return _ptr != nullptr;} //if(x) {/*x is not NULL*/} + bool operator==(const RCPtr &ptr) {return _ptr == ptr._ptr;} + bool operator==(const T *ptr) {return _ptr == ptr;} + +private: + T *_ptr; //Actual pointer +}; +#endif // CC_USE_ARRAY_VECTOR + + +/** + * @addtogroup data_structures + * @{ + */ + +/** @def CCARRAY_FOREACH +A convenience macro to iterate over a Array using. It is faster than the "fast enumeration" interface. +@since v0.99.4 +*/ + +/* +In cocos2d-iphone 1.0.0, This macro have been update to like this: + +#define CCARRAY_FOREACH(__array__, __object__) \ +if (__array__ && __array__->data->num > 0) \ +for(id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __array__->data->num-1; \ +__arr__ <= end && ((__object__ = *__arr__) != nil || true); \ +__arr__++) + +I found that it's not work in C++. So it keep what it's look like in version 1.0.0-rc3. ---By Bin +*/ + +#if CC_USE_ARRAY_VECTOR +#define CCARRAY_FOREACH(__array__, __object__) \ + if (__array__) \ + for( auto __it__ = (__array__)->data.begin(); \ + __it__ != (__array__)->data.end() && ((__object__) = __it__->get()) != nullptr; \ + ++__it__) + + +#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \ + if (__array__) \ + for( auto __it__ = (__array__)->data.rbegin(); \ + __it__ != (__array__)->data.rend() && ((__object__) = __it__->get()) != nullptr; \ + ++__it__ ) + + +#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) + +#else // ! CC_USE_ARRAY_VECTOR -------------------------- + +#define CCARRAY_FOREACH(__array__, __object__) \ + if ((__array__) && (__array__)->data->num > 0) \ + for(Object** __arr__ = (__array__)->data->arr, **__end__ = (__array__)->data->arr + (__array__)->data->num-1; \ + __arr__ <= __end__ && (((__object__) = *__arr__) != NULL/* || true*/); \ + __arr__++) + +#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \ + if ((__array__) && (__array__)->data->num > 0) \ + for(Object** __arr__ = (__array__)->data->arr + (__array__)->data->num-1, **__end__ = (__array__)->data->arr; \ + __arr__ >= __end__ && (((__object__) = *__arr__) != NULL/* || true*/); \ + __arr__--) + +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) +#define CCARRAY_VERIFY_TYPE(__array__, __type__) \ + do { \ + if ((__array__) && (__array__)->data->num > 0) \ + for(Object** __arr__ = (__array__)->data->arr, \ + **__end__ = (__array__)->data->arr + (__array__)->data->num-1; __arr__ <= __end__; __arr__++) \ + CCASSERT(dynamic_cast<__type__>(*__arr__), "element type is wrong!"); \ + } while(false) +#else +#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) +#endif + +#endif // ! CC_USE_ARRAY_VECTOR + + +// Common defines ----------------------------------------------------------------------------------------------- + +#define arrayMakeObjectsPerformSelector(pArray, func, elementType) \ +do { \ + if(pArray && pArray->count() > 0) \ + { \ + Object* child; \ + CCARRAY_FOREACH(pArray, child) \ + { \ + elementType pNode = static_cast(child); \ + if(pNode) \ + { \ + pNode->func(); \ + } \ + } \ + } \ +} \ +while(false) + +#define arrayMakeObjectsPerformSelectorWithObject(pArray, func, object, elementType) \ +do { \ + if(pArray && pArray->count() > 0) \ + { \ + Object* child; \ + CCARRAY_FOREACH(pArray, child) \ + { \ + elementType pNode = static_cast(child); \ + if(pNode) \ + { \ + pNode->func(object); \ + } \ + } \ + } \ +} \ +while(false) + + +NS_CC_BEGIN + +class CC_DLL Array : public Object, public Clonable +{ +public: + + /** Creates an empty array. Default capacity is 10 + * @js NA + * @lua NA + */ + static Array* create(); + /** Create an array with objects + * @js NA + */ + static Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; + /** Create an array with one object + * @js NA + */ + static Array* createWithObject(Object* object); + /** Create an array with a default capacity + * @js NA + */ + static Array* createWithCapacity(int capacity); + /** Create an array with from an existing array + * @js NA + */ + static Array* createWithArray(Array* otherArray); + /** + @brief Generate a Array pointer by file + @param pFileName The file name of *.plist file + @return The Array pointer generated from the file + * @js NA + */ + static Array* createWithContentsOfFile(const char* pFileName); + + /* + @brief The same meaning as arrayWithContentsOfFile(), but it doesn't call autorelease, so the + invoker should call release(). + * @js NA + * @lua NA + */ + static Array* createWithContentsOfFileThreadSafe(const char* pFileName); + /** + * @js NA + * @lua NA + */ + ~Array(); + + /** Initializes an array + * @js NA + * @lua NA + */ + bool init(); + /** Initializes an array with one object + * @js NA + * @lua NA + */ + bool initWithObject(Object* object); + /** Initializes an array with some objects + * @js NA + * @lua NA + */ + bool initWithObjects(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; + /** Initializes an array with capacity + * @js NA + * @lua NA + */ + bool initWithCapacity(int capacity); + /** Initializes an array with an existing array + * @js NA + * @lua NA + */ + bool initWithArray(Array* otherArray); + + // Querying an Array + + /** Returns element count of the array + * @js NA + */ + int count() const + { +#if CC_USE_ARRAY_VECTOR + return data.size(); +#else + return data->num; +#endif + } + /** Returns capacity of the array + * @js NA + */ + int capacity() const + { +#if CC_USE_ARRAY_VECTOR + return data.capacity(); +#else + return data->max; +#endif + } + /** Returns index of a certain object, return UINT_MAX if doesn't contain the object + * @js NA + * @lua NA + */ + int getIndexOfObject(Object* object) const; + /** + * @js NA + */ + CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } + + /** Returns an element with a certain index + * @js NA + * @lua NA + */ + Object* getObjectAtIndex(int index) + { + CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); +#if CC_USE_ARRAY_VECTOR + return data[index].get(); +#else + return data->arr[index]; +#endif + } + CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } + /** Returns the last element of the array + * @js NA + */ + Object* getLastObject() + { +#if CC_USE_ARRAY_VECTOR + return data.back().get(); +#else + if(data->num > 0) + return data->arr[data->num-1]; + + return nullptr; +#endif + } + /** + * @js NA + */ + CC_DEPRECATED_ATTRIBUTE Object* lastObject() { return getLastObject(); } + /** Returns a random element + * @js NA + * @lua NA + */ + Object* getRandomObject(); + /** + * @js NA + */ + CC_DEPRECATED_ATTRIBUTE Object* randomObject() { return getRandomObject(); } + /** Returns a Boolean value that indicates whether object is present in array. + * @js NA + */ + bool containsObject(Object* object) const; + /** @since 1.1 + * @js NA + */ + bool isEqualToArray(Array* otherArray); + // Adding Objects + + /** Add a certain object + * @js NA + */ + void addObject(Object* object); + /** + * @js NA + */ + /** Add all elements of an existing array + * @js NA + */ + void addObjectsFromArray(Array* otherArray); + /** Insert a certain object at a certain index + * @js NA + */ + void insertObject(Object* object, int index); + /** sets a certain object at a certain index + * @js NA + * @lua NA + */ + void setObject(Object* object, int index); + /** sets a certain object at a certain index without retaining. Use it with caution + * @js NA + * @lua NA + */ + void fastSetObject(Object* object, int index) + { +#if CC_USE_ARRAY_VECTOR + setObject(object, index); +#else + // no retain + data->arr[index] = object; +#endif + } + /** + * @js NA + * @lua NA + */ + void swap( int indexOne, int indexTwo ) + { + CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); +#if CC_USE_ARRAY_VECTOR + std::swap(data[indexOne], data[indexTwo]); +#else + std::swap(data->arr[indexOne], data->arr[indexTwo]); +#endif + } + + // Removing Objects + + /** Remove last object + * @js NA + */ + void removeLastObject(bool releaseObj = true); + /** Remove a certain object + * @js NA + */ + void removeObject(Object* object, bool releaseObj = true); + /** Remove an element with a certain index + * @js NA + */ + void removeObjectAtIndex(int index, bool releaseObj = true); + /** Remove all elements + * @js NA + */ + void removeObjectsInArray(Array* otherArray); + /** Remove all objects + * @js NA + */ + void removeAllObjects(); + /** Fast way to remove a certain object + * @js NA + */ + void fastRemoveObject(Object* object); + /** Fast way to remove an element with a certain index + * @js NA + */ + void fastRemoveObjectAtIndex(int index); + + // Rearranging Content + + /** Swap two elements + * @js NA + */ + void exchangeObject(Object* object1, Object* object2); + /** Swap two elements with certain indexes + * @js NA + */ + void exchangeObjectAtIndex(int index1, int index2); + + /** Replace object at index with another object. + * @js NA + */ + void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); + + /** Revers the array + * @js NA + */ + void reverseObjects(); + /* Shrinks the array so the memory footprint corresponds with the number of items + * @js NA + */ + void reduceMemoryFootprint(); + + /* override functions + * @js NA + */ + virtual void acceptVisitor(DataVisitor &visitor); + /** + * @js NA + * @lua NA + */ + virtual Array* clone() const; + + // ------------------------------------------ + // Iterators + // ------------------------------------------ +#if CC_USE_ARRAY_VECTOR + typedef std::vector>::iterator iterator; + typedef std::vector>::const_iterator const_iterator; + /** + * @js NA + * @lua NA + */ + iterator begin() { return data.begin(); } + /** + * @js NA + * @lua NA + */ + iterator end() { return data.end(); } + const_iterator cbegin() { return data.cbegin(); } + /** + * @js NA + * @lua NA + */ + const_iterator cend() { return data.cend(); } + + std::vector> data; + +#else + /** + * @js NA + * @lua NA + */ + Object** begin() { return &data->arr[0]; } + /** + * @js NA + * @lua NA + */ + Object** end() { return &data->arr[data->num]; } + + ccArray* data; + +#endif + +//protected: + /** + * @js NA + * @lua NA + */ + Array(); +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCARRAY_H__ diff --git a/cocos/base/cocoa/CCAutoreleasePool.cpp b/cocos/base/cocoa/CCAutoreleasePool.cpp new file mode 100644 index 0000000000..89a3528f73 --- /dev/null +++ b/cocos/base/cocoa/CCAutoreleasePool.cpp @@ -0,0 +1,204 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "CCAutoreleasePool.h" +#include "ccMacros.h" + +NS_CC_BEGIN + +static PoolManager* s_pPoolManager = NULL; + +AutoreleasePool::AutoreleasePool() +{ + _managedObjectArray = new Array(); + _managedObjectArray->initWithCapacity(150); +} + +AutoreleasePool::~AutoreleasePool() +{ + CCLOGINFO("deallocing AutoreleasePool: %p", this); + CC_SAFE_DELETE(_managedObjectArray); +} + +void AutoreleasePool::addObject(Object* object) +{ + _managedObjectArray->addObject(object); + + CCASSERT(object->_reference > 1, "reference count should be greater than 1"); + ++(object->_autoReleaseCount); + object->release(); // no ref count, in this case autorelease pool added. +} + +void AutoreleasePool::removeObject(Object* object) +{ + for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) + { + _managedObjectArray->removeObject(object, false); + } +} + +void AutoreleasePool::clear() +{ + if(_managedObjectArray->count() > 0) + { + //CCAutoreleasePool* pReleasePool; +#ifdef _DEBUG + int nIndex = _managedObjectArray->count() - 1; +#endif + + Object* pObj = NULL; + CCARRAY_FOREACH_REVERSE(_managedObjectArray, pObj) + { + if(!pObj) + break; + + --(pObj->_autoReleaseCount); + //(*it)->release(); + //delete (*it); +#ifdef _DEBUG + nIndex--; +#endif + } + + _managedObjectArray->removeAllObjects(); + } +} + + +//-------------------------------------------------------------------- +// +// PoolManager +// +//-------------------------------------------------------------------- + +PoolManager* PoolManager::sharedPoolManager() +{ + if (s_pPoolManager == NULL) + { + s_pPoolManager = new PoolManager(); + } + return s_pPoolManager; +} + +void PoolManager::purgePoolManager() +{ + CC_SAFE_DELETE(s_pPoolManager); +} + +PoolManager::PoolManager() +{ + _releasePoolStack = new Array(); + _releasePoolStack->initWithCapacity(150); + _curReleasePool = 0; +} + +PoolManager::~PoolManager() +{ + CCLOGINFO("deallocing PoolManager: %p", this); + finalize(); + + // we only release the last autorelease pool here + _curReleasePool = 0; + _releasePoolStack->removeObjectAtIndex(0); + + CC_SAFE_DELETE(_releasePoolStack); +} + +void PoolManager::finalize() +{ + if(_releasePoolStack->count() > 0) + { + //CCAutoreleasePool* pReleasePool; + Object* pObj = NULL; + CCARRAY_FOREACH(_releasePoolStack, pObj) + { + if(!pObj) + break; + AutoreleasePool* pPool = static_cast(pObj); + pPool->clear(); + } + } +} + +void PoolManager::push() +{ + AutoreleasePool* pPool = new AutoreleasePool(); //ref = 1 + _curReleasePool = pPool; + + _releasePoolStack->addObject(pPool); //ref = 2 + + pPool->release(); //ref = 1 +} + +void PoolManager::pop() +{ + if (! _curReleasePool) + { + return; + } + + int nCount = _releasePoolStack->count(); + + _curReleasePool->clear(); + + if (nCount > 1) + { + _releasePoolStack->removeObjectAtIndex(nCount-1); + +// if(nCount > 1) +// { +// _curReleasePool = _releasePoolStack->getObjectAtIndex(nCount - 2); +// return; +// } + _curReleasePool = (AutoreleasePool*)_releasePoolStack->getObjectAtIndex(nCount - 2); + } + + /*_curReleasePool = NULL;*/ +} + +void PoolManager::removeObject(Object* object) +{ + CCASSERT(_curReleasePool, "current auto release pool should not be null"); + + _curReleasePool->removeObject(object); +} + +void PoolManager::addObject(Object* object) +{ + getCurReleasePool()->addObject(object); +} + + +AutoreleasePool* PoolManager::getCurReleasePool() +{ + if(!_curReleasePool) + { + push(); + } + + CCASSERT(_curReleasePool, "current auto release pool should not be null"); + + return _curReleasePool; +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCAutoreleasePool.h b/cocos/base/cocoa/CCAutoreleasePool.h new file mode 100644 index 0000000000..e446ceb402 --- /dev/null +++ b/cocos/base/cocoa/CCAutoreleasePool.h @@ -0,0 +1,181 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#ifndef __AUTORELEASEPOOL_H__ +#define __AUTORELEASEPOOL_H__ + +#include "CCObject.h" +#include "CCArray.h" + +NS_CC_BEGIN + +/** + * @addtogroup base_nodes + * @{ + */ + +class CC_DLL AutoreleasePool : public Object +{ + /** + * The underlying array of object managed by the pool. + * + * Although Array retains the object once when an object is added, proper + * Object::release() is called outside the array to make sure that the pool + * does not affect the managed object's reference count. So an object can + * be destructed properly by calling Object::release() even if the object + * is in the pool. + */ + Array *_managedObjectArray; +public: + /** + * @js NA + * @lua NA + */ + AutoreleasePool(); + /** + * @js NA + * @lua NA + */ + ~AutoreleasePool(); + + /** + * Add a given object to this pool. + * + * The same object may be added several times to the same pool; When the + * pool is destructed, the object's Object::release() method will be called + * for each time it was added. + * + * @param object The object to add to the pool. + * @js NA + * @lua NA + */ + void addObject(Object *object); + + /** + * Remove a given object from this pool. + * + * @param object The object to be removed from the pool. + * @js NA + * @lua NA + */ + void removeObject(Object *object); + + /** + * Clear the autorelease pool. + * + * Object::release() will be called for each time the managed object is + * added to the pool. + * @js NA + * @lua NA + */ + void clear(); +}; + +class CC_DLL PoolManager +{ + Array *_releasePoolStack; + AutoreleasePool *_curReleasePool; + + AutoreleasePool *getCurReleasePool(); +public: + /** + * @js NA + * @lua NA + */ + static PoolManager* sharedPoolManager(); + /** + * @js NA + * @lua NA + */ + static void purgePoolManager(); + /** + * @js NA + * @lua NA + */ + PoolManager(); + /** + * @js NA + * @lua NA + */ + ~PoolManager(); + + /** + * Clear all the AutoreleasePool on the pool stack. + * @js NA + * @lua NA + */ + void finalize(); + + /** + * Push a new AutoreleasePool to the pool stack. + * @js NA + * @lua NA + */ + void push(); + + /** + * Pop one AutoreleasePool from the pool stack. + * + * This method will ensure that there is at least one AutoreleasePool on + * the stack. + * + * The AutoreleasePool being poped is destructed. + * @js NA + * @lua NA + */ + void pop(); + + /** + * Remove a given object from the current autorelease pool. + * + * @param object The object to be removed. + * + * @see AutoreleasePool::removeObject + * @js NA + * @lua NA + */ + void removeObject(Object *object); + + /** + * Add a given object to the current autorelease pool. + * + * @param object The object to add. + * + * @see AutoreleasePool::addObject + * @js NA + * @lua NA + */ + void addObject(Object *object); + /** + * @js NA + * @lua NA + */ + friend class AutoreleasePool; +}; + +// end of base_nodes group +/// @} + +NS_CC_END + +#endif //__AUTORELEASEPOOL_H__ diff --git a/cocos/base/cocoa/CCBool.h b/cocos/base/cocoa/CCBool.h new file mode 100644 index 0000000000..32b7b276ee --- /dev/null +++ b/cocos/base/cocoa/CCBool.h @@ -0,0 +1,70 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 __CCBOOL_H__ +#define __CCBOOL_H__ + +#include "CCObject.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +class CC_DLL Bool : public Object, public Clonable +{ +public: + Bool(bool v) + : _value(v) {} + bool getValue() const {return _value;} + + static Bool* create(bool v) + { + Bool* pRet = new Bool(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + /* override functions */ + virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } + + Bool* clone() const + { + return Bool::create(_value); + } +private: + bool _value; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCBOOL_H__ */ diff --git a/cocos/base/cocoa/CCData.cpp b/cocos/base/cocoa/CCData.cpp new file mode 100644 index 0000000000..1c42a12ee5 --- /dev/null +++ b/cocos/base/cocoa/CCData.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 +#include "CCData.h" +#include "platform/CCCommon.h" + +NS_CC_BEGIN + +Data::Data(unsigned char *pBytes, const unsigned long nSize) +{ + _size = nSize; + _bytes = new unsigned char[_size]; + memcpy(_bytes, pBytes, _size); +} + +Data::Data(Data *pData) +{ + _size = pData->_size; + _bytes = new unsigned char[_size]; + memcpy(_bytes, pData->_bytes, _size); +} + +Data::~Data() +{ + CCLOGINFO("deallocing Data: %p", this); + CC_SAFE_DELETE_ARRAY(_bytes); +} + +unsigned char* Data::getBytes() const +{ + return _bytes; +} + +unsigned long Data::getSize() const +{ + return _size; +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCData.h b/cocos/base/cocoa/CCData.h new file mode 100644 index 0000000000..889a2d557b --- /dev/null +++ b/cocos/base/cocoa/CCData.h @@ -0,0 +1,88 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 __CCDATA_H__ +#define __CCDATA_H__ + +#include "platform/CCPlatformMacros.h" +#include "CCObject.h" + +NS_CC_BEGIN + +class CC_DLL Data : public Object +{ +public: + /** + * @js NA + * @lua NA + */ + Data(unsigned char *pBytes, const unsigned long nSize); + /** + * @js NA + * @lua NA + */ + Data(Data *pData); + /** + * @js NA + * @lua NA + */ + ~Data(); + /** + * @js NA + * @lua NA + */ + static Data* create(unsigned char *pBytes, const unsigned long nSize) + { + Data* pRet = new Data(pBytes, nSize); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + /** + * @js NA + * @lua NA + */ + unsigned char* getBytes() const; + /** + * @js NA + * @lua NA + */ + unsigned long getSize() const; + + /** override functions + * @js NA + * @lua NA + */ + virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } + +private: + unsigned char* _bytes; + unsigned long _size; +}; + +NS_CC_END + +#endif // __CCDATA_H__ diff --git a/cocos/base/cocoa/CCDataVisitor.cpp b/cocos/base/cocoa/CCDataVisitor.cpp new file mode 100644 index 0000000000..2d2a1f8121 --- /dev/null +++ b/cocos/base/cocoa/CCDataVisitor.cpp @@ -0,0 +1,240 @@ +/**************************************************************************** + 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 "CCObject.h" +#include "CCBool.h" +#include "CCInteger.h" +#include "CCFloat.h" +#include "CCDouble.h" +#include "CCString.h" +#include "CCArray.h" +#include "CCDictionary.h" +#include "CCSet.h" +#include "CCData.h" + +NS_CC_BEGIN + +void DataVisitor::visit(const Bool *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Integer *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Float *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Double *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const String *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Array *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Dictionary *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Set *value) +{ + visitObject(value); +} + +void DataVisitor::visit(const Data *value) +{ + visitObject(value); +} + +// PrettyPrinter +PrettyPrinter::PrettyPrinter(int indentLevel/* = 0 */) +{ + setIndentLevel(indentLevel); +} + +void PrettyPrinter::clear() +{ + _result.clear(); +} + +std::string PrettyPrinter::getResult() +{ + return _result; +} + +void PrettyPrinter::visitObject(const Object *p) +{ + char buf[50] = {0}; + sprintf(buf, "%p", p); + _result += buf; +} + +void PrettyPrinter::visit(const Bool * p) +{ + char buf[50] = {0}; + sprintf(buf, "%s", p->getValue() ? "true" : "false"); + _result += buf; +} + +void PrettyPrinter::visit(const Integer *p) +{ + char buf[50] = {0}; + sprintf(buf, "%d", p->getValue()); + _result += buf; +} + +void PrettyPrinter::visit(const Float *p) +{ + char buf[50] = {0}; + sprintf(buf, "%f", p->getValue()); + _result += buf; +} + +void PrettyPrinter::visit(const Double *p) +{ + char buf[50] = {0}; + sprintf(buf, "%lf", p->getValue()); + _result += buf; +} + +void PrettyPrinter::visit(const String *p) +{ + _result += p->getCString(); +} + +void PrettyPrinter::visit(const Array *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + Object* obj; + int i = 0; + char buf[50] = {0}; + CCARRAY_FOREACH(p, obj) + { + if (i > 0) { + _result += "\n"; + } + sprintf(buf, "%s%02d: ", _indentStr.c_str(), i); + _result += buf; + PrettyPrinter v(_indentLevel); + obj->acceptVisitor(v); + _result += v.getResult(); + i++; + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += ""; +} + +void PrettyPrinter::visit(const Dictionary *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + DictElement* element; + bool bFirstElement = true; + char buf[1000] = {0}; + CCDICT_FOREACH(p, element) + { + if (!bFirstElement) { + _result += "\n"; + } + sprintf(buf, "%s%s: ", _indentStr.c_str(),element->getStrKey()); + _result += buf; + PrettyPrinter v(_indentLevel); + element->getObject()->acceptVisitor(v); + _result += v.getResult(); + bFirstElement = false; + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += ""; +} + +void PrettyPrinter::visit(const Set *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + + int i = 0; + Set* tmp = const_cast(p); + SetIterator it = tmp->begin(); + + for (; it != tmp->end(); ++it, ++i) { + if (i > 0) { + _result += "\n"; + } + _result += _indentStr.c_str(); + PrettyPrinter v(_indentLevel); + (*it)->acceptVisitor(v); + _result += v.getResult(); + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += "\n"; +} + +void PrettyPrinter::visit(const Data *p) +{ + //TODO Implement + DataVisitor::visit(p); +} + +void PrettyPrinter::setIndentLevel(int indentLevel) +{ + _indentLevel = indentLevel; + _indentStr.clear(); + for (int i = 0; i < _indentLevel; ++i) { + _indentStr += "\t"; + } +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCDataVisitor.h b/cocos/base/cocoa/CCDataVisitor.h new file mode 100644 index 0000000000..3395b43dea --- /dev/null +++ b/cocos/base/cocoa/CCDataVisitor.h @@ -0,0 +1,117 @@ +/**************************************************************************** + 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 __CCDATAVISITOR_H__ +#define __CCDATAVISITOR_H__ + +#include "platform/CCPlatformMacros.h" +#include + +NS_CC_BEGIN + +class Object; +class Bool; +class Integer; +class Float; +class Double; +class String; +class Array; +class Dictionary; +class Set; +class Data; + +/** + * @addtogroup data_structures + * @{ + */ + +/** + * Visitor that helps to perform action that depends on polymorphic object type + * + * Use cases: + * - data serialization, + * - pretty printing of Object * + * - safe value reading from Array, Dictionary, Set + * + * Usage: + * 1. subclass DataVisitor + * 2. overload visit() methods for object that you need to handle + * 3. handle other objects in visitObject() + * 4. pass your visitor to Object::acceptVisitor() + */ +class CC_DLL DataVisitor +{ +public: + /** + * @js NA + * @lua NA + */ + virtual ~DataVisitor() {} + + /** default method, called from non-overloaded methods and for unrecognized objects */ + virtual void visitObject(const Object *p) = 0; + + virtual void visit(const Bool *p); + virtual void visit(const Integer *p); + virtual void visit(const Float *p); + virtual void visit(const Double *p); + virtual void visit(const String *p); + virtual void visit(const Array *p); + virtual void visit(const Dictionary *p); + virtual void visit(const Set *p); + virtual void visit(const Data *p); +}; + + +class CC_DLL PrettyPrinter : public DataVisitor +{ +public: + PrettyPrinter(int indentLevel = 0); + + virtual void clear(); + virtual std::string getResult(); + + virtual void visitObject(const Object *p); + virtual void visit(const Bool * p); + virtual void visit(const Integer *p); + virtual void visit(const Float *p); + virtual void visit(const Double *p); + virtual void visit(const String *p); + virtual void visit(const Array *p); + virtual void visit(const Dictionary *p); + virtual void visit(const Set *p); + virtual void visit(const Data *p); +private: + void setIndentLevel(int indentLevel); + int _indentLevel; + std::string _indentStr; + std::string _result; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCDATAVISITOR_H__ diff --git a/cocos/base/cocoa/CCDictionary.cpp b/cocos/base/cocoa/CCDictionary.cpp new file mode 100644 index 0000000000..6b8df0febf --- /dev/null +++ b/cocos/base/cocoa/CCDictionary.cpp @@ -0,0 +1,454 @@ +/**************************************************************************** + Copyright (c) 2012 - 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 "CCDictionary.h" +#include "CCString.h" +#include "CCInteger.h" +#include "platform/CCFileUtils.h" + +using namespace std; + +NS_CC_BEGIN + +// ----------------------------------------------------------------------- +// DictElement + +DictElement::DictElement(const char* pszKey, Object* pObject) +{ + CCASSERT(pszKey && strlen(pszKey) > 0, "Invalid key value."); + _intKey = 0; + const char* pStart = pszKey; + + size_t len = strlen(pszKey); + if (len > MAX_KEY_LEN ) + { + char* pEnd = (char*)&pszKey[len-1]; + pStart = pEnd - (MAX_KEY_LEN-1); + } + + strcpy(_strKey, pStart); + + _object = pObject; + memset(&hh, 0, sizeof(hh)); +} + +DictElement::DictElement(intptr_t iKey, Object* pObject) +{ + _strKey[0] = '\0'; + _intKey = iKey; + _object = pObject; + memset(&hh, 0, sizeof(hh)); +} + +DictElement::~DictElement() +{ + CCLOGINFO("deallocing DictElement: %p", this); +} + +// ----------------------------------------------------------------------- +// Dictionary + +Dictionary::Dictionary() +: _elements(NULL) +, _dictType(kDictUnknown) +{ + +} + +Dictionary::~Dictionary() +{ + CCLOGINFO("deallocing Dictionary: %p", this); + removeAllObjects(); +} + +unsigned int Dictionary::count() +{ + return HASH_COUNT(_elements); +} + +Array* Dictionary::allKeys() +{ + int iKeyCount = this->count(); + if (iKeyCount <= 0) return NULL; + + Array* pArray = Array::createWithCapacity(iKeyCount); + + DictElement *pElement, *tmp; + if (_dictType == kDictStr) + { + HASH_ITER(hh, _elements, pElement, tmp) + { + String* pOneKey = new String(pElement->_strKey); + pArray->addObject(pOneKey); + CC_SAFE_RELEASE(pOneKey); + } + } + else if (_dictType == kDictInt) + { + HASH_ITER(hh, _elements, pElement, tmp) + { + Integer* pOneKey = new Integer(pElement->_intKey); + pArray->addObject(pOneKey); + CC_SAFE_RELEASE(pOneKey); + } + } + + return pArray; +} + +Array* Dictionary::allKeysForObject(Object* object) +{ + int iKeyCount = this->count(); + if (iKeyCount <= 0) return NULL; + Array* pArray = Array::create(); + + DictElement *pElement, *tmp; + + if (_dictType == kDictStr) + { + HASH_ITER(hh, _elements, pElement, tmp) + { + if (object == pElement->_object) + { + String* pOneKey = new String(pElement->_strKey); + pArray->addObject(pOneKey); + CC_SAFE_RELEASE(pOneKey); + } + } + } + else if (_dictType == kDictInt) + { + HASH_ITER(hh, _elements, pElement, tmp) + { + if (object == pElement->_object) + { + Integer* pOneKey = new Integer(pElement->_intKey); + pArray->addObject(pOneKey); + CC_SAFE_RELEASE(pOneKey); + } + } + } + return pArray; +} + +Object* Dictionary::objectForKey(const std::string& key) +{ + // if dictionary wasn't initialized, return NULL directly. + if (_dictType == kDictUnknown) return NULL; + // Dictionary only supports one kind of key, string or integer. + // This method uses string as key, therefore we should make sure that the key type of this Dictionary is string. + CCASSERT(_dictType == kDictStr, "this dictionary does not use string as key."); + + Object* pRetObject = NULL; + DictElement *pElement = NULL; + HASH_FIND_STR(_elements, key.c_str(), pElement); + if (pElement != NULL) + { + pRetObject = pElement->_object; + } + return pRetObject; +} + +Object* Dictionary::objectForKey(intptr_t key) +{ + // if dictionary wasn't initialized, return NULL directly. + if (_dictType == kDictUnknown) return NULL; + // Dictionary only supports one kind of key, string or integer. + // This method uses integer as key, therefore we should make sure that the key type of this Dictionary is integer. + CCASSERT(_dictType == kDictInt, "this dictionary does not use integer as key."); + + Object* pRetObject = NULL; + DictElement *pElement = NULL; + HASH_FIND_PTR(_elements, &key, pElement); + if (pElement != NULL) + { + pRetObject = pElement->_object; + } + return pRetObject; +} + +const String* Dictionary::valueForKey(const std::string& key) +{ + String* pStr = dynamic_cast(objectForKey(key)); + if (pStr == NULL) + { + pStr = String::create(""); + } + return pStr; +} + +const String* Dictionary::valueForKey(intptr_t key) +{ + String* pStr = dynamic_cast(objectForKey(key)); + if (pStr == NULL) + { + pStr = String::create(""); + } + return pStr; +} + +void Dictionary::setObject(Object* pObject, const std::string& key) +{ + CCASSERT(key.length() > 0 && pObject != NULL, "Invalid Argument!"); + if (_dictType == kDictUnknown) + { + _dictType = kDictStr; + } + + CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as key."); + + DictElement *pElement = NULL; + HASH_FIND_STR(_elements, key.c_str(), pElement); + if (pElement == NULL) + { + setObjectUnSafe(pObject, key); + } + else if (pElement->_object != pObject) + { + Object* pTmpObj = pElement->_object; + pTmpObj->retain(); + removeObjectForElememt(pElement); + setObjectUnSafe(pObject, key); + pTmpObj->release(); + } +} + +void Dictionary::setObject(Object* pObject, intptr_t key) +{ + CCASSERT(pObject != NULL, "Invalid Argument!"); + if (_dictType == kDictUnknown) + { + _dictType = kDictInt; + } + + CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as key."); + + DictElement *pElement = NULL; + HASH_FIND_PTR(_elements, &key, pElement); + if (pElement == NULL) + { + setObjectUnSafe(pObject, key); + } + else if (pElement->_object != pObject) + { + Object* pTmpObj = pElement->_object; + pTmpObj->retain(); + removeObjectForElememt(pElement); + setObjectUnSafe(pObject, key); + pTmpObj->release(); + } + +} + +void Dictionary::removeObjectForKey(const std::string& key) +{ + if (_dictType == kDictUnknown) + { + return; + } + + CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as its key"); + CCASSERT(key.length() > 0, "Invalid Argument!"); + DictElement *pElement = NULL; + HASH_FIND_STR(_elements, key.c_str(), pElement); + removeObjectForElememt(pElement); +} + +void Dictionary::removeObjectForKey(intptr_t key) +{ + if (_dictType == kDictUnknown) + { + return; + } + + CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as its key"); + DictElement *pElement = NULL; + HASH_FIND_PTR(_elements, &key, pElement); + removeObjectForElememt(pElement); +} + +void Dictionary::setObjectUnSafe(Object* pObject, const std::string& key) +{ + pObject->retain(); + DictElement* pElement = new DictElement(key.c_str(), pObject); + HASH_ADD_STR(_elements, _strKey, pElement); +} + +void Dictionary::setObjectUnSafe(Object* pObject, const intptr_t key) +{ + pObject->retain(); + DictElement* pElement = new DictElement(key, pObject); + HASH_ADD_PTR(_elements, _intKey, pElement); +} + +void Dictionary::removeObjectsForKeys(Array* pKeyArray) +{ + Object* pObj = NULL; + CCARRAY_FOREACH(pKeyArray, pObj) + { + String* pStr = static_cast(pObj); + removeObjectForKey(pStr->getCString()); + } +} + +void Dictionary::removeObjectForElememt(DictElement* pElement) +{ + if (pElement != NULL) + { + HASH_DEL(_elements, pElement); + pElement->_object->release(); + CC_SAFE_DELETE(pElement); + } +} + +void Dictionary::removeAllObjects() +{ + DictElement *pElement, *tmp; + HASH_ITER(hh, _elements, pElement, tmp) + { + HASH_DEL(_elements, pElement); + pElement->_object->release(); + CC_SAFE_DELETE(pElement); + + } +} + +Object* Dictionary::randomObject() +{ + if (_dictType == kDictUnknown) + { + return NULL; + } + + Object* key = allKeys()->getRandomObject(); + + if (_dictType == kDictInt) + { + return objectForKey( static_cast(key)->getValue()); + } + else if (_dictType == kDictStr) + { + return objectForKey( static_cast(key)->getCString()); + } + else + { + return NULL; + } +} + +Dictionary* Dictionary::create() +{ + Dictionary* ret = new Dictionary(); + if (ret && ret->init() ) + { + ret->autorelease(); + } + return ret; +} + +bool Dictionary::init() +{ + return true; +} + +Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) +{ + return srcDict->clone(); +} + +Dictionary* Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName) +{ + return FileUtils::getInstance()->createDictionaryWithContentsOfFile(pFileName); +} + +void Dictionary::acceptVisitor(DataVisitor &visitor) +{ + return visitor.visit(this); +} + +Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) +{ + auto ret = createWithContentsOfFileThreadSafe(pFileName); + if (ret != nullptr) + { + ret->autorelease(); + } + return ret; +} + +bool Dictionary::writeToFile(const char *fullPath) +{ + return FileUtils::getInstance()->writeToFile(this, fullPath); +} + +Dictionary* Dictionary::clone() const +{ + Dictionary* newDict = Dictionary::create(); + + DictElement* element = NULL; + Object* tmpObj = NULL; + Clonable* obj = NULL; + if (_dictType == kDictInt) + { + CCDICT_FOREACH(this, element) + { + obj = dynamic_cast(element->getObject()); + if (obj) + { + tmpObj = dynamic_cast(obj->clone()); + if (tmpObj) + { + newDict->setObject(tmpObj, element->getIntKey()); + } + } + else + { + CCLOGWARN("%s isn't clonable.", typeid(*element->getObject()).name()); + } + } + } + else if (_dictType == kDictStr) + { + CCDICT_FOREACH(this, element) + { + obj = dynamic_cast(element->getObject()); + if (obj) + { + tmpObj = dynamic_cast(obj->clone()); + if (tmpObj) + { + newDict->setObject(tmpObj, element->getStrKey()); + } + } + else + { + CCLOGWARN("%s isn't clonable.", typeid(*element->getObject()).name()); + } + } + } + + return newDict; +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCDictionary.h b/cocos/base/cocoa/CCDictionary.h new file mode 100644 index 0000000000..b0f1c98a9c --- /dev/null +++ b/cocos/base/cocoa/CCDictionary.h @@ -0,0 +1,458 @@ +/**************************************************************************** +Copyright (c) 2012 - 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 __CCDICTIONARY_H__ +#define __CCDICTIONARY_H__ + +#include "support/data_support/uthash.h" +#include "CCObject.h" +#include "CCArray.h" +#include "CCString.h" + +NS_CC_BEGIN + +class Dictionary; + +/** + * @addtogroup data_structures + * @{ + */ + + +/** + * DictElement is used for traversing Dictionary. + * + * A DictElement is one element of Dictionary, it contains two properties, key and object. + * Its key has two different type (integer and string). + * + * @note The key type is unique, all the elements in Dictionary has the same key type(integer or string). + * @code + * DictElement* pElement; + * CCDICT_FOREACH(dict, pElement) + * { + * const char*key = pElement->getStrKey(); + * // You certainly know the type of value, so we assume that it's a Sprite. + * Sprite* pSprite = static_cast(pElement->getObject()); + * // ...... + * } + * @endcode + * + */ +class CC_DLL DictElement +{ +private: + /** + * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class. + * + * @param pszKey The string key of this element. + * @param pObject The object of this element. + */ + DictElement(const char* pszKey, Object* pObject); + + /** + * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class. + * + * @param iKey The integer key of this element. + * @param pObject The object of this element. + */ + DictElement(intptr_t iKey, Object* pObject); + +public: + /** + * The destructor of DictElement. + * @js NA + * @lua NA + */ + ~DictElement(); + + // Inline functions need to be implemented in header file on Android. + + /** + * Get the string key of this element. + * @note This method assumes you know the key type in the element. + * If the element's key type is integer, invoking this method will cause an assert. + * + * @return The string key of this element. + */ + inline const char* getStrKey() const + { + CCASSERT(_strKey[0] != '\0', "Should not call this function for integer dictionary"); + return _strKey; + } + + /** + * Get the integer key of this element. + * @note This method assumes you know the key type in the element. + * If the element's key type is string, invoking this method will cause an assert. + * + * @return The integer key of this element. + */ + inline intptr_t getIntKey() const + { + CCASSERT(_strKey[0] == '\0', "Should not call this function for string dictionary"); + return _intKey; + } + + /** + * Get the object of this element. + * + * @return The object of this element. + */ + inline Object* getObject() const { return _object; } + +private: + // The max length of string key. + #define MAX_KEY_LEN 256 + // char array is needed for HASH_ADD_STR in UT_HASH. + // So it's a pain that all elements will allocate 256 bytes for this array. + char _strKey[MAX_KEY_LEN]; // hash key of string type + intptr_t _intKey; // hash key of integer type + Object* _object; // hash value +public: + UT_hash_handle hh; // makes this class hashable + friend class Dictionary; // declare Dictionary as friend class +}; + +/** The macro for traversing dictionary + * + * @note It's faster than getting all keys and traversing keys to get objects by objectForKey. + * It's also safe to remove elements while traversing. + */ +#define CCDICT_FOREACH(__dict__, __el__) \ + DictElement* pTmp##__dict__##__el__ = nullptr; \ + if (__dict__) \ + HASH_ITER(hh, (__dict__)->_elements, __el__, pTmp##__dict__##__el__) + + + +/** + * Dictionary is a class like NSDictionary in Obj-C . + * + * @note Only the pointer of Object or its subclass can be inserted to Dictionary. + * @code + * // Create a dictionary, return an autorelease object. + * Dictionary* pDict = Dictionary::create(); + * + * // Insert objects to dictionary + * String* pValue1 = String::create("100"); + * String* pValue2 = String::create("120"); + * Integer* pValue3 = Integer::create(200); + * pDict->setObject(pValue1, "key1"); + * pDict->setObject(pValue2, "key2"); + * pDict->setObject(pValue3, "key3"); + * + * // Get the object for key + * String* pStr1 = (String*)pDict->objectForKey("key1"); + * log("{ key1: %s }", pStr1->getCString()); + * Integer* pInteger = (Integer*)pDict->objectForKey("key3"); + * log("{ key3: %d }", pInteger->getValue()); + * @endcode + * + */ + +class CC_DLL Dictionary : public Object, public Clonable +{ +public: + /** + * The constructor of Dictionary. + * @js NA + * @lua NA + */ + Dictionary(); + + /** + * The destructor of Dictionary + * @js NA + * @lua NA + */ + ~Dictionary(); + + /** Initializes the dictionary. It returns true if the initializations was successful. + * @js NA + * @lua NA + */ + bool init(); + /** + * Get the count of elements in Dictionary. + * + * @return The count of elements. + * @js NA + */ + unsigned int count(); + + /** + * Return all keys of elements. + * + * @return The array contains all keys of elements. It's an autorelease object yet. + * @js NA + */ + Array* allKeys(); + + /** + * Get all keys according to the specified object. + * @warning We use '==' to compare two objects + * @return The array contains all keys for the specified object. It's an autorelease object yet. + * @js NA + */ + Array* allKeysForObject(Object* object); + + /** + * Get the object according to the specified string key. + * + * @note The dictionary needs to use string as key. If integer is passed, an assert will appear. + * @param key The string key for searching. + * @return The object matches the key. You need to force convert it to the type you know. + * @code + * // Assume that the elements are String* pointers. Convert it by following code. + * String* pStr = (String*)pDict->objectForKey("key1"); + * // Do something about pStr. + * // If you don't know the object type, properly you need to use dynamic_cast to check it. + * String* pStr2 = dynamic_cast(pDict->objectForKey("key1")); + * if (pStr2 != NULL) { + * // Do something about pStr2 + * } + * @endcode + * @see objectForKey(intptr_t) + * @js NA + */ + Object* objectForKey(const std::string& key); + + /** + * Get the object according to the specified integer key. + * + * @note The dictionary needs to use integer as key. If string is passed, an assert will appear. + * @param key The integer key for searching. + * @return The object matches the key. + * @see objectForKey(const std::string&) + * @js NA + */ + Object* objectForKey(intptr_t key); + + /** Get the value according to the specified string key. + * + * @note Be careful to use this function since it assumes the objects in the dictionary are String pointer. + * @param key The string key for searching + * @return An instance of String. + * It will return an empty string if the objects aren't String pointer or the key wasn't found. + * @see valueForKey(intptr_t) + * @js NA + */ + const String* valueForKey(const std::string& key); + + /** Get the value according to the specified integer key. + * + * @note Be careful to use this function since it assumes the objects in the dictionary are String pointer. + * @param key The string key for searching. + * @return An instance of String. + * It will return an empty string if the objects aren't String pointer or the key wasn't found. + * @see valueForKey(intptr_t) + * @js NA + */ + const String* valueForKey(intptr_t key); + + /** Insert an object to dictionary, and match it with the specified string key. + * + * @note Whe the first time this method is invoked, the key type will be set to string. + * After that you can't setObject with an integer key. + * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary. + * Then the new object will be inserted after that. + * + * @param pObject The Object to be inserted. + * @param key The string key for searching. + * @see setObject(Object*, intptr_t) + * @js NA + */ + void setObject(Object* pObject, const std::string& key); + + /** Insert an object to dictionary, and match it with the specified string key. + * + * @note Then the first time this method is invoked, the key type will be set to string. + * After that you can't setObject with an integer key. + * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary. + * Then the new object will be inserted after that. + * @param pObject The Object to be inserted. + * @param key The string key for searching. + * @see setObject(Object*, const std::string&) + * @js NA + */ + void setObject(Object* pObject, intptr_t key); + + /** + * Remove an object by the specified string key. + * + * @param key The string key for searching. + * @see removeObjectForKey(intptr_t), removeObjectsForKeys(Array*), + * removeObjectForElememt(DictElement*), removeAllObjects(). + * @js NA + */ + void removeObjectForKey(const std::string& key); + + /** + * Remove an object by the specified integer key. + * + * @param key The integer key for searching. + * @see removeObjectForKey(const std::string&), removeObjectsForKeys(Array*), + * removeObjectForElememt(DictElement*), removeAllObjects(). + * @js NA + */ + void removeObjectForKey(intptr_t key); + + /** + * Remove objects by an array of keys. + * + * @param pKeyArray The array contains keys to be removed. + * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), + * removeObjectForElememt(DictElement*), removeAllObjects(). + * @js NA + */ + void removeObjectsForKeys(Array* pKeyArray); + + /** + * Remove an object by an element. + * + * @param pElement The element need to be removed. + * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), + * removeObjectsForKeys(Array*), removeAllObjects(). + * @js NA + * @lua NA + */ + void removeObjectForElememt(DictElement* pElement); + + /** + * Remove all objects in the dictionary. + * + * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), + * removeObjectsForKeys(Array*), removeObjectForElememt(DictElement*). + * @js NA + */ + void removeAllObjects(); + + /** + * Return a random object in the dictionary. + * + * @return The random object. + * @see objectForKey(intptr_t), objectForKey(const std::string&) + * @js NA + * @lua NA + */ + Object* randomObject(); + + /** + * Create a dictionary. + * @return A dictionary which is an autorelease object. + * @see createWithDictionary(Dictionary*), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*). + * @js NA + */ + static Dictionary* create(); + + /** + * Create a dictionary with an existing dictionary. + * + * @param srcDict The exist dictionary. + * @return A dictionary which is an autorelease object. + * @see create(), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*). + * @js NA + */ + static Dictionary* createWithDictionary(Dictionary* srcDict); + + /** + * Create a dictionary with a plist file. + * @param pFileName The name of the plist file. + * @return A dictionary which is an autorelease object. + * @see create(), createWithDictionary(Dictionary*), createWithContentsOfFileThreadSafe(const char*). + * @js NA + */ + static Dictionary* createWithContentsOfFile(const char *pFileName); + + /** + * Write a dictionary to a plist file. + * @param fullPath The full path of the plist file. You can get writeable path by getWritablePath() + * @return true if successed, false if failed + * @js NA + * @lua NA + */ + bool writeToFile(const char *fullPath); + + /** + * Create a dictionary with a plist file. + * + * @note the return object isn't an autorelease object. + * This can make sure not using autorelease pool in a new thread. + * Therefore, you need to manage the lifecycle of the return object. + * It means that when you don't need it, CC_SAFE_RELEASE needs to be invoked. + * + * @param pFileName The name of the plist file. + * @return A dictionary which isn't an autorelease object. + * @js NA + * @lua NA + */ + static Dictionary* createWithContentsOfFileThreadSafe(const char *pFileName); + + /* override functions + * @js NA + * @lua NA + */ + virtual void acceptVisitor(DataVisitor &visitor); + /** + * @js NA + * @lua NA + */ + virtual Dictionary* clone() const; + +private: + /** + * For internal usage, invoked by setObject. + */ + void setObjectUnSafe(Object* pObject, const std::string& key); + void setObjectUnSafe(Object* pObject, const intptr_t key); + +public: + /** + * All the elements in dictionary. + * + * @note For internal usage, we need to declare this member variable as public since it's used in UT_HASH. + */ + DictElement* _elements; +private: + + /** The support type of dictionary, it's confirmed when setObject is invoked. */ + enum DictType + { + kDictUnknown = 0, + kDictStr, + kDictInt + }; + + /** + * The type of dictionary, it's assigned to kDictUnknown by default. + */ + DictType _dictType; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCDICTIONARY_H__ */ diff --git a/cocos/base/cocoa/CCDouble.h b/cocos/base/cocoa/CCDouble.h new file mode 100644 index 0000000000..5b45b1d6cf --- /dev/null +++ b/cocos/base/cocoa/CCDouble.h @@ -0,0 +1,70 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 __CCDOUBLE_H__ +#define __CCDOUBLE_H__ + +#include "CCObject.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +class CC_DLL Double : public Object, public Clonable +{ +public: + Double(double v) + : _value(v) {} + double getValue() const {return _value;} + + static Double* create(double v) + { + Double* pRet = new Double(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + /* override functions */ + virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } + + Double* clone() const + { + return Double::create(_value); + } +private: + double _value; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCDOUBLE_H__ */ diff --git a/cocos/base/cocoa/CCFloat.h b/cocos/base/cocoa/CCFloat.h new file mode 100644 index 0000000000..c85a2e1e70 --- /dev/null +++ b/cocos/base/cocoa/CCFloat.h @@ -0,0 +1,71 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 __CCFLOAT_H__ +#define __CCFLOAT_H__ + +#include "CCObject.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +class CC_DLL Float : public Object, public Clonable +{ +public: + Float(float v) + : _value(v) {} + float getValue() const {return _value;} + + static Float* create(float v) + { + Float* pRet = new Float(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + /* override functions */ + virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } + + Float* clone() const + { + return Float::create(_value); + } + +private: + float _value; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCFLOAT_H__ */ diff --git a/cocos/base/cocoa/CCGeometry.cpp b/cocos/base/cocoa/CCGeometry.cpp new file mode 100644 index 0000000000..cfce9d3fa7 --- /dev/null +++ b/cocos/base/cocoa/CCGeometry.cpp @@ -0,0 +1,463 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "CCGeometry.h" +#include "ccMacros.h" +#include + +// implementation of Point +NS_CC_BEGIN + +Point::Point(void) : x(0), y(0) +{ +} + +Point::Point(float xx, float yy) : x(xx), y(yy) +{ +} + +Point::Point(const Point& other) : x(other.x), y(other.y) +{ +} + +Point::Point(const Size& size) : x(size.width), y(size.height) +{ +} + +Point& Point::operator= (const Point& other) +{ + setPoint(other.x, other.y); + return *this; +} + +Point& Point::operator= (const Size& size) +{ + setPoint(size.width, size.height); + return *this; +} + +Point Point::operator+(const Point& right) const +{ + return Point(this->x + right.x, this->y + right.y); +} + +Point Point::operator-(const Point& right) const +{ + return Point(this->x - right.x, this->y - right.y); +} + +Point Point::operator-() const +{ + return Point(-x, -y); +} + +Point Point::operator*(float a) const +{ + return Point(this->x * a, this->y * a); +} + +Point Point::operator/(float a) const +{ + CCASSERT(a!=0, "CCPoint division by 0."); + return Point(this->x / a, this->y / a); +} + +void Point::setPoint(float xx, float yy) +{ + this->x = xx; + this->y = yy; +} + +bool Point::equals(const Point& target) const +{ + return (fabs(this->x - target.x) < FLT_EPSILON) + && (fabs(this->y - target.y) < FLT_EPSILON); +} + +bool Point::fuzzyEquals(const Point& b, float var) const +{ + if(x - var <= b.x && b.x <= x + var) + if(y - var <= b.y && b.y <= y + var) + return true; + return false; +} + +float Point::getAngle(const Point& other) const +{ + Point a2 = normalize(); + Point b2 = other.normalize(); + float angle = atan2f(a2.cross(b2), a2.dot(b2)); + if( fabs(angle) < FLT_EPSILON ) return 0.f; + return angle; +} + +Point Point::rotateByAngle(const Point& pivot, float angle) const +{ + return pivot + (*this - pivot).rotate(Point::forAngle(angle)); +} + +bool Point::isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float *E) +{ + float ABmin = MIN(A, B); + float ABmax = MAX(A, B); + float CDmin = MIN(C, D); + float CDmax = MAX(C, D); + + if (ABmax < CDmin || CDmax < ABmin) + { + // ABmin->ABmax->CDmin->CDmax or CDmin->CDmax->ABmin->ABmax + return false; + } + else + { + if (ABmin >= CDmin && ABmin <= CDmax) + { + // CDmin->ABmin->CDmax->ABmax or CDmin->ABmin->ABmax->CDmax + if (S != nullptr) *S = ABmin; + if (E != nullptr) *E = CDmax < ABmax ? CDmax : ABmax; + } + else if (ABmax >= CDmin && ABmax <= CDmax) + { + // ABmin->CDmin->ABmax->CDmax + if (S != nullptr) *S = CDmin; + if (E != nullptr) *E = ABmax; + } + else + { + // ABmin->CDmin->CDmax->ABmax + if (S != nullptr) *S = CDmin; + if (E != nullptr) *E = CDmax; + } + return true; + } +} + +bool Point::isLineIntersect(const Point& A, const Point& B, + const Point& C, const Point& D, + float *S, float *T) +{ + // FAIL: Line undefined + if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) + { + return false; + } + + const float denom = crossProduct2Vector(A, B, C, D); + + if (denom == 0) + { + // Lines parallel or overlap + return false; + } + + if (S != nullptr) *S = crossProduct2Vector(C, D, C, A) / denom; + if (T != nullptr) *T = crossProduct2Vector(A, B, C, A) / denom; + + return true; +} + +bool Point::isLineParallel(const Point& A, const Point& B, + const Point& C, const Point& D) +{ + // FAIL: Line undefined + if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) + { + return false; + } + + if (crossProduct2Vector(A, B, C, D) == 0) + { + // line overlap + if (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0) + { + return false; + } + + return true; + } + + return false; +} + +bool Point::isLineOverlap(const Point& A, const Point& B, + const Point& C, const Point& D) +{ + // FAIL: Line undefined + if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) + { + return false; + } + + if (crossProduct2Vector(A, B, C, D) == 0 && + (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0)) + { + return true; + } + + return false; +} + +bool Point::isSegmentOverlap(const Point& A, const Point& B, const Point& C, const Point& D, Point* S, Point* E) +{ + + if (isLineOverlap(A, B, C, D)) + { + return isOneDemensionSegmentOverlap(A.x, B.x, C.x, D.x, &S->x, &E->x) && + isOneDemensionSegmentOverlap(A.y, B.y, C.y, D.y, &S->y, &E->y); + } + + return false; +} + +bool Point::isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D) +{ + float S, T; + + if (isLineIntersect(A, B, C, D, &S, &T )&& + (S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f)) + { + return true; + } + + return false; +} + +Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D) +{ + float S, T; + + if (isLineIntersect(A, B, C, D, &S, &T)) + { + // Point of intersection + Point P; + P.x = A.x + S * (B.x - A.x); + P.y = A.y + S * (B.y - A.y); + return P; + } + + return Point::ZERO; +} + +const Point Point::ZERO = Point(0, 0); + +// implementation of Size + +Size::Size(void) : width(0), height(0) +{ +} + +Size::Size(float w, float h) : width(w), height(h) +{ +} + +Size::Size(const Size& other) : width(other.width), height(other.height) +{ +} + +Size::Size(const Point& point) : width(point.x), height(point.y) +{ +} + +Size& Size::operator= (const Size& other) +{ + setSize(other.width, other.height); + return *this; +} + +Size& Size::operator= (const Point& point) +{ + setSize(point.x, point.y); + return *this; +} + +Size Size::operator+(const Size& right) const +{ + return Size(this->width + right.width, this->height + right.height); +} + +Size Size::operator-(const Size& right) const +{ + return Size(this->width - right.width, this->height - right.height); +} + +Size Size::operator*(float a) const +{ + return Size(this->width * a, this->height * a); +} + +Size Size::operator/(float a) const +{ + CCASSERT(a!=0, "CCSize division by 0."); + return Size(this->width / a, this->height / a); +} + +void Size::setSize(float w, float h) +{ + this->width = w; + this->height = h; +} + +bool Size::equals(const Size& target) const +{ + return (fabs(this->width - target.width) < FLT_EPSILON) + && (fabs(this->height - target.height) < FLT_EPSILON); +} + +const Size Size::ZERO = Size(0, 0); + +// implementation of Rect + +Rect::Rect(void) +{ + setRect(0.0f, 0.0f, 0.0f, 0.0f); +} + +Rect::Rect(float x, float y, float width, float height) +{ + setRect(x, y, width, height); +} + +Rect::Rect(const Rect& other) +{ + setRect(other.origin.x, other.origin.y, other.size.width, other.size.height); +} + +Rect& Rect::operator= (const Rect& other) +{ + setRect(other.origin.x, other.origin.y, other.size.width, other.size.height); + return *this; +} + +void Rect::setRect(float x, float y, float width, float height) +{ + // CGRect can support width<0 or height<0 + // CCASSERT(width >= 0.0f && height >= 0.0f, "width and height of Rect must not less than 0."); + + origin.x = x; + origin.y = y; + + size.width = width; + size.height = height; +} + +bool Rect::equals(const Rect& rect) const +{ + return (origin.equals(rect.origin) && + size.equals(rect.size)); +} + +float Rect::getMaxX() const +{ + return origin.x + size.width; +} + +float Rect::getMidX() const +{ + return origin.x + size.width / 2.0f; +} + +float Rect::getMinX() const +{ + return origin.x; +} + +float Rect::getMaxY() const +{ + return origin.y + size.height; +} + +float Rect::getMidY() const +{ + return origin.y + size.height / 2.0f; +} + +float Rect::getMinY() const +{ + return origin.y; +} + +bool Rect::containsPoint(const Point& point) const +{ + bool bRet = false; + + if (point.x >= getMinX() && point.x <= getMaxX() + && point.y >= getMinY() && point.y <= getMaxY()) + { + bRet = true; + } + + return bRet; +} + +bool Rect::intersectsRect(const Rect& rect) const +{ + return !( getMaxX() < rect.getMinX() || + rect.getMaxX() < getMinX() || + getMaxY() < rect.getMinY() || + rect.getMaxY() < getMinY()); +} + +Rect Rect::unionWithRect(const Rect & rect) const +{ + float thisLeftX = origin.x; + float thisRightX = origin.x + size.width; + float thisTopY = origin.y + size.height; + float thisBottomY = origin.y; + + if (thisRightX < thisLeftX) + { + std::swap(thisRightX, thisLeftX); // This rect has negative width + } + + if (thisTopY < thisBottomY) + { + std::swap(thisTopY, thisBottomY); // This rect has negative height + } + + float otherLeftX = rect.origin.x; + float otherRightX = rect.origin.x + rect.size.width; + float otherTopY = rect.origin.y + rect.size.height; + float otherBottomY = rect.origin.y; + + if (otherRightX < otherLeftX) + { + std::swap(otherRightX, otherLeftX); // Other rect has negative width + } + + if (otherTopY < otherBottomY) + { + std::swap(otherTopY, otherBottomY); // Other rect has negative height + } + + float combinedLeftX = std::min(thisLeftX, otherLeftX); + float combinedRightX = std::max(thisRightX, otherRightX); + float combinedTopY = std::max(thisTopY, otherTopY); + float combinedBottomY = std::min(thisBottomY, otherBottomY); + + return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY); +} + +const Rect Rect::ZERO = Rect(0, 0, 0, 0); + +NS_CC_END diff --git a/cocos/base/cocoa/CCGeometry.h b/cocos/base/cocoa/CCGeometry.h new file mode 100644 index 0000000000..47e2fdf9ac --- /dev/null +++ b/cocos/base/cocoa/CCGeometry.h @@ -0,0 +1,564 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __CCGEMETRY_H__ +#define __CCGEMETRY_H__ + +#include +#include + +#include "platform/CCPlatformMacros.h" +#include "CCObject.h" +#include "ccMacros.h" + +NS_CC_BEGIN + +/** Clamp a value between from and to. + @since v0.99.1 + */ +inline float clampf(float value, float min_inclusive, float max_inclusive) +{ + if (min_inclusive > max_inclusive) { + CC_SWAP(min_inclusive, max_inclusive, float); + } + return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive; +} + +/** + * @addtogroup data_structures + * @{ + */ + +// for Point assignement operator and copy constructor +class CC_DLL Size; + +class CC_DLL Point +{ +public: + float x; + float y; + +public: + /** + * @js NA + */ + Point(); + /** + * @js NA + */ + Point(float x, float y); + /** + * @js NA + * @lua NA + */ + Point(const Point& other); + /** + * @js NA + * @lua NA + */ + explicit Point(const Size& size); + /** + * @js NA + * @lua NA + */ + Point& operator= (const Point& other); + /** + * @js NA + * @lua NA + */ + Point& operator= (const Size& size); + /** + * @js NA + * @lua NA + */ + Point operator+(const Point& right) const; + /** + * @js NA + * @lua NA + */ + Point operator-(const Point& right) const; + /** + * @js NA + * @lua NA + */ + Point operator-() const; + /** + * @js NA + * @lua NA + */ + Point operator*(float a) const; + /** + * @js NA + * @lua NA + */ + Point operator/(float a) const; + /** + * @js NA + * @lua NA + */ + void setPoint(float x, float y); + /** + * @js NA + */ + bool equals(const Point& target) const; + + /** @returns if points have fuzzy equality which means equal with some degree of variance. + @since v2.1.4 + * @js NA + * @lua NA + */ + bool fuzzyEquals(const Point& target, float variance) const; + + /** Calculates distance between point an origin + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float getLength() const { + return sqrtf(x*x + y*y); + }; + + /** Calculates the square length of a Point (not calling sqrt() ) + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float getLengthSq() const { + return dot(*this); //x*x + y*y; + }; + + /** Calculates the square distance between two points (not calling sqrt() ) + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float getDistanceSq(const Point& other) const { + return (*this - other).getLengthSq(); + }; + + /** Calculates the distance between two points + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float getDistance(const Point& other) const { + return (*this - other).getLength(); + }; + + /** @returns the angle in radians between this vector and the x axis + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float getAngle() const { + return atan2f(y, x); + }; + + /** @returns the angle in radians between two vector directions + @since v2.1.4 + * @js NA + * @lua NA + */ + float getAngle(const Point& other) const; + + /** Calculates dot product of two points. + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float dot(const Point& other) const { + return x*other.x + y*other.y; + }; + + /** Calculates cross product of two points. + @return float + @since v2.1.4 + * @js NA + * @lua NA + */ + inline float cross(const Point& other) const { + return x*other.y - y*other.x; + }; + + /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 + @return Point + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point getPerp() const { + return Point(-y, x); + }; + + /** Calculates midpoint between two points. + @return Point + @since v3.0 + * @js NA + * @lua NA + */ + inline Point getMidpoint(const Point& other) const + { + return Point((x + other.x) / 2.0f, (y + other.y) / 2.0f); + } + + /** Clamp a point between from and to. + @since v3.0 + * @js NA + * @lua NA + */ + inline Point getClampPoint(const Point& min_inclusive, const Point& max_inclusive) const + { + return Point(clampf(x,min_inclusive.x,max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y)); + } + + /** Run a math operation function on each point component + * absf, fllorf, ceilf, roundf + * any function that has the signature: float func(float); + * For example: let's try to take the floor of x,y + * p.compOp(floorf); + @since v3.0 + * @js NA + * @lua NA + */ + inline Point compOp(std::function function) const + { + return Point(function(x), function(y)); + } + + /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 + @return Point + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point getRPerp() const { + return Point(y, -x); + }; + + /** Calculates the projection of this over other. + @return Point + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point project(const Point& other) const { + return other * (dot(other)/other.dot(other)); + }; + + /** Complex multiplication of two points ("rotates" two points). + @return Point vector with an angle of this.getAngle() + other.getAngle(), + and a length of this.getLength() * other.getLength(). + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point rotate(const Point& other) const { + return Point(x*other.x - y*other.y, x*other.y + y*other.x); + }; + + /** Unrotates two points. + @return Point vector with an angle of this.getAngle() - other.getAngle(), + and a length of this.getLength() * other.getLength(). + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point unrotate(const Point& other) const { + return Point(x*other.x + y*other.y, y*other.x - x*other.y); + }; + + /** Returns point multiplied to a length of 1. + * If the point is 0, it returns (1, 0) + @return Point + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point normalize() const { + float length = getLength(); + if(length == 0.) return Point(1.f, 0); + return *this / getLength(); + }; + + /** Linear Interpolation between two points a and b + @returns + alpha == 0 ? a + alpha == 1 ? b + otherwise a value between a..b + @since v2.1.4 + * @js NA + * @lua NA + */ + inline Point lerp(const Point& other, float alpha) const { + return *this * (1.f - alpha) + other * alpha; + }; + + /** Rotates a point counter clockwise by the angle around a pivot + @param pivot is the pivot, naturally + @param angle is the angle of rotation ccw in radians + @returns the rotated point + @since v2.1.4 + * @js NA + * @lua NA + */ + Point rotateByAngle(const Point& pivot, float angle) const; + + /** + * @js NA + * @lua NA + */ + static inline Point forAngle(const float a) + { + return Point(cosf(a), sinf(a)); + } + + /** A general line-line intersection test + @param A the startpoint for the first line L1 = (A - B) + @param B the endpoint for the first line L1 = (A - B) + @param C the startpoint for the second line L2 = (C - D) + @param D the endpoint for the second line L2 = (C - D) + @param S the range for a hitpoint in L1 (p = A + S*(B - A)) + @param T the range for a hitpoint in L2 (p = C + T*(D - C)) + @returns whether these two lines interects. + + Note that to truly test intersection for segments we have to make + sure that S & T lie within [0..1] and for rays, make sure S & T > 0 + the hit point is C + T * (D - C); + the hit point also is A + S * (B - A); + @since 3.0 + * @js NA + * @lua NA + */ + static bool isLineIntersect(const Point& A, const Point& B, + const Point& C, const Point& D, + float *S = nullptr, float *T = nullptr); + + /** + returns true if Line A-B overlap with segment C-D + @since v3.0 + * @js NA + * @lua NA + */ + static bool isLineOverlap(const Point& A, const Point& B, + const Point& C, const Point& D); + + /** + returns true if Line A-B parallel with segment C-D + @since v3.0 + * @js NA + * @lua NA + */ + static bool isLineParallel(const Point& A, const Point& B, + const Point& C, const Point& D); + + /** + returns true if Segment A-B overlap with segment C-D + @since v3.0 + * @js NA + * @lua NA + */ + static bool isSegmentOverlap(const Point& A, const Point& B, + const Point& C, const Point& D, + Point* S = nullptr, Point* E = nullptr); + + /** + returns true if Segment A-B intersects with segment C-D + @since v3.0 + * @js NA + * @lua NA + */ + static bool isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D); + + /** + returns the intersection point of line A-B, C-D + @since v3.0 + * @js NA + * @lua NA + */ + static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); + + static const Point ZERO; + +private: + // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part + static bool isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E); + + // cross procuct of 2 vector. A->B X C->D + static float crossProduct2Vector(const Point& A, const Point& B, const Point& C, const Point& D) { return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y); } +}; + +class CC_DLL Size +{ +public: + float width; + float height; + +public: + /** + * @js NA + */ + Size(); + /** + * @js NA + */ + Size(float width, float height); + /** + * @js NA + * @lua NA + */ + Size(const Size& other); + /** + * @js NA + * @lua NA + */ + explicit Size(const Point& point); + /** + * @js NA + * @lua NA + */ + Size& operator= (const Size& other); + /** + * @js NA + * @lua NA + */ + Size& operator= (const Point& point); + /** + * @js NA + * @lua NA + */ + Size operator+(const Size& right) const; + /** + * @js NA + * @lua NA + */ + Size operator-(const Size& right) const; + /** + * @js NA + * @lua NA + */ + Size operator*(float a) const; + /** + * @js NA + * @lua NA + */ + Size operator/(float a) const; + /** + * @js NA + * @lua NA + */ + void setSize(float width, float height); + /** + * @js NA + */ + bool equals(const Size& target) const; + + static const Size ZERO; +}; + +class CC_DLL Rect +{ +public: + Point origin; + Size size; + +public: + /** + * @js NA + */ + Rect(); + /** + * @js NA + */ + Rect(float x, float y, float width, float height); + /** + * @js NA + * @lua NA + */ + Rect(const Rect& other); + /** + * @js NA + * @lua NA + */ + Rect& operator= (const Rect& other); + /** + * @js NA + * @lua NA + */ + void setRect(float x, float y, float width, float height); + /** + * @js NA + */ + float getMinX() const; /// return the leftmost x-value of current rect + /** + * @js NA + */ + float getMidX() const; /// return the midpoint x-value of current rect + /** + * @js NA + */ + float getMaxX() const; /// return the rightmost x-value of current rect + /** + * @js NA + */ + float getMinY() const; /// return the bottommost y-value of current rect + /** + * @js NA + */ + float getMidY() const; /// return the midpoint y-value of current rect + /** + * @js NA + */ + float getMaxY() const; /// return the topmost y-value of current rect + /** + * @js NA + */ + bool equals(const Rect& rect) const; + /** + * @js NA + */ + bool containsPoint(const Point& point) const; + /** + * @js NA + */ + bool intersectsRect(const Rect& rect) const; + /** + * @js NA + * @lua NA + */ + Rect unionWithRect(const Rect & rect) const; + + static const Rect ZERO; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCGEMETRY_H__ diff --git a/cocos/base/cocoa/CCInteger.h b/cocos/base/cocoa/CCInteger.h new file mode 100644 index 0000000000..23735627dd --- /dev/null +++ b/cocos/base/cocoa/CCInteger.h @@ -0,0 +1,79 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 __CCINTEGER_H__ +#define __CCINTEGER_H__ + +#include "CCObject.h" +#include "platform/CCCommon.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +class CC_DLL Integer : public Object, public Clonable +{ +public: + static Integer* create(int v) + { + Integer* pRet = new Integer(v); + pRet->autorelease(); + return pRet; + } + /** + * @js NA + */ + Integer(int v) + : _value(v) {} + int getValue() const {return _value;} + /** + * @js NA + * @lua NA + */ + virtual ~Integer() { + CCLOGINFO("deallocing ~Integer: %p", this); + } + + /* override functions */ + virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } + + // overrides + virtual Integer* clone() const override + { + return Integer::create(_value); + } + +private: + int _value; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif /* __CCINTEGER_H__ */ diff --git a/cocos/base/cocoa/CCNS.cpp b/cocos/base/cocoa/CCNS.cpp new file mode 100644 index 0000000000..8cf496c0b1 --- /dev/null +++ b/cocos/base/cocoa/CCNS.cpp @@ -0,0 +1,185 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "CCNS.h" +#include +#include +#include +#include + +using namespace std; + +NS_CC_BEGIN + +typedef std::vector strArray; + +// string toolkit +static inline void split(std::string src, const char* token, strArray& vect) +{ + int nend=0; + int nbegin=0; + while(nend != -1) + { + nend = src.find(token, nbegin); + if(nend == -1) + vect.push_back(src.substr(nbegin, src.length()-nbegin)); + else + vect.push_back(src.substr(nbegin, nend-nbegin)); + nbegin = nend + strlen(token); + } +} + +// first, judge whether the form of the string like this: {x,y} +// if the form is right,the string will be split into the parameter strs; +// or the parameter strs will be empty. +// if the form is right return true,else return false. +static bool splitWithForm(const char* pStr, strArray& strs) +{ + bool bRet = false; + + do + { + CC_BREAK_IF(!pStr); + + // string is empty + std::string content = pStr; + CC_BREAK_IF(content.length() == 0); + + int nPosLeft = content.find('{'); + int nPosRight = content.find('}'); + + // don't have '{' and '}' + CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); + // '}' is before '{' + CC_BREAK_IF(nPosLeft > nPosRight); + + std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); + // nothing between '{' and '}' + CC_BREAK_IF(pointStr.length() == 0); + + int nPos1 = pointStr.find('{'); + int nPos2 = pointStr.find('}'); + // contain '{' or '}' + CC_BREAK_IF(nPos1 != (int)std::string::npos || nPos2 != (int)std::string::npos); + + split(pointStr, ",", strs); + if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0) + { + strs.clear(); + break; + } + + bRet = true; + } while (0); + + return bRet; +} + +// implement the functions + +Rect RectFromString(const char* pszContent) +{ + Rect result = Rect::ZERO; + + do + { + CC_BREAK_IF(!pszContent); + std::string content = pszContent; + + // find the first '{' and the third '}' + int nPosLeft = content.find('{'); + int nPosRight = content.find('}'); + for (int i = 1; i < 3; ++i) + { + if (nPosRight == (int)std::string::npos) + { + break; + } + nPosRight = content.find('}', nPosRight + 1); + } + CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); + + content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); + int nPointEnd = content.find('}'); + CC_BREAK_IF(nPointEnd == (int)std::string::npos); + nPointEnd = content.find(',', nPointEnd); + CC_BREAK_IF(nPointEnd == (int)std::string::npos); + + // get the point string and size string + std::string pointStr = content.substr(0, nPointEnd); + std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); + + // split the string with ',' + strArray pointInfo; + CC_BREAK_IF(!splitWithForm(pointStr.c_str(), pointInfo)); + strArray sizeInfo; + CC_BREAK_IF(!splitWithForm(sizeStr.c_str(), sizeInfo)); + + float x = (float) atof(pointInfo[0].c_str()); + float y = (float) atof(pointInfo[1].c_str()); + float width = (float) atof(sizeInfo[0].c_str()); + float height = (float) atof(sizeInfo[1].c_str()); + + result = Rect(x, y, width, height); + } while (0); + + return result; +} + +Point PointFromString(const char* pszContent) +{ + Point ret = Point::ZERO; + + do + { + strArray strs; + CC_BREAK_IF(!splitWithForm(pszContent, strs)); + + float x = (float) atof(strs[0].c_str()); + float y = (float) atof(strs[1].c_str()); + + ret = Point(x, y); + } while (0); + + return ret; +} + +Size SizeFromString(const char* pszContent) +{ + Size ret = Size::ZERO; + + do + { + strArray strs; + CC_BREAK_IF(!splitWithForm(pszContent, strs)); + + float width = (float) atof(strs[0].c_str()); + float height = (float) atof(strs[1].c_str()); + + ret = Size(width, height); + } while (0); + + return ret; +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCNS.h b/cocos/base/cocoa/CCNS.h new file mode 100644 index 0000000000..8ce8e1dde6 --- /dev/null +++ b/cocos/base/cocoa/CCNS.h @@ -0,0 +1,80 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __PLATFOMR_CCNS_H__ +#define __PLATFOMR_CCNS_H__ + +#include "CCGeometry.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +/** +@brief Returns a Core Graphics rectangle structure corresponding to the data in a given string. +@param pszContent A string object whose contents are of the form "{{x,y},{w, h}}", + where x is the x coordinate, y is the y coordinate, w is the width, and h is the height. + These components can represent integer or float values. + An example of a valid string is "{{3,2},{4,5}}". + The string is not localized, so items are always separated with a comma. +@return A Core Graphics structure that represents a rectangle. + If the string is not well-formed, the function returns Rect::ZERO. +*/ +Rect CC_DLL RectFromString(const char* pszContent); + +/** +@brief Returns a Core Graphics point structure corresponding to the data in a given string. +@param pszContent A string object whose contents are of the form "{x,y}", + where x is the x coordinate and y is the y coordinate. + The x and y values can represent integer or float values. + An example of a valid string is "{3.0,2.5}". + The string is not localized, so items are always separated with a comma. +@return A Core Graphics structure that represents a point. + If the string is not well-formed, the function returns Point::ZERO. +*/ +Point CC_DLL PointFromString(const char* pszContent); + +/** +@brief Returns a Core Graphics size structure corresponding to the data in a given string. +@param pszContent A string object whose contents are of the form "{w, h}", + where w is the width and h is the height. + The w and h values can be integer or float values. + An example of a valid string is "{3.0,2.5}". + The string is not localized, so items are always separated with a comma. +@return A Core Graphics structure that represents a size. + If the string is not well-formed, the function returns Size::ZERO. +*/ +Size CC_DLL SizeFromString(const char* pszContent); + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __PLATFOMR_CCNS_H__ + + diff --git a/cocos/base/cocoa/CCObject.cpp b/cocos/base/cocoa/CCObject.cpp new file mode 100644 index 0000000000..13fa0e3236 --- /dev/null +++ b/cocos/base/cocoa/CCObject.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + + +#include "CCObject.h" +#include "CCAutoreleasePool.h" +#include "ccMacros.h" +#include "script_support/CCScriptSupport.h" + +NS_CC_BEGIN + +Object::Object() +: _luaID(0) +, _reference(1) // when the object is created, the reference count of it is 1 +, _autoReleaseCount(0) +{ + static unsigned int uObjectCount = 0; + + _ID = ++uObjectCount; +} + +Object::~Object() +{ + // if the object is managed, we should remove it + // from pool manager + if (_autoReleaseCount > 0) + { + PoolManager::sharedPoolManager()->removeObject(this); + } + + // if the object is referenced by Lua engine, remove it + if (_luaID) + { + ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptObjectByObject(this); + } + else + { + ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); + if (pEngine != NULL && pEngine->getScriptType() == kScriptTypeJavascript) + { + pEngine->removeScriptObjectByObject(this); + } + } +} + +Object* Object::autorelease() +{ + PoolManager::sharedPoolManager()->addObject(this); + return this; +} + +bool Object::isSingleReference() const +{ + return _reference == 1; +} + +unsigned int Object::retainCount() const +{ + return _reference; +} + +bool Object::isEqual(const Object *object) +{ + return this == object; +} + +void Object::acceptVisitor(DataVisitor &visitor) +{ + visitor.visitObject(this); +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCObject.h b/cocos/base/cocoa/CCObject.h new file mode 100644 index 0000000000..8de1ff9d8b --- /dev/null +++ b/cocos/base/cocoa/CCObject.h @@ -0,0 +1,216 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __CCOBJECT_H__ +#define __CCOBJECT_H__ + +#include "cocoa/CCDataVisitor.h" +#include "ccMacros.h" + +#ifdef EMSCRIPTEN +#include +#endif // EMSCRIPTEN + +NS_CC_BEGIN + +/** + * @addtogroup base_nodes + * @{ + */ + +class Object; +class Node; + +/** Interface that defines how to clone an object */ +class CC_DLL Clonable +{ +public: + /** returns a copy of the object */ + virtual Clonable* clone() const = 0; + /** + * @js NA + * @lua NA + */ + virtual ~Clonable() {}; + + /** returns a copy of the object. + @deprecated Use clone() instead + */ + CC_DEPRECATED_ATTRIBUTE Object* copy() const + { + // use "clone" instead + CC_ASSERT(false); + return nullptr; + } +}; + +class CC_DLL Object +{ +public: + /// object id, ScriptSupport need public _ID + unsigned int _ID; + /// Lua reference id + int _luaID; +protected: + /// count of references + unsigned int _reference; + /// count of autorelease + unsigned int _autoReleaseCount; +public: + /** + * Constructor + * + * The object's reference count is 1 after construction. + * @js NA + */ + Object(); + + /** + * @js NA + * @lua NA + */ + virtual ~Object(); + + /** + * Release the ownership immediately. + * + * This decrements the object's reference count. + * + * If the reference count reaches 0 after the descrement, this object is + * destructed. + * + * @see retain, autorelease + * @js NA + */ + inline void release() + { + CCASSERT(_reference > 0, "reference count should greater than 0"); + --_reference; + + if (_reference == 0) + delete this; + } + + /** + * Retains the ownership. + * + * This increases the object's reference count. + * + * @see release, autorelease + * @js NA + */ + inline void retain() + { + CCASSERT(_reference > 0, "reference count should greater than 0"); + ++_reference; + } + + /** + * Release the ownership sometime soon automatically. + * + * This descrements the object's reference count at the end of current + * autorelease pool block. + * + * If the reference count reaches 0 after the descrement, this object is + * destructed. + * + * @returns The object itself. + * + * @see AutoreleasePool, retain, release + * @js NA + * @lua NA + */ + Object* autorelease(); + + /** + * Returns a boolean value that indicates whether there is only one + * reference to the object. That is, whether the reference count is 1. + * + * @returns Whether the object's reference count is 1. + * @js NA + */ + bool isSingleReference() const; + + /** + * Returns the object's current reference count. + * + * @returns The object's reference count. + * @js NA + */ + unsigned int retainCount() const; + + /** + * Returns a boolean value that indicates whether this object and a given + * object are equal. + * + * @param object The object to be compared to this object. + * + * @returns True if this object and @p object are equal, otherwise false. + * @js NA + * @lua NA + */ + virtual bool isEqual(const Object* object); + /** + * @js NA + * @lua NA + */ + virtual void acceptVisitor(DataVisitor &visitor); + /** + * @js NA + * @lua NA + */ + virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; + + friend class AutoreleasePool; +}; + + +typedef void (Object::*SEL_SCHEDULE)(float); +typedef void (Object::*SEL_CallFunc)(); +typedef void (Object::*SEL_CallFuncN)(Node*); +typedef void (Object::*SEL_CallFuncND)(Node*, void*); +typedef void (Object::*SEL_CallFuncO)(Object*); +typedef void (Object::*SEL_MenuHandler)(Object*); +typedef int (Object::*SEL_Compare)(Object*); + +#define schedule_selector(_SELECTOR) static_cast(&_SELECTOR) +#define callfunc_selector(_SELECTOR) static_cast(&_SELECTOR) +#define callfuncN_selector(_SELECTOR) static_cast(&_SELECTOR) +#define callfuncND_selector(_SELECTOR) static_cast(&_SELECTOR) +#define callfuncO_selector(_SELECTOR) static_cast(&_SELECTOR) +#define menu_selector(_SELECTOR) static_cast(&_SELECTOR) +#define event_selector(_SELECTOR) static_cast(&_SELECTOR) +#define compare_selector(_SELECTOR) static_cast(&_SELECTOR) + +// new callbacks based on C++11 +#define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__) +#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) +#define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__) + +// end of base_nodes group +/// @} + +NS_CC_END + +#endif // __CCOBJECT_H__ diff --git a/cocos/base/cocoa/CCSet.cpp b/cocos/base/cocoa/CCSet.cpp new file mode 100644 index 0000000000..c3c24e0e5e --- /dev/null +++ b/cocos/base/cocoa/CCSet.cpp @@ -0,0 +1,166 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "CCSet.h" + +using namespace std; + +NS_CC_BEGIN + +Set::Set(void) +{ + _set = new set; +} + +Set::Set(const Set &rSetObject) +{ + _set = new set(*rSetObject._set); + + // call retain of members + SetIterator iter; + for (iter = _set->begin(); iter != _set->end(); ++iter) + { + if (! (*iter)) + { + break; + } + + (*iter)->retain(); + } +} + +Set::~Set(void) +{ + removeAllObjects(); + CC_SAFE_DELETE(_set); +} + +void Set::acceptVisitor(DataVisitor &visitor) +{ + visitor.visit(this); +} + +Set * Set::create() +{ + Set * pRet = new Set(); + + if (pRet != NULL) + { + pRet->autorelease(); + } + + return pRet; +} + +Set* Set::copy(void) +{ + Set *pSet = new Set(*this); + + return pSet; +} + +Set* Set::mutableCopy(void) +{ + return copy(); +} + +int Set::count(void) +{ + return (int)_set->size(); +} + +void Set::addObject(Object *pObject) +{ + if (_set->count(pObject) == 0) + { + CC_SAFE_RETAIN(pObject); + _set->insert(pObject); + } +} + +void Set::removeObject(Object *pObject) +{ + if (_set->erase(pObject) > 0) + { + CC_SAFE_RELEASE(pObject); + } +} + +void Set::removeAllObjects() +{ + SetIterator it = _set->begin(); + SetIterator tmp; + + while (it != _set->end()) + { + if (!(*it)) + { + break; + } + + tmp = it; + ++tmp; + Object * obj = *it; + _set->erase(it); + CC_SAFE_RELEASE(obj); + it = tmp; + } +} + +bool Set::containsObject(Object *pObject) +{ + return _set->find(pObject) != _set->end(); +} + +SetIterator Set::begin(void) +{ + return _set->begin(); +} + +SetIterator Set::end(void) +{ + return _set->end(); +} + +Object* Set::anyObject() +{ + if (!_set || _set->empty()) + { + return 0; + } + + SetIterator it; + + for( it = _set->begin(); it != _set->end(); ++it) + { + if (*it) + { + return (*it); + } + } + + return 0; +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCSet.h b/cocos/base/cocoa/CCSet.h new file mode 100644 index 0000000000..c748f0ada5 --- /dev/null +++ b/cocos/base/cocoa/CCSet.h @@ -0,0 +1,119 @@ +/**************************************************************************** +Copyright (c) 2010-2012 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 __CC_SET_H__ +#define __CC_SET_H__ + +#include +#include "CCObject.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +typedef std::set::iterator SetIterator; + +class CC_DLL Set : public Object +{ +public: + /** + * @js ctor + */ + Set(void); + Set(const Set &rSetObject); + /** + * @js NA + * @lua NA + */ + virtual ~Set(void); + + /** + * @brief Create and return a new empty set. + */ + static Set * create(); + + /** + *@brief Return a copy of the Set, it will copy all the elements. + */ + Set* copy(); + /** + *@brief It is the same as copy(). + */ + Set* mutableCopy(); + /** + *@brief Return the number of elements the Set contains. + */ + int count(); + /** + *@brief Add a element into Set, it will retain the element. + */ + void addObject(Object *pObject); + /** + *@brief Remove the given element, nothing todo if no element equals pObject. + */ + void removeObject(Object *pObject); + /** + *@brief Remove all elements of the set + */ + void removeAllObjects(); + /** + *@brief Check if Set contains a element equals pObject. + */ + bool containsObject(Object *pObject); + /** + *@brief Return the iterator that points to the first element. + * @js NA + * @lua NA + */ + SetIterator begin(); + /** + *@brief Return the iterator that points to the position after the last element. + * @js NA + * @lua NA + */ + SetIterator end(); + /** + *@brief Return the first element if it contains elements, or null if it doesn't contain any element. + */ + Object* anyObject(); + /** + * @js NA + * @lua NA + */ + virtual void acceptVisitor(DataVisitor &visitor); + +private: + std::set *_set; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CC_SET_H__ + diff --git a/cocos/base/cocoa/CCString.cpp b/cocos/base/cocoa/CCString.cpp new file mode 100644 index 0000000000..f9962b1ba4 --- /dev/null +++ b/cocos/base/cocoa/CCString.cpp @@ -0,0 +1,277 @@ +/**************************************************************************** + Copyright (c) 2010-2012 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 "CCString.h" +#include "platform/CCFileUtils.h" +#include "ccMacros.h" +#include +#include +#include "CCArray.h" + +NS_CC_BEGIN + +#define kMaxStringLen (1024*100) + +String::String() + :_string("") +{} + +String::String(const char * str) + :_string(str) +{} + +String::String(const std::string& str) + :_string(str) +{} + +String::String(const String& str) + :_string(str.getCString()) +{} + +String::~String() +{ + CCLOGINFO("deallocing String: %p", this); + + _string.clear(); +} + +String& String::operator= (const String& other) +{ + _string = other._string; + return *this; +} + +bool String::initWithFormatAndValist(const char* format, va_list ap) +{ + bool bRet = false; + char* pBuf = (char*)malloc(kMaxStringLen); + if (pBuf != NULL) + { + vsnprintf(pBuf, kMaxStringLen, format, ap); + _string = pBuf; + free(pBuf); + bRet = true; + } + return bRet; +} + +bool String::initWithFormat(const char* format, ...) +{ + bool bRet = false; + _string.clear(); + + va_list ap; + va_start(ap, format); + + bRet = initWithFormatAndValist(format, ap); + + va_end(ap); + + return bRet; +} + +int String::intValue() const +{ + if (length() == 0) + { + return 0; + } + return atoi(_string.c_str()); +} + +unsigned int String::uintValue() const +{ + if (length() == 0) + { + return 0; + } + return (unsigned int)atoi(_string.c_str()); +} + +float String::floatValue() const +{ + if (length() == 0) + { + return 0.0f; + } + return (float)atof(_string.c_str()); +} + +double String::doubleValue() const +{ + if (length() == 0) + { + return 0.0; + } + return atof(_string.c_str()); +} + +bool String::boolValue() const +{ + if (length() == 0) + { + return false; + } + + if (0 == strcmp(_string.c_str(), "0") || 0 == strcmp(_string.c_str(), "false")) + { + return false; + } + return true; +} + +const char* String::getCString() const +{ + return _string.c_str(); +} + +unsigned int String::length() const +{ + return _string.length(); +} + +int String::compare(const char * pStr) const +{ + return strcmp(getCString(), pStr); +} + +void String::append(const std::string& str) +{ + _string.append(str); +} + +void String::appendWithFormat(const char* format, ...) +{ + va_list ap; + va_start(ap, format); + + char* pBuf = (char*)malloc(kMaxStringLen); + if (pBuf != NULL) + { + vsnprintf(pBuf, kMaxStringLen, format, ap); + _string.append(pBuf); + free(pBuf); + } + + va_end(ap); + +} + +Array* String::componentsSeparatedByString(const char *delimiter) +{ + Array* result = Array::create(); + + int cutAt; + while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) + { + if(cutAt > 0) + { + result->addObject(String::create(_string.substr(0, cutAt))); + } + _string = _string.substr(cutAt + 1); + } + + if(_string.length() > 0) + { + result->addObject(String::create(_string)); + } + + return result; +} + +bool String::isEqual(const Object* pObject) +{ + bool bRet = false; + const String* pStr = dynamic_cast(pObject); + if (pStr != NULL) + { + if (0 == _string.compare(pStr->_string)) + { + bRet = true; + } + } + return bRet; +} + +String* String::create(const std::string& str) +{ + String* pRet = new String(str); + pRet->autorelease(); + return pRet; +} + +String* String::createWithData(const unsigned char* pData, unsigned long nLen) +{ + String* pRet = NULL; + if (pData != NULL) + { + char* pStr = (char*)malloc(nLen+1); + if (pStr != NULL) + { + pStr[nLen] = '\0'; + if (nLen > 0) + { + memcpy(pStr, pData, nLen); + } + + pRet = String::create(pStr); + free(pStr); + } + } + return pRet; +} + +String* String::createWithFormat(const char* format, ...) +{ + String* pRet = String::create(""); + va_list ap; + va_start(ap, format); + pRet->initWithFormatAndValist(format, ap); + va_end(ap); + + return pRet; +} + +String* String::createWithContentsOfFile(const char* filename) +{ + unsigned long size = 0; + unsigned char* pData = 0; + String* pRet = NULL; + pData = FileUtils::getInstance()->getFileData(filename, "rb", &size); + pRet = String::createWithData(pData, size); + CC_SAFE_DELETE_ARRAY(pData); + return pRet; +} + +void String::acceptVisitor(DataVisitor &visitor) +{ + visitor.visit(this); +} + +String* String::clone() const +{ + return String::create(_string); +} + +NS_CC_END diff --git a/cocos/base/cocoa/CCString.h b/cocos/base/cocoa/CCString.h new file mode 100644 index 0000000000..a6f237a476 --- /dev/null +++ b/cocos/base/cocoa/CCString.h @@ -0,0 +1,210 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#ifndef __CCSTRING_H__ +#define __CCSTRING_H__ + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) +#include +#endif + +#include +#include +#include +#include "CCObject.h" + +NS_CC_BEGIN + +/** + * @addtogroup data_structures + * @{ + */ + +class CC_DLL String : public Object, public Clonable +{ +public: + /** + * @js NA + * @lua NA + */ + String(); + /** + * @js NA + * @lua NA + */ + String(const char* str); + /** + * @js NA + * @lua NA + */ + String(const std::string& str); + /** + * @js NA + * @lua NA + */ + String(const String& str); + /** + * @js NA + * @lua NA + */ + virtual ~String(); + + /* override assignment operator + * @js NA + * @lua NA + */ + String& operator= (const String& other); + + /** init a string with format, it's similar with the c function 'sprintf' + * @js NA + * @lua NA + */ + bool initWithFormat(const char* format, ...) CC_FORMAT_PRINTF(2, 3); + + /** convert to int value + * @js NA + */ + int intValue() const; + + /** convert to unsigned int value + * @js NA + */ + unsigned int uintValue() const; + + /** convert to float value + * @js NA + */ + float floatValue() const; + + /** convert to double value + * @js NA + */ + double doubleValue() const; + + /** convert to bool value + * @js NA + */ + bool boolValue() const; + + /** get the C string + * @js NA + */ + const char* getCString() const; + + /** get the length of string + * @js NA + */ + unsigned int length() const; + + /** compare to a c string + * @js NA + */ + int compare(const char *) const; + + /** append additional characters at the end of its current value + * @js NA + * @lua NA + */ + void append(const std::string& str); + + /** append(w/ format) additional characters at the end of its current value + * @js NA + * @lua NA + */ + void appendWithFormat(const char* format, ...); + + /** split a string + * @js NA + * @lua NA + */ + Array* componentsSeparatedByString(const char *delimiter); + + /* override functions + * @js NA + */ + virtual bool isEqual(const Object* pObject); + + /** create a string with std string, you can also pass a c string pointer because the default constructor of std::string can access a c string pointer. + * @return A String pointer which is an autorelease object pointer, + * it means that you needn't do a release operation unless you retain it. + * @js NA + */ + static String* create(const std::string& str); + + /** create a string with format, it's similar with the c function 'sprintf', the default buffer size is (1024*100) bytes, + * if you want to change it, you should modify the kMaxStringLen macro in String.cpp file. + * @return A String pointer which is an autorelease object pointer, + * it means that you needn't do a release operation unless you retain it. + * @js NA + */ + static String* createWithFormat(const char* format, ...) CC_FORMAT_PRINTF(1, 2); + + /** create a string with binary data + * @return A String pointer which is an autorelease object pointer, + * it means that you needn't do a release operation unless you retain it. + * @js NA + */ + static String* createWithData(const unsigned char* pData, unsigned long nLen); + + /** create a string with a file, + * @return A String pointer which is an autorelease object pointer, + * it means that you needn't do a release operation unless you retain it. + * @js NA + */ + static String* createWithContentsOfFile(const char* filename); + /** + * @js NA + * @lua NA + */ + virtual void acceptVisitor(DataVisitor &visitor); + /** + * @js NA + * @lua NA + */ + virtual String* clone() const; + +private: + + /** only for internal use */ + bool initWithFormatAndValist(const char* format, va_list ap); + +public: + std::string _string; +}; + +struct StringCompare : public std::binary_function { + public: + bool operator() (String * a, String * b) const { + return strcmp(a->getCString(), b->getCString()) < 0; + } +}; + +#define StringMake(str) String::create(str) +#define ccs StringMake + +// end of data_structure group +/// @} + +NS_CC_END + +#endif //__CCSTRING_H__ diff --git a/cocos/base/etc1/etc1.cpp b/cocos/base/etc1/etc1.cpp new file mode 100644 index 0000000000..9c1cd43e83 --- /dev/null +++ b/cocos/base/etc1/etc1.cpp @@ -0,0 +1,670 @@ +// Copyright 2009 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "etc1.h" + +#include + +/* From http://www.khronos.org/registry/gles/extensions/OES/OES_compressed_ETC1_RGB8_texture.txt + + The number of bits that represent a 4x4 texel block is 64 bits if + is given by ETC1_RGB8_OES. + + The data for a block is a number of bytes, + + {q0, q1, q2, q3, q4, q5, q6, q7} + + where byte q0 is located at the lowest memory address and q7 at + the highest. The 64 bits specifying the block is then represented + by the following 64 bit integer: + + int64bit = 256*(256*(256*(256*(256*(256*(256*q0+q1)+q2)+q3)+q4)+q5)+q6)+q7; + + ETC1_RGB8_OES: + + a) bit layout in bits 63 through 32 if diffbit = 0 + + 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 + ----------------------------------------------- + | base col1 | base col2 | base col1 | base col2 | + | R1 (4bits)| R2 (4bits)| G1 (4bits)| G2 (4bits)| + ----------------------------------------------- + + 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 + --------------------------------------------------- + | base col1 | base col2 | table | table |diff|flip| + | B1 (4bits)| B2 (4bits)| cw 1 | cw 2 |bit |bit | + --------------------------------------------------- + + + b) bit layout in bits 63 through 32 if diffbit = 1 + + 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 + ----------------------------------------------- + | base col1 | dcol 2 | base col1 | dcol 2 | + | R1' (5 bits) | dR2 | G1' (5 bits) | dG2 | + ----------------------------------------------- + + 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 + --------------------------------------------------- + | base col 1 | dcol 2 | table | table |diff|flip| + | B1' (5 bits) | dB2 | cw 1 | cw 2 |bit |bit | + --------------------------------------------------- + + + c) bit layout in bits 31 through 0 (in both cases) + + 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 + ----------------------------------------------- + | most significant pixel index bits | + | p| o| n| m| l| k| j| i| h| g| f| e| d| c| b| a| + ----------------------------------------------- + + 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 + -------------------------------------------------- + | least significant pixel index bits | + | p| o| n| m| l| k| j| i| h| g| f| e| d| c | b | a | + -------------------------------------------------- + + + Add table 3.17.2: Intensity modifier sets for ETC1 compressed textures: + + table codeword modifier table + ------------------ ---------------------- + 0 -8 -2 2 8 + 1 -17 -5 5 17 + 2 -29 -9 9 29 + 3 -42 -13 13 42 + 4 -60 -18 18 60 + 5 -80 -24 24 80 + 6 -106 -33 33 106 + 7 -183 -47 47 183 + + + Add table 3.17.3 Mapping from pixel index values to modifier values for + ETC1 compressed textures: + + pixel index value + --------------- + msb lsb resulting modifier value + ----- ----- ------------------------- + 1 1 -b (large negative value) + 1 0 -a (small negative value) + 0 0 a (small positive value) + 0 1 b (large positive value) + + + */ + +static const int kModifierTable[] = { +/* 0 */2, 8, -2, -8, +/* 1 */5, 17, -5, -17, +/* 2 */9, 29, -9, -29, +/* 3 */13, 42, -13, -42, +/* 4 */18, 60, -18, -60, +/* 5 */24, 80, -24, -80, +/* 6 */33, 106, -33, -106, +/* 7 */47, 183, -47, -183 }; + +static const int kLookup[8] = { 0, 1, 2, 3, -4, -3, -2, -1 }; + +static inline etc1_byte clamp(int x) { + return (etc1_byte) (x >= 0 ? (x < 255 ? x : 255) : 0); +} + +static +inline int convert4To8(int b) { + int c = b & 0xf; + return (c << 4) | c; +} + +static +inline int convert5To8(int b) { + int c = b & 0x1f; + return (c << 3) | (c >> 2); +} + +static +inline int convert6To8(int b) { + int c = b & 0x3f; + return (c << 2) | (c >> 4); +} + +static +inline int divideBy255(int d) { + return (d + 128 + (d >> 8)) >> 8; +} + +static +inline int convert8To4(int b) { + int c = b & 0xff; + return divideBy255(c * 15); +} + +static +inline int convert8To5(int b) { + int c = b & 0xff; + return divideBy255(c * 31); +} + +static +inline int convertDiff(int base, int diff) { + return convert5To8((0x1f & base) + kLookup[0x7 & diff]); +} + +static +void decode_subblock(etc1_byte* pOut, int r, int g, int b, const int* table, + etc1_uint32 low, bool second, bool flipped) { + int baseX = 0; + int baseY = 0; + if (second) { + if (flipped) { + baseY = 2; + } else { + baseX = 2; + } + } + for (int i = 0; i < 8; i++) { + int x, y; + if (flipped) { + x = baseX + (i >> 1); + y = baseY + (i & 1); + } else { + x = baseX + (i >> 2); + y = baseY + (i & 3); + } + int k = y + (x * 4); + int offset = ((low >> k) & 1) | ((low >> (k + 15)) & 2); + int delta = table[offset]; + etc1_byte* q = pOut + 3 * (x + 4 * y); + *q++ = clamp(r + delta); + *q++ = clamp(g + delta); + *q++ = clamp(b + delta); + } +} + +// Input is an ETC1 compressed version of the data. +// Output is a 4 x 4 square of 3-byte pixels in form R, G, B + +void etc1_decode_block(const etc1_byte* pIn, etc1_byte* pOut) { + etc1_uint32 high = (pIn[0] << 24) | (pIn[1] << 16) | (pIn[2] << 8) | pIn[3]; + etc1_uint32 low = (pIn[4] << 24) | (pIn[5] << 16) | (pIn[6] << 8) | pIn[7]; + int r1, r2, g1, g2, b1, b2; + if (high & 2) { + // differential + int rBase = high >> 27; + int gBase = high >> 19; + int bBase = high >> 11; + r1 = convert5To8(rBase); + r2 = convertDiff(rBase, high >> 24); + g1 = convert5To8(gBase); + g2 = convertDiff(gBase, high >> 16); + b1 = convert5To8(bBase); + b2 = convertDiff(bBase, high >> 8); + } else { + // not differential + r1 = convert4To8(high >> 28); + r2 = convert4To8(high >> 24); + g1 = convert4To8(high >> 20); + g2 = convert4To8(high >> 16); + b1 = convert4To8(high >> 12); + b2 = convert4To8(high >> 8); + } + int tableIndexA = 7 & (high >> 5); + int tableIndexB = 7 & (high >> 2); + const int* tableA = kModifierTable + tableIndexA * 4; + const int* tableB = kModifierTable + tableIndexB * 4; + bool flipped = (high & 1) != 0; + decode_subblock(pOut, r1, g1, b1, tableA, low, false, flipped); + decode_subblock(pOut, r2, g2, b2, tableB, low, true, flipped); +} + +typedef struct { + etc1_uint32 high; + etc1_uint32 low; + etc1_uint32 score; // Lower is more accurate +} etc_compressed; + +static +inline void take_best(etc_compressed* a, const etc_compressed* b) { + if (a->score > b->score) { + *a = *b; + } +} + +static +void etc_average_colors_subblock(const etc1_byte* pIn, etc1_uint32 inMask, + etc1_byte* pColors, bool flipped, bool second) { + int r = 0; + int g = 0; + int b = 0; + + if (flipped) { + int by = 0; + if (second) { + by = 2; + } + for (int y = 0; y < 2; y++) { + int yy = by + y; + for (int x = 0; x < 4; x++) { + int i = x + 4 * yy; + if (inMask & (1 << i)) { + const etc1_byte* p = pIn + i * 3; + r += *(p++); + g += *(p++); + b += *(p++); + } + } + } + } else { + int bx = 0; + if (second) { + bx = 2; + } + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 2; x++) { + int xx = bx + x; + int i = xx + 4 * y; + if (inMask & (1 << i)) { + const etc1_byte* p = pIn + i * 3; + r += *(p++); + g += *(p++); + b += *(p++); + } + } + } + } + pColors[0] = (etc1_byte)((r + 4) >> 3); + pColors[1] = (etc1_byte)((g + 4) >> 3); + pColors[2] = (etc1_byte)((b + 4) >> 3); +} + +static +inline int square(int x) { + return x * x; +} + +static etc1_uint32 chooseModifier(const etc1_byte* pBaseColors, + const etc1_byte* pIn, etc1_uint32 *pLow, int bitIndex, + const int* pModifierTable) { + etc1_uint32 bestScore = ~0; + int bestIndex = 0; + int pixelR = pIn[0]; + int pixelG = pIn[1]; + int pixelB = pIn[2]; + int r = pBaseColors[0]; + int g = pBaseColors[1]; + int b = pBaseColors[2]; + for (int i = 0; i < 4; i++) { + int modifier = pModifierTable[i]; + int decodedG = clamp(g + modifier); + etc1_uint32 score = (etc1_uint32) (6 * square(decodedG - pixelG)); + if (score >= bestScore) { + continue; + } + int decodedR = clamp(r + modifier); + score += (etc1_uint32) (3 * square(decodedR - pixelR)); + if (score >= bestScore) { + continue; + } + int decodedB = clamp(b + modifier); + score += (etc1_uint32) square(decodedB - pixelB); + if (score < bestScore) { + bestScore = score; + bestIndex = i; + } + } + etc1_uint32 lowMask = (((bestIndex >> 1) << 16) | (bestIndex & 1)) + << bitIndex; + *pLow |= lowMask; + return bestScore; +} + +static +void etc_encode_subblock_helper(const etc1_byte* pIn, etc1_uint32 inMask, + etc_compressed* pCompressed, bool flipped, bool second, + const etc1_byte* pBaseColors, const int* pModifierTable) { + int score = pCompressed->score; + if (flipped) { + int by = 0; + if (second) { + by = 2; + } + for (int y = 0; y < 2; y++) { + int yy = by + y; + for (int x = 0; x < 4; x++) { + int i = x + 4 * yy; + if (inMask & (1 << i)) { + score += chooseModifier(pBaseColors, pIn + i * 3, + &pCompressed->low, yy + x * 4, pModifierTable); + } + } + } + } else { + int bx = 0; + if (second) { + bx = 2; + } + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 2; x++) { + int xx = bx + x; + int i = xx + 4 * y; + if (inMask & (1 << i)) { + score += chooseModifier(pBaseColors, pIn + i * 3, + &pCompressed->low, y + xx * 4, pModifierTable); + } + } + } + } + pCompressed->score = score; +} + +static bool inRange4bitSigned(int color) { + return color >= -4 && color <= 3; +} + +static void etc_encodeBaseColors(etc1_byte* pBaseColors, + const etc1_byte* pColors, etc_compressed* pCompressed) { + int r1, g1, b1, r2, g2, b2; // 8 bit base colors for sub-blocks + bool differential; + { + int r51 = convert8To5(pColors[0]); + int g51 = convert8To5(pColors[1]); + int b51 = convert8To5(pColors[2]); + int r52 = convert8To5(pColors[3]); + int g52 = convert8To5(pColors[4]); + int b52 = convert8To5(pColors[5]); + + r1 = convert5To8(r51); + g1 = convert5To8(g51); + b1 = convert5To8(b51); + + int dr = r52 - r51; + int dg = g52 - g51; + int db = b52 - b51; + + differential = inRange4bitSigned(dr) && inRange4bitSigned(dg) + && inRange4bitSigned(db); + if (differential) { + r2 = convert5To8(r51 + dr); + g2 = convert5To8(g51 + dg); + b2 = convert5To8(b51 + db); + pCompressed->high |= (r51 << 27) | ((7 & dr) << 24) | (g51 << 19) + | ((7 & dg) << 16) | (b51 << 11) | ((7 & db) << 8) | 2; + } + } + + if (!differential) { + int r41 = convert8To4(pColors[0]); + int g41 = convert8To4(pColors[1]); + int b41 = convert8To4(pColors[2]); + int r42 = convert8To4(pColors[3]); + int g42 = convert8To4(pColors[4]); + int b42 = convert8To4(pColors[5]); + r1 = convert4To8(r41); + g1 = convert4To8(g41); + b1 = convert4To8(b41); + r2 = convert4To8(r42); + g2 = convert4To8(g42); + b2 = convert4To8(b42); + pCompressed->high |= (r41 << 28) | (r42 << 24) | (g41 << 20) | (g42 + << 16) | (b41 << 12) | (b42 << 8); + } + pBaseColors[0] = r1; + pBaseColors[1] = g1; + pBaseColors[2] = b1; + pBaseColors[3] = r2; + pBaseColors[4] = g2; + pBaseColors[5] = b2; +} + +static +void etc_encode_block_helper(const etc1_byte* pIn, etc1_uint32 inMask, + const etc1_byte* pColors, etc_compressed* pCompressed, bool flipped) { + pCompressed->score = ~0; + pCompressed->high = (flipped ? 1 : 0); + pCompressed->low = 0; + + etc1_byte pBaseColors[6]; + + etc_encodeBaseColors(pBaseColors, pColors, pCompressed); + + int originalHigh = pCompressed->high; + + const int* pModifierTable = kModifierTable; + for (int i = 0; i < 8; i++, pModifierTable += 4) { + etc_compressed temp; + temp.score = 0; + temp.high = originalHigh | (i << 5); + temp.low = 0; + etc_encode_subblock_helper(pIn, inMask, &temp, flipped, false, + pBaseColors, pModifierTable); + take_best(pCompressed, &temp); + } + pModifierTable = kModifierTable; + etc_compressed firstHalf = *pCompressed; + for (int i = 0; i < 8; i++, pModifierTable += 4) { + etc_compressed temp; + temp.score = firstHalf.score; + temp.high = firstHalf.high | (i << 2); + temp.low = firstHalf.low; + etc_encode_subblock_helper(pIn, inMask, &temp, flipped, true, + pBaseColors + 3, pModifierTable); + if (i == 0) { + *pCompressed = temp; + } else { + take_best(pCompressed, &temp); + } + } +} + +static void writeBigEndian(etc1_byte* pOut, etc1_uint32 d) { + pOut[0] = (etc1_byte)(d >> 24); + pOut[1] = (etc1_byte)(d >> 16); + pOut[2] = (etc1_byte)(d >> 8); + pOut[3] = (etc1_byte) d; +} + +// Input is a 4 x 4 square of 3-byte pixels in form R, G, B +// inmask is a 16-bit mask where bit (1 << (x + y * 4)) tells whether the corresponding (x,y) +// pixel is valid or not. Invalid pixel color values are ignored when compressing. +// Output is an ETC1 compressed version of the data. + +void etc1_encode_block(const etc1_byte* pIn, etc1_uint32 inMask, + etc1_byte* pOut) { + etc1_byte colors[6]; + etc1_byte flippedColors[6]; + etc_average_colors_subblock(pIn, inMask, colors, false, false); + etc_average_colors_subblock(pIn, inMask, colors + 3, false, true); + etc_average_colors_subblock(pIn, inMask, flippedColors, true, false); + etc_average_colors_subblock(pIn, inMask, flippedColors + 3, true, true); + + etc_compressed a, b; + etc_encode_block_helper(pIn, inMask, colors, &a, false); + etc_encode_block_helper(pIn, inMask, flippedColors, &b, true); + take_best(&a, &b); + writeBigEndian(pOut, a.high); + writeBigEndian(pOut + 4, a.low); +} + +// Return the size of the encoded image data (does not include size of PKM header). + +etc1_uint32 etc1_get_encoded_data_size(etc1_uint32 width, etc1_uint32 height) { + return (((width + 3) & ~3) * ((height + 3) & ~3)) >> 1; +} + +// Encode an entire image. +// pIn - pointer to the image data. Formatted such that the Red component of +// pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset; +// pOut - pointer to encoded data. Must be large enough to store entire encoded image. + +int etc1_encode_image(const etc1_byte* pIn, etc1_uint32 width, etc1_uint32 height, + etc1_uint32 pixelSize, etc1_uint32 stride, etc1_byte* pOut) { + if (pixelSize < 2 || pixelSize > 3) { + return -1; + } + static const unsigned short kYMask[] = { 0x0, 0xf, 0xff, 0xfff, 0xffff }; + static const unsigned short kXMask[] = { 0x0, 0x1111, 0x3333, 0x7777, + 0xffff }; + etc1_byte block[ETC1_DECODED_BLOCK_SIZE]; + etc1_byte encoded[ETC1_ENCODED_BLOCK_SIZE]; + + etc1_uint32 encodedWidth = (width + 3) & ~3; + etc1_uint32 encodedHeight = (height + 3) & ~3; + + for (etc1_uint32 y = 0; y < encodedHeight; y += 4) { + etc1_uint32 yEnd = height - y; + if (yEnd > 4) { + yEnd = 4; + } + int ymask = kYMask[yEnd]; + for (etc1_uint32 x = 0; x < encodedWidth; x += 4) { + etc1_uint32 xEnd = width - x; + if (xEnd > 4) { + xEnd = 4; + } + int mask = ymask & kXMask[xEnd]; + for (etc1_uint32 cy = 0; cy < yEnd; cy++) { + etc1_byte* q = block + (cy * 4) * 3; + const etc1_byte* p = pIn + pixelSize * x + stride * (y + cy); + if (pixelSize == 3) { + memcpy(q, p, xEnd * 3); + } else { + for (etc1_uint32 cx = 0; cx < xEnd; cx++) { + int pixel = (p[1] << 8) | p[0]; + *q++ = convert5To8(pixel >> 11); + *q++ = convert6To8(pixel >> 5); + *q++ = convert5To8(pixel); + p += pixelSize; + } + } + } + etc1_encode_block(block, mask, encoded); + memcpy(pOut, encoded, sizeof(encoded)); + pOut += sizeof(encoded); + } + } + return 0; +} + +// Decode an entire image. +// pIn - pointer to encoded data. +// pOut - pointer to the image data. Will be written such that the Red component of +// pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset. Must be +// large enough to store entire image. + + +int etc1_decode_image(const etc1_byte* pIn, etc1_byte* pOut, + etc1_uint32 width, etc1_uint32 height, + etc1_uint32 pixelSize, etc1_uint32 stride) { + if (pixelSize < 2 || pixelSize > 3) { + return -1; + } + etc1_byte block[ETC1_DECODED_BLOCK_SIZE]; + + etc1_uint32 encodedWidth = (width + 3) & ~3; + etc1_uint32 encodedHeight = (height + 3) & ~3; + + for (etc1_uint32 y = 0; y < encodedHeight; y += 4) { + etc1_uint32 yEnd = height - y; + if (yEnd > 4) { + yEnd = 4; + } + for (etc1_uint32 x = 0; x < encodedWidth; x += 4) { + etc1_uint32 xEnd = width - x; + if (xEnd > 4) { + xEnd = 4; + } + etc1_decode_block(pIn, block); + pIn += ETC1_ENCODED_BLOCK_SIZE; + for (etc1_uint32 cy = 0; cy < yEnd; cy++) { + const etc1_byte* q = block + (cy * 4) * 3; + etc1_byte* p = pOut + pixelSize * x + stride * (y + cy); + if (pixelSize == 3) { + memcpy(p, q, xEnd * 3); + } else { + for (etc1_uint32 cx = 0; cx < xEnd; cx++) { + etc1_byte r = *q++; + etc1_byte g = *q++; + etc1_byte b = *q++; + etc1_uint32 pixel = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); + *p++ = (etc1_byte) pixel; + *p++ = (etc1_byte) (pixel >> 8); + } + } + } + } + } + return 0; +} + +static const char kMagic[] = { 'P', 'K', 'M', ' ', '1', '0' }; + +static const etc1_uint32 ETC1_PKM_FORMAT_OFFSET = 6; +static const etc1_uint32 ETC1_PKM_ENCODED_WIDTH_OFFSET = 8; +static const etc1_uint32 ETC1_PKM_ENCODED_HEIGHT_OFFSET = 10; +static const etc1_uint32 ETC1_PKM_WIDTH_OFFSET = 12; +static const etc1_uint32 ETC1_PKM_HEIGHT_OFFSET = 14; + +static const etc1_uint32 ETC1_RGB_NO_MIPMAPS = 0; + +static void writeBEUint16(etc1_byte* pOut, etc1_uint32 data) { + pOut[0] = (etc1_byte) (data >> 8); + pOut[1] = (etc1_byte) data; +} + +static etc1_uint32 readBEUint16(const etc1_byte* pIn) { + return (pIn[0] << 8) | pIn[1]; +} + +// Format a PKM header + +void etc1_pkm_format_header(etc1_byte* pHeader, etc1_uint32 width, etc1_uint32 height) { + memcpy(pHeader, kMagic, sizeof(kMagic)); + etc1_uint32 encodedWidth = (width + 3) & ~3; + etc1_uint32 encodedHeight = (height + 3) & ~3; + writeBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET, ETC1_RGB_NO_MIPMAPS); + writeBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET, encodedWidth); + writeBEUint16(pHeader + ETC1_PKM_ENCODED_HEIGHT_OFFSET, encodedHeight); + writeBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET, width); + writeBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET, height); +} + +// Check if a PKM header is correctly formatted. + +etc1_bool etc1_pkm_is_valid(const etc1_byte* pHeader) { + if (memcmp(pHeader, kMagic, sizeof(kMagic))) { + return false; + } + etc1_uint32 format = readBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET); + etc1_uint32 encodedWidth = readBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET); + etc1_uint32 encodedHeight = readBEUint16(pHeader + ETC1_PKM_ENCODED_HEIGHT_OFFSET); + etc1_uint32 width = readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); + etc1_uint32 height = readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); + return format == ETC1_RGB_NO_MIPMAPS && + encodedWidth >= width && encodedWidth - width < 4 && + encodedHeight >= height && encodedHeight - height < 4; +} + +// Read the image width from a PKM header + +etc1_uint32 etc1_pkm_get_width(const etc1_byte* pHeader) { + return readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); +} + +// Read the image height from a PKM header + +etc1_uint32 etc1_pkm_get_height(const etc1_byte* pHeader){ + return readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); +} diff --git a/cocos/base/etc1/etc1.h b/cocos/base/etc1/etc1.h new file mode 100644 index 0000000000..0d389052b7 --- /dev/null +++ b/cocos/base/etc1/etc1.h @@ -0,0 +1,106 @@ +// Copyright 2009 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef __etc1_h__ +#define __etc1_h__ + +#define ETC1_ENCODED_BLOCK_SIZE 8 +#define ETC1_DECODED_BLOCK_SIZE 48 + +#ifndef ETC1_RGB8_OES +#define ETC1_RGB8_OES 0x8D64 +#endif + +typedef unsigned char etc1_byte; +typedef int etc1_bool; +typedef unsigned int etc1_uint32; + +#ifdef __cplusplus +extern "C" { +#endif + +// Encode a block of pixels. +// +// pIn is a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a +// 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R +// value of pixel (x, y). +// +// validPixelMask is a 16-bit mask where bit (1 << (x + y * 4)) indicates whether +// the corresponding (x,y) pixel is valid. Invalid pixel color values are ignored when compressing. +// +// pOut is an ETC1 compressed version of the data. + +void etc1_encode_block(const etc1_byte* pIn, etc1_uint32 validPixelMask, etc1_byte* pOut); + +// Decode a block of pixels. +// +// pIn is an ETC1 compressed version of the data. +// +// pOut is a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a +// 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R +// value of pixel (x, y). + +void etc1_decode_block(const etc1_byte* pIn, etc1_byte* pOut); + +// Return the size of the encoded image data (does not include size of PKM header). + +etc1_uint32 etc1_get_encoded_data_size(etc1_uint32 width, etc1_uint32 height); + +// Encode an entire image. +// pIn - pointer to the image data. Formatted such that +// pixel (x,y) is at pIn + pixelSize * x + stride * y; +// pOut - pointer to encoded data. Must be large enough to store entire encoded image. +// pixelSize can be 2 or 3. 2 is an GL_UNSIGNED_SHORT_5_6_5 image, 3 is a GL_BYTE RGB image. +// returns non-zero if there is an error. + +int etc1_encode_image(const etc1_byte* pIn, etc1_uint32 width, etc1_uint32 height, + etc1_uint32 pixelSize, etc1_uint32 stride, etc1_byte* pOut); + +// Decode an entire image. +// pIn - pointer to encoded data. +// pOut - pointer to the image data. Will be written such that +// pixel (x,y) is at pIn + pixelSize * x + stride * y. Must be +// large enough to store entire image. +// pixelSize can be 2 or 3. 2 is an GL_UNSIGNED_SHORT_5_6_5 image, 3 is a GL_BYTE RGB image. +// returns non-zero if there is an error. + +int etc1_decode_image(const etc1_byte* pIn, etc1_byte* pOut, + etc1_uint32 width, etc1_uint32 height, + etc1_uint32 pixelSize, etc1_uint32 stride); + +// Size of a PKM header, in bytes. + +#define ETC_PKM_HEADER_SIZE 16 + +// Format a PKM header + +void etc1_pkm_format_header(etc1_byte* pHeader, etc1_uint32 width, etc1_uint32 height); + +// Check if a PKM header is correctly formatted. + +etc1_bool etc1_pkm_is_valid(const etc1_byte* pHeader); + +// Read the image width from a PKM header + +etc1_uint32 etc1_pkm_get_width(const etc1_byte* pHeader); + +// Read the image height from a PKM header + +etc1_uint32 etc1_pkm_get_height(const etc1_byte* pHeader); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/cocos/base/s3tc/s3tc.cpp b/cocos/base/s3tc/s3tc.cpp new file mode 100644 index 0000000000..e7869df631 --- /dev/null +++ b/cocos/base/s3tc/s3tc.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** + 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 "s3tc.h" + +//Decode S3TC encode block to 4x4 RGB32 pixels +static void s3tc_decode_block(uint8_t **blockData, + uint32_t *decodeBlockData, + unsigned int stride, + bool oneBitAlphaFlag, + uint64_t alpha, + S3TCDecodeFlag decodeFlag) +{ + unsigned int colorValue0 = 0 , colorValue1 = 0, initAlpha = (!oneBitAlphaFlag * 255u) << 24; + unsigned int rb0 = 0, rb1 = 0, rb2 = 0, rb3 = 0, g0 = 0, g1 = 0, g2 = 0, g3 = 0; + + uint32_t colors[4], pixelsIndex = 0; + + /* load the two color values*/ + memcpy((void *)&colorValue0, *blockData, 2); + (*blockData) += 2; + + memcpy((void *)&colorValue1, *blockData, 2); + (*blockData) += 2; + + /* the channel is r5g6b5 , 16 bits */ + rb0 = (colorValue0 << 19 | colorValue0 >> 8) & 0xf800f8; + rb1 = (colorValue1 << 19 | colorValue1 >> 8) & 0xf800f8; + g0 = (colorValue0 << 5) & 0x00fc00; + g1 = (colorValue1 << 5) & 0x00fc00; + g0 += (g0 >> 6) & 0x000300; + g1 += (g1 >> 6) & 0x000300; + + colors[0] = rb0 + g0 + initAlpha; + colors[1] = rb1 + g1 + initAlpha; + + /* interpolate the other two color values */ + if (colorValue0 > colorValue1 || oneBitAlphaFlag) + { + rb2 = (((2*rb0 + rb1) * 21) >> 6) & 0xff00ff; + rb3 = (((2*rb1 + rb0) * 21) >> 6) & 0xff00ff; + g2 = (((2*g0 + g1 ) * 21) >> 6) & 0x00ff00; + g3 = (((2*g1 + g0 ) * 21) >> 6) & 0x00ff00; + colors[3] = rb3 + g3 + initAlpha; + } + else + { + rb2 = ((rb0+rb1) >> 1) & 0xff00ff; + g2 = ((g0 +g1 ) >> 1) & 0x00ff00; + colors[3] = 0 ; + } + colors[2] = rb2 + g2 + initAlpha; + + /*read the pixelsIndex , 2bits per pixel, 4 bytes */ + memcpy((void*)&pixelsIndex, *blockData, 4); + (*blockData) += 4; + + if (S3TCDecodeFlag::DXT5 == decodeFlag) + { + //dxt5 use interpolate alpha + // 8-Alpha block: derive the other six alphas. + // Bit code 000 = alpha0, 001 = alpha1, other are interpolated. + + unsigned int alphaArray[8]; + + alphaArray[0] = (alpha ) & 0xff ; + alphaArray[1] = (alpha >> 8) & 0xff ; + + if (alphaArray[0] >= alphaArray[1]) + { + alphaArray[2] = (alphaArray[0]*6 + alphaArray[1]*1) / 7; + alphaArray[3] = (alphaArray[0]*5 + alphaArray[1]*2) / 7; + alphaArray[4] = (alphaArray[0]*4 + alphaArray[1]*3) / 7; + alphaArray[5] = (alphaArray[0]*3 + alphaArray[1]*4) / 7; + alphaArray[6] = (alphaArray[0]*2 + alphaArray[1]*5) / 7; + alphaArray[7] = (alphaArray[0]*1 + alphaArray[1]*6) / 7; + } + else if (alphaArray[0] < alphaArray[1]) + { + alphaArray[2] = (alphaArray[0]*4 + alphaArray[1]*1) / 5; + alphaArray[3] = (alphaArray[0]*3 + alphaArray[1]*2) / 5; + alphaArray[4] = (alphaArray[0]*2 + alphaArray[1]*3) / 5; + alphaArray[5] = (alphaArray[0]*1 + alphaArray[1]*4) / 5; + alphaArray[6] = 0; + alphaArray[7] = 255; + } + + // read the flowing 48bit indices (16*3) + alpha >>= 16; + + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 4; ++x) + { + decodeBlockData[x] = (alphaArray[alpha & 5] << 24) + colors[pixelsIndex & 3]; + pixelsIndex >>= 2; + alpha >>= 3; + } + decodeBlockData += stride; + } + } //if (dxt5 == comFlag) + else + { //dxt1 dxt3 use explicit alpha + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 4; ++x) + { + initAlpha = (alpha & 0x0f) << 28; + initAlpha += initAlpha >> 4; + decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; + pixelsIndex >>= 2; + alpha >>= 4; + } + decodeBlockData += stride; + } + } +} + +//Decode S3TC encode data to RGB32 +void s3tc_decode(uint8_t *encodeData, //in_data + uint8_t *decodeData, //out_data + const int pixelsWidth, + const int pixelsHeight, + S3TCDecodeFlag decodeFlag) +{ + uint32_t *decodeBlockData = (uint32_t *)decodeData; + for (int block_y = 0; block_y < pixelsHeight / 4; ++block_y, decodeBlockData += 3 * pixelsWidth) //stride = 3*width + { + for(int block_x = 0; block_x < pixelsWidth / 4; ++block_x, decodeBlockData += 4) //skip 4 pixels + { + uint64_t blockAlpha = 0; + + switch (decodeFlag) + { + case S3TCDecodeFlag::DXT1: + { + s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 0, 0LL, S3TCDecodeFlag::DXT1); + } + break; + case S3TCDecodeFlag::DXT3: + { + memcpy((void *)&blockAlpha, encodeData, 8); + encodeData += 8; + s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, S3TCDecodeFlag::DXT3); + } + break; + case S3TCDecodeFlag::DXT5: + { + memcpy((void *)&blockAlpha, encodeData, 8); + encodeData += 8; + s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, S3TCDecodeFlag::DXT5); + } + break; + default: + break; + }//switch + }//for block_x + }//for block_y +} + + diff --git a/cocos/base/s3tc/s3tc.h b/cocos/base/s3tc/s3tc.h new file mode 100644 index 0000000000..a3cf233257 --- /dev/null +++ b/cocos/base/s3tc/s3tc.h @@ -0,0 +1,48 @@ +/**************************************************************************** + 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 COCOS2DX_PLATFORM_THIRDPARTY_S3TC_ +#define COCOS2DX_PLATFORM_THIRDPARTY_S3TC_ + +#include "CCStdC.h" + +enum class S3TCDecodeFlag +{ + DXT1 = 1, + DXT3 = 3, + DXT5 = 5, +}; + +//Decode S3TC encode data to RGB32 + void s3tc_decode(uint8_t *encode_data, + uint8_t *decode_data, + const int pixelsWidth, + const int pixelsHeight, + S3TCDecodeFlag decodeFlag + ); + + +#endif /* defined(COCOS2DX_PLATFORM_THIRDPARTY_S3TC_) */ + diff --git a/external/tinyxml2/tinyxml2.cpp b/external/tinyxml2/tinyxml2.cpp new file mode 100644 index 0000000000..f181b9050c --- /dev/null +++ b/external/tinyxml2/tinyxml2.cpp @@ -0,0 +1,2101 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#include "tinyxml2.h" + +#include // yes, this one new style header, is in the Android SDK. +# if defined(ANDROID_NDK) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) +# include +#else +# include +#endif + +static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; + +// Bunch of unicode info at: +// http://www.unicode.org/faq/utf_bom.html +// ef bb bf (Microsoft "lead bytes") - designates UTF-8 + +static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; +static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; +static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; + + +#define DELETE_NODE( node ) { \ + if ( node ) { \ + MemPool* pool = node->_memPool; \ + node->~XMLNode(); \ + pool->Free( node ); \ + } \ + } +#define DELETE_ATTRIBUTE( attrib ) { \ + if ( attrib ) { \ + MemPool* pool = attrib->_memPool; \ + attrib->~XMLAttribute(); \ + pool->Free( attrib ); \ + } \ + } + +namespace tinyxml2 +{ + +struct Entity { + const char* pattern; + int length; + char value; +}; + +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } +}; + + +StrPair::~StrPair() +{ + Reset(); +} + + +void StrPair::Reset() +{ + if ( _flags & NEEDS_DELETE ) { + delete [] _start; + } + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::SetStr( const char* str, int flags ) +{ + Reset(); + size_t len = strlen( str ); + _start = new char[ len+1 ]; + memcpy( _start, str, len+1 ); + _end = _start + len; + _flags = flags | NEEDS_DELETE; +} + + +char* StrPair::ParseText( char* p, const char* endTag, int strFlags ) +{ + TIXMLASSERT( endTag && *endTag ); + + char* start = p; // fixme: hides a member + char endChar = *endTag; + size_t length = strlen( endTag ); + + // Inner loop of text parsing. + while ( *p ) { + if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { + Set( start, p, strFlags ); + return p + length; + } + ++p; + } + return 0; +} + + +char* StrPair::ParseName( char* p ) +{ + char* start = p; + + if ( !start || !(*start) ) { + return 0; + } + + while( *p && ( + XMLUtil::IsAlphaNum( (unsigned char) *p ) + || *p == '_' + || *p == ':' + || (*p == '-' && p>start ) // can be in a name, but not lead it. + || (*p == '.' && p>start ) )) { // can be in a name, but not lead it. + ++p; + } + + if ( p > start ) { + Set( start, p, 0 ); + return p; + } + return 0; +} + + +void StrPair::CollapseWhitespace() +{ + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace( _start ); + + if ( _start && *_start ) { + char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( *p ) { + if ( XMLUtil::IsWhiteSpace( *p )) { + p = XMLUtil::SkipWhiteSpace( p ); + if ( *p == 0 ) { + break; // don't write to q; this trims the trailing space. + } + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; + } + *q = 0; + } +} + + +const char* StrPair::GetStr() +{ + if ( _flags & NEEDS_FLUSH ) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if ( _flags ) { + char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( p < _end ) { + if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if ( *(p+1) == LF ) { + p += 2; + } + else { + ++p; + } + *q++ = LF; + } + else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { + if ( *(p+1) == CR ) { + p += 2; + } + else { + ++p; + } + *q++ = LF; + } + else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if ( *(p+1) == '#' ) { + char buf[10] = { 0 }; + int len; + p = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); + for( int i=0; i(p); + // Check for BOM: + if ( *(pu+0) == TIXML_UTF_LEAD_0 + && *(pu+1) == TIXML_UTF_LEAD_1 + && *(pu+2) == TIXML_UTF_LEAD_2 ) { + *bom = true; + p += 3; + } + return p; +} + + +void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + + if (input < 0x80) { + *length = 1; + } + else if ( input < 0x800 ) { + *length = 2; + } + else if ( input < 0x10000 ) { + *length = 3; + } + else if ( input < 0x200000 ) { + *length = 4; + } + else { + *length = 0; // This code won't covert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs. + switch (*length) { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + default: + break; + } +} + + +const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) +{ + // Presume an entity, and pull it out. + *length = 0; + + if ( *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + ptrdiff_t delta = 0; + unsigned mult = 1; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + if ( !*(p+3) ) { + return 0; + } + + const char* q = p+3; + q = strchr( q, ';' ); + + if ( !q || !*q ) { + return 0; + } + + delta = q-p; + --q; + + while ( *q != 'x' ) { + if ( *q >= '0' && *q <= '9' ) { + ucs += mult * (*q - '0'); + } + else if ( *q >= 'a' && *q <= 'f' ) { + ucs += mult * (*q - 'a' + 10); + } + else if ( *q >= 'A' && *q <= 'F' ) { + ucs += mult * (*q - 'A' + 10 ); + } + else { + return 0; + } + mult *= 16; + --q; + } + } + else { + // Decimal. + if ( !*(p+2) ) { + return 0; + } + + const char* q = p+2; + q = strchr( q, ';' ); + + if ( !q || !*q ) { + return 0; + } + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) { + ucs += mult * (*q - '0'); + } + else { + return 0; + } + mult *= 10; + --q; + } + } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + return p + delta + 1; + } + return p+1; +} + + +void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); +} + + +void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); +} + + +void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 ); +} + + +void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%g", v ); +} + + +void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%g", v ); +} + + +bool XMLUtil::ToInt( const char* str, int* value ) +{ + if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) +{ + if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToBool( const char* str, bool* value ) +{ + int ival = 0; + if ( ToInt( str, &ival )) { + *value = (ival==0) ? false : true; + return true; + } + if ( StringEqual( str, "true" ) ) { + *value = true; + return true; + } + else if ( StringEqual( str, "false" ) ) { + *value = false; + return true; + } + return false; +} + + +bool XMLUtil::ToFloat( const char* str, float* value ) +{ + if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToDouble( const char* str, double* value ) +{ + if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { + return true; + } + return false; +} + + +char* XMLDocument::Identify( char* p, XMLNode** node ) +{ + XMLNode* returnNode = 0; + char* start = p; + p = XMLUtil::SkipWhiteSpace( p ); + if( !p || !*p ) { + return p; + } + + // What is this thing? + // - Elements start with a letter or underscore, but xml is reserved. + // - Comments: + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + while( p && *p ) { + XMLNode* node = 0; + + p = _document->Identify( p, &node ); + if ( p == 0 || node == 0 ) { + break; + } + + StrPair endTag; + p = node->ParseDeep( p, &endTag ); + if ( !p ) { + DELETE_NODE( node ); + node = 0; + if ( !_document->Error() ) { + _document->SetError( XML_ERROR_PARSING, 0, 0 ); + } + break; + } + + // We read the end tag. Return it to the parent. + if ( node->ToElement() && node->ToElement()->ClosingType() == XMLElement::CLOSING ) { + if ( parentEnd ) { + *parentEnd = static_cast(node)->_value; + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DELETE_NODE( node ); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + XMLElement* ele = node->ToElement(); + if ( ele ) { + if ( endTag.Empty() && ele->ClosingType() == XMLElement::OPEN ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); + p = 0; + } + else if ( !endTag.Empty() && ele->ClosingType() != XMLElement::OPEN ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); + p = 0; + } + else if ( !endTag.Empty() ) { + if ( !XMLUtil::StringEqual( endTag.GetStr(), node->Value() )) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); + p = 0; + } + } + } + if ( p == 0 ) { + DELETE_NODE( node ); + node = 0; + } + if ( node ) { + this->InsertEndChild( node ); + } + } + return 0; +} + +// --------- XMLText ---------- // +char* XMLText::ParseDeep( char* p, StrPair* ) +{ + const char* start = p; + if ( this->CData() ) { + p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 ); + } + return p; + } + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { + flags |= StrPair::COLLAPSE_WHITESPACE; + } + + p = _value.ParseText( p, "<", flags ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 ); + } + if ( p && *p ) { + return p-1; + } + } + return 0; +} + + +XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? + text->SetCData( this->CData() ); + return text; +} + + +bool XMLText::ShallowEqual( const XMLNode* compare ) const +{ + return ( compare->ToText() && XMLUtil::StringEqual( compare->ToText()->Value(), Value() )); +} + + +bool XMLText::Accept( XMLVisitor* visitor ) const +{ + return visitor->Visit( *this ); +} + + +// --------- XMLComment ---------- // + +XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLComment::~XMLComment() +{ +} + + +char* XMLComment::ParseDeep( char* p, StrPair* ) +{ + // Comment parses as text. + const char* start = p; + p = _value.ParseText( p, "-->", StrPair::COMMENT ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 ); + } + return p; +} + + +XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? + return comment; +} + + +bool XMLComment::ShallowEqual( const XMLNode* compare ) const +{ + return ( compare->ToComment() && XMLUtil::StringEqual( compare->ToComment()->Value(), Value() )); +} + + +bool XMLComment::Accept( XMLVisitor* visitor ) const +{ + return visitor->Visit( *this ); +} + + +// --------- XMLDeclaration ---------- // + +XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLDeclaration::~XMLDeclaration() +{ + //printf( "~XMLDeclaration\n" ); +} + + +char* XMLDeclaration::ParseDeep( char* p, StrPair* ) +{ + // Declaration parses as text. + const char* start = p; + p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 ); + } + return p; +} + + +XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? + return dec; +} + + +bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const +{ + return ( compare->ToDeclaration() && XMLUtil::StringEqual( compare->ToDeclaration()->Value(), Value() )); +} + + + +bool XMLDeclaration::Accept( XMLVisitor* visitor ) const +{ + return visitor->Visit( *this ); +} + +// --------- XMLUnknown ---------- // + +XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLUnknown::~XMLUnknown() +{ +} + + +char* XMLUnknown::ParseDeep( char* p, StrPair* ) +{ + // Unknown parses as text. + const char* start = p; + + p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 ); + } + return p; +} + + +XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? + return text; +} + + +bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const +{ + return ( compare->ToUnknown() && XMLUtil::StringEqual( compare->ToUnknown()->Value(), Value() )); +} + + +bool XMLUnknown::Accept( XMLVisitor* visitor ) const +{ + return visitor->Visit( *this ); +} + +// --------- XMLAttribute ---------- // +char* XMLAttribute::ParseDeep( char* p, bool processEntities ) +{ + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName( p ); + if ( !p || !*p ) { + return 0; + } + + // Skip white space before = + p = XMLUtil::SkipWhiteSpace( p ); + if ( !p || *p != '=' ) { + return 0; + } + + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace( p ); + if ( *p != '\"' && *p != '\'' ) { + return 0; + } + + char endTag[2] = { *p, 0 }; + ++p; // move past opening quote + + p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES ); + return p; +} + + +void XMLAttribute::SetName( const char* n ) +{ + _name.SetStr( n ); +} + + +XMLError XMLAttribute::QueryIntValue( int* value ) const +{ + if ( XMLUtil::ToInt( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const +{ + if ( XMLUtil::ToUnsigned( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryBoolValue( bool* value ) const +{ + if ( XMLUtil::ToBool( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryFloatValue( float* value ) const +{ + if ( XMLUtil::ToFloat( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryDoubleValue( double* value ) const +{ + if ( XMLUtil::ToDouble( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +void XMLAttribute::SetAttribute( const char* v ) +{ + _value.SetStr( v ); +} + + +void XMLAttribute::SetAttribute( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +// --------- XMLElement ---------- // +XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), + _closingType( 0 ), + _rootAttribute( 0 ) +{ +} + + +XMLElement::~XMLElement() +{ + while( _rootAttribute ) { + XMLAttribute* next = _rootAttribute->_next; + DELETE_ATTRIBUTE( _rootAttribute ); + _rootAttribute = next; + } +} + + +XMLAttribute* XMLElement::FindAttribute( const char* name ) +{ + XMLAttribute* a = 0; + for( a=_rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } + } + return 0; +} + + +const XMLAttribute* XMLElement::FindAttribute( const char* name ) const +{ + XMLAttribute* a = 0; + for( a=_rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } + } + return 0; +} + + +const char* XMLElement::Attribute( const char* name, const char* value ) const +{ + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return 0; + } + if ( !value || XMLUtil::StringEqual( a->Value(), value )) { + return a->Value(); + } + return 0; +} + + +const char* XMLElement::GetText() const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + return FirstChild()->ToText()->Value(); + } + return 0; +} + + +XMLError XMLElement::QueryIntText( int* ival ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->ToText()->Value(); + if ( XMLUtil::ToInt( t, ival ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->ToText()->Value(); + if ( XMLUtil::ToUnsigned( t, uval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryBoolText( bool* bval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->ToText()->Value(); + if ( XMLUtil::ToBool( t, bval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryDoubleText( double* dval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->ToText()->Value(); + if ( XMLUtil::ToDouble( t, dval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryFloatText( float* fval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->ToText()->Value(); + if ( XMLUtil::ToFloat( t, fval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + + +XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) +{ + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for( attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next ) { + if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { + break; + } + } + if ( !attrib ) { + attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + attrib->_memPool = &_document->_attributePool; + if ( last ) { + last->_next = attrib; + } + else { + _rootAttribute = attrib; + } + attrib->SetName( name ); + attrib->_memPool->SetTracked(); // always created and linked. + } + return attrib; +} + + +void XMLElement::DeleteAttribute( const char* name ) +{ + XMLAttribute* prev = 0; + for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { + if ( XMLUtil::StringEqual( name, a->Name() ) ) { + if ( prev ) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DELETE_ATTRIBUTE( a ); + break; + } + prev = a; + } +} + + +char* XMLElement::ParseAttributes( char* p ) +{ + const char* start = p; + XMLAttribute* prevAttribute = 0; + + // Read the attributes. + while( p ) { + p = XMLUtil::SkipWhiteSpace( p ); + if ( !p || !(*p) ) { + _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() ); + return 0; + } + + // attribute. + if ( XMLUtil::IsAlpha( *p ) ) { + XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + + p = attrib->ParseDeep( p, _document->ProcessEntities() ); + if ( !p || Attribute( attrib->Name() ) ) { + DELETE_ATTRIBUTE( attrib ); + _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p ); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if ( prevAttribute ) { + prevAttribute->_next = attrib; + } + else { + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if ( *p == '/' && *(p+1) == '>' ) { + _closingType = CLOSED; + return p+2; // done; sealed element. + } + // end of the tag + else if ( *p == '>' ) { + ++p; + break; + } + else { + _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p ); + return 0; + } + } + return p; +} + + +// +// +// foobar +// +char* XMLElement::ParseDeep( char* p, StrPair* strPair ) +{ + // Read the element name. + p = XMLUtil::SkipWhiteSpace( p ); + if ( !p ) { + return 0; + } + + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if ( *p == '/' ) { + _closingType = CLOSING; + ++p; + } + + p = _value.ParseName( p ); + if ( _value.Empty() ) { + return 0; + } + + p = ParseAttributes( p ); + if ( !p || !*p || _closingType ) { + return p; + } + + p = XMLNode::ParseDeep( p, strPair ); + return p; +} + + + +XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? + for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { + element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + } + return element; +} + + +bool XMLElement::ShallowEqual( const XMLNode* compare ) const +{ + const XMLElement* other = compare->ToElement(); + if ( other && XMLUtil::StringEqual( other->Value(), Value() )) { + + const XMLAttribute* a=FirstAttribute(); + const XMLAttribute* b=other->FirstAttribute(); + + while ( a && b ) { + if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if ( a || b ) { + // different count + return false; + } + return true; + } + return false; +} + + +bool XMLElement::Accept( XMLVisitor* visitor ) const +{ + if ( visitor->VisitEnter( *this, _rootAttribute ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLDocument ----------- // +XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) : + XMLNode( 0 ), + _writeBOM( false ), + _processEntities( processEntities ), + _errorID( XML_NO_ERROR ), + _whitespace( whitespace ), + _errorStr1( 0 ), + _errorStr2( 0 ), + _charBuffer( 0 ) +{ + _document = this; // avoid warning about 'this' in initializer list +} + + +XMLDocument::~XMLDocument() +{ + DeleteChildren(); + delete [] _charBuffer; + +#if 0 + textPool.Trace( "text" ); + elementPool.Trace( "element" ); + commentPool.Trace( "comment" ); + attributePool.Trace( "attribute" ); +#endif + +#ifdef DEBUG + if ( Error() == false ) { + TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); + TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); + TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); + TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); + } +#endif +} + + +void XMLDocument::InitDocument() +{ + _errorID = XML_NO_ERROR; + _errorStr1 = 0; + _errorStr2 = 0; + + delete [] _charBuffer; + _charBuffer = 0; +} + + +XMLElement* XMLDocument::NewElement( const char* name ) +{ + XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this ); + ele->_memPool = &_elementPool; + ele->SetName( name ); + return ele; +} + + +XMLComment* XMLDocument::NewComment( const char* str ) +{ + XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this ); + comment->_memPool = &_commentPool; + comment->SetValue( str ); + return comment; +} + + +XMLText* XMLDocument::NewText( const char* str ) +{ + XMLText* text = new (_textPool.Alloc()) XMLText( this ); + text->_memPool = &_textPool; + text->SetValue( str ); + return text; +} + + +XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) +{ + XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this ); + dec->_memPool = &_commentPool; + dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); + return dec; +} + + +XMLUnknown* XMLDocument::NewUnknown( const char* str ) +{ + XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this ); + unk->_memPool = &_commentPool; + unk->SetValue( str ); + return unk; +} + + +XMLError XMLDocument::LoadFile( const char* filename ) +{ + DeleteChildren(); + InitDocument(); + FILE* fp = 0; + +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + errno_t err = fopen_s(&fp, filename, "rb" ); + if ( !fp || err) { +#else + fp = fopen( filename, "rb" ); + if ( !fp) { +#endif + SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 ); + return _errorID; + } + LoadFile( fp ); + fclose( fp ); + return _errorID; +} + + +XMLError XMLDocument::LoadFile( FILE* fp ) +{ + DeleteChildren(); + InitDocument(); + + fseek( fp, 0, SEEK_END ); + size_t size = ftell( fp ); + fseek( fp, 0, SEEK_SET ); + + if ( size == 0 ) { + return _errorID; + } + + _charBuffer = new char[size+1]; + size_t read = fread( _charBuffer, 1, size, fp ); + if ( read != size ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + _charBuffer[size] = 0; + + const char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace( p ); + p = XMLUtil::ReadBOM( p, &_writeBOM ); + if ( !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + ParseDeep( _charBuffer + (p-_charBuffer), 0 ); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( const char* filename, bool compact ) +{ + FILE* fp = 0; +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + errno_t err = fopen_s(&fp, filename, "w" ); + if ( !fp || err) { +#else + fp = fopen( filename, "w" ); + if ( !fp) { +#endif + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 ); + return _errorID; + } + SaveFile(fp, compact); + fclose( fp ); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) +{ + XMLPrinter stream( fp, compact ); + Print( &stream ); + return _errorID; +} + + +XMLError XMLDocument::Parse( const char* p, size_t len ) +{ + DeleteChildren(); + InitDocument(); + + if ( !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + if ( len == (size_t)(-1) ) { + len = strlen( p ); + } + _charBuffer = new char[ len+1 ]; + memcpy( _charBuffer, p, len ); + _charBuffer[len] = 0; + + p = XMLUtil::SkipWhiteSpace( p ); + p = XMLUtil::ReadBOM( p, &_writeBOM ); + if ( !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + ParseDeep( _charBuffer, 0 ); + return _errorID; +} + + +void XMLDocument::Print( XMLPrinter* streamer ) +{ + XMLPrinter stdStreamer( stdout ); + if ( !streamer ) { + streamer = &stdStreamer; + } + Accept( streamer ); +} + + +void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 ) +{ + _errorID = error; + _errorStr1 = str1; + _errorStr2 = str2; +} + + +void XMLDocument::PrintError() const +{ + if ( _errorID ) { + static const int LEN = 20; + char buf1[LEN] = { 0 }; + char buf2[LEN] = { 0 }; + + if ( _errorStr1 ) { + TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 ); + } + if ( _errorStr2 ) { + TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 ); + } + + printf( "XMLDocument error id=%d str1=%s str2=%s\n", + _errorID, buf1, buf2 ); + } +} + + +XMLPrinter::XMLPrinter( FILE* file, bool compact ) : + _elementJustOpened( false ), + _firstElement( true ), + _fp( file ), + _depth( 0 ), + _textDepth( -1 ), + _processEntities( true ), + _compactMode( compact ) +{ + for( int i=0; i'] = true; // not required, but consistency is nice + _buffer.Push( 0 ); +} + + +void XMLPrinter::Print( const char* format, ... ) +{ + va_list va; + va_start( va, format ); + + if ( _fp ) { + vfprintf( _fp, format, va ); + } + else { + // This seems brutally complex. Haven't figured out a better + // way on windows. +#if defined _MSC_VER && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + int len = -1; + int expand = 1000; + while ( len < 0 ) { + len = vsnprintf_s( _accumulator.Mem(), _accumulator.Capacity(), _TRUNCATE, format, va ); + if ( len < 0 ) { + expand *= 3/2; + _accumulator.PushArr( expand ); + } + } + char* p = _buffer.PushArr( len ) - 1; + memcpy( p, _accumulator.Mem(), len+1 ); +#else + int len = vsnprintf( 0, 0, format, va ); + // Close out and re-start the va-args + va_end( va ); + va_start( va, format ); + char* p = _buffer.PushArr( len ) - 1; + vsnprintf( p, len+1, format, va ); +#endif + } + va_end( va ); +} + + +void XMLPrinter::PrintSpace( int depth ) +{ + for( int i=0; i 0 && *q < ENTITY_RANGE ) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if ( flag[(unsigned)(*q)] ) { + while ( p < q ) { + Print( "%c", *p ); + ++p; + } + for( int i=0; i 0) ) { + Print( "%s", p ); + } +} + + +void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) +{ + static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; + if ( writeBOM ) { + Print( "%s", bom ); + } + if ( writeDec ) { + PushDeclaration( "xml version=\"1.0\"" ); + } +} + + +void XMLPrinter::OpenElement( const char* name ) +{ + if ( _elementJustOpened ) { + SealElement(); + } + _stack.Push( name ); + + if ( _textDepth < 0 && !_firstElement && !_compactMode ) { + Print( "\n" ); + PrintSpace( _depth ); + } + + Print( "<%s", name ); + _elementJustOpened = true; + _firstElement = false; + ++_depth; +} + + +void XMLPrinter::PushAttribute( const char* name, const char* value ) +{ + TIXMLASSERT( _elementJustOpened ); + Print( " %s=\"", name ); + PrintString( value, false ); + Print( "\"" ); +} + + +void XMLPrinter::PushAttribute( const char* name, int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::CloseElement() +{ + --_depth; + const char* name = _stack.Pop(); + + if ( _elementJustOpened ) { + Print( "/>" ); + } + else { + if ( _textDepth < 0 && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + Print( "", name ); + } + + if ( _textDepth == _depth ) { + _textDepth = -1; + } + if ( _depth == 0 && !_compactMode) { + Print( "\n" ); + } + _elementJustOpened = false; +} + + +void XMLPrinter::SealElement() +{ + _elementJustOpened = false; + Print( ">" ); +} + + +void XMLPrinter::PushText( const char* text, bool cdata ) +{ + _textDepth = _depth-1; + + if ( _elementJustOpened ) { + SealElement(); + } + if ( cdata ) { + Print( "" ); + } + else { + PrintString( text, true ); + } +} + +void XMLPrinter::PushText( int value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( unsigned value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( bool value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( float value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( double value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushComment( const char* comment ) +{ + if ( _elementJustOpened ) { + SealElement(); + } + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", comment ); +} + + +void XMLPrinter::PushDeclaration( const char* value ) +{ + if ( _elementJustOpened ) { + SealElement(); + } + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", value ); +} + + +void XMLPrinter::PushUnknown( const char* value ) +{ + if ( _elementJustOpened ) { + SealElement(); + } + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", value ); +} + + +bool XMLPrinter::VisitEnter( const XMLDocument& doc ) +{ + _processEntities = doc.ProcessEntities(); + if ( doc.HasBOM() ) { + PushHeader( true, false ); + } + return true; +} + + +bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) +{ + OpenElement( element.Name() ); + while ( attribute ) { + PushAttribute( attribute->Name(), attribute->Value() ); + attribute = attribute->Next(); + } + return true; +} + + +bool XMLPrinter::VisitExit( const XMLElement& ) +{ + CloseElement(); + return true; +} + + +bool XMLPrinter::Visit( const XMLText& text ) +{ + PushText( text.Value(), text.CData() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLComment& comment ) +{ + PushComment( comment.Value() ); + return true; +} + +bool XMLPrinter::Visit( const XMLDeclaration& declaration ) +{ + PushDeclaration( declaration.Value() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLUnknown& unknown ) +{ + PushUnknown( unknown.Value() ); + return true; +} + +} // namespace tinyxml2 + diff --git a/external/tinyxml2/tinyxml2.h b/external/tinyxml2/tinyxml2.h new file mode 100644 index 0000000000..eeffa1096f --- /dev/null +++ b/external/tinyxml2/tinyxml2.h @@ -0,0 +1,1914 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#ifndef TINYXML2_INCLUDED +#define TINYXML2_INCLUDED + +#include "platform/CCPlatformConfig.h" +#include "platform/CCPlatformMacros.h" + +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) +# include +# include +# include +# include +# include +# include +#else +# include +# include +# include +# include +# include +# include +#endif + +/* + TODO: intern strings instead of allocation. +*/ +/* + gcc: + g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe + + Formatting, Artistic Style: + AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h +*/ + +#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) +# ifndef DEBUG +# define DEBUG +# endif +#endif + + +#if defined(DEBUG) +# if defined(_MSC_VER) +# define TIXMLASSERT( x ) if ( !(x)) { __debugbreak(); } //if ( !(x)) WinDebugBreak() +# elif defined (ANDROID_NDK) +# include +# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } +# else +# include +# define TIXMLASSERT assert +# endif +# else +# define TIXMLASSERT( x ) {} +#endif + + +#if (defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)) +// Microsoft visual studio, version 2005 and higher. +/*int _snprintf_s( + char *buffer, + size_t sizeOfBuffer, + size_t count, + const char *format [, + argument] ... +);*/ +inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) +{ + va_list va; + va_start( va, format ); + int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + va_end( va ); + return result; +} +#define TIXML_SSCANF sscanf_s +#else +// GCC version 3 and higher +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_SSCANF sscanf +#endif + +static const int TIXML2_MAJOR_VERSION = 1; +static const int TIXML2_MINOR_VERSION = 0; +static const int TIXML2_PATCH_VERSION = 9; + +namespace tinyxml2 +{ +class XMLDocument; +class XMLElement; +class XMLAttribute; +class XMLComment; +class XMLNode; +class XMLText; +class XMLDeclaration; +class XMLUnknown; + +class XMLPrinter; + +/* + A class that wraps strings. Normally stores the start and end + pointers into the XML file itself, and will apply normalization + and entity translation if actually read. Can also store (and memory + manage) a traditional char[] +*/ +class CC_DLL StrPair +{ +public: + enum { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + COLLAPSE_WHITESPACE = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} + ~StrPair(); + + void Set( char* start, char* end, int flags ) { + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { + return _start == _end; + } + + void SetInternedStr( const char* str ) { + Reset(); + _start = const_cast(str); + } + + void SetStr( const char* str, int flags=0 ); + + char* ParseText( char* in, const char* endTag, int strFlags ); + char* ParseName( char* in ); + +private: + void Reset(); + void CollapseWhitespace(); + + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; + + // After parsing, if *end != 0, it can be set to zero. + int _flags; + char* _start; + char* _end; +}; + + +/* + A dynamic array of Plain Old Data. Doesn't support constructors, etc. + Has a small initial memory pool, so that low or no usage will not + cause a call to new/delete +*/ +template +class CC_DLL DynArray +{ +public: + DynArray< T, INIT >() { + _mem = _pool; + _allocated = INIT; + _size = 0; + } + + ~DynArray() { + if ( _mem != _pool ) { + delete [] _mem; + } + } + + void Push( T t ) { + EnsureCapacity( _size+1 ); + _mem[_size++] = t; + } + + T* PushArr( int count ) { + EnsureCapacity( _size+count ); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() { + return _mem[--_size]; + } + + void PopArr( int count ) { + TIXMLASSERT( _size >= count ); + _size -= count; + } + + bool Empty() const { + return _size == 0; + } + + T& operator[](int i) { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& operator[](int i) const { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + int Size() const { + return _size; + } + + int Capacity() const { + return _allocated; + } + + const T* Mem() const { + return _mem; + } + + T* Mem() { + return _mem; + } + +private: + void EnsureCapacity( int cap ) { + if ( cap > _allocated ) { + int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs + if ( _mem != _pool ) { + delete [] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } + + T* _mem; + T _pool[INIT]; + int _allocated; // objects allocated + int _size; // number objects in use +}; + + +/* + Parent virtual class of a pool for fast allocation + and deallocation of objects. +*/ +class CC_DLL MemPool +{ +public: + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free( void* ) = 0; + virtual void SetTracked() = 0; +}; + + +/* + Template child class to create pools of the correct type. +*/ +template< int SIZE > +class CC_DLL MemPoolT : public MemPool +{ +public: + MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + // Delete the blocks. + for( int i=0; i<_blockPtrs.Size(); ++i ) { + delete _blockPtrs[i]; + } + } + + virtual int ItemSize() const { + return SIZE; + } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if ( !_root ) { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push( block ); + + for( int i=0; ichunk[i].next = &block->chunk[i+1]; + } + block->chunk[COUNT-1].next = 0; + _root = block->chunk; + } + void* result = _root; + _root = _root->next; + + ++_currentAllocs; + if ( _currentAllocs > _maxAllocs ) { + _maxAllocs = _currentAllocs; + } + _nAllocs++; + _nUntracked++; + return result; + } + virtual void Free( void* mem ) { + if ( !mem ) { + return; + } + --_currentAllocs; + Chunk* chunk = (Chunk*)mem; +#ifdef DEBUG + memset( chunk, 0xfe, sizeof(Chunk) ); +#endif + chunk->next = _root; + _root = chunk; + } + void Trace( const char* name ) { + printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs*SIZE/1024, _currentAllocs, SIZE, _nAllocs, _blockPtrs.Size() ); + } + + void SetTracked() { + _nUntracked--; + } + + int Untracked() const { + return _nUntracked; + } + + enum { COUNT = 1024/SIZE }; // Some compilers do not accept to use COUNT in private part if COUNT is private + +private: + union Chunk { + Chunk* next; + char mem[SIZE]; + }; + struct Block { + Chunk chunk[COUNT]; + }; + DynArray< Block*, 10 > _blockPtrs; + Chunk* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; +}; + + + +/** + Implements the interface to the "Visitor pattern" (see the Accept() method.) + If you call the Accept() method, it requires being passed a XMLVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs + are simply called with Visit(). + + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, no children of this node or its sibilings will be visited. + + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. + + Generally Accept() is called on the TiXmlDocument, although all nodes support visiting. + + You should never change the document from a callback. + + @sa XMLNode::Accept() +*/ +class CC_DLL XMLVisitor +{ +public: + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const XMLElement& /*element*/ ) { + return true; + } + + /// Visit a declaration. + virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node. + virtual bool Visit( const XMLText& /*text*/ ) { + return true; + } + /// Visit a comment node. + virtual bool Visit( const XMLComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node. + virtual bool Visit( const XMLUnknown& /*unknown*/ ) { + return true; + } +}; + + +/* + Utility functionality. +*/ +class CC_DLL XMLUtil +{ +public: + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static const char* SkipWhiteSpace( const char* p ) { + while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast(p) ) ) { + ++p; + } + return p; + } + static char* SkipWhiteSpace( char* p ) { + while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast(p) ) ) { + ++p; + } + return p; + } + static bool IsWhiteSpace( char p ) { + return !IsUTF8Continuation(p) && isspace( static_cast(p) ); + } + + inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { + int n = 0; + if ( p == q ) { + return true; + } + while( *p && *q && *p == *q && n(const_cast(this)->FirstChildElement( value )); + } + + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } + + XMLNode* LastChild() { + return const_cast(const_cast(this)->LastChild() ); + } + + /** Get the last child element or optionally the last child + element with the specified name. + */ + const XMLElement* LastChildElement( const char* value=0 ) const; + + XMLElement* LastChildElement( const char* value=0 ) { + return const_cast(const_cast(this)->LastChildElement(value) ); + } + + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } + + XMLNode* PreviousSibling() { + return _prev; + } + + /// Get the previous (left) sibling element of this node, with an opitionally supplied name. + const XMLElement* PreviousSiblingElement( const char* value=0 ) const ; + + XMLElement* PreviousSiblingElement( const char* value=0 ) { + return const_cast(const_cast(this)->PreviousSiblingElement( value ) ); + } + + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } + + XMLNode* NextSibling() { + return _next; + } + + /// Get the next (right) sibling element of this node, with an opitionally supplied name. + const XMLElement* NextSiblingElement( const char* value=0 ) const; + + XMLElement* NextSiblingElement( const char* value=0 ) { + return const_cast(const_cast(this)->NextSiblingElement( value ) ); + } + + /** + Add a child node as the last (right) child. + */ + XMLNode* InsertEndChild( XMLNode* addThis ); + + XMLNode* LinkEndChild( XMLNode* addThis ) { + return InsertEndChild( addThis ); + } + /** + Add a child node as the first (left) child. + */ + XMLNode* InsertFirstChild( XMLNode* addThis ); + /** + Add a node after the specified child node. + */ + XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + + /** + Delete all the children of this node. + */ + void DeleteChildren(); + + /** + Delete a child of this node. + */ + void DeleteChild( XMLNode* node ); + + /** + Make a copy of this node, but not its children. + You may pass in a Document pointer that will be + the owner of the new Node. If the 'document' is + null, then the node returned will be allocated + from the current Document. (this->GetDocument()) + + Note: if called on a XMLDocument, this will return null. + */ + virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + + /** + Test if 2 nodes are the same, but don't test children. + The 2 nodes do not need to be in the same Document. + + Note: if called on a XMLDocument, this will return false. + */ + virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + + /** Accept a hierarchical visit of the nodes in the TinyXML DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the TiXmlVisitor interface. + + This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + TiXmlPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( XMLVisitor* visitor ) const = 0; + + // internal + virtual char* ParseDeep( char*, StrPair* ); + +protected: + XMLNode( XMLDocument* ); + virtual ~XMLNode(); + XMLNode( const XMLNode& ); // not supported + XMLNode& operator=( const XMLNode& ); // not supported + + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + + XMLNode* _firstChild; + XMLNode* _lastChild; + + XMLNode* _prev; + XMLNode* _next; + +private: + MemPool* _memPool; + void Unlink( XMLNode* child ); +}; + + +/** XML text. + + Note that a text node can have child element nodes, for example: + @verbatim + This is bold + @endverbatim + + A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCDATA() and query it with CDATA(). +*/ +class CC_DLL XMLText : public XMLNode +{ + friend class XMLBase; + friend class XMLDocument; +public: + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } + + /// Declare whether this should be CDATA or standard text. + void SetCData( bool isCData ) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } + + char* ParseDeep( char*, StrPair* endTag ); + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} + virtual ~XMLText() {} + XMLText( const XMLText& ); // not supported + XMLText& operator=( const XMLText& ); // not supported + +private: + bool _isCData; +}; + + +/** An XML Comment. */ +class CC_DLL XMLComment : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + char* ParseDeep( char*, StrPair* endTag ); + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLComment( XMLDocument* doc ); + virtual ~XMLComment(); + XMLComment( const XMLComment& ); // not supported + XMLComment& operator=( const XMLComment& ); // not supported + +private: +}; + + +/** In correct XML the declaration is the first entry in the file. + @verbatim + + @endverbatim + + TinyXML2 will happily read or write files without a declaration, + however. + + The text of the declaration isn't interpreted. It is parsed + and written as a string. +*/ +class CC_DLL XMLDeclaration : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + char* ParseDeep( char*, StrPair* endTag ); + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLDeclaration( XMLDocument* doc ); + virtual ~XMLDeclaration(); + XMLDeclaration( const XMLDeclaration& ); // not supported + XMLDeclaration& operator=( const XMLDeclaration& ); // not supported +}; + + +/** Any tag that tinyXml doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. + + DTD tags get thrown into TiXmlUnknowns. +*/ +class CC_DLL XMLUnknown : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + char* ParseDeep( char*, StrPair* endTag ); + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLUnknown( XMLDocument* doc ); + virtual ~XMLUnknown(); + XMLUnknown( const XMLUnknown& ); // not supported + XMLUnknown& operator=( const XMLUnknown& ); // not supported +}; + + +enum XMLError { + XML_NO_ERROR = 0, + XML_SUCCESS = 0, + + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + XML_ERROR_ELEMENT_MISMATCH, + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + XML_ERROR_IDENTIFYING_TAG, + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE +}; + + +/** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. + + @note The attributes are not XMLNodes. You may only query the + Next() attribute in a list. +*/ +class CC_DLL XMLAttribute +{ + friend class XMLElement; +public: + /// The name of the attribute. + const char* Name() const { + return _name.GetStr(); + } + /// The value of the attribute. + const char* Value() const { + return _value.GetStr(); + } + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } + + /** IntAttribute interprets the attribute as an integer, and returns the value. + If the value isn't an integer, 0 will be returned. There is no error checking; + use QueryIntAttribute() if you need error checking. + */ + int IntValue() const { + int i=0; + QueryIntValue( &i ); + return i; + } + /// Query as an unsigned integer. See IntAttribute() + unsigned UnsignedValue() const { + unsigned i=0; + QueryUnsignedValue( &i ); + return i; + } + /// Query as a boolean. See IntAttribute() + bool BoolValue() const { + bool b=false; + QueryBoolValue( &b ); + return b; + } + /// Query as a double. See IntAttribute() + double DoubleValue() const { + double d=0; + QueryDoubleValue( &d ); + return d; + } + /// Query as a float. See IntAttribute() + float FloatValue() const { + float f=0; + QueryFloatValue( &f ); + return f; + } + + /** QueryIntAttribute interprets the attribute as an integer, and returns the value + in the provided paremeter. The function will return XML_NO_ERROR on success, + and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. + */ + XMLError QueryIntValue( int* value ) const; + /// See QueryIntAttribute + XMLError QueryUnsignedValue( unsigned int* value ) const; + /// See QueryIntAttribute + XMLError QueryBoolValue( bool* value ) const; + /// See QueryIntAttribute + XMLError QueryDoubleValue( double* value ) const; + /// See QueryIntAttribute + XMLError QueryFloatValue( float* value ) const; + + /// Set the attribute to a string value. + void SetAttribute( const char* value ); + /// Set the attribute to value. + void SetAttribute( int value ); + /// Set the attribute to value. + void SetAttribute( unsigned value ); + /// Set the attribute to value. + void SetAttribute( bool value ); + /// Set the attribute to value. + void SetAttribute( double value ); + /// Set the attribute to value. + void SetAttribute( float value ); + +private: + enum { BUF_SIZE = 200 }; + + XMLAttribute() : _next( 0 ) {} + virtual ~XMLAttribute() {} + + XMLAttribute( const XMLAttribute& ); // not supported + void operator=( const XMLAttribute& ); // not supported + void SetName( const char* name ); + + char* ParseDeep( char* p, bool processEntities ); + + mutable StrPair _name; + mutable StrPair _value; + XMLAttribute* _next; + MemPool* _memPool; +}; + + +/** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. +*/ +class CC_DLL XMLElement : public XMLNode +{ + friend class XMLBase; + friend class XMLDocument; +public: + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName( const char* str, bool staticMem=false ) { + SetValue( str, staticMem ); + } + + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept( XMLVisitor* visitor ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none + exists. For example: + + @verbatim + const char* value = ele->Attribute( "foo" ); + @endverbatim + + The 'value' parameter is normally null. However, if specified, + the attribute will only be returned if the 'name' and 'value' + match. This allow you to write code: + + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim + + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim + */ + const char* Attribute( const char* name, const char* value=0 ) const; + + /** Given an attribute name, IntAttribute() returns the value + of the attribute interpreted as an integer. 0 will be + returned if there is an error. For a method with error + checking, see QueryIntAttribute() + */ + int IntAttribute( const char* name ) const { + int i=0; + QueryIntAttribute( name, &i ); + return i; + } + /// See IntAttribute() + unsigned UnsignedAttribute( const char* name ) const { + unsigned i=0; + QueryUnsignedAttribute( name, &i ); + return i; + } + /// See IntAttribute() + bool BoolAttribute( const char* name ) const { + bool b=false; + QueryBoolAttribute( name, &b ); + return b; + } + /// See IntAttribute() + double DoubleAttribute( const char* name ) const { + double d=0; + QueryDoubleAttribute( name, &d ); + return d; + } + /// See IntAttribute() + float FloatAttribute( const char* name ) const { + float f=0; + QueryFloatAttribute( name, &f ); + return f; + } + + /** Given an attribute name, QueryIntAttribute() returns + XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryIntAttribute( const char* name, int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryBoolAttribute( const char* name, bool* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute( const char* name, double* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute( const char* name, float* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue( value ); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, const char* value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, int value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, unsigned value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, bool value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, double value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /** + Delete an attribute. + */ + void DeleteAttribute( const char* name ); + + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute( const char* name ) const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the TiXmlText child + and accessing it directly. + + If the first child of 'this' is a TiXmlText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". + */ + const char* GetText() const; + + /** + Convenience method to query the value of a child text node. This is probably best + shown by example. Given you have a document is this form: + @verbatim + + 1 + 1.4 + + @endverbatim + + The QueryIntText() and similar functions provide a safe and easier way to get to the + "value" of x and y. + + @verbatim + int x = 0; + float y = 0; // types of x and y are contrived for example + const XMLElement* xElement = pointElement->FirstChildElement( "x" ); + const XMLElement* yElement = pointElement->FirstChildElement( "y" ); + xElement->QueryIntText( &x ); + yElement->QueryFloatText( &y ); + @endverbatim + + @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted + to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + + */ + XMLError QueryIntText( int* ival ) const; + /// See QueryIntText() + XMLError QueryUnsignedText( unsigned* uval ) const; + /// See QueryIntText() + XMLError QueryBoolText( bool* bval ) const; + /// See QueryIntText() + XMLError QueryDoubleText( double* dval ) const; + /// See QueryIntText() + XMLError QueryFloatText( float* fval ) const; + + // internal: + enum { + OPEN, // + CLOSED, // + CLOSING // + }; + int ClosingType() const { + return _closingType; + } + char* ParseDeep( char* p, StrPair* endTag ); + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +private: + XMLElement( XMLDocument* doc ); + virtual ~XMLElement(); + XMLElement( const XMLElement& ); // not supported + void operator=( const XMLElement& ); // not supported + + XMLAttribute* FindAttribute( const char* name ); + XMLAttribute* FindOrCreateAttribute( const char* name ); + //void LinkAttribute( XMLAttribute* attrib ); + char* ParseAttributes( char* p ); + + int _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; +}; + + +enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE +}; + + +/** A Document binds together all the functionality. + It can be saved, loaded, and printed to the screen. + All Nodes are connected and allocated to a Document. + If the Document is deleted, all its Nodes are also deleted. +*/ +class CC_DLL XMLDocument : public XMLNode +{ + friend class XMLElement; +public: + /// constructor + XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + return this; + } + virtual const XMLDocument* ToDocument() const { + return this; + } + + /** + Parse an XML file from a character string. + Returns XML_NO_ERROR (0) on success, or + an errorID. + + You may optionally pass in the 'nBytes', which is + the number of bytes which will be parsed. If not + specified, TinyXML will assume 'xml' points to a + null terminated string. + */ + XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); + + /** + Load an XML file from disk. + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError LoadFile( const char* filename ); + + /** + Load an XML file from disk. You are responsible + for providing and closing the FILE*. + + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError LoadFile( FILE* ); + + /** + Save the XML file to disk. + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError SaveFile( const char* filename, bool compact = false ); + + /** + Save the XML file to disk. You are responsible + for providing and closing the FILE*. + + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError SaveFile( FILE* fp, bool compact = false ); + + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespace; + } + + /** + Returns true if this document has a leading Byte Order Mark of UTF8. + */ + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. + */ + void SetBOM( bool useBOM ) { + _writeBOM = useBOM; + } + + /** Return the root element of DOM. Equivalent to FirstChildElement(). + To get the first node, use FirstChild(). + */ + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } + + /** Print the Document. If the Printer is not provided, it will + print to stdout. If you provide Printer, this can print to a file: + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Or you can use a printer to print to memory: + @verbatim + XMLPrinter printer; + doc->Print( &printer ); + // printer.CStr() has a const char* to the XML + @endverbatim + */ + void Print( XMLPrinter* streamer=0 ); + virtual bool Accept( XMLVisitor* visitor ) const; + + /** + Create a new Element associated with + this Document. The memory for the Element + is managed by the Document. + */ + XMLElement* NewElement( const char* name ); + /** + Create a new Comment associated with + this Document. The memory for the Comment + is managed by the Document. + */ + XMLComment* NewComment( const char* comment ); + /** + Create a new Text associated with + this Document. The memory for the Text + is managed by the Document. + */ + XMLText* NewText( const char* text ); + /** + Create a new Declaration associated with + this Document. The memory for the object + is managed by the Document. + + If the 'text' param is null, the standard + declaration is used.: + @verbatim + + @endverbatim + */ + XMLDeclaration* NewDeclaration( const char* text=0 ); + /** + Create a new Unknown associated with + this Document. The memory forthe object + is managed by the Document. + */ + XMLUnknown* NewUnknown( const char* text ); + + /** + Delete a node associated with this document. + It will be unlinked from the DOM. + */ + void DeleteNode( XMLNode* node ) { + node->_parent->DeleteChild( node ); + } + + void SetError( XMLError error, const char* str1, const char* str2 ); + + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_NO_ERROR; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + /// Return a possibly helpful diagnostic location or string. + const char* GetErrorStr1() const { + return _errorStr1; + } + /// Return a possibly helpful secondary diagnostic location or string. + const char* GetErrorStr2() const { + return _errorStr2; + } + /// If there is an error, print it to stdout. + void PrintError() const; + + // internal + char* Identify( char* p, XMLNode** node ); + + virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { + return 0; + } + virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { + return false; + } + +private: + XMLDocument( const XMLDocument& ); // not supported + void operator=( const XMLDocument& ); // not supported + void InitDocument(); + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespace; + const char* _errorStr1; + const char* _errorStr2; + char* _charBuffer; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; +}; + + +/** + A XMLHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that XMLHandle is not part of the TinyXML + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + + + + + + + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + XMLElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + XMLElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + XMLElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + XMLElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. XMLHandle addresses the verbosity + of such code. A XMLHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + XMLHandle docHandle( &document ); + XMLElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild().NextSibling().ToElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + XMLHandle handleCopy = handle; + @endverbatim + + See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. +*/ +class CC_DLL XMLHandle +{ +public: + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + XMLHandle( XMLNode* node ) { + _node = node; + } + /// Create a handle from a node. + XMLHandle( XMLNode& node ) { + _node = &node; + } + /// Copy constructor + XMLHandle( const XMLHandle& ref ) { + _node = ref._node; + } + /// Assignment + XMLHandle& operator=( const XMLHandle& ref ) { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle( _node ? _node->FirstChild() : 0 ); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement( const char* value=0 ) { + return XMLHandle( _node ? _node->FirstChildElement( value ) : 0 ); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle( _node ? _node->LastChild() : 0 ); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement( const char* _value=0 ) { + return XMLHandle( _node ? _node->LastChildElement( _value ) : 0 ); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle( _node ? _node->PreviousSibling() : 0 ); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement( const char* _value=0 ) { + return XMLHandle( _node ? _node->PreviousSiblingElement( _value ) : 0 ); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle( _node ? _node->NextSibling() : 0 ); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement( const char* _value=0 ) { + return XMLHandle( _node ? _node->NextSiblingElement( _value ) : 0 ); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return ( ( _node && _node->ToElement() ) ? _node->ToElement() : 0 ); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return ( ( _node && _node->ToText() ) ? _node->ToText() : 0 ); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return ( ( _node && _node->ToUnknown() ) ? _node->ToUnknown() : 0 ); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return ( ( _node && _node->ToDeclaration() ) ? _node->ToDeclaration() : 0 ); + } + +private: + XMLNode* _node; +}; + + +/** + A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the + same in all regards, except for the 'const' qualifiers. See XMLHandle for API. +*/ +class CC_DLL XMLConstHandle +{ +public: + XMLConstHandle( const XMLNode* node ) { + _node = node; + } + XMLConstHandle( const XMLNode& node ) { + _node = &node; + } + XMLConstHandle( const XMLConstHandle& ref ) { + _node = ref._node; + } + + XMLConstHandle& operator=( const XMLConstHandle& ref ) { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const { + return XMLConstHandle( _node ? _node->FirstChild() : 0 ); + } + const XMLConstHandle FirstChildElement( const char* value=0 ) const { + return XMLConstHandle( _node ? _node->FirstChildElement( value ) : 0 ); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle( _node ? _node->LastChild() : 0 ); + } + const XMLConstHandle LastChildElement( const char* _value=0 ) const { + return XMLConstHandle( _node ? _node->LastChildElement( _value ) : 0 ); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); + } + const XMLConstHandle PreviousSiblingElement( const char* _value=0 ) const { + return XMLConstHandle( _node ? _node->PreviousSiblingElement( _value ) : 0 ); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle( _node ? _node->NextSibling() : 0 ); + } + const XMLConstHandle NextSiblingElement( const char* _value=0 ) const { + return XMLConstHandle( _node ? _node->NextSiblingElement( _value ) : 0 ); + } + + + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return ( ( _node && _node->ToElement() ) ? _node->ToElement() : 0 ); + } + const XMLText* ToText() const { + return ( ( _node && _node->ToText() ) ? _node->ToText() : 0 ); + } + const XMLUnknown* ToUnknown() const { + return ( ( _node && _node->ToUnknown() ) ? _node->ToUnknown() : 0 ); + } + const XMLDeclaration* ToDeclaration() const { + return ( ( _node && _node->ToDeclaration() ) ? _node->ToDeclaration() : 0 ); + } + +private: + const XMLNode* _node; +}; + + +/** + Printing functionality. The XMLPrinter gives you more + options than the XMLDocument::Print() method. + + It can: + -# Print to memory. + -# Print to a file you provide. + -# Print XML without a XMLDocument. + + Print to Memory + + @verbatim + XMLPrinter printer; + doc->Print( &printer ); + SomeFunction( printer.CStr() ); + @endverbatim + + Print to a File + + You provide the file pointer. + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Print without a XMLDocument + + When loading, an XML parser is very useful. However, sometimes + when saving, it just gets in the way. The code is often set up + for streaming, and constructing the DOM is just overhead. + + The Printer supports the streaming case. The following code + prints out a trivially simple XML file without ever creating + an XML document. + + @verbatim + XMLPrinter printer( fp ); + printer.OpenElement( "foo" ); + printer.PushAttribute( "foo", "bar" ); + printer.CloseElement(); + @endverbatim +*/ +class CC_DLL XMLPrinter : public XMLVisitor +{ +public: + /** Construct the printer. If the FILE* is specified, + this will print to the FILE. Else it will print + to memory, and the result is available in CStr(). + If 'compact' is set to true, then output is created + with only required whitespace and newlines. + */ + XMLPrinter( FILE* file=0, bool compact = false ); + ~XMLPrinter() {} + + /** If streaming, write the BOM and declaration. */ + void PushHeader( bool writeBOM, bool writeDeclaration ); + /** If streaming, start writing an element. + The element must be closed with CloseElement() + */ + void OpenElement( const char* name ); + /// If streaming, add an attribute to an open element. + void PushAttribute( const char* name, const char* value ); + void PushAttribute( const char* name, int value ); + void PushAttribute( const char* name, unsigned value ); + void PushAttribute( const char* name, bool value ); + void PushAttribute( const char* name, double value ); + /// If streaming, close the Element. + void CloseElement(); + + /// Add a text node. + void PushText( const char* text, bool cdata=false ); + /// Add a text node from an integer. + void PushText( int value ); + /// Add a text node from an unsigned. + void PushText( unsigned value ); + /// Add a text node from a bool. + void PushText( bool value ); + /// Add a text node from a float. + void PushText( float value ); + /// Add a text node from a double. + void PushText( double value ); + + /// Add a comment + void PushComment( const char* comment ); + + void PushDeclaration( const char* value ); + void PushUnknown( const char* value ); + + virtual bool VisitEnter( const XMLDocument& /*doc*/ ); + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); + virtual bool VisitExit( const XMLElement& element ); + + virtual bool Visit( const XMLText& text ); + virtual bool Visit( const XMLComment& comment ); + virtual bool Visit( const XMLDeclaration& declaration ); + virtual bool Visit( const XMLUnknown& unknown ); + + /** + If in print to memory mode, return a pointer to + the XML file in memory. + */ + const char* CStr() const { + return _buffer.Mem(); + } + /** + If in print to memory mode, return the size + of the XML file in memory. (Note the size returned + includes the terminating null.) + */ + int CStrSize() const { + return _buffer.Size(); + } + +private: + void SealElement(); + void PrintSpace( int depth ); + void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. + void Print( const char* format, ... ); + + bool _elementJustOpened; + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< const char*, 10 > _stack; + DynArray< char, 20 > _buffer; +#ifdef _MSC_VER + DynArray< char, 20 > _accumulator; +#endif +}; + + +} // tinyxml2 + + +#endif // TINYXML2_INCLUDED diff --git a/external/unzip/ioapi.cpp b/external/unzip/ioapi.cpp new file mode 100644 index 0000000000..669ea36927 --- /dev/null +++ b/external/unzip/ioapi.cpp @@ -0,0 +1,245 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#include "ioapi.h" + +namespace cocos2d { + +voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) +{ + if (pfilefunc->zfile_func64.zopen64_file != NULL) + return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); + else + { + return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); + } +} + +long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); + else + { + uLong offsetTruncated = (uLong)offset; + if (offsetTruncated != offset) + return -1; + else + return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); + } +} + +ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); + else + { + uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); + if ((tell_uLong) == ((uLong)-1)) + return (ZPOS64_T)-1; + else + return tell_uLong; + } +} + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) +{ + p_filefunc64_32->zfile_func64.zopen64_file = NULL; + p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; + p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; + p_filefunc64_32->zfile_func64.ztell64_file = NULL; + p_filefunc64_32->zfile_func64.zseek64_file = NULL; + p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; + p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; + p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; +} + + + +static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); +static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); +static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); +static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); +static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); + +static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + file = fopen(filename, mode_fopen); + return file; +} + +static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) + file = NULL; +#else + file = fopen64((const char*)filename, mode_fopen); +#endif + } + + return file; +} + + +static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) +{ + long ret; + ret = ftell((FILE *)stream); + return ret; +} + + +static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) +{ + ZPOS64_T ret; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) + ret = 0; +#else + ret = ftello64((FILE *)stream); +#endif + return ret; +} + +static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) +{ + int fseek_origin=0; + long ret; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + ret = 0; + if (fseek((FILE *)stream, offset, fseek_origin) != 0) + ret = -1; + return ret; +} + +static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) +{ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) + return -1; +#else + int fseek_origin=0; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + if(fseeko64((FILE *)stream, offset, fseek_origin) != 0) + return -1; + return 0; +#endif +} + + +static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = fclose((FILE *)stream); + return ret; +} + +static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = ferror((FILE *)stream); + return ret; +} + +void fill_fopen_filefunc (zlib_filefunc_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen_file = fopen_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell_file = ftell_file_func; + pzlib_filefunc_def->zseek_file = fseek_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = fopen64_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell64_file = ftell64_file_func; + pzlib_filefunc_def->zseek64_file = fseek64_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +} // end of namespace cocos2d diff --git a/external/unzip/ioapi.h b/external/unzip/ioapi.h new file mode 100644 index 0000000000..575f44ece4 --- /dev/null +++ b/external/unzip/ioapi.h @@ -0,0 +1,201 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + Changes + + Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) + Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. + More if/def section may be needed to support other platforms + Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. + (but you should use iowin32.c for windows instead) + +*/ + +#ifndef _ZLIBIOAPI64_H +#define _ZLIBIOAPI64_H + +#include "platform/CCPlatformConfig.h" + +#if (!defined(_WIN32)) && (!defined(WIN32)) + + // Linux needs this to support file operation on files larger then 4+GB + // But might need better if/def to select just the platforms that needs them. + + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif +#endif + +#include +#include +#include "zlib.h" + +namespace cocos2d { + +#ifndef OF +#define OF _Z_OF +#endif + +#if defined(USE_FILE32API) +#define fopen64 fopen +#define ftello64 ftell +#define fseeko64 fseek +#else +#ifdef _MSC_VER + #define fopen64 fopen + #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) + #define ftello64 _ftelli64 + #define fseeko64 _fseeki64 + #else // old MSC + #define ftello64 ftell + #define fseeko64 fseek + #endif +#endif +#endif + +/* +#ifndef ZPOS64_T + #ifdef _WIN32 + #define ZPOS64_T fpos_t + #else + #include + #define ZPOS64_T uint64_t + #endif +#endif +*/ + +#ifdef HAVE_MINIZIP64_CONF_H +#include "mz64conf.h" +#endif + +/* a type chosen by DEFINE */ +#ifdef HAVE_64BIT_INT_CUSTOM +typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; +#else +#ifdef HAS_STDINT_H +#include "stdint.h" +typedef uint64_t ZPOS64_T; +#else + + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef unsigned __int64 ZPOS64_T; +#else +typedef unsigned long long int ZPOS64_T; +#endif +#endif +#endif + + + +#define ZLIB_FILEFUNC_SEEK_CUR (1) +#define ZLIB_FILEFUNC_SEEK_END (2) +#define ZLIB_FILEFUNC_SEEK_SET (0) + +#define ZLIB_FILEFUNC_MODE_READ (1) +#define ZLIB_FILEFUNC_MODE_WRITE (2) +#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) + +#define ZLIB_FILEFUNC_MODE_EXISTING (4) +#define ZLIB_FILEFUNC_MODE_CREATE (8) + + +#ifndef ZCALLBACK + #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) + #define ZCALLBACK CALLBACK + #else + #define ZCALLBACK + #endif +#endif + + + + +typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); +typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); + +typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); + + +/* here is the "old" 32 bits structure structure */ +typedef struct zlib_filefunc_def_s +{ + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc_def; + +typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode)); + +typedef struct zlib_filefunc64_def_s +{ + open64_file_func zopen64_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell64_file_func ztell64_file; + seek64_file_func zseek64_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc64_def; + +void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); + +/* now internal definition, only for zip.c and unzip.h */ +typedef struct zlib_filefunc64_32_def_s +{ + zlib_filefunc64_def zfile_func64; + open_file_func zopen32_file; + tell_file_func ztell32_file; + seek_file_func zseek32_file; +} zlib_filefunc64_32_def; + + +#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) +//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) +#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) +#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) + +voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)); +long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); +ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); + +#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) +#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) +#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) + +} // end of namespace cocos2d + +#endif diff --git a/external/unzip/unzip.cpp b/external/unzip/unzip.cpp new file mode 100644 index 0000000000..66cfeff16a --- /dev/null +++ b/external/unzip/unzip.cpp @@ -0,0 +1,2161 @@ +/* unzip.c -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + + ------------------------------------------------------------------------------------ + Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of + compatibility with older software. The following is from the original crypt.c. + Code woven in by Terry Thorsen 1/2003. + + Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + + See the accompanying file LICENSE, version 2000-Apr-09 or later + (the contents of which are also included in zip.h) for terms of use. + If, for some reason, all these files are missing, the Info-ZIP license + also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html + + crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + ------------------------------------------------------------------------------------ + + Changes in unzip.c + + 2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos + 2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz* + 2007-2008 - Even Rouault - Remove old C style function prototypes + 2007-2008 - Even Rouault - Add unzip support for ZIP64 + + Copyright (C) 2007-2008 Even Rouault + + + Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again). + Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G + should only read the compressed/uncompressed size from the Zip64 format if + the size from normal header was 0xFFFFFFFF + Oct-2009 - Mathias Svensson - Applied some bug fixes from patches received from Gilles Vollant + Oct-2009 - Mathias Svensson - Applied support to unzip files with compression method BZIP2 (bzip2 lib is required) + Patch created by Daniel Borca + + Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer + + Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson + +*/ + + +#include +#include +#include + +#ifndef NOUNCRYPT + #define NOUNCRYPT +#endif + +#include "zlib.h" +#include "unzip.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + +namespace cocos2d { + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + + +#ifndef CASESENSITIVITYDEFAULT_NO +# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) +# define CASESENSITIVITYDEFAULT_NO +# endif +#endif + + +#ifndef UNZ_BUFSIZE +#define UNZ_BUFSIZE (16384) +#endif + +#ifndef UNZ_MAXFILENAMEINZIP +#define UNZ_MAXFILENAMEINZIP (256) +#endif + +#ifndef ALLOC +# define ALLOC(size) (malloc(size)) +#endif +#ifndef TRYFREE +# define TRYFREE(p) {if (p) free(p);} +#endif + +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) + + +const char unz_copyright[] = + " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + +/* unz_file_info_interntal contain internal info about a file in zipfile*/ +typedef struct unz_file_info64_internal_s +{ + ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */ +} unz_file_info64_internal; + + +/* file_in_zip_read_info_s contain internal information about a file in zipfile, + when reading and decompress it */ +typedef struct +{ + char *read_buffer; /* internal buffer for compressed data */ + z_stream stream; /* zLib stream structure for inflate */ + +#ifdef HAVE_BZIP2 + bz_stream bstream; /* bzLib stream structure for bziped */ +#endif + + ZPOS64_T pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ + uLong stream_initialised; /* flag set if stream structure is initialized*/ + + ZPOS64_T offset_local_extrafield;/* offset of the local extra field */ + uInt size_local_extrafield;/* size of the local extra field */ + ZPOS64_T pos_local_extrafield; /* position in the local extra field in read*/ + ZPOS64_T total_out_64; + + uLong crc32; /* crc32 of all data uncompressed */ + uLong crc32_wait; /* crc32 we must obtain after decompress all */ + ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */ + ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/ + zlib_filefunc64_32_def z_filefunc; + voidpf filestream; /* io structure of the zipfile */ + uLong compression_method; /* compression method (0==store) */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + int raw; +} file_in_zip64_read_info_s; + + +/* unz64_s contain internal information about the zipfile +*/ +typedef struct +{ + zlib_filefunc64_32_def z_filefunc; + int is64bitOpenFunction; + voidpf filestream; /* io structure of the zipfile */ + unz_global_info64 gi; /* public global information */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + ZPOS64_T num_file; /* number of the current file in the zipfile*/ + ZPOS64_T pos_in_central_dir; /* pos of the current file in the central dir*/ + ZPOS64_T current_file_ok; /* flag about the usability of the current file*/ + ZPOS64_T central_pos; /* position of the beginning of the central dir*/ + + ZPOS64_T size_central_dir; /* size of the central directory */ + ZPOS64_T offset_central_dir; /* offset of start of central directory with + respect to the starting disk number */ + + unz_file_info64 cur_file_info; /* public info about the current file in zip*/ + unz_file_info64_internal cur_file_info_internal; /* private info about it*/ + file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current + file if we are decompressing it */ + int encrypted; + + int isZip64; + +# ifndef NOUNCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const unsigned long* pcrc_32_tab; +# endif +} unz64_s; + + +#ifndef NOUNCRYPT +#include "crypt.h" +#endif + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been successfully opened for reading. +*/ + + +local int unz64local_getByte OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + int *pi)); + +local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi) +{ + unsigned char c; + int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); + if (err==1) + { + *pi = (int)c; + return UNZ_OK; + } + else + { + if (ZERROR64(*pzlib_filefunc_def,filestream)) + return UNZ_ERRNO; + else + return UNZ_EOF; + } +} + + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets +*/ +local int unz64local_getShort OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<24; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX)); + + +local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX) +{ + ZPOS64_T x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (ZPOS64_T)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<24; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<32; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<40; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<48; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<56; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +/* My own strcmpi / strcasecmp */ +local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2) +{ + for (;;) + { + char c1=*(fileName1++); + char c2=*(fileName2++); + if ((c1>='a') && (c1<='z')) + c1 -= 0x20; + if ((c2>='a') && (c2<='z')) + c2 -= 0x20; + if (c1=='\0') + return ((c2=='\0') ? 0 : -1); + if (c2=='\0') + return 1; + if (c1c2) + return 1; + } +} + + +#ifdef CASESENSITIVITYDEFAULT_NO +#define CASESENSITIVITYDEFAULTVALUE 2 +#else +#define CASESENSITIVITYDEFAULTVALUE 1 +#endif + +#ifndef STRCMPCASENOSENTIVEFUNCTION +#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal +#endif + +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparison is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparison is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is default of your operating system + (like 1 on Unix, 2 on Windows) + +*/ +int ZEXPORT unzStringFileNameCompare (const char* fileName1, + const char* fileName2, + int iCaseSensitivity) + +{ + if (iCaseSensitivity==0) + iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; + + if (iCaseSensitivity==1) + return strcmp(fileName1,fileName2); + + return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); +} + +#ifndef BUFREADCOMMENT +#define BUFREADCOMMENT (0x400) +#endif + +/* + Locate the Central directory of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); +local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + return uPosFound; +} + + +/* + Locate the Central directory 64 of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream)); + +local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + uLong uL; + ZPOS64_T relativeOffset; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + if (uPosFound == 0) + return 0; + + /* Zip64 end of central directory locator */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature, already checked */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + /* number of the disk with the start of the zip64 end of central directory */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 0) + return 0; + + /* relative offset of the zip64 end of central directory record */ + if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK) + return 0; + + /* total number of disks */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 1) + return 0; + + /* Goto end of central directory record */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + if (uL != 0x06064b50) + return 0; + + return relativeOffset; +} + +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer + "zlib/zlib114.zip". + If the zipfile cannot be opened (file doesn't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. +*/ +local unzFile unzOpenInternal (const void *path, + zlib_filefunc64_32_def* pzlib_filefunc64_32_def, + int is64bitOpenFunction) +{ + unz64_s us; + unz64_s *s; + ZPOS64_T central_pos; + uLong uL; + + uLong number_disk; /* number of the current dist, used for + spanning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spanning ZIP, unsupported, always 0*/ + ZPOS64_T number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ + + int err=UNZ_OK; + + if (unz_copyright[0]!=' ') + return NULL; + + us.z_filefunc.zseek32_file = NULL; + us.z_filefunc.ztell32_file = NULL; + if (pzlib_filefunc64_32_def==NULL) + fill_fopen64_filefunc(&us.z_filefunc.zfile_func64); + else + us.z_filefunc = *pzlib_filefunc64_32_def; + us.is64bitOpenFunction = is64bitOpenFunction; + + + + us.filestream = ZOPEN64(us.z_filefunc, + path, + ZLIB_FILEFUNC_MODE_READ | + ZLIB_FILEFUNC_MODE_EXISTING); + if (us.filestream==NULL) + return NULL; + + central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream); + if (central_pos) + { + uLong uS; + ZPOS64_T uL64; + + us.isZip64 = 1; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* size of zip64 end of central directory record */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version made by */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version needed to extract */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory on this disk */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + us.gi.size_comment = 0; + } + else + { + central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream); + if (central_pos==0) + err=UNZ_ERRNO; + + us.isZip64 = 0; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central dir on this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.gi.number_entry = uL; + + /* total number of entries in the central dir */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + number_entry_CD = uL; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.size_central_dir = uL; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.offset_central_dir = uL; + + /* zipfile comment length */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) + err=UNZ_ERRNO; + } + + if ((central_pospfile_in_zip_read!=NULL) + unzCloseCurrentFile(file); + + ZCLOSE64(s->z_filefunc, s->filestream); + TRYFREE(s); + return UNZ_OK; +} + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ +int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + *pglobal_info=s->gi; + return UNZ_OK; +} + +int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + /* to do : check if number_entry is not truncated */ + pglobal_info32->number_entry = (uLong)s->gi.number_entry; + pglobal_info32->size_comment = s->gi.size_comment; + return UNZ_OK; +} +/* + Translate date/time from Dos format to tm_unz (readable more easily) +*/ +local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm) +{ + ZPOS64_T uDate; + uDate = (ZPOS64_T)(ulDosDate>>16); + ptm->tm_mday = (uInt)(uDate&0x1f) ; + ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; + ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; + + ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; + ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; +} + +/* + Get Info about the current file in the zipfile, with internal only info +*/ +local int unz64local_GetCurrentFileInfoInternal OF((unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +local int unz64local_GetCurrentFileInfoInternal (unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize) +{ + unz64_s* s; + unz_file_info64 file_info; + unz_file_info64_internal file_info_internal; + int err=UNZ_OK; + uLong uMagic; + long lSeek=0; + uLong uL; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pos_in_central_dir+s->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + + /* we check the magic */ + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x02014b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) + err=UNZ_ERRNO; + + unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.compressed_size = uL; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.uncompressed_size = uL; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) + err=UNZ_ERRNO; + + // relative offset of local header + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info_internal.offset_curfile = uL; + + lSeek+=file_info.size_filename; + if ((err==UNZ_OK) && (szFileName!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_filename0) && (fileNameBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + lSeek -= uSizeRead; + } + + // Read extrafield + if ((err==UNZ_OK) && (extraField!=NULL)) + { + ZPOS64_T uSizeRead ; + if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + + lSeek += file_info.size_file_extra - (uLong)uSizeRead; + } + else + lSeek += file_info.size_file_extra; + + + if ((err==UNZ_OK) && (file_info.size_file_extra != 0)) + { + uLong acc = 0; + + // since lSeek now points to after the extra field we need to move back + lSeek -= file_info.size_file_extra; + + if (lSeek!=0) + { + if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + while(acc < file_info.size_file_extra) + { + uLong headerId; + uLong dataSize; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK) + err=UNZ_ERRNO; + + /* ZIP64 extra fields */ + if (headerId == 0x0001) + { + uLong uL; + + if(file_info.uncompressed_size == (ZPOS64_T)(unsigned long)-1) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.compressed_size == (ZPOS64_T)(unsigned long)-1) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info_internal.offset_curfile == (ZPOS64_T)(unsigned long)-1) + { + /* Relative Header offset */ + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.disk_num_start == (unsigned long)-1) + { + /* Disk Start Number */ + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + } + + } + else + { + if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) + err=UNZ_ERRNO; + } + + acc += 2 + 2 + dataSize; + } + } + + if ((err==UNZ_OK) && (szComment!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) { + //lSeek=0; + } + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_comment>0) && (commentBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + //lSeek+=file_info.size_file_comment - uSizeRead; + } + //else + // lSeek+=file_info.size_file_comment; + + + if ((err==UNZ_OK) && (pfile_info!=NULL)) + *pfile_info=file_info; + + if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) + *pfile_info_internal=file_info_internal; + + return err; +} + + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. +*/ +int ZEXPORT unzGetCurrentFileInfo64 (unzFile file, + unz_file_info64 * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); +} + +int ZEXPORT unzGetCurrentFileInfo (unzFile file, + unz_file_info * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + int err; + unz_file_info64 file_info64; + err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); + if (err==UNZ_OK) + { + pfile_info->version = file_info64.version; + pfile_info->version_needed = file_info64.version_needed; + pfile_info->flag = file_info64.flag; + pfile_info->compression_method = file_info64.compression_method; + pfile_info->dosDate = file_info64.dosDate; + pfile_info->crc = file_info64.crc; + + pfile_info->size_filename = file_info64.size_filename; + pfile_info->size_file_extra = file_info64.size_file_extra; + pfile_info->size_file_comment = file_info64.size_file_comment; + + pfile_info->disk_num_start = file_info64.disk_num_start; + pfile_info->internal_fa = file_info64.internal_fa; + pfile_info->external_fa = file_info64.external_fa; + + pfile_info->tmu_date = file_info64.tmu_date, + + + pfile_info->compressed_size = (uLong)file_info64.compressed_size; + pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; + + } + return err; +} + +/* + Set the current file of the zipfile to the first file + with retrieving an information about the file. + return UNZ_OK if there is no problem +*/ +int ZEXPORT unzGoToFirstFile64 (unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize) +{ + int err=UNZ_OK; + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + s->pos_in_central_dir=s->offset_central_dir; + s->num_file=0; + err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + szFileName,fileNameBufferSize,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + if (pfile_info) + *pfile_info = s->cur_file_info; + return err; +} + +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ +int ZEXPORT unzGoToFirstFile (unzFile file) +{ + return unzGoToFirstFile64(file, NULL, NULL, 0); +} + +/* + Set the current file of the zipfile to the next file + with retrieving an information about the file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ +int ZEXPORT unzGoToNextFile64 (unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ + if (s->num_file+1==s->gi.number_entry) + return UNZ_END_OF_LIST_OF_FILE; + + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; + s->num_file++; + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + szFileName,fileNameBufferSize,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + if (pfile_info) + *pfile_info = s->cur_file_info; + return err; +} + +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ +int ZEXPORT unzGoToNextFile (unzFile file) +{ + return unzGoToNextFile64(file, NULL, NULL, 0); +} + + +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzipStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ +int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) +{ + unz64_s* s; + int err; + + /* We remember the 'current' position in the file so that we can jump + * back there if we fail. + */ + unz_file_info64 cur_file_infoSaved; + unz_file_info64_internal cur_file_info_internalSaved; + ZPOS64_T num_fileSaved; + ZPOS64_T pos_in_central_dirSaved; + + + if (file==NULL) + return UNZ_PARAMERROR; + + if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) + return UNZ_PARAMERROR; + + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + /* Save the current state */ + num_fileSaved = s->num_file; + pos_in_central_dirSaved = s->pos_in_central_dir; + cur_file_infoSaved = s->cur_file_info; + cur_file_info_internalSaved = s->cur_file_info_internal; + + err = unzGoToFirstFile(file); + + while (err == UNZ_OK) + { + char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; + err = unzGetCurrentFileInfo64(file,NULL, + szCurrentFileName,sizeof(szCurrentFileName)-1, + NULL,0,NULL,0); + if (err == UNZ_OK) + { + if (unzStringFileNameCompare(szCurrentFileName, + szFileName,iCaseSensitivity)==0) + return UNZ_OK; + err = unzGoToNextFile(file); + } + } + + /* We failed, so restore the state of the 'current file' to where we + * were. + */ + s->num_file = num_fileSaved ; + s->pos_in_central_dir = pos_in_central_dirSaved ; + s->cur_file_info = cur_file_infoSaved; + s->cur_file_info_internal = cur_file_info_internalSaved; + return err; +} + + +/* +/////////////////////////////////////////// +// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) +// I need random access +// +// Further optimization could be realized by adding an ability +// to cache the directory in memory. The goal being a single +// comprehensive file read to put the file I need in a memory. +*/ + +/* +typedef struct unz_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; // offset in file + ZPOS64_T num_of_file; // # of file +} unz_file_pos; +*/ + +int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos* file_pos) +{ + unz64_s* s; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + file_pos->pos_in_zip_directory = s->pos_in_central_dir; + file_pos->num_of_file = s->num_file; + + return UNZ_OK; +} + +int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + int err = unzGetFilePos64(file,&file_pos64); + if (err==UNZ_OK) + { + file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory; + file_pos->num_of_file = (uLong)file_pos64.num_of_file; + } + return err; +} + +int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos) +{ + unz64_s* s; + int err; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + /* jump to the right spot */ + s->pos_in_central_dir = file_pos->pos_in_zip_directory; + s->num_file = file_pos->num_of_file; + + /* set the current file */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + /* return results */ + s->current_file_ok = (err == UNZ_OK); + return err; +} + +int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + if (file_pos == NULL) + return UNZ_PARAMERROR; + + file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; + file_pos64.num_of_file = file_pos->num_of_file; + return unzGoToFilePos64(file,&file_pos64); +} + +/* +// Unzip Helper Functions - should be here? +/////////////////////////////////////////// +*/ + +/* + Read the local header of the current zipfile + Check the coherency of the local header and info in the end of central + directory about this file + store in *piSizeVar the size of extra info in local header + (filename and size of extra field data) +*/ +local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar, + ZPOS64_T * poffset_local_extrafield, + uInt * psize_local_extrafield) +{ + uLong uMagic,uData,uFlags; + uLong size_filename; + uLong size_extra_field; + int err=UNZ_OK; + + *piSizeVar = 0; + *poffset_local_extrafield = 0; + *psize_local_extrafield = 0; + + if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + + s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x04034b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; +/* + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) + err=UNZ_BADZIPFILE; +*/ + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) + err=UNZ_BADZIPFILE; + + if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) + err=UNZ_BADZIPFILE; + + *piSizeVar += (uInt)size_filename; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) + err=UNZ_ERRNO; + *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt)size_extra_field; + + *piSizeVar += (uInt)size_extra_field; + + return err; +} + +/* + Open for reading data the current file in the zipfile. + If there is no error and the file is opened, the return value is UNZ_OK. +*/ +int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, + int* level, int raw, const char* password) +{ + int err=UNZ_OK; + uInt iSizeVar; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + ZPOS64_T offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ +# ifndef NOUNCRYPT + char source[12]; +# else + if (password != NULL) + return UNZ_PARAMERROR; +# endif + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_PARAMERROR; + + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); + + if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) + return UNZ_BADZIPFILE; + + pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s)); + if (pfile_in_zip_read_info==NULL) + return UNZ_INTERNALERROR; + + pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); + pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; + pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; + pfile_in_zip_read_info->pos_local_extrafield=0; + pfile_in_zip_read_info->raw=raw; + + if (pfile_in_zip_read_info->read_buffer==NULL) + { + TRYFREE(pfile_in_zip_read_info); + return UNZ_INTERNALERROR; + } + + pfile_in_zip_read_info->stream_initialised=0; + + if (method!=NULL) + *method = (int)s->cur_file_info.compression_method; + + if (level!=NULL) + { + *level = 6; + switch (s->cur_file_info.flag & 0x06) + { + case 6 : *level = 1; break; + case 4 : *level = 2; break; + case 2 : *level = 9; break; + } + } + + if ((s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) { + + //err=UNZ_BADZIPFILE; + } + pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; + pfile_in_zip_read_info->crc32=0; + pfile_in_zip_read_info->total_out_64=0; + pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; + pfile_in_zip_read_info->filestream=s->filestream; + pfile_in_zip_read_info->z_filefunc=s->z_filefunc; + pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; + + pfile_in_zip_read_info->stream.total_out = 0; + + if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) + { +#ifdef HAVE_BZIP2 + pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; + pfile_in_zip_read_info->bstream.bzfree = (free_func)0; + pfile_in_zip_read_info->bstream.opaque = (voidpf)0; + pfile_in_zip_read_info->bstream.state = (voidpf)0; + + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = (voidpf)0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } +#else + pfile_in_zip_read_info->raw=1; +#endif + } + else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) + { + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = 0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. + * In unzip, i don't wait absolutely Z_STREAM_END because I known the + * size of both compressed and uncompressed data + */ + } + pfile_in_zip_read_info->rest_read_compressed = + s->cur_file_info.compressed_size ; + pfile_in_zip_read_info->rest_read_uncompressed = + s->cur_file_info.uncompressed_size ; + + + pfile_in_zip_read_info->pos_in_zipfile = + s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + + iSizeVar; + + pfile_in_zip_read_info->stream.avail_in = (uInt)0; + + s->pfile_in_zip_read = pfile_in_zip_read_info; + s->encrypted = 0; + +# ifndef NOUNCRYPT + if (password != NULL) + { + int i; + s->pcrc_32_tab = get_crc_table(); + init_keys(password,s->keys,s->pcrc_32_tab); + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pfile_in_zip_read->pos_in_zipfile + + s->pfile_in_zip_read->byte_before_the_zipfile, + SEEK_SET)!=0) + return UNZ_INTERNALERROR; + if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12) + return UNZ_INTERNALERROR; + + for (i = 0; i<12; i++) + zdecode(s->keys,s->pcrc_32_tab,source[i]); + + s->pfile_in_zip_read->pos_in_zipfile+=12; + s->encrypted=1; + } +# endif + + + return UNZ_OK; +} + +int ZEXPORT unzOpenCurrentFile (unzFile file) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); +} + +int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char* password) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, password); +} + +int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw) +{ + return unzOpenCurrentFile3(file, method, level, raw, NULL); +} + +/** Addition for GDAL : START */ + +ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + s=(unz64_s*)file; + if (file==NULL) + return 0; //UNZ_PARAMERROR; + pfile_in_zip_read_info=s->pfile_in_zip_read; + if (pfile_in_zip_read_info==NULL) + return 0; //UNZ_PARAMERROR; + return pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile; +} + +/** Addition for GDAL : END */ + +/* + Read bytes from the current file. + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if some bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ +int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) +{ + int err=UNZ_OK; + uInt iRead = 0; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if (pfile_in_zip_read_info->read_buffer == NULL) + return UNZ_END_OF_LIST_OF_FILE; + if (len==0) + return 0; + + pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + + if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && + (!(pfile_in_zip_read_info->raw))) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_uncompressed; + + if ((len>pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in; + + while (pfile_in_zip_read_info->stream.avail_out>0) + { + if ((pfile_in_zip_read_info->stream.avail_in==0) && + (pfile_in_zip_read_info->rest_read_compressed>0)) + { + uInt uReadThis = UNZ_BUFSIZE; + if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; + if (uReadThis == 0) + return UNZ_EOF; + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->read_buffer, + uReadThis)!=uReadThis) + return UNZ_ERRNO; + + +# ifndef NOUNCRYPT + if(s->encrypted) + { + uInt i; + for(i=0;iread_buffer[i] = + zdecode(s->keys,s->pcrc_32_tab, + pfile_in_zip_read_info->read_buffer[i]); + } +# endif + + + pfile_in_zip_read_info->pos_in_zipfile += uReadThis; + + pfile_in_zip_read_info->rest_read_compressed-=uReadThis; + + pfile_in_zip_read_info->stream.next_in = + (Bytef*)pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; + } + + if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) + { + uInt uDoCopy,i ; + + if ((pfile_in_zip_read_info->stream.avail_in == 0) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + return (iRead==0) ? UNZ_EOF : iRead; + + if (pfile_in_zip_read_info->stream.avail_out < + pfile_in_zip_read_info->stream.avail_in) + uDoCopy = pfile_in_zip_read_info->stream.avail_out ; + else + uDoCopy = pfile_in_zip_read_info->stream.avail_in ; + + for (i=0;istream.next_out+i) = + *(pfile_in_zip_read_info->stream.next_in+i); + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, + pfile_in_zip_read_info->stream.next_out, + uDoCopy); + pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; + pfile_in_zip_read_info->stream.avail_in -= uDoCopy; + pfile_in_zip_read_info->stream.avail_out -= uDoCopy; + pfile_in_zip_read_info->stream.next_out += uDoCopy; + pfile_in_zip_read_info->stream.next_in += uDoCopy; + pfile_in_zip_read_info->stream.total_out += uDoCopy; + iRead += uDoCopy; + } + else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) + { +#ifdef HAVE_BZIP2 + uLong uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + uLong uOutThis; + + pfile_in_zip_read_info->bstream.next_in = (char*)pfile_in_zip_read_info->stream.next_in; + pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; + pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; + pfile_in_zip_read_info->bstream.total_in_hi32 = 0; + pfile_in_zip_read_info->bstream.next_out = (char*)pfile_in_zip_read_info->stream.next_out; + pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; + pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; + pfile_in_zip_read_info->bstream.total_out_hi32 = 0; + + uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; + bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out; + + err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); + + uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); + pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->bstream.next_in; + pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; + pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; + pfile_in_zip_read_info->stream.next_out = (Bytef*)pfile_in_zip_read_info->bstream.next_out; + pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; + pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; + + if (err==BZ_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=BZ_OK) + break; +#endif + } // end Z_BZIP2ED + else + { + ZPOS64_T uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + ZPOS64_T uOutThis; + int flush=Z_SYNC_FLUSH; + + uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; + bufBefore = pfile_in_zip_read_info->stream.next_out; + + /* + if ((pfile_in_zip_read_info->rest_read_uncompressed == + pfile_in_zip_read_info->stream.avail_out) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + flush = Z_FINISH; + */ + err=inflate(&pfile_in_zip_read_info->stream,flush); + + if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) + err = Z_DATA_ERROR; + + uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = + crc32(pfile_in_zip_read_info->crc32,bufBefore, + (uInt)(uOutThis)); + + pfile_in_zip_read_info->rest_read_uncompressed -= + uOutThis; + + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + if (err==Z_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=Z_OK) + break; + } + } + + if (err==Z_OK) + return iRead; + return err; +} + + +/* + Give the current position in uncompressed data +*/ +z_off_t ZEXPORT unztell (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + return (z_off_t)pfile_in_zip_read_info->stream.total_out; +} + +ZPOS64_T ZEXPORT unztell64 (unzFile file) +{ + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return (ZPOS64_T)-1; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return (ZPOS64_T)-1; + + return pfile_in_zip_read_info->total_out_64; +} + + +/* + return 1 if the end of file was reached, 0 elsewhere +*/ +int ZEXPORT unzeof (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + return 1; + else + return 0; +} + + + +/* +Read extra field from the current file (opened by unzOpenCurrentFile) +This is the local-header version of the extra field (sometimes, there is +more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field that can be read + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ +int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + uInt read_now; + ZPOS64_T size_to_read; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - + pfile_in_zip_read_info->pos_local_extrafield); + + if (buf==NULL) + return (int)size_to_read; + + if (len>size_to_read) + read_now = (uInt)size_to_read; + else + read_now = (uInt)len ; + + if (read_now==0) + return 0; + + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->offset_local_extrafield + + pfile_in_zip_read_info->pos_local_extrafield, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + buf,read_now)!=read_now) + return UNZ_ERRNO; + + return (int)read_now; +} + +/* + Close the file in zip opened with unzipOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ +int ZEXPORT unzCloseCurrentFile (unzFile file) +{ + int err=UNZ_OK; + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && + (!pfile_in_zip_read_info->raw)) + { + if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) + err=UNZ_CRCERROR; + } + + + TRYFREE(pfile_in_zip_read_info->read_buffer); + pfile_in_zip_read_info->read_buffer = NULL; + if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) + inflateEnd(&pfile_in_zip_read_info->stream); +#ifdef HAVE_BZIP2 + else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) + BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); +#endif + + + pfile_in_zip_read_info->stream_initialised = 0; + TRYFREE(pfile_in_zip_read_info); + + s->pfile_in_zip_read=NULL; + + return err; +} + + +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ +int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf) +{ + unz64_s* s; + uLong uReadThis ; + if (file==NULL) + return (int)UNZ_PARAMERROR; + s=(unz64_s*)file; + + uReadThis = uSizeBuf; + if (uReadThis>s->gi.size_comment) + uReadThis = s->gi.size_comment; + + if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (uReadThis>0) + { + *szComment='\0'; + if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) + return UNZ_ERRNO; + } + + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) + *(szComment+s->gi.size_comment)='\0'; + return (int)uReadThis; +} + +/* Additions by RX '2004 */ +ZPOS64_T ZEXPORT unzGetOffset64(unzFile file) +{ + unz64_s* s; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return 0; + if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) + if (s->num_file==s->gi.number_entry) + return 0; + return s->pos_in_central_dir; +} + +uLong ZEXPORT unzGetOffset (unzFile file) +{ + ZPOS64_T offset64; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + offset64 = unzGetOffset64(file); + return (uLong)offset64; +} + +int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + s->pos_in_central_dir = pos; + s->num_file = s->gi.number_entry; /* hack */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + +int ZEXPORT unzSetOffset (unzFile file, uLong pos) +{ + return unzSetOffset64(file,pos); +} + +} // end of namespace cocos2d diff --git a/external/unzip/unzip.h b/external/unzip/unzip.h new file mode 100644 index 0000000000..54e73a55ea --- /dev/null +++ b/external/unzip/unzip.h @@ -0,0 +1,455 @@ +/* unzip.h -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------------- + + Changes + + See header of unzip64.c + +*/ + +#ifndef _unz64_H +#define _unz64_H + +#include "CCPlatformDefine.h" + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagunzFile__ { int unused; } unzFile__; +typedef unzFile__ *unzFile; +#else +typedef voidp unzFile; +#endif + + +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) + +namespace cocos2d { + +/* tm_unz contain date/time info */ +typedef struct tm_unz_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_unz; + +/* unz_global_info structure contain global data about the ZIPfile + These data comes from the end of central dir */ +typedef struct unz_global_info64_s +{ + ZPOS64_T number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info64; + +typedef struct unz_global_info_s +{ + uLong number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info; + +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_info64_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + ZPOS64_T compressed_size; /* compressed size 8 bytes */ + ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info64; + +typedef struct unz_file_info_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + uLong compressed_size; /* compressed size 4 bytes */ + uLong uncompressed_size; /* uncompressed size 4 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info; + +int CC_DLL unzStringFileNameCompare OF ((const char* fileName1, + const char* fileName2, + int iCaseSensitivity)); +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparison is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparison is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is default of your operating system + (like 1 on Unix, 2 on Windows) +*/ + + +unzFile CC_DLL unzOpen OF((const char *path)); +unzFile CC_DLL unzOpen64 OF((const void *path)); +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + "zlib/zlib113.zip". + If the zipfile cannot be opened (file don't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + the "64" function take a const void* pointer, because the path is just the + value passed to the open64_file_func callback. + Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path + is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* + does not describe the reality +*/ + + +unzFile CC_DLL unzOpen2 OF((const char *path, + zlib_filefunc_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unzOpen, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +unzFile CC_DLL unzOpen2_64 OF((const void *path, + zlib_filefunc64_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unz64Open, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +int CC_DLL unzClose OF((unzFile file)); +/* + Close a ZipFile opened with unzipOpen. + If there is files inside the .Zip opened with unzOpenCurrentFile (see later), + these files MUST be closed with unzipCloseCurrentFile before call unzipClose. + return UNZ_OK if there is no problem. */ + +int CC_DLL unzGetGlobalInfo OF((unzFile file, + unz_global_info *pglobal_info)); + +int CC_DLL unzGetGlobalInfo64 OF((unzFile file, + unz_global_info64 *pglobal_info)); +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ + + +int CC_DLL unzGetGlobalComment OF((unzFile file, + char *szComment, + uLong uSizeBuf)); +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ + + +/***************************************************************************/ +/* Unzip package allow you browse the directory of the zipfile */ + +int CC_DLL unzGoToFirstFile OF((unzFile file)); + +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ + +int CC_DLL unzGoToFirstFile64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize)); +/* + Set the current file of the zipfile to the first file + with retrieving an information about the file. + return UNZ_OK if there is no problem +*/ + +int CC_DLL unzGoToNextFile OF((unzFile file)); +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ + +int CC_DLL unzGoToNextFile64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize)); +/* + Set the current file of the zipfile to the next file + with retrieving an information about the file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ + +int CC_DLL unzLocateFile OF((unzFile file, + const char *szFileName, + int iCaseSensitivity)); +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ + + +/* ****************************************** */ +/* Ryan supplied functions */ +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_pos_s +{ + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ +} unz_file_pos; + +int CC_DLL unzGetFilePos( + unzFile file, + unz_file_pos* file_pos); + +int CC_DLL unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos); + +typedef struct unz64_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ + ZPOS64_T num_of_file; /* # of file */ +} unz64_file_pos; + +int CC_DLL unzGetFilePos64( + unzFile file, + unz64_file_pos* file_pos); + +int CC_DLL unzGoToFilePos64( + unzFile file, + const unz64_file_pos* file_pos); + +/* ****************************************** */ + +int CC_DLL unzGetCurrentFileInfo64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +int CC_DLL unzGetCurrentFileInfo OF((unzFile file, + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); +/* + Get Info about the current file + if pfile_info!=NULL, the *pfile_info structure will contain some info about + the current file + if szFileName!=NULL, the filename string will be copied in szFileName + (fileNameBufferSize is the size of the buffer) + if extraField!=NULL, the extra field information will be copied in extraField + (extraFieldBufferSize is the size of the buffer). + This is the Central-header version of the extra field + if szComment!=NULL, the comment string of the file will be copied in szComment + (commentBufferSize is the size of the buffer) +*/ + + +/** Addition for GDAL : START */ + +ZPOS64_T CC_DLL unzGetCurrentFileZStreamPos64 OF((unzFile file)); + +/** Addition for GDAL : END */ + + +/***************************************************************************/ +/* for reading the content of the current zipfile, you can open it, read data + from it, and close it (you can close it before reading all the file) + */ + +int CC_DLL unzOpenCurrentFile OF((unzFile file)); +/* + Open for reading data the current file in the zipfile. + If there is no error, the return value is UNZ_OK. +*/ + +int CC_DLL unzOpenCurrentFilePassword OF((unzFile file, + const char* password)); +/* + Open for reading data the current file in the zipfile. + password is a crypting password + If there is no error, the return value is UNZ_OK. +*/ + +int CC_DLL unzOpenCurrentFile2 OF((unzFile file, + int* method, + int* level, + int raw)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + +int CC_DLL unzOpenCurrentFile3 OF((unzFile file, + int* method, + int* level, + int raw, + const char* password)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + + +int CC_DLL unzCloseCurrentFile OF((unzFile file)); +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ + +int CC_DLL unzReadCurrentFile OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read bytes from the current file (opened by unzOpenCurrentFile) + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if some bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ + +z_off_t CC_DLL unztell OF((unzFile file)); + +ZPOS64_T CC_DLL unztell64 OF((unzFile file)); +/* + Give the current position in uncompressed data +*/ + +int CC_DLL unzeof OF((unzFile file)); +/* + return 1 if the end of file was reached, 0 elsewhere +*/ + +int CC_DLL unzGetLocalExtrafield OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ + +/***************************************************************************/ + +/* Get the current file offset */ +ZPOS64_T CC_DLL unzGetOffset64 (unzFile file); +uLong CC_DLL unzGetOffset (unzFile file); + +/* Set the current file offset */ +int CC_DLL unzSetOffset64 (unzFile file, ZPOS64_T pos); +int CC_DLL unzSetOffset (unzFile file, uLong pos); + +} // end of namespace cocos2d + +#endif /* _unz64_H */ From bb6208eec1f339d5511cac3b4f5dc17c788e320a Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 15:31:05 +0800 Subject: [PATCH 127/557] issue #2905: remove redundant codes --- external/atitc/atitc.cpp | 195 ------------ external/atitc/atitc.h | 48 --- external/etc1/etc1.cpp | 670 --------------------------------------- external/etc1/etc1.h | 106 ------- external/s3tc/s3tc.cpp | 182 ----------- external/s3tc/s3tc.h | 48 --- 6 files changed, 1249 deletions(-) delete mode 100644 external/atitc/atitc.cpp delete mode 100644 external/atitc/atitc.h delete mode 100644 external/etc1/etc1.cpp delete mode 100644 external/etc1/etc1.h delete mode 100644 external/s3tc/s3tc.cpp delete mode 100644 external/s3tc/s3tc.h diff --git a/external/atitc/atitc.cpp b/external/atitc/atitc.cpp deleted file mode 100644 index 3a60d6d2f7..0000000000 --- a/external/atitc/atitc.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "atitc.h" - -//Decode ATITC encode block to 4x4 RGB32 pixels -static void atitc_decode_block(uint8_t **blockData, - uint32_t *decodeBlockData, - unsigned int stride, - bool oneBitAlphaFlag, - uint64_t alpha, - ATITCDecodeFlag decodeFlag) -{ - unsigned int colorValue0 = 0 , colorValue1 = 0, initAlpha = (!oneBitAlphaFlag * 255u) << 24; - unsigned int rb0 = 0, rb1 = 0, rb2 = 0, rb3 = 0, g0 = 0, g1 = 0, g2 = 0, g3 = 0; - bool msb = 0; - - uint32_t colors[4], pixelsIndex = 0; - - /* load the two color values*/ - memcpy((void *)&colorValue0, *blockData, 2); - (*blockData) += 2; - - memcpy((void *)&colorValue1, *blockData, 2); - (*blockData) += 2; - - //extract the msb flag - msb = (colorValue0 & 0x8000) != 0; - - /* the channel is r5g6b5 , 16 bits */ - rb0 = (colorValue0 << 3 | colorValue0 << 9) & 0xf800f8; - rb1 = (colorValue1 << 3 | colorValue1 << 8) & 0xf800f8; - g0 = (colorValue0 << 6) & 0x00fc00; - g1 = (colorValue1 << 5) & 0x00fc00; - g0 += (g0 >> 6) & 0x000300; - g1 += (g1 >> 6) & 0x000300; - - /* interpolate the other two color values */ - if (!msb) - { - colors[0] = rb0 + g0 + initAlpha; - colors[3] = rb1 + g1 + initAlpha; - - rb2 = (((2*rb0 + rb1) * 21) >> 6) & 0xff00ff; - rb3 = (((2*rb1 + rb0) * 21) >> 6) & 0xff00ff; - g2 = (((2*g0 + g1 ) * 21) >> 6) & 0x00ff00; - g3 = (((2*g1 + g0 ) * 21) >> 6) & 0x00ff00; - - colors[2] = rb3 + g3 + initAlpha; - colors[1] = rb2 + g2 + initAlpha; - } - else - { - colors[2] = rb0 + g0 + initAlpha; - colors[3] = rb1 + g1 + initAlpha; - - rb2 = (rb0 - (rb1 >> 2)) & 0xff00ff; - g2 = (g0 - (g1 >> 2)) & 0x00ff00; - colors[0] = 0 ; - - colors[1] = rb2 + g2 + initAlpha; - } - - /*read the pixelsIndex , 2bits per pixel, 4 bytes */ - memcpy((void*)&pixelsIndex, *blockData, 4); - (*blockData) += 4; - - if (ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA == decodeFlag) - { - // atitc_interpolated_alpha use interpolate alpha - // 8-Alpha block: derive the other six alphas. - // Bit code 000 = alpha0, 001 = alpha1, other are interpolated. - - unsigned int alphaArray[8]; - - alphaArray[0] = (alpha ) & 0xff ; - alphaArray[1] = (alpha >> 8) & 0xff ; - - if (alphaArray[0] >= alphaArray[1]) - { - alphaArray[2] = (alphaArray[0]*6 + alphaArray[1]*1) / 7; - alphaArray[3] = (alphaArray[0]*5 + alphaArray[1]*2) / 7; - alphaArray[4] = (alphaArray[0]*4 + alphaArray[1]*3) / 7; - alphaArray[5] = (alphaArray[0]*3 + alphaArray[1]*4) / 7; - alphaArray[6] = (alphaArray[0]*2 + alphaArray[1]*5) / 7; - alphaArray[7] = (alphaArray[0]*1 + alphaArray[1]*6) / 7; - } - else if (alphaArray[0] < alphaArray[1]) - { - alphaArray[2] = (alphaArray[0]*4 + alphaArray[1]*1) / 5; - alphaArray[3] = (alphaArray[0]*3 + alphaArray[1]*2) / 5; - alphaArray[4] = (alphaArray[0]*2 + alphaArray[1]*3) / 5; - alphaArray[5] = (alphaArray[0]*1 + alphaArray[1]*4) / 5; - alphaArray[6] = 0; - alphaArray[7] = 255; - } - - // read the flowing 48bit indices (16*3) - alpha >>= 16; - - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - decodeBlockData[x] = (alphaArray[alpha & 5] << 24) + colors[pixelsIndex & 3]; - pixelsIndex >>= 2; - alpha >>= 3; - } - decodeBlockData += stride; - } - } //if (atc_interpolated_alpha == comFlag) - else - { - /* atc_rgb atc_explicit_alpha use explicit alpha */ - - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - initAlpha = (alpha & 0x0f) << 28; - initAlpha += initAlpha >> 4; - decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; - pixelsIndex >>= 2; - alpha >>= 4; - } - decodeBlockData += stride; - } - } -} - -//Decode ATITC encode data to RGB32 -void atitc_decode(uint8_t *encodeData, //in_data - uint8_t *decodeData, //out_data - const int pixelsWidth, - const int pixelsHeight, - ATITCDecodeFlag decodeFlag) -{ - uint32_t *decodeBlockData = (uint32_t *)decodeData; - - for (int block_y = 0; block_y < pixelsHeight / 4; ++block_y, decodeBlockData += 3 * pixelsWidth) //stride = 3*width - { - for (int block_x = 0; block_x < pixelsWidth / 4; ++block_x, decodeBlockData += 4) //skip 4 pixels - { - uint64_t blockAlpha = 0; - - switch (decodeFlag) - { - case ATITCDecodeFlag::ATC_RGB: - { - atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 0, 0LL, ATITCDecodeFlag::ATC_RGB); - } - break; - case ATITCDecodeFlag::ATC_EXPLICIT_ALPHA: - { - memcpy((void *)&blockAlpha, encodeData, 8); - encodeData += 8; - atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA); - } - break; - case ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA: - { - memcpy((void *)&blockAlpha, encodeData, 8); - encodeData += 8; - atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA); - } - break; - default: - break; - }//switch - }//for block_x - }//for block_y -} - - diff --git a/external/atitc/atitc.h b/external/atitc/atitc.h deleted file mode 100644 index 72bfd32a8c..0000000000 --- a/external/atitc/atitc.h +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - - -#ifndef COCOS2DX_PLATFORM_THIRDPARTY_ATITC_ -#define COCOS2DX_PLATFORM_THIRDPARTY_ATITC_ - -#include "CCStdC.h" - -enum class ATITCDecodeFlag -{ - ATC_RGB = 1, - ATC_EXPLICIT_ALPHA = 3, - ATC_INTERPOLATED_ALPHA = 5, -}; - -//Decode ATITC encode data to RGB32 -void atitc_decode(uint8_t *encode_data, - uint8_t *decode_data, - const int pixelsWidth, - const int pixelsHeight, - ATITCDecodeFlag decodeFlag - ); - - -#endif /* defined(COCOS2DX_PLATFORM_THIRDPARTY_ATITC_) */ - diff --git a/external/etc1/etc1.cpp b/external/etc1/etc1.cpp deleted file mode 100644 index 9c1cd43e83..0000000000 --- a/external/etc1/etc1.cpp +++ /dev/null @@ -1,670 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "etc1.h" - -#include - -/* From http://www.khronos.org/registry/gles/extensions/OES/OES_compressed_ETC1_RGB8_texture.txt - - The number of bits that represent a 4x4 texel block is 64 bits if - is given by ETC1_RGB8_OES. - - The data for a block is a number of bytes, - - {q0, q1, q2, q3, q4, q5, q6, q7} - - where byte q0 is located at the lowest memory address and q7 at - the highest. The 64 bits specifying the block is then represented - by the following 64 bit integer: - - int64bit = 256*(256*(256*(256*(256*(256*(256*q0+q1)+q2)+q3)+q4)+q5)+q6)+q7; - - ETC1_RGB8_OES: - - a) bit layout in bits 63 through 32 if diffbit = 0 - - 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 - ----------------------------------------------- - | base col1 | base col2 | base col1 | base col2 | - | R1 (4bits)| R2 (4bits)| G1 (4bits)| G2 (4bits)| - ----------------------------------------------- - - 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 - --------------------------------------------------- - | base col1 | base col2 | table | table |diff|flip| - | B1 (4bits)| B2 (4bits)| cw 1 | cw 2 |bit |bit | - --------------------------------------------------- - - - b) bit layout in bits 63 through 32 if diffbit = 1 - - 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 - ----------------------------------------------- - | base col1 | dcol 2 | base col1 | dcol 2 | - | R1' (5 bits) | dR2 | G1' (5 bits) | dG2 | - ----------------------------------------------- - - 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 - --------------------------------------------------- - | base col 1 | dcol 2 | table | table |diff|flip| - | B1' (5 bits) | dB2 | cw 1 | cw 2 |bit |bit | - --------------------------------------------------- - - - c) bit layout in bits 31 through 0 (in both cases) - - 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 - ----------------------------------------------- - | most significant pixel index bits | - | p| o| n| m| l| k| j| i| h| g| f| e| d| c| b| a| - ----------------------------------------------- - - 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 - -------------------------------------------------- - | least significant pixel index bits | - | p| o| n| m| l| k| j| i| h| g| f| e| d| c | b | a | - -------------------------------------------------- - - - Add table 3.17.2: Intensity modifier sets for ETC1 compressed textures: - - table codeword modifier table - ------------------ ---------------------- - 0 -8 -2 2 8 - 1 -17 -5 5 17 - 2 -29 -9 9 29 - 3 -42 -13 13 42 - 4 -60 -18 18 60 - 5 -80 -24 24 80 - 6 -106 -33 33 106 - 7 -183 -47 47 183 - - - Add table 3.17.3 Mapping from pixel index values to modifier values for - ETC1 compressed textures: - - pixel index value - --------------- - msb lsb resulting modifier value - ----- ----- ------------------------- - 1 1 -b (large negative value) - 1 0 -a (small negative value) - 0 0 a (small positive value) - 0 1 b (large positive value) - - - */ - -static const int kModifierTable[] = { -/* 0 */2, 8, -2, -8, -/* 1 */5, 17, -5, -17, -/* 2 */9, 29, -9, -29, -/* 3 */13, 42, -13, -42, -/* 4 */18, 60, -18, -60, -/* 5 */24, 80, -24, -80, -/* 6 */33, 106, -33, -106, -/* 7 */47, 183, -47, -183 }; - -static const int kLookup[8] = { 0, 1, 2, 3, -4, -3, -2, -1 }; - -static inline etc1_byte clamp(int x) { - return (etc1_byte) (x >= 0 ? (x < 255 ? x : 255) : 0); -} - -static -inline int convert4To8(int b) { - int c = b & 0xf; - return (c << 4) | c; -} - -static -inline int convert5To8(int b) { - int c = b & 0x1f; - return (c << 3) | (c >> 2); -} - -static -inline int convert6To8(int b) { - int c = b & 0x3f; - return (c << 2) | (c >> 4); -} - -static -inline int divideBy255(int d) { - return (d + 128 + (d >> 8)) >> 8; -} - -static -inline int convert8To4(int b) { - int c = b & 0xff; - return divideBy255(c * 15); -} - -static -inline int convert8To5(int b) { - int c = b & 0xff; - return divideBy255(c * 31); -} - -static -inline int convertDiff(int base, int diff) { - return convert5To8((0x1f & base) + kLookup[0x7 & diff]); -} - -static -void decode_subblock(etc1_byte* pOut, int r, int g, int b, const int* table, - etc1_uint32 low, bool second, bool flipped) { - int baseX = 0; - int baseY = 0; - if (second) { - if (flipped) { - baseY = 2; - } else { - baseX = 2; - } - } - for (int i = 0; i < 8; i++) { - int x, y; - if (flipped) { - x = baseX + (i >> 1); - y = baseY + (i & 1); - } else { - x = baseX + (i >> 2); - y = baseY + (i & 3); - } - int k = y + (x * 4); - int offset = ((low >> k) & 1) | ((low >> (k + 15)) & 2); - int delta = table[offset]; - etc1_byte* q = pOut + 3 * (x + 4 * y); - *q++ = clamp(r + delta); - *q++ = clamp(g + delta); - *q++ = clamp(b + delta); - } -} - -// Input is an ETC1 compressed version of the data. -// Output is a 4 x 4 square of 3-byte pixels in form R, G, B - -void etc1_decode_block(const etc1_byte* pIn, etc1_byte* pOut) { - etc1_uint32 high = (pIn[0] << 24) | (pIn[1] << 16) | (pIn[2] << 8) | pIn[3]; - etc1_uint32 low = (pIn[4] << 24) | (pIn[5] << 16) | (pIn[6] << 8) | pIn[7]; - int r1, r2, g1, g2, b1, b2; - if (high & 2) { - // differential - int rBase = high >> 27; - int gBase = high >> 19; - int bBase = high >> 11; - r1 = convert5To8(rBase); - r2 = convertDiff(rBase, high >> 24); - g1 = convert5To8(gBase); - g2 = convertDiff(gBase, high >> 16); - b1 = convert5To8(bBase); - b2 = convertDiff(bBase, high >> 8); - } else { - // not differential - r1 = convert4To8(high >> 28); - r2 = convert4To8(high >> 24); - g1 = convert4To8(high >> 20); - g2 = convert4To8(high >> 16); - b1 = convert4To8(high >> 12); - b2 = convert4To8(high >> 8); - } - int tableIndexA = 7 & (high >> 5); - int tableIndexB = 7 & (high >> 2); - const int* tableA = kModifierTable + tableIndexA * 4; - const int* tableB = kModifierTable + tableIndexB * 4; - bool flipped = (high & 1) != 0; - decode_subblock(pOut, r1, g1, b1, tableA, low, false, flipped); - decode_subblock(pOut, r2, g2, b2, tableB, low, true, flipped); -} - -typedef struct { - etc1_uint32 high; - etc1_uint32 low; - etc1_uint32 score; // Lower is more accurate -} etc_compressed; - -static -inline void take_best(etc_compressed* a, const etc_compressed* b) { - if (a->score > b->score) { - *a = *b; - } -} - -static -void etc_average_colors_subblock(const etc1_byte* pIn, etc1_uint32 inMask, - etc1_byte* pColors, bool flipped, bool second) { - int r = 0; - int g = 0; - int b = 0; - - if (flipped) { - int by = 0; - if (second) { - by = 2; - } - for (int y = 0; y < 2; y++) { - int yy = by + y; - for (int x = 0; x < 4; x++) { - int i = x + 4 * yy; - if (inMask & (1 << i)) { - const etc1_byte* p = pIn + i * 3; - r += *(p++); - g += *(p++); - b += *(p++); - } - } - } - } else { - int bx = 0; - if (second) { - bx = 2; - } - for (int y = 0; y < 4; y++) { - for (int x = 0; x < 2; x++) { - int xx = bx + x; - int i = xx + 4 * y; - if (inMask & (1 << i)) { - const etc1_byte* p = pIn + i * 3; - r += *(p++); - g += *(p++); - b += *(p++); - } - } - } - } - pColors[0] = (etc1_byte)((r + 4) >> 3); - pColors[1] = (etc1_byte)((g + 4) >> 3); - pColors[2] = (etc1_byte)((b + 4) >> 3); -} - -static -inline int square(int x) { - return x * x; -} - -static etc1_uint32 chooseModifier(const etc1_byte* pBaseColors, - const etc1_byte* pIn, etc1_uint32 *pLow, int bitIndex, - const int* pModifierTable) { - etc1_uint32 bestScore = ~0; - int bestIndex = 0; - int pixelR = pIn[0]; - int pixelG = pIn[1]; - int pixelB = pIn[2]; - int r = pBaseColors[0]; - int g = pBaseColors[1]; - int b = pBaseColors[2]; - for (int i = 0; i < 4; i++) { - int modifier = pModifierTable[i]; - int decodedG = clamp(g + modifier); - etc1_uint32 score = (etc1_uint32) (6 * square(decodedG - pixelG)); - if (score >= bestScore) { - continue; - } - int decodedR = clamp(r + modifier); - score += (etc1_uint32) (3 * square(decodedR - pixelR)); - if (score >= bestScore) { - continue; - } - int decodedB = clamp(b + modifier); - score += (etc1_uint32) square(decodedB - pixelB); - if (score < bestScore) { - bestScore = score; - bestIndex = i; - } - } - etc1_uint32 lowMask = (((bestIndex >> 1) << 16) | (bestIndex & 1)) - << bitIndex; - *pLow |= lowMask; - return bestScore; -} - -static -void etc_encode_subblock_helper(const etc1_byte* pIn, etc1_uint32 inMask, - etc_compressed* pCompressed, bool flipped, bool second, - const etc1_byte* pBaseColors, const int* pModifierTable) { - int score = pCompressed->score; - if (flipped) { - int by = 0; - if (second) { - by = 2; - } - for (int y = 0; y < 2; y++) { - int yy = by + y; - for (int x = 0; x < 4; x++) { - int i = x + 4 * yy; - if (inMask & (1 << i)) { - score += chooseModifier(pBaseColors, pIn + i * 3, - &pCompressed->low, yy + x * 4, pModifierTable); - } - } - } - } else { - int bx = 0; - if (second) { - bx = 2; - } - for (int y = 0; y < 4; y++) { - for (int x = 0; x < 2; x++) { - int xx = bx + x; - int i = xx + 4 * y; - if (inMask & (1 << i)) { - score += chooseModifier(pBaseColors, pIn + i * 3, - &pCompressed->low, y + xx * 4, pModifierTable); - } - } - } - } - pCompressed->score = score; -} - -static bool inRange4bitSigned(int color) { - return color >= -4 && color <= 3; -} - -static void etc_encodeBaseColors(etc1_byte* pBaseColors, - const etc1_byte* pColors, etc_compressed* pCompressed) { - int r1, g1, b1, r2, g2, b2; // 8 bit base colors for sub-blocks - bool differential; - { - int r51 = convert8To5(pColors[0]); - int g51 = convert8To5(pColors[1]); - int b51 = convert8To5(pColors[2]); - int r52 = convert8To5(pColors[3]); - int g52 = convert8To5(pColors[4]); - int b52 = convert8To5(pColors[5]); - - r1 = convert5To8(r51); - g1 = convert5To8(g51); - b1 = convert5To8(b51); - - int dr = r52 - r51; - int dg = g52 - g51; - int db = b52 - b51; - - differential = inRange4bitSigned(dr) && inRange4bitSigned(dg) - && inRange4bitSigned(db); - if (differential) { - r2 = convert5To8(r51 + dr); - g2 = convert5To8(g51 + dg); - b2 = convert5To8(b51 + db); - pCompressed->high |= (r51 << 27) | ((7 & dr) << 24) | (g51 << 19) - | ((7 & dg) << 16) | (b51 << 11) | ((7 & db) << 8) | 2; - } - } - - if (!differential) { - int r41 = convert8To4(pColors[0]); - int g41 = convert8To4(pColors[1]); - int b41 = convert8To4(pColors[2]); - int r42 = convert8To4(pColors[3]); - int g42 = convert8To4(pColors[4]); - int b42 = convert8To4(pColors[5]); - r1 = convert4To8(r41); - g1 = convert4To8(g41); - b1 = convert4To8(b41); - r2 = convert4To8(r42); - g2 = convert4To8(g42); - b2 = convert4To8(b42); - pCompressed->high |= (r41 << 28) | (r42 << 24) | (g41 << 20) | (g42 - << 16) | (b41 << 12) | (b42 << 8); - } - pBaseColors[0] = r1; - pBaseColors[1] = g1; - pBaseColors[2] = b1; - pBaseColors[3] = r2; - pBaseColors[4] = g2; - pBaseColors[5] = b2; -} - -static -void etc_encode_block_helper(const etc1_byte* pIn, etc1_uint32 inMask, - const etc1_byte* pColors, etc_compressed* pCompressed, bool flipped) { - pCompressed->score = ~0; - pCompressed->high = (flipped ? 1 : 0); - pCompressed->low = 0; - - etc1_byte pBaseColors[6]; - - etc_encodeBaseColors(pBaseColors, pColors, pCompressed); - - int originalHigh = pCompressed->high; - - const int* pModifierTable = kModifierTable; - for (int i = 0; i < 8; i++, pModifierTable += 4) { - etc_compressed temp; - temp.score = 0; - temp.high = originalHigh | (i << 5); - temp.low = 0; - etc_encode_subblock_helper(pIn, inMask, &temp, flipped, false, - pBaseColors, pModifierTable); - take_best(pCompressed, &temp); - } - pModifierTable = kModifierTable; - etc_compressed firstHalf = *pCompressed; - for (int i = 0; i < 8; i++, pModifierTable += 4) { - etc_compressed temp; - temp.score = firstHalf.score; - temp.high = firstHalf.high | (i << 2); - temp.low = firstHalf.low; - etc_encode_subblock_helper(pIn, inMask, &temp, flipped, true, - pBaseColors + 3, pModifierTable); - if (i == 0) { - *pCompressed = temp; - } else { - take_best(pCompressed, &temp); - } - } -} - -static void writeBigEndian(etc1_byte* pOut, etc1_uint32 d) { - pOut[0] = (etc1_byte)(d >> 24); - pOut[1] = (etc1_byte)(d >> 16); - pOut[2] = (etc1_byte)(d >> 8); - pOut[3] = (etc1_byte) d; -} - -// Input is a 4 x 4 square of 3-byte pixels in form R, G, B -// inmask is a 16-bit mask where bit (1 << (x + y * 4)) tells whether the corresponding (x,y) -// pixel is valid or not. Invalid pixel color values are ignored when compressing. -// Output is an ETC1 compressed version of the data. - -void etc1_encode_block(const etc1_byte* pIn, etc1_uint32 inMask, - etc1_byte* pOut) { - etc1_byte colors[6]; - etc1_byte flippedColors[6]; - etc_average_colors_subblock(pIn, inMask, colors, false, false); - etc_average_colors_subblock(pIn, inMask, colors + 3, false, true); - etc_average_colors_subblock(pIn, inMask, flippedColors, true, false); - etc_average_colors_subblock(pIn, inMask, flippedColors + 3, true, true); - - etc_compressed a, b; - etc_encode_block_helper(pIn, inMask, colors, &a, false); - etc_encode_block_helper(pIn, inMask, flippedColors, &b, true); - take_best(&a, &b); - writeBigEndian(pOut, a.high); - writeBigEndian(pOut + 4, a.low); -} - -// Return the size of the encoded image data (does not include size of PKM header). - -etc1_uint32 etc1_get_encoded_data_size(etc1_uint32 width, etc1_uint32 height) { - return (((width + 3) & ~3) * ((height + 3) & ~3)) >> 1; -} - -// Encode an entire image. -// pIn - pointer to the image data. Formatted such that the Red component of -// pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset; -// pOut - pointer to encoded data. Must be large enough to store entire encoded image. - -int etc1_encode_image(const etc1_byte* pIn, etc1_uint32 width, etc1_uint32 height, - etc1_uint32 pixelSize, etc1_uint32 stride, etc1_byte* pOut) { - if (pixelSize < 2 || pixelSize > 3) { - return -1; - } - static const unsigned short kYMask[] = { 0x0, 0xf, 0xff, 0xfff, 0xffff }; - static const unsigned short kXMask[] = { 0x0, 0x1111, 0x3333, 0x7777, - 0xffff }; - etc1_byte block[ETC1_DECODED_BLOCK_SIZE]; - etc1_byte encoded[ETC1_ENCODED_BLOCK_SIZE]; - - etc1_uint32 encodedWidth = (width + 3) & ~3; - etc1_uint32 encodedHeight = (height + 3) & ~3; - - for (etc1_uint32 y = 0; y < encodedHeight; y += 4) { - etc1_uint32 yEnd = height - y; - if (yEnd > 4) { - yEnd = 4; - } - int ymask = kYMask[yEnd]; - for (etc1_uint32 x = 0; x < encodedWidth; x += 4) { - etc1_uint32 xEnd = width - x; - if (xEnd > 4) { - xEnd = 4; - } - int mask = ymask & kXMask[xEnd]; - for (etc1_uint32 cy = 0; cy < yEnd; cy++) { - etc1_byte* q = block + (cy * 4) * 3; - const etc1_byte* p = pIn + pixelSize * x + stride * (y + cy); - if (pixelSize == 3) { - memcpy(q, p, xEnd * 3); - } else { - for (etc1_uint32 cx = 0; cx < xEnd; cx++) { - int pixel = (p[1] << 8) | p[0]; - *q++ = convert5To8(pixel >> 11); - *q++ = convert6To8(pixel >> 5); - *q++ = convert5To8(pixel); - p += pixelSize; - } - } - } - etc1_encode_block(block, mask, encoded); - memcpy(pOut, encoded, sizeof(encoded)); - pOut += sizeof(encoded); - } - } - return 0; -} - -// Decode an entire image. -// pIn - pointer to encoded data. -// pOut - pointer to the image data. Will be written such that the Red component of -// pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset. Must be -// large enough to store entire image. - - -int etc1_decode_image(const etc1_byte* pIn, etc1_byte* pOut, - etc1_uint32 width, etc1_uint32 height, - etc1_uint32 pixelSize, etc1_uint32 stride) { - if (pixelSize < 2 || pixelSize > 3) { - return -1; - } - etc1_byte block[ETC1_DECODED_BLOCK_SIZE]; - - etc1_uint32 encodedWidth = (width + 3) & ~3; - etc1_uint32 encodedHeight = (height + 3) & ~3; - - for (etc1_uint32 y = 0; y < encodedHeight; y += 4) { - etc1_uint32 yEnd = height - y; - if (yEnd > 4) { - yEnd = 4; - } - for (etc1_uint32 x = 0; x < encodedWidth; x += 4) { - etc1_uint32 xEnd = width - x; - if (xEnd > 4) { - xEnd = 4; - } - etc1_decode_block(pIn, block); - pIn += ETC1_ENCODED_BLOCK_SIZE; - for (etc1_uint32 cy = 0; cy < yEnd; cy++) { - const etc1_byte* q = block + (cy * 4) * 3; - etc1_byte* p = pOut + pixelSize * x + stride * (y + cy); - if (pixelSize == 3) { - memcpy(p, q, xEnd * 3); - } else { - for (etc1_uint32 cx = 0; cx < xEnd; cx++) { - etc1_byte r = *q++; - etc1_byte g = *q++; - etc1_byte b = *q++; - etc1_uint32 pixel = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); - *p++ = (etc1_byte) pixel; - *p++ = (etc1_byte) (pixel >> 8); - } - } - } - } - } - return 0; -} - -static const char kMagic[] = { 'P', 'K', 'M', ' ', '1', '0' }; - -static const etc1_uint32 ETC1_PKM_FORMAT_OFFSET = 6; -static const etc1_uint32 ETC1_PKM_ENCODED_WIDTH_OFFSET = 8; -static const etc1_uint32 ETC1_PKM_ENCODED_HEIGHT_OFFSET = 10; -static const etc1_uint32 ETC1_PKM_WIDTH_OFFSET = 12; -static const etc1_uint32 ETC1_PKM_HEIGHT_OFFSET = 14; - -static const etc1_uint32 ETC1_RGB_NO_MIPMAPS = 0; - -static void writeBEUint16(etc1_byte* pOut, etc1_uint32 data) { - pOut[0] = (etc1_byte) (data >> 8); - pOut[1] = (etc1_byte) data; -} - -static etc1_uint32 readBEUint16(const etc1_byte* pIn) { - return (pIn[0] << 8) | pIn[1]; -} - -// Format a PKM header - -void etc1_pkm_format_header(etc1_byte* pHeader, etc1_uint32 width, etc1_uint32 height) { - memcpy(pHeader, kMagic, sizeof(kMagic)); - etc1_uint32 encodedWidth = (width + 3) & ~3; - etc1_uint32 encodedHeight = (height + 3) & ~3; - writeBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET, ETC1_RGB_NO_MIPMAPS); - writeBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET, encodedWidth); - writeBEUint16(pHeader + ETC1_PKM_ENCODED_HEIGHT_OFFSET, encodedHeight); - writeBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET, width); - writeBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET, height); -} - -// Check if a PKM header is correctly formatted. - -etc1_bool etc1_pkm_is_valid(const etc1_byte* pHeader) { - if (memcmp(pHeader, kMagic, sizeof(kMagic))) { - return false; - } - etc1_uint32 format = readBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET); - etc1_uint32 encodedWidth = readBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET); - etc1_uint32 encodedHeight = readBEUint16(pHeader + ETC1_PKM_ENCODED_HEIGHT_OFFSET); - etc1_uint32 width = readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); - etc1_uint32 height = readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); - return format == ETC1_RGB_NO_MIPMAPS && - encodedWidth >= width && encodedWidth - width < 4 && - encodedHeight >= height && encodedHeight - height < 4; -} - -// Read the image width from a PKM header - -etc1_uint32 etc1_pkm_get_width(const etc1_byte* pHeader) { - return readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); -} - -// Read the image height from a PKM header - -etc1_uint32 etc1_pkm_get_height(const etc1_byte* pHeader){ - return readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); -} diff --git a/external/etc1/etc1.h b/external/etc1/etc1.h deleted file mode 100644 index 0d389052b7..0000000000 --- a/external/etc1/etc1.h +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef __etc1_h__ -#define __etc1_h__ - -#define ETC1_ENCODED_BLOCK_SIZE 8 -#define ETC1_DECODED_BLOCK_SIZE 48 - -#ifndef ETC1_RGB8_OES -#define ETC1_RGB8_OES 0x8D64 -#endif - -typedef unsigned char etc1_byte; -typedef int etc1_bool; -typedef unsigned int etc1_uint32; - -#ifdef __cplusplus -extern "C" { -#endif - -// Encode a block of pixels. -// -// pIn is a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a -// 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R -// value of pixel (x, y). -// -// validPixelMask is a 16-bit mask where bit (1 << (x + y * 4)) indicates whether -// the corresponding (x,y) pixel is valid. Invalid pixel color values are ignored when compressing. -// -// pOut is an ETC1 compressed version of the data. - -void etc1_encode_block(const etc1_byte* pIn, etc1_uint32 validPixelMask, etc1_byte* pOut); - -// Decode a block of pixels. -// -// pIn is an ETC1 compressed version of the data. -// -// pOut is a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a -// 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R -// value of pixel (x, y). - -void etc1_decode_block(const etc1_byte* pIn, etc1_byte* pOut); - -// Return the size of the encoded image data (does not include size of PKM header). - -etc1_uint32 etc1_get_encoded_data_size(etc1_uint32 width, etc1_uint32 height); - -// Encode an entire image. -// pIn - pointer to the image data. Formatted such that -// pixel (x,y) is at pIn + pixelSize * x + stride * y; -// pOut - pointer to encoded data. Must be large enough to store entire encoded image. -// pixelSize can be 2 or 3. 2 is an GL_UNSIGNED_SHORT_5_6_5 image, 3 is a GL_BYTE RGB image. -// returns non-zero if there is an error. - -int etc1_encode_image(const etc1_byte* pIn, etc1_uint32 width, etc1_uint32 height, - etc1_uint32 pixelSize, etc1_uint32 stride, etc1_byte* pOut); - -// Decode an entire image. -// pIn - pointer to encoded data. -// pOut - pointer to the image data. Will be written such that -// pixel (x,y) is at pIn + pixelSize * x + stride * y. Must be -// large enough to store entire image. -// pixelSize can be 2 or 3. 2 is an GL_UNSIGNED_SHORT_5_6_5 image, 3 is a GL_BYTE RGB image. -// returns non-zero if there is an error. - -int etc1_decode_image(const etc1_byte* pIn, etc1_byte* pOut, - etc1_uint32 width, etc1_uint32 height, - etc1_uint32 pixelSize, etc1_uint32 stride); - -// Size of a PKM header, in bytes. - -#define ETC_PKM_HEADER_SIZE 16 - -// Format a PKM header - -void etc1_pkm_format_header(etc1_byte* pHeader, etc1_uint32 width, etc1_uint32 height); - -// Check if a PKM header is correctly formatted. - -etc1_bool etc1_pkm_is_valid(const etc1_byte* pHeader); - -// Read the image width from a PKM header - -etc1_uint32 etc1_pkm_get_width(const etc1_byte* pHeader); - -// Read the image height from a PKM header - -etc1_uint32 etc1_pkm_get_height(const etc1_byte* pHeader); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/external/s3tc/s3tc.cpp b/external/s3tc/s3tc.cpp deleted file mode 100644 index e7869df631..0000000000 --- a/external/s3tc/s3tc.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "s3tc.h" - -//Decode S3TC encode block to 4x4 RGB32 pixels -static void s3tc_decode_block(uint8_t **blockData, - uint32_t *decodeBlockData, - unsigned int stride, - bool oneBitAlphaFlag, - uint64_t alpha, - S3TCDecodeFlag decodeFlag) -{ - unsigned int colorValue0 = 0 , colorValue1 = 0, initAlpha = (!oneBitAlphaFlag * 255u) << 24; - unsigned int rb0 = 0, rb1 = 0, rb2 = 0, rb3 = 0, g0 = 0, g1 = 0, g2 = 0, g3 = 0; - - uint32_t colors[4], pixelsIndex = 0; - - /* load the two color values*/ - memcpy((void *)&colorValue0, *blockData, 2); - (*blockData) += 2; - - memcpy((void *)&colorValue1, *blockData, 2); - (*blockData) += 2; - - /* the channel is r5g6b5 , 16 bits */ - rb0 = (colorValue0 << 19 | colorValue0 >> 8) & 0xf800f8; - rb1 = (colorValue1 << 19 | colorValue1 >> 8) & 0xf800f8; - g0 = (colorValue0 << 5) & 0x00fc00; - g1 = (colorValue1 << 5) & 0x00fc00; - g0 += (g0 >> 6) & 0x000300; - g1 += (g1 >> 6) & 0x000300; - - colors[0] = rb0 + g0 + initAlpha; - colors[1] = rb1 + g1 + initAlpha; - - /* interpolate the other two color values */ - if (colorValue0 > colorValue1 || oneBitAlphaFlag) - { - rb2 = (((2*rb0 + rb1) * 21) >> 6) & 0xff00ff; - rb3 = (((2*rb1 + rb0) * 21) >> 6) & 0xff00ff; - g2 = (((2*g0 + g1 ) * 21) >> 6) & 0x00ff00; - g3 = (((2*g1 + g0 ) * 21) >> 6) & 0x00ff00; - colors[3] = rb3 + g3 + initAlpha; - } - else - { - rb2 = ((rb0+rb1) >> 1) & 0xff00ff; - g2 = ((g0 +g1 ) >> 1) & 0x00ff00; - colors[3] = 0 ; - } - colors[2] = rb2 + g2 + initAlpha; - - /*read the pixelsIndex , 2bits per pixel, 4 bytes */ - memcpy((void*)&pixelsIndex, *blockData, 4); - (*blockData) += 4; - - if (S3TCDecodeFlag::DXT5 == decodeFlag) - { - //dxt5 use interpolate alpha - // 8-Alpha block: derive the other six alphas. - // Bit code 000 = alpha0, 001 = alpha1, other are interpolated. - - unsigned int alphaArray[8]; - - alphaArray[0] = (alpha ) & 0xff ; - alphaArray[1] = (alpha >> 8) & 0xff ; - - if (alphaArray[0] >= alphaArray[1]) - { - alphaArray[2] = (alphaArray[0]*6 + alphaArray[1]*1) / 7; - alphaArray[3] = (alphaArray[0]*5 + alphaArray[1]*2) / 7; - alphaArray[4] = (alphaArray[0]*4 + alphaArray[1]*3) / 7; - alphaArray[5] = (alphaArray[0]*3 + alphaArray[1]*4) / 7; - alphaArray[6] = (alphaArray[0]*2 + alphaArray[1]*5) / 7; - alphaArray[7] = (alphaArray[0]*1 + alphaArray[1]*6) / 7; - } - else if (alphaArray[0] < alphaArray[1]) - { - alphaArray[2] = (alphaArray[0]*4 + alphaArray[1]*1) / 5; - alphaArray[3] = (alphaArray[0]*3 + alphaArray[1]*2) / 5; - alphaArray[4] = (alphaArray[0]*2 + alphaArray[1]*3) / 5; - alphaArray[5] = (alphaArray[0]*1 + alphaArray[1]*4) / 5; - alphaArray[6] = 0; - alphaArray[7] = 255; - } - - // read the flowing 48bit indices (16*3) - alpha >>= 16; - - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - decodeBlockData[x] = (alphaArray[alpha & 5] << 24) + colors[pixelsIndex & 3]; - pixelsIndex >>= 2; - alpha >>= 3; - } - decodeBlockData += stride; - } - } //if (dxt5 == comFlag) - else - { //dxt1 dxt3 use explicit alpha - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - initAlpha = (alpha & 0x0f) << 28; - initAlpha += initAlpha >> 4; - decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; - pixelsIndex >>= 2; - alpha >>= 4; - } - decodeBlockData += stride; - } - } -} - -//Decode S3TC encode data to RGB32 -void s3tc_decode(uint8_t *encodeData, //in_data - uint8_t *decodeData, //out_data - const int pixelsWidth, - const int pixelsHeight, - S3TCDecodeFlag decodeFlag) -{ - uint32_t *decodeBlockData = (uint32_t *)decodeData; - for (int block_y = 0; block_y < pixelsHeight / 4; ++block_y, decodeBlockData += 3 * pixelsWidth) //stride = 3*width - { - for(int block_x = 0; block_x < pixelsWidth / 4; ++block_x, decodeBlockData += 4) //skip 4 pixels - { - uint64_t blockAlpha = 0; - - switch (decodeFlag) - { - case S3TCDecodeFlag::DXT1: - { - s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 0, 0LL, S3TCDecodeFlag::DXT1); - } - break; - case S3TCDecodeFlag::DXT3: - { - memcpy((void *)&blockAlpha, encodeData, 8); - encodeData += 8; - s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, S3TCDecodeFlag::DXT3); - } - break; - case S3TCDecodeFlag::DXT5: - { - memcpy((void *)&blockAlpha, encodeData, 8); - encodeData += 8; - s3tc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, S3TCDecodeFlag::DXT5); - } - break; - default: - break; - }//switch - }//for block_x - }//for block_y -} - - diff --git a/external/s3tc/s3tc.h b/external/s3tc/s3tc.h deleted file mode 100644 index a3cf233257..0000000000 --- a/external/s3tc/s3tc.h +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - - -#ifndef COCOS2DX_PLATFORM_THIRDPARTY_S3TC_ -#define COCOS2DX_PLATFORM_THIRDPARTY_S3TC_ - -#include "CCStdC.h" - -enum class S3TCDecodeFlag -{ - DXT1 = 1, - DXT3 = 3, - DXT5 = 5, -}; - -//Decode S3TC encode data to RGB32 - void s3tc_decode(uint8_t *encode_data, - uint8_t *decode_data, - const int pixelsWidth, - const int pixelsHeight, - S3TCDecodeFlag decodeFlag - ); - - -#endif /* defined(COCOS2DX_PLATFORM_THIRDPARTY_S3TC_) */ - From 49d7bbd6009d28b9e5c4519a7a53e89c7b982a04 Mon Sep 17 00:00:00 2001 From: minggo Date: Sat, 12 Oct 2013 15:41:45 +0800 Subject: [PATCH 128/557] issue #2905: remove sub folders except platform --- cocos/2d/{actions => }/CCAction.cpp | 0 cocos/2d/{actions => }/CCAction.h | 0 cocos/2d/{actions => }/CCActionCamera.cpp | 0 cocos/2d/{actions => }/CCActionCamera.h | 0 cocos/2d/{actions => }/CCActionCatmullRom.cpp | 0 cocos/2d/{actions => }/CCActionCatmullRom.h | 0 cocos/2d/{actions => }/CCActionEase.cpp | 0 cocos/2d/{actions => }/CCActionEase.h | 0 cocos/2d/{actions => }/CCActionGrid.cpp | 0 cocos/2d/{actions => }/CCActionGrid.h | 0 cocos/2d/{actions => }/CCActionGrid3D.cpp | 0 cocos/2d/{actions => }/CCActionGrid3D.h | 0 cocos/2d/{actions => }/CCActionInstant.cpp | 0 cocos/2d/{actions => }/CCActionInstant.h | 0 cocos/2d/{actions => }/CCActionInterval.cpp | 0 cocos/2d/{actions => }/CCActionInterval.h | 0 cocos/2d/{actions => }/CCActionManager.cpp | 0 cocos/2d/{actions => }/CCActionManager.h | 0 cocos/2d/{actions => }/CCActionPageTurn3D.cpp | 0 cocos/2d/{actions => }/CCActionPageTurn3D.h | 0 .../{actions => }/CCActionProgressTimer.cpp | 0 .../2d/{actions => }/CCActionProgressTimer.h | 0 cocos/2d/{actions => }/CCActionTiledGrid.cpp | 0 cocos/2d/{actions => }/CCActionTiledGrid.h | 0 cocos/2d/{actions => }/CCActionTween.cpp | 0 cocos/2d/{actions => }/CCActionTween.h | 0 cocos/2d/{sprite-nodes => }/CCAnimation.cpp | 0 cocos/2d/{sprite-nodes => }/CCAnimation.h | 0 .../{sprite-nodes => }/CCAnimationCache.cpp | 0 .../2d/{sprite-nodes => }/CCAnimationCache.h | 0 cocos/2d/{base-nodes => }/CCAtlasNode.cpp | 0 cocos/2d/{base-nodes => }/CCAtlasNode.h | 0 cocos/2d/{misc-nodes => }/CCClippingNode.cpp | 0 cocos/2d/{misc-nodes => }/CCClippingNode.h | 0 .../{support/component => }/CCComponent.cpp | 0 .../2d/{support/component => }/CCComponent.h | 0 .../component => }/CCComponentContainer.cpp | 0 .../component => }/CCComponentContainer.h | 0 cocos/2d/{include => }/CCDeprecated.h | 0 cocos/2d/{draw-nodes => }/CCDrawNode.cpp | 0 cocos/2d/{draw-nodes => }/CCDrawNode.h | 0 .../{draw-nodes => }/CCDrawingPrimitives.cpp | 0 .../2d/{draw-nodes => }/CCDrawingPrimitives.h | 0 cocos/2d/{event-dispatcher => }/CCEvent.cpp | 0 cocos/2d/{event-dispatcher => }/CCEvent.h | 0 .../CCEventAcceleration.cpp | 0 .../CCEventAcceleration.h | 0 .../{event-dispatcher => }/CCEventCustom.cpp | 0 .../2d/{event-dispatcher => }/CCEventCustom.h | 0 .../CCEventDispatcher.cpp | 0 .../CCEventDispatcher.h | 0 .../CCEventKeyboard.cpp | 0 .../{event-dispatcher => }/CCEventKeyboard.h | 0 .../CCEventListener.cpp | 0 .../{event-dispatcher => }/CCEventListener.h | 0 .../CCEventListenerAcceleration.cpp | 0 .../CCEventListenerAcceleration.h | 0 .../CCEventListenerCustom.cpp | 0 .../CCEventListenerCustom.h | 0 .../CCEventListenerKeyboard.cpp | 0 .../CCEventListenerKeyboard.h | 0 .../CCEventListenerTouch.cpp | 0 .../CCEventListenerTouch.h | 0 .../{event-dispatcher => }/CCEventTouch.cpp | 0 .../2d/{event-dispatcher => }/CCEventTouch.h | 0 cocos/2d/{include => }/CCEventType.h | 0 cocos/2d/{label-nodes => }/CCFont.cpp | 0 cocos/2d/{label-nodes => }/CCFont.h | 0 cocos/2d/{label-nodes => }/CCFontAtlas.cpp | 0 cocos/2d/{label-nodes => }/CCFontAtlas.h | 0 .../2d/{label-nodes => }/CCFontAtlasCache.cpp | 0 cocos/2d/{label-nodes => }/CCFontAtlasCache.h | 0 .../{label-nodes => }/CCFontAtlasFactory.cpp | 0 .../2d/{label-nodes => }/CCFontAtlasFactory.h | 0 .../2d/{label-nodes => }/CCFontDefinition.cpp | 0 cocos/2d/{label-nodes => }/CCFontDefinition.h | 0 cocos/2d/{label-nodes => }/CCFontFNT.cpp | 0 cocos/2d/{label-nodes => }/CCFontFNT.h | 0 cocos/2d/{label-nodes => }/CCFontFreeType.cpp | 0 cocos/2d/{label-nodes => }/CCFontFreeType.h | 0 .../2d/{base-nodes => }/CCGLBufferedNode.cpp | 0 cocos/2d/{base-nodes => }/CCGLBufferedNode.h | 0 cocos/2d/{shaders => }/CCGLProgram.cpp | 0 cocos/2d/{shaders => }/CCGLProgram.h | 0 cocos/2d/{effects => }/CCGrabber.cpp | 0 cocos/2d/{effects => }/CCGrabber.h | 0 cocos/2d/{effects => }/CCGrid.cpp | 0 cocos/2d/{effects => }/CCGrid.h | 0 .../2d/{text-input-node => }/CCIMEDelegate.h | 0 .../{text-input-node => }/CCIMEDispatcher.cpp | 0 .../{text-input-node => }/CCIMEDispatcher.h | 0 cocos/2d/{label-nodes => }/CCLabel.cpp | 0 cocos/2d/{label-nodes => }/CCLabel.h | 0 cocos/2d/{label-nodes => }/CCLabelAtlas.cpp | 0 cocos/2d/{label-nodes => }/CCLabelAtlas.h | 0 cocos/2d/{label-nodes => }/CCLabelBMFont.cpp | 0 cocos/2d/{label-nodes => }/CCLabelBMFont.h | 0 cocos/2d/{label-nodes => }/CCLabelTTF.cpp | 0 cocos/2d/{label-nodes => }/CCLabelTTF.h | 0 .../CCLabelTextFormatProtocol.h | 0 .../CCLabelTextFormatter.cpp | 0 .../{label-nodes => }/CCLabelTextFormatter.h | 0 .../CCLayer.cpp | 0 .../CCLayer.h | 0 cocos/2d/{menu-nodes => }/CCMenu.cpp | 0 cocos/2d/{menu-nodes => }/CCMenu.h | 0 cocos/2d/{menu-nodes => }/CCMenuItem.cpp | 0 cocos/2d/{menu-nodes => }/CCMenuItem.h | 0 cocos/2d/{misc-nodes => }/CCMotionStreak.cpp | 0 cocos/2d/{misc-nodes => }/CCMotionStreak.h | 0 cocos/2d/{base-nodes => }/CCNode.cpp | 0 cocos/2d/{base-nodes => }/CCNode.h | 0 .../2d/{support => }/CCNotificationCenter.cpp | 0 cocos/2d/{support => }/CCNotificationCenter.h | 0 .../CCParallaxNode.cpp | 0 .../CCParallaxNode.h | 0 .../CCParticleBatchNode.cpp | 0 .../CCParticleBatchNode.h | 0 .../CCParticleExamples.cpp | 0 .../{particle-nodes => }/CCParticleExamples.h | 0 .../{particle-nodes => }/CCParticleSystem.cpp | 0 .../{particle-nodes => }/CCParticleSystem.h | 0 .../CCParticleSystemQuad.cpp | 0 .../CCParticleSystemQuad.h | 0 cocos/2d/{support => }/CCProfiling.cpp | 0 cocos/2d/{support => }/CCProfiling.h | 0 cocos/2d/{misc-nodes => }/CCProgressTimer.cpp | 0 cocos/2d/{misc-nodes => }/CCProgressTimer.h | 0 cocos/2d/{include => }/CCProtocols.h | 0 cocos/2d/{misc-nodes => }/CCRenderTexture.cpp | 0 cocos/2d/{misc-nodes => }/CCRenderTexture.h | 0 .../CCScene.cpp | 0 .../CCScene.h | 0 .../{script-support => }/CCScriptSupport.cpp | 0 .../2d/{script-support => }/CCScriptSupport.h | 0 cocos/2d/{shaders => }/CCShaderCache.cpp | 0 cocos/2d/{shaders => }/CCShaderCache.h | 0 cocos/2d/{sprite-nodes => }/CCSprite.cpp | 0 cocos/2d/{sprite-nodes => }/CCSprite.h | 0 .../{sprite-nodes => }/CCSpriteBatchNode.cpp | 0 .../2d/{sprite-nodes => }/CCSpriteBatchNode.h | 0 cocos/2d/{sprite-nodes => }/CCSpriteFrame.cpp | 0 cocos/2d/{sprite-nodes => }/CCSpriteFrame.h | 0 .../{sprite-nodes => }/CCSpriteFrameCache.cpp | 0 .../{sprite-nodes => }/CCSpriteFrameCache.h | 0 .../CCTMXLayer.cpp | 0 .../{tilemap-parallax-nodes => }/CCTMXLayer.h | 0 .../CCTMXObjectGroup.cpp | 0 .../CCTMXObjectGroup.h | 0 .../CCTMXTiledMap.cpp | 0 .../CCTMXTiledMap.h | 0 .../CCTMXXMLParser.cpp | 0 .../CCTMXXMLParser.h | 0 .../{text-input-node => }/CCTextFieldTTF.cpp | 0 .../2d/{text-input-node => }/CCTextFieldTTF.h | 0 cocos/2d/{label-nodes => }/CCTextImage.cpp | 0 cocos/2d/{label-nodes => }/CCTextImage.h | 0 cocos/2d/{textures => }/CCTexture2D.cpp | 0 cocos/2d/{textures => }/CCTexture2D.h | 0 cocos/2d/{textures => }/CCTextureAtlas.cpp | 0 cocos/2d/{textures => }/CCTextureAtlas.h | 0 cocos/2d/{textures => }/CCTextureCache.cpp | 0 cocos/2d/{textures => }/CCTextureCache.h | 0 .../CCTileMapAtlas.cpp | 0 .../CCTileMapAtlas.h | 0 cocos/2d/{event-dispatcher => }/CCTouch.cpp | 0 cocos/2d/{event-dispatcher => }/CCTouch.h | 0 .../CCTransition.cpp | 0 .../CCTransition.h | 0 .../CCTransitionPageTurn.cpp | 0 .../CCTransitionPageTurn.h | 0 .../CCTransitionProgress.cpp | 0 .../CCTransitionProgress.h | 0 .../user_default => }/CCUserDefault.cpp | 0 .../user_default => }/CCUserDefault.h | 0 .../user_default => }/CCUserDefault.mm | 0 .../CCUserDefaultAndroid.cpp | 0 cocos/2d/{support => }/CCVertex.cpp | 0 cocos/2d/{support => }/CCVertex.h | 0 cocos/2d/{proj.linux => }/Makefile | 0 .../2d/{support/image_support => }/TGAlib.cpp | 0 cocos/2d/{support/image_support => }/TGAlib.h | 0 cocos/2d/{support => }/TransformUtils.cpp | 0 cocos/2d/{support => }/TransformUtils.h | 0 .../2d/{support/zip_support => }/ZipUtils.cpp | 0 cocos/2d/{support/zip_support => }/ZipUtils.h | 0 cocos/2d/{support => }/base64.cpp | 0 cocos/2d/{support => }/base64.h | 0 .../{support/data_support => }/ccCArray.cpp | 0 .../2d/{support/data_support => }/ccCArray.h | 0 cocos/2d/{include => }/ccConfig.h | 0 cocos/2d/{shaders => }/ccGLStateCache.cpp | 0 cocos/2d/{shaders => }/ccGLStateCache.h | 0 cocos/2d/{include => }/ccMacros.h | 0 .../ccShaderEx_SwitchMask_frag.h | 0 ...ccShader_PositionColorLengthTexture_frag.h | 0 ...ccShader_PositionColorLengthTexture_vert.h | 0 .../ccShader_PositionColor_frag.h | 0 .../ccShader_PositionColor_vert.h | 0 .../ccShader_PositionTextureA8Color_frag.h | 0 .../ccShader_PositionTextureA8Color_vert.h | 0 ...hader_PositionTextureColorAlphaTest_frag.h | 0 .../ccShader_PositionTextureColor_frag.h | 0 .../ccShader_PositionTextureColor_vert.h | 0 .../ccShader_PositionTexture_frag.h | 0 .../ccShader_PositionTexture_uColor_frag.h | 0 .../ccShader_PositionTexture_uColor_vert.h | 0 .../ccShader_PositionTexture_vert.h | 0 .../ccShader_Position_uColor_frag.h | 0 .../ccShader_Position_uColor_vert.h | 0 cocos/2d/{shaders => }/ccShaders.cpp | 0 cocos/2d/{shaders => }/ccShaders.h | 0 cocos/2d/{include => }/ccTypes.h | 0 cocos/2d/{support => }/ccUTF8.cpp | 0 cocos/2d/{support => }/ccUTF8.h | 0 cocos/2d/{support => }/ccUtils.h | 0 cocos/2d/{include => }/cocos2d.h | 0 cocos/2d/{proj.win32 => }/cocos2d.vcxproj | 0 .../{proj.win32 => }/cocos2d.vcxproj.filters | 0 .../2d/{proj.win32 => }/cocos2d.vcxproj.user | 0 cocos/2d/{proj.linux => }/cocos2dx.mk | 0 cocos/2d/{proj.win32 => }/cocos2dx.props | 0 cocos/2d/{particle-nodes => }/firePngData.h | 0 cocos/2d/proj.linux/.cproject | 602 ----- cocos/2d/proj.linux/.project | 256 -- cocos/2d/proj.linux/cocos2dx.prf | 37 - cocos/2d/proj.linux/cocos2dx.pri | 70 - cocos/2d/support/ccUtils.cpp | 39 - cocos/2d/support/tinyxml2/tinyxml2.cpp | 2101 ---------------- cocos/2d/support/tinyxml2/tinyxml2.h | 1914 --------------- cocos/2d/support/zip_support/ioapi.cpp | 245 -- cocos/2d/support/zip_support/ioapi.h | 201 -- cocos/2d/support/zip_support/unzip.cpp | 2161 ----------------- cocos/2d/support/zip_support/unzip.h | 455 ---- cocos/2d/{support/data_support => }/uthash.h | 0 cocos/2d/{support/data_support => }/utlist.h | 0 cocos/platform/CCPlatformConfig.h | 140 -- cocos/platform/CCPlatformMacros.h | 301 --- cocos/platform/cocoa/CCAffineTransform.cpp | 132 - cocos/platform/cocoa/CCAffineTransform.h | 63 - cocos/platform/cocoa/CCArray.cpp | 754 ------ cocos/platform/cocoa/CCArray.h | 557 ----- cocos/platform/cocoa/CCAutoreleasePool.cpp | 204 -- cocos/platform/cocoa/CCAutoreleasePool.h | 181 -- cocos/platform/cocoa/CCBool.h | 70 - cocos/platform/cocoa/CCData.cpp | 61 - cocos/platform/cocoa/CCData.h | 88 - cocos/platform/cocoa/CCDataVisitor.cpp | 240 -- cocos/platform/cocoa/CCDataVisitor.h | 117 - cocos/platform/cocoa/CCDictionary.cpp | 454 ---- cocos/platform/cocoa/CCDictionary.h | 458 ---- cocos/platform/cocoa/CCDouble.h | 70 - cocos/platform/cocoa/CCFloat.h | 71 - cocos/platform/cocoa/CCGeometry.cpp | 463 ---- cocos/platform/cocoa/CCGeometry.h | 564 ----- cocos/platform/cocoa/CCInteger.h | 79 - cocos/platform/cocoa/CCNS.cpp | 185 -- cocos/platform/cocoa/CCNS.h | 80 - cocos/platform/cocoa/CCObject.cpp | 93 - cocos/platform/cocoa/CCObject.h | 216 -- cocos/platform/cocoa/CCSet.cpp | 166 -- cocos/platform/cocoa/CCSet.h | 119 - cocos/platform/cocoa/CCString.cpp | 277 --- cocos/platform/cocoa/CCString.h | 210 -- 264 files changed, 14494 deletions(-) rename cocos/2d/{actions => }/CCAction.cpp (100%) rename cocos/2d/{actions => }/CCAction.h (100%) rename cocos/2d/{actions => }/CCActionCamera.cpp (100%) rename cocos/2d/{actions => }/CCActionCamera.h (100%) rename cocos/2d/{actions => }/CCActionCatmullRom.cpp (100%) rename cocos/2d/{actions => }/CCActionCatmullRom.h (100%) rename cocos/2d/{actions => }/CCActionEase.cpp (100%) rename cocos/2d/{actions => }/CCActionEase.h (100%) rename cocos/2d/{actions => }/CCActionGrid.cpp (100%) rename cocos/2d/{actions => }/CCActionGrid.h (100%) rename cocos/2d/{actions => }/CCActionGrid3D.cpp (100%) rename cocos/2d/{actions => }/CCActionGrid3D.h (100%) rename cocos/2d/{actions => }/CCActionInstant.cpp (100%) rename cocos/2d/{actions => }/CCActionInstant.h (100%) rename cocos/2d/{actions => }/CCActionInterval.cpp (100%) rename cocos/2d/{actions => }/CCActionInterval.h (100%) rename cocos/2d/{actions => }/CCActionManager.cpp (100%) rename cocos/2d/{actions => }/CCActionManager.h (100%) rename cocos/2d/{actions => }/CCActionPageTurn3D.cpp (100%) rename cocos/2d/{actions => }/CCActionPageTurn3D.h (100%) rename cocos/2d/{actions => }/CCActionProgressTimer.cpp (100%) rename cocos/2d/{actions => }/CCActionProgressTimer.h (100%) rename cocos/2d/{actions => }/CCActionTiledGrid.cpp (100%) rename cocos/2d/{actions => }/CCActionTiledGrid.h (100%) rename cocos/2d/{actions => }/CCActionTween.cpp (100%) rename cocos/2d/{actions => }/CCActionTween.h (100%) rename cocos/2d/{sprite-nodes => }/CCAnimation.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCAnimation.h (100%) rename cocos/2d/{sprite-nodes => }/CCAnimationCache.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCAnimationCache.h (100%) rename cocos/2d/{base-nodes => }/CCAtlasNode.cpp (100%) rename cocos/2d/{base-nodes => }/CCAtlasNode.h (100%) rename cocos/2d/{misc-nodes => }/CCClippingNode.cpp (100%) rename cocos/2d/{misc-nodes => }/CCClippingNode.h (100%) rename cocos/2d/{support/component => }/CCComponent.cpp (100%) rename cocos/2d/{support/component => }/CCComponent.h (100%) rename cocos/2d/{support/component => }/CCComponentContainer.cpp (100%) rename cocos/2d/{support/component => }/CCComponentContainer.h (100%) rename cocos/2d/{include => }/CCDeprecated.h (100%) rename cocos/2d/{draw-nodes => }/CCDrawNode.cpp (100%) rename cocos/2d/{draw-nodes => }/CCDrawNode.h (100%) rename cocos/2d/{draw-nodes => }/CCDrawingPrimitives.cpp (100%) rename cocos/2d/{draw-nodes => }/CCDrawingPrimitives.h (100%) rename cocos/2d/{event-dispatcher => }/CCEvent.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEvent.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventAcceleration.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventAcceleration.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventCustom.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventCustom.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventDispatcher.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventDispatcher.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventKeyboard.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventKeyboard.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventListener.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventListener.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerAcceleration.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerAcceleration.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerCustom.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerCustom.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerKeyboard.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerKeyboard.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerTouch.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventListenerTouch.h (100%) rename cocos/2d/{event-dispatcher => }/CCEventTouch.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCEventTouch.h (100%) rename cocos/2d/{include => }/CCEventType.h (100%) rename cocos/2d/{label-nodes => }/CCFont.cpp (100%) rename cocos/2d/{label-nodes => }/CCFont.h (100%) rename cocos/2d/{label-nodes => }/CCFontAtlas.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontAtlas.h (100%) rename cocos/2d/{label-nodes => }/CCFontAtlasCache.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontAtlasCache.h (100%) rename cocos/2d/{label-nodes => }/CCFontAtlasFactory.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontAtlasFactory.h (100%) rename cocos/2d/{label-nodes => }/CCFontDefinition.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontDefinition.h (100%) rename cocos/2d/{label-nodes => }/CCFontFNT.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontFNT.h (100%) rename cocos/2d/{label-nodes => }/CCFontFreeType.cpp (100%) rename cocos/2d/{label-nodes => }/CCFontFreeType.h (100%) rename cocos/2d/{base-nodes => }/CCGLBufferedNode.cpp (100%) rename cocos/2d/{base-nodes => }/CCGLBufferedNode.h (100%) rename cocos/2d/{shaders => }/CCGLProgram.cpp (100%) rename cocos/2d/{shaders => }/CCGLProgram.h (100%) rename cocos/2d/{effects => }/CCGrabber.cpp (100%) rename cocos/2d/{effects => }/CCGrabber.h (100%) rename cocos/2d/{effects => }/CCGrid.cpp (100%) rename cocos/2d/{effects => }/CCGrid.h (100%) rename cocos/2d/{text-input-node => }/CCIMEDelegate.h (100%) rename cocos/2d/{text-input-node => }/CCIMEDispatcher.cpp (100%) rename cocos/2d/{text-input-node => }/CCIMEDispatcher.h (100%) rename cocos/2d/{label-nodes => }/CCLabel.cpp (100%) rename cocos/2d/{label-nodes => }/CCLabel.h (100%) rename cocos/2d/{label-nodes => }/CCLabelAtlas.cpp (100%) rename cocos/2d/{label-nodes => }/CCLabelAtlas.h (100%) rename cocos/2d/{label-nodes => }/CCLabelBMFont.cpp (100%) rename cocos/2d/{label-nodes => }/CCLabelBMFont.h (100%) rename cocos/2d/{label-nodes => }/CCLabelTTF.cpp (100%) rename cocos/2d/{label-nodes => }/CCLabelTTF.h (100%) rename cocos/2d/{label-nodes => }/CCLabelTextFormatProtocol.h (100%) rename cocos/2d/{label-nodes => }/CCLabelTextFormatter.cpp (100%) rename cocos/2d/{label-nodes => }/CCLabelTextFormatter.h (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCLayer.cpp (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCLayer.h (100%) rename cocos/2d/{menu-nodes => }/CCMenu.cpp (100%) rename cocos/2d/{menu-nodes => }/CCMenu.h (100%) rename cocos/2d/{menu-nodes => }/CCMenuItem.cpp (100%) rename cocos/2d/{menu-nodes => }/CCMenuItem.h (100%) rename cocos/2d/{misc-nodes => }/CCMotionStreak.cpp (100%) rename cocos/2d/{misc-nodes => }/CCMotionStreak.h (100%) rename cocos/2d/{base-nodes => }/CCNode.cpp (100%) rename cocos/2d/{base-nodes => }/CCNode.h (100%) rename cocos/2d/{support => }/CCNotificationCenter.cpp (100%) rename cocos/2d/{support => }/CCNotificationCenter.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCParallaxNode.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCParallaxNode.h (100%) rename cocos/2d/{particle-nodes => }/CCParticleBatchNode.cpp (100%) rename cocos/2d/{particle-nodes => }/CCParticleBatchNode.h (100%) rename cocos/2d/{particle-nodes => }/CCParticleExamples.cpp (100%) rename cocos/2d/{particle-nodes => }/CCParticleExamples.h (100%) rename cocos/2d/{particle-nodes => }/CCParticleSystem.cpp (100%) rename cocos/2d/{particle-nodes => }/CCParticleSystem.h (100%) rename cocos/2d/{particle-nodes => }/CCParticleSystemQuad.cpp (100%) rename cocos/2d/{particle-nodes => }/CCParticleSystemQuad.h (100%) rename cocos/2d/{support => }/CCProfiling.cpp (100%) rename cocos/2d/{support => }/CCProfiling.h (100%) rename cocos/2d/{misc-nodes => }/CCProgressTimer.cpp (100%) rename cocos/2d/{misc-nodes => }/CCProgressTimer.h (100%) rename cocos/2d/{include => }/CCProtocols.h (100%) rename cocos/2d/{misc-nodes => }/CCRenderTexture.cpp (100%) rename cocos/2d/{misc-nodes => }/CCRenderTexture.h (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCScene.cpp (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCScene.h (100%) rename cocos/2d/{script-support => }/CCScriptSupport.cpp (100%) rename cocos/2d/{script-support => }/CCScriptSupport.h (100%) rename cocos/2d/{shaders => }/CCShaderCache.cpp (100%) rename cocos/2d/{shaders => }/CCShaderCache.h (100%) rename cocos/2d/{sprite-nodes => }/CCSprite.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCSprite.h (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteBatchNode.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteBatchNode.h (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteFrame.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteFrame.h (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteFrameCache.cpp (100%) rename cocos/2d/{sprite-nodes => }/CCSpriteFrameCache.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXLayer.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXLayer.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXObjectGroup.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXObjectGroup.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXTiledMap.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXTiledMap.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXXMLParser.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTMXXMLParser.h (100%) rename cocos/2d/{text-input-node => }/CCTextFieldTTF.cpp (100%) rename cocos/2d/{text-input-node => }/CCTextFieldTTF.h (100%) rename cocos/2d/{label-nodes => }/CCTextImage.cpp (100%) rename cocos/2d/{label-nodes => }/CCTextImage.h (100%) rename cocos/2d/{textures => }/CCTexture2D.cpp (100%) rename cocos/2d/{textures => }/CCTexture2D.h (100%) rename cocos/2d/{textures => }/CCTextureAtlas.cpp (100%) rename cocos/2d/{textures => }/CCTextureAtlas.h (100%) rename cocos/2d/{textures => }/CCTextureCache.cpp (100%) rename cocos/2d/{textures => }/CCTextureCache.h (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTileMapAtlas.cpp (100%) rename cocos/2d/{tilemap-parallax-nodes => }/CCTileMapAtlas.h (100%) rename cocos/2d/{event-dispatcher => }/CCTouch.cpp (100%) rename cocos/2d/{event-dispatcher => }/CCTouch.h (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransition.cpp (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransition.h (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransitionPageTurn.cpp (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransitionPageTurn.h (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransitionProgress.cpp (100%) rename cocos/2d/{layers-scenes-transitions-nodes => }/CCTransitionProgress.h (100%) rename cocos/2d/{support/user_default => }/CCUserDefault.cpp (100%) rename cocos/2d/{support/user_default => }/CCUserDefault.h (100%) rename cocos/2d/{support/user_default => }/CCUserDefault.mm (100%) rename cocos/2d/{support/user_default => }/CCUserDefaultAndroid.cpp (100%) rename cocos/2d/{support => }/CCVertex.cpp (100%) rename cocos/2d/{support => }/CCVertex.h (100%) rename cocos/2d/{proj.linux => }/Makefile (100%) rename cocos/2d/{support/image_support => }/TGAlib.cpp (100%) rename cocos/2d/{support/image_support => }/TGAlib.h (100%) rename cocos/2d/{support => }/TransformUtils.cpp (100%) rename cocos/2d/{support => }/TransformUtils.h (100%) rename cocos/2d/{support/zip_support => }/ZipUtils.cpp (100%) rename cocos/2d/{support/zip_support => }/ZipUtils.h (100%) rename cocos/2d/{support => }/base64.cpp (100%) rename cocos/2d/{support => }/base64.h (100%) rename cocos/2d/{support/data_support => }/ccCArray.cpp (100%) rename cocos/2d/{support/data_support => }/ccCArray.h (100%) rename cocos/2d/{include => }/ccConfig.h (100%) rename cocos/2d/{shaders => }/ccGLStateCache.cpp (100%) rename cocos/2d/{shaders => }/ccGLStateCache.h (100%) rename cocos/2d/{include => }/ccMacros.h (100%) rename cocos/2d/{shaders => }/ccShaderEx_SwitchMask_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionColorLengthTexture_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionColorLengthTexture_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionColor_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionColor_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTextureA8Color_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTextureA8Color_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTextureColorAlphaTest_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTextureColor_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTextureColor_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTexture_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTexture_uColor_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTexture_uColor_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_PositionTexture_vert.h (100%) rename cocos/2d/{shaders => }/ccShader_Position_uColor_frag.h (100%) rename cocos/2d/{shaders => }/ccShader_Position_uColor_vert.h (100%) rename cocos/2d/{shaders => }/ccShaders.cpp (100%) rename cocos/2d/{shaders => }/ccShaders.h (100%) rename cocos/2d/{include => }/ccTypes.h (100%) rename cocos/2d/{support => }/ccUTF8.cpp (100%) rename cocos/2d/{support => }/ccUTF8.h (100%) rename cocos/2d/{support => }/ccUtils.h (100%) rename cocos/2d/{include => }/cocos2d.h (100%) rename cocos/2d/{proj.win32 => }/cocos2d.vcxproj (100%) rename cocos/2d/{proj.win32 => }/cocos2d.vcxproj.filters (100%) rename cocos/2d/{proj.win32 => }/cocos2d.vcxproj.user (100%) rename cocos/2d/{proj.linux => }/cocos2dx.mk (100%) rename cocos/2d/{proj.win32 => }/cocos2dx.props (100%) rename cocos/2d/{particle-nodes => }/firePngData.h (100%) delete mode 100755 cocos/2d/proj.linux/.cproject delete mode 100755 cocos/2d/proj.linux/.project delete mode 100644 cocos/2d/proj.linux/cocos2dx.prf delete mode 100644 cocos/2d/proj.linux/cocos2dx.pri delete mode 100644 cocos/2d/support/ccUtils.cpp delete mode 100644 cocos/2d/support/tinyxml2/tinyxml2.cpp delete mode 100644 cocos/2d/support/tinyxml2/tinyxml2.h delete mode 100644 cocos/2d/support/zip_support/ioapi.cpp delete mode 100644 cocos/2d/support/zip_support/ioapi.h delete mode 100644 cocos/2d/support/zip_support/unzip.cpp delete mode 100644 cocos/2d/support/zip_support/unzip.h rename cocos/2d/{support/data_support => }/uthash.h (100%) rename cocos/2d/{support/data_support => }/utlist.h (100%) delete mode 100644 cocos/platform/CCPlatformConfig.h delete mode 100644 cocos/platform/CCPlatformMacros.h delete mode 100644 cocos/platform/cocoa/CCAffineTransform.cpp delete mode 100644 cocos/platform/cocoa/CCAffineTransform.h delete mode 100644 cocos/platform/cocoa/CCArray.cpp delete mode 100644 cocos/platform/cocoa/CCArray.h delete mode 100644 cocos/platform/cocoa/CCAutoreleasePool.cpp delete mode 100644 cocos/platform/cocoa/CCAutoreleasePool.h delete mode 100644 cocos/platform/cocoa/CCBool.h delete mode 100644 cocos/platform/cocoa/CCData.cpp delete mode 100644 cocos/platform/cocoa/CCData.h delete mode 100644 cocos/platform/cocoa/CCDataVisitor.cpp delete mode 100644 cocos/platform/cocoa/CCDataVisitor.h delete mode 100644 cocos/platform/cocoa/CCDictionary.cpp delete mode 100644 cocos/platform/cocoa/CCDictionary.h delete mode 100644 cocos/platform/cocoa/CCDouble.h delete mode 100644 cocos/platform/cocoa/CCFloat.h delete mode 100644 cocos/platform/cocoa/CCGeometry.cpp delete mode 100644 cocos/platform/cocoa/CCGeometry.h delete mode 100644 cocos/platform/cocoa/CCInteger.h delete mode 100644 cocos/platform/cocoa/CCNS.cpp delete mode 100644 cocos/platform/cocoa/CCNS.h delete mode 100644 cocos/platform/cocoa/CCObject.cpp delete mode 100644 cocos/platform/cocoa/CCObject.h delete mode 100644 cocos/platform/cocoa/CCSet.cpp delete mode 100644 cocos/platform/cocoa/CCSet.h delete mode 100644 cocos/platform/cocoa/CCString.cpp delete mode 100644 cocos/platform/cocoa/CCString.h diff --git a/cocos/2d/actions/CCAction.cpp b/cocos/2d/CCAction.cpp similarity index 100% rename from cocos/2d/actions/CCAction.cpp rename to cocos/2d/CCAction.cpp diff --git a/cocos/2d/actions/CCAction.h b/cocos/2d/CCAction.h similarity index 100% rename from cocos/2d/actions/CCAction.h rename to cocos/2d/CCAction.h diff --git a/cocos/2d/actions/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp similarity index 100% rename from cocos/2d/actions/CCActionCamera.cpp rename to cocos/2d/CCActionCamera.cpp diff --git a/cocos/2d/actions/CCActionCamera.h b/cocos/2d/CCActionCamera.h similarity index 100% rename from cocos/2d/actions/CCActionCamera.h rename to cocos/2d/CCActionCamera.h diff --git a/cocos/2d/actions/CCActionCatmullRom.cpp b/cocos/2d/CCActionCatmullRom.cpp similarity index 100% rename from cocos/2d/actions/CCActionCatmullRom.cpp rename to cocos/2d/CCActionCatmullRom.cpp diff --git a/cocos/2d/actions/CCActionCatmullRom.h b/cocos/2d/CCActionCatmullRom.h similarity index 100% rename from cocos/2d/actions/CCActionCatmullRom.h rename to cocos/2d/CCActionCatmullRom.h diff --git a/cocos/2d/actions/CCActionEase.cpp b/cocos/2d/CCActionEase.cpp similarity index 100% rename from cocos/2d/actions/CCActionEase.cpp rename to cocos/2d/CCActionEase.cpp diff --git a/cocos/2d/actions/CCActionEase.h b/cocos/2d/CCActionEase.h similarity index 100% rename from cocos/2d/actions/CCActionEase.h rename to cocos/2d/CCActionEase.h diff --git a/cocos/2d/actions/CCActionGrid.cpp b/cocos/2d/CCActionGrid.cpp similarity index 100% rename from cocos/2d/actions/CCActionGrid.cpp rename to cocos/2d/CCActionGrid.cpp diff --git a/cocos/2d/actions/CCActionGrid.h b/cocos/2d/CCActionGrid.h similarity index 100% rename from cocos/2d/actions/CCActionGrid.h rename to cocos/2d/CCActionGrid.h diff --git a/cocos/2d/actions/CCActionGrid3D.cpp b/cocos/2d/CCActionGrid3D.cpp similarity index 100% rename from cocos/2d/actions/CCActionGrid3D.cpp rename to cocos/2d/CCActionGrid3D.cpp diff --git a/cocos/2d/actions/CCActionGrid3D.h b/cocos/2d/CCActionGrid3D.h similarity index 100% rename from cocos/2d/actions/CCActionGrid3D.h rename to cocos/2d/CCActionGrid3D.h diff --git a/cocos/2d/actions/CCActionInstant.cpp b/cocos/2d/CCActionInstant.cpp similarity index 100% rename from cocos/2d/actions/CCActionInstant.cpp rename to cocos/2d/CCActionInstant.cpp diff --git a/cocos/2d/actions/CCActionInstant.h b/cocos/2d/CCActionInstant.h similarity index 100% rename from cocos/2d/actions/CCActionInstant.h rename to cocos/2d/CCActionInstant.h diff --git a/cocos/2d/actions/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp similarity index 100% rename from cocos/2d/actions/CCActionInterval.cpp rename to cocos/2d/CCActionInterval.cpp diff --git a/cocos/2d/actions/CCActionInterval.h b/cocos/2d/CCActionInterval.h similarity index 100% rename from cocos/2d/actions/CCActionInterval.h rename to cocos/2d/CCActionInterval.h diff --git a/cocos/2d/actions/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp similarity index 100% rename from cocos/2d/actions/CCActionManager.cpp rename to cocos/2d/CCActionManager.cpp diff --git a/cocos/2d/actions/CCActionManager.h b/cocos/2d/CCActionManager.h similarity index 100% rename from cocos/2d/actions/CCActionManager.h rename to cocos/2d/CCActionManager.h diff --git a/cocos/2d/actions/CCActionPageTurn3D.cpp b/cocos/2d/CCActionPageTurn3D.cpp similarity index 100% rename from cocos/2d/actions/CCActionPageTurn3D.cpp rename to cocos/2d/CCActionPageTurn3D.cpp diff --git a/cocos/2d/actions/CCActionPageTurn3D.h b/cocos/2d/CCActionPageTurn3D.h similarity index 100% rename from cocos/2d/actions/CCActionPageTurn3D.h rename to cocos/2d/CCActionPageTurn3D.h diff --git a/cocos/2d/actions/CCActionProgressTimer.cpp b/cocos/2d/CCActionProgressTimer.cpp similarity index 100% rename from cocos/2d/actions/CCActionProgressTimer.cpp rename to cocos/2d/CCActionProgressTimer.cpp diff --git a/cocos/2d/actions/CCActionProgressTimer.h b/cocos/2d/CCActionProgressTimer.h similarity index 100% rename from cocos/2d/actions/CCActionProgressTimer.h rename to cocos/2d/CCActionProgressTimer.h diff --git a/cocos/2d/actions/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp similarity index 100% rename from cocos/2d/actions/CCActionTiledGrid.cpp rename to cocos/2d/CCActionTiledGrid.cpp diff --git a/cocos/2d/actions/CCActionTiledGrid.h b/cocos/2d/CCActionTiledGrid.h similarity index 100% rename from cocos/2d/actions/CCActionTiledGrid.h rename to cocos/2d/CCActionTiledGrid.h diff --git a/cocos/2d/actions/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp similarity index 100% rename from cocos/2d/actions/CCActionTween.cpp rename to cocos/2d/CCActionTween.cpp diff --git a/cocos/2d/actions/CCActionTween.h b/cocos/2d/CCActionTween.h similarity index 100% rename from cocos/2d/actions/CCActionTween.h rename to cocos/2d/CCActionTween.h diff --git a/cocos/2d/sprite-nodes/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCAnimation.cpp rename to cocos/2d/CCAnimation.cpp diff --git a/cocos/2d/sprite-nodes/CCAnimation.h b/cocos/2d/CCAnimation.h similarity index 100% rename from cocos/2d/sprite-nodes/CCAnimation.h rename to cocos/2d/CCAnimation.h diff --git a/cocos/2d/sprite-nodes/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCAnimationCache.cpp rename to cocos/2d/CCAnimationCache.cpp diff --git a/cocos/2d/sprite-nodes/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h similarity index 100% rename from cocos/2d/sprite-nodes/CCAnimationCache.h rename to cocos/2d/CCAnimationCache.h diff --git a/cocos/2d/base-nodes/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp similarity index 100% rename from cocos/2d/base-nodes/CCAtlasNode.cpp rename to cocos/2d/CCAtlasNode.cpp diff --git a/cocos/2d/base-nodes/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h similarity index 100% rename from cocos/2d/base-nodes/CCAtlasNode.h rename to cocos/2d/CCAtlasNode.h diff --git a/cocos/2d/misc-nodes/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp similarity index 100% rename from cocos/2d/misc-nodes/CCClippingNode.cpp rename to cocos/2d/CCClippingNode.cpp diff --git a/cocos/2d/misc-nodes/CCClippingNode.h b/cocos/2d/CCClippingNode.h similarity index 100% rename from cocos/2d/misc-nodes/CCClippingNode.h rename to cocos/2d/CCClippingNode.h diff --git a/cocos/2d/support/component/CCComponent.cpp b/cocos/2d/CCComponent.cpp similarity index 100% rename from cocos/2d/support/component/CCComponent.cpp rename to cocos/2d/CCComponent.cpp diff --git a/cocos/2d/support/component/CCComponent.h b/cocos/2d/CCComponent.h similarity index 100% rename from cocos/2d/support/component/CCComponent.h rename to cocos/2d/CCComponent.h diff --git a/cocos/2d/support/component/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp similarity index 100% rename from cocos/2d/support/component/CCComponentContainer.cpp rename to cocos/2d/CCComponentContainer.cpp diff --git a/cocos/2d/support/component/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h similarity index 100% rename from cocos/2d/support/component/CCComponentContainer.h rename to cocos/2d/CCComponentContainer.h diff --git a/cocos/2d/include/CCDeprecated.h b/cocos/2d/CCDeprecated.h similarity index 100% rename from cocos/2d/include/CCDeprecated.h rename to cocos/2d/CCDeprecated.h diff --git a/cocos/2d/draw-nodes/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp similarity index 100% rename from cocos/2d/draw-nodes/CCDrawNode.cpp rename to cocos/2d/CCDrawNode.cpp diff --git a/cocos/2d/draw-nodes/CCDrawNode.h b/cocos/2d/CCDrawNode.h similarity index 100% rename from cocos/2d/draw-nodes/CCDrawNode.h rename to cocos/2d/CCDrawNode.h diff --git a/cocos/2d/draw-nodes/CCDrawingPrimitives.cpp b/cocos/2d/CCDrawingPrimitives.cpp similarity index 100% rename from cocos/2d/draw-nodes/CCDrawingPrimitives.cpp rename to cocos/2d/CCDrawingPrimitives.cpp diff --git a/cocos/2d/draw-nodes/CCDrawingPrimitives.h b/cocos/2d/CCDrawingPrimitives.h similarity index 100% rename from cocos/2d/draw-nodes/CCDrawingPrimitives.h rename to cocos/2d/CCDrawingPrimitives.h diff --git a/cocos/2d/event-dispatcher/CCEvent.cpp b/cocos/2d/CCEvent.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEvent.cpp rename to cocos/2d/CCEvent.cpp diff --git a/cocos/2d/event-dispatcher/CCEvent.h b/cocos/2d/CCEvent.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEvent.h rename to cocos/2d/CCEvent.h diff --git a/cocos/2d/event-dispatcher/CCEventAcceleration.cpp b/cocos/2d/CCEventAcceleration.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventAcceleration.cpp rename to cocos/2d/CCEventAcceleration.cpp diff --git a/cocos/2d/event-dispatcher/CCEventAcceleration.h b/cocos/2d/CCEventAcceleration.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventAcceleration.h rename to cocos/2d/CCEventAcceleration.h diff --git a/cocos/2d/event-dispatcher/CCEventCustom.cpp b/cocos/2d/CCEventCustom.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventCustom.cpp rename to cocos/2d/CCEventCustom.cpp diff --git a/cocos/2d/event-dispatcher/CCEventCustom.h b/cocos/2d/CCEventCustom.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventCustom.h rename to cocos/2d/CCEventCustom.h diff --git a/cocos/2d/event-dispatcher/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventDispatcher.cpp rename to cocos/2d/CCEventDispatcher.cpp diff --git a/cocos/2d/event-dispatcher/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventDispatcher.h rename to cocos/2d/CCEventDispatcher.h diff --git a/cocos/2d/event-dispatcher/CCEventKeyboard.cpp b/cocos/2d/CCEventKeyboard.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventKeyboard.cpp rename to cocos/2d/CCEventKeyboard.cpp diff --git a/cocos/2d/event-dispatcher/CCEventKeyboard.h b/cocos/2d/CCEventKeyboard.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventKeyboard.h rename to cocos/2d/CCEventKeyboard.h diff --git a/cocos/2d/event-dispatcher/CCEventListener.cpp b/cocos/2d/CCEventListener.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListener.cpp rename to cocos/2d/CCEventListener.cpp diff --git a/cocos/2d/event-dispatcher/CCEventListener.h b/cocos/2d/CCEventListener.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListener.h rename to cocos/2d/CCEventListener.h diff --git a/cocos/2d/event-dispatcher/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerAcceleration.cpp rename to cocos/2d/CCEventListenerAcceleration.cpp diff --git a/cocos/2d/event-dispatcher/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerAcceleration.h rename to cocos/2d/CCEventListenerAcceleration.h diff --git a/cocos/2d/event-dispatcher/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerCustom.cpp rename to cocos/2d/CCEventListenerCustom.cpp diff --git a/cocos/2d/event-dispatcher/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerCustom.h rename to cocos/2d/CCEventListenerCustom.h diff --git a/cocos/2d/event-dispatcher/CCEventListenerKeyboard.cpp b/cocos/2d/CCEventListenerKeyboard.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerKeyboard.cpp rename to cocos/2d/CCEventListenerKeyboard.cpp diff --git a/cocos/2d/event-dispatcher/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerKeyboard.h rename to cocos/2d/CCEventListenerKeyboard.h diff --git a/cocos/2d/event-dispatcher/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerTouch.cpp rename to cocos/2d/CCEventListenerTouch.cpp diff --git a/cocos/2d/event-dispatcher/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventListenerTouch.h rename to cocos/2d/CCEventListenerTouch.h diff --git a/cocos/2d/event-dispatcher/CCEventTouch.cpp b/cocos/2d/CCEventTouch.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCEventTouch.cpp rename to cocos/2d/CCEventTouch.cpp diff --git a/cocos/2d/event-dispatcher/CCEventTouch.h b/cocos/2d/CCEventTouch.h similarity index 100% rename from cocos/2d/event-dispatcher/CCEventTouch.h rename to cocos/2d/CCEventTouch.h diff --git a/cocos/2d/include/CCEventType.h b/cocos/2d/CCEventType.h similarity index 100% rename from cocos/2d/include/CCEventType.h rename to cocos/2d/CCEventType.h diff --git a/cocos/2d/label-nodes/CCFont.cpp b/cocos/2d/CCFont.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFont.cpp rename to cocos/2d/CCFont.cpp diff --git a/cocos/2d/label-nodes/CCFont.h b/cocos/2d/CCFont.h similarity index 100% rename from cocos/2d/label-nodes/CCFont.h rename to cocos/2d/CCFont.h diff --git a/cocos/2d/label-nodes/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlas.cpp rename to cocos/2d/CCFontAtlas.cpp diff --git a/cocos/2d/label-nodes/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlas.h rename to cocos/2d/CCFontAtlas.h diff --git a/cocos/2d/label-nodes/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlasCache.cpp rename to cocos/2d/CCFontAtlasCache.cpp diff --git a/cocos/2d/label-nodes/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlasCache.h rename to cocos/2d/CCFontAtlasCache.h diff --git a/cocos/2d/label-nodes/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlasFactory.cpp rename to cocos/2d/CCFontAtlasFactory.cpp diff --git a/cocos/2d/label-nodes/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h similarity index 100% rename from cocos/2d/label-nodes/CCFontAtlasFactory.h rename to cocos/2d/CCFontAtlasFactory.h diff --git a/cocos/2d/label-nodes/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontDefinition.cpp rename to cocos/2d/CCFontDefinition.cpp diff --git a/cocos/2d/label-nodes/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h similarity index 100% rename from cocos/2d/label-nodes/CCFontDefinition.h rename to cocos/2d/CCFontDefinition.h diff --git a/cocos/2d/label-nodes/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontFNT.cpp rename to cocos/2d/CCFontFNT.cpp diff --git a/cocos/2d/label-nodes/CCFontFNT.h b/cocos/2d/CCFontFNT.h similarity index 100% rename from cocos/2d/label-nodes/CCFontFNT.h rename to cocos/2d/CCFontFNT.h diff --git a/cocos/2d/label-nodes/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp similarity index 100% rename from cocos/2d/label-nodes/CCFontFreeType.cpp rename to cocos/2d/CCFontFreeType.cpp diff --git a/cocos/2d/label-nodes/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h similarity index 100% rename from cocos/2d/label-nodes/CCFontFreeType.h rename to cocos/2d/CCFontFreeType.h diff --git a/cocos/2d/base-nodes/CCGLBufferedNode.cpp b/cocos/2d/CCGLBufferedNode.cpp similarity index 100% rename from cocos/2d/base-nodes/CCGLBufferedNode.cpp rename to cocos/2d/CCGLBufferedNode.cpp diff --git a/cocos/2d/base-nodes/CCGLBufferedNode.h b/cocos/2d/CCGLBufferedNode.h similarity index 100% rename from cocos/2d/base-nodes/CCGLBufferedNode.h rename to cocos/2d/CCGLBufferedNode.h diff --git a/cocos/2d/shaders/CCGLProgram.cpp b/cocos/2d/CCGLProgram.cpp similarity index 100% rename from cocos/2d/shaders/CCGLProgram.cpp rename to cocos/2d/CCGLProgram.cpp diff --git a/cocos/2d/shaders/CCGLProgram.h b/cocos/2d/CCGLProgram.h similarity index 100% rename from cocos/2d/shaders/CCGLProgram.h rename to cocos/2d/CCGLProgram.h diff --git a/cocos/2d/effects/CCGrabber.cpp b/cocos/2d/CCGrabber.cpp similarity index 100% rename from cocos/2d/effects/CCGrabber.cpp rename to cocos/2d/CCGrabber.cpp diff --git a/cocos/2d/effects/CCGrabber.h b/cocos/2d/CCGrabber.h similarity index 100% rename from cocos/2d/effects/CCGrabber.h rename to cocos/2d/CCGrabber.h diff --git a/cocos/2d/effects/CCGrid.cpp b/cocos/2d/CCGrid.cpp similarity index 100% rename from cocos/2d/effects/CCGrid.cpp rename to cocos/2d/CCGrid.cpp diff --git a/cocos/2d/effects/CCGrid.h b/cocos/2d/CCGrid.h similarity index 100% rename from cocos/2d/effects/CCGrid.h rename to cocos/2d/CCGrid.h diff --git a/cocos/2d/text-input-node/CCIMEDelegate.h b/cocos/2d/CCIMEDelegate.h similarity index 100% rename from cocos/2d/text-input-node/CCIMEDelegate.h rename to cocos/2d/CCIMEDelegate.h diff --git a/cocos/2d/text-input-node/CCIMEDispatcher.cpp b/cocos/2d/CCIMEDispatcher.cpp similarity index 100% rename from cocos/2d/text-input-node/CCIMEDispatcher.cpp rename to cocos/2d/CCIMEDispatcher.cpp diff --git a/cocos/2d/text-input-node/CCIMEDispatcher.h b/cocos/2d/CCIMEDispatcher.h similarity index 100% rename from cocos/2d/text-input-node/CCIMEDispatcher.h rename to cocos/2d/CCIMEDispatcher.h diff --git a/cocos/2d/label-nodes/CCLabel.cpp b/cocos/2d/CCLabel.cpp similarity index 100% rename from cocos/2d/label-nodes/CCLabel.cpp rename to cocos/2d/CCLabel.cpp diff --git a/cocos/2d/label-nodes/CCLabel.h b/cocos/2d/CCLabel.h similarity index 100% rename from cocos/2d/label-nodes/CCLabel.h rename to cocos/2d/CCLabel.h diff --git a/cocos/2d/label-nodes/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp similarity index 100% rename from cocos/2d/label-nodes/CCLabelAtlas.cpp rename to cocos/2d/CCLabelAtlas.cpp diff --git a/cocos/2d/label-nodes/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h similarity index 100% rename from cocos/2d/label-nodes/CCLabelAtlas.h rename to cocos/2d/CCLabelAtlas.h diff --git a/cocos/2d/label-nodes/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp similarity index 100% rename from cocos/2d/label-nodes/CCLabelBMFont.cpp rename to cocos/2d/CCLabelBMFont.cpp diff --git a/cocos/2d/label-nodes/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h similarity index 100% rename from cocos/2d/label-nodes/CCLabelBMFont.h rename to cocos/2d/CCLabelBMFont.h diff --git a/cocos/2d/label-nodes/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp similarity index 100% rename from cocos/2d/label-nodes/CCLabelTTF.cpp rename to cocos/2d/CCLabelTTF.cpp diff --git a/cocos/2d/label-nodes/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h similarity index 100% rename from cocos/2d/label-nodes/CCLabelTTF.h rename to cocos/2d/CCLabelTTF.h diff --git a/cocos/2d/label-nodes/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h similarity index 100% rename from cocos/2d/label-nodes/CCLabelTextFormatProtocol.h rename to cocos/2d/CCLabelTextFormatProtocol.h diff --git a/cocos/2d/label-nodes/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp similarity index 100% rename from cocos/2d/label-nodes/CCLabelTextFormatter.cpp rename to cocos/2d/CCLabelTextFormatter.cpp diff --git a/cocos/2d/label-nodes/CCLabelTextFormatter.h b/cocos/2d/CCLabelTextFormatter.h similarity index 100% rename from cocos/2d/label-nodes/CCLabelTextFormatter.h rename to cocos/2d/CCLabelTextFormatter.h diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCLayer.cpp b/cocos/2d/CCLayer.cpp similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCLayer.cpp rename to cocos/2d/CCLayer.cpp diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCLayer.h b/cocos/2d/CCLayer.h similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCLayer.h rename to cocos/2d/CCLayer.h diff --git a/cocos/2d/menu-nodes/CCMenu.cpp b/cocos/2d/CCMenu.cpp similarity index 100% rename from cocos/2d/menu-nodes/CCMenu.cpp rename to cocos/2d/CCMenu.cpp diff --git a/cocos/2d/menu-nodes/CCMenu.h b/cocos/2d/CCMenu.h similarity index 100% rename from cocos/2d/menu-nodes/CCMenu.h rename to cocos/2d/CCMenu.h diff --git a/cocos/2d/menu-nodes/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp similarity index 100% rename from cocos/2d/menu-nodes/CCMenuItem.cpp rename to cocos/2d/CCMenuItem.cpp diff --git a/cocos/2d/menu-nodes/CCMenuItem.h b/cocos/2d/CCMenuItem.h similarity index 100% rename from cocos/2d/menu-nodes/CCMenuItem.h rename to cocos/2d/CCMenuItem.h diff --git a/cocos/2d/misc-nodes/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp similarity index 100% rename from cocos/2d/misc-nodes/CCMotionStreak.cpp rename to cocos/2d/CCMotionStreak.cpp diff --git a/cocos/2d/misc-nodes/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h similarity index 100% rename from cocos/2d/misc-nodes/CCMotionStreak.h rename to cocos/2d/CCMotionStreak.h diff --git a/cocos/2d/base-nodes/CCNode.cpp b/cocos/2d/CCNode.cpp similarity index 100% rename from cocos/2d/base-nodes/CCNode.cpp rename to cocos/2d/CCNode.cpp diff --git a/cocos/2d/base-nodes/CCNode.h b/cocos/2d/CCNode.h similarity index 100% rename from cocos/2d/base-nodes/CCNode.h rename to cocos/2d/CCNode.h diff --git a/cocos/2d/support/CCNotificationCenter.cpp b/cocos/2d/CCNotificationCenter.cpp similarity index 100% rename from cocos/2d/support/CCNotificationCenter.cpp rename to cocos/2d/CCNotificationCenter.cpp diff --git a/cocos/2d/support/CCNotificationCenter.h b/cocos/2d/CCNotificationCenter.h similarity index 100% rename from cocos/2d/support/CCNotificationCenter.h rename to cocos/2d/CCNotificationCenter.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCParallaxNode.cpp rename to cocos/2d/CCParallaxNode.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCParallaxNode.h rename to cocos/2d/CCParallaxNode.h diff --git a/cocos/2d/particle-nodes/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp similarity index 100% rename from cocos/2d/particle-nodes/CCParticleBatchNode.cpp rename to cocos/2d/CCParticleBatchNode.cpp diff --git a/cocos/2d/particle-nodes/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h similarity index 100% rename from cocos/2d/particle-nodes/CCParticleBatchNode.h rename to cocos/2d/CCParticleBatchNode.h diff --git a/cocos/2d/particle-nodes/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp similarity index 100% rename from cocos/2d/particle-nodes/CCParticleExamples.cpp rename to cocos/2d/CCParticleExamples.cpp diff --git a/cocos/2d/particle-nodes/CCParticleExamples.h b/cocos/2d/CCParticleExamples.h similarity index 100% rename from cocos/2d/particle-nodes/CCParticleExamples.h rename to cocos/2d/CCParticleExamples.h diff --git a/cocos/2d/particle-nodes/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp similarity index 100% rename from cocos/2d/particle-nodes/CCParticleSystem.cpp rename to cocos/2d/CCParticleSystem.cpp diff --git a/cocos/2d/particle-nodes/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h similarity index 100% rename from cocos/2d/particle-nodes/CCParticleSystem.h rename to cocos/2d/CCParticleSystem.h diff --git a/cocos/2d/particle-nodes/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp similarity index 100% rename from cocos/2d/particle-nodes/CCParticleSystemQuad.cpp rename to cocos/2d/CCParticleSystemQuad.cpp diff --git a/cocos/2d/particle-nodes/CCParticleSystemQuad.h b/cocos/2d/CCParticleSystemQuad.h similarity index 100% rename from cocos/2d/particle-nodes/CCParticleSystemQuad.h rename to cocos/2d/CCParticleSystemQuad.h diff --git a/cocos/2d/support/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp similarity index 100% rename from cocos/2d/support/CCProfiling.cpp rename to cocos/2d/CCProfiling.cpp diff --git a/cocos/2d/support/CCProfiling.h b/cocos/2d/CCProfiling.h similarity index 100% rename from cocos/2d/support/CCProfiling.h rename to cocos/2d/CCProfiling.h diff --git a/cocos/2d/misc-nodes/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp similarity index 100% rename from cocos/2d/misc-nodes/CCProgressTimer.cpp rename to cocos/2d/CCProgressTimer.cpp diff --git a/cocos/2d/misc-nodes/CCProgressTimer.h b/cocos/2d/CCProgressTimer.h similarity index 100% rename from cocos/2d/misc-nodes/CCProgressTimer.h rename to cocos/2d/CCProgressTimer.h diff --git a/cocos/2d/include/CCProtocols.h b/cocos/2d/CCProtocols.h similarity index 100% rename from cocos/2d/include/CCProtocols.h rename to cocos/2d/CCProtocols.h diff --git a/cocos/2d/misc-nodes/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp similarity index 100% rename from cocos/2d/misc-nodes/CCRenderTexture.cpp rename to cocos/2d/CCRenderTexture.cpp diff --git a/cocos/2d/misc-nodes/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h similarity index 100% rename from cocos/2d/misc-nodes/CCRenderTexture.h rename to cocos/2d/CCRenderTexture.h diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCScene.cpp b/cocos/2d/CCScene.cpp similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCScene.cpp rename to cocos/2d/CCScene.cpp diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCScene.h b/cocos/2d/CCScene.h similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCScene.h rename to cocos/2d/CCScene.h diff --git a/cocos/2d/script-support/CCScriptSupport.cpp b/cocos/2d/CCScriptSupport.cpp similarity index 100% rename from cocos/2d/script-support/CCScriptSupport.cpp rename to cocos/2d/CCScriptSupport.cpp diff --git a/cocos/2d/script-support/CCScriptSupport.h b/cocos/2d/CCScriptSupport.h similarity index 100% rename from cocos/2d/script-support/CCScriptSupport.h rename to cocos/2d/CCScriptSupport.h diff --git a/cocos/2d/shaders/CCShaderCache.cpp b/cocos/2d/CCShaderCache.cpp similarity index 100% rename from cocos/2d/shaders/CCShaderCache.cpp rename to cocos/2d/CCShaderCache.cpp diff --git a/cocos/2d/shaders/CCShaderCache.h b/cocos/2d/CCShaderCache.h similarity index 100% rename from cocos/2d/shaders/CCShaderCache.h rename to cocos/2d/CCShaderCache.h diff --git a/cocos/2d/sprite-nodes/CCSprite.cpp b/cocos/2d/CCSprite.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCSprite.cpp rename to cocos/2d/CCSprite.cpp diff --git a/cocos/2d/sprite-nodes/CCSprite.h b/cocos/2d/CCSprite.h similarity index 100% rename from cocos/2d/sprite-nodes/CCSprite.h rename to cocos/2d/CCSprite.h diff --git a/cocos/2d/sprite-nodes/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteBatchNode.cpp rename to cocos/2d/CCSpriteBatchNode.cpp diff --git a/cocos/2d/sprite-nodes/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteBatchNode.h rename to cocos/2d/CCSpriteBatchNode.h diff --git a/cocos/2d/sprite-nodes/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteFrame.cpp rename to cocos/2d/CCSpriteFrame.cpp diff --git a/cocos/2d/sprite-nodes/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteFrame.h rename to cocos/2d/CCSpriteFrame.h diff --git a/cocos/2d/sprite-nodes/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteFrameCache.cpp rename to cocos/2d/CCSpriteFrameCache.cpp diff --git a/cocos/2d/sprite-nodes/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h similarity index 100% rename from cocos/2d/sprite-nodes/CCSpriteFrameCache.h rename to cocos/2d/CCSpriteFrameCache.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXLayer.cpp rename to cocos/2d/CCTMXLayer.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXLayer.h b/cocos/2d/CCTMXLayer.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXLayer.h rename to cocos/2d/CCTMXLayer.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXObjectGroup.cpp rename to cocos/2d/CCTMXObjectGroup.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXObjectGroup.h rename to cocos/2d/CCTMXObjectGroup.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXTiledMap.cpp rename to cocos/2d/CCTMXTiledMap.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXTiledMap.h rename to cocos/2d/CCTMXTiledMap.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXXMLParser.cpp rename to cocos/2d/CCTMXXMLParser.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTMXXMLParser.h rename to cocos/2d/CCTMXXMLParser.h diff --git a/cocos/2d/text-input-node/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp similarity index 100% rename from cocos/2d/text-input-node/CCTextFieldTTF.cpp rename to cocos/2d/CCTextFieldTTF.cpp diff --git a/cocos/2d/text-input-node/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h similarity index 100% rename from cocos/2d/text-input-node/CCTextFieldTTF.h rename to cocos/2d/CCTextFieldTTF.h diff --git a/cocos/2d/label-nodes/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp similarity index 100% rename from cocos/2d/label-nodes/CCTextImage.cpp rename to cocos/2d/CCTextImage.cpp diff --git a/cocos/2d/label-nodes/CCTextImage.h b/cocos/2d/CCTextImage.h similarity index 100% rename from cocos/2d/label-nodes/CCTextImage.h rename to cocos/2d/CCTextImage.h diff --git a/cocos/2d/textures/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp similarity index 100% rename from cocos/2d/textures/CCTexture2D.cpp rename to cocos/2d/CCTexture2D.cpp diff --git a/cocos/2d/textures/CCTexture2D.h b/cocos/2d/CCTexture2D.h similarity index 100% rename from cocos/2d/textures/CCTexture2D.h rename to cocos/2d/CCTexture2D.h diff --git a/cocos/2d/textures/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp similarity index 100% rename from cocos/2d/textures/CCTextureAtlas.cpp rename to cocos/2d/CCTextureAtlas.cpp diff --git a/cocos/2d/textures/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h similarity index 100% rename from cocos/2d/textures/CCTextureAtlas.h rename to cocos/2d/CCTextureAtlas.h diff --git a/cocos/2d/textures/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp similarity index 100% rename from cocos/2d/textures/CCTextureCache.cpp rename to cocos/2d/CCTextureCache.cpp diff --git a/cocos/2d/textures/CCTextureCache.h b/cocos/2d/CCTextureCache.h similarity index 100% rename from cocos/2d/textures/CCTextureCache.h rename to cocos/2d/CCTextureCache.h diff --git a/cocos/2d/tilemap-parallax-nodes/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTileMapAtlas.cpp rename to cocos/2d/CCTileMapAtlas.cpp diff --git a/cocos/2d/tilemap-parallax-nodes/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h similarity index 100% rename from cocos/2d/tilemap-parallax-nodes/CCTileMapAtlas.h rename to cocos/2d/CCTileMapAtlas.h diff --git a/cocos/2d/event-dispatcher/CCTouch.cpp b/cocos/2d/CCTouch.cpp similarity index 100% rename from cocos/2d/event-dispatcher/CCTouch.cpp rename to cocos/2d/CCTouch.cpp diff --git a/cocos/2d/event-dispatcher/CCTouch.h b/cocos/2d/CCTouch.h similarity index 100% rename from cocos/2d/event-dispatcher/CCTouch.h rename to cocos/2d/CCTouch.h diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransition.cpp b/cocos/2d/CCTransition.cpp similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransition.cpp rename to cocos/2d/CCTransition.cpp diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransition.h b/cocos/2d/CCTransition.h similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransition.h rename to cocos/2d/CCTransition.h diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransitionPageTurn.cpp rename to cocos/2d/CCTransitionPageTurn.cpp diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransitionPageTurn.h b/cocos/2d/CCTransitionPageTurn.h similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransitionPageTurn.h rename to cocos/2d/CCTransitionPageTurn.h diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransitionProgress.cpp b/cocos/2d/CCTransitionProgress.cpp similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransitionProgress.cpp rename to cocos/2d/CCTransitionProgress.cpp diff --git a/cocos/2d/layers-scenes-transitions-nodes/CCTransitionProgress.h b/cocos/2d/CCTransitionProgress.h similarity index 100% rename from cocos/2d/layers-scenes-transitions-nodes/CCTransitionProgress.h rename to cocos/2d/CCTransitionProgress.h diff --git a/cocos/2d/support/user_default/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp similarity index 100% rename from cocos/2d/support/user_default/CCUserDefault.cpp rename to cocos/2d/CCUserDefault.cpp diff --git a/cocos/2d/support/user_default/CCUserDefault.h b/cocos/2d/CCUserDefault.h similarity index 100% rename from cocos/2d/support/user_default/CCUserDefault.h rename to cocos/2d/CCUserDefault.h diff --git a/cocos/2d/support/user_default/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm similarity index 100% rename from cocos/2d/support/user_default/CCUserDefault.mm rename to cocos/2d/CCUserDefault.mm diff --git a/cocos/2d/support/user_default/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp similarity index 100% rename from cocos/2d/support/user_default/CCUserDefaultAndroid.cpp rename to cocos/2d/CCUserDefaultAndroid.cpp diff --git a/cocos/2d/support/CCVertex.cpp b/cocos/2d/CCVertex.cpp similarity index 100% rename from cocos/2d/support/CCVertex.cpp rename to cocos/2d/CCVertex.cpp diff --git a/cocos/2d/support/CCVertex.h b/cocos/2d/CCVertex.h similarity index 100% rename from cocos/2d/support/CCVertex.h rename to cocos/2d/CCVertex.h diff --git a/cocos/2d/proj.linux/Makefile b/cocos/2d/Makefile similarity index 100% rename from cocos/2d/proj.linux/Makefile rename to cocos/2d/Makefile diff --git a/cocos/2d/support/image_support/TGAlib.cpp b/cocos/2d/TGAlib.cpp similarity index 100% rename from cocos/2d/support/image_support/TGAlib.cpp rename to cocos/2d/TGAlib.cpp diff --git a/cocos/2d/support/image_support/TGAlib.h b/cocos/2d/TGAlib.h similarity index 100% rename from cocos/2d/support/image_support/TGAlib.h rename to cocos/2d/TGAlib.h diff --git a/cocos/2d/support/TransformUtils.cpp b/cocos/2d/TransformUtils.cpp similarity index 100% rename from cocos/2d/support/TransformUtils.cpp rename to cocos/2d/TransformUtils.cpp diff --git a/cocos/2d/support/TransformUtils.h b/cocos/2d/TransformUtils.h similarity index 100% rename from cocos/2d/support/TransformUtils.h rename to cocos/2d/TransformUtils.h diff --git a/cocos/2d/support/zip_support/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp similarity index 100% rename from cocos/2d/support/zip_support/ZipUtils.cpp rename to cocos/2d/ZipUtils.cpp diff --git a/cocos/2d/support/zip_support/ZipUtils.h b/cocos/2d/ZipUtils.h similarity index 100% rename from cocos/2d/support/zip_support/ZipUtils.h rename to cocos/2d/ZipUtils.h diff --git a/cocos/2d/support/base64.cpp b/cocos/2d/base64.cpp similarity index 100% rename from cocos/2d/support/base64.cpp rename to cocos/2d/base64.cpp diff --git a/cocos/2d/support/base64.h b/cocos/2d/base64.h similarity index 100% rename from cocos/2d/support/base64.h rename to cocos/2d/base64.h diff --git a/cocos/2d/support/data_support/ccCArray.cpp b/cocos/2d/ccCArray.cpp similarity index 100% rename from cocos/2d/support/data_support/ccCArray.cpp rename to cocos/2d/ccCArray.cpp diff --git a/cocos/2d/support/data_support/ccCArray.h b/cocos/2d/ccCArray.h similarity index 100% rename from cocos/2d/support/data_support/ccCArray.h rename to cocos/2d/ccCArray.h diff --git a/cocos/2d/include/ccConfig.h b/cocos/2d/ccConfig.h similarity index 100% rename from cocos/2d/include/ccConfig.h rename to cocos/2d/ccConfig.h diff --git a/cocos/2d/shaders/ccGLStateCache.cpp b/cocos/2d/ccGLStateCache.cpp similarity index 100% rename from cocos/2d/shaders/ccGLStateCache.cpp rename to cocos/2d/ccGLStateCache.cpp diff --git a/cocos/2d/shaders/ccGLStateCache.h b/cocos/2d/ccGLStateCache.h similarity index 100% rename from cocos/2d/shaders/ccGLStateCache.h rename to cocos/2d/ccGLStateCache.h diff --git a/cocos/2d/include/ccMacros.h b/cocos/2d/ccMacros.h similarity index 100% rename from cocos/2d/include/ccMacros.h rename to cocos/2d/ccMacros.h diff --git a/cocos/2d/shaders/ccShaderEx_SwitchMask_frag.h b/cocos/2d/ccShaderEx_SwitchMask_frag.h similarity index 100% rename from cocos/2d/shaders/ccShaderEx_SwitchMask_frag.h rename to cocos/2d/ccShaderEx_SwitchMask_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionColorLengthTexture_frag.h b/cocos/2d/ccShader_PositionColorLengthTexture_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionColorLengthTexture_frag.h rename to cocos/2d/ccShader_PositionColorLengthTexture_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionColorLengthTexture_vert.h b/cocos/2d/ccShader_PositionColorLengthTexture_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionColorLengthTexture_vert.h rename to cocos/2d/ccShader_PositionColorLengthTexture_vert.h diff --git a/cocos/2d/shaders/ccShader_PositionColor_frag.h b/cocos/2d/ccShader_PositionColor_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionColor_frag.h rename to cocos/2d/ccShader_PositionColor_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionColor_vert.h b/cocos/2d/ccShader_PositionColor_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionColor_vert.h rename to cocos/2d/ccShader_PositionColor_vert.h diff --git a/cocos/2d/shaders/ccShader_PositionTextureA8Color_frag.h b/cocos/2d/ccShader_PositionTextureA8Color_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTextureA8Color_frag.h rename to cocos/2d/ccShader_PositionTextureA8Color_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionTextureA8Color_vert.h b/cocos/2d/ccShader_PositionTextureA8Color_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTextureA8Color_vert.h rename to cocos/2d/ccShader_PositionTextureA8Color_vert.h diff --git a/cocos/2d/shaders/ccShader_PositionTextureColorAlphaTest_frag.h b/cocos/2d/ccShader_PositionTextureColorAlphaTest_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTextureColorAlphaTest_frag.h rename to cocos/2d/ccShader_PositionTextureColorAlphaTest_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionTextureColor_frag.h b/cocos/2d/ccShader_PositionTextureColor_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTextureColor_frag.h rename to cocos/2d/ccShader_PositionTextureColor_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionTextureColor_vert.h b/cocos/2d/ccShader_PositionTextureColor_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTextureColor_vert.h rename to cocos/2d/ccShader_PositionTextureColor_vert.h diff --git a/cocos/2d/shaders/ccShader_PositionTexture_frag.h b/cocos/2d/ccShader_PositionTexture_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTexture_frag.h rename to cocos/2d/ccShader_PositionTexture_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionTexture_uColor_frag.h b/cocos/2d/ccShader_PositionTexture_uColor_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTexture_uColor_frag.h rename to cocos/2d/ccShader_PositionTexture_uColor_frag.h diff --git a/cocos/2d/shaders/ccShader_PositionTexture_uColor_vert.h b/cocos/2d/ccShader_PositionTexture_uColor_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTexture_uColor_vert.h rename to cocos/2d/ccShader_PositionTexture_uColor_vert.h diff --git a/cocos/2d/shaders/ccShader_PositionTexture_vert.h b/cocos/2d/ccShader_PositionTexture_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_PositionTexture_vert.h rename to cocos/2d/ccShader_PositionTexture_vert.h diff --git a/cocos/2d/shaders/ccShader_Position_uColor_frag.h b/cocos/2d/ccShader_Position_uColor_frag.h similarity index 100% rename from cocos/2d/shaders/ccShader_Position_uColor_frag.h rename to cocos/2d/ccShader_Position_uColor_frag.h diff --git a/cocos/2d/shaders/ccShader_Position_uColor_vert.h b/cocos/2d/ccShader_Position_uColor_vert.h similarity index 100% rename from cocos/2d/shaders/ccShader_Position_uColor_vert.h rename to cocos/2d/ccShader_Position_uColor_vert.h diff --git a/cocos/2d/shaders/ccShaders.cpp b/cocos/2d/ccShaders.cpp similarity index 100% rename from cocos/2d/shaders/ccShaders.cpp rename to cocos/2d/ccShaders.cpp diff --git a/cocos/2d/shaders/ccShaders.h b/cocos/2d/ccShaders.h similarity index 100% rename from cocos/2d/shaders/ccShaders.h rename to cocos/2d/ccShaders.h diff --git a/cocos/2d/include/ccTypes.h b/cocos/2d/ccTypes.h similarity index 100% rename from cocos/2d/include/ccTypes.h rename to cocos/2d/ccTypes.h diff --git a/cocos/2d/support/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp similarity index 100% rename from cocos/2d/support/ccUTF8.cpp rename to cocos/2d/ccUTF8.cpp diff --git a/cocos/2d/support/ccUTF8.h b/cocos/2d/ccUTF8.h similarity index 100% rename from cocos/2d/support/ccUTF8.h rename to cocos/2d/ccUTF8.h diff --git a/cocos/2d/support/ccUtils.h b/cocos/2d/ccUtils.h similarity index 100% rename from cocos/2d/support/ccUtils.h rename to cocos/2d/ccUtils.h diff --git a/cocos/2d/include/cocos2d.h b/cocos/2d/cocos2d.h similarity index 100% rename from cocos/2d/include/cocos2d.h rename to cocos/2d/cocos2d.h diff --git a/cocos/2d/proj.win32/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj similarity index 100% rename from cocos/2d/proj.win32/cocos2d.vcxproj rename to cocos/2d/cocos2d.vcxproj diff --git a/cocos/2d/proj.win32/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters similarity index 100% rename from cocos/2d/proj.win32/cocos2d.vcxproj.filters rename to cocos/2d/cocos2d.vcxproj.filters diff --git a/cocos/2d/proj.win32/cocos2d.vcxproj.user b/cocos/2d/cocos2d.vcxproj.user similarity index 100% rename from cocos/2d/proj.win32/cocos2d.vcxproj.user rename to cocos/2d/cocos2d.vcxproj.user diff --git a/cocos/2d/proj.linux/cocos2dx.mk b/cocos/2d/cocos2dx.mk similarity index 100% rename from cocos/2d/proj.linux/cocos2dx.mk rename to cocos/2d/cocos2dx.mk diff --git a/cocos/2d/proj.win32/cocos2dx.props b/cocos/2d/cocos2dx.props similarity index 100% rename from cocos/2d/proj.win32/cocos2dx.props rename to cocos/2d/cocos2dx.props diff --git a/cocos/2d/particle-nodes/firePngData.h b/cocos/2d/firePngData.h similarity index 100% rename from cocos/2d/particle-nodes/firePngData.h rename to cocos/2d/firePngData.h diff --git a/cocos/2d/proj.linux/.cproject b/cocos/2d/proj.linux/.cproject deleted file mode 100755 index aaae232fb4..0000000000 --- a/cocos/2d/proj.linux/.cproject +++ /dev/null @@ -1,602 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cocos/2d/proj.linux/.project b/cocos/2d/proj.linux/.project deleted file mode 100755 index 8811b56dd0..0000000000 --- a/cocos/2d/proj.linux/.project +++ /dev/null @@ -1,256 +0,0 @@ - - - libcocos2d - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/cocos2dx-base/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - CCCamera.cpp - 1 - PARENT-1-PROJECT_LOC/CCCamera.cpp - - - CCConfiguration.cpp - 1 - PARENT-1-PROJECT_LOC/CCConfiguration.cpp - - - CCConfiguration.h - 1 - PARENT-1-PROJECT_LOC/CCConfiguration.h - - - ccFPSImages.c - 1 - PARENT-1-PROJECT_LOC/ccFPSImages.c - - - ccFPSImages.h - 1 - PARENT-1-PROJECT_LOC/ccFPSImages.h - - - ccTypes.cpp - 1 - PARENT-1-PROJECT_LOC/ccTypes.cpp - - - CCDirector.cpp - 1 - PARENT-1-PROJECT_LOC/CCDirector.cpp - - - CCScheduler.cpp - 1 - PARENT-1-PROJECT_LOC/CCScheduler.cpp - - - actions - 2 - PARENT-1-PROJECT_LOC/actions - - - base_nodes - 2 - PARENT-1-PROJECT_LOC/base_nodes - - - cocoa - 2 - PARENT-1-PROJECT_LOC/cocoa - - - cocos2d.cpp - 1 - PARENT-1-PROJECT_LOC/cocos2d.cpp - - - draw_nodes - 2 - PARENT-1-PROJECT_LOC/draw_nodes - - - effects - 2 - PARENT-1-PROJECT_LOC/effects - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - kazmath - 2 - PARENT-1-PROJECT_LOC/kazmath - - - keypad_dispatcher - 2 - PARENT-1-PROJECT_LOC/keypad_dispatcher - - - keyboard_dispatcher - 2 - PARENT-1-PROJECT_LOC/keyboard_dispatcher - - - label_nodes - 2 - PARENT-1-PROJECT_LOC/label_nodes - - - layers_scenes_transitions_nodes - 2 - PARENT-1-PROJECT_LOC/layers_scenes_transitions_nodes - - - menu_nodes - 2 - PARENT-1-PROJECT_LOC/menu_nodes - - - misc_nodes - 2 - PARENT-1-PROJECT_LOC/misc_nodes - - - particle_nodes - 2 - PARENT-1-PROJECT_LOC/particle_nodes - - - platform - 2 - PARENT-1-PROJECT_LOC/platform - - - script_support - 2 - PARENT-1-PROJECT_LOC/script_support - - - shaders - 2 - PARENT-1-PROJECT_LOC/shaders - - - sprite_nodes - 2 - PARENT-1-PROJECT_LOC/sprite_nodes - - - support - 2 - PARENT-1-PROJECT_LOC/support - - - text_input_node - 2 - PARENT-1-PROJECT_LOC/text_input_node - - - textures - 2 - PARENT-1-PROJECT_LOC/textures - - - tilemap_parallax_nodes - 2 - PARENT-1-PROJECT_LOC/tilemap_parallax_nodes - - - touch_dispatcher - 2 - PARENT-1-PROJECT_LOC/touch_dispatcher - - - - - 1360135975775 - platform - 9 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-true-false-linux - - - - diff --git a/cocos/2d/proj.linux/cocos2dx.prf b/cocos/2d/proj.linux/cocos2dx.prf deleted file mode 100644 index 1122180b53..0000000000 --- a/cocos/2d/proj.linux/cocos2dx.prf +++ /dev/null @@ -1,37 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # Use OpenAL in default QtCreator project. - isEmpty(COCOS2D_USE_FMOD):COCOS2D_USE_FMOD=0 - - # Variables used when building libraries. - CC_LIBRARY_DIR = $$PWD/../../lib/linux/release - CC_MAKE_FLAGS = -s - CONFIG(debug, debug|release) { - # Override in debug build. - CC_MAKE_FLAGS += DEBUG=1 - CC_LIBRARY_DIR = $$PWD/../../lib/linux/debug - } - contains(COCOS2D_MODULES,box2d) { - CC_MAKE_FLAGS += USE_BOX2D=1 - } - !equals(COCOS2D_USE_FMOD, 1) { - CC_MAKE_FLAGS += OPENAL=1 - } - - # We will compile cocos2d shared library on demand using Makefile. - build_cocos2d.name = Build cocos2d shared library - build_cocos2d.input = $$PWD/Makefile - build_cocos2d.output = $$CC_LIBRARY_DIR/libcocos2d.so - build_cocos2d.target = $$CC_LIBRARY_DIR/libcocos2d.so - build_cocos2d.CONFIG = no_link target_predeps - build_cocos2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS ${QMAKE_FILE_IN} - - QMAKE_EXTRA_COMPILERS += build_cocos2d - QMAKE_EXTRA_TARGETS += build_cocos2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libcocos2d.so - LIBS += -L$$CC_LIBRARY_DIR -lcocos2d -Wl,-rpath,\'$$CC_LIBRARY_DIR\' -} diff --git a/cocos/2d/proj.linux/cocos2dx.pri b/cocos/2d/proj.linux/cocos2dx.pri deleted file mode 100644 index 84bbb6d987..0000000000 --- a/cocos/2d/proj.linux/cocos2dx.pri +++ /dev/null @@ -1,70 +0,0 @@ - -################################################################################ -# -# If you want enable extra modules, set COCOS2D_MODULES variable before include -# this file, example: -# COCOS2D_MODULES += CocosDenshion -# COCOS2D_MODULES += extensions -# COCOS2D_MODULES += box2d -# or -# COCOS2D_MODULES += chipmunk -# note: you cannot include both box2d and chipmunk. -# -# By default, QtCreator project will use OpenAL audio backend (because FMOD is -# free only for non-commercial use). If you are legal FMOD user, set variable -# COCOS2D_USE_FMOD to use FMOD audio backend: -# COCOS2D_USE_FMOD = 1 -# -################################################################################ - -INCLUDEPATH += $$PWD/../ -INCLUDEPATH += $$PWD/../cocoa/ -INCLUDEPATH += $$PWD/../include/ -INCLUDEPATH += $$PWD/../platform/ -INCLUDEPATH += $$PWD/../kazmath/include - -*-msvc* { - # Use equivalents of -Wno-overloaded-virtual -Wno-unused-parameter. - QMAKE_CXXFLAGS_WARN_ON += /wd4263 /wd4100 -} else { - QMAKE_CXXFLAGS_WARN_ON += -Wno-ignored-qualifiers -Wno-overloaded-virtual -Wno-unused-parameter -Wno-unused-function - QMAKE_CXXFLAGS += -std=c++0x -} - -include($$PWD/cocos2dx.prf) - -linux { - DEFINES += LINUX - INCLUDEPATH += $$PWD/../platform/linux - LIBS += -lpthread -} - -contains(COCOS2D_MODULES,CocosDenshion) { - INCLUDEPATH += $$PWD/../../CocosDenshion/include - include($$PWD/../../CocosDenshion/proj.linux/CocosDenshion.prf) -} - -contains(COCOS2D_MODULES,extensions) { - INCLUDEPATH += $$PWD/../../extensions - LIBS += -lcurl - include($$PWD/../../extensions/proj.linux/extensions.prf) -} - -contains(COCOS2D_MODULES,box2d) { - INCLUDEPATH += $$PWD/../../external - include($$PWD/../../external/Box2D/proj.linux/box2d.prf) -} - -contains(COCOS2D_MODULES,chipmunk) { - contains(COCOS2D_MODULES,box2d):error("COCOS2D_MODULES cannot contain both box2d and chipmunk: choose one and remove another.") - - INCLUDEPATH += $$PWD/../../external/chipmunk/include/chipmunk - include($$PWD/../../external/chipmunk/proj.linux/chipmunk.prf) -} - -CONFIG(debug, debug|release) { - DEFINES += COCOS2D_DEBUG=1 -} -else { - DEFINES += COCOS2D_DEBUG=0 -} diff --git a/cocos/2d/support/ccUtils.cpp b/cocos/2d/support/ccUtils.cpp deleted file mode 100644 index d78324565b..0000000000 --- a/cocos/2d/support/ccUtils.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#include "ccUtils.h" - -namespace cocos2d { - -unsigned long ccNextPOT(unsigned long x) -{ - x = x - 1; - x = x | (x >> 1); - x = x | (x >> 2); - x = x | (x >> 4); - x = x | (x >> 8); - x = x | (x >>16); - return x + 1; -} - -} \ No newline at end of file diff --git a/cocos/2d/support/tinyxml2/tinyxml2.cpp b/cocos/2d/support/tinyxml2/tinyxml2.cpp deleted file mode 100644 index f181b9050c..0000000000 --- a/cocos/2d/support/tinyxml2/tinyxml2.cpp +++ /dev/null @@ -1,2101 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#include "tinyxml2.h" - -#include // yes, this one new style header, is in the Android SDK. -# if defined(ANDROID_NDK) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) -# include -#else -# include -#endif - -static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF -static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out -static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; - -// Bunch of unicode info at: -// http://www.unicode.org/faq/utf_bom.html -// ef bb bf (Microsoft "lead bytes") - designates UTF-8 - -static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; -static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; -static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; - - -#define DELETE_NODE( node ) { \ - if ( node ) { \ - MemPool* pool = node->_memPool; \ - node->~XMLNode(); \ - pool->Free( node ); \ - } \ - } -#define DELETE_ATTRIBUTE( attrib ) { \ - if ( attrib ) { \ - MemPool* pool = attrib->_memPool; \ - attrib->~XMLAttribute(); \ - pool->Free( attrib ); \ - } \ - } - -namespace tinyxml2 -{ - -struct Entity { - const char* pattern; - int length; - char value; -}; - -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = { - { "quot", 4, DOUBLE_QUOTE }, - { "amp", 3, '&' }, - { "apos", 4, SINGLE_QUOTE }, - { "lt", 2, '<' }, - { "gt", 2, '>' } -}; - - -StrPair::~StrPair() -{ - Reset(); -} - - -void StrPair::Reset() -{ - if ( _flags & NEEDS_DELETE ) { - delete [] _start; - } - _flags = 0; - _start = 0; - _end = 0; -} - - -void StrPair::SetStr( const char* str, int flags ) -{ - Reset(); - size_t len = strlen( str ); - _start = new char[ len+1 ]; - memcpy( _start, str, len+1 ); - _end = _start + len; - _flags = flags | NEEDS_DELETE; -} - - -char* StrPair::ParseText( char* p, const char* endTag, int strFlags ) -{ - TIXMLASSERT( endTag && *endTag ); - - char* start = p; // fixme: hides a member - char endChar = *endTag; - size_t length = strlen( endTag ); - - // Inner loop of text parsing. - while ( *p ) { - if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { - Set( start, p, strFlags ); - return p + length; - } - ++p; - } - return 0; -} - - -char* StrPair::ParseName( char* p ) -{ - char* start = p; - - if ( !start || !(*start) ) { - return 0; - } - - while( *p && ( - XMLUtil::IsAlphaNum( (unsigned char) *p ) - || *p == '_' - || *p == ':' - || (*p == '-' && p>start ) // can be in a name, but not lead it. - || (*p == '.' && p>start ) )) { // can be in a name, but not lead it. - ++p; - } - - if ( p > start ) { - Set( start, p, 0 ); - return p; - } - return 0; -} - - -void StrPair::CollapseWhitespace() -{ - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace( _start ); - - if ( _start && *_start ) { - char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( *p ) { - if ( XMLUtil::IsWhiteSpace( *p )) { - p = XMLUtil::SkipWhiteSpace( p ); - if ( *p == 0 ) { - break; // don't write to q; this trims the trailing space. - } - *q = ' '; - ++q; - } - *q = *p; - ++q; - ++p; - } - *q = 0; - } -} - - -const char* StrPair::GetStr() -{ - if ( _flags & NEEDS_FLUSH ) { - *_end = 0; - _flags ^= NEEDS_FLUSH; - - if ( _flags ) { - char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( p < _end ) { - if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if ( *(p+1) == LF ) { - p += 2; - } - else { - ++p; - } - *q++ = LF; - } - else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { - if ( *(p+1) == CR ) { - p += 2; - } - else { - ++p; - } - *q++ = LF; - } - else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if ( *(p+1) == '#' ) { - char buf[10] = { 0 }; - int len; - p = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); - for( int i=0; i(p); - // Check for BOM: - if ( *(pu+0) == TIXML_UTF_LEAD_0 - && *(pu+1) == TIXML_UTF_LEAD_1 - && *(pu+2) == TIXML_UTF_LEAD_2 ) { - *bom = true; - p += 3; - } - return p; -} - - -void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) { - *length = 1; - } - else if ( input < 0x800 ) { - *length = 2; - } - else if ( input < 0x10000 ) { - *length = 3; - } - else if ( input < 0x200000 ) { - *length = 4; - } - else { - *length = 0; // This code won't covert this correctly anyway. - return; - } - - output += *length; - - // Scary scary fall throughs. - switch (*length) { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - default: - break; - } -} - - -const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) -{ - // Presume an entity, and pull it out. - *length = 0; - - if ( *(p+1) == '#' && *(p+2) ) { - unsigned long ucs = 0; - ptrdiff_t delta = 0; - unsigned mult = 1; - - if ( *(p+2) == 'x' ) { - // Hexadecimal. - if ( !*(p+3) ) { - return 0; - } - - const char* q = p+3; - q = strchr( q, ';' ); - - if ( !q || !*q ) { - return 0; - } - - delta = q-p; - --q; - - while ( *q != 'x' ) { - if ( *q >= '0' && *q <= '9' ) { - ucs += mult * (*q - '0'); - } - else if ( *q >= 'a' && *q <= 'f' ) { - ucs += mult * (*q - 'a' + 10); - } - else if ( *q >= 'A' && *q <= 'F' ) { - ucs += mult * (*q - 'A' + 10 ); - } - else { - return 0; - } - mult *= 16; - --q; - } - } - else { - // Decimal. - if ( !*(p+2) ) { - return 0; - } - - const char* q = p+2; - q = strchr( q, ';' ); - - if ( !q || !*q ) { - return 0; - } - - delta = q-p; - --q; - - while ( *q != '#' ) { - if ( *q >= '0' && *q <= '9' ) { - ucs += mult * (*q - '0'); - } - else { - return 0; - } - mult *= 10; - --q; - } - } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - return p + delta + 1; - } - return p+1; -} - - -void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); -} - - -void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); -} - - -void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 ); -} - - -void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%g", v ); -} - - -void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%g", v ); -} - - -bool XMLUtil::ToInt( const char* str, int* value ) -{ - if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) -{ - if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToBool( const char* str, bool* value ) -{ - int ival = 0; - if ( ToInt( str, &ival )) { - *value = (ival==0) ? false : true; - return true; - } - if ( StringEqual( str, "true" ) ) { - *value = true; - return true; - } - else if ( StringEqual( str, "false" ) ) { - *value = false; - return true; - } - return false; -} - - -bool XMLUtil::ToFloat( const char* str, float* value ) -{ - if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { - return true; - } - return false; -} - -bool XMLUtil::ToDouble( const char* str, double* value ) -{ - if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { - return true; - } - return false; -} - - -char* XMLDocument::Identify( char* p, XMLNode** node ) -{ - XMLNode* returnNode = 0; - char* start = p; - p = XMLUtil::SkipWhiteSpace( p ); - if( !p || !*p ) { - return p; - } - - // What is this thing? - // - Elements start with a letter or underscore, but xml is reserved. - // - Comments: - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - - while( p && *p ) { - XMLNode* node = 0; - - p = _document->Identify( p, &node ); - if ( p == 0 || node == 0 ) { - break; - } - - StrPair endTag; - p = node->ParseDeep( p, &endTag ); - if ( !p ) { - DELETE_NODE( node ); - node = 0; - if ( !_document->Error() ) { - _document->SetError( XML_ERROR_PARSING, 0, 0 ); - } - break; - } - - // We read the end tag. Return it to the parent. - if ( node->ToElement() && node->ToElement()->ClosingType() == XMLElement::CLOSING ) { - if ( parentEnd ) { - *parentEnd = static_cast(node)->_value; - } - node->_memPool->SetTracked(); // created and then immediately deleted. - DELETE_NODE( node ); - return p; - } - - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - XMLElement* ele = node->ToElement(); - if ( ele ) { - if ( endTag.Empty() && ele->ClosingType() == XMLElement::OPEN ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); - p = 0; - } - else if ( !endTag.Empty() && ele->ClosingType() != XMLElement::OPEN ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); - p = 0; - } - else if ( !endTag.Empty() ) { - if ( !XMLUtil::StringEqual( endTag.GetStr(), node->Value() )) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 ); - p = 0; - } - } - } - if ( p == 0 ) { - DELETE_NODE( node ); - node = 0; - } - if ( node ) { - this->InsertEndChild( node ); - } - } - return 0; -} - -// --------- XMLText ---------- // -char* XMLText::ParseDeep( char* p, StrPair* ) -{ - const char* start = p; - if ( this->CData() ) { - p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 ); - } - return p; - } - else { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { - flags |= StrPair::COLLAPSE_WHITESPACE; - } - - p = _value.ParseText( p, "<", flags ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 ); - } - if ( p && *p ) { - return p-1; - } - } - return 0; -} - - -XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? - text->SetCData( this->CData() ); - return text; -} - - -bool XMLText::ShallowEqual( const XMLNode* compare ) const -{ - return ( compare->ToText() && XMLUtil::StringEqual( compare->ToText()->Value(), Value() )); -} - - -bool XMLText::Accept( XMLVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -// --------- XMLComment ---------- // - -XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLComment::~XMLComment() -{ -} - - -char* XMLComment::ParseDeep( char* p, StrPair* ) -{ - // Comment parses as text. - const char* start = p; - p = _value.ParseText( p, "-->", StrPair::COMMENT ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 ); - } - return p; -} - - -XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? - return comment; -} - - -bool XMLComment::ShallowEqual( const XMLNode* compare ) const -{ - return ( compare->ToComment() && XMLUtil::StringEqual( compare->ToComment()->Value(), Value() )); -} - - -bool XMLComment::Accept( XMLVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - - -// --------- XMLDeclaration ---------- // - -XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLDeclaration::~XMLDeclaration() -{ - //printf( "~XMLDeclaration\n" ); -} - - -char* XMLDeclaration::ParseDeep( char* p, StrPair* ) -{ - // Declaration parses as text. - const char* start = p; - p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 ); - } - return p; -} - - -XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? - return dec; -} - - -bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const -{ - return ( compare->ToDeclaration() && XMLUtil::StringEqual( compare->ToDeclaration()->Value(), Value() )); -} - - - -bool XMLDeclaration::Accept( XMLVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - -// --------- XMLUnknown ---------- // - -XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) -{ -} - - -XMLUnknown::~XMLUnknown() -{ -} - - -char* XMLUnknown::ParseDeep( char* p, StrPair* ) -{ - // Unknown parses as text. - const char* start = p; - - p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 ); - } - return p; -} - - -XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? - return text; -} - - -bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const -{ - return ( compare->ToUnknown() && XMLUtil::StringEqual( compare->ToUnknown()->Value(), Value() )); -} - - -bool XMLUnknown::Accept( XMLVisitor* visitor ) const -{ - return visitor->Visit( *this ); -} - -// --------- XMLAttribute ---------- // -char* XMLAttribute::ParseDeep( char* p, bool processEntities ) -{ - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName( p ); - if ( !p || !*p ) { - return 0; - } - - // Skip white space before = - p = XMLUtil::SkipWhiteSpace( p ); - if ( !p || *p != '=' ) { - return 0; - } - - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace( p ); - if ( *p != '\"' && *p != '\'' ) { - return 0; - } - - char endTag[2] = { *p, 0 }; - ++p; // move past opening quote - - p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES ); - return p; -} - - -void XMLAttribute::SetName( const char* n ) -{ - _name.SetStr( n ); -} - - -XMLError XMLAttribute::QueryIntValue( int* value ) const -{ - if ( XMLUtil::ToInt( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const -{ - if ( XMLUtil::ToUnsigned( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryBoolValue( bool* value ) const -{ - if ( XMLUtil::ToBool( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryFloatValue( float* value ) const -{ - if ( XMLUtil::ToFloat( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -XMLError XMLAttribute::QueryDoubleValue( double* value ) const -{ - if ( XMLUtil::ToDouble( Value(), value )) { - return XML_NO_ERROR; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} - - -void XMLAttribute::SetAttribute( const char* v ) -{ - _value.SetStr( v ); -} - - -void XMLAttribute::SetAttribute( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -void XMLAttribute::SetAttribute( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - -void XMLAttribute::SetAttribute( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} - - -// --------- XMLElement ---------- // -XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), - _closingType( 0 ), - _rootAttribute( 0 ) -{ -} - - -XMLElement::~XMLElement() -{ - while( _rootAttribute ) { - XMLAttribute* next = _rootAttribute->_next; - DELETE_ATTRIBUTE( _rootAttribute ); - _rootAttribute = next; - } -} - - -XMLAttribute* XMLElement::FindAttribute( const char* name ) -{ - XMLAttribute* a = 0; - for( a=_rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; - } - } - return 0; -} - - -const XMLAttribute* XMLElement::FindAttribute( const char* name ) const -{ - XMLAttribute* a = 0; - for( a=_rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; - } - } - return 0; -} - - -const char* XMLElement::Attribute( const char* name, const char* value ) const -{ - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return 0; - } - if ( !value || XMLUtil::StringEqual( a->Value(), value )) { - return a->Value(); - } - return 0; -} - - -const char* XMLElement::GetText() const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - return FirstChild()->ToText()->Value(); - } - return 0; -} - - -XMLError XMLElement::QueryIntText( int* ival ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->ToText()->Value(); - if ( XMLUtil::ToInt( t, ival ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->ToText()->Value(); - if ( XMLUtil::ToUnsigned( t, uval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryBoolText( bool* bval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->ToText()->Value(); - if ( XMLUtil::ToBool( t, bval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryDoubleText( double* dval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->ToText()->Value(); - if ( XMLUtil::ToDouble( t, dval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - -XMLError XMLElement::QueryFloatText( float* fval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->ToText()->Value(); - if ( XMLUtil::ToFloat( t, fval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} - - - -XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) -{ - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for( attrib = _rootAttribute; - attrib; - last = attrib, attrib = attrib->_next ) { - if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { - break; - } - } - if ( !attrib ) { - attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - attrib->_memPool = &_document->_attributePool; - if ( last ) { - last->_next = attrib; - } - else { - _rootAttribute = attrib; - } - attrib->SetName( name ); - attrib->_memPool->SetTracked(); // always created and linked. - } - return attrib; -} - - -void XMLElement::DeleteAttribute( const char* name ) -{ - XMLAttribute* prev = 0; - for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { - if ( XMLUtil::StringEqual( name, a->Name() ) ) { - if ( prev ) { - prev->_next = a->_next; - } - else { - _rootAttribute = a->_next; - } - DELETE_ATTRIBUTE( a ); - break; - } - prev = a; - } -} - - -char* XMLElement::ParseAttributes( char* p ) -{ - const char* start = p; - XMLAttribute* prevAttribute = 0; - - // Read the attributes. - while( p ) { - p = XMLUtil::SkipWhiteSpace( p ); - if ( !p || !(*p) ) { - _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() ); - return 0; - } - - // attribute. - if ( XMLUtil::IsAlpha( *p ) ) { - XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - - p = attrib->ParseDeep( p, _document->ProcessEntities() ); - if ( !p || Attribute( attrib->Name() ) ) { - DELETE_ATTRIBUTE( attrib ); - _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p ); - return 0; - } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if ( prevAttribute ) { - prevAttribute->_next = attrib; - } - else { - _rootAttribute = attrib; - } - prevAttribute = attrib; - } - // end of the tag - else if ( *p == '/' && *(p+1) == '>' ) { - _closingType = CLOSED; - return p+2; // done; sealed element. - } - // end of the tag - else if ( *p == '>' ) { - ++p; - break; - } - else { - _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p ); - return 0; - } - } - return p; -} - - -// -// -// foobar -// -char* XMLElement::ParseDeep( char* p, StrPair* strPair ) -{ - // Read the element name. - p = XMLUtil::SkipWhiteSpace( p ); - if ( !p ) { - return 0; - } - - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if ( *p == '/' ) { - _closingType = CLOSING; - ++p; - } - - p = _value.ParseName( p ); - if ( _value.Empty() ) { - return 0; - } - - p = ParseAttributes( p ); - if ( !p || !*p || _closingType ) { - return p; - } - - p = XMLNode::ParseDeep( p, strPair ); - return p; -} - - - -XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? - for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { - element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? - } - return element; -} - - -bool XMLElement::ShallowEqual( const XMLNode* compare ) const -{ - const XMLElement* other = compare->ToElement(); - if ( other && XMLUtil::StringEqual( other->Value(), Value() )) { - - const XMLAttribute* a=FirstAttribute(); - const XMLAttribute* b=other->FirstAttribute(); - - while ( a && b ) { - if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { - return false; - } - a = a->Next(); - b = b->Next(); - } - if ( a || b ) { - // different count - return false; - } - return true; - } - return false; -} - - -bool XMLElement::Accept( XMLVisitor* visitor ) const -{ - if ( visitor->VisitEnter( *this, _rootAttribute ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } - } - return visitor->VisitExit( *this ); -} - - -// --------- XMLDocument ----------- // -XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) : - XMLNode( 0 ), - _writeBOM( false ), - _processEntities( processEntities ), - _errorID( XML_NO_ERROR ), - _whitespace( whitespace ), - _errorStr1( 0 ), - _errorStr2( 0 ), - _charBuffer( 0 ) -{ - _document = this; // avoid warning about 'this' in initializer list -} - - -XMLDocument::~XMLDocument() -{ - DeleteChildren(); - delete [] _charBuffer; - -#if 0 - textPool.Trace( "text" ); - elementPool.Trace( "element" ); - commentPool.Trace( "comment" ); - attributePool.Trace( "attribute" ); -#endif - -#ifdef DEBUG - if ( Error() == false ) { - TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); - TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); - TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); - TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); - } -#endif -} - - -void XMLDocument::InitDocument() -{ - _errorID = XML_NO_ERROR; - _errorStr1 = 0; - _errorStr2 = 0; - - delete [] _charBuffer; - _charBuffer = 0; -} - - -XMLElement* XMLDocument::NewElement( const char* name ) -{ - XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this ); - ele->_memPool = &_elementPool; - ele->SetName( name ); - return ele; -} - - -XMLComment* XMLDocument::NewComment( const char* str ) -{ - XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this ); - comment->_memPool = &_commentPool; - comment->SetValue( str ); - return comment; -} - - -XMLText* XMLDocument::NewText( const char* str ) -{ - XMLText* text = new (_textPool.Alloc()) XMLText( this ); - text->_memPool = &_textPool; - text->SetValue( str ); - return text; -} - - -XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) -{ - XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this ); - dec->_memPool = &_commentPool; - dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); - return dec; -} - - -XMLUnknown* XMLDocument::NewUnknown( const char* str ) -{ - XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this ); - unk->_memPool = &_commentPool; - unk->SetValue( str ); - return unk; -} - - -XMLError XMLDocument::LoadFile( const char* filename ) -{ - DeleteChildren(); - InitDocument(); - FILE* fp = 0; - -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) - errno_t err = fopen_s(&fp, filename, "rb" ); - if ( !fp || err) { -#else - fp = fopen( filename, "rb" ); - if ( !fp) { -#endif - SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 ); - return _errorID; - } - LoadFile( fp ); - fclose( fp ); - return _errorID; -} - - -XMLError XMLDocument::LoadFile( FILE* fp ) -{ - DeleteChildren(); - InitDocument(); - - fseek( fp, 0, SEEK_END ); - size_t size = ftell( fp ); - fseek( fp, 0, SEEK_SET ); - - if ( size == 0 ) { - return _errorID; - } - - _charBuffer = new char[size+1]; - size_t read = fread( _charBuffer, 1, size, fp ); - if ( read != size ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - _charBuffer[size] = 0; - - const char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace( p ); - p = XMLUtil::ReadBOM( p, &_writeBOM ); - if ( !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - - ParseDeep( _charBuffer + (p-_charBuffer), 0 ); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( const char* filename, bool compact ) -{ - FILE* fp = 0; -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) - errno_t err = fopen_s(&fp, filename, "w" ); - if ( !fp || err) { -#else - fp = fopen( filename, "w" ); - if ( !fp) { -#endif - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 ); - return _errorID; - } - SaveFile(fp, compact); - fclose( fp ); - return _errorID; -} - - -XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) -{ - XMLPrinter stream( fp, compact ); - Print( &stream ); - return _errorID; -} - - -XMLError XMLDocument::Parse( const char* p, size_t len ) -{ - DeleteChildren(); - InitDocument(); - - if ( !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - if ( len == (size_t)(-1) ) { - len = strlen( p ); - } - _charBuffer = new char[ len+1 ]; - memcpy( _charBuffer, p, len ); - _charBuffer[len] = 0; - - p = XMLUtil::SkipWhiteSpace( p ); - p = XMLUtil::ReadBOM( p, &_writeBOM ); - if ( !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - - ParseDeep( _charBuffer, 0 ); - return _errorID; -} - - -void XMLDocument::Print( XMLPrinter* streamer ) -{ - XMLPrinter stdStreamer( stdout ); - if ( !streamer ) { - streamer = &stdStreamer; - } - Accept( streamer ); -} - - -void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 ) -{ - _errorID = error; - _errorStr1 = str1; - _errorStr2 = str2; -} - - -void XMLDocument::PrintError() const -{ - if ( _errorID ) { - static const int LEN = 20; - char buf1[LEN] = { 0 }; - char buf2[LEN] = { 0 }; - - if ( _errorStr1 ) { - TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 ); - } - if ( _errorStr2 ) { - TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 ); - } - - printf( "XMLDocument error id=%d str1=%s str2=%s\n", - _errorID, buf1, buf2 ); - } -} - - -XMLPrinter::XMLPrinter( FILE* file, bool compact ) : - _elementJustOpened( false ), - _firstElement( true ), - _fp( file ), - _depth( 0 ), - _textDepth( -1 ), - _processEntities( true ), - _compactMode( compact ) -{ - for( int i=0; i'] = true; // not required, but consistency is nice - _buffer.Push( 0 ); -} - - -void XMLPrinter::Print( const char* format, ... ) -{ - va_list va; - va_start( va, format ); - - if ( _fp ) { - vfprintf( _fp, format, va ); - } - else { - // This seems brutally complex. Haven't figured out a better - // way on windows. -#if defined _MSC_VER && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) - int len = -1; - int expand = 1000; - while ( len < 0 ) { - len = vsnprintf_s( _accumulator.Mem(), _accumulator.Capacity(), _TRUNCATE, format, va ); - if ( len < 0 ) { - expand *= 3/2; - _accumulator.PushArr( expand ); - } - } - char* p = _buffer.PushArr( len ) - 1; - memcpy( p, _accumulator.Mem(), len+1 ); -#else - int len = vsnprintf( 0, 0, format, va ); - // Close out and re-start the va-args - va_end( va ); - va_start( va, format ); - char* p = _buffer.PushArr( len ) - 1; - vsnprintf( p, len+1, format, va ); -#endif - } - va_end( va ); -} - - -void XMLPrinter::PrintSpace( int depth ) -{ - for( int i=0; i 0 && *q < ENTITY_RANGE ) { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if ( flag[(unsigned)(*q)] ) { - while ( p < q ) { - Print( "%c", *p ); - ++p; - } - for( int i=0; i 0) ) { - Print( "%s", p ); - } -} - - -void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) -{ - static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; - if ( writeBOM ) { - Print( "%s", bom ); - } - if ( writeDec ) { - PushDeclaration( "xml version=\"1.0\"" ); - } -} - - -void XMLPrinter::OpenElement( const char* name ) -{ - if ( _elementJustOpened ) { - SealElement(); - } - _stack.Push( name ); - - if ( _textDepth < 0 && !_firstElement && !_compactMode ) { - Print( "\n" ); - PrintSpace( _depth ); - } - - Print( "<%s", name ); - _elementJustOpened = true; - _firstElement = false; - ++_depth; -} - - -void XMLPrinter::PushAttribute( const char* name, const char* value ) -{ - TIXMLASSERT( _elementJustOpened ); - Print( " %s=\"", name ); - PrintString( value, false ); - Print( "\"" ); -} - - -void XMLPrinter::PushAttribute( const char* name, int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute( const char* name, unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute( const char* name, bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::PushAttribute( const char* name, double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} - - -void XMLPrinter::CloseElement() -{ - --_depth; - const char* name = _stack.Pop(); - - if ( _elementJustOpened ) { - Print( "/>" ); - } - else { - if ( _textDepth < 0 && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - Print( "", name ); - } - - if ( _textDepth == _depth ) { - _textDepth = -1; - } - if ( _depth == 0 && !_compactMode) { - Print( "\n" ); - } - _elementJustOpened = false; -} - - -void XMLPrinter::SealElement() -{ - _elementJustOpened = false; - Print( ">" ); -} - - -void XMLPrinter::PushText( const char* text, bool cdata ) -{ - _textDepth = _depth-1; - - if ( _elementJustOpened ) { - SealElement(); - } - if ( cdata ) { - Print( "" ); - } - else { - PrintString( text, true ); - } -} - -void XMLPrinter::PushText( int value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( unsigned value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( bool value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( float value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushText( double value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} - - -void XMLPrinter::PushComment( const char* comment ) -{ - if ( _elementJustOpened ) { - SealElement(); - } - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", comment ); -} - - -void XMLPrinter::PushDeclaration( const char* value ) -{ - if ( _elementJustOpened ) { - SealElement(); - } - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", value ); -} - - -void XMLPrinter::PushUnknown( const char* value ) -{ - if ( _elementJustOpened ) { - SealElement(); - } - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Print( "\n" ); - PrintSpace( _depth ); - } - _firstElement = false; - Print( "", value ); -} - - -bool XMLPrinter::VisitEnter( const XMLDocument& doc ) -{ - _processEntities = doc.ProcessEntities(); - if ( doc.HasBOM() ) { - PushHeader( true, false ); - } - return true; -} - - -bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) -{ - OpenElement( element.Name() ); - while ( attribute ) { - PushAttribute( attribute->Name(), attribute->Value() ); - attribute = attribute->Next(); - } - return true; -} - - -bool XMLPrinter::VisitExit( const XMLElement& ) -{ - CloseElement(); - return true; -} - - -bool XMLPrinter::Visit( const XMLText& text ) -{ - PushText( text.Value(), text.CData() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLComment& comment ) -{ - PushComment( comment.Value() ); - return true; -} - -bool XMLPrinter::Visit( const XMLDeclaration& declaration ) -{ - PushDeclaration( declaration.Value() ); - return true; -} - - -bool XMLPrinter::Visit( const XMLUnknown& unknown ) -{ - PushUnknown( unknown.Value() ); - return true; -} - -} // namespace tinyxml2 - diff --git a/cocos/2d/support/tinyxml2/tinyxml2.h b/cocos/2d/support/tinyxml2/tinyxml2.h deleted file mode 100644 index eeffa1096f..0000000000 --- a/cocos/2d/support/tinyxml2/tinyxml2.h +++ /dev/null @@ -1,1914 +0,0 @@ -/* -Original code by Lee Thomason (www.grinninglizard.com) - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source -distribution. -*/ - -#ifndef TINYXML2_INCLUDED -#define TINYXML2_INCLUDED - -#include "platform/CCPlatformConfig.h" -#include "platform/CCPlatformMacros.h" - -#if defined(ANDROID_NDK) || defined(__BORLANDC__) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) -# include -# include -# include -# include -# include -# include -#else -# include -# include -# include -# include -# include -# include -#endif - -/* - TODO: intern strings instead of allocation. -*/ -/* - gcc: - g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe - - Formatting, Artistic Style: - AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h -*/ - -#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) -# ifndef DEBUG -# define DEBUG -# endif -#endif - - -#if defined(DEBUG) -# if defined(_MSC_VER) -# define TIXMLASSERT( x ) if ( !(x)) { __debugbreak(); } //if ( !(x)) WinDebugBreak() -# elif defined (ANDROID_NDK) -# include -# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } -# else -# include -# define TIXMLASSERT assert -# endif -# else -# define TIXMLASSERT( x ) {} -#endif - - -#if (defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)) -// Microsoft visual studio, version 2005 and higher. -/*int _snprintf_s( - char *buffer, - size_t sizeOfBuffer, - size_t count, - const char *format [, - argument] ... -);*/ -inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) -{ - va_list va; - va_start( va, format ); - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - va_end( va ); - return result; -} -#define TIXML_SSCANF sscanf_s -#else -// GCC version 3 and higher -//#warning( "Using sn* functions." ) -#define TIXML_SNPRINTF snprintf -#define TIXML_SSCANF sscanf -#endif - -static const int TIXML2_MAJOR_VERSION = 1; -static const int TIXML2_MINOR_VERSION = 0; -static const int TIXML2_PATCH_VERSION = 9; - -namespace tinyxml2 -{ -class XMLDocument; -class XMLElement; -class XMLAttribute; -class XMLComment; -class XMLNode; -class XMLText; -class XMLDeclaration; -class XMLUnknown; - -class XMLPrinter; - -/* - A class that wraps strings. Normally stores the start and end - pointers into the XML file itself, and will apply normalization - and entity translation if actually read. Can also store (and memory - manage) a traditional char[] -*/ -class CC_DLL StrPair -{ -public: - enum { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - COLLAPSE_WHITESPACE = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; - - StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} - ~StrPair(); - - void Set( char* start, char* end, int flags ) { - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } - - const char* GetStr(); - - bool Empty() const { - return _start == _end; - } - - void SetInternedStr( const char* str ) { - Reset(); - _start = const_cast(str); - } - - void SetStr( const char* str, int flags=0 ); - - char* ParseText( char* in, const char* endTag, int strFlags ); - char* ParseName( char* in ); - -private: - void Reset(); - void CollapseWhitespace(); - - enum { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 - }; - - // After parsing, if *end != 0, it can be set to zero. - int _flags; - char* _start; - char* _end; -}; - - -/* - A dynamic array of Plain Old Data. Doesn't support constructors, etc. - Has a small initial memory pool, so that low or no usage will not - cause a call to new/delete -*/ -template -class CC_DLL DynArray -{ -public: - DynArray< T, INIT >() { - _mem = _pool; - _allocated = INIT; - _size = 0; - } - - ~DynArray() { - if ( _mem != _pool ) { - delete [] _mem; - } - } - - void Push( T t ) { - EnsureCapacity( _size+1 ); - _mem[_size++] = t; - } - - T* PushArr( int count ) { - EnsureCapacity( _size+count ); - T* ret = &_mem[_size]; - _size += count; - return ret; - } - - T Pop() { - return _mem[--_size]; - } - - void PopArr( int count ) { - TIXMLASSERT( _size >= count ); - _size -= count; - } - - bool Empty() const { - return _size == 0; - } - - T& operator[](int i) { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& operator[](int i) const { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - int Size() const { - return _size; - } - - int Capacity() const { - return _allocated; - } - - const T* Mem() const { - return _mem; - } - - T* Mem() { - return _mem; - } - -private: - void EnsureCapacity( int cap ) { - if ( cap > _allocated ) { - int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs - if ( _mem != _pool ) { - delete [] _mem; - } - _mem = newMem; - _allocated = newAllocated; - } - } - - T* _mem; - T _pool[INIT]; - int _allocated; // objects allocated - int _size; // number objects in use -}; - - -/* - Parent virtual class of a pool for fast allocation - and deallocation of objects. -*/ -class CC_DLL MemPool -{ -public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free( void* ) = 0; - virtual void SetTracked() = 0; -}; - - -/* - Template child class to create pools of the correct type. -*/ -template< int SIZE > -class CC_DLL MemPoolT : public MemPool -{ -public: - MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} - ~MemPoolT() { - // Delete the blocks. - for( int i=0; i<_blockPtrs.Size(); ++i ) { - delete _blockPtrs[i]; - } - } - - virtual int ItemSize() const { - return SIZE; - } - int CurrentAllocs() const { - return _currentAllocs; - } - - virtual void* Alloc() { - if ( !_root ) { - // Need a new block. - Block* block = new Block(); - _blockPtrs.Push( block ); - - for( int i=0; ichunk[i].next = &block->chunk[i+1]; - } - block->chunk[COUNT-1].next = 0; - _root = block->chunk; - } - void* result = _root; - _root = _root->next; - - ++_currentAllocs; - if ( _currentAllocs > _maxAllocs ) { - _maxAllocs = _currentAllocs; - } - _nAllocs++; - _nUntracked++; - return result; - } - virtual void Free( void* mem ) { - if ( !mem ) { - return; - } - --_currentAllocs; - Chunk* chunk = (Chunk*)mem; -#ifdef DEBUG - memset( chunk, 0xfe, sizeof(Chunk) ); -#endif - chunk->next = _root; - _root = chunk; - } - void Trace( const char* name ) { - printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, _maxAllocs, _maxAllocs*SIZE/1024, _currentAllocs, SIZE, _nAllocs, _blockPtrs.Size() ); - } - - void SetTracked() { - _nUntracked--; - } - - int Untracked() const { - return _nUntracked; - } - - enum { COUNT = 1024/SIZE }; // Some compilers do not accept to use COUNT in private part if COUNT is private - -private: - union Chunk { - Chunk* next; - char mem[SIZE]; - }; - struct Block { - Chunk chunk[COUNT]; - }; - DynArray< Block*, 10 > _blockPtrs; - Chunk* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; -}; - - - -/** - Implements the interface to the "Visitor pattern" (see the Accept() method.) - If you call the Accept() method, it requires being passed a XMLVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs - are simply called with Visit(). - - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, no children of this node or its sibilings will be visited. - - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. - - Generally Accept() is called on the TiXmlDocument, although all nodes support visiting. - - You should never change the document from a callback. - - @sa XMLNode::Accept() -*/ -class CC_DLL XMLVisitor -{ -public: - virtual ~XMLVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { - return true; - } - /// Visit a document. - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - /// Visit an element. - virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { - return true; - } - /// Visit an element. - virtual bool VisitExit( const XMLElement& /*element*/ ) { - return true; - } - - /// Visit a declaration. - virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { - return true; - } - /// Visit a text node. - virtual bool Visit( const XMLText& /*text*/ ) { - return true; - } - /// Visit a comment node. - virtual bool Visit( const XMLComment& /*comment*/ ) { - return true; - } - /// Visit an unknown node. - virtual bool Visit( const XMLUnknown& /*unknown*/ ) { - return true; - } -}; - - -/* - Utility functionality. -*/ -class CC_DLL XMLUtil -{ -public: - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static const char* SkipWhiteSpace( const char* p ) { - while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast(p) ) ) { - ++p; - } - return p; - } - static char* SkipWhiteSpace( char* p ) { - while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast(p) ) ) { - ++p; - } - return p; - } - static bool IsWhiteSpace( char p ) { - return !IsUTF8Continuation(p) && isspace( static_cast(p) ); - } - - inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { - int n = 0; - if ( p == q ) { - return true; - } - while( *p && *q && *p == *q && n(const_cast(this)->FirstChildElement( value )); - } - - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { - return _lastChild; - } - - XMLNode* LastChild() { - return const_cast(const_cast(this)->LastChild() ); - } - - /** Get the last child element or optionally the last child - element with the specified name. - */ - const XMLElement* LastChildElement( const char* value=0 ) const; - - XMLElement* LastChildElement( const char* value=0 ) { - return const_cast(const_cast(this)->LastChildElement(value) ); - } - - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { - return _prev; - } - - XMLNode* PreviousSibling() { - return _prev; - } - - /// Get the previous (left) sibling element of this node, with an opitionally supplied name. - const XMLElement* PreviousSiblingElement( const char* value=0 ) const ; - - XMLElement* PreviousSiblingElement( const char* value=0 ) { - return const_cast(const_cast(this)->PreviousSiblingElement( value ) ); - } - - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { - return _next; - } - - XMLNode* NextSibling() { - return _next; - } - - /// Get the next (right) sibling element of this node, with an opitionally supplied name. - const XMLElement* NextSiblingElement( const char* value=0 ) const; - - XMLElement* NextSiblingElement( const char* value=0 ) { - return const_cast(const_cast(this)->NextSiblingElement( value ) ); - } - - /** - Add a child node as the last (right) child. - */ - XMLNode* InsertEndChild( XMLNode* addThis ); - - XMLNode* LinkEndChild( XMLNode* addThis ) { - return InsertEndChild( addThis ); - } - /** - Add a child node as the first (left) child. - */ - XMLNode* InsertFirstChild( XMLNode* addThis ); - /** - Add a node after the specified child node. - */ - XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); - - /** - Delete all the children of this node. - */ - void DeleteChildren(); - - /** - Delete a child of this node. - */ - void DeleteChild( XMLNode* node ); - - /** - Make a copy of this node, but not its children. - You may pass in a Document pointer that will be - the owner of the new Node. If the 'document' is - null, then the node returned will be allocated - from the current Document. (this->GetDocument()) - - Note: if called on a XMLDocument, this will return null. - */ - virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; - - /** - Test if 2 nodes are the same, but don't test children. - The 2 nodes do not need to be in the same Document. - - Note: if called on a XMLDocument, this will return false. - */ - virtual bool ShallowEqual( const XMLNode* compare ) const = 0; - - /** Accept a hierarchical visit of the nodes in the TinyXML DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the TiXmlVisitor interface. - - This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML is unchanged by using this - interface versus any other.) - - The interface has been based on ideas from: - - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - - Which are both good references for "visiting". - - An example of using Accept(): - @verbatim - TiXmlPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( XMLVisitor* visitor ) const = 0; - - // internal - virtual char* ParseDeep( char*, StrPair* ); - -protected: - XMLNode( XMLDocument* ); - virtual ~XMLNode(); - XMLNode( const XMLNode& ); // not supported - XMLNode& operator=( const XMLNode& ); // not supported - - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - - XMLNode* _firstChild; - XMLNode* _lastChild; - - XMLNode* _prev; - XMLNode* _next; - -private: - MemPool* _memPool; - void Unlink( XMLNode* child ); -}; - - -/** XML text. - - Note that a text node can have child element nodes, for example: - @verbatim - This is bold - @endverbatim - - A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCDATA() and query it with CDATA(). -*/ -class CC_DLL XMLText : public XMLNode -{ - friend class XMLBase; - friend class XMLDocument; -public: - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLText* ToText() { - return this; - } - virtual const XMLText* ToText() const { - return this; - } - - /// Declare whether this should be CDATA or standard text. - void SetCData( bool isCData ) { - _isCData = isCData; - } - /// Returns true if this is a CDATA text element. - bool CData() const { - return _isCData; - } - - char* ParseDeep( char*, StrPair* endTag ); - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} - virtual ~XMLText() {} - XMLText( const XMLText& ); // not supported - XMLText& operator=( const XMLText& ); // not supported - -private: - bool _isCData; -}; - - -/** An XML Comment. */ -class CC_DLL XMLComment : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLComment* ToComment() { - return this; - } - virtual const XMLComment* ToComment() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - char* ParseDeep( char*, StrPair* endTag ); - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLComment( XMLDocument* doc ); - virtual ~XMLComment(); - XMLComment( const XMLComment& ); // not supported - XMLComment& operator=( const XMLComment& ); // not supported - -private: -}; - - -/** In correct XML the declaration is the first entry in the file. - @verbatim - - @endverbatim - - TinyXML2 will happily read or write files without a declaration, - however. - - The text of the declaration isn't interpreted. It is parsed - and written as a string. -*/ -class CC_DLL XMLDeclaration : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLDeclaration* ToDeclaration() { - return this; - } - virtual const XMLDeclaration* ToDeclaration() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - char* ParseDeep( char*, StrPair* endTag ); - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLDeclaration( XMLDocument* doc ); - virtual ~XMLDeclaration(); - XMLDeclaration( const XMLDeclaration& ); // not supported - XMLDeclaration& operator=( const XMLDeclaration& ); // not supported -}; - - -/** Any tag that tinyXml doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. - - DTD tags get thrown into TiXmlUnknowns. -*/ -class CC_DLL XMLUnknown : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLUnknown* ToUnknown() { - return this; - } - virtual const XMLUnknown* ToUnknown() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - char* ParseDeep( char*, StrPair* endTag ); - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - XMLUnknown( XMLDocument* doc ); - virtual ~XMLUnknown(); - XMLUnknown( const XMLUnknown& ); // not supported - XMLUnknown& operator=( const XMLUnknown& ); // not supported -}; - - -enum XMLError { - XML_NO_ERROR = 0, - XML_SUCCESS = 0, - - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - XML_ERROR_ELEMENT_MISMATCH, - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - XML_ERROR_IDENTIFYING_TAG, - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE -}; - - -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. - - @note The attributes are not XMLNodes. You may only query the - Next() attribute in a list. -*/ -class CC_DLL XMLAttribute -{ - friend class XMLElement; -public: - /// The name of the attribute. - const char* Name() const { - return _name.GetStr(); - } - /// The value of the attribute. - const char* Value() const { - return _value.GetStr(); - } - /// The next attribute in the list. - const XMLAttribute* Next() const { - return _next; - } - - /** IntAttribute interprets the attribute as an integer, and returns the value. - If the value isn't an integer, 0 will be returned. There is no error checking; - use QueryIntAttribute() if you need error checking. - */ - int IntValue() const { - int i=0; - QueryIntValue( &i ); - return i; - } - /// Query as an unsigned integer. See IntAttribute() - unsigned UnsignedValue() const { - unsigned i=0; - QueryUnsignedValue( &i ); - return i; - } - /// Query as a boolean. See IntAttribute() - bool BoolValue() const { - bool b=false; - QueryBoolValue( &b ); - return b; - } - /// Query as a double. See IntAttribute() - double DoubleValue() const { - double d=0; - QueryDoubleValue( &d ); - return d; - } - /// Query as a float. See IntAttribute() - float FloatValue() const { - float f=0; - QueryFloatValue( &f ); - return f; - } - - /** QueryIntAttribute interprets the attribute as an integer, and returns the value - in the provided paremeter. The function will return XML_NO_ERROR on success, - and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. - */ - XMLError QueryIntValue( int* value ) const; - /// See QueryIntAttribute - XMLError QueryUnsignedValue( unsigned int* value ) const; - /// See QueryIntAttribute - XMLError QueryBoolValue( bool* value ) const; - /// See QueryIntAttribute - XMLError QueryDoubleValue( double* value ) const; - /// See QueryIntAttribute - XMLError QueryFloatValue( float* value ) const; - - /// Set the attribute to a string value. - void SetAttribute( const char* value ); - /// Set the attribute to value. - void SetAttribute( int value ); - /// Set the attribute to value. - void SetAttribute( unsigned value ); - /// Set the attribute to value. - void SetAttribute( bool value ); - /// Set the attribute to value. - void SetAttribute( double value ); - /// Set the attribute to value. - void SetAttribute( float value ); - -private: - enum { BUF_SIZE = 200 }; - - XMLAttribute() : _next( 0 ) {} - virtual ~XMLAttribute() {} - - XMLAttribute( const XMLAttribute& ); // not supported - void operator=( const XMLAttribute& ); // not supported - void SetName( const char* name ); - - char* ParseDeep( char* p, bool processEntities ); - - mutable StrPair _name; - mutable StrPair _value; - XMLAttribute* _next; - MemPool* _memPool; -}; - - -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class CC_DLL XMLElement : public XMLNode -{ - friend class XMLBase; - friend class XMLDocument; -public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { - return Value(); - } - /// Set the name of the element. - void SetName( const char* str, bool staticMem=false ) { - SetValue( str, staticMem ); - } - - virtual XMLElement* ToElement() { - return this; - } - virtual const XMLElement* ToElement() const { - return this; - } - virtual bool Accept( XMLVisitor* visitor ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none - exists. For example: - - @verbatim - const char* value = ele->Attribute( "foo" ); - @endverbatim - - The 'value' parameter is normally null. However, if specified, - the attribute will only be returned if the 'name' and 'value' - match. This allow you to write code: - - @verbatim - if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); - @endverbatim - - rather than: - @verbatim - if ( ele->Attribute( "foo" ) ) { - if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); - } - @endverbatim - */ - const char* Attribute( const char* name, const char* value=0 ) const; - - /** Given an attribute name, IntAttribute() returns the value - of the attribute interpreted as an integer. 0 will be - returned if there is an error. For a method with error - checking, see QueryIntAttribute() - */ - int IntAttribute( const char* name ) const { - int i=0; - QueryIntAttribute( name, &i ); - return i; - } - /// See IntAttribute() - unsigned UnsignedAttribute( const char* name ) const { - unsigned i=0; - QueryUnsignedAttribute( name, &i ); - return i; - } - /// See IntAttribute() - bool BoolAttribute( const char* name ) const { - bool b=false; - QueryBoolAttribute( name, &b ); - return b; - } - /// See IntAttribute() - double DoubleAttribute( const char* name ) const { - double d=0; - QueryDoubleAttribute( name, &d ); - return d; - } - /// See IntAttribute() - float FloatAttribute( const char* name ) const { - float f=0; - QueryFloatAttribute( name, &f ); - return f; - } - - /** Given an attribute name, QueryIntAttribute() returns - XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryIntAttribute( const char* name, int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryIntValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryUnsignedValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryBoolAttribute( const char* name, bool* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryBoolValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute( const char* name, double* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryDoubleValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute( const char* name, float* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryFloatValue( value ); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, const char* value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, int value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, unsigned value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, bool value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, double value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /** - Delete an attribute. - */ - void DeleteAttribute( const char* name ); - - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { - return _rootAttribute; - } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute( const char* name ) const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the TiXmlText child - and accessing it directly. - - If the first child of 'this' is a TiXmlText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". - */ - const char* GetText() const; - - /** - Convenience method to query the value of a child text node. This is probably best - shown by example. Given you have a document is this form: - @verbatim - - 1 - 1.4 - - @endverbatim - - The QueryIntText() and similar functions provide a safe and easier way to get to the - "value" of x and y. - - @verbatim - int x = 0; - float y = 0; // types of x and y are contrived for example - const XMLElement* xElement = pointElement->FirstChildElement( "x" ); - const XMLElement* yElement = pointElement->FirstChildElement( "y" ); - xElement->QueryIntText( &x ); - yElement->QueryFloatText( &y ); - @endverbatim - - @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted - to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. - - */ - XMLError QueryIntText( int* ival ) const; - /// See QueryIntText() - XMLError QueryUnsignedText( unsigned* uval ) const; - /// See QueryIntText() - XMLError QueryBoolText( bool* bval ) const; - /// See QueryIntText() - XMLError QueryDoubleText( double* dval ) const; - /// See QueryIntText() - XMLError QueryFloatText( float* fval ) const; - - // internal: - enum { - OPEN, // - CLOSED, // - CLOSING // - }; - int ClosingType() const { - return _closingType; - } - char* ParseDeep( char* p, StrPair* endTag ); - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -private: - XMLElement( XMLDocument* doc ); - virtual ~XMLElement(); - XMLElement( const XMLElement& ); // not supported - void operator=( const XMLElement& ); // not supported - - XMLAttribute* FindAttribute( const char* name ); - XMLAttribute* FindOrCreateAttribute( const char* name ); - //void LinkAttribute( XMLAttribute* attrib ); - char* ParseAttributes( char* p ); - - int _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; -}; - - -enum Whitespace { - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE -}; - - -/** A Document binds together all the functionality. - It can be saved, loaded, and printed to the screen. - All Nodes are connected and allocated to a Document. - If the Document is deleted, all its Nodes are also deleted. -*/ -class CC_DLL XMLDocument : public XMLNode -{ - friend class XMLElement; -public: - /// constructor - XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() { - return this; - } - virtual const XMLDocument* ToDocument() const { - return this; - } - - /** - Parse an XML file from a character string. - Returns XML_NO_ERROR (0) on success, or - an errorID. - - You may optionally pass in the 'nBytes', which is - the number of bytes which will be parsed. If not - specified, TinyXML will assume 'xml' points to a - null terminated string. - */ - XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); - - /** - Load an XML file from disk. - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError LoadFile( const char* filename ); - - /** - Load an XML file from disk. You are responsible - for providing and closing the FILE*. - - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError LoadFile( FILE* ); - - /** - Save the XML file to disk. - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError SaveFile( const char* filename, bool compact = false ); - - /** - Save the XML file to disk. You are responsible - for providing and closing the FILE*. - - Returns XML_NO_ERROR (0) on success, or - an errorID. - */ - XMLError SaveFile( FILE* fp, bool compact = false ); - - bool ProcessEntities() const { - return _processEntities; - } - Whitespace WhitespaceMode() const { - return _whitespace; - } - - /** - Returns true if this document has a leading Byte Order Mark of UTF8. - */ - bool HasBOM() const { - return _writeBOM; - } - /** Sets whether to write the BOM when writing the file. - */ - void SetBOM( bool useBOM ) { - _writeBOM = useBOM; - } - - /** Return the root element of DOM. Equivalent to FirstChildElement(). - To get the first node, use FirstChild(). - */ - XMLElement* RootElement() { - return FirstChildElement(); - } - const XMLElement* RootElement() const { - return FirstChildElement(); - } - - /** Print the Document. If the Printer is not provided, it will - print to stdout. If you provide Printer, this can print to a file: - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Or you can use a printer to print to memory: - @verbatim - XMLPrinter printer; - doc->Print( &printer ); - // printer.CStr() has a const char* to the XML - @endverbatim - */ - void Print( XMLPrinter* streamer=0 ); - virtual bool Accept( XMLVisitor* visitor ) const; - - /** - Create a new Element associated with - this Document. The memory for the Element - is managed by the Document. - */ - XMLElement* NewElement( const char* name ); - /** - Create a new Comment associated with - this Document. The memory for the Comment - is managed by the Document. - */ - XMLComment* NewComment( const char* comment ); - /** - Create a new Text associated with - this Document. The memory for the Text - is managed by the Document. - */ - XMLText* NewText( const char* text ); - /** - Create a new Declaration associated with - this Document. The memory for the object - is managed by the Document. - - If the 'text' param is null, the standard - declaration is used.: - @verbatim - - @endverbatim - */ - XMLDeclaration* NewDeclaration( const char* text=0 ); - /** - Create a new Unknown associated with - this Document. The memory forthe object - is managed by the Document. - */ - XMLUnknown* NewUnknown( const char* text ); - - /** - Delete a node associated with this document. - It will be unlinked from the DOM. - */ - void DeleteNode( XMLNode* node ) { - node->_parent->DeleteChild( node ); - } - - void SetError( XMLError error, const char* str1, const char* str2 ); - - /// Return true if there was an error parsing the document. - bool Error() const { - return _errorID != XML_NO_ERROR; - } - /// Return the errorID. - XMLError ErrorID() const { - return _errorID; - } - /// Return a possibly helpful diagnostic location or string. - const char* GetErrorStr1() const { - return _errorStr1; - } - /// Return a possibly helpful secondary diagnostic location or string. - const char* GetErrorStr2() const { - return _errorStr2; - } - /// If there is an error, print it to stdout. - void PrintError() const; - - // internal - char* Identify( char* p, XMLNode** node ); - - virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { - return 0; - } - virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { - return false; - } - -private: - XMLDocument( const XMLDocument& ); // not supported - void operator=( const XMLDocument& ); // not supported - void InitDocument(); - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespace; - const char* _errorStr1; - const char* _errorStr2; - char* _charBuffer; - - MemPoolT< sizeof(XMLElement) > _elementPool; - MemPoolT< sizeof(XMLAttribute) > _attributePool; - MemPoolT< sizeof(XMLText) > _textPool; - MemPoolT< sizeof(XMLComment) > _commentPool; -}; - - -/** - A XMLHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that XMLHandle is not part of the TinyXML - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - - - - - - - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - XMLElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - XMLElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - XMLElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - XMLElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. XMLHandle addresses the verbosity - of such code. A XMLHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - XMLHandle docHandle( &document ); - XMLElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild().NextSibling().ToElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - XMLHandle handleCopy = handle; - @endverbatim - - See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. -*/ -class CC_DLL XMLHandle -{ -public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - XMLHandle( XMLNode* node ) { - _node = node; - } - /// Create a handle from a node. - XMLHandle( XMLNode& node ) { - _node = &node; - } - /// Copy constructor - XMLHandle( const XMLHandle& ref ) { - _node = ref._node; - } - /// Assignment - XMLHandle& operator=( const XMLHandle& ref ) { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { - return XMLHandle( _node ? _node->FirstChild() : 0 ); - } - /// Get the first child element of this handle. - XMLHandle FirstChildElement( const char* value=0 ) { - return XMLHandle( _node ? _node->FirstChildElement( value ) : 0 ); - } - /// Get the last child of this handle. - XMLHandle LastChild() { - return XMLHandle( _node ? _node->LastChild() : 0 ); - } - /// Get the last child element of this handle. - XMLHandle LastChildElement( const char* _value=0 ) { - return XMLHandle( _node ? _node->LastChildElement( _value ) : 0 ); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { - return XMLHandle( _node ? _node->PreviousSibling() : 0 ); - } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement( const char* _value=0 ) { - return XMLHandle( _node ? _node->PreviousSiblingElement( _value ) : 0 ); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { - return XMLHandle( _node ? _node->NextSibling() : 0 ); - } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement( const char* _value=0 ) { - return XMLHandle( _node ? _node->NextSiblingElement( _value ) : 0 ); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { - return _node; - } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { - return ( ( _node && _node->ToElement() ) ? _node->ToElement() : 0 ); - } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { - return ( ( _node && _node->ToText() ) ? _node->ToText() : 0 ); - } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { - return ( ( _node && _node->ToUnknown() ) ? _node->ToUnknown() : 0 ); - } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { - return ( ( _node && _node->ToDeclaration() ) ? _node->ToDeclaration() : 0 ); - } - -private: - XMLNode* _node; -}; - - -/** - A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the - same in all regards, except for the 'const' qualifiers. See XMLHandle for API. -*/ -class CC_DLL XMLConstHandle -{ -public: - XMLConstHandle( const XMLNode* node ) { - _node = node; - } - XMLConstHandle( const XMLNode& node ) { - _node = &node; - } - XMLConstHandle( const XMLConstHandle& ref ) { - _node = ref._node; - } - - XMLConstHandle& operator=( const XMLConstHandle& ref ) { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const { - return XMLConstHandle( _node ? _node->FirstChild() : 0 ); - } - const XMLConstHandle FirstChildElement( const char* value=0 ) const { - return XMLConstHandle( _node ? _node->FirstChildElement( value ) : 0 ); - } - const XMLConstHandle LastChild() const { - return XMLConstHandle( _node ? _node->LastChild() : 0 ); - } - const XMLConstHandle LastChildElement( const char* _value=0 ) const { - return XMLConstHandle( _node ? _node->LastChildElement( _value ) : 0 ); - } - const XMLConstHandle PreviousSibling() const { - return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); - } - const XMLConstHandle PreviousSiblingElement( const char* _value=0 ) const { - return XMLConstHandle( _node ? _node->PreviousSiblingElement( _value ) : 0 ); - } - const XMLConstHandle NextSibling() const { - return XMLConstHandle( _node ? _node->NextSibling() : 0 ); - } - const XMLConstHandle NextSiblingElement( const char* _value=0 ) const { - return XMLConstHandle( _node ? _node->NextSiblingElement( _value ) : 0 ); - } - - - const XMLNode* ToNode() const { - return _node; - } - const XMLElement* ToElement() const { - return ( ( _node && _node->ToElement() ) ? _node->ToElement() : 0 ); - } - const XMLText* ToText() const { - return ( ( _node && _node->ToText() ) ? _node->ToText() : 0 ); - } - const XMLUnknown* ToUnknown() const { - return ( ( _node && _node->ToUnknown() ) ? _node->ToUnknown() : 0 ); - } - const XMLDeclaration* ToDeclaration() const { - return ( ( _node && _node->ToDeclaration() ) ? _node->ToDeclaration() : 0 ); - } - -private: - const XMLNode* _node; -}; - - -/** - Printing functionality. The XMLPrinter gives you more - options than the XMLDocument::Print() method. - - It can: - -# Print to memory. - -# Print to a file you provide. - -# Print XML without a XMLDocument. - - Print to Memory - - @verbatim - XMLPrinter printer; - doc->Print( &printer ); - SomeFunction( printer.CStr() ); - @endverbatim - - Print to a File - - You provide the file pointer. - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Print without a XMLDocument - - When loading, an XML parser is very useful. However, sometimes - when saving, it just gets in the way. The code is often set up - for streaming, and constructing the DOM is just overhead. - - The Printer supports the streaming case. The following code - prints out a trivially simple XML file without ever creating - an XML document. - - @verbatim - XMLPrinter printer( fp ); - printer.OpenElement( "foo" ); - printer.PushAttribute( "foo", "bar" ); - printer.CloseElement(); - @endverbatim -*/ -class CC_DLL XMLPrinter : public XMLVisitor -{ -public: - /** Construct the printer. If the FILE* is specified, - this will print to the FILE. Else it will print - to memory, and the result is available in CStr(). - If 'compact' is set to true, then output is created - with only required whitespace and newlines. - */ - XMLPrinter( FILE* file=0, bool compact = false ); - ~XMLPrinter() {} - - /** If streaming, write the BOM and declaration. */ - void PushHeader( bool writeBOM, bool writeDeclaration ); - /** If streaming, start writing an element. - The element must be closed with CloseElement() - */ - void OpenElement( const char* name ); - /// If streaming, add an attribute to an open element. - void PushAttribute( const char* name, const char* value ); - void PushAttribute( const char* name, int value ); - void PushAttribute( const char* name, unsigned value ); - void PushAttribute( const char* name, bool value ); - void PushAttribute( const char* name, double value ); - /// If streaming, close the Element. - void CloseElement(); - - /// Add a text node. - void PushText( const char* text, bool cdata=false ); - /// Add a text node from an integer. - void PushText( int value ); - /// Add a text node from an unsigned. - void PushText( unsigned value ); - /// Add a text node from a bool. - void PushText( bool value ); - /// Add a text node from a float. - void PushText( float value ); - /// Add a text node from a double. - void PushText( double value ); - - /// Add a comment - void PushComment( const char* comment ); - - void PushDeclaration( const char* value ); - void PushUnknown( const char* value ); - - virtual bool VisitEnter( const XMLDocument& /*doc*/ ); - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); - virtual bool VisitExit( const XMLElement& element ); - - virtual bool Visit( const XMLText& text ); - virtual bool Visit( const XMLComment& comment ); - virtual bool Visit( const XMLDeclaration& declaration ); - virtual bool Visit( const XMLUnknown& unknown ); - - /** - If in print to memory mode, return a pointer to - the XML file in memory. - */ - const char* CStr() const { - return _buffer.Mem(); - } - /** - If in print to memory mode, return the size - of the XML file in memory. (Note the size returned - includes the terminating null.) - */ - int CStrSize() const { - return _buffer.Size(); - } - -private: - void SealElement(); - void PrintSpace( int depth ); - void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. - void Print( const char* format, ... ); - - bool _elementJustOpened; - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum { - ENTITY_RANGE = 64, - BUF_SIZE = 200 - }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray< const char*, 10 > _stack; - DynArray< char, 20 > _buffer; -#ifdef _MSC_VER - DynArray< char, 20 > _accumulator; -#endif -}; - - -} // tinyxml2 - - -#endif // TINYXML2_INCLUDED diff --git a/cocos/2d/support/zip_support/ioapi.cpp b/cocos/2d/support/zip_support/ioapi.cpp deleted file mode 100644 index 669ea36927..0000000000 --- a/cocos/2d/support/zip_support/ioapi.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/* ioapi.h -- IO base function header for compress/uncompress .zip - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - -*/ - -#include "ioapi.h" - -namespace cocos2d { - -voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) -{ - if (pfilefunc->zfile_func64.zopen64_file != NULL) - return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); - else - { - return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); - } -} - -long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) -{ - if (pfilefunc->zfile_func64.zseek64_file != NULL) - return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); - else - { - uLong offsetTruncated = (uLong)offset; - if (offsetTruncated != offset) - return -1; - else - return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); - } -} - -ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) -{ - if (pfilefunc->zfile_func64.zseek64_file != NULL) - return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); - else - { - uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); - if ((tell_uLong) == ((uLong)-1)) - return (ZPOS64_T)-1; - else - return tell_uLong; - } -} - -void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) -{ - p_filefunc64_32->zfile_func64.zopen64_file = NULL; - p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; - p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; - p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; - p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; - p_filefunc64_32->zfile_func64.ztell64_file = NULL; - p_filefunc64_32->zfile_func64.zseek64_file = NULL; - p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; - p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; - p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; - p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; - p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; -} - - - -static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); -static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); -static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); -static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); -static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); -static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); - -static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) -{ - FILE* file = NULL; - const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename!=NULL) && (mode_fopen != NULL)) - file = fopen(filename, mode_fopen); - return file; -} - -static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) -{ - FILE* file = NULL; - const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename!=NULL) && (mode_fopen != NULL)) - { -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) - file = NULL; -#else - file = fopen64((const char*)filename, mode_fopen); -#endif - } - - return file; -} - - -static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) -{ - uLong ret; - ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); - return ret; -} - -static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) -{ - uLong ret; - ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); - return ret; -} - -static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) -{ - long ret; - ret = ftell((FILE *)stream); - return ret; -} - - -static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) -{ - ZPOS64_T ret; -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) - ret = 0; -#else - ret = ftello64((FILE *)stream); -#endif - return ret; -} - -static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) -{ - int fseek_origin=0; - long ret; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: return -1; - } - ret = 0; - if (fseek((FILE *)stream, offset, fseek_origin) != 0) - ret = -1; - return ret; -} - -static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) -{ -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE || CC_TARGET_PLATFORM == CC_PLATFORM_BADA || CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_NACL || CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) - return -1; -#else - int fseek_origin=0; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: return -1; - } - if(fseeko64((FILE *)stream, offset, fseek_origin) != 0) - return -1; - return 0; -#endif -} - - -static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) -{ - int ret; - ret = fclose((FILE *)stream); - return ret; -} - -static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) -{ - int ret; - ret = ferror((FILE *)stream); - return ret; -} - -void fill_fopen_filefunc (zlib_filefunc_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen_file = fopen_file_func; - pzlib_filefunc_def->zread_file = fread_file_func; - pzlib_filefunc_def->zwrite_file = fwrite_file_func; - pzlib_filefunc_def->ztell_file = ftell_file_func; - pzlib_filefunc_def->zseek_file = fseek_file_func; - pzlib_filefunc_def->zclose_file = fclose_file_func; - pzlib_filefunc_def->zerror_file = ferror_file_func; - pzlib_filefunc_def->opaque = NULL; -} - -void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen64_file = fopen64_file_func; - pzlib_filefunc_def->zread_file = fread_file_func; - pzlib_filefunc_def->zwrite_file = fwrite_file_func; - pzlib_filefunc_def->ztell64_file = ftell64_file_func; - pzlib_filefunc_def->zseek64_file = fseek64_file_func; - pzlib_filefunc_def->zclose_file = fclose_file_func; - pzlib_filefunc_def->zerror_file = ferror_file_func; - pzlib_filefunc_def->opaque = NULL; -} - -} // end of namespace cocos2d diff --git a/cocos/2d/support/zip_support/ioapi.h b/cocos/2d/support/zip_support/ioapi.h deleted file mode 100644 index 575f44ece4..0000000000 --- a/cocos/2d/support/zip_support/ioapi.h +++ /dev/null @@ -1,201 +0,0 @@ -/* ioapi.h -- IO base function header for compress/uncompress .zip - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - Changes - - Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) - Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. - More if/def section may be needed to support other platforms - Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. - (but you should use iowin32.c for windows instead) - -*/ - -#ifndef _ZLIBIOAPI64_H -#define _ZLIBIOAPI64_H - -#include "platform/CCPlatformConfig.h" - -#if (!defined(_WIN32)) && (!defined(WIN32)) - - // Linux needs this to support file operation on files larger then 4+GB - // But might need better if/def to select just the platforms that needs them. - - #ifndef __USE_FILE_OFFSET64 - #define __USE_FILE_OFFSET64 - #endif - #ifndef __USE_LARGEFILE64 - #define __USE_LARGEFILE64 - #endif - #ifndef _LARGEFILE64_SOURCE - #define _LARGEFILE64_SOURCE - #endif - #ifndef _FILE_OFFSET_BIT - #define _FILE_OFFSET_BIT 64 - #endif -#endif - -#include -#include -#include "zlib.h" - -namespace cocos2d { - -#ifndef OF -#define OF _Z_OF -#endif - -#if defined(USE_FILE32API) -#define fopen64 fopen -#define ftello64 ftell -#define fseeko64 fseek -#else -#ifdef _MSC_VER - #define fopen64 fopen - #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) - #define ftello64 _ftelli64 - #define fseeko64 _fseeki64 - #else // old MSC - #define ftello64 ftell - #define fseeko64 fseek - #endif -#endif -#endif - -/* -#ifndef ZPOS64_T - #ifdef _WIN32 - #define ZPOS64_T fpos_t - #else - #include - #define ZPOS64_T uint64_t - #endif -#endif -*/ - -#ifdef HAVE_MINIZIP64_CONF_H -#include "mz64conf.h" -#endif - -/* a type chosen by DEFINE */ -#ifdef HAVE_64BIT_INT_CUSTOM -typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; -#else -#ifdef HAS_STDINT_H -#include "stdint.h" -typedef uint64_t ZPOS64_T; -#else - - -#if defined(_MSC_VER) || defined(__BORLANDC__) -typedef unsigned __int64 ZPOS64_T; -#else -typedef unsigned long long int ZPOS64_T; -#endif -#endif -#endif - - - -#define ZLIB_FILEFUNC_SEEK_CUR (1) -#define ZLIB_FILEFUNC_SEEK_END (2) -#define ZLIB_FILEFUNC_SEEK_SET (0) - -#define ZLIB_FILEFUNC_MODE_READ (1) -#define ZLIB_FILEFUNC_MODE_WRITE (2) -#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) - -#define ZLIB_FILEFUNC_MODE_EXISTING (4) -#define ZLIB_FILEFUNC_MODE_CREATE (8) - - -#ifndef ZCALLBACK - #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) - #define ZCALLBACK CALLBACK - #else - #define ZCALLBACK - #endif -#endif - - - - -typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); -typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); -typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); -typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); - -typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); -typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); - - -/* here is the "old" 32 bits structure structure */ -typedef struct zlib_filefunc_def_s -{ - open_file_func zopen_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell_file_func ztell_file; - seek_file_func zseek_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; -} zlib_filefunc_def; - -typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); -typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); -typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode)); - -typedef struct zlib_filefunc64_def_s -{ - open64_file_func zopen64_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell64_file_func ztell64_file; - seek64_file_func zseek64_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; -} zlib_filefunc64_def; - -void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); -void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); - -/* now internal definition, only for zip.c and unzip.h */ -typedef struct zlib_filefunc64_32_def_s -{ - zlib_filefunc64_def zfile_func64; - open_file_func zopen32_file; - tell_file_func ztell32_file; - seek_file_func zseek32_file; -} zlib_filefunc64_32_def; - - -#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) -#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) -//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) -//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) -#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) -#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) - -voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)); -long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); -ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); - -void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); - -#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) -#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) -#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) - -} // end of namespace cocos2d - -#endif diff --git a/cocos/2d/support/zip_support/unzip.cpp b/cocos/2d/support/zip_support/unzip.cpp deleted file mode 100644 index 66cfeff16a..0000000000 --- a/cocos/2d/support/zip_support/unzip.cpp +++ /dev/null @@ -1,2161 +0,0 @@ -/* unzip.c -- IO for uncompress .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications of Unzip for Zip64 - Copyright (C) 2007-2008 Even Rouault - - Modifications for Zip64 support on both zip and unzip - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - - ------------------------------------------------------------------------------------ - Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of - compatibility with older software. The following is from the original crypt.c. - Code woven in by Terry Thorsen 1/2003. - - Copyright (c) 1990-2000 Info-ZIP. All rights reserved. - - See the accompanying file LICENSE, version 2000-Apr-09 or later - (the contents of which are also included in zip.h) for terms of use. - If, for some reason, all these files are missing, the Info-ZIP license - also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html - - crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] - - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) - - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). - - ------------------------------------------------------------------------------------ - - Changes in unzip.c - - 2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos - 2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz* - 2007-2008 - Even Rouault - Remove old C style function prototypes - 2007-2008 - Even Rouault - Add unzip support for ZIP64 - - Copyright (C) 2007-2008 Even Rouault - - - Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again). - Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G - should only read the compressed/uncompressed size from the Zip64 format if - the size from normal header was 0xFFFFFFFF - Oct-2009 - Mathias Svensson - Applied some bug fixes from patches received from Gilles Vollant - Oct-2009 - Mathias Svensson - Applied support to unzip files with compression method BZIP2 (bzip2 lib is required) - Patch created by Daniel Borca - - Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer - - Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson - -*/ - - -#include -#include -#include - -#ifndef NOUNCRYPT - #define NOUNCRYPT -#endif - -#include "zlib.h" -#include "unzip.h" - -#ifdef STDC -# include -# include -# include -#endif -#ifdef NO_ERRNO_H - extern int errno; -#else -# include -#endif - -namespace cocos2d { - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - - -#ifndef CASESENSITIVITYDEFAULT_NO -# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) -# define CASESENSITIVITYDEFAULT_NO -# endif -#endif - - -#ifndef UNZ_BUFSIZE -#define UNZ_BUFSIZE (16384) -#endif - -#ifndef UNZ_MAXFILENAMEINZIP -#define UNZ_MAXFILENAMEINZIP (256) -#endif - -#ifndef ALLOC -# define ALLOC(size) (malloc(size)) -#endif -#ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} -#endif - -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) - - -const char unz_copyright[] = - " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; - -/* unz_file_info_interntal contain internal info about a file in zipfile*/ -typedef struct unz_file_info64_internal_s -{ - ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */ -} unz_file_info64_internal; - - -/* file_in_zip_read_info_s contain internal information about a file in zipfile, - when reading and decompress it */ -typedef struct -{ - char *read_buffer; /* internal buffer for compressed data */ - z_stream stream; /* zLib stream structure for inflate */ - -#ifdef HAVE_BZIP2 - bz_stream bstream; /* bzLib stream structure for bziped */ -#endif - - ZPOS64_T pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ - uLong stream_initialised; /* flag set if stream structure is initialized*/ - - ZPOS64_T offset_local_extrafield;/* offset of the local extra field */ - uInt size_local_extrafield;/* size of the local extra field */ - ZPOS64_T pos_local_extrafield; /* position in the local extra field in read*/ - ZPOS64_T total_out_64; - - uLong crc32; /* crc32 of all data uncompressed */ - uLong crc32_wait; /* crc32 we must obtain after decompress all */ - ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */ - ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/ - zlib_filefunc64_32_def z_filefunc; - voidpf filestream; /* io structure of the zipfile */ - uLong compression_method; /* compression method (0==store) */ - ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - int raw; -} file_in_zip64_read_info_s; - - -/* unz64_s contain internal information about the zipfile -*/ -typedef struct -{ - zlib_filefunc64_32_def z_filefunc; - int is64bitOpenFunction; - voidpf filestream; /* io structure of the zipfile */ - unz_global_info64 gi; /* public global information */ - ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - ZPOS64_T num_file; /* number of the current file in the zipfile*/ - ZPOS64_T pos_in_central_dir; /* pos of the current file in the central dir*/ - ZPOS64_T current_file_ok; /* flag about the usability of the current file*/ - ZPOS64_T central_pos; /* position of the beginning of the central dir*/ - - ZPOS64_T size_central_dir; /* size of the central directory */ - ZPOS64_T offset_central_dir; /* offset of start of central directory with - respect to the starting disk number */ - - unz_file_info64 cur_file_info; /* public info about the current file in zip*/ - unz_file_info64_internal cur_file_info_internal; /* private info about it*/ - file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current - file if we are decompressing it */ - int encrypted; - - int isZip64; - -# ifndef NOUNCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ - const unsigned long* pcrc_32_tab; -# endif -} unz64_s; - - -#ifndef NOUNCRYPT -#include "crypt.h" -#endif - -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been successfully opened for reading. -*/ - - -local int unz64local_getByte OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - int *pi)); - -local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi) -{ - unsigned char c; - int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); - if (err==1) - { - *pi = (int)c; - return UNZ_OK; - } - else - { - if (ZERROR64(*pzlib_filefunc_def,filestream)) - return UNZ_ERRNO; - else - return UNZ_EOF; - } -} - - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ -local int unz64local_getShort OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX)); - -local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX) -{ - uLong x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<8; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int unz64local_getLong OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX)); - -local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX) -{ - uLong x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<8; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<16; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<24; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int unz64local_getLong64 OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - ZPOS64_T *pX)); - - -local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - ZPOS64_T *pX) -{ - ZPOS64_T x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (ZPOS64_T)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<8; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<16; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<24; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<32; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<40; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<48; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<56; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -/* My own strcmpi / strcasecmp */ -local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2) -{ - for (;;) - { - char c1=*(fileName1++); - char c2=*(fileName2++); - if ((c1>='a') && (c1<='z')) - c1 -= 0x20; - if ((c2>='a') && (c2<='z')) - c2 -= 0x20; - if (c1=='\0') - return ((c2=='\0') ? 0 : -1); - if (c2=='\0') - return 1; - if (c1c2) - return 1; - } -} - - -#ifdef CASESENSITIVITYDEFAULT_NO -#define CASESENSITIVITYDEFAULTVALUE 2 -#else -#define CASESENSITIVITYDEFAULTVALUE 1 -#endif - -#ifndef STRCMPCASENOSENTIVEFUNCTION -#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal -#endif - -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparison is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparison is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is default of your operating system - (like 1 on Unix, 2 on Windows) - -*/ -int ZEXPORT unzStringFileNameCompare (const char* fileName1, - const char* fileName2, - int iCaseSensitivity) - -{ - if (iCaseSensitivity==0) - iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; - - if (iCaseSensitivity==1) - return strcmp(fileName1,fileName2); - - return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); -} - -#ifndef BUFREADCOMMENT -#define BUFREADCOMMENT (0x400) -#endif - -/* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ -local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); -local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - return uPosFound; -} - - -/* - Locate the Central directory 64 of a zipfile (at the end, just before - the global comment) -*/ -local ZPOS64_T unz64local_SearchCentralDir64 OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream)); - -local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - uLong uL; - ZPOS64_T relativeOffset; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - if (uPosFound == 0) - return 0; - - /* Zip64 end of central directory locator */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature, already checked */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - - /* number of the disk with the start of the zip64 end of central directory */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - if (uL != 0) - return 0; - - /* relative offset of the zip64 end of central directory record */ - if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK) - return 0; - - /* total number of disks */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - if (uL != 1) - return 0; - - /* Goto end of central directory record */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - - if (uL != 0x06064b50) - return 0; - - return relativeOffset; -} - -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer - "zlib/zlib114.zip". - If the zipfile cannot be opened (file doesn't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ -local unzFile unzOpenInternal (const void *path, - zlib_filefunc64_32_def* pzlib_filefunc64_32_def, - int is64bitOpenFunction) -{ - unz64_s us; - unz64_s *s; - ZPOS64_T central_pos; - uLong uL; - - uLong number_disk; /* number of the current dist, used for - spanning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spanning ZIP, unsupported, always 0*/ - ZPOS64_T number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - - int err=UNZ_OK; - - if (unz_copyright[0]!=' ') - return NULL; - - us.z_filefunc.zseek32_file = NULL; - us.z_filefunc.ztell32_file = NULL; - if (pzlib_filefunc64_32_def==NULL) - fill_fopen64_filefunc(&us.z_filefunc.zfile_func64); - else - us.z_filefunc = *pzlib_filefunc64_32_def; - us.is64bitOpenFunction = is64bitOpenFunction; - - - - us.filestream = ZOPEN64(us.z_filefunc, - path, - ZLIB_FILEFUNC_MODE_READ | - ZLIB_FILEFUNC_MODE_EXISTING); - if (us.filestream==NULL) - return NULL; - - central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream); - if (central_pos) - { - uLong uS; - ZPOS64_T uL64; - - us.isZip64 = 1; - - if (ZSEEK64(us.z_filefunc, us.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* size of zip64 end of central directory record */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK) - err=UNZ_ERRNO; - - /* version made by */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) - err=UNZ_ERRNO; - - /* version needed to extract */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central directory on this disk */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central directory */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - us.gi.size_comment = 0; - } - else - { - central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream); - if (central_pos==0) - err=UNZ_ERRNO; - - us.isZip64 = 0; - - if (ZSEEK64(us.z_filefunc, us.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir on this disk */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.gi.number_entry = uL; - - /* total number of entries in the central dir */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - number_entry_CD = uL; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.size_central_dir = uL; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.offset_central_dir = uL; - - /* zipfile comment length */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) - err=UNZ_ERRNO; - } - - if ((central_pospfile_in_zip_read!=NULL) - unzCloseCurrentFile(file); - - ZCLOSE64(s->z_filefunc, s->filestream); - TRYFREE(s); - return UNZ_OK; -} - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ -int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info) -{ - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - *pglobal_info=s->gi; - return UNZ_OK; -} - -int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32) -{ - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - /* to do : check if number_entry is not truncated */ - pglobal_info32->number_entry = (uLong)s->gi.number_entry; - pglobal_info32->size_comment = s->gi.size_comment; - return UNZ_OK; -} -/* - Translate date/time from Dos format to tm_unz (readable more easily) -*/ -local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm) -{ - ZPOS64_T uDate; - uDate = (ZPOS64_T)(ulDosDate>>16); - ptm->tm_mday = (uInt)(uDate&0x1f) ; - ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; - ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; - - ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); - ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; - ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; -} - -/* - Get Info about the current file in the zipfile, with internal only info -*/ -local int unz64local_GetCurrentFileInfoInternal OF((unzFile file, - unz_file_info64 *pfile_info, - unz_file_info64_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); - -local int unz64local_GetCurrentFileInfoInternal (unzFile file, - unz_file_info64 *pfile_info, - unz_file_info64_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize) -{ - unz64_s* s; - unz_file_info64 file_info; - unz_file_info64_internal file_info_internal; - int err=UNZ_OK; - uLong uMagic; - long lSeek=0; - uLong uL; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (ZSEEK64(s->z_filefunc, s->filestream, - s->pos_in_central_dir+s->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - - /* we check the magic */ - if (err==UNZ_OK) - { - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x02014b50) - err=UNZ_BADZIPFILE; - } - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) - err=UNZ_ERRNO; - - unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info.compressed_size = uL; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info.uncompressed_size = uL; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) - err=UNZ_ERRNO; - - // relative offset of local header - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info_internal.offset_curfile = uL; - - lSeek+=file_info.size_filename; - if ((err==UNZ_OK) && (szFileName!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_filename0) && (fileNameBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek -= uSizeRead; - } - - // Read extrafield - if ((err==UNZ_OK) && (extraField!=NULL)) - { - ZPOS64_T uSizeRead ; - if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - } - - if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - - lSeek += file_info.size_file_extra - (uLong)uSizeRead; - } - else - lSeek += file_info.size_file_extra; - - - if ((err==UNZ_OK) && (file_info.size_file_extra != 0)) - { - uLong acc = 0; - - // since lSeek now points to after the extra field we need to move back - lSeek -= file_info.size_file_extra; - - if (lSeek!=0) - { - if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - } - - while(acc < file_info.size_file_extra) - { - uLong headerId; - uLong dataSize; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK) - err=UNZ_ERRNO; - - /* ZIP64 extra fields */ - if (headerId == 0x0001) - { - uLong uL; - - if(file_info.uncompressed_size == (ZPOS64_T)(unsigned long)-1) - { - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info.compressed_size == (ZPOS64_T)(unsigned long)-1) - { - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info_internal.offset_curfile == (ZPOS64_T)(unsigned long)-1) - { - /* Relative Header offset */ - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info.disk_num_start == (unsigned long)-1) - { - /* Disk Start Number */ - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - } - - } - else - { - if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) - err=UNZ_ERRNO; - } - - acc += 2 + 2 + dataSize; - } - } - - if ((err==UNZ_OK) && (szComment!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) { - //lSeek=0; - } - else - err=UNZ_ERRNO; - } - - if ((file_info.size_file_comment>0) && (commentBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - //lSeek+=file_info.size_file_comment - uSizeRead; - } - //else - // lSeek+=file_info.size_file_comment; - - - if ((err==UNZ_OK) && (pfile_info!=NULL)) - *pfile_info=file_info; - - if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) - *pfile_info_internal=file_info_internal; - - return err; -} - - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. -*/ -int ZEXPORT unzGetCurrentFileInfo64 (unzFile file, - unz_file_info64 * pfile_info, - char * szFileName, uLong fileNameBufferSize, - void *extraField, uLong extraFieldBufferSize, - char* szComment, uLong commentBufferSize) -{ - return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); -} - -int ZEXPORT unzGetCurrentFileInfo (unzFile file, - unz_file_info * pfile_info, - char * szFileName, uLong fileNameBufferSize, - void *extraField, uLong extraFieldBufferSize, - char* szComment, uLong commentBufferSize) -{ - int err; - unz_file_info64 file_info64; - err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); - if (err==UNZ_OK) - { - pfile_info->version = file_info64.version; - pfile_info->version_needed = file_info64.version_needed; - pfile_info->flag = file_info64.flag; - pfile_info->compression_method = file_info64.compression_method; - pfile_info->dosDate = file_info64.dosDate; - pfile_info->crc = file_info64.crc; - - pfile_info->size_filename = file_info64.size_filename; - pfile_info->size_file_extra = file_info64.size_file_extra; - pfile_info->size_file_comment = file_info64.size_file_comment; - - pfile_info->disk_num_start = file_info64.disk_num_start; - pfile_info->internal_fa = file_info64.internal_fa; - pfile_info->external_fa = file_info64.external_fa; - - pfile_info->tmu_date = file_info64.tmu_date, - - - pfile_info->compressed_size = (uLong)file_info64.compressed_size; - pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; - - } - return err; -} - -/* - Set the current file of the zipfile to the first file - with retrieving an information about the file. - return UNZ_OK if there is no problem -*/ -int ZEXPORT unzGoToFirstFile64 (unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize) -{ - int err=UNZ_OK; - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - s->pos_in_central_dir=s->offset_central_dir; - s->num_file=0; - err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - szFileName,fileNameBufferSize,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - if (pfile_info) - *pfile_info = s->cur_file_info; - return err; -} - -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ -int ZEXPORT unzGoToFirstFile (unzFile file) -{ - return unzGoToFirstFile64(file, NULL, NULL, 0); -} - -/* - Set the current file of the zipfile to the next file - with retrieving an information about the file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -int ZEXPORT unzGoToNextFile64 (unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize) -{ - unz64_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ - if (s->num_file+1==s->gi.number_entry) - return UNZ_END_OF_LIST_OF_FILE; - - s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + - s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; - s->num_file++; - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - szFileName,fileNameBufferSize,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - if (pfile_info) - *pfile_info = s->cur_file_info; - return err; -} - -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -int ZEXPORT unzGoToNextFile (unzFile file) -{ - return unzGoToNextFile64(file, NULL, NULL, 0); -} - - -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzipStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ -int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) -{ - unz64_s* s; - int err; - - /* We remember the 'current' position in the file so that we can jump - * back there if we fail. - */ - unz_file_info64 cur_file_infoSaved; - unz_file_info64_internal cur_file_info_internalSaved; - ZPOS64_T num_fileSaved; - ZPOS64_T pos_in_central_dirSaved; - - - if (file==NULL) - return UNZ_PARAMERROR; - - if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) - return UNZ_PARAMERROR; - - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - /* Save the current state */ - num_fileSaved = s->num_file; - pos_in_central_dirSaved = s->pos_in_central_dir; - cur_file_infoSaved = s->cur_file_info; - cur_file_info_internalSaved = s->cur_file_info_internal; - - err = unzGoToFirstFile(file); - - while (err == UNZ_OK) - { - char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; - err = unzGetCurrentFileInfo64(file,NULL, - szCurrentFileName,sizeof(szCurrentFileName)-1, - NULL,0,NULL,0); - if (err == UNZ_OK) - { - if (unzStringFileNameCompare(szCurrentFileName, - szFileName,iCaseSensitivity)==0) - return UNZ_OK; - err = unzGoToNextFile(file); - } - } - - /* We failed, so restore the state of the 'current file' to where we - * were. - */ - s->num_file = num_fileSaved ; - s->pos_in_central_dir = pos_in_central_dirSaved ; - s->cur_file_info = cur_file_infoSaved; - s->cur_file_info_internal = cur_file_info_internalSaved; - return err; -} - - -/* -/////////////////////////////////////////// -// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) -// I need random access -// -// Further optimization could be realized by adding an ability -// to cache the directory in memory. The goal being a single -// comprehensive file read to put the file I need in a memory. -*/ - -/* -typedef struct unz_file_pos_s -{ - ZPOS64_T pos_in_zip_directory; // offset in file - ZPOS64_T num_of_file; // # of file -} unz_file_pos; -*/ - -int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos* file_pos) -{ - unz64_s* s; - - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - file_pos->pos_in_zip_directory = s->pos_in_central_dir; - file_pos->num_of_file = s->num_file; - - return UNZ_OK; -} - -int ZEXPORT unzGetFilePos( - unzFile file, - unz_file_pos* file_pos) -{ - unz64_file_pos file_pos64; - int err = unzGetFilePos64(file,&file_pos64); - if (err==UNZ_OK) - { - file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory; - file_pos->num_of_file = (uLong)file_pos64.num_of_file; - } - return err; -} - -int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos) -{ - unz64_s* s; - int err; - - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - - /* jump to the right spot */ - s->pos_in_central_dir = file_pos->pos_in_zip_directory; - s->num_file = file_pos->num_of_file; - - /* set the current file */ - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - /* return results */ - s->current_file_ok = (err == UNZ_OK); - return err; -} - -int ZEXPORT unzGoToFilePos( - unzFile file, - unz_file_pos* file_pos) -{ - unz64_file_pos file_pos64; - if (file_pos == NULL) - return UNZ_PARAMERROR; - - file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; - file_pos64.num_of_file = file_pos->num_of_file; - return unzGoToFilePos64(file,&file_pos64); -} - -/* -// Unzip Helper Functions - should be here? -/////////////////////////////////////////// -*/ - -/* - Read the local header of the current zipfile - Check the coherency of the local header and info in the end of central - directory about this file - store in *piSizeVar the size of extra info in local header - (filename and size of extra field data) -*/ -local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar, - ZPOS64_T * poffset_local_extrafield, - uInt * psize_local_extrafield) -{ - uLong uMagic,uData,uFlags; - uLong size_filename; - uLong size_extra_field; - int err=UNZ_OK; - - *piSizeVar = 0; - *poffset_local_extrafield = 0; - *psize_local_extrafield = 0; - - if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + - s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - - if (err==UNZ_OK) - { - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x04034b50) - err=UNZ_BADZIPFILE; - } - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; -/* - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) - err=UNZ_BADZIPFILE; -*/ - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) - err=UNZ_BADZIPFILE; - - if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && -/* #ifdef HAVE_BZIP2 */ - (s->cur_file_info.compression_method!=Z_BZIP2ED) && -/* #endif */ - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ - err=UNZ_ERRNO; - else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ - err=UNZ_ERRNO; - else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) - err=UNZ_BADZIPFILE; - - *piSizeVar += (uInt)size_filename; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) - err=UNZ_ERRNO; - *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + - SIZEZIPLOCALHEADER + size_filename; - *psize_local_extrafield = (uInt)size_extra_field; - - *piSizeVar += (uInt)size_extra_field; - - return err; -} - -/* - Open for reading data the current file in the zipfile. - If there is no error and the file is opened, the return value is UNZ_OK. -*/ -int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, - int* level, int raw, const char* password) -{ - int err=UNZ_OK; - uInt iSizeVar; - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - ZPOS64_T offset_local_extrafield; /* offset of the local extra field */ - uInt size_local_extrafield; /* size of the local extra field */ -# ifndef NOUNCRYPT - char source[12]; -# else - if (password != NULL) - return UNZ_PARAMERROR; -# endif - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_PARAMERROR; - - if (s->pfile_in_zip_read != NULL) - unzCloseCurrentFile(file); - - if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) - return UNZ_BADZIPFILE; - - pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s)); - if (pfile_in_zip_read_info==NULL) - return UNZ_INTERNALERROR; - - pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); - pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; - pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; - pfile_in_zip_read_info->pos_local_extrafield=0; - pfile_in_zip_read_info->raw=raw; - - if (pfile_in_zip_read_info->read_buffer==NULL) - { - TRYFREE(pfile_in_zip_read_info); - return UNZ_INTERNALERROR; - } - - pfile_in_zip_read_info->stream_initialised=0; - - if (method!=NULL) - *method = (int)s->cur_file_info.compression_method; - - if (level!=NULL) - { - *level = 6; - switch (s->cur_file_info.flag & 0x06) - { - case 6 : *level = 1; break; - case 4 : *level = 2; break; - case 2 : *level = 9; break; - } - } - - if ((s->cur_file_info.compression_method!=0) && -/* #ifdef HAVE_BZIP2 */ - (s->cur_file_info.compression_method!=Z_BZIP2ED) && -/* #endif */ - (s->cur_file_info.compression_method!=Z_DEFLATED)) { - - //err=UNZ_BADZIPFILE; - } - pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; - pfile_in_zip_read_info->crc32=0; - pfile_in_zip_read_info->total_out_64=0; - pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; - pfile_in_zip_read_info->filestream=s->filestream; - pfile_in_zip_read_info->z_filefunc=s->z_filefunc; - pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; - - pfile_in_zip_read_info->stream.total_out = 0; - - if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) - { -#ifdef HAVE_BZIP2 - pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; - pfile_in_zip_read_info->bstream.bzfree = (free_func)0; - pfile_in_zip_read_info->bstream.opaque = (voidpf)0; - pfile_in_zip_read_info->bstream.state = (voidpf)0; - - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidpf)0; - pfile_in_zip_read_info->stream.next_in = (voidpf)0; - pfile_in_zip_read_info->stream.avail_in = 0; - - err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; - else - { - TRYFREE(pfile_in_zip_read_info); - return err; - } -#else - pfile_in_zip_read_info->raw=1; -#endif - } - else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) - { - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidpf)0; - pfile_in_zip_read_info->stream.next_in = 0; - pfile_in_zip_read_info->stream.avail_in = 0; - - err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; - else - { - TRYFREE(pfile_in_zip_read_info); - return err; - } - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. - * In unzip, i don't wait absolutely Z_STREAM_END because I known the - * size of both compressed and uncompressed data - */ - } - pfile_in_zip_read_info->rest_read_compressed = - s->cur_file_info.compressed_size ; - pfile_in_zip_read_info->rest_read_uncompressed = - s->cur_file_info.uncompressed_size ; - - - pfile_in_zip_read_info->pos_in_zipfile = - s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + - iSizeVar; - - pfile_in_zip_read_info->stream.avail_in = (uInt)0; - - s->pfile_in_zip_read = pfile_in_zip_read_info; - s->encrypted = 0; - -# ifndef NOUNCRYPT - if (password != NULL) - { - int i; - s->pcrc_32_tab = get_crc_table(); - init_keys(password,s->keys,s->pcrc_32_tab); - if (ZSEEK64(s->z_filefunc, s->filestream, - s->pfile_in_zip_read->pos_in_zipfile + - s->pfile_in_zip_read->byte_before_the_zipfile, - SEEK_SET)!=0) - return UNZ_INTERNALERROR; - if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12) - return UNZ_INTERNALERROR; - - for (i = 0; i<12; i++) - zdecode(s->keys,s->pcrc_32_tab,source[i]); - - s->pfile_in_zip_read->pos_in_zipfile+=12; - s->encrypted=1; - } -# endif - - - return UNZ_OK; -} - -int ZEXPORT unzOpenCurrentFile (unzFile file) -{ - return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); -} - -int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char* password) -{ - return unzOpenCurrentFile3(file, NULL, NULL, 0, password); -} - -int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw) -{ - return unzOpenCurrentFile3(file, method, level, raw, NULL); -} - -/** Addition for GDAL : START */ - -ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - s=(unz64_s*)file; - if (file==NULL) - return 0; //UNZ_PARAMERROR; - pfile_in_zip_read_info=s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) - return 0; //UNZ_PARAMERROR; - return pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile; -} - -/** Addition for GDAL : END */ - -/* - Read bytes from the current file. - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if some bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ -int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) -{ - int err=UNZ_OK; - uInt iRead = 0; - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if (pfile_in_zip_read_info->read_buffer == NULL) - return UNZ_END_OF_LIST_OF_FILE; - if (len==0) - return 0; - - pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; - - pfile_in_zip_read_info->stream.avail_out = (uInt)len; - - if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && - (!(pfile_in_zip_read_info->raw))) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_uncompressed; - - if ((len>pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in) && - (pfile_in_zip_read_info->raw)) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in; - - while (pfile_in_zip_read_info->stream.avail_out>0) - { - if ((pfile_in_zip_read_info->stream.avail_in==0) && - (pfile_in_zip_read_info->rest_read_compressed>0)) - { - uInt uReadThis = UNZ_BUFSIZE; - if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; - if (uReadThis == 0) - return UNZ_EOF; - if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - if (ZREAD64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->read_buffer, - uReadThis)!=uReadThis) - return UNZ_ERRNO; - - -# ifndef NOUNCRYPT - if(s->encrypted) - { - uInt i; - for(i=0;iread_buffer[i] = - zdecode(s->keys,s->pcrc_32_tab, - pfile_in_zip_read_info->read_buffer[i]); - } -# endif - - - pfile_in_zip_read_info->pos_in_zipfile += uReadThis; - - pfile_in_zip_read_info->rest_read_compressed-=uReadThis; - - pfile_in_zip_read_info->stream.next_in = - (Bytef*)pfile_in_zip_read_info->read_buffer; - pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; - } - - if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) - { - uInt uDoCopy,i ; - - if ((pfile_in_zip_read_info->stream.avail_in == 0) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - return (iRead==0) ? UNZ_EOF : iRead; - - if (pfile_in_zip_read_info->stream.avail_out < - pfile_in_zip_read_info->stream.avail_in) - uDoCopy = pfile_in_zip_read_info->stream.avail_out ; - else - uDoCopy = pfile_in_zip_read_info->stream.avail_in ; - - for (i=0;istream.next_out+i) = - *(pfile_in_zip_read_info->stream.next_in+i); - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy; - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, - pfile_in_zip_read_info->stream.next_out, - uDoCopy); - pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; - pfile_in_zip_read_info->stream.avail_in -= uDoCopy; - pfile_in_zip_read_info->stream.avail_out -= uDoCopy; - pfile_in_zip_read_info->stream.next_out += uDoCopy; - pfile_in_zip_read_info->stream.next_in += uDoCopy; - pfile_in_zip_read_info->stream.total_out += uDoCopy; - iRead += uDoCopy; - } - else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) - { -#ifdef HAVE_BZIP2 - uLong uTotalOutBefore,uTotalOutAfter; - const Bytef *bufBefore; - uLong uOutThis; - - pfile_in_zip_read_info->bstream.next_in = (char*)pfile_in_zip_read_info->stream.next_in; - pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; - pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; - pfile_in_zip_read_info->bstream.total_in_hi32 = 0; - pfile_in_zip_read_info->bstream.next_out = (char*)pfile_in_zip_read_info->stream.next_out; - pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; - pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; - pfile_in_zip_read_info->bstream.total_out_hi32 = 0; - - uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; - bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out; - - err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); - - uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); - pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->bstream.next_in; - pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; - pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; - pfile_in_zip_read_info->stream.next_out = (Bytef*)pfile_in_zip_read_info->bstream.next_out; - pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; - pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; - - if (err==BZ_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=BZ_OK) - break; -#endif - } // end Z_BZIP2ED - else - { - ZPOS64_T uTotalOutBefore,uTotalOutAfter; - const Bytef *bufBefore; - ZPOS64_T uOutThis; - int flush=Z_SYNC_FLUSH; - - uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; - bufBefore = pfile_in_zip_read_info->stream.next_out; - - /* - if ((pfile_in_zip_read_info->rest_read_uncompressed == - pfile_in_zip_read_info->stream.avail_out) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - flush = Z_FINISH; - */ - err=inflate(&pfile_in_zip_read_info->stream,flush); - - if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) - err = Z_DATA_ERROR; - - uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; - - pfile_in_zip_read_info->crc32 = - crc32(pfile_in_zip_read_info->crc32,bufBefore, - (uInt)(uOutThis)); - - pfile_in_zip_read_info->rest_read_uncompressed -= - uOutThis; - - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - if (err==Z_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=Z_OK) - break; - } - } - - if (err==Z_OK) - return iRead; - return err; -} - - -/* - Give the current position in uncompressed data -*/ -z_off_t ZEXPORT unztell (unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - return (z_off_t)pfile_in_zip_read_info->stream.total_out; -} - -ZPOS64_T ZEXPORT unztell64 (unzFile file) -{ - - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return (ZPOS64_T)-1; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return (ZPOS64_T)-1; - - return pfile_in_zip_read_info->total_out_64; -} - - -/* - return 1 if the end of file was reached, 0 elsewhere -*/ -int ZEXPORT unzeof (unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - if (pfile_in_zip_read_info->rest_read_uncompressed == 0) - return 1; - else - return 0; -} - - - -/* -Read extra field from the current file (opened by unzOpenCurrentFile) -This is the local-header version of the extra field (sometimes, there is -more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field that can be read - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ -int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - uInt read_now; - ZPOS64_T size_to_read; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - size_to_read = (pfile_in_zip_read_info->size_local_extrafield - - pfile_in_zip_read_info->pos_local_extrafield); - - if (buf==NULL) - return (int)size_to_read; - - if (len>size_to_read) - read_now = (uInt)size_to_read; - else - read_now = (uInt)len ; - - if (read_now==0) - return 0; - - if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->offset_local_extrafield + - pfile_in_zip_read_info->pos_local_extrafield, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (ZREAD64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - buf,read_now)!=read_now) - return UNZ_ERRNO; - - return (int)read_now; -} - -/* - Close the file in zip opened with unzipOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ -int ZEXPORT unzCloseCurrentFile (unzFile file) -{ - int err=UNZ_OK; - - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && - (!pfile_in_zip_read_info->raw)) - { - if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) - err=UNZ_CRCERROR; - } - - - TRYFREE(pfile_in_zip_read_info->read_buffer); - pfile_in_zip_read_info->read_buffer = NULL; - if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) - inflateEnd(&pfile_in_zip_read_info->stream); -#ifdef HAVE_BZIP2 - else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) - BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); -#endif - - - pfile_in_zip_read_info->stream_initialised = 0; - TRYFREE(pfile_in_zip_read_info); - - s->pfile_in_zip_read=NULL; - - return err; -} - - -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ -int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf) -{ - unz64_s* s; - uLong uReadThis ; - if (file==NULL) - return (int)UNZ_PARAMERROR; - s=(unz64_s*)file; - - uReadThis = uSizeBuf; - if (uReadThis>s->gi.size_comment) - uReadThis = s->gi.size_comment; - - if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (uReadThis>0) - { - *szComment='\0'; - if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) - return UNZ_ERRNO; - } - - if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) - *(szComment+s->gi.size_comment)='\0'; - return (int)uReadThis; -} - -/* Additions by RX '2004 */ -ZPOS64_T ZEXPORT unzGetOffset64(unzFile file) -{ - unz64_s* s; - - if (file==NULL) - return 0; //UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return 0; - if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) - if (s->num_file==s->gi.number_entry) - return 0; - return s->pos_in_central_dir; -} - -uLong ZEXPORT unzGetOffset (unzFile file) -{ - ZPOS64_T offset64; - - if (file==NULL) - return 0; //UNZ_PARAMERROR; - offset64 = unzGetOffset64(file); - return (uLong)offset64; -} - -int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos) -{ - unz64_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - - s->pos_in_central_dir = pos; - s->num_file = s->gi.number_entry; /* hack */ - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - -int ZEXPORT unzSetOffset (unzFile file, uLong pos) -{ - return unzSetOffset64(file,pos); -} - -} // end of namespace cocos2d diff --git a/cocos/2d/support/zip_support/unzip.h b/cocos/2d/support/zip_support/unzip.h deleted file mode 100644 index 54e73a55ea..0000000000 --- a/cocos/2d/support/zip_support/unzip.h +++ /dev/null @@ -1,455 +0,0 @@ -/* unzip.h -- IO for uncompress .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications of Unzip for Zip64 - Copyright (C) 2007-2008 Even Rouault - - Modifications for Zip64 support on both zip and unzip - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - --------------------------------------------------------------------------------- - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - --------------------------------------------------------------------------------- - - Changes - - See header of unzip64.c - -*/ - -#ifndef _unz64_H -#define _unz64_H - -#include "CCPlatformDefine.h" - -#ifndef _ZLIB_H -#include "zlib.h" -#endif - -#ifndef _ZLIBIOAPI_H -#include "ioapi.h" -#endif - -#ifdef HAVE_BZIP2 -#include "bzlib.h" -#endif - -#define Z_BZIP2ED 12 - -#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ -typedef struct TagunzFile__ { int unused; } unzFile__; -typedef unzFile__ *unzFile; -#else -typedef voidp unzFile; -#endif - - -#define UNZ_OK (0) -#define UNZ_END_OF_LIST_OF_FILE (-100) -#define UNZ_ERRNO (Z_ERRNO) -#define UNZ_EOF (0) -#define UNZ_PARAMERROR (-102) -#define UNZ_BADZIPFILE (-103) -#define UNZ_INTERNALERROR (-104) -#define UNZ_CRCERROR (-105) - -namespace cocos2d { - -/* tm_unz contain date/time info */ -typedef struct tm_unz_s -{ - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ -} tm_unz; - -/* unz_global_info structure contain global data about the ZIPfile - These data comes from the end of central dir */ -typedef struct unz_global_info64_s -{ - ZPOS64_T number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ -} unz_global_info64; - -typedef struct unz_global_info_s -{ - uLong number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ -} unz_global_info; - -/* unz_file_info contain information about a file in the zipfile */ -typedef struct unz_file_info64_s -{ - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - ZPOS64_T compressed_size; /* compressed size 8 bytes */ - ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ - - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ - - tm_unz tmu_date; -} unz_file_info64; - -typedef struct unz_file_info_s -{ - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - uLong compressed_size; /* compressed size 4 bytes */ - uLong uncompressed_size; /* uncompressed size 4 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ - - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ - - tm_unz tmu_date; -} unz_file_info; - -int CC_DLL unzStringFileNameCompare OF ((const char* fileName1, - const char* fileName2, - int iCaseSensitivity)); -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparison is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparison is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is default of your operating system - (like 1 on Unix, 2 on Windows) -*/ - - -unzFile CC_DLL unzOpen OF((const char *path)); -unzFile CC_DLL unzOpen64 OF((const void *path)); -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer - "zlib/zlib113.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. - the "64" function take a const void* pointer, because the path is just the - value passed to the open64_file_func callback. - Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path - is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* - does not describe the reality -*/ - - -unzFile CC_DLL unzOpen2 OF((const char *path, - zlib_filefunc_def* pzlib_filefunc_def)); -/* - Open a Zip file, like unzOpen, but provide a set of file low level API - for read/write the zip file (see ioapi.h) -*/ - -unzFile CC_DLL unzOpen2_64 OF((const void *path, - zlib_filefunc64_def* pzlib_filefunc_def)); -/* - Open a Zip file, like unz64Open, but provide a set of file low level API - for read/write the zip file (see ioapi.h) -*/ - -int CC_DLL unzClose OF((unzFile file)); -/* - Close a ZipFile opened with unzipOpen. - If there is files inside the .Zip opened with unzOpenCurrentFile (see later), - these files MUST be closed with unzipCloseCurrentFile before call unzipClose. - return UNZ_OK if there is no problem. */ - -int CC_DLL unzGetGlobalInfo OF((unzFile file, - unz_global_info *pglobal_info)); - -int CC_DLL unzGetGlobalInfo64 OF((unzFile file, - unz_global_info64 *pglobal_info)); -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ - - -int CC_DLL unzGetGlobalComment OF((unzFile file, - char *szComment, - uLong uSizeBuf)); -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ - - -/***************************************************************************/ -/* Unzip package allow you browse the directory of the zipfile */ - -int CC_DLL unzGoToFirstFile OF((unzFile file)); - -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ - -int CC_DLL unzGoToFirstFile64 OF((unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize)); -/* - Set the current file of the zipfile to the first file - with retrieving an information about the file. - return UNZ_OK if there is no problem -*/ - -int CC_DLL unzGoToNextFile OF((unzFile file)); -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ - -int CC_DLL unzGoToNextFile64 OF((unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize)); -/* - Set the current file of the zipfile to the next file - with retrieving an information about the file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ - -int CC_DLL unzLocateFile OF((unzFile file, - const char *szFileName, - int iCaseSensitivity)); -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ - - -/* ****************************************** */ -/* Ryan supplied functions */ -/* unz_file_info contain information about a file in the zipfile */ -typedef struct unz_file_pos_s -{ - uLong pos_in_zip_directory; /* offset in zip file directory */ - uLong num_of_file; /* # of file */ -} unz_file_pos; - -int CC_DLL unzGetFilePos( - unzFile file, - unz_file_pos* file_pos); - -int CC_DLL unzGoToFilePos( - unzFile file, - unz_file_pos* file_pos); - -typedef struct unz64_file_pos_s -{ - ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ - ZPOS64_T num_of_file; /* # of file */ -} unz64_file_pos; - -int CC_DLL unzGetFilePos64( - unzFile file, - unz64_file_pos* file_pos); - -int CC_DLL unzGoToFilePos64( - unzFile file, - const unz64_file_pos* file_pos); - -/* ****************************************** */ - -int CC_DLL unzGetCurrentFileInfo64 OF((unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); - -int CC_DLL unzGetCurrentFileInfo OF((unzFile file, - unz_file_info *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); -/* - Get Info about the current file - if pfile_info!=NULL, the *pfile_info structure will contain some info about - the current file - if szFileName!=NULL, the filename string will be copied in szFileName - (fileNameBufferSize is the size of the buffer) - if extraField!=NULL, the extra field information will be copied in extraField - (extraFieldBufferSize is the size of the buffer). - This is the Central-header version of the extra field - if szComment!=NULL, the comment string of the file will be copied in szComment - (commentBufferSize is the size of the buffer) -*/ - - -/** Addition for GDAL : START */ - -ZPOS64_T CC_DLL unzGetCurrentFileZStreamPos64 OF((unzFile file)); - -/** Addition for GDAL : END */ - - -/***************************************************************************/ -/* for reading the content of the current zipfile, you can open it, read data - from it, and close it (you can close it before reading all the file) - */ - -int CC_DLL unzOpenCurrentFile OF((unzFile file)); -/* - Open for reading data the current file in the zipfile. - If there is no error, the return value is UNZ_OK. -*/ - -int CC_DLL unzOpenCurrentFilePassword OF((unzFile file, - const char* password)); -/* - Open for reading data the current file in the zipfile. - password is a crypting password - If there is no error, the return value is UNZ_OK. -*/ - -int CC_DLL unzOpenCurrentFile2 OF((unzFile file, - int* method, - int* level, - int raw)); -/* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ - -int CC_DLL unzOpenCurrentFile3 OF((unzFile file, - int* method, - int* level, - int raw, - const char* password)); -/* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ - - -int CC_DLL unzCloseCurrentFile OF((unzFile file)); -/* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ - -int CC_DLL unzReadCurrentFile OF((unzFile file, - voidp buf, - unsigned len)); -/* - Read bytes from the current file (opened by unzOpenCurrentFile) - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if some bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ - -z_off_t CC_DLL unztell OF((unzFile file)); - -ZPOS64_T CC_DLL unztell64 OF((unzFile file)); -/* - Give the current position in uncompressed data -*/ - -int CC_DLL unzeof OF((unzFile file)); -/* - return 1 if the end of file was reached, 0 elsewhere -*/ - -int CC_DLL unzGetLocalExtrafield OF((unzFile file, - voidp buf, - unsigned len)); -/* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ - -/***************************************************************************/ - -/* Get the current file offset */ -ZPOS64_T CC_DLL unzGetOffset64 (unzFile file); -uLong CC_DLL unzGetOffset (unzFile file); - -/* Set the current file offset */ -int CC_DLL unzSetOffset64 (unzFile file, ZPOS64_T pos); -int CC_DLL unzSetOffset (unzFile file, uLong pos); - -} // end of namespace cocos2d - -#endif /* _unz64_H */ diff --git a/cocos/2d/support/data_support/uthash.h b/cocos/2d/uthash.h similarity index 100% rename from cocos/2d/support/data_support/uthash.h rename to cocos/2d/uthash.h diff --git a/cocos/2d/support/data_support/utlist.h b/cocos/2d/utlist.h similarity index 100% rename from cocos/2d/support/data_support/utlist.h rename to cocos/2d/utlist.h diff --git a/cocos/platform/CCPlatformConfig.h b/cocos/platform/CCPlatformConfig.h deleted file mode 100644 index 5ba0757dac..0000000000 --- a/cocos/platform/CCPlatformConfig.h +++ /dev/null @@ -1,140 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CC_PLATFORM_CONFIG_H__ -#define __CC_PLATFORM_CONFIG_H__ - -/** -Config of cocos2d-x project, per target platform. -*/ - -////////////////////////////////////////////////////////////////////////// -// pre configure -////////////////////////////////////////////////////////////////////////// - -// define supported target platform macro which CC uses. -#define CC_PLATFORM_UNKNOWN 0 -#define CC_PLATFORM_IOS 1 -#define CC_PLATFORM_ANDROID 2 -#define CC_PLATFORM_WIN32 3 -#define CC_PLATFORM_MARMALADE 4 -#define CC_PLATFORM_LINUX 5 -#define CC_PLATFORM_BADA 6 -#define CC_PLATFORM_BLACKBERRY 7 -#define CC_PLATFORM_MAC 8 -#define CC_PLATFORM_NACL 9 -#define CC_PLATFORM_EMSCRIPTEN 10 -#define CC_PLATFORM_TIZEN 11 -#define CC_PLATFORM_QT5 12 - -// Determine target platform by compile environment macro. -#define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN - -// mac -#if defined(CC_TARGET_OS_MAC) -#undef CC_TARGET_PLATFORM -#define CC_TARGET_PLATFORM CC_PLATFORM_MAC -#endif - -// iphone -#if defined(CC_TARGET_OS_IPHONE) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_IOS -#endif - -// android -#if defined(ANDROID) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID -#endif - -// win32 -#if defined(WIN32) && defined(_WINDOWS) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_WIN32 -#endif - -// linux -#if defined(LINUX) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_LINUX -#endif - -// marmalade -#if defined(MARMALADE) -#undef CC_TARGET_PLATFORM -#define CC_TARGET_PLATFORM CC_PLATFORM_MARMALADE -#endif - -// bada -#if defined(SHP) -#undef CC_TARGET_PLATFORM -#define CC_TARGET_PLATFORM CC_PLATFORM_BADA -#endif - -// qnx -#if defined(__QNX__) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_BLACKBERRY -#endif - -// native client -#if defined(__native_client__) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_NACL -#endif - -// Emscripten -#if defined(EMSCRIPTEN) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_EMSCRIPTEN -#endif - -// tizen -#if defined(TIZEN) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_TIZEN -#endif - -// qt5 -#if defined(CC_TARGET_QT5) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_QT5 -#endif - -////////////////////////////////////////////////////////////////////////// -// post configure -////////////////////////////////////////////////////////////////////////// - -// check user set platform -#if ! CC_TARGET_PLATFORM - #error "Cannot recognize the target platform; are you targeting an unsupported platform?" -#endif - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -#pragma warning (disable:4127) -#endif // CC_PLATFORM_WIN32 - -#endif // __CC_PLATFORM_CONFIG_H__ - diff --git a/cocos/platform/CCPlatformMacros.h b/cocos/platform/CCPlatformMacros.h deleted file mode 100644 index fca1255c0d..0000000000 --- a/cocos/platform/CCPlatformMacros.h +++ /dev/null @@ -1,301 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -#ifndef __CC_PLATFORM_MACROS_H__ -#define __CC_PLATFORM_MACROS_H__ - -/** - * define some platform specific macros - */ -#include "ccConfig.h" -#include "CCPlatformConfig.h" -#include "CCPlatformDefine.h" - -/** - * define a create function for a specific type, such as Layer - * @param \__TYPE__ class type to add create(), such as Layer - */ -#define CREATE_FUNC(__TYPE__) \ -static __TYPE__* create() \ -{ \ - __TYPE__ *pRet = new __TYPE__(); \ - if (pRet && pRet->init()) \ - { \ - pRet->autorelease(); \ - return pRet; \ - } \ - else \ - { \ - delete pRet; \ - pRet = NULL; \ - return NULL; \ - } \ -} - -/** - * define a node function for a specific type, such as Layer - * @param \__TYPE__ class type to add node(), such as Layer - * @deprecated This interface will be deprecated sooner or later. - */ -#define NODE_FUNC(__TYPE__) \ -CC_DEPRECATED_ATTRIBUTE static __TYPE__* node() \ -{ \ - __TYPE__ *pRet = new __TYPE__(); \ - if (pRet && pRet->init()) \ - { \ - pRet->autorelease(); \ - return pRet; \ - } \ - else \ - { \ - delete pRet; \ - pRet = NULL; \ - return NULL; \ - } \ -} - -/** @def CC_ENABLE_CACHE_TEXTURE_DATA -Enable it if you want to cache the texture data. -Not enabling for Emscripten any more -- doesn't seem necessary and don't want -to be different from other platforms unless there's a good reason. - -It's new in cocos2d-x since v0.99.5 -*/ -#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) - #define CC_ENABLE_CACHE_TEXTURE_DATA 1 -#else - #define CC_ENABLE_CACHE_TEXTURE_DATA 0 -#endif - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_EMSCRIPTEN) - /* Application will crash in glDrawElements function on some win32 computers and some android devices. - Indices should be bound again while drawing to avoid this bug. - */ - #define CC_REBIND_INDICES_BUFFER 1 -#else - #define CC_REBIND_INDICES_BUFFER 0 -#endif - -// generic macros - -// namespace cocos2d {} -#ifdef __cplusplus - #define NS_CC_BEGIN namespace cocos2d { - #define NS_CC_END } - #define USING_NS_CC using namespace cocos2d -#else - #define NS_CC_BEGIN - #define NS_CC_END - #define USING_NS_CC -#endif - -/** CC_PROPERTY_READONLY is used to declare a protected variable. - We can use getter to read the variable. - @param varType the type of variable. - @param varName variable name. - @param funName "get + funName" will be the name of the getter. - @warning The getter is a public virtual function, you should rewrite it first. - The variables and methods declared after CC_PROPERTY_READONLY are all public. - If you need protected or private, please declare. - */ -#define CC_PROPERTY_READONLY(varType, varName, funName)\ -protected: varType varName;\ -public: virtual varType get##funName(void) const; - -#define CC_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName)\ -protected: varType varName;\ -public: virtual const varType& get##funName(void) const; - -/** CC_PROPERTY is used to declare a protected variable. - We can use getter to read the variable, and use the setter to change the variable. - @param varType the type of variable. - @param varName variable name. - @param funName "get + funName" will be the name of the getter. - "set + funName" will be the name of the setter. - @warning The getter and setter are public virtual functions, you should rewrite them first. - The variables and methods declared after CC_PROPERTY are all public. - If you need protected or private, please declare. - */ -#define CC_PROPERTY(varType, varName, funName)\ -protected: varType varName;\ -public: virtual varType get##funName(void);\ -public: virtual void set##funName(varType var); - -#define CC_PROPERTY_PASS_BY_REF(varType, varName, funName)\ -protected: varType varName;\ -public: virtual const varType& get##funName(void) const;\ -public: virtual void set##funName(const varType& var); - -/** CC_SYNTHESIZE_READONLY is used to declare a protected variable. - We can use getter to read the variable. - @param varType the type of variable. - @param varName variable name. - @param funName "get + funName" will be the name of the getter. - @warning The getter is a public inline function. - The variables and methods declared after CC_SYNTHESIZE_READONLY are all public. - If you need protected or private, please declare. - */ -#define CC_SYNTHESIZE_READONLY(varType, varName, funName)\ -protected: varType varName;\ -public: virtual varType get##funName(void) const { return varName; } - -#define CC_SYNTHESIZE_READONLY_PASS_BY_REF(varType, varName, funName)\ -protected: varType varName;\ -public: virtual const varType& get##funName(void) const { return varName; } - -/** CC_SYNTHESIZE is used to declare a protected variable. - We can use getter to read the variable, and use the setter to change the variable. - @param varType the type of variable. - @param varName variable name. - @param funName "get + funName" will be the name of the getter. - "set + funName" will be the name of the setter. - @warning The getter and setter are public inline functions. - The variables and methods declared after CC_SYNTHESIZE are all public. - If you need protected or private, please declare. - */ -#define CC_SYNTHESIZE(varType, varName, funName)\ -protected: varType varName;\ -public: virtual varType get##funName(void) const { return varName; }\ -public: virtual void set##funName(varType var){ varName = var; } - -#define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\ -protected: varType varName;\ -public: virtual const varType& get##funName(void) const { return varName; }\ -public: virtual void set##funName(const varType& var){ varName = var; } - -#define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \ -private: varType varName; \ -public: virtual varType get##funName(void) const { return varName; } \ -public: virtual void set##funName(varType var) \ -{ \ - if (varName != var) \ - { \ - CC_SAFE_RETAIN(var); \ - CC_SAFE_RELEASE(varName); \ - varName = var; \ - } \ -} - -#define CC_SAFE_DELETE(p) do { delete (p); (p) = nullptr; } while(0) -#define CC_SAFE_DELETE_ARRAY(p) do { if(p) { delete[] (p); (p) = nullptr; } } while(0) -#define CC_SAFE_FREE(p) do { if(p) { free(p); (p) = nullptr; } } while(0) -#define CC_SAFE_RELEASE(p) do { if(p) { (p)->release(); } } while(0) -#define CC_SAFE_RELEASE_NULL(p) do { if(p) { (p)->release(); (p) = nullptr; } } while(0) -#define CC_SAFE_RETAIN(p) do { if(p) { (p)->retain(); } } while(0) -#define CC_BREAK_IF(cond) if(cond) break - -#define __CCLOGWITHFUNCTION(s, ...) \ - log("%s : %s",__FUNCTION__, String::createWithFormat(s, ##__VA_ARGS__)->getCString()) - -// cocos2d debug -#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 -#define CCLOG(...) do {} while (0) -#define CCLOGINFO(...) do {} while (0) -#define CCLOGERROR(...) do {} while (0) -#define CCLOGWARN(...) do {} while (0) - -#elif COCOS2D_DEBUG == 1 -#define CCLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) -#define CCLOGERROR(format,...) cocos2d::log(format, ##__VA_ARGS__) -#define CCLOGINFO(format,...) do {} while (0) -#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) - -#elif COCOS2D_DEBUG > 1 -#define CCLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) -#define CCLOGERROR(format,...) cocos2d::log(format, ##__VA_ARGS__) -#define CCLOGINFO(format,...) cocos2d::log(format, ##__VA_ARGS__) -#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__) -#endif // COCOS2D_DEBUG - -// Lua engine debug -#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 || CC_LUA_ENGINE_DEBUG == 0 -#define LUALOG(...) -#else -#define LUALOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) -#endif // Lua engine debug - -#if defined(__GNUC__) && ((__GNUC__ >= 5) || ((__GNUG__ == 4) && (__GNUC_MINOR__ >= 4))) \ - || (defined(__clang__) && (__clang_major__ >= 3)) -#define CC_DISABLE_COPY(Class) \ -private: \ - Class(const Class &) = delete; \ - Class &operator =(const Class &) = delete; -#else -#define CC_DISABLE_COPY(Class) \ -private: \ - Class(const Class &); \ - Class &operator =(const Class &); -#endif - -/* - * only certain compilers support __attribute__((deprecated)) - */ -#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) - #define CC_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) -#elif _MSC_VER >= 1400 //vs 2005 or higher - #define CC_DEPRECATED_ATTRIBUTE __declspec(deprecated) -#else - #define CC_DEPRECATED_ATTRIBUTE -#endif - -/* - * only certain compiler support __attribute__((format)) - * formatPos - 1-based position of format string argument - * argPos - 1-based position of first format-dependent argument - */ -#if defined(__GNUC__) && (__GNUC__ >= 4) -#define CC_FORMAT_PRINTF(formatPos, argPos) __attribute__((__format__(printf, formatPos, argPos))) -#elif defined(__has_attribute) - #if __has_attribute(format) - #define CC_FORMAT_PRINTF(formatPos, argPos) __attribute__((__format__(printf, formatPos, argPos))) - #endif // __has_attribute(format) -#else -#define CC_FORMAT_PRINTF(formatPos, argPos) -#endif - -#if defined(_MSC_VER) -#define CC_FORMAT_PRINTF_SIZE_T "%08lX" -#else -#define CC_FORMAT_PRINTF_SIZE_T "%08zX" -#endif - -#ifdef __GNUC__ -#define CC_UNUSED __attribute__ ((unused)) -#else -#define CC_UNUSED -#endif - -// -// CC_REQUIRES_NULL_TERMINATION -// -#if !defined(CC_REQUIRES_NULL_TERMINATION) - #if defined(__APPLE_CC__) && (__APPLE_CC__ >= 5549) - #define CC_REQUIRES_NULL_TERMINATION __attribute__((sentinel(0,1))) - #elif defined(__GNUC__) - #define CC_REQUIRES_NULL_TERMINATION __attribute__((sentinel)) - #else - #define CC_REQUIRES_NULL_TERMINATION - #endif -#endif - -#endif // __CC_PLATFORM_MACROS_H__ diff --git a/cocos/platform/cocoa/CCAffineTransform.cpp b/cocos/platform/cocoa/CCAffineTransform.cpp deleted file mode 100644 index 2e39f344cc..0000000000 --- a/cocos/platform/cocoa/CCAffineTransform.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#include "CCAffineTransform.h" -#include -#include - -using namespace std; - - -NS_CC_BEGIN - -AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty) -{ - AffineTransform t; - t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty; - return t; -} - -Point __CCPointApplyAffineTransform(const Point& point, const AffineTransform& t) -{ - Point p; - p.x = (float)((double)t.a * point.x + (double)t.c * point.y + t.tx); - p.y = (float)((double)t.b * point.x + (double)t.d * point.y + t.ty); - return p; -} - -Size __CCSizeApplyAffineTransform(const Size& size, const AffineTransform& t) -{ - Size s; - s.width = (float)((double)t.a * size.width + (double)t.c * size.height); - s.height = (float)((double)t.b * size.width + (double)t.d * size.height); - return s; -} - - -AffineTransform AffineTransformMakeIdentity() -{ - return __CCAffineTransformMake(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); -} - -extern const AffineTransform AffineTransformIdentity = AffineTransformMakeIdentity(); -const AffineTransform AffineTransform::IDENTITY = AffineTransformMakeIdentity(); - -Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform) -{ - float top = rect.getMinY(); - float left = rect.getMinX(); - float right = rect.getMaxX(); - float bottom = rect.getMaxY(); - - Point topLeft = PointApplyAffineTransform(Point(left, top), anAffineTransform); - Point topRight = PointApplyAffineTransform(Point(right, top), anAffineTransform); - Point bottomLeft = PointApplyAffineTransform(Point(left, bottom), anAffineTransform); - Point bottomRight = PointApplyAffineTransform(Point(right, bottom), anAffineTransform); - - float minX = min(min(topLeft.x, topRight.x), min(bottomLeft.x, bottomRight.x)); - float maxX = max(max(topLeft.x, topRight.x), max(bottomLeft.x, bottomRight.x)); - float minY = min(min(topLeft.y, topRight.y), min(bottomLeft.y, bottomRight.y)); - float maxY = max(max(topLeft.y, topRight.y), max(bottomLeft.y, bottomRight.y)); - - return Rect(minX, minY, (maxX - minX), (maxY - minY)); -} - -AffineTransform AffineTransformTranslate(const AffineTransform& t, float tx, float ty) -{ - return __CCAffineTransformMake(t.a, t.b, t.c, t.d, t.tx + t.a * tx + t.c * ty, t.ty + t.b * tx + t.d * ty); -} - -AffineTransform AffineTransformScale(const AffineTransform& t, float sx, float sy) -{ - return __CCAffineTransformMake(t.a * sx, t.b * sx, t.c * sy, t.d * sy, t.tx, t.ty); -} - -AffineTransform AffineTransformRotate(const AffineTransform& t, float anAngle) -{ - float sine = sinf(anAngle); - float cosine = cosf(anAngle); - - return __CCAffineTransformMake( t.a * cosine + t.c * sine, - t.b * cosine + t.d * sine, - t.c * cosine - t.a * sine, - t.d * cosine - t.b * sine, - t.tx, - t.ty); -} - -/* Concatenate `t2' to `t1' and return the result: - t' = t1 * t2 */ -AffineTransform AffineTransformConcat(const AffineTransform& t1, const AffineTransform& t2) -{ - return __CCAffineTransformMake( t1.a * t2.a + t1.b * t2.c, t1.a * t2.b + t1.b * t2.d, //a,b - t1.c * t2.a + t1.d * t2.c, t1.c * t2.b + t1.d * t2.d, //c,d - t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx - t1.tx * t2.b + t1.ty * t2.d + t2.ty); //ty -} - -/* Return true if `t1' and `t2' are equal, false otherwise. */ -bool AffineTransformEqualToTransform(const AffineTransform& t1, const AffineTransform& t2) -{ - return (t1.a == t2.a && t1.b == t2.b && t1.c == t2.c && t1.d == t2.d && t1.tx == t2.tx && t1.ty == t2.ty); -} - -AffineTransform AffineTransformInvert(const AffineTransform& t) -{ - float determinant = 1 / (t.a * t.d - t.b * t.c); - - return __CCAffineTransformMake(determinant * t.d, -determinant * t.b, -determinant * t.c, determinant * t.a, - determinant * (t.c * t.ty - t.d * t.tx), determinant * (t.b * t.tx - t.a * t.ty) ); -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCAffineTransform.h b/cocos/platform/cocoa/CCAffineTransform.h deleted file mode 100644 index 667b5d9b46..0000000000 --- a/cocos/platform/cocoa/CCAffineTransform.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __COCOA_CGAFFINETRANSFORM_H__ -#define __COCOA_CGAFFINETRANSFORM_H__ - -#include "CCGeometry.h" -#include "platform/CCPlatformMacros.h" - -NS_CC_BEGIN - -struct AffineTransform { - float a, b, c, d; - float tx, ty; - - static const AffineTransform IDENTITY; -}; - -CC_DLL AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty); -#define AffineTransformMake __CCAffineTransformMake - -CC_DLL Point __CCPointApplyAffineTransform(const Point& point, const AffineTransform& t); -#define PointApplyAffineTransform __CCPointApplyAffineTransform - -CC_DLL Size __CCSizeApplyAffineTransform(const Size& size, const AffineTransform& t); -#define SizeApplyAffineTransform __CCSizeApplyAffineTransform - -CC_DLL AffineTransform AffineTransformMakeIdentity(); -CC_DLL Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform); - -CC_DLL AffineTransform AffineTransformTranslate(const AffineTransform& t, float tx, float ty); -CC_DLL AffineTransform AffineTransformRotate(const AffineTransform& aTransform, float anAngle); -CC_DLL AffineTransform AffineTransformScale(const AffineTransform& t, float sx, float sy); -CC_DLL AffineTransform AffineTransformConcat(const AffineTransform& t1, const AffineTransform& t2); -CC_DLL bool AffineTransformEqualToTransform(const AffineTransform& t1, const AffineTransform& t2); -CC_DLL AffineTransform AffineTransformInvert(const AffineTransform& t); - -extern CC_DLL const AffineTransform AffineTransformIdentity; - -NS_CC_END - -#endif // __COCOA_CGAFFINETRANSFORM_H__ diff --git a/cocos/platform/cocoa/CCArray.cpp b/cocos/platform/cocoa/CCArray.cpp deleted file mode 100644 index 3a55d6050d..0000000000 --- a/cocos/platform/cocoa/CCArray.cpp +++ /dev/null @@ -1,754 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCArray.h" -#include "CCString.h" -#include "platform/CCFileUtils.h" - -NS_CC_BEGIN - - -#if CC_USE_ARRAY_VECTOR - -// ---------------------------------------------------------------------------------- -// std::vector implementation -// ---------------------------------------------------------------------------------- - -Array::Array() -: data(NULL) -{ - init(); -} - -Array* Array::create() -{ - Array* array = new Array(); - - if (array && array->initWithCapacity(7)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::createWithObject(Object* object) -{ - Array* array = new Array(); - - if (array && array->initWithObject(object)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::create(Object* object, ...) -{ - va_list args; - va_start(args,object); - - Array* array = create(); - if (array && object) - { - array->addObject(object); - Object *i = va_arg(args, Object*); - while (i) - { - array->addObject(i); - i = va_arg(args, Object*); - } - } - else - { - CC_SAFE_DELETE(array); - } - - va_end(args); - - return array; -} - -Array* Array::createWithArray(Array* otherArray) -{ - return otherArray->clone(); -} - -Array* Array::createWithCapacity(int capacity) -{ - CCASSERT(capacity>=0, "Invalid capacity"); - - Array* array = new Array(); - - if (array && array->initWithCapacity(capacity)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::createWithContentsOfFile(const char* fileName) -{ - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); - if (ret != nullptr) - { - ret->autorelease(); - } - return ret; -} - -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) -{ - return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); -} - -bool Array::init() -{ - return initWithCapacity(7); -} - -bool Array::initWithObject(Object* object) -{ - bool ret = initWithCapacity(7); - if (ret) - { - addObject(object); - } - return ret; -} - -/** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) -{ - bool ret = false; - do - { - CC_BREAK_IF(object == nullptr); - - va_list args; - va_start(args, object); - - if (object) - { - this->addObject(object); - Object* i = va_arg(args, Object*); - while (i) - { - this->addObject(i); - i = va_arg(args, Object*); - } - ret = true; - } - va_end(args); - - } while (false); - - return ret; -} - -bool Array::initWithCapacity(int capacity) -{ - CCASSERT(capacity>=0, "Invalid capacity"); - - data.reserve(capacity); - return true; -} - -bool Array::initWithArray(Array* otherArray) -{ - data = otherArray->data; - return true; -} - -int Array::getIndexOfObject(Object* object) const -{ - auto it = data.begin(); - - for (int i = 0; it != data.end(); ++it, ++i) - { - if (it->get() == object) - { - return i; - } - } - - return -1; -} - -Object* Array::getRandomObject() -{ - if (data.size()==0) - { - return nullptr; - } - - float r = CCRANDOM_0_1(); - - if (r == 1) // to prevent from accessing data-arr[data->num], out of range. - { - r = 0; - } - - r *= data.size(); - - return data[r].get(); -} - -bool Array::containsObject(Object* object) const -{ - int i = this->getIndexOfObject(object); - return (i >=0); -} - -bool Array::isEqualToArray(Array* otherArray) -{ - for (int i = 0; i< this->count(); i++) - { - if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) - { - return false; - } - } - return true; -} - -void Array::addObject(Object* object) -{ - data.push_back( RCPtr(object) ); -} - -void Array::addObjectsFromArray(Array* otherArray) -{ - data.insert(data.end(), otherArray->data.begin(), otherArray->data.end()); -} - -void Array::insertObject(Object* object, int index) -{ - data.insert( std::begin(data) + index, RCPtr(object) ); -} - -void Array::setObject(Object* object, int index) -{ - data[index] = RCPtr(object); -} - -void Array::removeLastObject(bool releaseObj) -{ - CCASSERT(data.size(), "no objects added"); - data.pop_back(); -} - -void Array::removeObject(Object* object, bool releaseObj /* ignored */) -{ - data.erase( std::remove( data.begin(), data.end(), object ) ); -} - -void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) -{ - auto obj = data[index]; - data.erase( data.begin() + index ); -} - -void Array::removeObjectsInArray(Array* otherArray) -{ - CCASSERT(false, "not implemented"); -} - -void Array::removeAllObjects() -{ - data.erase(std::begin(data), std::end(data)); -} - -void Array::fastRemoveObjectAtIndex(int index) -{ - removeObjectAtIndex(index); -} - -void Array::fastRemoveObject(Object* object) -{ - removeObject(object); -} - -void Array::exchangeObject(Object* object1, Object* object2) -{ - int idx1 = getIndexOfObject(object1); - int idx2 = getIndexOfObject(object2); - - CCASSERT(idx1>=0 && idx2>=2, "invalid object index"); - - std::swap( data[idx1], data[idx2] ); -} - -void Array::exchangeObjectAtIndex(int index1, int index2) -{ - std::swap( data[index1], data[index2] ); -} - -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) -{ - data[index] = object; -} - -void Array::reverseObjects() -{ - std::reverse( std::begin(data), std::end(data) ); -} - -void Array::reduceMemoryFootprint() -{ - // N/A -} - -Array::~Array() -{ - CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); -} - -Array* Array::clone() const -{ - Array* ret = new Array(); - ret->autorelease(); - ret->initWithCapacity(this->data.size() > 0 ? this->data.size() : 1); - - Object* obj = nullptr; - Object* tmpObj = nullptr; - Clonable* clonable = nullptr; - CCARRAY_FOREACH(this, obj) - { - clonable = dynamic_cast(obj); - if (clonable) - { - tmpObj = dynamic_cast(clonable->clone()); - if (tmpObj) - { - ret->addObject(tmpObj); - } - } - else - { - CCLOGWARN("%s isn't clonable.", typeid(*obj).name()); - } - } - return ret; -} - -void Array::acceptVisitor(DataVisitor &visitor) -{ - visitor.visit(this); -} - -// ---------------------------------------------------------------------------------- -// ccArray implementation -// ---------------------------------------------------------------------------------- - -#else - -Array::Array() -: data(nullptr) -{ -// init(); -} - -Array* Array::create() -{ - Array* array = new Array(); - - if (array && array->initWithCapacity(7)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::createWithObject(Object* object) -{ - Array* array = new Array(); - - if (array && array->initWithObject(object)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::create(Object* object, ...) -{ - va_list args; - va_start(args,object); - - Array* array = create(); - if (array && object) - { - array->addObject(object); - Object *i = va_arg(args, Object*); - while (i) - { - array->addObject(i); - i = va_arg(args, Object*); - } - } - else - { - CC_SAFE_DELETE(array); - } - - va_end(args); - - return array; -} - -Array* Array::createWithArray(Array* otherArray) -{ - return otherArray->clone(); -} - -Array* Array::createWithCapacity(int capacity) -{ - CCASSERT(capacity>=0, "Invalid capacity"); - - Array* array = new Array(); - - if (array && array->initWithCapacity(capacity)) - { - array->autorelease(); - } - else - { - CC_SAFE_DELETE(array); - } - - return array; -} - -Array* Array::createWithContentsOfFile(const char* fileName) -{ - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); - if (ret != nullptr) - { - ret->autorelease(); - } - return ret; -} - -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) -{ - return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); -} - -bool Array::init() -{ - CCASSERT(!data, "Array cannot be re-initialized"); - - return initWithCapacity(7); -} - -bool Array::initWithObject(Object* object) -{ - CCASSERT(!data, "Array cannot be re-initialized"); - - bool ret = initWithCapacity(7); - if (ret) - { - addObject(object); - } - return ret; -} - -/** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) -{ - CCASSERT(!data, "Array cannot be re-initialized"); - - bool ret = false; - do - { - CC_BREAK_IF(object == nullptr); - - va_list args; - va_start(args, object); - - if (object) - { - this->addObject(object); - Object* i = va_arg(args, Object*); - while (i) - { - this->addObject(i); - i = va_arg(args, Object*); - } - ret = true; - } - va_end(args); - - } while (false); - - return ret; -} - -bool Array::initWithCapacity(int capacity) -{ - CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); - - data = ccArrayNew(capacity); - return true; -} - -bool Array::initWithArray(Array* otherArray) -{ - CCASSERT(!data, "Array cannot be re-initialized"); - - bool ret = false; - do - { - CC_BREAK_IF(! initWithCapacity(otherArray->data->num)); - - addObjectsFromArray(otherArray); - ret = true; - } while (0); - - return ret; -} - -int Array::getIndexOfObject(Object* object) const -{ - return ccArrayGetIndexOfObject(data, object); -} - -Object* Array::getRandomObject() -{ - if (data->num == 0) - { - return nullptr; - } - - float r = CCRANDOM_0_1(); - - if (r == 1) // to prevent from accessing data-arr[data->num], out of range. - { - r = 0; - } - - return data->arr[(int)(data->num * r)]; -} - -bool Array::containsObject(Object* object) const -{ - return ccArrayContainsObject(data, object); -} - -bool Array::isEqualToArray(Array* otherArray) -{ - for (int i = 0; i< this->count(); i++) - { - if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) - { - return false; - } - } - return true; -} - -void Array::addObject(Object* object) -{ - CCASSERT(data, "Array not initialized"); - ccArrayAppendObjectWithResize(data, object); -} - -void Array::addObjectsFromArray(Array* otherArray) -{ - CCASSERT(data, "Array not initialized"); - ccArrayAppendArrayWithResize(data, otherArray->data); -} - -void Array::insertObject(Object* object, int index) -{ - CCASSERT(data, "Array not initialized"); - ccArrayInsertObjectAtIndex(data, object, index); -} - -void Array::setObject(Object* object, int index) -{ - CCASSERT(index>=0 && index < count(), "Invalid index"); - - if (object != data->arr[index]) - { - data->arr[index]->release(); - data->arr[index] = object; - object->retain(); - } -} - -void Array::removeLastObject(bool releaseObj) -{ - CCASSERT(data->num, "no objects added"); - ccArrayRemoveObjectAtIndex(data, data->num-1, releaseObj); -} - -void Array::removeObject(Object* object, bool releaseObj/* = true*/) -{ - ccArrayRemoveObject(data, object, releaseObj); -} - -void Array::removeObjectAtIndex(int index, bool releaseObj) -{ - ccArrayRemoveObjectAtIndex(data, index, releaseObj); -} - -void Array::removeObjectsInArray(Array* otherArray) -{ - ccArrayRemoveArray(data, otherArray->data); -} - -void Array::removeAllObjects() -{ - ccArrayRemoveAllObjects(data); -} - -void Array::fastRemoveObjectAtIndex(int index) -{ - ccArrayFastRemoveObjectAtIndex(data, index); -} - -void Array::fastRemoveObject(Object* object) -{ - ccArrayFastRemoveObject(data, object); -} - -void Array::exchangeObject(Object* object1, Object* object2) -{ - int index1 = ccArrayGetIndexOfObject(data, object1); - if (index1 == UINT_MAX) - { - return; - } - - int index2 = ccArrayGetIndexOfObject(data, object2); - if (index2 == UINT_MAX) - { - return; - } - - ccArraySwapObjectsAtIndexes(data, index1, index2); -} - -void Array::exchangeObjectAtIndex(int index1, int index2) -{ - ccArraySwapObjectsAtIndexes(data, index1, index2); -} - -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) -{ - ccArrayInsertObjectAtIndex(data, object, index); - ccArrayRemoveObjectAtIndex(data, index+1); -} - -void Array::reverseObjects() -{ - if (data->num > 1) - { - // floorf(), since in the case of an even number, the number of swaps stays the same - int count = (int) floorf(data->num/2.f); - int maxIndex = data->num - 1; - - for (int i = 0; i < count ; i++) - { - ccArraySwapObjectsAtIndexes(data, i, maxIndex); - --maxIndex; - } - } -} - -void Array::reduceMemoryFootprint() -{ - ccArrayShrink(data); -} - -Array::~Array() -{ - CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); - - ccArrayFree(data); -} - -Array* Array::clone() const -{ - Array* ret = new Array(); - ret->autorelease(); - ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1); - - Object* obj = nullptr; - Object* tmpObj = nullptr; - Clonable* clonable = nullptr; - CCARRAY_FOREACH(this, obj) - { - clonable = dynamic_cast(obj); - if (clonable) - { - tmpObj = dynamic_cast(clonable->clone()); - if (tmpObj) - { - ret->addObject(tmpObj); - } - } - else - { - CCLOGWARN("%s isn't clonable.", typeid(*obj).name()); - } - } - return ret; -} - -void Array::acceptVisitor(DataVisitor &visitor) -{ - visitor.visit(this); -} - -#endif // uses ccArray - -NS_CC_END diff --git a/cocos/platform/cocoa/CCArray.h b/cocos/platform/cocoa/CCArray.h deleted file mode 100644 index 4f5beea501..0000000000 --- a/cocos/platform/cocoa/CCArray.h +++ /dev/null @@ -1,557 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.com -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#ifndef __CCARRAY_H__ -#define __CCARRAY_H__ - -#define CC_USE_ARRAY_VECTOR 0 - -#if CC_USE_ARRAY_VECTOR -#include -#include -#include "cocoa/CCObject.h" -#include "ccMacros.h" -#else -#include "support/data_support/ccCArray.h" -#endif - - -#if CC_USE_ARRAY_VECTOR -/** - * A reference counting-managed pointer for classes derived from RCBase which can - * be used as C pointer - * Original code: http://www.codeproject.com/Articles/64111/Building-a-Quick-and-Handy-Reference-Counting-Clas - * License: http://www.codeproject.com/info/cpol10.aspx - */ -template < class T > -class RCPtr -{ -public: - //Construct using a C pointer - //e.g. RCPtr< T > x = new T(); - RCPtr(T* ptr = nullptr) - : _ptr(ptr) - { - if(ptr != nullptr) {ptr->retain();} - } - - //Copy constructor - RCPtr(const RCPtr &ptr) - : _ptr(ptr._ptr) - { -// printf("Array: copy constructor: %p\n", this); - if(_ptr != NULL) {_ptr->retain();} - } - - //Move constructor - RCPtr(RCPtr &&ptr) - : _ptr(ptr._ptr) - { -// printf("Array: Move Constructor: %p\n", this); - ptr._ptr = nullptr; - } - - ~RCPtr() - { -// printf("Array: Destructor: %p\n", this); - if(_ptr != nullptr) {_ptr->release();} - } - - //Assign a pointer - //e.g. x = new T(); - RCPtr &operator=(T* ptr) - { -// printf("Array: operator= T*: %p\n", this); - - //The following grab and release operations have to be performed - //in that order to handle the case where ptr == _ptr - //(See comment below by David Garlisch) - if(ptr != nullptr) {ptr->retain();} - if(_ptr != nullptr) {_ptr->release();} - _ptr = ptr; - return (*this); - } - - //Assign another RCPtr - RCPtr &operator=(const RCPtr &ptr) - { -// printf("Array: operator= const&: %p\n", this); - return (*this) = ptr._ptr; - } - - //Retrieve actual pointer - T* get() const - { - return _ptr; - } - - //Some overloaded operators to facilitate dealing with an RCPtr - //as a conventional C pointer. - //Without these operators, one can still use the less transparent - //get() method to access the pointer. - T* operator->() const {return _ptr;} //x->member - T &operator*() const {return *_ptr;} //*x, (*x).member - explicit operator T*() const {return _ptr;} //T* y = x; - explicit operator bool() const {return _ptr != nullptr;} //if(x) {/*x is not NULL*/} - bool operator==(const RCPtr &ptr) {return _ptr == ptr._ptr;} - bool operator==(const T *ptr) {return _ptr == ptr;} - -private: - T *_ptr; //Actual pointer -}; -#endif // CC_USE_ARRAY_VECTOR - - -/** - * @addtogroup data_structures - * @{ - */ - -/** @def CCARRAY_FOREACH -A convenience macro to iterate over a Array using. It is faster than the "fast enumeration" interface. -@since v0.99.4 -*/ - -/* -In cocos2d-iphone 1.0.0, This macro have been update to like this: - -#define CCARRAY_FOREACH(__array__, __object__) \ -if (__array__ && __array__->data->num > 0) \ -for(id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __array__->data->num-1; \ -__arr__ <= end && ((__object__ = *__arr__) != nil || true); \ -__arr__++) - -I found that it's not work in C++. So it keep what it's look like in version 1.0.0-rc3. ---By Bin -*/ - -#if CC_USE_ARRAY_VECTOR -#define CCARRAY_FOREACH(__array__, __object__) \ - if (__array__) \ - for( auto __it__ = (__array__)->data.begin(); \ - __it__ != (__array__)->data.end() && ((__object__) = __it__->get()) != nullptr; \ - ++__it__) - - -#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \ - if (__array__) \ - for( auto __it__ = (__array__)->data.rbegin(); \ - __it__ != (__array__)->data.rend() && ((__object__) = __it__->get()) != nullptr; \ - ++__it__ ) - - -#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) - -#else // ! CC_USE_ARRAY_VECTOR -------------------------- - -#define CCARRAY_FOREACH(__array__, __object__) \ - if ((__array__) && (__array__)->data->num > 0) \ - for(Object** __arr__ = (__array__)->data->arr, **__end__ = (__array__)->data->arr + (__array__)->data->num-1; \ - __arr__ <= __end__ && (((__object__) = *__arr__) != NULL/* || true*/); \ - __arr__++) - -#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \ - if ((__array__) && (__array__)->data->num > 0) \ - for(Object** __arr__ = (__array__)->data->arr + (__array__)->data->num-1, **__end__ = (__array__)->data->arr; \ - __arr__ >= __end__ && (((__object__) = *__arr__) != NULL/* || true*/); \ - __arr__--) - -#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) -#define CCARRAY_VERIFY_TYPE(__array__, __type__) \ - do { \ - if ((__array__) && (__array__)->data->num > 0) \ - for(Object** __arr__ = (__array__)->data->arr, \ - **__end__ = (__array__)->data->arr + (__array__)->data->num-1; __arr__ <= __end__; __arr__++) \ - CCASSERT(dynamic_cast<__type__>(*__arr__), "element type is wrong!"); \ - } while(false) -#else -#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) -#endif - -#endif // ! CC_USE_ARRAY_VECTOR - - -// Common defines ----------------------------------------------------------------------------------------------- - -#define arrayMakeObjectsPerformSelector(pArray, func, elementType) \ -do { \ - if(pArray && pArray->count() > 0) \ - { \ - Object* child; \ - CCARRAY_FOREACH(pArray, child) \ - { \ - elementType pNode = static_cast(child); \ - if(pNode) \ - { \ - pNode->func(); \ - } \ - } \ - } \ -} \ -while(false) - -#define arrayMakeObjectsPerformSelectorWithObject(pArray, func, object, elementType) \ -do { \ - if(pArray && pArray->count() > 0) \ - { \ - Object* child; \ - CCARRAY_FOREACH(pArray, child) \ - { \ - elementType pNode = static_cast(child); \ - if(pNode) \ - { \ - pNode->func(object); \ - } \ - } \ - } \ -} \ -while(false) - - -NS_CC_BEGIN - -class CC_DLL Array : public Object, public Clonable -{ -public: - - /** Creates an empty array. Default capacity is 10 - * @js NA - * @lua NA - */ - static Array* create(); - /** Create an array with objects - * @js NA - */ - static Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; - /** Create an array with one object - * @js NA - */ - static Array* createWithObject(Object* object); - /** Create an array with a default capacity - * @js NA - */ - static Array* createWithCapacity(int capacity); - /** Create an array with from an existing array - * @js NA - */ - static Array* createWithArray(Array* otherArray); - /** - @brief Generate a Array pointer by file - @param pFileName The file name of *.plist file - @return The Array pointer generated from the file - * @js NA - */ - static Array* createWithContentsOfFile(const char* pFileName); - - /* - @brief The same meaning as arrayWithContentsOfFile(), but it doesn't call autorelease, so the - invoker should call release(). - * @js NA - * @lua NA - */ - static Array* createWithContentsOfFileThreadSafe(const char* pFileName); - /** - * @js NA - * @lua NA - */ - ~Array(); - - /** Initializes an array - * @js NA - * @lua NA - */ - bool init(); - /** Initializes an array with one object - * @js NA - * @lua NA - */ - bool initWithObject(Object* object); - /** Initializes an array with some objects - * @js NA - * @lua NA - */ - bool initWithObjects(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; - /** Initializes an array with capacity - * @js NA - * @lua NA - */ - bool initWithCapacity(int capacity); - /** Initializes an array with an existing array - * @js NA - * @lua NA - */ - bool initWithArray(Array* otherArray); - - // Querying an Array - - /** Returns element count of the array - * @js NA - */ - int count() const - { -#if CC_USE_ARRAY_VECTOR - return data.size(); -#else - return data->num; -#endif - } - /** Returns capacity of the array - * @js NA - */ - int capacity() const - { -#if CC_USE_ARRAY_VECTOR - return data.capacity(); -#else - return data->max; -#endif - } - /** Returns index of a certain object, return UINT_MAX if doesn't contain the object - * @js NA - * @lua NA - */ - int getIndexOfObject(Object* object) const; - /** - * @js NA - */ - CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } - - /** Returns an element with a certain index - * @js NA - * @lua NA - */ - Object* getObjectAtIndex(int index) - { - CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); -#if CC_USE_ARRAY_VECTOR - return data[index].get(); -#else - return data->arr[index]; -#endif - } - CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } - /** Returns the last element of the array - * @js NA - */ - Object* getLastObject() - { -#if CC_USE_ARRAY_VECTOR - return data.back().get(); -#else - if(data->num > 0) - return data->arr[data->num-1]; - - return nullptr; -#endif - } - /** - * @js NA - */ - CC_DEPRECATED_ATTRIBUTE Object* lastObject() { return getLastObject(); } - /** Returns a random element - * @js NA - * @lua NA - */ - Object* getRandomObject(); - /** - * @js NA - */ - CC_DEPRECATED_ATTRIBUTE Object* randomObject() { return getRandomObject(); } - /** Returns a Boolean value that indicates whether object is present in array. - * @js NA - */ - bool containsObject(Object* object) const; - /** @since 1.1 - * @js NA - */ - bool isEqualToArray(Array* otherArray); - // Adding Objects - - /** Add a certain object - * @js NA - */ - void addObject(Object* object); - /** - * @js NA - */ - /** Add all elements of an existing array - * @js NA - */ - void addObjectsFromArray(Array* otherArray); - /** Insert a certain object at a certain index - * @js NA - */ - void insertObject(Object* object, int index); - /** sets a certain object at a certain index - * @js NA - * @lua NA - */ - void setObject(Object* object, int index); - /** sets a certain object at a certain index without retaining. Use it with caution - * @js NA - * @lua NA - */ - void fastSetObject(Object* object, int index) - { -#if CC_USE_ARRAY_VECTOR - setObject(object, index); -#else - // no retain - data->arr[index] = object; -#endif - } - /** - * @js NA - * @lua NA - */ - void swap( int indexOne, int indexTwo ) - { - CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); -#if CC_USE_ARRAY_VECTOR - std::swap(data[indexOne], data[indexTwo]); -#else - std::swap(data->arr[indexOne], data->arr[indexTwo]); -#endif - } - - // Removing Objects - - /** Remove last object - * @js NA - */ - void removeLastObject(bool releaseObj = true); - /** Remove a certain object - * @js NA - */ - void removeObject(Object* object, bool releaseObj = true); - /** Remove an element with a certain index - * @js NA - */ - void removeObjectAtIndex(int index, bool releaseObj = true); - /** Remove all elements - * @js NA - */ - void removeObjectsInArray(Array* otherArray); - /** Remove all objects - * @js NA - */ - void removeAllObjects(); - /** Fast way to remove a certain object - * @js NA - */ - void fastRemoveObject(Object* object); - /** Fast way to remove an element with a certain index - * @js NA - */ - void fastRemoveObjectAtIndex(int index); - - // Rearranging Content - - /** Swap two elements - * @js NA - */ - void exchangeObject(Object* object1, Object* object2); - /** Swap two elements with certain indexes - * @js NA - */ - void exchangeObjectAtIndex(int index1, int index2); - - /** Replace object at index with another object. - * @js NA - */ - void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); - - /** Revers the array - * @js NA - */ - void reverseObjects(); - /* Shrinks the array so the memory footprint corresponds with the number of items - * @js NA - */ - void reduceMemoryFootprint(); - - /* override functions - * @js NA - */ - virtual void acceptVisitor(DataVisitor &visitor); - /** - * @js NA - * @lua NA - */ - virtual Array* clone() const; - - // ------------------------------------------ - // Iterators - // ------------------------------------------ -#if CC_USE_ARRAY_VECTOR - typedef std::vector>::iterator iterator; - typedef std::vector>::const_iterator const_iterator; - /** - * @js NA - * @lua NA - */ - iterator begin() { return data.begin(); } - /** - * @js NA - * @lua NA - */ - iterator end() { return data.end(); } - const_iterator cbegin() { return data.cbegin(); } - /** - * @js NA - * @lua NA - */ - const_iterator cend() { return data.cend(); } - - std::vector> data; - -#else - /** - * @js NA - * @lua NA - */ - Object** begin() { return &data->arr[0]; } - /** - * @js NA - * @lua NA - */ - Object** end() { return &data->arr[data->num]; } - - ccArray* data; - -#endif - -//protected: - /** - * @js NA - * @lua NA - */ - Array(); -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CCARRAY_H__ diff --git a/cocos/platform/cocoa/CCAutoreleasePool.cpp b/cocos/platform/cocoa/CCAutoreleasePool.cpp deleted file mode 100644 index 89a3528f73..0000000000 --- a/cocos/platform/cocoa/CCAutoreleasePool.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#include "CCAutoreleasePool.h" -#include "ccMacros.h" - -NS_CC_BEGIN - -static PoolManager* s_pPoolManager = NULL; - -AutoreleasePool::AutoreleasePool() -{ - _managedObjectArray = new Array(); - _managedObjectArray->initWithCapacity(150); -} - -AutoreleasePool::~AutoreleasePool() -{ - CCLOGINFO("deallocing AutoreleasePool: %p", this); - CC_SAFE_DELETE(_managedObjectArray); -} - -void AutoreleasePool::addObject(Object* object) -{ - _managedObjectArray->addObject(object); - - CCASSERT(object->_reference > 1, "reference count should be greater than 1"); - ++(object->_autoReleaseCount); - object->release(); // no ref count, in this case autorelease pool added. -} - -void AutoreleasePool::removeObject(Object* object) -{ - for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) - { - _managedObjectArray->removeObject(object, false); - } -} - -void AutoreleasePool::clear() -{ - if(_managedObjectArray->count() > 0) - { - //CCAutoreleasePool* pReleasePool; -#ifdef _DEBUG - int nIndex = _managedObjectArray->count() - 1; -#endif - - Object* pObj = NULL; - CCARRAY_FOREACH_REVERSE(_managedObjectArray, pObj) - { - if(!pObj) - break; - - --(pObj->_autoReleaseCount); - //(*it)->release(); - //delete (*it); -#ifdef _DEBUG - nIndex--; -#endif - } - - _managedObjectArray->removeAllObjects(); - } -} - - -//-------------------------------------------------------------------- -// -// PoolManager -// -//-------------------------------------------------------------------- - -PoolManager* PoolManager::sharedPoolManager() -{ - if (s_pPoolManager == NULL) - { - s_pPoolManager = new PoolManager(); - } - return s_pPoolManager; -} - -void PoolManager::purgePoolManager() -{ - CC_SAFE_DELETE(s_pPoolManager); -} - -PoolManager::PoolManager() -{ - _releasePoolStack = new Array(); - _releasePoolStack->initWithCapacity(150); - _curReleasePool = 0; -} - -PoolManager::~PoolManager() -{ - CCLOGINFO("deallocing PoolManager: %p", this); - finalize(); - - // we only release the last autorelease pool here - _curReleasePool = 0; - _releasePoolStack->removeObjectAtIndex(0); - - CC_SAFE_DELETE(_releasePoolStack); -} - -void PoolManager::finalize() -{ - if(_releasePoolStack->count() > 0) - { - //CCAutoreleasePool* pReleasePool; - Object* pObj = NULL; - CCARRAY_FOREACH(_releasePoolStack, pObj) - { - if(!pObj) - break; - AutoreleasePool* pPool = static_cast(pObj); - pPool->clear(); - } - } -} - -void PoolManager::push() -{ - AutoreleasePool* pPool = new AutoreleasePool(); //ref = 1 - _curReleasePool = pPool; - - _releasePoolStack->addObject(pPool); //ref = 2 - - pPool->release(); //ref = 1 -} - -void PoolManager::pop() -{ - if (! _curReleasePool) - { - return; - } - - int nCount = _releasePoolStack->count(); - - _curReleasePool->clear(); - - if (nCount > 1) - { - _releasePoolStack->removeObjectAtIndex(nCount-1); - -// if(nCount > 1) -// { -// _curReleasePool = _releasePoolStack->getObjectAtIndex(nCount - 2); -// return; -// } - _curReleasePool = (AutoreleasePool*)_releasePoolStack->getObjectAtIndex(nCount - 2); - } - - /*_curReleasePool = NULL;*/ -} - -void PoolManager::removeObject(Object* object) -{ - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - _curReleasePool->removeObject(object); -} - -void PoolManager::addObject(Object* object) -{ - getCurReleasePool()->addObject(object); -} - - -AutoreleasePool* PoolManager::getCurReleasePool() -{ - if(!_curReleasePool) - { - push(); - } - - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - return _curReleasePool; -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCAutoreleasePool.h b/cocos/platform/cocoa/CCAutoreleasePool.h deleted file mode 100644 index e446ceb402..0000000000 --- a/cocos/platform/cocoa/CCAutoreleasePool.h +++ /dev/null @@ -1,181 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#ifndef __AUTORELEASEPOOL_H__ -#define __AUTORELEASEPOOL_H__ - -#include "CCObject.h" -#include "CCArray.h" - -NS_CC_BEGIN - -/** - * @addtogroup base_nodes - * @{ - */ - -class CC_DLL AutoreleasePool : public Object -{ - /** - * The underlying array of object managed by the pool. - * - * Although Array retains the object once when an object is added, proper - * Object::release() is called outside the array to make sure that the pool - * does not affect the managed object's reference count. So an object can - * be destructed properly by calling Object::release() even if the object - * is in the pool. - */ - Array *_managedObjectArray; -public: - /** - * @js NA - * @lua NA - */ - AutoreleasePool(); - /** - * @js NA - * @lua NA - */ - ~AutoreleasePool(); - - /** - * Add a given object to this pool. - * - * The same object may be added several times to the same pool; When the - * pool is destructed, the object's Object::release() method will be called - * for each time it was added. - * - * @param object The object to add to the pool. - * @js NA - * @lua NA - */ - void addObject(Object *object); - - /** - * Remove a given object from this pool. - * - * @param object The object to be removed from the pool. - * @js NA - * @lua NA - */ - void removeObject(Object *object); - - /** - * Clear the autorelease pool. - * - * Object::release() will be called for each time the managed object is - * added to the pool. - * @js NA - * @lua NA - */ - void clear(); -}; - -class CC_DLL PoolManager -{ - Array *_releasePoolStack; - AutoreleasePool *_curReleasePool; - - AutoreleasePool *getCurReleasePool(); -public: - /** - * @js NA - * @lua NA - */ - static PoolManager* sharedPoolManager(); - /** - * @js NA - * @lua NA - */ - static void purgePoolManager(); - /** - * @js NA - * @lua NA - */ - PoolManager(); - /** - * @js NA - * @lua NA - */ - ~PoolManager(); - - /** - * Clear all the AutoreleasePool on the pool stack. - * @js NA - * @lua NA - */ - void finalize(); - - /** - * Push a new AutoreleasePool to the pool stack. - * @js NA - * @lua NA - */ - void push(); - - /** - * Pop one AutoreleasePool from the pool stack. - * - * This method will ensure that there is at least one AutoreleasePool on - * the stack. - * - * The AutoreleasePool being poped is destructed. - * @js NA - * @lua NA - */ - void pop(); - - /** - * Remove a given object from the current autorelease pool. - * - * @param object The object to be removed. - * - * @see AutoreleasePool::removeObject - * @js NA - * @lua NA - */ - void removeObject(Object *object); - - /** - * Add a given object to the current autorelease pool. - * - * @param object The object to add. - * - * @see AutoreleasePool::addObject - * @js NA - * @lua NA - */ - void addObject(Object *object); - /** - * @js NA - * @lua NA - */ - friend class AutoreleasePool; -}; - -// end of base_nodes group -/// @} - -NS_CC_END - -#endif //__AUTORELEASEPOOL_H__ diff --git a/cocos/platform/cocoa/CCBool.h b/cocos/platform/cocoa/CCBool.h deleted file mode 100644 index 32b7b276ee..0000000000 --- a/cocos/platform/cocoa/CCBool.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 __CCBOOL_H__ -#define __CCBOOL_H__ - -#include "CCObject.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -class CC_DLL Bool : public Object, public Clonable -{ -public: - Bool(bool v) - : _value(v) {} - bool getValue() const {return _value;} - - static Bool* create(bool v) - { - Bool* pRet = new Bool(v); - if (pRet) - { - pRet->autorelease(); - } - return pRet; - } - - /* override functions */ - virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } - - Bool* clone() const - { - return Bool::create(_value); - } -private: - bool _value; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif /* __CCBOOL_H__ */ diff --git a/cocos/platform/cocoa/CCData.cpp b/cocos/platform/cocoa/CCData.cpp deleted file mode 100644 index 1c42a12ee5..0000000000 --- a/cocos/platform/cocoa/CCData.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 -#include "CCData.h" -#include "platform/CCCommon.h" - -NS_CC_BEGIN - -Data::Data(unsigned char *pBytes, const unsigned long nSize) -{ - _size = nSize; - _bytes = new unsigned char[_size]; - memcpy(_bytes, pBytes, _size); -} - -Data::Data(Data *pData) -{ - _size = pData->_size; - _bytes = new unsigned char[_size]; - memcpy(_bytes, pData->_bytes, _size); -} - -Data::~Data() -{ - CCLOGINFO("deallocing Data: %p", this); - CC_SAFE_DELETE_ARRAY(_bytes); -} - -unsigned char* Data::getBytes() const -{ - return _bytes; -} - -unsigned long Data::getSize() const -{ - return _size; -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCData.h b/cocos/platform/cocoa/CCData.h deleted file mode 100644 index 889a2d557b..0000000000 --- a/cocos/platform/cocoa/CCData.h +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 __CCDATA_H__ -#define __CCDATA_H__ - -#include "platform/CCPlatformMacros.h" -#include "CCObject.h" - -NS_CC_BEGIN - -class CC_DLL Data : public Object -{ -public: - /** - * @js NA - * @lua NA - */ - Data(unsigned char *pBytes, const unsigned long nSize); - /** - * @js NA - * @lua NA - */ - Data(Data *pData); - /** - * @js NA - * @lua NA - */ - ~Data(); - /** - * @js NA - * @lua NA - */ - static Data* create(unsigned char *pBytes, const unsigned long nSize) - { - Data* pRet = new Data(pBytes, nSize); - if (pRet) - { - pRet->autorelease(); - } - return pRet; - } - /** - * @js NA - * @lua NA - */ - unsigned char* getBytes() const; - /** - * @js NA - * @lua NA - */ - unsigned long getSize() const; - - /** override functions - * @js NA - * @lua NA - */ - virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } - -private: - unsigned char* _bytes; - unsigned long _size; -}; - -NS_CC_END - -#endif // __CCDATA_H__ diff --git a/cocos/platform/cocoa/CCDataVisitor.cpp b/cocos/platform/cocoa/CCDataVisitor.cpp deleted file mode 100644 index 2d2a1f8121..0000000000 --- a/cocos/platform/cocoa/CCDataVisitor.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCObject.h" -#include "CCBool.h" -#include "CCInteger.h" -#include "CCFloat.h" -#include "CCDouble.h" -#include "CCString.h" -#include "CCArray.h" -#include "CCDictionary.h" -#include "CCSet.h" -#include "CCData.h" - -NS_CC_BEGIN - -void DataVisitor::visit(const Bool *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Integer *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Float *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Double *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const String *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Array *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Dictionary *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Set *value) -{ - visitObject(value); -} - -void DataVisitor::visit(const Data *value) -{ - visitObject(value); -} - -// PrettyPrinter -PrettyPrinter::PrettyPrinter(int indentLevel/* = 0 */) -{ - setIndentLevel(indentLevel); -} - -void PrettyPrinter::clear() -{ - _result.clear(); -} - -std::string PrettyPrinter::getResult() -{ - return _result; -} - -void PrettyPrinter::visitObject(const Object *p) -{ - char buf[50] = {0}; - sprintf(buf, "%p", p); - _result += buf; -} - -void PrettyPrinter::visit(const Bool * p) -{ - char buf[50] = {0}; - sprintf(buf, "%s", p->getValue() ? "true" : "false"); - _result += buf; -} - -void PrettyPrinter::visit(const Integer *p) -{ - char buf[50] = {0}; - sprintf(buf, "%d", p->getValue()); - _result += buf; -} - -void PrettyPrinter::visit(const Float *p) -{ - char buf[50] = {0}; - sprintf(buf, "%f", p->getValue()); - _result += buf; -} - -void PrettyPrinter::visit(const Double *p) -{ - char buf[50] = {0}; - sprintf(buf, "%lf", p->getValue()); - _result += buf; -} - -void PrettyPrinter::visit(const String *p) -{ - _result += p->getCString(); -} - -void PrettyPrinter::visit(const Array *p) -{ - _result += "\n"; - _result += _indentStr; - _result += "\n"; - - setIndentLevel(_indentLevel+1); - Object* obj; - int i = 0; - char buf[50] = {0}; - CCARRAY_FOREACH(p, obj) - { - if (i > 0) { - _result += "\n"; - } - sprintf(buf, "%s%02d: ", _indentStr.c_str(), i); - _result += buf; - PrettyPrinter v(_indentLevel); - obj->acceptVisitor(v); - _result += v.getResult(); - i++; - } - setIndentLevel(_indentLevel-1); - - _result += "\n"; - _result += _indentStr; - _result += ""; -} - -void PrettyPrinter::visit(const Dictionary *p) -{ - _result += "\n"; - _result += _indentStr; - _result += "\n"; - - setIndentLevel(_indentLevel+1); - DictElement* element; - bool bFirstElement = true; - char buf[1000] = {0}; - CCDICT_FOREACH(p, element) - { - if (!bFirstElement) { - _result += "\n"; - } - sprintf(buf, "%s%s: ", _indentStr.c_str(),element->getStrKey()); - _result += buf; - PrettyPrinter v(_indentLevel); - element->getObject()->acceptVisitor(v); - _result += v.getResult(); - bFirstElement = false; - } - setIndentLevel(_indentLevel-1); - - _result += "\n"; - _result += _indentStr; - _result += ""; -} - -void PrettyPrinter::visit(const Set *p) -{ - _result += "\n"; - _result += _indentStr; - _result += "\n"; - - setIndentLevel(_indentLevel+1); - - int i = 0; - Set* tmp = const_cast(p); - SetIterator it = tmp->begin(); - - for (; it != tmp->end(); ++it, ++i) { - if (i > 0) { - _result += "\n"; - } - _result += _indentStr.c_str(); - PrettyPrinter v(_indentLevel); - (*it)->acceptVisitor(v); - _result += v.getResult(); - } - setIndentLevel(_indentLevel-1); - - _result += "\n"; - _result += _indentStr; - _result += "\n"; -} - -void PrettyPrinter::visit(const Data *p) -{ - //TODO Implement - DataVisitor::visit(p); -} - -void PrettyPrinter::setIndentLevel(int indentLevel) -{ - _indentLevel = indentLevel; - _indentStr.clear(); - for (int i = 0; i < _indentLevel; ++i) { - _indentStr += "\t"; - } -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCDataVisitor.h b/cocos/platform/cocoa/CCDataVisitor.h deleted file mode 100644 index 3395b43dea..0000000000 --- a/cocos/platform/cocoa/CCDataVisitor.h +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __CCDATAVISITOR_H__ -#define __CCDATAVISITOR_H__ - -#include "platform/CCPlatformMacros.h" -#include - -NS_CC_BEGIN - -class Object; -class Bool; -class Integer; -class Float; -class Double; -class String; -class Array; -class Dictionary; -class Set; -class Data; - -/** - * @addtogroup data_structures - * @{ - */ - -/** - * Visitor that helps to perform action that depends on polymorphic object type - * - * Use cases: - * - data serialization, - * - pretty printing of Object * - * - safe value reading from Array, Dictionary, Set - * - * Usage: - * 1. subclass DataVisitor - * 2. overload visit() methods for object that you need to handle - * 3. handle other objects in visitObject() - * 4. pass your visitor to Object::acceptVisitor() - */ -class CC_DLL DataVisitor -{ -public: - /** - * @js NA - * @lua NA - */ - virtual ~DataVisitor() {} - - /** default method, called from non-overloaded methods and for unrecognized objects */ - virtual void visitObject(const Object *p) = 0; - - virtual void visit(const Bool *p); - virtual void visit(const Integer *p); - virtual void visit(const Float *p); - virtual void visit(const Double *p); - virtual void visit(const String *p); - virtual void visit(const Array *p); - virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); - virtual void visit(const Data *p); -}; - - -class CC_DLL PrettyPrinter : public DataVisitor -{ -public: - PrettyPrinter(int indentLevel = 0); - - virtual void clear(); - virtual std::string getResult(); - - virtual void visitObject(const Object *p); - virtual void visit(const Bool * p); - virtual void visit(const Integer *p); - virtual void visit(const Float *p); - virtual void visit(const Double *p); - virtual void visit(const String *p); - virtual void visit(const Array *p); - virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); - virtual void visit(const Data *p); -private: - void setIndentLevel(int indentLevel); - int _indentLevel; - std::string _indentStr; - std::string _result; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CCDATAVISITOR_H__ diff --git a/cocos/platform/cocoa/CCDictionary.cpp b/cocos/platform/cocoa/CCDictionary.cpp deleted file mode 100644 index 6b8df0febf..0000000000 --- a/cocos/platform/cocoa/CCDictionary.cpp +++ /dev/null @@ -1,454 +0,0 @@ -/**************************************************************************** - Copyright (c) 2012 - 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 "CCDictionary.h" -#include "CCString.h" -#include "CCInteger.h" -#include "platform/CCFileUtils.h" - -using namespace std; - -NS_CC_BEGIN - -// ----------------------------------------------------------------------- -// DictElement - -DictElement::DictElement(const char* pszKey, Object* pObject) -{ - CCASSERT(pszKey && strlen(pszKey) > 0, "Invalid key value."); - _intKey = 0; - const char* pStart = pszKey; - - size_t len = strlen(pszKey); - if (len > MAX_KEY_LEN ) - { - char* pEnd = (char*)&pszKey[len-1]; - pStart = pEnd - (MAX_KEY_LEN-1); - } - - strcpy(_strKey, pStart); - - _object = pObject; - memset(&hh, 0, sizeof(hh)); -} - -DictElement::DictElement(intptr_t iKey, Object* pObject) -{ - _strKey[0] = '\0'; - _intKey = iKey; - _object = pObject; - memset(&hh, 0, sizeof(hh)); -} - -DictElement::~DictElement() -{ - CCLOGINFO("deallocing DictElement: %p", this); -} - -// ----------------------------------------------------------------------- -// Dictionary - -Dictionary::Dictionary() -: _elements(NULL) -, _dictType(kDictUnknown) -{ - -} - -Dictionary::~Dictionary() -{ - CCLOGINFO("deallocing Dictionary: %p", this); - removeAllObjects(); -} - -unsigned int Dictionary::count() -{ - return HASH_COUNT(_elements); -} - -Array* Dictionary::allKeys() -{ - int iKeyCount = this->count(); - if (iKeyCount <= 0) return NULL; - - Array* pArray = Array::createWithCapacity(iKeyCount); - - DictElement *pElement, *tmp; - if (_dictType == kDictStr) - { - HASH_ITER(hh, _elements, pElement, tmp) - { - String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); - CC_SAFE_RELEASE(pOneKey); - } - } - else if (_dictType == kDictInt) - { - HASH_ITER(hh, _elements, pElement, tmp) - { - Integer* pOneKey = new Integer(pElement->_intKey); - pArray->addObject(pOneKey); - CC_SAFE_RELEASE(pOneKey); - } - } - - return pArray; -} - -Array* Dictionary::allKeysForObject(Object* object) -{ - int iKeyCount = this->count(); - if (iKeyCount <= 0) return NULL; - Array* pArray = Array::create(); - - DictElement *pElement, *tmp; - - if (_dictType == kDictStr) - { - HASH_ITER(hh, _elements, pElement, tmp) - { - if (object == pElement->_object) - { - String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); - CC_SAFE_RELEASE(pOneKey); - } - } - } - else if (_dictType == kDictInt) - { - HASH_ITER(hh, _elements, pElement, tmp) - { - if (object == pElement->_object) - { - Integer* pOneKey = new Integer(pElement->_intKey); - pArray->addObject(pOneKey); - CC_SAFE_RELEASE(pOneKey); - } - } - } - return pArray; -} - -Object* Dictionary::objectForKey(const std::string& key) -{ - // if dictionary wasn't initialized, return NULL directly. - if (_dictType == kDictUnknown) return NULL; - // Dictionary only supports one kind of key, string or integer. - // This method uses string as key, therefore we should make sure that the key type of this Dictionary is string. - CCASSERT(_dictType == kDictStr, "this dictionary does not use string as key."); - - Object* pRetObject = NULL; - DictElement *pElement = NULL; - HASH_FIND_STR(_elements, key.c_str(), pElement); - if (pElement != NULL) - { - pRetObject = pElement->_object; - } - return pRetObject; -} - -Object* Dictionary::objectForKey(intptr_t key) -{ - // if dictionary wasn't initialized, return NULL directly. - if (_dictType == kDictUnknown) return NULL; - // Dictionary only supports one kind of key, string or integer. - // This method uses integer as key, therefore we should make sure that the key type of this Dictionary is integer. - CCASSERT(_dictType == kDictInt, "this dictionary does not use integer as key."); - - Object* pRetObject = NULL; - DictElement *pElement = NULL; - HASH_FIND_PTR(_elements, &key, pElement); - if (pElement != NULL) - { - pRetObject = pElement->_object; - } - return pRetObject; -} - -const String* Dictionary::valueForKey(const std::string& key) -{ - String* pStr = dynamic_cast(objectForKey(key)); - if (pStr == NULL) - { - pStr = String::create(""); - } - return pStr; -} - -const String* Dictionary::valueForKey(intptr_t key) -{ - String* pStr = dynamic_cast(objectForKey(key)); - if (pStr == NULL) - { - pStr = String::create(""); - } - return pStr; -} - -void Dictionary::setObject(Object* pObject, const std::string& key) -{ - CCASSERT(key.length() > 0 && pObject != NULL, "Invalid Argument!"); - if (_dictType == kDictUnknown) - { - _dictType = kDictStr; - } - - CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as key."); - - DictElement *pElement = NULL; - HASH_FIND_STR(_elements, key.c_str(), pElement); - if (pElement == NULL) - { - setObjectUnSafe(pObject, key); - } - else if (pElement->_object != pObject) - { - Object* pTmpObj = pElement->_object; - pTmpObj->retain(); - removeObjectForElememt(pElement); - setObjectUnSafe(pObject, key); - pTmpObj->release(); - } -} - -void Dictionary::setObject(Object* pObject, intptr_t key) -{ - CCASSERT(pObject != NULL, "Invalid Argument!"); - if (_dictType == kDictUnknown) - { - _dictType = kDictInt; - } - - CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as key."); - - DictElement *pElement = NULL; - HASH_FIND_PTR(_elements, &key, pElement); - if (pElement == NULL) - { - setObjectUnSafe(pObject, key); - } - else if (pElement->_object != pObject) - { - Object* pTmpObj = pElement->_object; - pTmpObj->retain(); - removeObjectForElememt(pElement); - setObjectUnSafe(pObject, key); - pTmpObj->release(); - } - -} - -void Dictionary::removeObjectForKey(const std::string& key) -{ - if (_dictType == kDictUnknown) - { - return; - } - - CCASSERT(_dictType == kDictStr, "this dictionary doesn't use string as its key"); - CCASSERT(key.length() > 0, "Invalid Argument!"); - DictElement *pElement = NULL; - HASH_FIND_STR(_elements, key.c_str(), pElement); - removeObjectForElememt(pElement); -} - -void Dictionary::removeObjectForKey(intptr_t key) -{ - if (_dictType == kDictUnknown) - { - return; - } - - CCASSERT(_dictType == kDictInt, "this dictionary doesn't use integer as its key"); - DictElement *pElement = NULL; - HASH_FIND_PTR(_elements, &key, pElement); - removeObjectForElememt(pElement); -} - -void Dictionary::setObjectUnSafe(Object* pObject, const std::string& key) -{ - pObject->retain(); - DictElement* pElement = new DictElement(key.c_str(), pObject); - HASH_ADD_STR(_elements, _strKey, pElement); -} - -void Dictionary::setObjectUnSafe(Object* pObject, const intptr_t key) -{ - pObject->retain(); - DictElement* pElement = new DictElement(key, pObject); - HASH_ADD_PTR(_elements, _intKey, pElement); -} - -void Dictionary::removeObjectsForKeys(Array* pKeyArray) -{ - Object* pObj = NULL; - CCARRAY_FOREACH(pKeyArray, pObj) - { - String* pStr = static_cast(pObj); - removeObjectForKey(pStr->getCString()); - } -} - -void Dictionary::removeObjectForElememt(DictElement* pElement) -{ - if (pElement != NULL) - { - HASH_DEL(_elements, pElement); - pElement->_object->release(); - CC_SAFE_DELETE(pElement); - } -} - -void Dictionary::removeAllObjects() -{ - DictElement *pElement, *tmp; - HASH_ITER(hh, _elements, pElement, tmp) - { - HASH_DEL(_elements, pElement); - pElement->_object->release(); - CC_SAFE_DELETE(pElement); - - } -} - -Object* Dictionary::randomObject() -{ - if (_dictType == kDictUnknown) - { - return NULL; - } - - Object* key = allKeys()->getRandomObject(); - - if (_dictType == kDictInt) - { - return objectForKey( static_cast(key)->getValue()); - } - else if (_dictType == kDictStr) - { - return objectForKey( static_cast(key)->getCString()); - } - else - { - return NULL; - } -} - -Dictionary* Dictionary::create() -{ - Dictionary* ret = new Dictionary(); - if (ret && ret->init() ) - { - ret->autorelease(); - } - return ret; -} - -bool Dictionary::init() -{ - return true; -} - -Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) -{ - return srcDict->clone(); -} - -Dictionary* Dictionary::createWithContentsOfFileThreadSafe(const char *pFileName) -{ - return FileUtils::getInstance()->createDictionaryWithContentsOfFile(pFileName); -} - -void Dictionary::acceptVisitor(DataVisitor &visitor) -{ - return visitor.visit(this); -} - -Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) -{ - auto ret = createWithContentsOfFileThreadSafe(pFileName); - if (ret != nullptr) - { - ret->autorelease(); - } - return ret; -} - -bool Dictionary::writeToFile(const char *fullPath) -{ - return FileUtils::getInstance()->writeToFile(this, fullPath); -} - -Dictionary* Dictionary::clone() const -{ - Dictionary* newDict = Dictionary::create(); - - DictElement* element = NULL; - Object* tmpObj = NULL; - Clonable* obj = NULL; - if (_dictType == kDictInt) - { - CCDICT_FOREACH(this, element) - { - obj = dynamic_cast(element->getObject()); - if (obj) - { - tmpObj = dynamic_cast(obj->clone()); - if (tmpObj) - { - newDict->setObject(tmpObj, element->getIntKey()); - } - } - else - { - CCLOGWARN("%s isn't clonable.", typeid(*element->getObject()).name()); - } - } - } - else if (_dictType == kDictStr) - { - CCDICT_FOREACH(this, element) - { - obj = dynamic_cast(element->getObject()); - if (obj) - { - tmpObj = dynamic_cast(obj->clone()); - if (tmpObj) - { - newDict->setObject(tmpObj, element->getStrKey()); - } - } - else - { - CCLOGWARN("%s isn't clonable.", typeid(*element->getObject()).name()); - } - } - } - - return newDict; -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCDictionary.h b/cocos/platform/cocoa/CCDictionary.h deleted file mode 100644 index b0f1c98a9c..0000000000 --- a/cocos/platform/cocoa/CCDictionary.h +++ /dev/null @@ -1,458 +0,0 @@ -/**************************************************************************** -Copyright (c) 2012 - 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 __CCDICTIONARY_H__ -#define __CCDICTIONARY_H__ - -#include "support/data_support/uthash.h" -#include "CCObject.h" -#include "CCArray.h" -#include "CCString.h" - -NS_CC_BEGIN - -class Dictionary; - -/** - * @addtogroup data_structures - * @{ - */ - - -/** - * DictElement is used for traversing Dictionary. - * - * A DictElement is one element of Dictionary, it contains two properties, key and object. - * Its key has two different type (integer and string). - * - * @note The key type is unique, all the elements in Dictionary has the same key type(integer or string). - * @code - * DictElement* pElement; - * CCDICT_FOREACH(dict, pElement) - * { - * const char*key = pElement->getStrKey(); - * // You certainly know the type of value, so we assume that it's a Sprite. - * Sprite* pSprite = static_cast(pElement->getObject()); - * // ...... - * } - * @endcode - * - */ -class CC_DLL DictElement -{ -private: - /** - * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class. - * - * @param pszKey The string key of this element. - * @param pObject The object of this element. - */ - DictElement(const char* pszKey, Object* pObject); - - /** - * Constructor of DictElement. It's only for internal usage. Dictionary is its friend class. - * - * @param iKey The integer key of this element. - * @param pObject The object of this element. - */ - DictElement(intptr_t iKey, Object* pObject); - -public: - /** - * The destructor of DictElement. - * @js NA - * @lua NA - */ - ~DictElement(); - - // Inline functions need to be implemented in header file on Android. - - /** - * Get the string key of this element. - * @note This method assumes you know the key type in the element. - * If the element's key type is integer, invoking this method will cause an assert. - * - * @return The string key of this element. - */ - inline const char* getStrKey() const - { - CCASSERT(_strKey[0] != '\0', "Should not call this function for integer dictionary"); - return _strKey; - } - - /** - * Get the integer key of this element. - * @note This method assumes you know the key type in the element. - * If the element's key type is string, invoking this method will cause an assert. - * - * @return The integer key of this element. - */ - inline intptr_t getIntKey() const - { - CCASSERT(_strKey[0] == '\0', "Should not call this function for string dictionary"); - return _intKey; - } - - /** - * Get the object of this element. - * - * @return The object of this element. - */ - inline Object* getObject() const { return _object; } - -private: - // The max length of string key. - #define MAX_KEY_LEN 256 - // char array is needed for HASH_ADD_STR in UT_HASH. - // So it's a pain that all elements will allocate 256 bytes for this array. - char _strKey[MAX_KEY_LEN]; // hash key of string type - intptr_t _intKey; // hash key of integer type - Object* _object; // hash value -public: - UT_hash_handle hh; // makes this class hashable - friend class Dictionary; // declare Dictionary as friend class -}; - -/** The macro for traversing dictionary - * - * @note It's faster than getting all keys and traversing keys to get objects by objectForKey. - * It's also safe to remove elements while traversing. - */ -#define CCDICT_FOREACH(__dict__, __el__) \ - DictElement* pTmp##__dict__##__el__ = nullptr; \ - if (__dict__) \ - HASH_ITER(hh, (__dict__)->_elements, __el__, pTmp##__dict__##__el__) - - - -/** - * Dictionary is a class like NSDictionary in Obj-C . - * - * @note Only the pointer of Object or its subclass can be inserted to Dictionary. - * @code - * // Create a dictionary, return an autorelease object. - * Dictionary* pDict = Dictionary::create(); - * - * // Insert objects to dictionary - * String* pValue1 = String::create("100"); - * String* pValue2 = String::create("120"); - * Integer* pValue3 = Integer::create(200); - * pDict->setObject(pValue1, "key1"); - * pDict->setObject(pValue2, "key2"); - * pDict->setObject(pValue3, "key3"); - * - * // Get the object for key - * String* pStr1 = (String*)pDict->objectForKey("key1"); - * log("{ key1: %s }", pStr1->getCString()); - * Integer* pInteger = (Integer*)pDict->objectForKey("key3"); - * log("{ key3: %d }", pInteger->getValue()); - * @endcode - * - */ - -class CC_DLL Dictionary : public Object, public Clonable -{ -public: - /** - * The constructor of Dictionary. - * @js NA - * @lua NA - */ - Dictionary(); - - /** - * The destructor of Dictionary - * @js NA - * @lua NA - */ - ~Dictionary(); - - /** Initializes the dictionary. It returns true if the initializations was successful. - * @js NA - * @lua NA - */ - bool init(); - /** - * Get the count of elements in Dictionary. - * - * @return The count of elements. - * @js NA - */ - unsigned int count(); - - /** - * Return all keys of elements. - * - * @return The array contains all keys of elements. It's an autorelease object yet. - * @js NA - */ - Array* allKeys(); - - /** - * Get all keys according to the specified object. - * @warning We use '==' to compare two objects - * @return The array contains all keys for the specified object. It's an autorelease object yet. - * @js NA - */ - Array* allKeysForObject(Object* object); - - /** - * Get the object according to the specified string key. - * - * @note The dictionary needs to use string as key. If integer is passed, an assert will appear. - * @param key The string key for searching. - * @return The object matches the key. You need to force convert it to the type you know. - * @code - * // Assume that the elements are String* pointers. Convert it by following code. - * String* pStr = (String*)pDict->objectForKey("key1"); - * // Do something about pStr. - * // If you don't know the object type, properly you need to use dynamic_cast to check it. - * String* pStr2 = dynamic_cast(pDict->objectForKey("key1")); - * if (pStr2 != NULL) { - * // Do something about pStr2 - * } - * @endcode - * @see objectForKey(intptr_t) - * @js NA - */ - Object* objectForKey(const std::string& key); - - /** - * Get the object according to the specified integer key. - * - * @note The dictionary needs to use integer as key. If string is passed, an assert will appear. - * @param key The integer key for searching. - * @return The object matches the key. - * @see objectForKey(const std::string&) - * @js NA - */ - Object* objectForKey(intptr_t key); - - /** Get the value according to the specified string key. - * - * @note Be careful to use this function since it assumes the objects in the dictionary are String pointer. - * @param key The string key for searching - * @return An instance of String. - * It will return an empty string if the objects aren't String pointer or the key wasn't found. - * @see valueForKey(intptr_t) - * @js NA - */ - const String* valueForKey(const std::string& key); - - /** Get the value according to the specified integer key. - * - * @note Be careful to use this function since it assumes the objects in the dictionary are String pointer. - * @param key The string key for searching. - * @return An instance of String. - * It will return an empty string if the objects aren't String pointer or the key wasn't found. - * @see valueForKey(intptr_t) - * @js NA - */ - const String* valueForKey(intptr_t key); - - /** Insert an object to dictionary, and match it with the specified string key. - * - * @note Whe the first time this method is invoked, the key type will be set to string. - * After that you can't setObject with an integer key. - * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary. - * Then the new object will be inserted after that. - * - * @param pObject The Object to be inserted. - * @param key The string key for searching. - * @see setObject(Object*, intptr_t) - * @js NA - */ - void setObject(Object* pObject, const std::string& key); - - /** Insert an object to dictionary, and match it with the specified string key. - * - * @note Then the first time this method is invoked, the key type will be set to string. - * After that you can't setObject with an integer key. - * If the dictionary contains the key you passed, the object matching the key will be released and removed from dictionary. - * Then the new object will be inserted after that. - * @param pObject The Object to be inserted. - * @param key The string key for searching. - * @see setObject(Object*, const std::string&) - * @js NA - */ - void setObject(Object* pObject, intptr_t key); - - /** - * Remove an object by the specified string key. - * - * @param key The string key for searching. - * @see removeObjectForKey(intptr_t), removeObjectsForKeys(Array*), - * removeObjectForElememt(DictElement*), removeAllObjects(). - * @js NA - */ - void removeObjectForKey(const std::string& key); - - /** - * Remove an object by the specified integer key. - * - * @param key The integer key for searching. - * @see removeObjectForKey(const std::string&), removeObjectsForKeys(Array*), - * removeObjectForElememt(DictElement*), removeAllObjects(). - * @js NA - */ - void removeObjectForKey(intptr_t key); - - /** - * Remove objects by an array of keys. - * - * @param pKeyArray The array contains keys to be removed. - * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectForElememt(DictElement*), removeAllObjects(). - * @js NA - */ - void removeObjectsForKeys(Array* pKeyArray); - - /** - * Remove an object by an element. - * - * @param pElement The element need to be removed. - * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeAllObjects(). - * @js NA - * @lua NA - */ - void removeObjectForElememt(DictElement* pElement); - - /** - * Remove all objects in the dictionary. - * - * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeObjectForElememt(DictElement*). - * @js NA - */ - void removeAllObjects(); - - /** - * Return a random object in the dictionary. - * - * @return The random object. - * @see objectForKey(intptr_t), objectForKey(const std::string&) - * @js NA - * @lua NA - */ - Object* randomObject(); - - /** - * Create a dictionary. - * @return A dictionary which is an autorelease object. - * @see createWithDictionary(Dictionary*), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*). - * @js NA - */ - static Dictionary* create(); - - /** - * Create a dictionary with an existing dictionary. - * - * @param srcDict The exist dictionary. - * @return A dictionary which is an autorelease object. - * @see create(), createWithContentsOfFile(const char*), createWithContentsOfFileThreadSafe(const char*). - * @js NA - */ - static Dictionary* createWithDictionary(Dictionary* srcDict); - - /** - * Create a dictionary with a plist file. - * @param pFileName The name of the plist file. - * @return A dictionary which is an autorelease object. - * @see create(), createWithDictionary(Dictionary*), createWithContentsOfFileThreadSafe(const char*). - * @js NA - */ - static Dictionary* createWithContentsOfFile(const char *pFileName); - - /** - * Write a dictionary to a plist file. - * @param fullPath The full path of the plist file. You can get writeable path by getWritablePath() - * @return true if successed, false if failed - * @js NA - * @lua NA - */ - bool writeToFile(const char *fullPath); - - /** - * Create a dictionary with a plist file. - * - * @note the return object isn't an autorelease object. - * This can make sure not using autorelease pool in a new thread. - * Therefore, you need to manage the lifecycle of the return object. - * It means that when you don't need it, CC_SAFE_RELEASE needs to be invoked. - * - * @param pFileName The name of the plist file. - * @return A dictionary which isn't an autorelease object. - * @js NA - * @lua NA - */ - static Dictionary* createWithContentsOfFileThreadSafe(const char *pFileName); - - /* override functions - * @js NA - * @lua NA - */ - virtual void acceptVisitor(DataVisitor &visitor); - /** - * @js NA - * @lua NA - */ - virtual Dictionary* clone() const; - -private: - /** - * For internal usage, invoked by setObject. - */ - void setObjectUnSafe(Object* pObject, const std::string& key); - void setObjectUnSafe(Object* pObject, const intptr_t key); - -public: - /** - * All the elements in dictionary. - * - * @note For internal usage, we need to declare this member variable as public since it's used in UT_HASH. - */ - DictElement* _elements; -private: - - /** The support type of dictionary, it's confirmed when setObject is invoked. */ - enum DictType - { - kDictUnknown = 0, - kDictStr, - kDictInt - }; - - /** - * The type of dictionary, it's assigned to kDictUnknown by default. - */ - DictType _dictType; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif /* __CCDICTIONARY_H__ */ diff --git a/cocos/platform/cocoa/CCDouble.h b/cocos/platform/cocoa/CCDouble.h deleted file mode 100644 index 5b45b1d6cf..0000000000 --- a/cocos/platform/cocoa/CCDouble.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 __CCDOUBLE_H__ -#define __CCDOUBLE_H__ - -#include "CCObject.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -class CC_DLL Double : public Object, public Clonable -{ -public: - Double(double v) - : _value(v) {} - double getValue() const {return _value;} - - static Double* create(double v) - { - Double* pRet = new Double(v); - if (pRet) - { - pRet->autorelease(); - } - return pRet; - } - - /* override functions */ - virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } - - Double* clone() const - { - return Double::create(_value); - } -private: - double _value; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif /* __CCDOUBLE_H__ */ diff --git a/cocos/platform/cocoa/CCFloat.h b/cocos/platform/cocoa/CCFloat.h deleted file mode 100644 index c85a2e1e70..0000000000 --- a/cocos/platform/cocoa/CCFloat.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 __CCFLOAT_H__ -#define __CCFLOAT_H__ - -#include "CCObject.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -class CC_DLL Float : public Object, public Clonable -{ -public: - Float(float v) - : _value(v) {} - float getValue() const {return _value;} - - static Float* create(float v) - { - Float* pRet = new Float(v); - if (pRet) - { - pRet->autorelease(); - } - return pRet; - } - - /* override functions */ - virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } - - Float* clone() const - { - return Float::create(_value); - } - -private: - float _value; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif /* __CCFLOAT_H__ */ diff --git a/cocos/platform/cocoa/CCGeometry.cpp b/cocos/platform/cocoa/CCGeometry.cpp deleted file mode 100644 index cfce9d3fa7..0000000000 --- a/cocos/platform/cocoa/CCGeometry.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCGeometry.h" -#include "ccMacros.h" -#include - -// implementation of Point -NS_CC_BEGIN - -Point::Point(void) : x(0), y(0) -{ -} - -Point::Point(float xx, float yy) : x(xx), y(yy) -{ -} - -Point::Point(const Point& other) : x(other.x), y(other.y) -{ -} - -Point::Point(const Size& size) : x(size.width), y(size.height) -{ -} - -Point& Point::operator= (const Point& other) -{ - setPoint(other.x, other.y); - return *this; -} - -Point& Point::operator= (const Size& size) -{ - setPoint(size.width, size.height); - return *this; -} - -Point Point::operator+(const Point& right) const -{ - return Point(this->x + right.x, this->y + right.y); -} - -Point Point::operator-(const Point& right) const -{ - return Point(this->x - right.x, this->y - right.y); -} - -Point Point::operator-() const -{ - return Point(-x, -y); -} - -Point Point::operator*(float a) const -{ - return Point(this->x * a, this->y * a); -} - -Point Point::operator/(float a) const -{ - CCASSERT(a!=0, "CCPoint division by 0."); - return Point(this->x / a, this->y / a); -} - -void Point::setPoint(float xx, float yy) -{ - this->x = xx; - this->y = yy; -} - -bool Point::equals(const Point& target) const -{ - return (fabs(this->x - target.x) < FLT_EPSILON) - && (fabs(this->y - target.y) < FLT_EPSILON); -} - -bool Point::fuzzyEquals(const Point& b, float var) const -{ - if(x - var <= b.x && b.x <= x + var) - if(y - var <= b.y && b.y <= y + var) - return true; - return false; -} - -float Point::getAngle(const Point& other) const -{ - Point a2 = normalize(); - Point b2 = other.normalize(); - float angle = atan2f(a2.cross(b2), a2.dot(b2)); - if( fabs(angle) < FLT_EPSILON ) return 0.f; - return angle; -} - -Point Point::rotateByAngle(const Point& pivot, float angle) const -{ - return pivot + (*this - pivot).rotate(Point::forAngle(angle)); -} - -bool Point::isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float *E) -{ - float ABmin = MIN(A, B); - float ABmax = MAX(A, B); - float CDmin = MIN(C, D); - float CDmax = MAX(C, D); - - if (ABmax < CDmin || CDmax < ABmin) - { - // ABmin->ABmax->CDmin->CDmax or CDmin->CDmax->ABmin->ABmax - return false; - } - else - { - if (ABmin >= CDmin && ABmin <= CDmax) - { - // CDmin->ABmin->CDmax->ABmax or CDmin->ABmin->ABmax->CDmax - if (S != nullptr) *S = ABmin; - if (E != nullptr) *E = CDmax < ABmax ? CDmax : ABmax; - } - else if (ABmax >= CDmin && ABmax <= CDmax) - { - // ABmin->CDmin->ABmax->CDmax - if (S != nullptr) *S = CDmin; - if (E != nullptr) *E = ABmax; - } - else - { - // ABmin->CDmin->CDmax->ABmax - if (S != nullptr) *S = CDmin; - if (E != nullptr) *E = CDmax; - } - return true; - } -} - -bool Point::isLineIntersect(const Point& A, const Point& B, - const Point& C, const Point& D, - float *S, float *T) -{ - // FAIL: Line undefined - if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) - { - return false; - } - - const float denom = crossProduct2Vector(A, B, C, D); - - if (denom == 0) - { - // Lines parallel or overlap - return false; - } - - if (S != nullptr) *S = crossProduct2Vector(C, D, C, A) / denom; - if (T != nullptr) *T = crossProduct2Vector(A, B, C, A) / denom; - - return true; -} - -bool Point::isLineParallel(const Point& A, const Point& B, - const Point& C, const Point& D) -{ - // FAIL: Line undefined - if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) - { - return false; - } - - if (crossProduct2Vector(A, B, C, D) == 0) - { - // line overlap - if (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0) - { - return false; - } - - return true; - } - - return false; -} - -bool Point::isLineOverlap(const Point& A, const Point& B, - const Point& C, const Point& D) -{ - // FAIL: Line undefined - if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) ) - { - return false; - } - - if (crossProduct2Vector(A, B, C, D) == 0 && - (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0)) - { - return true; - } - - return false; -} - -bool Point::isSegmentOverlap(const Point& A, const Point& B, const Point& C, const Point& D, Point* S, Point* E) -{ - - if (isLineOverlap(A, B, C, D)) - { - return isOneDemensionSegmentOverlap(A.x, B.x, C.x, D.x, &S->x, &E->x) && - isOneDemensionSegmentOverlap(A.y, B.y, C.y, D.y, &S->y, &E->y); - } - - return false; -} - -bool Point::isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D) -{ - float S, T; - - if (isLineIntersect(A, B, C, D, &S, &T )&& - (S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f)) - { - return true; - } - - return false; -} - -Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D) -{ - float S, T; - - if (isLineIntersect(A, B, C, D, &S, &T)) - { - // Point of intersection - Point P; - P.x = A.x + S * (B.x - A.x); - P.y = A.y + S * (B.y - A.y); - return P; - } - - return Point::ZERO; -} - -const Point Point::ZERO = Point(0, 0); - -// implementation of Size - -Size::Size(void) : width(0), height(0) -{ -} - -Size::Size(float w, float h) : width(w), height(h) -{ -} - -Size::Size(const Size& other) : width(other.width), height(other.height) -{ -} - -Size::Size(const Point& point) : width(point.x), height(point.y) -{ -} - -Size& Size::operator= (const Size& other) -{ - setSize(other.width, other.height); - return *this; -} - -Size& Size::operator= (const Point& point) -{ - setSize(point.x, point.y); - return *this; -} - -Size Size::operator+(const Size& right) const -{ - return Size(this->width + right.width, this->height + right.height); -} - -Size Size::operator-(const Size& right) const -{ - return Size(this->width - right.width, this->height - right.height); -} - -Size Size::operator*(float a) const -{ - return Size(this->width * a, this->height * a); -} - -Size Size::operator/(float a) const -{ - CCASSERT(a!=0, "CCSize division by 0."); - return Size(this->width / a, this->height / a); -} - -void Size::setSize(float w, float h) -{ - this->width = w; - this->height = h; -} - -bool Size::equals(const Size& target) const -{ - return (fabs(this->width - target.width) < FLT_EPSILON) - && (fabs(this->height - target.height) < FLT_EPSILON); -} - -const Size Size::ZERO = Size(0, 0); - -// implementation of Rect - -Rect::Rect(void) -{ - setRect(0.0f, 0.0f, 0.0f, 0.0f); -} - -Rect::Rect(float x, float y, float width, float height) -{ - setRect(x, y, width, height); -} - -Rect::Rect(const Rect& other) -{ - setRect(other.origin.x, other.origin.y, other.size.width, other.size.height); -} - -Rect& Rect::operator= (const Rect& other) -{ - setRect(other.origin.x, other.origin.y, other.size.width, other.size.height); - return *this; -} - -void Rect::setRect(float x, float y, float width, float height) -{ - // CGRect can support width<0 or height<0 - // CCASSERT(width >= 0.0f && height >= 0.0f, "width and height of Rect must not less than 0."); - - origin.x = x; - origin.y = y; - - size.width = width; - size.height = height; -} - -bool Rect::equals(const Rect& rect) const -{ - return (origin.equals(rect.origin) && - size.equals(rect.size)); -} - -float Rect::getMaxX() const -{ - return origin.x + size.width; -} - -float Rect::getMidX() const -{ - return origin.x + size.width / 2.0f; -} - -float Rect::getMinX() const -{ - return origin.x; -} - -float Rect::getMaxY() const -{ - return origin.y + size.height; -} - -float Rect::getMidY() const -{ - return origin.y + size.height / 2.0f; -} - -float Rect::getMinY() const -{ - return origin.y; -} - -bool Rect::containsPoint(const Point& point) const -{ - bool bRet = false; - - if (point.x >= getMinX() && point.x <= getMaxX() - && point.y >= getMinY() && point.y <= getMaxY()) - { - bRet = true; - } - - return bRet; -} - -bool Rect::intersectsRect(const Rect& rect) const -{ - return !( getMaxX() < rect.getMinX() || - rect.getMaxX() < getMinX() || - getMaxY() < rect.getMinY() || - rect.getMaxY() < getMinY()); -} - -Rect Rect::unionWithRect(const Rect & rect) const -{ - float thisLeftX = origin.x; - float thisRightX = origin.x + size.width; - float thisTopY = origin.y + size.height; - float thisBottomY = origin.y; - - if (thisRightX < thisLeftX) - { - std::swap(thisRightX, thisLeftX); // This rect has negative width - } - - if (thisTopY < thisBottomY) - { - std::swap(thisTopY, thisBottomY); // This rect has negative height - } - - float otherLeftX = rect.origin.x; - float otherRightX = rect.origin.x + rect.size.width; - float otherTopY = rect.origin.y + rect.size.height; - float otherBottomY = rect.origin.y; - - if (otherRightX < otherLeftX) - { - std::swap(otherRightX, otherLeftX); // Other rect has negative width - } - - if (otherTopY < otherBottomY) - { - std::swap(otherTopY, otherBottomY); // Other rect has negative height - } - - float combinedLeftX = std::min(thisLeftX, otherLeftX); - float combinedRightX = std::max(thisRightX, otherRightX); - float combinedTopY = std::max(thisTopY, otherTopY); - float combinedBottomY = std::min(thisBottomY, otherBottomY); - - return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY); -} - -const Rect Rect::ZERO = Rect(0, 0, 0, 0); - -NS_CC_END diff --git a/cocos/platform/cocoa/CCGeometry.h b/cocos/platform/cocoa/CCGeometry.h deleted file mode 100644 index 47e2fdf9ac..0000000000 --- a/cocos/platform/cocoa/CCGeometry.h +++ /dev/null @@ -1,564 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCGEMETRY_H__ -#define __CCGEMETRY_H__ - -#include -#include - -#include "platform/CCPlatformMacros.h" -#include "CCObject.h" -#include "ccMacros.h" - -NS_CC_BEGIN - -/** Clamp a value between from and to. - @since v0.99.1 - */ -inline float clampf(float value, float min_inclusive, float max_inclusive) -{ - if (min_inclusive > max_inclusive) { - CC_SWAP(min_inclusive, max_inclusive, float); - } - return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive; -} - -/** - * @addtogroup data_structures - * @{ - */ - -// for Point assignement operator and copy constructor -class CC_DLL Size; - -class CC_DLL Point -{ -public: - float x; - float y; - -public: - /** - * @js NA - */ - Point(); - /** - * @js NA - */ - Point(float x, float y); - /** - * @js NA - * @lua NA - */ - Point(const Point& other); - /** - * @js NA - * @lua NA - */ - explicit Point(const Size& size); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Point& other); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Size& size); - /** - * @js NA - * @lua NA - */ - Point operator+(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point operator-(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point operator-() const; - /** - * @js NA - * @lua NA - */ - Point operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Point operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setPoint(float x, float y); - /** - * @js NA - */ - bool equals(const Point& target) const; - - /** @returns if points have fuzzy equality which means equal with some degree of variance. - @since v2.1.4 - * @js NA - * @lua NA - */ - bool fuzzyEquals(const Point& target, float variance) const; - - /** Calculates distance between point an origin - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLength() const { - return sqrtf(x*x + y*y); - }; - - /** Calculates the square length of a Point (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLengthSq() const { - return dot(*this); //x*x + y*y; - }; - - /** Calculates the square distance between two points (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistanceSq(const Point& other) const { - return (*this - other).getLengthSq(); - }; - - /** Calculates the distance between two points - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistance(const Point& other) const { - return (*this - other).getLength(); - }; - - /** @returns the angle in radians between this vector and the x axis - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getAngle() const { - return atan2f(y, x); - }; - - /** @returns the angle in radians between two vector directions - @since v2.1.4 - * @js NA - * @lua NA - */ - float getAngle(const Point& other) const; - - /** Calculates dot product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float dot(const Point& other) const { - return x*other.x + y*other.y; - }; - - /** Calculates cross product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float cross(const Point& other) const { - return x*other.y - y*other.x; - }; - - /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getPerp() const { - return Point(-y, x); - }; - - /** Calculates midpoint between two points. - @return Point - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getMidpoint(const Point& other) const - { - return Point((x + other.x) / 2.0f, (y + other.y) / 2.0f); - } - - /** Clamp a point between from and to. - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getClampPoint(const Point& min_inclusive, const Point& max_inclusive) const - { - return Point(clampf(x,min_inclusive.x,max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y)); - } - - /** Run a math operation function on each point component - * absf, fllorf, ceilf, roundf - * any function that has the signature: float func(float); - * For example: let's try to take the floor of x,y - * p.compOp(floorf); - @since v3.0 - * @js NA - * @lua NA - */ - inline Point compOp(std::function function) const - { - return Point(function(x), function(y)); - } - - /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getRPerp() const { - return Point(y, -x); - }; - - /** Calculates the projection of this over other. - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point project(const Point& other) const { - return other * (dot(other)/other.dot(other)); - }; - - /** Complex multiplication of two points ("rotates" two points). - @return Point vector with an angle of this.getAngle() + other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point rotate(const Point& other) const { - return Point(x*other.x - y*other.y, x*other.y + y*other.x); - }; - - /** Unrotates two points. - @return Point vector with an angle of this.getAngle() - other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point unrotate(const Point& other) const { - return Point(x*other.x + y*other.y, y*other.x - x*other.y); - }; - - /** Returns point multiplied to a length of 1. - * If the point is 0, it returns (1, 0) - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point normalize() const { - float length = getLength(); - if(length == 0.) return Point(1.f, 0); - return *this / getLength(); - }; - - /** Linear Interpolation between two points a and b - @returns - alpha == 0 ? a - alpha == 1 ? b - otherwise a value between a..b - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point lerp(const Point& other, float alpha) const { - return *this * (1.f - alpha) + other * alpha; - }; - - /** Rotates a point counter clockwise by the angle around a pivot - @param pivot is the pivot, naturally - @param angle is the angle of rotation ccw in radians - @returns the rotated point - @since v2.1.4 - * @js NA - * @lua NA - */ - Point rotateByAngle(const Point& pivot, float angle) const; - - /** - * @js NA - * @lua NA - */ - static inline Point forAngle(const float a) - { - return Point(cosf(a), sinf(a)); - } - - /** A general line-line intersection test - @param A the startpoint for the first line L1 = (A - B) - @param B the endpoint for the first line L1 = (A - B) - @param C the startpoint for the second line L2 = (C - D) - @param D the endpoint for the second line L2 = (C - D) - @param S the range for a hitpoint in L1 (p = A + S*(B - A)) - @param T the range for a hitpoint in L2 (p = C + T*(D - C)) - @returns whether these two lines interects. - - Note that to truly test intersection for segments we have to make - sure that S & T lie within [0..1] and for rays, make sure S & T > 0 - the hit point is C + T * (D - C); - the hit point also is A + S * (B - A); - @since 3.0 - * @js NA - * @lua NA - */ - static bool isLineIntersect(const Point& A, const Point& B, - const Point& C, const Point& D, - float *S = nullptr, float *T = nullptr); - - /** - returns true if Line A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineOverlap(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Line A-B parallel with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineParallel(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Segment A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentOverlap(const Point& A, const Point& B, - const Point& C, const Point& D, - Point* S = nullptr, Point* E = nullptr); - - /** - returns true if Segment A-B intersects with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D); - - /** - returns the intersection point of line A-B, C-D - @since v3.0 - * @js NA - * @lua NA - */ - static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); - - static const Point ZERO; - -private: - // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part - static bool isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E); - - // cross procuct of 2 vector. A->B X C->D - static float crossProduct2Vector(const Point& A, const Point& B, const Point& C, const Point& D) { return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y); } -}; - -class CC_DLL Size -{ -public: - float width; - float height; - -public: - /** - * @js NA - */ - Size(); - /** - * @js NA - */ - Size(float width, float height); - /** - * @js NA - * @lua NA - */ - Size(const Size& other); - /** - * @js NA - * @lua NA - */ - explicit Size(const Point& point); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Size& other); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Point& point); - /** - * @js NA - * @lua NA - */ - Size operator+(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator-(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Size operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setSize(float width, float height); - /** - * @js NA - */ - bool equals(const Size& target) const; - - static const Size ZERO; -}; - -class CC_DLL Rect -{ -public: - Point origin; - Size size; - -public: - /** - * @js NA - */ - Rect(); - /** - * @js NA - */ - Rect(float x, float y, float width, float height); - /** - * @js NA - * @lua NA - */ - Rect(const Rect& other); - /** - * @js NA - * @lua NA - */ - Rect& operator= (const Rect& other); - /** - * @js NA - * @lua NA - */ - void setRect(float x, float y, float width, float height); - /** - * @js NA - */ - float getMinX() const; /// return the leftmost x-value of current rect - /** - * @js NA - */ - float getMidX() const; /// return the midpoint x-value of current rect - /** - * @js NA - */ - float getMaxX() const; /// return the rightmost x-value of current rect - /** - * @js NA - */ - float getMinY() const; /// return the bottommost y-value of current rect - /** - * @js NA - */ - float getMidY() const; /// return the midpoint y-value of current rect - /** - * @js NA - */ - float getMaxY() const; /// return the topmost y-value of current rect - /** - * @js NA - */ - bool equals(const Rect& rect) const; - /** - * @js NA - */ - bool containsPoint(const Point& point) const; - /** - * @js NA - */ - bool intersectsRect(const Rect& rect) const; - /** - * @js NA - * @lua NA - */ - Rect unionWithRect(const Rect & rect) const; - - static const Rect ZERO; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CCGEMETRY_H__ diff --git a/cocos/platform/cocoa/CCInteger.h b/cocos/platform/cocoa/CCInteger.h deleted file mode 100644 index 23735627dd..0000000000 --- a/cocos/platform/cocoa/CCInteger.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 __CCINTEGER_H__ -#define __CCINTEGER_H__ - -#include "CCObject.h" -#include "platform/CCCommon.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -class CC_DLL Integer : public Object, public Clonable -{ -public: - static Integer* create(int v) - { - Integer* pRet = new Integer(v); - pRet->autorelease(); - return pRet; - } - /** - * @js NA - */ - Integer(int v) - : _value(v) {} - int getValue() const {return _value;} - /** - * @js NA - * @lua NA - */ - virtual ~Integer() { - CCLOGINFO("deallocing ~Integer: %p", this); - } - - /* override functions */ - virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } - - // overrides - virtual Integer* clone() const override - { - return Integer::create(_value); - } - -private: - int _value; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif /* __CCINTEGER_H__ */ diff --git a/cocos/platform/cocoa/CCNS.cpp b/cocos/platform/cocoa/CCNS.cpp deleted file mode 100644 index 8cf496c0b1..0000000000 --- a/cocos/platform/cocoa/CCNS.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#include "CCNS.h" -#include -#include -#include -#include - -using namespace std; - -NS_CC_BEGIN - -typedef std::vector strArray; - -// string toolkit -static inline void split(std::string src, const char* token, strArray& vect) -{ - int nend=0; - int nbegin=0; - while(nend != -1) - { - nend = src.find(token, nbegin); - if(nend == -1) - vect.push_back(src.substr(nbegin, src.length()-nbegin)); - else - vect.push_back(src.substr(nbegin, nend-nbegin)); - nbegin = nend + strlen(token); - } -} - -// first, judge whether the form of the string like this: {x,y} -// if the form is right,the string will be split into the parameter strs; -// or the parameter strs will be empty. -// if the form is right return true,else return false. -static bool splitWithForm(const char* pStr, strArray& strs) -{ - bool bRet = false; - - do - { - CC_BREAK_IF(!pStr); - - // string is empty - std::string content = pStr; - CC_BREAK_IF(content.length() == 0); - - int nPosLeft = content.find('{'); - int nPosRight = content.find('}'); - - // don't have '{' and '}' - CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); - // '}' is before '{' - CC_BREAK_IF(nPosLeft > nPosRight); - - std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); - // nothing between '{' and '}' - CC_BREAK_IF(pointStr.length() == 0); - - int nPos1 = pointStr.find('{'); - int nPos2 = pointStr.find('}'); - // contain '{' or '}' - CC_BREAK_IF(nPos1 != (int)std::string::npos || nPos2 != (int)std::string::npos); - - split(pointStr, ",", strs); - if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0) - { - strs.clear(); - break; - } - - bRet = true; - } while (0); - - return bRet; -} - -// implement the functions - -Rect RectFromString(const char* pszContent) -{ - Rect result = Rect::ZERO; - - do - { - CC_BREAK_IF(!pszContent); - std::string content = pszContent; - - // find the first '{' and the third '}' - int nPosLeft = content.find('{'); - int nPosRight = content.find('}'); - for (int i = 1; i < 3; ++i) - { - if (nPosRight == (int)std::string::npos) - { - break; - } - nPosRight = content.find('}', nPosRight + 1); - } - CC_BREAK_IF(nPosLeft == (int)std::string::npos || nPosRight == (int)std::string::npos); - - content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); - int nPointEnd = content.find('}'); - CC_BREAK_IF(nPointEnd == (int)std::string::npos); - nPointEnd = content.find(',', nPointEnd); - CC_BREAK_IF(nPointEnd == (int)std::string::npos); - - // get the point string and size string - std::string pointStr = content.substr(0, nPointEnd); - std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); - - // split the string with ',' - strArray pointInfo; - CC_BREAK_IF(!splitWithForm(pointStr.c_str(), pointInfo)); - strArray sizeInfo; - CC_BREAK_IF(!splitWithForm(sizeStr.c_str(), sizeInfo)); - - float x = (float) atof(pointInfo[0].c_str()); - float y = (float) atof(pointInfo[1].c_str()); - float width = (float) atof(sizeInfo[0].c_str()); - float height = (float) atof(sizeInfo[1].c_str()); - - result = Rect(x, y, width, height); - } while (0); - - return result; -} - -Point PointFromString(const char* pszContent) -{ - Point ret = Point::ZERO; - - do - { - strArray strs; - CC_BREAK_IF(!splitWithForm(pszContent, strs)); - - float x = (float) atof(strs[0].c_str()); - float y = (float) atof(strs[1].c_str()); - - ret = Point(x, y); - } while (0); - - return ret; -} - -Size SizeFromString(const char* pszContent) -{ - Size ret = Size::ZERO; - - do - { - strArray strs; - CC_BREAK_IF(!splitWithForm(pszContent, strs)); - - float width = (float) atof(strs[0].c_str()); - float height = (float) atof(strs[1].c_str()); - - ret = Size(width, height); - } while (0); - - return ret; -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCNS.h b/cocos/platform/cocoa/CCNS.h deleted file mode 100644 index 8ce8e1dde6..0000000000 --- a/cocos/platform/cocoa/CCNS.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __PLATFOMR_CCNS_H__ -#define __PLATFOMR_CCNS_H__ - -#include "CCGeometry.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -/** -@brief Returns a Core Graphics rectangle structure corresponding to the data in a given string. -@param pszContent A string object whose contents are of the form "{{x,y},{w, h}}", - where x is the x coordinate, y is the y coordinate, w is the width, and h is the height. - These components can represent integer or float values. - An example of a valid string is "{{3,2},{4,5}}". - The string is not localized, so items are always separated with a comma. -@return A Core Graphics structure that represents a rectangle. - If the string is not well-formed, the function returns Rect::ZERO. -*/ -Rect CC_DLL RectFromString(const char* pszContent); - -/** -@brief Returns a Core Graphics point structure corresponding to the data in a given string. -@param pszContent A string object whose contents are of the form "{x,y}", - where x is the x coordinate and y is the y coordinate. - The x and y values can represent integer or float values. - An example of a valid string is "{3.0,2.5}". - The string is not localized, so items are always separated with a comma. -@return A Core Graphics structure that represents a point. - If the string is not well-formed, the function returns Point::ZERO. -*/ -Point CC_DLL PointFromString(const char* pszContent); - -/** -@brief Returns a Core Graphics size structure corresponding to the data in a given string. -@param pszContent A string object whose contents are of the form "{w, h}", - where w is the width and h is the height. - The w and h values can be integer or float values. - An example of a valid string is "{3.0,2.5}". - The string is not localized, so items are always separated with a comma. -@return A Core Graphics structure that represents a size. - If the string is not well-formed, the function returns Size::ZERO. -*/ -Size CC_DLL SizeFromString(const char* pszContent); - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __PLATFOMR_CCNS_H__ - - diff --git a/cocos/platform/cocoa/CCObject.cpp b/cocos/platform/cocoa/CCObject.cpp deleted file mode 100644 index 13fa0e3236..0000000000 --- a/cocos/platform/cocoa/CCObject.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - - -#include "CCObject.h" -#include "CCAutoreleasePool.h" -#include "ccMacros.h" -#include "script_support/CCScriptSupport.h" - -NS_CC_BEGIN - -Object::Object() -: _luaID(0) -, _reference(1) // when the object is created, the reference count of it is 1 -, _autoReleaseCount(0) -{ - static unsigned int uObjectCount = 0; - - _ID = ++uObjectCount; -} - -Object::~Object() -{ - // if the object is managed, we should remove it - // from pool manager - if (_autoReleaseCount > 0) - { - PoolManager::sharedPoolManager()->removeObject(this); - } - - // if the object is referenced by Lua engine, remove it - if (_luaID) - { - ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptObjectByObject(this); - } - else - { - ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); - if (pEngine != NULL && pEngine->getScriptType() == kScriptTypeJavascript) - { - pEngine->removeScriptObjectByObject(this); - } - } -} - -Object* Object::autorelease() -{ - PoolManager::sharedPoolManager()->addObject(this); - return this; -} - -bool Object::isSingleReference() const -{ - return _reference == 1; -} - -unsigned int Object::retainCount() const -{ - return _reference; -} - -bool Object::isEqual(const Object *object) -{ - return this == object; -} - -void Object::acceptVisitor(DataVisitor &visitor) -{ - visitor.visitObject(this); -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCObject.h b/cocos/platform/cocoa/CCObject.h deleted file mode 100644 index 8de1ff9d8b..0000000000 --- a/cocos/platform/cocoa/CCObject.h +++ /dev/null @@ -1,216 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCOBJECT_H__ -#define __CCOBJECT_H__ - -#include "cocoa/CCDataVisitor.h" -#include "ccMacros.h" - -#ifdef EMSCRIPTEN -#include -#endif // EMSCRIPTEN - -NS_CC_BEGIN - -/** - * @addtogroup base_nodes - * @{ - */ - -class Object; -class Node; - -/** Interface that defines how to clone an object */ -class CC_DLL Clonable -{ -public: - /** returns a copy of the object */ - virtual Clonable* clone() const = 0; - /** - * @js NA - * @lua NA - */ - virtual ~Clonable() {}; - - /** returns a copy of the object. - @deprecated Use clone() instead - */ - CC_DEPRECATED_ATTRIBUTE Object* copy() const - { - // use "clone" instead - CC_ASSERT(false); - return nullptr; - } -}; - -class CC_DLL Object -{ -public: - /// object id, ScriptSupport need public _ID - unsigned int _ID; - /// Lua reference id - int _luaID; -protected: - /// count of references - unsigned int _reference; - /// count of autorelease - unsigned int _autoReleaseCount; -public: - /** - * Constructor - * - * The object's reference count is 1 after construction. - * @js NA - */ - Object(); - - /** - * @js NA - * @lua NA - */ - virtual ~Object(); - - /** - * Release the ownership immediately. - * - * This decrements the object's reference count. - * - * If the reference count reaches 0 after the descrement, this object is - * destructed. - * - * @see retain, autorelease - * @js NA - */ - inline void release() - { - CCASSERT(_reference > 0, "reference count should greater than 0"); - --_reference; - - if (_reference == 0) - delete this; - } - - /** - * Retains the ownership. - * - * This increases the object's reference count. - * - * @see release, autorelease - * @js NA - */ - inline void retain() - { - CCASSERT(_reference > 0, "reference count should greater than 0"); - ++_reference; - } - - /** - * Release the ownership sometime soon automatically. - * - * This descrements the object's reference count at the end of current - * autorelease pool block. - * - * If the reference count reaches 0 after the descrement, this object is - * destructed. - * - * @returns The object itself. - * - * @see AutoreleasePool, retain, release - * @js NA - * @lua NA - */ - Object* autorelease(); - - /** - * Returns a boolean value that indicates whether there is only one - * reference to the object. That is, whether the reference count is 1. - * - * @returns Whether the object's reference count is 1. - * @js NA - */ - bool isSingleReference() const; - - /** - * Returns the object's current reference count. - * - * @returns The object's reference count. - * @js NA - */ - unsigned int retainCount() const; - - /** - * Returns a boolean value that indicates whether this object and a given - * object are equal. - * - * @param object The object to be compared to this object. - * - * @returns True if this object and @p object are equal, otherwise false. - * @js NA - * @lua NA - */ - virtual bool isEqual(const Object* object); - /** - * @js NA - * @lua NA - */ - virtual void acceptVisitor(DataVisitor &visitor); - /** - * @js NA - * @lua NA - */ - virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; - - friend class AutoreleasePool; -}; - - -typedef void (Object::*SEL_SCHEDULE)(float); -typedef void (Object::*SEL_CallFunc)(); -typedef void (Object::*SEL_CallFuncN)(Node*); -typedef void (Object::*SEL_CallFuncND)(Node*, void*); -typedef void (Object::*SEL_CallFuncO)(Object*); -typedef void (Object::*SEL_MenuHandler)(Object*); -typedef int (Object::*SEL_Compare)(Object*); - -#define schedule_selector(_SELECTOR) static_cast(&_SELECTOR) -#define callfunc_selector(_SELECTOR) static_cast(&_SELECTOR) -#define callfuncN_selector(_SELECTOR) static_cast(&_SELECTOR) -#define callfuncND_selector(_SELECTOR) static_cast(&_SELECTOR) -#define callfuncO_selector(_SELECTOR) static_cast(&_SELECTOR) -#define menu_selector(_SELECTOR) static_cast(&_SELECTOR) -#define event_selector(_SELECTOR) static_cast(&_SELECTOR) -#define compare_selector(_SELECTOR) static_cast(&_SELECTOR) - -// new callbacks based on C++11 -#define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__) -#define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) -#define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__) - -// end of base_nodes group -/// @} - -NS_CC_END - -#endif // __CCOBJECT_H__ diff --git a/cocos/platform/cocoa/CCSet.cpp b/cocos/platform/cocoa/CCSet.cpp deleted file mode 100644 index c3c24e0e5e..0000000000 --- a/cocos/platform/cocoa/CCSet.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCSet.h" - -using namespace std; - -NS_CC_BEGIN - -Set::Set(void) -{ - _set = new set; -} - -Set::Set(const Set &rSetObject) -{ - _set = new set(*rSetObject._set); - - // call retain of members - SetIterator iter; - for (iter = _set->begin(); iter != _set->end(); ++iter) - { - if (! (*iter)) - { - break; - } - - (*iter)->retain(); - } -} - -Set::~Set(void) -{ - removeAllObjects(); - CC_SAFE_DELETE(_set); -} - -void Set::acceptVisitor(DataVisitor &visitor) -{ - visitor.visit(this); -} - -Set * Set::create() -{ - Set * pRet = new Set(); - - if (pRet != NULL) - { - pRet->autorelease(); - } - - return pRet; -} - -Set* Set::copy(void) -{ - Set *pSet = new Set(*this); - - return pSet; -} - -Set* Set::mutableCopy(void) -{ - return copy(); -} - -int Set::count(void) -{ - return (int)_set->size(); -} - -void Set::addObject(Object *pObject) -{ - if (_set->count(pObject) == 0) - { - CC_SAFE_RETAIN(pObject); - _set->insert(pObject); - } -} - -void Set::removeObject(Object *pObject) -{ - if (_set->erase(pObject) > 0) - { - CC_SAFE_RELEASE(pObject); - } -} - -void Set::removeAllObjects() -{ - SetIterator it = _set->begin(); - SetIterator tmp; - - while (it != _set->end()) - { - if (!(*it)) - { - break; - } - - tmp = it; - ++tmp; - Object * obj = *it; - _set->erase(it); - CC_SAFE_RELEASE(obj); - it = tmp; - } -} - -bool Set::containsObject(Object *pObject) -{ - return _set->find(pObject) != _set->end(); -} - -SetIterator Set::begin(void) -{ - return _set->begin(); -} - -SetIterator Set::end(void) -{ - return _set->end(); -} - -Object* Set::anyObject() -{ - if (!_set || _set->empty()) - { - return 0; - } - - SetIterator it; - - for( it = _set->begin(); it != _set->end(); ++it) - { - if (*it) - { - return (*it); - } - } - - return 0; -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCSet.h b/cocos/platform/cocoa/CCSet.h deleted file mode 100644 index c748f0ada5..0000000000 --- a/cocos/platform/cocoa/CCSet.h +++ /dev/null @@ -1,119 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 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 __CC_SET_H__ -#define __CC_SET_H__ - -#include -#include "CCObject.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -typedef std::set::iterator SetIterator; - -class CC_DLL Set : public Object -{ -public: - /** - * @js ctor - */ - Set(void); - Set(const Set &rSetObject); - /** - * @js NA - * @lua NA - */ - virtual ~Set(void); - - /** - * @brief Create and return a new empty set. - */ - static Set * create(); - - /** - *@brief Return a copy of the Set, it will copy all the elements. - */ - Set* copy(); - /** - *@brief It is the same as copy(). - */ - Set* mutableCopy(); - /** - *@brief Return the number of elements the Set contains. - */ - int count(); - /** - *@brief Add a element into Set, it will retain the element. - */ - void addObject(Object *pObject); - /** - *@brief Remove the given element, nothing todo if no element equals pObject. - */ - void removeObject(Object *pObject); - /** - *@brief Remove all elements of the set - */ - void removeAllObjects(); - /** - *@brief Check if Set contains a element equals pObject. - */ - bool containsObject(Object *pObject); - /** - *@brief Return the iterator that points to the first element. - * @js NA - * @lua NA - */ - SetIterator begin(); - /** - *@brief Return the iterator that points to the position after the last element. - * @js NA - * @lua NA - */ - SetIterator end(); - /** - *@brief Return the first element if it contains elements, or null if it doesn't contain any element. - */ - Object* anyObject(); - /** - * @js NA - * @lua NA - */ - virtual void acceptVisitor(DataVisitor &visitor); - -private: - std::set *_set; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CC_SET_H__ - diff --git a/cocos/platform/cocoa/CCString.cpp b/cocos/platform/cocoa/CCString.cpp deleted file mode 100644 index f9962b1ba4..0000000000 --- a/cocos/platform/cocoa/CCString.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 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 "CCString.h" -#include "platform/CCFileUtils.h" -#include "ccMacros.h" -#include -#include -#include "CCArray.h" - -NS_CC_BEGIN - -#define kMaxStringLen (1024*100) - -String::String() - :_string("") -{} - -String::String(const char * str) - :_string(str) -{} - -String::String(const std::string& str) - :_string(str) -{} - -String::String(const String& str) - :_string(str.getCString()) -{} - -String::~String() -{ - CCLOGINFO("deallocing String: %p", this); - - _string.clear(); -} - -String& String::operator= (const String& other) -{ - _string = other._string; - return *this; -} - -bool String::initWithFormatAndValist(const char* format, va_list ap) -{ - bool bRet = false; - char* pBuf = (char*)malloc(kMaxStringLen); - if (pBuf != NULL) - { - vsnprintf(pBuf, kMaxStringLen, format, ap); - _string = pBuf; - free(pBuf); - bRet = true; - } - return bRet; -} - -bool String::initWithFormat(const char* format, ...) -{ - bool bRet = false; - _string.clear(); - - va_list ap; - va_start(ap, format); - - bRet = initWithFormatAndValist(format, ap); - - va_end(ap); - - return bRet; -} - -int String::intValue() const -{ - if (length() == 0) - { - return 0; - } - return atoi(_string.c_str()); -} - -unsigned int String::uintValue() const -{ - if (length() == 0) - { - return 0; - } - return (unsigned int)atoi(_string.c_str()); -} - -float String::floatValue() const -{ - if (length() == 0) - { - return 0.0f; - } - return (float)atof(_string.c_str()); -} - -double String::doubleValue() const -{ - if (length() == 0) - { - return 0.0; - } - return atof(_string.c_str()); -} - -bool String::boolValue() const -{ - if (length() == 0) - { - return false; - } - - if (0 == strcmp(_string.c_str(), "0") || 0 == strcmp(_string.c_str(), "false")) - { - return false; - } - return true; -} - -const char* String::getCString() const -{ - return _string.c_str(); -} - -unsigned int String::length() const -{ - return _string.length(); -} - -int String::compare(const char * pStr) const -{ - return strcmp(getCString(), pStr); -} - -void String::append(const std::string& str) -{ - _string.append(str); -} - -void String::appendWithFormat(const char* format, ...) -{ - va_list ap; - va_start(ap, format); - - char* pBuf = (char*)malloc(kMaxStringLen); - if (pBuf != NULL) - { - vsnprintf(pBuf, kMaxStringLen, format, ap); - _string.append(pBuf); - free(pBuf); - } - - va_end(ap); - -} - -Array* String::componentsSeparatedByString(const char *delimiter) -{ - Array* result = Array::create(); - - int cutAt; - while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) - { - if(cutAt > 0) - { - result->addObject(String::create(_string.substr(0, cutAt))); - } - _string = _string.substr(cutAt + 1); - } - - if(_string.length() > 0) - { - result->addObject(String::create(_string)); - } - - return result; -} - -bool String::isEqual(const Object* pObject) -{ - bool bRet = false; - const String* pStr = dynamic_cast(pObject); - if (pStr != NULL) - { - if (0 == _string.compare(pStr->_string)) - { - bRet = true; - } - } - return bRet; -} - -String* String::create(const std::string& str) -{ - String* pRet = new String(str); - pRet->autorelease(); - return pRet; -} - -String* String::createWithData(const unsigned char* pData, unsigned long nLen) -{ - String* pRet = NULL; - if (pData != NULL) - { - char* pStr = (char*)malloc(nLen+1); - if (pStr != NULL) - { - pStr[nLen] = '\0'; - if (nLen > 0) - { - memcpy(pStr, pData, nLen); - } - - pRet = String::create(pStr); - free(pStr); - } - } - return pRet; -} - -String* String::createWithFormat(const char* format, ...) -{ - String* pRet = String::create(""); - va_list ap; - va_start(ap, format); - pRet->initWithFormatAndValist(format, ap); - va_end(ap); - - return pRet; -} - -String* String::createWithContentsOfFile(const char* filename) -{ - unsigned long size = 0; - unsigned char* pData = 0; - String* pRet = NULL; - pData = FileUtils::getInstance()->getFileData(filename, "rb", &size); - pRet = String::createWithData(pData, size); - CC_SAFE_DELETE_ARRAY(pData); - return pRet; -} - -void String::acceptVisitor(DataVisitor &visitor) -{ - visitor.visit(this); -} - -String* String::clone() const -{ - return String::create(_string); -} - -NS_CC_END diff --git a/cocos/platform/cocoa/CCString.h b/cocos/platform/cocoa/CCString.h deleted file mode 100644 index a6f237a476..0000000000 --- a/cocos/platform/cocoa/CCString.h +++ /dev/null @@ -1,210 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#ifndef __CCSTRING_H__ -#define __CCSTRING_H__ - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) -#include -#endif - -#include -#include -#include -#include "CCObject.h" - -NS_CC_BEGIN - -/** - * @addtogroup data_structures - * @{ - */ - -class CC_DLL String : public Object, public Clonable -{ -public: - /** - * @js NA - * @lua NA - */ - String(); - /** - * @js NA - * @lua NA - */ - String(const char* str); - /** - * @js NA - * @lua NA - */ - String(const std::string& str); - /** - * @js NA - * @lua NA - */ - String(const String& str); - /** - * @js NA - * @lua NA - */ - virtual ~String(); - - /* override assignment operator - * @js NA - * @lua NA - */ - String& operator= (const String& other); - - /** init a string with format, it's similar with the c function 'sprintf' - * @js NA - * @lua NA - */ - bool initWithFormat(const char* format, ...) CC_FORMAT_PRINTF(2, 3); - - /** convert to int value - * @js NA - */ - int intValue() const; - - /** convert to unsigned int value - * @js NA - */ - unsigned int uintValue() const; - - /** convert to float value - * @js NA - */ - float floatValue() const; - - /** convert to double value - * @js NA - */ - double doubleValue() const; - - /** convert to bool value - * @js NA - */ - bool boolValue() const; - - /** get the C string - * @js NA - */ - const char* getCString() const; - - /** get the length of string - * @js NA - */ - unsigned int length() const; - - /** compare to a c string - * @js NA - */ - int compare(const char *) const; - - /** append additional characters at the end of its current value - * @js NA - * @lua NA - */ - void append(const std::string& str); - - /** append(w/ format) additional characters at the end of its current value - * @js NA - * @lua NA - */ - void appendWithFormat(const char* format, ...); - - /** split a string - * @js NA - * @lua NA - */ - Array* componentsSeparatedByString(const char *delimiter); - - /* override functions - * @js NA - */ - virtual bool isEqual(const Object* pObject); - - /** create a string with std string, you can also pass a c string pointer because the default constructor of std::string can access a c string pointer. - * @return A String pointer which is an autorelease object pointer, - * it means that you needn't do a release operation unless you retain it. - * @js NA - */ - static String* create(const std::string& str); - - /** create a string with format, it's similar with the c function 'sprintf', the default buffer size is (1024*100) bytes, - * if you want to change it, you should modify the kMaxStringLen macro in String.cpp file. - * @return A String pointer which is an autorelease object pointer, - * it means that you needn't do a release operation unless you retain it. - * @js NA - */ - static String* createWithFormat(const char* format, ...) CC_FORMAT_PRINTF(1, 2); - - /** create a string with binary data - * @return A String pointer which is an autorelease object pointer, - * it means that you needn't do a release operation unless you retain it. - * @js NA - */ - static String* createWithData(const unsigned char* pData, unsigned long nLen); - - /** create a string with a file, - * @return A String pointer which is an autorelease object pointer, - * it means that you needn't do a release operation unless you retain it. - * @js NA - */ - static String* createWithContentsOfFile(const char* filename); - /** - * @js NA - * @lua NA - */ - virtual void acceptVisitor(DataVisitor &visitor); - /** - * @js NA - * @lua NA - */ - virtual String* clone() const; - -private: - - /** only for internal use */ - bool initWithFormatAndValist(const char* format, va_list ap); - -public: - std::string _string; -}; - -struct StringCompare : public std::binary_function { - public: - bool operator() (String * a, String * b) const { - return strcmp(a->getCString(), b->getCString()) < 0; - } -}; - -#define StringMake(str) String::create(str) -#define ccs StringMake - -// end of data_structure group -/// @} - -NS_CC_END - -#endif //__CCSTRING_H__ From 5c7603e0ce940992732214867d1f75c4f446fed2 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 14 Oct 2013 13:56:08 +0800 Subject: [PATCH 129/557] issue #2771: change angular damping to moment. (these two have different meaning, change to the correct one) --- cocos2dx/physics/CCPhysicsBody.cpp | 178 ++++++++++++------ cocos2dx/physics/CCPhysicsBody.h | 38 +++- cocos2dx/physics/CCPhysicsShape.cpp | 16 +- cocos2dx/physics/CCPhysicsShape.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 3 +- 5 files changed, 162 insertions(+), 79 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 2dc38bf286..eb98bef258 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -56,8 +56,7 @@ NS_CC_BEGIN namespace { static const float MASS_DEFAULT = 1.0; - static const float DENSITY_DEFAULT = 1.0; - static const float ANGULARDAMPING_DEFAULT = 200; + static const float MOMENT_DEFAULT = 200; } PhysicsBody::PhysicsBody() @@ -67,11 +66,11 @@ PhysicsBody::PhysicsBody() , _dynamic(true) , _enable(true) , _massDefault(true) -, _angularDampingDefault(true) +, _momentDefault(true) , _mass(MASS_DEFAULT) , _area(0.0) -, _density(DENSITY_DEFAULT) -, _angularDamping(ANGULARDAMPING_DEFAULT) +, _density(0) +, _moment(MOMENT_DEFAULT) , _tag(0) { } @@ -217,7 +216,7 @@ bool PhysicsBody::init() _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); - _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_angularDamping)); + _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); CC_BREAK_IF(_info->body == nullptr); return true; @@ -233,7 +232,7 @@ void PhysicsBody::setDynamic(bool dynamic) if (dynamic) { cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_angularDamping)); + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); }else { cpBodySetMass(_info->body, PHYSICS_INFINITY); @@ -322,21 +321,7 @@ void PhysicsBody::addShape(PhysicsShape* shape) } } - if (shape->getAngularDumping() > 0) - { - if (shape->getAngularDumping() == INFINITY) - { - _angularDamping = INFINITY; - _angularDampingDefault = false; - cpBodySetMoment(_info->body, _angularDamping); - } - else if (_angularDamping != INFINITY) - { - _angularDamping = (_angularDampingDefault ? 0 : _angularDamping) + shape->getAngularDumping(); - _angularDampingDefault = false; - cpBodySetMoment(_info->body, _angularDamping); - } - } + addMoment(shape->getMoment()); if (_world != nullptr) _world->addShape(shape); @@ -371,12 +356,112 @@ void PhysicsBody::applyTorque(float torque) void PhysicsBody::setMass(float mass) { + if (mass <= 0) + { + return; + } + _mass = mass; _massDefault = false; + // update density + if (_mass == PHYSICS_INFINITY) + { + _density = PHYSICS_INFINITY; + } + else + { + if (_area > 0) + { + _density = _mass / _area; + }else + { + _density = 0; + } + } + cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); } +void PhysicsBody::addMass(float mass) +{ + if (mass == PHYSICS_INFINITY) + { + mass = PHYSICS_INFINITY; + _massDefault = false; + _density = PHYSICS_INFINITY; + } + else if (mass == -PHYSICS_INFINITY) + { + return; + } + else if (_mass != PHYSICS_INFINITY) + { + if (_massDefault) + { + _mass = 0; + _massDefault = false; + } + + if (_mass + mass > 0) + { + _mass += mass; + }else + { + _mass = MASS_DEFAULT; + _massDefault = true; + } + + if (_area > 0) + { + _density = _mass / _area; + } + else + { + _density = 0; + } + } +} + +void PhysicsBody::addMoment(float moment) +{ + if (moment == PHYSICS_INFINITY) + { + // if moment is INFINITY, the moment of the body will become INFINITY + _moment = PHYSICS_INFINITY; + _momentDefault = false; + } + else if (moment == -PHYSICS_INFINITY) + { + // if moment is -INFINITY, it won't change + return; + } + else + { + // if moment of the body is INFINITY is has no effect + if (_moment != PHYSICS_INFINITY) + { + if (_momentDefault) + { + _moment = 0; + _momentDefault = false; + } + + if (_moment + moment > 0) + { + _moment += moment; + } + else + { + _moment = MOMENT_DEFAULT; + _momentDefault = true; + } + } + } + + cpBodySetMoment(_info->body, moment); +} + void PhysicsBody::setVelocity(Point velocity) { cpBodySetVel(_info->body, PhysicsHelper::point2cpv(velocity)); @@ -387,12 +472,12 @@ Point PhysicsBody::getVelocity() return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); } -void PhysicsBody::setAngularDamping(float angularDamping) +void PhysicsBody::setMoment(float moment) { - _angularDamping = angularDamping; - _angularDampingDefault = false; + _moment = moment; + _momentDefault = false; - cpBodySetMoment(_info->body, _angularDamping); + cpBodySetMoment(_info->body, _moment); } PhysicsShape* PhysicsBody::getShapeByTag(int tag) @@ -434,42 +519,11 @@ void PhysicsBody::removeShape(PhysicsShape* shape) _shapes.erase(it); - // deduce the mass, area and angularDamping - if (_mass != PHYSICS_INFINITY && shape->getMass() != PHYSICS_INFINITY) - { - if (_mass - shape->getMass() <= 0) - { - _mass = MASS_DEFAULT; - _massDefault = true; - }else - { - _mass = _mass = shape->getMass(); - } - - _area -= shape->getArea(); - - if (_mass == PHYSICS_INFINITY) - { - _density = PHYSICS_INFINITY; - } - else if (_area > 0) - { - _density = _mass / _area; - } - else - { - _density = DENSITY_DEFAULT; - } - - if (_angularDamping - shape->getAngularDumping() > 0) - { - _angularDamping -= shape->getAngularDumping(); - }else - { - _angularDamping = ANGULARDAMPING_DEFAULT; - _angularDampingDefault = true; - } - } + // deduce the area, mass and moment + // area must update before mass, because the density changes depend on it. + _area -= shape->getArea(); + addMass(-shape->getMass()); + addMoment(-shape->getMoment()); shape->release(); } diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 9bfd9ece3e..84507cfb00 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -172,21 +172,49 @@ public: /* * @brief set the body mass. + * @note if you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead. */ void setMass(float mass); /* * @brief get the body mass. */ inline float getMass() { return _mass; } + /* + * @brief add mass to body. + * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. + * if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY. + * if mass == -PHYSICS_INFINITY, _mass will not change. + * if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0) + * other wise, mass = mass + _mass; + */ + void addMass(float mass); + /* + * @brief set the body moment of inertia. + * @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead. + */ + void setMoment(float moment); + /* + * @brief get the body moment of inertia. + */ + inline float getMoment(float moment) { return _moment; } + /* + * @brief add moment of inertia to body. + * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. + * if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY. + * if moment == -PHYSICS_INFINITY, _moment will not change. + * if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0) + * other wise, moment = moment + _moment; + */ + void addMoment(float moment); /* * @brief set angular damping. */ - void setAngularDamping(float angularDamping); + //void setAngularDamping(float angularDamping); /* * @brief get angular damping. */ - inline float getAngularDamping() { return _angularDamping; } + //inline float getAngularDamping() { return _angularDamping; } //virtual Clonable* clone() const override; @@ -196,6 +224,7 @@ public: inline int getTag() { return _tag; } inline void setTag(int tag) { _tag = tag; } + protected: bool init(); @@ -216,11 +245,12 @@ protected: bool _dynamic; bool _enable; bool _massDefault; - bool _angularDampingDefault; + bool _momentDefault; float _mass; float _area; float _density; - float _angularDamping; + float _moment; + //float _angularDamping; int _tag; int _categoryBitmask; diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index b373e0710e..05bf303f91 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -48,7 +48,7 @@ PhysicsShape::PhysicsShape() , _type(Type::UNKNOWN) , _area(0) , _mass(0) -, _angularDamping(0) +, _moment(0) , _tag(0) , _enable(true) { @@ -234,7 +234,7 @@ bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = Materia _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); + _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); _info->add(shape); @@ -273,7 +273,7 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* CC_BREAK_IF(shape == nullptr); _mass = PHYSICS_INFINITY; - _angularDamping = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; _info->add(shape); @@ -311,7 +311,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(4, ((cpPolyShape*)shape)->verts)); _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); + _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); _info->add(shape); @@ -352,7 +352,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _angularDamping = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); + _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); _info->add(shape); @@ -401,7 +401,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD CC_BREAK_IF(i < 4); _mass = PHYSICS_INFINITY; - _angularDamping = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; initEnd(); @@ -450,7 +450,7 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat CC_BREAK_IF(i < count); _mass = PHYSICS_INFINITY; - _angularDamping = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; initEnd(); @@ -500,7 +500,7 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater CC_BREAK_IF(i < count); _mass = PHYSICS_INFINITY; - _angularDamping = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; initEnd(); diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index d754f6030b..688ccad2a6 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -79,8 +79,8 @@ public: inline PhysicsBody* getBody(){ return _body; } inline Type getType() { return _type; } inline float getArea() { return _area; } - inline float getAngularDumping() { return _angularDamping; } - void setAngularDumping(float angularDumping); + inline float getMoment() { return _moment; } + void setMoment(float moment); inline void setTag(int tag) { _tag = tag; } inline int getTag() { return _tag; } void setEnable(bool enable); @@ -115,7 +115,7 @@ protected: Type _type; float _area; float _mass; - float _angularDamping; + float _moment; PhysicsMaterial _material; int _tag; bool _enable; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 0ab5ba4ae4..91c67da54d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -311,9 +311,8 @@ Node* PhysicsDemoLogoSmash::makeBall(float x, float y) auto body = PhysicsBody::createCircle(0.95, PhysicsMaterial(1, 0, 0)); body->setMass(1.0); - body->setAngularDamping(PHYSICS_INFINITY); + body->setMoment(PHYSICS_INFINITY); - //body->setDynamic(false); ball->setPhysicsBody(body); ball->setPosition(Point(x, y)); From 95acb1b9e37b55214ed30a0586c47cd18e31f3d3 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 14 Oct 2013 14:01:00 +0800 Subject: [PATCH 130/557] issue #2905: helloworld build ok on android --- cocos/2d/Android.mk | 340 +++++++++--------- cocos/2d/CCAction.cpp | 2 +- cocos/2d/CCAction.h | 6 +- cocos/2d/CCActionCamera.cpp | 2 +- cocos/2d/CCActionCatmullRom.h | 4 +- cocos/2d/CCActionGrid.cpp | 2 +- cocos/2d/CCActionInstant.cpp | 6 +- cocos/2d/CCActionInterval.cpp | 4 +- cocos/2d/CCActionInterval.h | 6 +- cocos/2d/CCActionManager.cpp | 8 +- cocos/2d/CCActionManager.h | 4 +- cocos/2d/CCActionProgressTimer.cpp | 2 +- cocos/2d/CCActionTiledGrid.cpp | 2 +- cocos/2d/CCAnimation.cpp | 6 +- cocos/2d/CCAnimation.h | 10 +- cocos/2d/CCAnimationCache.cpp | 2 +- cocos/2d/CCAnimationCache.h | 4 +- cocos/2d/CCAtlasNode.cpp | 12 +- cocos/2d/CCCamera.cpp | 4 +- cocos/2d/CCCamera.h | 2 +- cocos/2d/CCClippingNode.cpp | 6 +- cocos/2d/CCClippingNode.h | 2 +- cocos/2d/CCComponent.cpp | 2 +- cocos/2d/CCComponent.h | 2 +- cocos/2d/CCComponentContainer.cpp | 4 +- cocos/2d/CCComponentContainer.h | 2 +- cocos/2d/CCConfiguration.cpp | 6 +- cocos/2d/CCConfiguration.h | 4 +- cocos/2d/CCDeprecated.h | 2 +- cocos/2d/CCDirector.cpp | 38 +- cocos/2d/CCDirector.h | 10 +- cocos/2d/CCDrawNode.cpp | 4 +- cocos/2d/CCDrawNode.h | 2 +- cocos/2d/CCDrawingPrimitives.cpp | 8 +- cocos/2d/CCDrawingPrimitives.h | 2 +- cocos/2d/CCEvent.h | 2 +- cocos/2d/CCEventDispatcher.cpp | 2 +- cocos/2d/CCEventDispatcher.h | 2 +- cocos/2d/CCEventListener.h | 4 +- cocos/2d/CCEventListenerTouch.h | 2 +- cocos/2d/CCEventTouch.h | 2 +- cocos/2d/CCFont.cpp | 2 +- cocos/2d/CCFontFreeType.cpp | 2 +- cocos/2d/CCGLProgram.cpp | 4 +- cocos/2d/CCGLProgram.h | 2 +- cocos/2d/CCGrabber.cpp | 2 +- cocos/2d/CCGrabber.h | 2 +- cocos/2d/CCGrid.cpp | 14 +- cocos/2d/CCGrid.h | 8 +- cocos/2d/CCIMEDelegate.h | 2 +- cocos/2d/CCLabel.h | 2 +- cocos/2d/CCLabelAtlas.cpp | 16 +- cocos/2d/CCLabelAtlas.h | 2 +- cocos/2d/CCLabelBMFont.cpp | 12 +- cocos/2d/CCLabelBMFont.h | 4 +- cocos/2d/CCLabelTTF.cpp | 4 +- cocos/2d/CCLabelTTF.h | 4 +- cocos/2d/CCLabelTextFormatter.cpp | 2 +- cocos/2d/CCLayer.cpp | 24 +- cocos/2d/CCLayer.h | 10 +- cocos/2d/CCMenu.cpp | 6 +- cocos/2d/CCMenu.h | 4 +- cocos/2d/CCMenuItem.cpp | 10 +- cocos/2d/CCMenuItem.h | 4 +- cocos/2d/CCMotionStreak.cpp | 10 +- cocos/2d/CCMotionStreak.h | 6 +- cocos/2d/CCNode.cpp | 28 +- cocos/2d/CCNode.h | 14 +- cocos/2d/CCNotificationCenter.cpp | 4 +- cocos/2d/CCNotificationCenter.h | 4 +- cocos/2d/CCParallaxNode.cpp | 2 +- cocos/2d/CCParallaxNode.h | 4 +- cocos/2d/CCParticleBatchNode.cpp | 18 +- cocos/2d/CCParticleBatchNode.h | 2 +- cocos/2d/CCParticleExamples.cpp | 2 +- cocos/2d/CCParticleSystem.cpp | 10 +- cocos/2d/CCParticleSystem.h | 6 +- cocos/2d/CCParticleSystemQuad.cpp | 14 +- cocos/2d/CCProfiling.h | 4 +- cocos/2d/CCProgressTimer.cpp | 12 +- cocos/2d/CCProgressTimer.h | 4 +- cocos/2d/CCProtocols.h | 2 +- cocos/2d/CCRenderTexture.cpp | 14 +- cocos/2d/CCRenderTexture.h | 4 +- cocos/2d/CCScene.cpp | 6 +- cocos/2d/CCScene.h | 4 +- cocos/2d/CCScheduler.cpp | 8 +- cocos/2d/CCScheduler.h | 4 +- cocos/2d/CCScriptSupport.h | 8 +- cocos/2d/CCShaderCache.h | 2 +- cocos/2d/CCSprite.cpp | 20 +- cocos/2d/CCSprite.h | 10 +- cocos/2d/CCSpriteBatchNode.cpp | 20 +- cocos/2d/CCSpriteBatchNode.h | 4 +- cocos/2d/CCSpriteFrame.cpp | 2 +- cocos/2d/CCSpriteFrame.h | 6 +- cocos/2d/CCSpriteFrameCache.cpp | 12 +- cocos/2d/CCSpriteFrameCache.h | 6 +- cocos/2d/CCTMXLayer.cpp | 10 +- cocos/2d/CCTMXLayer.h | 6 +- cocos/2d/CCTMXObjectGroup.h | 8 +- cocos/2d/CCTMXTiledMap.cpp | 2 +- cocos/2d/CCTMXTiledMap.h | 2 +- cocos/2d/CCTMXXMLParser.cpp | 4 +- cocos/2d/CCTMXXMLParser.h | 6 +- cocos/2d/CCTextFieldTTF.h | 4 +- cocos/2d/CCTexture2D.cpp | 10 +- cocos/2d/CCTexture2D.h | 6 +- cocos/2d/CCTextureAtlas.cpp | 8 +- cocos/2d/CCTextureAtlas.h | 2 +- cocos/2d/CCTextureCache.cpp | 4 +- cocos/2d/CCTextureCache.h | 4 +- cocos/2d/CCTileMapAtlas.cpp | 8 +- cocos/2d/CCTileMapAtlas.h | 2 +- cocos/2d/CCTouch.h | 4 +- cocos/2d/CCTransition.cpp | 14 +- cocos/2d/CCTransitionPageTurn.cpp | 8 +- cocos/2d/CCTransitionProgress.cpp | 8 +- cocos/2d/CCUserDefault.cpp | 4 +- cocos/2d/CCUserDefault.h | 4 +- cocos/2d/CCUserDefault.mm | 6 +- cocos/2d/CCUserDefaultAndroid.cpp | 4 +- cocos/2d/TransformUtils.cpp | 2 +- cocos/2d/ZipUtils.h | 2 +- cocos/2d/base64.cpp | 2 +- cocos/2d/ccCArray.cpp | 2 +- cocos/2d/ccCArray.h | 2 +- cocos/2d/ccConfig.h | 2 +- cocos/2d/ccGLStateCache.h | 2 +- cocos/2d/ccShaders.h | 2 +- cocos/2d/ccTypes.cpp | 2 +- cocos/2d/ccTypes.h | 2 +- cocos/2d/ccUTF8.h | 2 +- cocos/2d/cocos2d.h | 197 +++++----- cocos/2d/platform/CCEGLViewProtocol.cpp | 6 +- cocos/2d/platform/CCEGLViewProtocol.h | 2 +- cocos/2d/platform/CCFileUtils.cpp | 8 +- cocos/2d/platform/CCImage.h | 4 +- cocos/2d/platform/CCImageCommon_cpp.h | 19 +- cocos/2d/platform/CCSAXParser.cpp | 4 +- cocos/2d/platform/android/Android.mk | 14 +- cocos/2d/platform/android/CCEGLView.cpp | 2 +- cocos/2d/platform/android/CCEGLView.h | 2 +- .../2d/platform/android/CCFileUtilsAndroid.h | 2 +- cocos/2d/platform/android/CCImage.cpp | 2 +- cocos/2d/platform/android/CCStdC.h | 2 +- cocos/2d/platform/android/jni/IMEJni.cpp | 2 +- .../Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp | 2 +- .../Java_org_cocos2dx_lib_Cocos2dxHelper.cpp | 2 +- cocos/2d/platform/android/jni/JniHelper.h | 2 +- cocos/2d/platform/android/nativeactivity.cpp | 14 +- cocos/2d/platform/apple/CCFileUtilsApple.mm | 4 +- cocos/2d/platform/ios/CCDevice.mm | 4 +- cocos/2d/platform/ios/CCStdC.h | 2 +- cocos/2d/platform/linux/CCEGLView.cpp | 8 +- cocos/2d/platform/linux/CCEGLView.h | 2 +- cocos/2d/platform/linux/CCFileUtilsLinux.cpp | 2 +- cocos/2d/platform/linux/CCFileUtilsLinux.h | 2 +- cocos/2d/platform/linux/CCImage.cpp | 2 +- cocos/2d/platform/linux/CCStdC.h | 2 +- cocos/2d/platform/mac/CCEGLView.mm | 6 +- cocos/2d/platform/mac/CCEventDispatcher.mm | 2 +- cocos/2d/platform/mac/CCStdC.h | 2 +- cocos/2d/platform/win32/CCEGLView.cpp | 10 +- cocos/2d/platform/win32/CCEGLView.h | 2 +- cocos/2d/platform/win32/CCFileUtilsWin32.h | 2 +- cocos/2d/platform/win32/CCStdC.h | 2 +- cocos/audio/android/Android.mk | 9 +- cocos/base/{cocoa => }/CCAffineTransform.cpp | 0 cocos/base/{cocoa => }/CCAffineTransform.h | 2 +- cocos/base/{cocoa => }/CCArray.cpp | 0 cocos/base/{cocoa => }/CCArray.h | 4 +- cocos/base/{cocoa => }/CCAutoreleasePool.cpp | 0 cocos/base/{cocoa => }/CCAutoreleasePool.h | 0 cocos/base/{cocoa => }/CCBool.h | 0 cocos/base/{cocoa => }/CCData.cpp | 0 cocos/base/{cocoa => }/CCData.h | 2 +- cocos/base/{cocoa => }/CCDataVisitor.cpp | 0 cocos/base/{cocoa => }/CCDataVisitor.h | 2 +- cocos/base/{cocoa => }/CCDictionary.cpp | 0 cocos/base/{cocoa => }/CCDictionary.h | 2 +- cocos/base/{cocoa => }/CCDouble.h | 0 cocos/base/{cocoa => }/CCFloat.h | 0 cocos/base/{cocoa => }/CCGeometry.cpp | 0 cocos/base/{cocoa => }/CCGeometry.h | 2 +- cocos/base/{cocoa => }/CCInteger.h | 0 cocos/base/{cocoa => }/CCNS.cpp | 0 cocos/base/{cocoa => }/CCNS.h | 0 cocos/base/{cocoa => }/CCObject.cpp | 2 +- cocos/base/{cocoa => }/CCObject.h | 2 +- cocos/base/{cocoa => }/CCSet.cpp | 0 cocos/base/{cocoa => }/CCSet.h | 0 cocos/base/{cocoa => }/CCString.cpp | 0 cocos/base/{cocoa => }/CCString.h | 0 cocos/base/{atitc => }/atitc.cpp | 0 cocos/base/{atitc => }/atitc.h | 0 cocos/base/{etc1 => }/etc1.cpp | 0 cocos/base/{etc1 => }/etc1.h | 0 cocos/base/{s3tc => }/s3tc.cpp | 0 cocos/base/{s3tc => }/s3tc.h | 0 .../math/kazmath/include/kazmath/GL/matrix.h | 2 +- cocos/math/kazmath/include/kazmath/aabb.h | 2 +- cocos/math/kazmath/include/kazmath/mat3.h | 2 +- cocos/math/kazmath/include/kazmath/mat4.h | 2 +- cocos/math/kazmath/include/kazmath/plane.h | 2 +- .../math/kazmath/include/kazmath/quaternion.h | 2 +- cocos/math/kazmath/include/kazmath/ray2.h | 2 +- cocos/math/kazmath/include/kazmath/utility.h | 2 +- cocos/math/kazmath/include/kazmath/vec2.h | 2 +- cocos/math/kazmath/include/kazmath/vec3.h | 2 +- cocos/math/kazmath/include/kazmath/vec4.h | 2 +- cocos/physics/CCPhysicsBody.h | 4 +- cocos/physics/CCPhysicsContact.h | 4 +- cocos/physics/CCPhysicsJoint.h | 4 +- cocos/physics/CCPhysicsShape.h | 4 +- cocos/physics/CCPhysicsWorld.cpp | 6 +- cocos/physics/CCPhysicsWorld.h | 4 +- cocos/physics/box2d/CCPhysicsBodyInfo.h | 2 +- cocos/physics/box2d/CCPhysicsContactInfo.h | 2 +- cocos/physics/box2d/CCPhysicsHelper.h | 4 +- cocos/physics/box2d/CCPhysicsJointInfo.h | 2 +- cocos/physics/box2d/CCPhysicsShapeInfo.h | 2 +- cocos/physics/box2d/CCPhysicsWorldInfo.h | 2 +- cocos/physics/chipmunk/CCPhysicsBodyInfo.h | 4 +- cocos/physics/chipmunk/CCPhysicsContactInfo.h | 2 +- cocos/physics/chipmunk/CCPhysicsHelper.h | 4 +- cocos/physics/chipmunk/CCPhysicsJointInfo.h | 2 +- cocos/physics/chipmunk/CCPhysicsShapeInfo.h | 2 +- cocos/physics/chipmunk/CCPhysicsWorldInfo.h | 2 +- extensions/Android.mk | 157 ++------ external/Box2D/Android.mk | 90 ++--- external/chipmunk/Android.mk | 58 +-- .../curl/include/{andorid => android}/curl.h | 0 .../include/{andorid => android}/curlbuild.h | 0 .../include/{andorid => android}/curlrules.h | 0 .../include/{andorid => android}/curlver.h | 0 .../curl/include/{andorid => android}/easy.h | 0 .../include/{andorid => android}/mprintf.h | 0 .../curl/include/{andorid => android}/multi.h | 0 .../{andorid => android}/stdcheaders.h | 0 .../{andorid => android}/typecheck-gcc.h | 0 .../curl/include/{andorid => android}/types.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libcurl.a.REMOVED.git-id | 0 .../armeabi/libcurl.a.REMOVED.git-id | 0 .../x86/libcurl.a.REMOVED.git-id | 0 .../freetype2/freetype/config/ftconfig.h | 0 .../freetype2/freetype/config/ftheader.h | 0 .../freetype2/freetype/config/ftmodule.h | 0 .../freetype2/freetype/config/ftoption.h | 0 .../freetype2/freetype/config/ftstdlib.h | 0 .../freetype/freetype.h.REMOVED.git-id | 0 .../freetype2/freetype/ftadvanc.h | 0 .../freetype2/freetype/ftautoh.h | 0 .../freetype2/freetype/ftbbox.h | 0 .../freetype2/freetype/ftbdf.h | 0 .../freetype2/freetype/ftbitmap.h | 0 .../freetype2/freetype/ftbzip2.h | 0 .../freetype2/freetype/ftcache.h | 0 .../freetype2/freetype/ftcffdrv.h | 0 .../freetype2/freetype/ftchapters.h | 0 .../freetype2/freetype/ftcid.h | 0 .../freetype2/freetype/fterrdef.h | 0 .../freetype2/freetype/fterrors.h | 0 .../freetype2/freetype/ftgasp.h | 0 .../freetype2/freetype/ftglyph.h | 0 .../freetype2/freetype/ftgxval.h | 0 .../freetype2/freetype/ftgzip.h | 0 .../freetype2/freetype/ftimage.h | 0 .../freetype2/freetype/ftincrem.h | 0 .../freetype2/freetype/ftlcdfil.h | 0 .../freetype2/freetype/ftlist.h | 0 .../freetype2/freetype/ftlzw.h | 0 .../freetype2/freetype/ftmac.h | 0 .../freetype2/freetype/ftmm.h | 0 .../freetype2/freetype/ftmodapi.h | 0 .../freetype2/freetype/ftmoderr.h | 0 .../freetype2/freetype/ftotval.h | 0 .../freetype2/freetype/ftoutln.h | 0 .../freetype2/freetype/ftpfr.h | 0 .../freetype2/freetype/ftrender.h | 0 .../freetype2/freetype/ftsizes.h | 0 .../freetype2/freetype/ftsnames.h | 0 .../freetype2/freetype/ftstroke.h | 0 .../freetype2/freetype/ftsynth.h | 0 .../freetype2/freetype/ftsystem.h | 0 .../freetype2/freetype/fttrigon.h | 0 .../freetype2/freetype/ftttdrv.h | 0 .../freetype2/freetype/fttypes.h | 0 .../freetype2/freetype/ftwinfnt.h | 0 .../freetype2/freetype/ftxf86.h | 0 .../freetype2/freetype/t1tables.h | 0 .../freetype2/freetype/ttnameid.h | 0 .../freetype2/freetype/tttables.h | 0 .../freetype2/freetype/tttags.h | 0 .../freetype2/freetype/ttunpat.h | 0 .../include/{andorid => android}/ft2build.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libfreetype.a.REMOVED.git-id | 0 .../armeabi/libfreetype.a.REMOVED.git-id | 0 .../x86/libfreetype.a.REMOVED.git-id | 0 .../include/{andorid => android}/jconfig.h | 0 .../include/{andorid => android}/jerror.h | 0 .../include/{andorid => android}/jmorecfg.h | 0 .../include/{andorid => android}/jpeglib.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libjpeg.a.REMOVED.git-id | 0 .../armeabi/libjpeg.a.REMOVED.git-id | 0 .../x86/libjpeg.a.REMOVED.git-id | 0 .../{andorid => android}/png.h.REMOVED.git-id | 0 .../include/{andorid => android}/pngconf.h | 0 .../include/{andorid => android}/pnglibconf.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libpng.a.REMOVED.git-id | 0 .../armeabi/libpng.a.REMOVED.git-id | 0 .../x86/libpng.a.REMOVED.git-id | 0 .../include/{andorid => android}/js-config.h | 0 .../include/{andorid => android}/js.msg | 0 .../include/{andorid => android}/js/Anchor.h | 0 .../{andorid => android}/js/CallArgs.h | 0 .../js/CharacterEncoding.h | 0 .../include/{andorid => android}/js/Date.h | 0 .../include/{andorid => android}/js/GCAPI.h | 0 .../{andorid => android}/js/HashTable.h | 0 .../include/{andorid => android}/js/HeapAPI.h | 0 .../{andorid => android}/js/LegacyIntTypes.h | 0 .../{andorid => android}/js/MemoryMetrics.h | 0 .../{andorid => android}/js/PropertyKey.h | 0 .../{andorid => android}/js/RequiredDefines.h | 0 .../{andorid => android}/js/RootingAPI.h | 0 .../{andorid => android}/js/TemplateLib.h | 0 .../include/{andorid => android}/js/Utility.h | 0 .../include/{andorid => android}/js/Value.h | 0 .../include/{andorid => android}/js/Vector.h | 0 .../include/{andorid => android}/jsalloc.h | 0 .../jsapi.h.REMOVED.git-id | 0 .../include/{andorid => android}/jsclass.h | 0 .../include/{andorid => android}/jsclist.h | 0 .../include/{andorid => android}/jscpucfg.h | 0 .../include/{andorid => android}/jsdbgapi.h | 0 .../include/{andorid => android}/jsdhash.h | 0 .../{andorid => android}/jsfriendapi.h | 0 .../include/{andorid => android}/jslock.h | 0 .../include/{andorid => android}/json.h | 0 .../include/{andorid => android}/jsperf.h | 0 .../include/{andorid => android}/jsprf.h | 0 .../{andorid => android}/jsprototypes.h | 0 .../include/{andorid => android}/jsproxy.h | 0 .../include/{andorid => android}/jsprvtd.h | 0 .../include/{andorid => android}/jspubtd.h | 0 .../include/{andorid => android}/jstypes.h | 0 .../include/{andorid => android}/jsutil.h | 0 .../include/{andorid => android}/jsversion.h | 0 .../include/{andorid => android}/jswrapper.h | 0 .../{andorid => android}/mozilla/Assertions.h | 0 .../{andorid => android}/mozilla/Attributes.h | 0 .../mozilla/BloomFilter.h | 0 .../{andorid => android}/mozilla/Casting.h | 0 .../{andorid => android}/mozilla/Char16.h | 0 .../{andorid => android}/mozilla/CheckedInt.h | 0 .../{andorid => android}/mozilla/Compiler.h | 0 .../{andorid => android}/mozilla/Constants.h | 0 .../{andorid => android}/mozilla/DebugOnly.h | 0 .../{andorid => android}/mozilla/Decimal.h | 0 .../{andorid => android}/mozilla/Endian.h | 0 .../{andorid => android}/mozilla/EnumSet.h | 0 .../mozilla/FloatingPoint.h | 0 .../mozilla/GuardObjects.h | 0 .../mozilla/HashFunctions.h | 0 .../{andorid => android}/mozilla/Likely.h | 0 .../{andorid => android}/mozilla/LinkedList.h | 0 .../{andorid => android}/mozilla/MSStdInt.h | 0 .../mozilla/MathAlgorithms.h | 0 .../mozilla/MemoryChecking.h | 0 .../{andorid => android}/mozilla/NullPtr.h | 0 .../mozilla/PodOperations.h | 0 .../{andorid => android}/mozilla/Poison.h | 0 .../{andorid => android}/mozilla/Range.h | 0 .../{andorid => android}/mozilla/RangedPtr.h | 0 .../{andorid => android}/mozilla/RefPtr.h | 0 .../{andorid => android}/mozilla/SHA1.h | 0 .../{andorid => android}/mozilla/Scoped.h | 0 .../{andorid => android}/mozilla/SplayTree.h | 0 .../mozilla/StandardInteger.h | 0 .../mozilla/ThreadLocal.h | 0 .../{andorid => android}/mozilla/TypeTraits.h | 0 .../{andorid => android}/mozilla/TypedEnum.h | 0 .../{andorid => android}/mozilla/Types.h | 0 .../{andorid => android}/mozilla/Util.h | 0 .../{andorid => android}/mozilla/WeakPtr.h | 0 .../prebuilt/{andorid => android}/Android.mk | 0 .../armeabi-v7a/libjs_static.a.REMOVED.git-id | 0 .../armeabi/libjs_static.a.REMOVED.git-id | 0 .../x86/libjs_static.a.REMOVED.git-id | 0 .../tiff/include/{andorid => android}/tiff.h | 0 .../include/{andorid => android}/tiffconf.h | 0 .../include/{andorid => android}/tiffio.h | 0 .../include/{andorid => android}/tiffvers.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libtiff.a.REMOVED.git-id | 0 .../armeabi/libtiff.a.REMOVED.git-id | 0 .../x86/libtiff.a.REMOVED.git-id | 0 external/tinyxml2/tinyxml2.h | 4 +- external/unzip/ioapi.h | 2 +- .../include/{andorid => android}/decode.h | 0 .../include/{andorid => android}/encode.h | 0 .../webp/include/{andorid => android}/types.h | 0 .../prebuilt/{andorid => android}/Android.mk | 4 +- .../armeabi-v7a/libwebp.a.REMOVED.git-id | 0 .../armeabi/libwebp.a.REMOVED.git-id | 0 .../x86/libwebp.a.REMOVED.git-id | 0 .../Cpp/HelloCpp/Classes/HelloWorldScene.cpp | 2 +- .../Cpp/HelloCpp/proj.android/build_native.sh | 5 +- .../Cpp/HelloCpp/proj.android/jni/Android.mk | 5 +- samples/Cpp/TestCpp/Android.mk | 262 +++++++------- .../android_mk_generator.py | 2 +- tools/android-mk-generator/config.py | 6 +- 417 files changed, 1035 insertions(+), 1141 deletions(-) rename cocos/base/{cocoa => }/CCAffineTransform.cpp (100%) rename cocos/base/{cocoa => }/CCAffineTransform.h (98%) rename cocos/base/{cocoa => }/CCArray.cpp (100%) rename cocos/base/{cocoa => }/CCArray.h (99%) rename cocos/base/{cocoa => }/CCAutoreleasePool.cpp (100%) rename cocos/base/{cocoa => }/CCAutoreleasePool.h (100%) rename cocos/base/{cocoa => }/CCBool.h (100%) rename cocos/base/{cocoa => }/CCData.cpp (100%) rename cocos/base/{cocoa => }/CCData.h (98%) rename cocos/base/{cocoa => }/CCDataVisitor.cpp (100%) rename cocos/base/{cocoa => }/CCDataVisitor.h (98%) rename cocos/base/{cocoa => }/CCDictionary.cpp (100%) rename cocos/base/{cocoa => }/CCDictionary.h (99%) rename cocos/base/{cocoa => }/CCDouble.h (100%) rename cocos/base/{cocoa => }/CCFloat.h (100%) rename cocos/base/{cocoa => }/CCGeometry.cpp (100%) rename cocos/base/{cocoa => }/CCGeometry.h (99%) rename cocos/base/{cocoa => }/CCInteger.h (100%) rename cocos/base/{cocoa => }/CCNS.cpp (100%) rename cocos/base/{cocoa => }/CCNS.h (100%) rename cocos/base/{cocoa => }/CCObject.cpp (98%) rename cocos/base/{cocoa => }/CCObject.h (99%) rename cocos/base/{cocoa => }/CCSet.cpp (100%) rename cocos/base/{cocoa => }/CCSet.h (100%) rename cocos/base/{cocoa => }/CCString.cpp (100%) rename cocos/base/{cocoa => }/CCString.h (100%) rename cocos/base/{atitc => }/atitc.cpp (100%) rename cocos/base/{atitc => }/atitc.h (100%) rename cocos/base/{etc1 => }/etc1.cpp (100%) rename cocos/base/{etc1 => }/etc1.h (100%) rename cocos/base/{s3tc => }/s3tc.cpp (100%) rename cocos/base/{s3tc => }/s3tc.h (100%) rename external/curl/include/{andorid => android}/curl.h (100%) rename external/curl/include/{andorid => android}/curlbuild.h (100%) rename external/curl/include/{andorid => android}/curlrules.h (100%) rename external/curl/include/{andorid => android}/curlver.h (100%) rename external/curl/include/{andorid => android}/easy.h (100%) rename external/curl/include/{andorid => android}/mprintf.h (100%) rename external/curl/include/{andorid => android}/multi.h (100%) rename external/curl/include/{andorid => android}/stdcheaders.h (100%) rename external/curl/include/{andorid => android}/typecheck-gcc.h (100%) rename external/curl/include/{andorid => android}/types.h (100%) rename external/curl/prebuilt/{andorid => android}/Android.mk (57%) rename external/curl/prebuilt/{andorid => android}/armeabi-v7a/libcurl.a.REMOVED.git-id (100%) rename external/curl/prebuilt/{andorid => android}/armeabi/libcurl.a.REMOVED.git-id (100%) rename external/curl/prebuilt/{andorid => android}/x86/libcurl.a.REMOVED.git-id (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/config/ftconfig.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/config/ftheader.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/config/ftmodule.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/config/ftoption.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/config/ftstdlib.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/freetype.h.REMOVED.git-id (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftadvanc.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftautoh.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftbbox.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftbdf.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftbitmap.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftbzip2.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftcache.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftcffdrv.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftchapters.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftcid.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/fterrdef.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/fterrors.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftgasp.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftglyph.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftgxval.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftgzip.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftimage.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftincrem.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftlcdfil.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftlist.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftlzw.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftmac.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftmm.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftmodapi.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftmoderr.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftotval.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftoutln.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftpfr.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftrender.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftsizes.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftsnames.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftstroke.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftsynth.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftsystem.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/fttrigon.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftttdrv.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/fttypes.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftwinfnt.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ftxf86.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/t1tables.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ttnameid.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/tttables.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/tttags.h (100%) rename external/freetype2/include/{andorid => android}/freetype2/freetype/ttunpat.h (100%) rename external/freetype2/include/{andorid => android}/ft2build.h (100%) rename external/freetype2/prebuilt/{andorid => android}/Android.mk (50%) rename external/freetype2/prebuilt/{andorid => android}/armeabi-v7a/libfreetype.a.REMOVED.git-id (100%) rename external/freetype2/prebuilt/{andorid => android}/armeabi/libfreetype.a.REMOVED.git-id (100%) rename external/freetype2/prebuilt/{andorid => android}/x86/libfreetype.a.REMOVED.git-id (100%) rename external/jpeg/include/{andorid => android}/jconfig.h (100%) rename external/jpeg/include/{andorid => android}/jerror.h (100%) rename external/jpeg/include/{andorid => android}/jmorecfg.h (100%) rename external/jpeg/include/{andorid => android}/jpeglib.h (100%) rename external/jpeg/prebuilt/{andorid => android}/Android.mk (57%) rename external/jpeg/prebuilt/{andorid => android}/armeabi-v7a/libjpeg.a.REMOVED.git-id (100%) rename external/jpeg/prebuilt/{andorid => android}/armeabi/libjpeg.a.REMOVED.git-id (100%) rename external/jpeg/prebuilt/{andorid => android}/x86/libjpeg.a.REMOVED.git-id (100%) rename external/png/include/{andorid => android}/png.h.REMOVED.git-id (100%) rename external/png/include/{andorid => android}/pngconf.h (100%) rename external/png/include/{andorid => android}/pnglibconf.h (100%) rename external/png/prebuilt/{andorid => android}/Android.mk (58%) rename external/png/prebuilt/{andorid => android}/armeabi-v7a/libpng.a.REMOVED.git-id (100%) rename external/png/prebuilt/{andorid => android}/armeabi/libpng.a.REMOVED.git-id (100%) rename external/png/prebuilt/{andorid => android}/x86/libpng.a.REMOVED.git-id (100%) rename external/spidermonkey/include/{andorid => android}/js-config.h (100%) rename external/spidermonkey/include/{andorid => android}/js.msg (100%) rename external/spidermonkey/include/{andorid => android}/js/Anchor.h (100%) rename external/spidermonkey/include/{andorid => android}/js/CallArgs.h (100%) rename external/spidermonkey/include/{andorid => android}/js/CharacterEncoding.h (100%) rename external/spidermonkey/include/{andorid => android}/js/Date.h (100%) rename external/spidermonkey/include/{andorid => android}/js/GCAPI.h (100%) rename external/spidermonkey/include/{andorid => android}/js/HashTable.h (100%) rename external/spidermonkey/include/{andorid => android}/js/HeapAPI.h (100%) rename external/spidermonkey/include/{andorid => android}/js/LegacyIntTypes.h (100%) rename external/spidermonkey/include/{andorid => android}/js/MemoryMetrics.h (100%) rename external/spidermonkey/include/{andorid => android}/js/PropertyKey.h (100%) rename external/spidermonkey/include/{andorid => android}/js/RequiredDefines.h (100%) rename external/spidermonkey/include/{andorid => android}/js/RootingAPI.h (100%) rename external/spidermonkey/include/{andorid => android}/js/TemplateLib.h (100%) rename external/spidermonkey/include/{andorid => android}/js/Utility.h (100%) rename external/spidermonkey/include/{andorid => android}/js/Value.h (100%) rename external/spidermonkey/include/{andorid => android}/js/Vector.h (100%) rename external/spidermonkey/include/{andorid => android}/jsalloc.h (100%) rename external/spidermonkey/include/{andorid => android}/jsapi.h.REMOVED.git-id (100%) rename external/spidermonkey/include/{andorid => android}/jsclass.h (100%) rename external/spidermonkey/include/{andorid => android}/jsclist.h (100%) rename external/spidermonkey/include/{andorid => android}/jscpucfg.h (100%) rename external/spidermonkey/include/{andorid => android}/jsdbgapi.h (100%) rename external/spidermonkey/include/{andorid => android}/jsdhash.h (100%) rename external/spidermonkey/include/{andorid => android}/jsfriendapi.h (100%) rename external/spidermonkey/include/{andorid => android}/jslock.h (100%) rename external/spidermonkey/include/{andorid => android}/json.h (100%) rename external/spidermonkey/include/{andorid => android}/jsperf.h (100%) rename external/spidermonkey/include/{andorid => android}/jsprf.h (100%) rename external/spidermonkey/include/{andorid => android}/jsprototypes.h (100%) rename external/spidermonkey/include/{andorid => android}/jsproxy.h (100%) rename external/spidermonkey/include/{andorid => android}/jsprvtd.h (100%) rename external/spidermonkey/include/{andorid => android}/jspubtd.h (100%) rename external/spidermonkey/include/{andorid => android}/jstypes.h (100%) rename external/spidermonkey/include/{andorid => android}/jsutil.h (100%) rename external/spidermonkey/include/{andorid => android}/jsversion.h (100%) rename external/spidermonkey/include/{andorid => android}/jswrapper.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Assertions.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Attributes.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/BloomFilter.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Casting.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Char16.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/CheckedInt.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Compiler.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Constants.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/DebugOnly.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Decimal.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Endian.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/EnumSet.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/FloatingPoint.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/GuardObjects.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/HashFunctions.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Likely.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/LinkedList.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/MSStdInt.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/MathAlgorithms.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/MemoryChecking.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/NullPtr.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/PodOperations.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Poison.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Range.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/RangedPtr.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/RefPtr.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/SHA1.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Scoped.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/SplayTree.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/StandardInteger.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/ThreadLocal.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/TypeTraits.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/TypedEnum.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Types.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/Util.h (100%) rename external/spidermonkey/include/{andorid => android}/mozilla/WeakPtr.h (100%) rename external/spidermonkey/prebuilt/{andorid => android}/Android.mk (100%) rename external/spidermonkey/prebuilt/{andorid => android}/armeabi-v7a/libjs_static.a.REMOVED.git-id (100%) rename external/spidermonkey/prebuilt/{andorid => android}/armeabi/libjs_static.a.REMOVED.git-id (100%) rename external/spidermonkey/prebuilt/{andorid => android}/x86/libjs_static.a.REMOVED.git-id (100%) rename external/tiff/include/{andorid => android}/tiff.h (100%) rename external/tiff/include/{andorid => android}/tiffconf.h (100%) rename external/tiff/include/{andorid => android}/tiffio.h (100%) rename external/tiff/include/{andorid => android}/tiffvers.h (100%) rename external/tiff/prebuilt/{andorid => android}/Android.mk (58%) rename external/tiff/prebuilt/{andorid => android}/armeabi-v7a/libtiff.a.REMOVED.git-id (100%) rename external/tiff/prebuilt/{andorid => android}/armeabi/libtiff.a.REMOVED.git-id (100%) rename external/tiff/prebuilt/{andorid => android}/x86/libtiff.a.REMOVED.git-id (100%) rename external/webp/include/{andorid => android}/decode.h (100%) rename external/webp/include/{andorid => android}/encode.h (100%) rename external/webp/include/{andorid => android}/types.h (100%) rename external/webp/prebuilt/{andorid => android}/Android.mk (74%) rename external/webp/prebuilt/{andorid => android}/armeabi-v7a/libwebp.a.REMOVED.git-id (100%) rename external/webp/prebuilt/{andorid => android}/armeabi/libwebp.a.REMOVED.git-id (100%) rename external/webp/prebuilt/{andorid => android}/x86/libwebp.a.REMOVED.git-id (100%) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 6caa61be36..74c8b0313f 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -7,176 +7,180 @@ LOCAL_MODULE := cocos2dx_static LOCAL_MODULE_FILENAME := libcocos2d LOCAL_SRC_FILES := \ -CCCamera.cpp \ -CCConfiguration.cpp \ -CCDeprecated.cpp \ -CCDirector.cpp \ -ccFPSImages.c \ -CCScheduler.cpp \ -ccTypes.cpp \ -cocos2d.cpp \ -actions/CCAction.cpp \ -actions/CCActionCamera.cpp \ -actions/CCActionCatmullRom.cpp \ -actions/CCActionEase.cpp \ -actions/CCActionGrid.cpp \ -actions/CCActionGrid3D.cpp \ -actions/CCActionInstant.cpp \ -actions/CCActionInterval.cpp \ -actions/CCActionManager.cpp \ -actions/CCActionPageTurn3D.cpp \ -actions/CCActionProgressTimer.cpp \ -actions/CCActionTiledGrid.cpp \ -actions/CCActionTween.cpp \ -base_nodes/CCAtlasNode.cpp \ -base_nodes/CCNode.cpp \ -cocoa/CCAffineTransform.cpp \ -cocoa/CCArray.cpp \ -cocoa/CCAutoreleasePool.cpp \ -cocoa/CCData.cpp \ -cocoa/CCDataVisitor.cpp \ -cocoa/CCDictionary.cpp \ -cocoa/CCGeometry.cpp \ -cocoa/CCNS.cpp \ -cocoa/CCObject.cpp \ -cocoa/CCSet.cpp \ -cocoa/CCString.cpp \ -draw_nodes/CCDrawingPrimitives.cpp \ -draw_nodes/CCDrawNode.cpp \ -effects/CCGrabber.cpp \ -effects/CCGrid.cpp \ -event_dispatcher/CCEventAcceleration.cpp \ -event_dispatcher/CCEventListenerAcceleration.cpp \ -event_dispatcher/CCEventCustom.cpp \ -event_dispatcher/CCEventListenerCustom.cpp \ -event_dispatcher/CCEvent.cpp \ -event_dispatcher/CCEventDispatcher.cpp \ -event_dispatcher/CCEventListener.cpp \ -event_dispatcher/CCEventKeyboard.cpp \ -event_dispatcher/CCEventListenerKeyboard.cpp \ -event_dispatcher/CCTouch.cpp \ -event_dispatcher/CCEventTouch.cpp \ -event_dispatcher/CCEventListenerTouch.cpp \ -kazmath/src/aabb.c \ -kazmath/src/mat3.c \ -kazmath/src/mat4.c \ -kazmath/src/neon_matrix_impl.c \ -kazmath/src/plane.c \ -kazmath/src/quaternion.c \ -kazmath/src/ray2.c \ -kazmath/src/utility.c \ -kazmath/src/vec2.c \ -kazmath/src/vec3.c \ -kazmath/src/vec4.c \ -kazmath/src/GL/mat4stack.c \ -kazmath/src/GL/matrix.c \ -label_nodes/CCFont.cpp \ -label_nodes/CCFontAtlas.cpp \ -label_nodes/CCFontAtlasCache.cpp \ -label_nodes/CCFontAtlasFactory.cpp \ -label_nodes/CCFontDefinition.cpp \ -label_nodes/CCFontFNT.cpp \ -label_nodes/CCFontFreeType.cpp \ -label_nodes/CCLabel.cpp \ -label_nodes/CCLabelAtlas.cpp \ -label_nodes/CCLabelBMFont.cpp \ -label_nodes/CCLabelTextFormatter.cpp \ -label_nodes/CCLabelTTF.cpp \ -label_nodes/CCTextImage.cpp \ -layers_scenes_transitions_nodes/CCLayer.cpp \ -layers_scenes_transitions_nodes/CCScene.cpp \ -layers_scenes_transitions_nodes/CCTransition.cpp \ -layers_scenes_transitions_nodes/CCTransitionPageTurn.cpp \ -layers_scenes_transitions_nodes/CCTransitionProgress.cpp \ -menu_nodes/CCMenu.cpp \ -menu_nodes/CCMenuItem.cpp \ -misc_nodes/CCClippingNode.cpp \ -misc_nodes/CCMotionStreak.cpp \ -misc_nodes/CCProgressTimer.cpp \ -misc_nodes/CCRenderTexture.cpp \ -particle_nodes/CCParticleBatchNode.cpp \ -particle_nodes/CCParticleExamples.cpp \ -particle_nodes/CCParticleSystem.cpp \ -particle_nodes/CCParticleSystemQuad.cpp \ -physics/CCPhysicsBody.cpp \ -physics/CCPhysicsContact.cpp \ -physics/CCPhysicsJoint.cpp \ -physics/CCPhysicsShape.cpp \ -physics/CCPhysicsWorld.cpp \ -physics/Box2D/CCPhysicsBodyInfo.cpp \ -physics/Box2D/CCPhysicsContactInfo.cpp \ -physics/Box2D/CCPhysicsJointInfo.cpp \ -physics/Box2D/CCPhysicsShapeInfo.cpp \ -physics/Box2D/CCPhysicsWorldInfo.cpp \ -physics/chipmunk/CCPhysicsBodyInfo.cpp \ -physics/chipmunk/CCPhysicsContactInfo.cpp \ -physics/chipmunk/CCPhysicsJointInfo.cpp \ -physics/chipmunk/CCPhysicsShapeInfo.cpp \ -physics/chipmunk/CCPhysicsWorldInfo.cpp \ -platform/CCEGLViewProtocol.cpp \ -platform/CCFileUtils.cpp \ -platform/CCSAXParser.cpp \ -platform/CCThread.cpp \ -platform/third_party/common/atitc/atitc.cpp \ -platform/third_party/common/etc/etc1.cpp \ -platform/third_party/common/s3tc/s3tc.cpp \ -script_support/CCScriptSupport.cpp \ -shaders/CCGLProgram.cpp \ -shaders/ccGLStateCache.cpp \ -shaders/CCShaderCache.cpp \ -shaders/ccShaders.cpp \ -sprite_nodes/CCAnimation.cpp \ -sprite_nodes/CCAnimationCache.cpp \ -sprite_nodes/CCSprite.cpp \ -sprite_nodes/CCSpriteBatchNode.cpp \ -sprite_nodes/CCSpriteFrame.cpp \ -sprite_nodes/CCSpriteFrameCache.cpp \ -support/base64.cpp \ -support/CCNotificationCenter.cpp \ -support/CCProfiling.cpp \ -support/ccUTF8.cpp \ -support/ccUtils.cpp \ -support/CCVertex.cpp \ -support/TransformUtils.cpp \ -support/component/CCComponent.cpp \ -support/component/CCComponentContainer.cpp \ -support/data_support/ccCArray.cpp \ -support/image_support/TGAlib.cpp \ -support/tinyxml2/tinyxml2.cpp \ -support/user_default/CCUserDefaultAndroid.cpp \ -support/zip_support/ioapi.cpp \ -support/zip_support/unzip.cpp \ -support/zip_support/ZipUtils.cpp \ -text_input_node/CCIMEDispatcher.cpp \ -text_input_node/CCTextFieldTTF.cpp \ -textures/CCTexture2D.cpp \ -textures/CCTextureAtlas.cpp \ -textures/CCTextureCache.cpp \ -tilemap_parallax_nodes/CCParallaxNode.cpp \ -tilemap_parallax_nodes/CCTileMapAtlas.cpp \ -tilemap_parallax_nodes/CCTMXLayer.cpp \ -tilemap_parallax_nodes/CCTMXObjectGroup.cpp \ -tilemap_parallax_nodes/CCTMXTiledMap.cpp \ -tilemap_parallax_nodes/CCTMXXMLParser.cpp +$(LOCAL_PATH)/base64.cpp \ +$(LOCAL_PATH)/CCAction.cpp \ +$(LOCAL_PATH)/CCActionCamera.cpp \ +$(LOCAL_PATH)/CCActionCatmullRom.cpp \ +$(LOCAL_PATH)/CCActionEase.cpp \ +$(LOCAL_PATH)/CCActionGrid.cpp \ +$(LOCAL_PATH)/CCActionGrid3D.cpp \ +$(LOCAL_PATH)/CCActionInstant.cpp \ +$(LOCAL_PATH)/CCActionInterval.cpp \ +$(LOCAL_PATH)/CCActionManager.cpp \ +$(LOCAL_PATH)/CCActionPageTurn3D.cpp \ +$(LOCAL_PATH)/CCActionProgressTimer.cpp \ +$(LOCAL_PATH)/CCActionTiledGrid.cpp \ +$(LOCAL_PATH)/CCActionTween.cpp \ +$(LOCAL_PATH)/CCAnimation.cpp \ +$(LOCAL_PATH)/CCAnimationCache.cpp \ +$(LOCAL_PATH)/CCAtlasNode.cpp \ +$(LOCAL_PATH)/CCCamera.cpp \ +$(LOCAL_PATH)/ccCArray.cpp \ +$(LOCAL_PATH)/CCClippingNode.cpp \ +$(LOCAL_PATH)/CCComponent.cpp \ +$(LOCAL_PATH)/CCComponentContainer.cpp \ +$(LOCAL_PATH)/CCConfiguration.cpp \ +$(LOCAL_PATH)/CCDeprecated.cpp \ +$(LOCAL_PATH)/CCDirector.cpp \ +$(LOCAL_PATH)/CCDrawingPrimitives.cpp \ +$(LOCAL_PATH)/CCDrawNode.cpp \ +$(LOCAL_PATH)/CCEvent.cpp \ +$(LOCAL_PATH)/CCEventAcceleration.cpp \ +$(LOCAL_PATH)/CCEventCustom.cpp \ +$(LOCAL_PATH)/CCEventDispatcher.cpp \ +$(LOCAL_PATH)/CCEventKeyboard.cpp \ +$(LOCAL_PATH)/CCEventListener.cpp \ +$(LOCAL_PATH)/CCEventListenerAcceleration.cpp \ +$(LOCAL_PATH)/CCEventListenerCustom.cpp \ +$(LOCAL_PATH)/CCEventListenerKeyboard.cpp \ +$(LOCAL_PATH)/CCEventListenerTouch.cpp \ +$(LOCAL_PATH)/CCEventTouch.cpp \ +$(LOCAL_PATH)/CCFont.cpp \ +$(LOCAL_PATH)/CCFontAtlas.cpp \ +$(LOCAL_PATH)/CCFontAtlasCache.cpp \ +$(LOCAL_PATH)/CCFontAtlasFactory.cpp \ +$(LOCAL_PATH)/CCFontDefinition.cpp \ +$(LOCAL_PATH)/CCFontFNT.cpp \ +$(LOCAL_PATH)/CCFontFreeType.cpp \ +$(LOCAL_PATH)/ccFPSImages.c \ +$(LOCAL_PATH)/CCGLBufferedNode.cpp \ +$(LOCAL_PATH)/CCGLProgram.cpp \ +$(LOCAL_PATH)/ccGLStateCache.cpp \ +$(LOCAL_PATH)/CCGrabber.cpp \ +$(LOCAL_PATH)/CCGrid.cpp \ +$(LOCAL_PATH)/CCIMEDispatcher.cpp \ +$(LOCAL_PATH)/CCLabel.cpp \ +$(LOCAL_PATH)/CCLabelAtlas.cpp \ +$(LOCAL_PATH)/CCLabelBMFont.cpp \ +$(LOCAL_PATH)/CCLabelTextFormatter.cpp \ +$(LOCAL_PATH)/CCLabelTTF.cpp \ +$(LOCAL_PATH)/CCLayer.cpp \ +$(LOCAL_PATH)/CCMenu.cpp \ +$(LOCAL_PATH)/CCMenuItem.cpp \ +$(LOCAL_PATH)/CCMotionStreak.cpp \ +$(LOCAL_PATH)/CCNode.cpp \ +$(LOCAL_PATH)/CCNotificationCenter.cpp \ +$(LOCAL_PATH)/CCParallaxNode.cpp \ +$(LOCAL_PATH)/CCParticleBatchNode.cpp \ +$(LOCAL_PATH)/CCParticleExamples.cpp \ +$(LOCAL_PATH)/CCParticleSystem.cpp \ +$(LOCAL_PATH)/CCParticleSystemQuad.cpp \ +$(LOCAL_PATH)/CCProfiling.cpp \ +$(LOCAL_PATH)/CCProgressTimer.cpp \ +$(LOCAL_PATH)/CCRenderTexture.cpp \ +$(LOCAL_PATH)/CCScene.cpp \ +$(LOCAL_PATH)/CCScheduler.cpp \ +$(LOCAL_PATH)/CCScriptSupport.cpp \ +$(LOCAL_PATH)/CCShaderCache.cpp \ +$(LOCAL_PATH)/ccShaders.cpp \ +$(LOCAL_PATH)/CCSprite.cpp \ +$(LOCAL_PATH)/CCSpriteBatchNode.cpp \ +$(LOCAL_PATH)/CCSpriteFrame.cpp \ +$(LOCAL_PATH)/CCSpriteFrameCache.cpp \ +$(LOCAL_PATH)/CCTextFieldTTF.cpp \ +$(LOCAL_PATH)/CCTextImage.cpp \ +$(LOCAL_PATH)/CCTexture2D.cpp \ +$(LOCAL_PATH)/CCTextureAtlas.cpp \ +$(LOCAL_PATH)/CCTextureCache.cpp \ +$(LOCAL_PATH)/CCTileMapAtlas.cpp \ +$(LOCAL_PATH)/CCTMXLayer.cpp \ +$(LOCAL_PATH)/CCTMXObjectGroup.cpp \ +$(LOCAL_PATH)/CCTMXTiledMap.cpp \ +$(LOCAL_PATH)/CCTMXXMLParser.cpp \ +$(LOCAL_PATH)/CCTouch.cpp \ +$(LOCAL_PATH)/CCTransition.cpp \ +$(LOCAL_PATH)/CCTransitionPageTurn.cpp \ +$(LOCAL_PATH)/CCTransitionProgress.cpp \ +$(LOCAL_PATH)/ccTypes.cpp \ +$(LOCAL_PATH)/CCUserDefault.cpp \ +$(LOCAL_PATH)/CCUserDefaultAndroid.cpp \ +$(LOCAL_PATH)/ccUTF8.cpp \ +$(LOCAL_PATH)/ccUtils.cpp \ +$(LOCAL_PATH)/CCVertex.cpp \ +$(LOCAL_PATH)/cocos2d.cpp \ +$(LOCAL_PATH)/TGAlib.cpp \ +$(LOCAL_PATH)/TransformUtils.cpp \ +$(LOCAL_PATH)/ZipUtils.cpp \ +$(LOCAL_PATH)/platform/CCEGLViewProtocol.cpp \ +$(LOCAL_PATH)/platform/CCFileUtils.cpp \ +$(LOCAL_PATH)/platform/CCSAXParser.cpp \ +$(LOCAL_PATH)/platform/CCThread.cpp \ +$(LOCAL_PATH)/../base/atitc.cpp \ +$(LOCAL_PATH)/../base/CCAffineTransform.cpp \ +$(LOCAL_PATH)/../base/CCArray.cpp \ +$(LOCAL_PATH)/../base/CCAutoreleasePool.cpp \ +$(LOCAL_PATH)/../base/CCData.cpp \ +$(LOCAL_PATH)/../base/CCDataVisitor.cpp \ +$(LOCAL_PATH)/../base/CCDictionary.cpp \ +$(LOCAL_PATH)/../base/CCGeometry.cpp \ +$(LOCAL_PATH)/../base/CCNS.cpp \ +$(LOCAL_PATH)/../base/CCObject.cpp \ +$(LOCAL_PATH)/../base/CCSet.cpp \ +$(LOCAL_PATH)/../base/CCString.cpp \ +$(LOCAL_PATH)/../base/etc1.cpp \ +$(LOCAL_PATH)/../base/s3tc.cpp \ +$(LOCAL_PATH)/../math/kazmath/src/aabb.c \ +$(LOCAL_PATH)/../math/kazmath/src/mat3.c \ +$(LOCAL_PATH)/../math/kazmath/src/mat4.c \ +$(LOCAL_PATH)/../math/kazmath/src/neon_matrix_impl.c \ +$(LOCAL_PATH)/../math/kazmath/src/plane.c \ +$(LOCAL_PATH)/../math/kazmath/src/quaternion.c \ +$(LOCAL_PATH)/../math/kazmath/src/ray2.c \ +$(LOCAL_PATH)/../math/kazmath/src/utility.c \ +$(LOCAL_PATH)/../math/kazmath/src/vec2.c \ +$(LOCAL_PATH)/../math/kazmath/src/vec3.c \ +$(LOCAL_PATH)/../math/kazmath/src/vec4.c \ +$(LOCAL_PATH)/../math/kazmath/src/GL/mat4stack.c \ +$(LOCAL_PATH)/../math/kazmath/src/GL/matrix.c \ +$(LOCAL_PATH)/../physics/CCPhysicsBody.cpp \ +$(LOCAL_PATH)/../physics/CCPhysicsContact.cpp \ +$(LOCAL_PATH)/../physics/CCPhysicsJoint.cpp \ +$(LOCAL_PATH)/../physics/CCPhysicsShape.cpp \ +$(LOCAL_PATH)/../physics/CCPhysicsWorld.cpp \ +$(LOCAL_PATH)/../physics/box2d/CCPhysicsBodyInfo.cpp \ +$(LOCAL_PATH)/../physics/box2d/CCPhysicsContactInfo.cpp \ +$(LOCAL_PATH)/../physics/box2d/CCPhysicsJointInfo.cpp \ +$(LOCAL_PATH)/../physics/box2d/CCPhysicsShapeInfo.cpp \ +$(LOCAL_PATH)/../physics/box2d/CCPhysicsWorldInfo.cpp \ +$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsBodyInfo.cpp \ +$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsContactInfo.cpp \ +$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsJointInfo.cpp \ +$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsShapeInfo.cpp \ +$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +$(LOCAL_PATH)/../../external/tinyxml2/tinyxml2.cpp \ +$(LOCAL_PATH)/../../external/unzip/ioapi.cpp \ +$(LOCAL_PATH)/../../external/unzip/unzip.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/kazmath/include \ + $(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/platform/android \ - $(LOCAL_PATH)/platform/third_party/common/etc \ - $(LOCAL_PATH)/platform/third_party/common/s3tc \ - $(LOCAL_PATH)/platform/third_party/common/atitc \ - $(LOCAL_PATH)/../external/chipmunk/include/chipmunk + $(LOCAL_PATH)/../physics \ + $(LOCAL_PATH)/../base \ + $(LOCAL_PATH)/../../external/tinyxml2 \ + $(LOCAL_PATH)/../../external/unzip \ + $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk LOCAL_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/kazmath/include \ + $(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/platform/android \ - $(LOCAL_PATH)/platform/third_party/common/etc \ - $(LOCAL_PATH)/platform/third_party/common/s3tc \ - $(LOCAL_PATH)/platform/third_party/common/atitc \ - $(LOCAL_PATH)/../external/chipmunk/include/chipmunk + $(LOCAL_PATH)/../physics \ + $(LOCAL_PATH)/../base \ + $(LOCAL_PATH)/../../external/tinyxml2 \ + $(LOCAL_PATH)/../../external/unzip \ + $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk LOCAL_LDLIBS := -lGLESv2 \ @@ -196,6 +200,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libtiff_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libwebp_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_freetype2_static LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static # define the macro to compile through support/zip_support/ioapi.c LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API @@ -203,9 +208,10 @@ LOCAL_EXPORT_CFLAGS := -Wno-psabi -DUSE_FILE32API include $(BUILD_STATIC_LIBRARY) -$(call import-module,libjpeg) -$(call import-module,libpng) -$(call import-module,libtiff) -$(call import-module,libwebp) -$(call import-module,libfreetype2) -$(call import-module,external/chipmunk) +$(call import-module,jpeg/prebuilt/android) +$(call import-module,png/prebuilt/android) +$(call import-module,tiff/prebuilt/android) +$(call import-module,webp/prebuilt/android) +$(call import-module,freetype2/prebuilt/android) +$(call import-module,chipmunk) +$(call import-module,2d/platform/android) diff --git a/cocos/2d/CCAction.cpp b/cocos/2d/CCAction.cpp index 515aa53f14..3a6f66953c 100644 --- a/cocos/2d/CCAction.cpp +++ b/cocos/2d/CCAction.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCAction.h" #include "CCActionInterval.h" -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/CCAction.h b/cocos/2d/CCAction.h index ccb787fcda..2ead2ad96e 100644 --- a/cocos/2d/CCAction.h +++ b/cocos/2d/CCAction.h @@ -27,9 +27,9 @@ THE SOFTWARE. #ifndef __ACTIONS_CCACTION_H__ #define __ACTIONS_CCACTION_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" -#include "platform/CCPlatformMacros.h" +#include "CCObject.h" +#include "CCGeometry.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp index 395d5277c7..8b9673914a 100644 --- a/cocos/2d/CCActionCamera.cpp +++ b/cocos/2d/CCActionCamera.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCActionCamera.h" -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCCamera.h" #include "CCStdC.h" diff --git a/cocos/2d/CCActionCatmullRom.h b/cocos/2d/CCActionCatmullRom.h index ca864ea820..7b4452d1bc 100644 --- a/cocos/2d/CCActionCatmullRom.h +++ b/cocos/2d/CCActionCatmullRom.h @@ -40,8 +40,8 @@ #include #include "CCActionInterval.h" -#include "base_nodes/CCNode.h" -#include "cocoa/CCGeometry.h" +#include "CCNode.h" +#include "CCGeometry.h" NS_CC_BEGIN; diff --git a/cocos/2d/CCActionGrid.cpp b/cocos/2d/CCActionGrid.cpp index 57f61a384f..c174f3cf0f 100644 --- a/cocos/2d/CCActionGrid.cpp +++ b/cocos/2d/CCActionGrid.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCActionGrid.h" #include "CCDirector.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" NS_CC_BEGIN // implementation of GridAction diff --git a/cocos/2d/CCActionInstant.cpp b/cocos/2d/CCActionInstant.cpp index 21e1a1c745..f71a361a02 100644 --- a/cocos/2d/CCActionInstant.cpp +++ b/cocos/2d/CCActionInstant.cpp @@ -25,9 +25,9 @@ ****************************************************************************/ #include "CCActionInstant.h" -#include "base_nodes/CCNode.h" -#include "sprite_nodes/CCSprite.h" -#include "script_support/CCScriptSupport.h" +#include "CCNode.h" +#include "CCSprite.h" +#include "CCScriptSupport.h" #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index d5a9d88704..0fe7e055b9 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -25,8 +25,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCActionInterval.h" -#include "sprite_nodes/CCSprite.h" -#include "base_nodes/CCNode.h" +#include "CCSprite.h" +#include "CCNode.h" #include "CCStdC.h" #include "CCActionInstant.h" #include diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index 6e3a5371e0..270dca3414 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -27,11 +27,11 @@ THE SOFTWARE. #ifndef __ACTION_CCINTERVAL_ACTION_H__ #define __ACTION_CCINTERVAL_ACTION_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCAction.h" #include "CCProtocols.h" -#include "sprite_nodes/CCSpriteFrame.h" -#include "sprite_nodes/CCAnimation.h" +#include "CCSpriteFrame.h" +#include "CCAnimation.h" #include NS_CC_BEGIN diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index ba964f73a2..9d1fb1ee93 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -26,12 +26,12 @@ THE SOFTWARE. ****************************************************************************/ #include "CCActionManager.h" -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCScheduler.h" #include "ccMacros.h" -#include "support/data_support/ccCArray.h" -#include "support/data_support/uthash.h" -#include "cocoa/CCSet.h" +#include "ccCArray.h" +#include "uthash.h" +#include "CCSet.h" NS_CC_BEGIN // diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 6b20f0e806..72427a5648 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -29,8 +29,8 @@ THE SOFTWARE. #define __ACTION_CCACTION_MANAGER_H__ #include "CCAction.h" -#include "cocoa/CCArray.h" -#include "cocoa/CCObject.h" +#include "CCArray.h" +#include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/2d/CCActionProgressTimer.cpp b/cocos/2d/CCActionProgressTimer.cpp index 4fa9de2f31..cf9e11f436 100644 --- a/cocos/2d/CCActionProgressTimer.cpp +++ b/cocos/2d/CCActionProgressTimer.cpp @@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCActionProgressTimer.h" -#include "misc_nodes/CCProgressTimer.h" +#include "CCProgressTimer.h" NS_CC_BEGIN diff --git a/cocos/2d/CCActionTiledGrid.cpp b/cocos/2d/CCActionTiledGrid.cpp index 63ccb223f4..269a798b1d 100644 --- a/cocos/2d/CCActionTiledGrid.cpp +++ b/cocos/2d/CCActionTiledGrid.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. #include "CCActionTiledGrid.h" #include "CCDirector.h" #include "ccMacros.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" #include NS_CC_BEGIN diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 65f88953aa..5fa37cd85c 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -24,10 +24,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCAnimation.h" -#include "textures/CCTextureCache.h" -#include "textures/CCTexture2D.h" +#include "CCTextureCache.h" +#include "CCTexture2D.h" #include "ccMacros.h" -#include "sprite_nodes/CCSpriteFrame.h" +#include "CCSpriteFrame.h" NS_CC_BEGIN diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index 24799355c4..cc38ca6d84 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -26,11 +26,11 @@ THE SOFTWARE. #ifndef __CC_ANIMATION_H__ #define __CC_ANIMATION_H__ -#include "platform/CCPlatformConfig.h" -#include "cocoa/CCObject.h" -#include "cocoa/CCArray.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCGeometry.h" +#include "CCPlatformConfig.h" +#include "CCObject.h" +#include "CCArray.h" +#include "CCDictionary.h" +#include "CCGeometry.h" #include "CCSpriteFrame.h" #include diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 4c36fa0231..37f516347a 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCAnimation.h" #include "CCSpriteFrame.h" #include "CCSpriteFrameCache.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include "platform/CCFileUtils.h" using namespace std; diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index 8fc0b62f6a..f30d6ee94f 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -26,8 +26,8 @@ THE SOFTWARE. #ifndef __CC_ANIMATION_CACHE_H__ #define __CC_ANIMATION_CACHE_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCDictionary.h" +#include "CCObject.h" +#include "CCDictionary.h" #include diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 02338220f8..7d5a64dba7 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -25,14 +25,14 @@ THE SOFTWARE. ****************************************************************************/ #include "CCAtlasNode.h" -#include "textures/CCTextureAtlas.h" -#include "textures/CCTextureCache.h" +#include "CCTextureAtlas.h" +#include "CCTextureCache.h" #include "CCDirector.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" #include "CCDirector.h" -#include "support/TransformUtils.h" +#include "TransformUtils.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCCamera.cpp b/cocos/2d/CCCamera.cpp index 2d97fe2678..36487c88fc 100644 --- a/cocos/2d/CCCamera.cpp +++ b/cocos/2d/CCCamera.cpp @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ #include "CCCamera.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include "CCGL.h" -#include "draw_nodes/CCDrawingPrimitives.h" +#include "CCDrawingPrimitives.h" #include "CCDirector.h" #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCCamera.h b/cocos/2d/CCCamera.h index 9e8f0d1d49..cb99787855 100644 --- a/cocos/2d/CCCamera.h +++ b/cocos/2d/CCCamera.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "ccMacros.h" #include "kazmath/mat4.h" diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index 7b797617cb..d51fcc5002 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -27,10 +27,10 @@ #include "CCClippingNode.h" #include "kazmath/GL/matrix.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" #include "CCDirector.h" -#include "draw_nodes/CCDrawingPrimitives.h" +#include "CCDrawingPrimitives.h" NS_CC_BEGIN diff --git a/cocos/2d/CCClippingNode.h b/cocos/2d/CCClippingNode.h index 3ad7f1f944..ca2a17b8d7 100644 --- a/cocos/2d/CCClippingNode.h +++ b/cocos/2d/CCClippingNode.h @@ -28,7 +28,7 @@ #ifndef __MISCNODE_CCCLIPPING_NODE_H__ #define __MISCNODE_CCCLIPPING_NODE_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCGL.h" NS_CC_BEGIN diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index e0bfd75031..b073051e06 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "support/component/CCComponent.h" +#include "CCComponent.h" NS_CC_BEGIN diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index e658d10eee..58023fe9fb 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_FRAMEWORK_COMPONENT_H__ #define __CC_FRAMEWORK_COMPONENT_H__ -#include "cocoa/CCObject.h" +#include "CCObject.h" #include NS_CC_BEGIN diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index ea0fc99d3b..b0f5bc3fd9 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -#include "support/component/CCComponentContainer.h" -#include "support/component/CCComponent.h" +#include "CCComponentContainer.h" +#include "CCComponent.h" #include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/CCComponentContainer.h b/cocos/2d/CCComponentContainer.h index 2125e2d28a..57622a7d1b 100644 --- a/cocos/2d/CCComponentContainer.h +++ b/cocos/2d/CCComponentContainer.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_FRAMEWORK_COMCONTAINER_H__ #define __CC_FRAMEWORK_COMCONTAINER_H__ -#include "cocoa/CCDictionary.h" +#include "CCDictionary.h" NS_CC_BEGIN diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index cf88679366..6e5b5cf966 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -27,9 +27,9 @@ THE SOFTWARE. #include #include "ccMacros.h" #include "ccConfig.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCInteger.h" -#include "cocoa/CCBool.h" +#include "CCDictionary.h" +#include "CCInteger.h" +#include "CCBool.h" #include "cocos2d.h" #include "platform/CCFileUtils.h" diff --git a/cocos/2d/CCConfiguration.h b/cocos/2d/CCConfiguration.h index 2b2a4f98ee..eb78275ef9 100644 --- a/cocos/2d/CCConfiguration.h +++ b/cocos/2d/CCConfiguration.h @@ -26,9 +26,9 @@ THE SOFTWARE. #ifndef __CCCONFIGURATION_H__ #define __CCCONFIGURATION_H__ -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "CCGL.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 0e201a9668..323be9f642 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -29,7 +29,7 @@ #define __COCOS2D_CCDEPRECATED_H__ #include -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include "ccTypes.h" NS_CC_BEGIN diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 3046957708..8d1d8cb5df 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -31,31 +31,31 @@ THE SOFTWARE. #include #include "ccFPSImages.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "cocoa/CCNS.h" -#include "layers_scenes_transitions_nodes/CCScene.h" -#include "cocoa/CCArray.h" +#include "CCDrawingPrimitives.h" +#include "CCNS.h" +#include "CCScene.h" +#include "CCArray.h" #include "CCScheduler.h" #include "ccMacros.h" -#include "support/CCNotificationCenter.h" -#include "layers_scenes_transitions_nodes/CCTransition.h" -#include "textures/CCTextureCache.h" -#include "sprite_nodes/CCSpriteFrameCache.h" -#include "cocoa/CCAutoreleasePool.h" +#include "CCNotificationCenter.h" +#include "CCTransition.h" +#include "CCTextureCache.h" +#include "CCSpriteFrameCache.h" +#include "CCAutoreleasePool.h" #include "platform/CCFileUtils.h" #include "CCApplication.h" -#include "label_nodes/CCLabelBMFont.h" -#include "label_nodes/CCLabelAtlas.h" -#include "actions/CCActionManager.h" -#include "sprite_nodes/CCAnimationCache.h" -#include "event_dispatcher/CCTouch.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "support/user_default/CCUserDefault.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCShaderCache.h" +#include "CCLabelBMFont.h" +#include "CCLabelAtlas.h" +#include "CCActionManager.h" +#include "CCAnimationCache.h" +#include "CCTouch.h" +#include "CCEventDispatcher.h" +#include "CCUserDefault.h" +#include "ccGLStateCache.h" +#include "CCShaderCache.h" #include "kazmath/kazmath.h" #include "kazmath/GL/matrix.h" -#include "support/CCProfiling.h" +#include "CCProfiling.h" #include "platform/CCImage.h" #include "CCEGLView.h" #include "CCConfiguration.h" diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 9cc20393ea..4da35a96a8 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -27,15 +27,15 @@ THE SOFTWARE. #ifndef __CCDIRECTOR_H__ #define __CCDIRECTOR_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "ccTypes.h" -#include "cocoa/CCGeometry.h" -#include "cocoa/CCArray.h" +#include "CCGeometry.h" +#include "CCArray.h" #include "CCGL.h" #include "kazmath/mat4.h" -#include "label_nodes/CCLabelAtlas.h" +#include "CCLabelAtlas.h" NS_CC_BEGIN diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 541bd8974c..3623266864 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -21,9 +21,9 @@ */ #include "CCDrawNode.h" -#include "shaders/CCShaderCache.h" +#include "CCShaderCache.h" #include "CCGL.h" -#include "support/CCNotificationCenter.h" +#include "CCNotificationCenter.h" #include "CCEventType.h" NS_CC_BEGIN diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 9349430880..3e128d26ea 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -30,7 +30,7 @@ #ifndef __CCDRAWNODES_CCDRAW_NODE_H__ #define __CCDRAWNODES_CCDRAW_NODE_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "ccTypes.h" NS_CC_BEGIN diff --git a/cocos/2d/CCDrawingPrimitives.cpp b/cocos/2d/CCDrawingPrimitives.cpp index 632ca57ea8..4e22032e21 100644 --- a/cocos/2d/CCDrawingPrimitives.cpp +++ b/cocos/2d/CCDrawingPrimitives.cpp @@ -40,10 +40,10 @@ THE SOFTWARE. #include "ccMacros.h" #include "CCGL.h" #include "CCDirector.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "actions/CCActionCatmullRom.h" +#include "ccGLStateCache.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "CCActionCatmullRom.h" #include #include diff --git a/cocos/2d/CCDrawingPrimitives.h b/cocos/2d/CCDrawingPrimitives.h index ba4f2c1955..c46c88a0ad 100644 --- a/cocos/2d/CCDrawingPrimitives.h +++ b/cocos/2d/CCDrawingPrimitives.h @@ -42,7 +42,7 @@ THE SOFTWARE. #include "ccTypes.h" #include "ccMacros.h" -#include "cocoa/CCGeometry.h" // for Point +#include "CCGeometry.h" // for Point /** @file diff --git a/cocos/2d/CCEvent.h b/cocos/2d/CCEvent.h index dd7e36a47a..1652066fd3 100644 --- a/cocos/2d/CCEvent.h +++ b/cocos/2d/CCEvent.h @@ -29,7 +29,7 @@ #include #include -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 468db2f39b..14be190f68 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -25,7 +25,7 @@ #include "CCEvent.h" #include "CCEventTouch.h" #include "CCEventListenerTouch.h" -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCDirector.h" #include diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 2fdd0ae24e..06b6e430c7 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -25,7 +25,7 @@ #ifndef __CC_EVENT_DISPATCHER_H__ #define __CC_EVENT_DISPATCHER_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "CCEventListener.h" #include diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index 156d644f17..82c47445e0 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -25,8 +25,8 @@ #ifndef cocos2d_libs_EventListener_h #define cocos2d_libs_EventListener_h -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCObject.h" +#include "CCPlatformMacros.h" +#include "CCObject.h" #include #include diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 62cd4c3e6d..3002676bda 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -27,7 +27,7 @@ #define __cocos2d_libs__CCTouchEventListener__ #include "CCEventListener.h" -#include "event_dispatcher/CCTouch.h" +#include "CCTouch.h" #include diff --git a/cocos/2d/CCEventTouch.h b/cocos/2d/CCEventTouch.h index a005073173..3d54cecea7 100644 --- a/cocos/2d/CCEventTouch.h +++ b/cocos/2d/CCEventTouch.h @@ -26,7 +26,7 @@ #define __cocos2d_libs__TouchEvent__ #include "CCEvent.h" -#include "event_dispatcher/CCTouch.h" +#include "CCTouch.h" #include NS_CC_BEGIN diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 7274ddcaf9..63fe7af7d1 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "CCFont.h" -#include "support/ccUTF8.h" +#include "ccUTF8.h" #include "CCFontFNT.h" #include "CCFontFreeType.h" diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 33157aab88..c0522f522b 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -24,7 +24,7 @@ #include -#include "support/ccUTF8.h" +#include "ccUTF8.h" #include "CCFontFreeType.h" #include "CCTextImage.h" #include "CCFont.h" diff --git a/cocos/2d/CCGLProgram.cpp b/cocos/2d/CCGLProgram.cpp index 85fdbfe029..83da8f9bdc 100644 --- a/cocos/2d/CCGLProgram.cpp +++ b/cocos/2d/CCGLProgram.cpp @@ -30,8 +30,8 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "ccMacros.h" #include "platform/CCFileUtils.h" -#include "support/data_support/uthash.h" -#include "cocoa/CCString.h" +#include "uthash.h" +#include "CCString.h" // extern #include "kazmath/GL/matrix.h" #include "kazmath/kazmath.h" diff --git a/cocos/2d/CCGLProgram.h b/cocos/2d/CCGLProgram.h index 8174f7632a..cea1add0b2 100644 --- a/cocos/2d/CCGLProgram.h +++ b/cocos/2d/CCGLProgram.h @@ -29,7 +29,7 @@ THE SOFTWARE. #define __CCGLPROGRAM_H__ #include "ccMacros.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "CCGL.h" diff --git a/cocos/2d/CCGrabber.cpp b/cocos/2d/CCGrabber.cpp index ad07a7e99e..4486e58712 100644 --- a/cocos/2d/CCGrabber.cpp +++ b/cocos/2d/CCGrabber.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCGrabber.h" #include "ccMacros.h" -#include "textures/CCTexture2D.h" +#include "CCTexture2D.h" NS_CC_BEGIN diff --git a/cocos/2d/CCGrabber.h b/cocos/2d/CCGrabber.h index 8556101703..9fef542459 100644 --- a/cocos/2d/CCGrabber.h +++ b/cocos/2d/CCGrabber.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __EFFECTS_CCGRABBER_H__ #include "CCConfiguration.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "CCGL.h" NS_CC_BEGIN diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index 04da5fa6b7..fc2152ab13 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -23,15 +23,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "ccMacros.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" #include "CCDirector.h" -#include "effects/CCGrabber.h" -#include "support/ccUtils.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" +#include "CCGrabber.h" +#include "ccUtils.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" #include "CCGL.h" -#include "support/TransformUtils.h" +#include "TransformUtils.h" #include "kazmath/kazmath.h" #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 7d91fbf620..97904cdf3e 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -25,15 +25,15 @@ THE SOFTWARE. #ifndef __EFFECTS_CCGRID_H__ #define __EFFECTS_CCGRID_H__ -#include "cocoa/CCObject.h" -#include "base_nodes/CCNode.h" +#include "CCObject.h" +#include "CCNode.h" #include "CCCamera.h" #include "ccTypes.h" -#include "textures/CCTexture2D.h" +#include "CCTexture2D.h" #include "CCDirector.h" #include "kazmath/mat4.h" #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN NS_CC_BEGIN diff --git a/cocos/2d/CCIMEDelegate.h b/cocos/2d/CCIMEDelegate.h index 3ab7387af5..d7fee2e59b 100644 --- a/cocos/2d/CCIMEDelegate.h +++ b/cocos/2d/CCIMEDelegate.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_IME_DELEGATE_H__ #define __CC_IME_DELEGATE_H__ -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 65688258db..e65c27eb7b 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -26,7 +26,7 @@ #ifndef _COCOS2D_CCLABEL_H_ #define _COCOS2D_CCLABEL_H_ -#include "sprite_nodes/CCSpriteBatchNode.h" +#include "CCSpriteBatchNode.h" #include "CCLabelTextFormatProtocol.h" #include "ccTypes.h" diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 9c659d91cc..e96df277b5 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -24,16 +24,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCLabelAtlas.h" -#include "textures/CCTextureAtlas.h" -#include "textures/CCTextureCache.h" -#include "draw_nodes/CCDrawingPrimitives.h" +#include "CCTextureAtlas.h" +#include "CCTextureCache.h" +#include "CCDrawingPrimitives.h" #include "ccConfig.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" #include "CCDirector.h" -#include "support/TransformUtils.h" -#include "cocoa/CCInteger.h" +#include "TransformUtils.h" +#include "CCInteger.h" #include "platform/CCFileUtils.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 4ec488203a..2c7d98ea5b 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -26,7 +26,7 @@ THE SOFTWARE. #ifndef __CCLABEL_ATLAS_H__ #define __CCLABEL_ATLAS_H__ -#include "base_nodes/CCAtlasNode.h" +#include "CCAtlasNode.h" NS_CC_BEGIN diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 863f6d947e..601187d619 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -31,15 +31,15 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) ****************************************************************************/ #include "CCLabelBMFont.h" -#include "cocoa/CCString.h" -#include "cocoa/CCDictionary.h" +#include "CCString.h" +#include "CCDictionary.h" #include "CCConfiguration.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "sprite_nodes/CCSprite.h" +#include "CCDrawingPrimitives.h" +#include "CCSprite.h" #include "platform/CCFileUtils.h" #include "CCDirector.h" -#include "textures/CCTextureCache.h" -#include "support/ccUTF8.h" +#include "CCTextureCache.h" +#include "ccUTF8.h" using namespace std; diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index bd218b65a2..11ff078ac5 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -33,8 +33,8 @@ Use any of these editors to generate BMFonts: #ifndef __CCBITMAP_FONT_ATLAS_H__ #define __CCBITMAP_FONT_ATLAS_H__ -#include "sprite_nodes/CCSpriteBatchNode.h" -#include "support/data_support/uthash.h" +#include "CCSpriteBatchNode.h" +#include "uthash.h" #include #include #include diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 91dba16fe6..bead3ea020 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCLabelTTF.h" #include "CCDirector.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" #include "CCApplication.h" NS_CC_BEGIN diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index acdd67017c..9243a50e1c 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCLABELTTF_H__ #define __CCLABELTTF_H__ -#include "sprite_nodes/CCSprite.h" -#include "textures/CCTexture2D.h" +#include "CCSprite.h" +#include "CCTexture2D.h" NS_CC_BEGIN diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 2a3853740a..0c674a5345 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -25,7 +25,7 @@ #include #include "cocos2d.h" -#include "support/ccUTF8.h" +#include "ccUTF8.h" #include "CCLabelTextFormatter.h" using namespace std; diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 37037b456a..19346ea844 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -27,20 +27,20 @@ THE SOFTWARE. #include #include "CCLayer.h" #include "CCDirector.h" -#include "script_support/CCScriptSupport.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" -#include "support/TransformUtils.h" +#include "CCScriptSupport.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" +#include "TransformUtils.h" // extern #include "kazmath/GL/matrix.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventListenerTouch.h" -#include "event_dispatcher/CCEventTouch.h" -#include "event_dispatcher/CCEventKeyboard.h" -#include "event_dispatcher/CCEventListenerKeyboard.h" -#include "event_dispatcher/CCEventAcceleration.h" -#include "event_dispatcher/CCEventListenerAcceleration.h" +#include "CCEventDispatcher.h" +#include "CCEventListenerTouch.h" +#include "CCEventTouch.h" +#include "CCEventKeyboard.h" +#include "CCEventListenerKeyboard.h" +#include "CCEventAcceleration.h" +#include "CCEventListenerAcceleration.h" #include "platform/CCDevice.h" #include "CCScene.h" diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 1d8f143b51..0dad16ff21 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -27,15 +27,15 @@ THE SOFTWARE. #ifndef __CCLAYER_H__ #define __CCLAYER_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" -#include "cocoa/CCArray.h" +#include "CCArray.h" #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN -#include "physics/CCPhysicsSetting.h" +#include "CCPhysicsSetting.h" -#include "event_dispatcher/CCEventKeyboard.h" +#include "CCEventKeyboard.h" NS_CC_BEGIN diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 48613dfb00..c0c10e9cdb 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -25,10 +25,10 @@ THE SOFTWARE. #include "CCMenu.h" #include "CCDirector.h" #include "CCApplication.h" -#include "event_dispatcher/CCTouch.h" +#include "CCTouch.h" #include "CCStdC.h" -#include "cocoa/CCInteger.h" -#include "event_dispatcher/CCEventListenerTouch.h" +#include "CCInteger.h" +#include "CCEventListenerTouch.h" #include diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 92dd66f788..bd685786c4 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -26,9 +26,9 @@ THE SOFTWARE. #define __CCMENU_H_ #include "CCMenuItem.h" -#include "layers_scenes_transitions_nodes/CCLayer.h" +#include "CCLayer.h" -#include "event_dispatcher/CCEventTouch.h" +#include "CCEventTouch.h" NS_CC_BEGIN diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 1df5075647..c735677e9f 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -25,11 +25,11 @@ THE SOFTWARE. ****************************************************************************/ #include "CCMenuItem.h" -#include "actions/CCActionInterval.h" -#include "sprite_nodes/CCSprite.h" -#include "label_nodes/CCLabelAtlas.h" -#include "label_nodes/CCLabelTTF.h" -#include "script_support/CCScriptSupport.h" +#include "CCActionInterval.h" +#include "CCSprite.h" +#include "CCLabelAtlas.h" +#include "CCLabelTTF.h" +#include "CCScriptSupport.h" #include #include diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 65e75ae28a..021832df30 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -31,9 +31,9 @@ THE SOFTWARE. #include // cocos2d includes -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" -#include "cocoa/CCArray.h" +#include "CCArray.h" NS_CC_BEGIN diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 8ef2a4124e..47cb43a207 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -23,13 +23,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCMotionStreak.h" -#include "textures/CCTextureCache.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" +#include "CCTextureCache.h" +#include "ccGLStateCache.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" #include "ccMacros.h" -#include "support/CCVertex.h" +#include "CCVertex.h" NS_CC_BEGIN diff --git a/cocos/2d/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h index 6b6535f371..c0fc986c73 100644 --- a/cocos/2d/CCMotionStreak.h +++ b/cocos/2d/CCMotionStreak.h @@ -26,11 +26,11 @@ THE SOFTWARE. #define __CCMOTION_STREAK_H__ #include "CCProtocols.h" -#include "textures/CCTexture2D.h" +#include "CCTexture2D.h" #include "ccTypes.h" -#include "base_nodes/CCNode.h" +#include "CCNode.h" #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN NS_CC_BEGIN diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 4db892fdd6..5c6a47e822 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -29,29 +29,29 @@ THE SOFTWARE. #include -#include "cocoa/CCString.h" -#include "support/data_support/ccCArray.h" -#include "support/TransformUtils.h" +#include "CCString.h" +#include "ccCArray.h" +#include "TransformUtils.h" #include "CCCamera.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" #include "CCDirector.h" #include "CCScheduler.h" -#include "event_dispatcher/CCTouch.h" -#include "actions/CCActionManager.h" -#include "script_support/CCScriptSupport.h" -#include "shaders/CCGLProgram.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEvent.h" -#include "event_dispatcher/CCEventTouch.h" +#include "CCTouch.h" +#include "CCActionManager.h" +#include "CCScriptSupport.h" +#include "CCGLProgram.h" +#include "CCEventDispatcher.h" +#include "CCEvent.h" +#include "CCEventTouch.h" #ifdef CC_USE_PHYSICS -#include "physics/CCPhysicsBody.h" +#include "CCPhysicsBody.h" #endif // externals #include "kazmath/GL/matrix.h" -#include "support/component/CCComponent.h" -#include "support/component/CCComponentContainer.h" +#include "CCComponent.h" +#include "CCComponentContainer.h" diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 605b178bbf..133968d19b 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -29,16 +29,16 @@ #define __PLATFORM_CCNODE_H__ #include "ccMacros.h" -#include "cocoa/CCAffineTransform.h" -#include "cocoa/CCArray.h" +#include "CCAffineTransform.h" +#include "CCArray.h" #include "CCGL.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" +#include "ccGLStateCache.h" +#include "CCGLProgram.h" #include "kazmath/kazmath.h" -#include "script_support/CCScriptSupport.h" +#include "CCScriptSupport.h" #include "CCProtocols.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "physics/CCPhysicsSetting.h" +#include "CCEventDispatcher.h" +#include "CCPhysicsSetting.h" #include diff --git a/cocos/2d/CCNotificationCenter.cpp b/cocos/2d/CCNotificationCenter.cpp index a7f19d5ff0..8b109daacc 100644 --- a/cocos/2d/CCNotificationCenter.cpp +++ b/cocos/2d/CCNotificationCenter.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCNotificationCenter.h" -#include "cocoa/CCArray.h" -#include "script_support/CCScriptSupport.h" +#include "CCArray.h" +#include "CCScriptSupport.h" #include using namespace std; diff --git a/cocos/2d/CCNotificationCenter.h b/cocos/2d/CCNotificationCenter.h index 62587a02f7..41025bdf87 100644 --- a/cocos/2d/CCNotificationCenter.h +++ b/cocos/2d/CCNotificationCenter.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCNOTIFICATIONCENTER_H__ #define __CCNOTIFICATIONCENTER_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCArray.h" +#include "CCObject.h" +#include "CCArray.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index 29f16ea2a4..781147b457 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -24,7 +24,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCParallaxNode.h" -#include "support/data_support/ccCArray.h" +#include "ccCArray.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h index eeaa2be707..36c3a192a9 100644 --- a/cocos/2d/CCParallaxNode.h +++ b/cocos/2d/CCParallaxNode.h @@ -26,8 +26,8 @@ THE SOFTWARE. #ifndef __CCPARALLAX_NODE_H__ #define __CCPARALLAX_NODE_H__ -#include "base_nodes/CCNode.h" -/*#include "support/data_support/ccArray.h"*/ +#include "CCNode.h" +/*#include "ccArray.h"*/ NS_CC_BEGIN diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index f0f82c8f98..a7dbdc14d1 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -28,20 +28,20 @@ */ #include "CCParticleBatchNode.h" -#include "textures/CCTextureCache.h" -#include "textures/CCTextureAtlas.h" +#include "CCTextureCache.h" +#include "CCTextureAtlas.h" #include "ccConfig.h" #include "ccMacros.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" #include "CCParticleSystem.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" -#include "support/base64.h" -#include "support/zip_support/ZipUtils.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" +#include "base64.h" +#include "ZipUtils.h" #include "platform/CCFileUtils.h" #include "kazmath/GL/matrix.h" -#include "support/CCProfiling.h" +#include "CCProfiling.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index b63e72c1c6..9b5808be45 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -29,7 +29,7 @@ #ifndef __CCPARTICLEBATCHNODE_H__ #define __CCPARTICLEBATCHNODE_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp index 465e4af325..c7e2946172 100644 --- a/cocos/2d/CCParticleExamples.cpp +++ b/cocos/2d/CCParticleExamples.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCParticleExamples.h" #include "CCDirector.h" -#include "textures/CCTextureCache.h" +#include "CCTextureCache.h" #include "firePngData.h" #include "platform/CCImage.h" diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 04f2bf3c5c..a42ac234cb 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -47,14 +47,14 @@ THE SOFTWARE. #include "CCParticleBatchNode.h" #include "ccTypes.h" -#include "textures/CCTextureCache.h" -#include "textures/CCTextureAtlas.h" -#include "support/base64.h" +#include "CCTextureCache.h" +#include "CCTextureAtlas.h" +#include "base64.h" #include "platform/CCFileUtils.h" #include "platform/CCImage.h" -#include "support/zip_support/ZipUtils.h" +#include "ZipUtils.h" #include "CCDirector.h" -#include "support/CCProfiling.h" +#include "CCProfiling.h" // opengl #include "CCGL.h" diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index c26d12840c..ae22671c4c 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -27,9 +27,9 @@ THE SOFTWARE. #define __CCPARTICLE_SYSTEM_H__ #include "CCProtocols.h" -#include "base_nodes/CCNode.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCString.h" +#include "CCNode.h" +#include "CCDictionary.h" +#include "CCString.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 5a8912b203..3cf7d9e1d4 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -27,15 +27,15 @@ THE SOFTWARE. #include "CCGL.h" #include "CCParticleSystemQuad.h" -#include "sprite_nodes/CCSpriteFrame.h" +#include "CCSpriteFrame.h" #include "CCDirector.h" #include "CCParticleBatchNode.h" -#include "textures/CCTextureAtlas.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "support/TransformUtils.h" -#include "support/CCNotificationCenter.h" +#include "CCTextureAtlas.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" +#include "CCGLProgram.h" +#include "TransformUtils.h" +#include "CCNotificationCenter.h" #include "CCEventType.h" // extern diff --git a/cocos/2d/CCProfiling.h b/cocos/2d/CCProfiling.h index 9b02b490e5..d68dc6f918 100644 --- a/cocos/2d/CCProfiling.h +++ b/cocos/2d/CCProfiling.h @@ -28,8 +28,8 @@ THE SOFTWARE. #include #include #include "ccConfig.h" -#include "cocoa/CCObject.h" -#include "cocoa/CCDictionary.h" +#include "CCObject.h" +#include "CCDictionary.h" NS_CC_BEGIN diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index 01f9ae107c..d370866d1b 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -25,13 +25,13 @@ THE SOFTWARE. #include "CCProgressTimer.h" #include "ccMacros.h" -#include "textures/CCTextureCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" +#include "CCTextureCache.h" +#include "CCGLProgram.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" #include "CCDirector.h" -#include "support/TransformUtils.h" -#include "draw_nodes/CCDrawingPrimitives.h" +#include "TransformUtils.h" +#include "CCDrawingPrimitives.h" // extern #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCProgressTimer.h b/cocos/2d/CCProgressTimer.h index 6bd7d56542..e09e34be0f 100644 --- a/cocos/2d/CCProgressTimer.h +++ b/cocos/2d/CCProgressTimer.h @@ -25,9 +25,9 @@ THE SOFTWARE. #ifndef __MISC_NODE_CCPROGRESS_TIMER_H__ #define __MISC_NODE_CCPROGRESS_TIMER_H__ -#include "sprite_nodes/CCSprite.h" +#include "CCSprite.h" #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN NS_CC_BEGIN diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index bde86e318d..01b7ebc011 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -27,7 +27,7 @@ THE SOFTWARE. #define __CCPROTOCOLS_H__ #include "ccTypes.h" -#include "textures/CCTexture2D.h" +#include "CCTexture2D.h" #include NS_CC_BEGIN diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 3a217fef8d..5bace186cf 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -24,19 +24,19 @@ THE SOFTWARE. ****************************************************************************/ #include "CCConfiguration.h" -#include "misc_nodes/CCRenderTexture.h" +#include "CCRenderTexture.h" #include "CCDirector.h" #include "platform/CCImage.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" #include "CCConfiguration.h" -#include "support/ccUtils.h" -#include "textures/CCTextureCache.h" +#include "ccUtils.h" +#include "CCTextureCache.h" #include "platform/CCFileUtils.h" #include "CCGL.h" -#include "support/CCNotificationCenter.h" +#include "CCNotificationCenter.h" #include "CCEventType.h" -#include "effects/CCGrid.h" +#include "CCGrid.h" // extern #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 9105d55d38..5318e83fdf 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCRENDER_TEXTURE_H__ #define __CCRENDER_TEXTURE_H__ -#include "base_nodes/CCNode.h" -#include "sprite_nodes/CCSprite.h" +#include "CCNode.h" +#include "CCSprite.h" #include "kazmath/mat4.h" #include "platform/CCImage.h" diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index c48f95c860..cc8654204b 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -27,9 +27,9 @@ THE SOFTWARE. #include "CCScene.h" #include "CCDirector.h" #include "CCLayer.h" -#include "sprite_nodes/CCSprite.h" -#include "sprite_nodes/CCSpriteBatchNode.h" -#include "physics/CCPhysicsWorld.h" +#include "CCSprite.h" +#include "CCSpriteBatchNode.h" +#include "CCPhysicsWorld.h" NS_CC_BEGIN diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index c2e2aa7bcb..11e3e0fbb5 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -27,8 +27,8 @@ THE SOFTWARE. #ifndef __CCSCENE_H__ #define __CCSCENE_H__ -#include "base_nodes/CCNode.h" -#include "physics/CCPhysicsWorld.h" +#include "CCNode.h" +#include "CCPhysicsWorld.h" NS_CC_BEGIN diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 2bf62c1fef..3f9c9da9f8 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -27,10 +27,10 @@ THE SOFTWARE. #include "CCScheduler.h" #include "ccMacros.h" #include "CCDirector.h" -#include "support/data_support/utlist.h" -#include "support/data_support/ccCArray.h" -#include "cocoa/CCArray.h" -#include "script_support/CCScriptSupport.h" +#include "utlist.h" +#include "ccCArray.h" +#include "CCArray.h" +#include "CCScriptSupport.h" using namespace std; diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index e4b3526ae2..221781f776 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -27,8 +27,8 @@ THE SOFTWARE. #ifndef __CCSCHEDULER_H__ #define __CCSCHEDULER_H__ -#include "cocoa/CCObject.h" -#include "support/data_support/uthash.h" +#include "CCObject.h" +#include "uthash.h" NS_CC_BEGIN diff --git a/cocos/2d/CCScriptSupport.h b/cocos/2d/CCScriptSupport.h index 324d337ed8..0c7f502a8b 100644 --- a/cocos/2d/CCScriptSupport.h +++ b/cocos/2d/CCScriptSupport.h @@ -26,10 +26,10 @@ #define __SCRIPT_SUPPORT_H__ #include "platform/CCCommon.h" -#include "event_dispatcher/CCTouch.h" -#include "event_dispatcher/CCEventTouch.h" -#include "event_dispatcher/CCEventKeyboard.h" -#include "cocoa/CCSet.h" +#include "CCTouch.h" +#include "CCEventTouch.h" +#include "CCEventKeyboard.h" +#include "CCSet.h" #include #include #include diff --git a/cocos/2d/CCShaderCache.h b/cocos/2d/CCShaderCache.h index ec326b50cf..ee65bc33b9 100644 --- a/cocos/2d/CCShaderCache.h +++ b/cocos/2d/CCShaderCache.h @@ -30,7 +30,7 @@ THE SOFTWARE. #include #include -#include "cocoa/CCDictionary.h" +#include "CCDictionary.h" NS_CC_BEGIN diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index e1cfd9b5da..db9f4544f2 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -33,17 +33,17 @@ THE SOFTWARE. #include "CCSprite.h" #include "CCSpriteFrame.h" #include "CCSpriteFrameCache.h" -#include "textures/CCTextureCache.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" +#include "CCTextureCache.h" +#include "CCDrawingPrimitives.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" +#include "CCGLProgram.h" #include "CCDirector.h" -#include "cocoa/CCGeometry.h" -#include "textures/CCTexture2D.h" -#include "cocoa/CCAffineTransform.h" -#include "support/TransformUtils.h" -#include "support/CCProfiling.h" +#include "CCGeometry.h" +#include "CCTexture2D.h" +#include "CCAffineTransform.h" +#include "TransformUtils.h" +#include "CCProfiling.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index d150c55213..cc6470c7da 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -27,16 +27,16 @@ THE SOFTWARE. #ifndef __SPITE_NODE_CCSPRITE_H__ #define __SPITE_NODE_CCSPRITE_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" -#include "textures/CCTextureAtlas.h" +#include "CCTextureAtlas.h" #include "ccTypes.h" -#include "cocoa/CCDictionary.h" +#include "CCDictionary.h" #include #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN -#include "physics/CCPhysicsBody.h" +#include "CCPhysicsBody.h" NS_CC_BEGIN diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 6df8215bd0..b4be9bd045 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -31,17 +31,17 @@ THE SOFTWARE. #include "ccConfig.h" #include "CCSprite.h" -#include "effects/CCGrid.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "textures/CCTextureCache.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" +#include "CCGrid.h" +#include "CCDrawingPrimitives.h" +#include "CCTextureCache.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" #include "CCDirector.h" -#include "support/TransformUtils.h" -#include "support/CCProfiling.h" -#include "layers_scenes_transitions_nodes/CCLayer.h" -#include "layers_scenes_transitions_nodes/CCScene.h" +#include "TransformUtils.h" +#include "CCProfiling.h" +#include "CCLayer.h" +#include "CCScene.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 091c012160..6ba402fe57 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -30,9 +30,9 @@ THE SOFTWARE. #include -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" -#include "textures/CCTextureAtlas.h" +#include "CCTextureAtlas.h" #include "ccMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 2cb21824b5..8bc0bafa6d 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -23,7 +23,7 @@ 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 "textures/CCTextureCache.h" +#include "CCTextureCache.h" #include "CCSpriteFrame.h" #include "CCDirector.h" diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index 30899290a4..f9b2d68c4a 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -27,10 +27,10 @@ THE SOFTWARE. #ifndef __SPRITE_CCSPRITE_FRAME_H__ #define __SPRITE_CCSPRITE_FRAME_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCProtocols.h" -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 1d19773c60..78fc2f8fa6 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -26,17 +26,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "cocoa/CCNS.h" +#include "CCNS.h" #include "ccMacros.h" -#include "textures/CCTextureCache.h" +#include "CCTextureCache.h" #include "CCSpriteFrameCache.h" #include "CCSpriteFrame.h" #include "CCSprite.h" -#include "support/TransformUtils.h" +#include "TransformUtils.h" #include "platform/CCFileUtils.h" -#include "cocoa/CCString.h" -#include "cocoa/CCArray.h" -#include "cocoa/CCDictionary.h" +#include "CCString.h" +#include "CCArray.h" +#include "CCDictionary.h" #include using namespace std; diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index 7a9129018e..c7249d222c 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -34,9 +34,9 @@ THE SOFTWARE. * http://zwoptex.zwopple.com/ */ -#include "sprite_nodes/CCSpriteFrame.h" -#include "textures/CCTexture2D.h" -#include "cocoa/CCObject.h" +#include "CCSpriteFrame.h" +#include "CCTexture2D.h" +#include "CCObject.h" #include #include diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index c0a1b1e10f..4b801ea83e 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -26,11 +26,11 @@ THE SOFTWARE. #include "CCTMXLayer.h" #include "CCTMXXMLParser.h" #include "CCTMXTiledMap.h" -#include "sprite_nodes/CCSprite.h" -#include "textures/CCTextureCache.h" -#include "shaders/CCShaderCache.h" -#include "shaders/CCGLProgram.h" -#include "support/data_support/ccCArray.h" +#include "CCSprite.h" +#include "CCTextureCache.h" +#include "CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccCArray.h" #include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTMXLayer.h b/cocos/2d/CCTMXLayer.h index c5a8340b80..b85de82c1e 100644 --- a/cocos/2d/CCTMXLayer.h +++ b/cocos/2d/CCTMXLayer.h @@ -27,10 +27,10 @@ THE SOFTWARE. #define __CCTMX_LAYER_H__ #include "CCTMXObjectGroup.h" -#include "base_nodes/CCAtlasNode.h" -#include "sprite_nodes/CCSpriteBatchNode.h" +#include "CCAtlasNode.h" +#include "CCSpriteBatchNode.h" #include "CCTMXXMLParser.h" -#include "support/data_support/ccCArray.h" +#include "ccCArray.h" NS_CC_BEGIN class TMXMapInfo; diff --git a/cocos/2d/CCTMXObjectGroup.h b/cocos/2d/CCTMXObjectGroup.h index c4c5462946..7a06e4b961 100644 --- a/cocos/2d/CCTMXObjectGroup.h +++ b/cocos/2d/CCTMXObjectGroup.h @@ -27,10 +27,10 @@ THE SOFTWARE. #ifndef __CCTMX_OBJECT_GROUP_H__ #define __CCTMX_OBJECT_GROUP_H__ -#include "cocoa/CCGeometry.h" -#include "cocoa/CCString.h" -#include "cocoa/CCArray.h" -#include "cocoa/CCDictionary.h" +#include "CCGeometry.h" +#include "CCString.h" +#include "CCArray.h" +#include "CCDictionary.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index a856f577a4..c6c47b3abd 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCTMXTiledMap.h" #include "CCTMXXMLParser.h" #include "CCTMXLayer.h" -#include "sprite_nodes/CCSprite.h" +#include "CCSprite.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index f3c92c91ae..82ea45bd13 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -26,7 +26,7 @@ THE SOFTWARE. #ifndef __CCTMX_TILE_MAP_H__ #define __CCTMX_TILE_MAP_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCTMXObjectGroup.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 8f95cc5487..8497638cf7 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -31,8 +31,8 @@ THE SOFTWARE. #include "CCTMXTiledMap.h" #include "ccMacros.h" #include "platform/CCFileUtils.h" -#include "support/zip_support/ZipUtils.h" -#include "support/base64.h" +#include "ZipUtils.h" +#include "base64.h" using namespace std; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 6cad378de0..7b4851386c 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -28,9 +28,9 @@ THE SOFTWARE. #ifndef __CC_TM_XML_PARSER__ #define __CC_TM_XML_PARSER__ -#include "cocoa/CCArray.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCGeometry.h" +#include "CCArray.h" +#include "CCDictionary.h" +#include "CCGeometry.h" #include "platform/CCSAXParser.h" #include diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 18a58c3ffb..79feb55d7c 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CC_TEXT_FIELD_H__ #define __CC_TEXT_FIELD_H__ -#include "label_nodes/CCLabelTTF.h" -#include "text_input_node/CCIMEDelegate.h" +#include "CCLabelTTF.h" +#include "CCIMEDelegate.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 7ff46a3e83..84a6822dda 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -36,12 +36,12 @@ THE SOFTWARE. #include "CCConfiguration.h" #include "platform/CCImage.h" #include "CCGL.h" -#include "support/ccUtils.h" -#include "platform/CCPlatformMacros.h" +#include "ccUtils.h" +#include "CCPlatformMacros.h" #include "CCDirector.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCShaderCache.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" +#include "CCShaderCache.h" #if CC_ENABLE_CACHE_TEXTURE_DATA #include "CCTextureCache.h" diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index f962560c7b..6f15273f9c 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -29,11 +29,11 @@ THE SOFTWARE. #include #include -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" #include "ccTypes.h" #ifdef EMSCRIPTEN -#include "base_nodes/CCGLBufferedNode.h" +#include "CCGLBufferedNode.h" #endif // EMSCRIPTEN NS_CC_BEGIN diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 239294e7a3..c83a042dde 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -28,14 +28,14 @@ THE SOFTWARE. #include "CCTextureAtlas.h" #include "CCTextureCache.h" #include "ccMacros.h" -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" -#include "support/CCNotificationCenter.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" +#include "CCNotificationCenter.h" #include "CCEventType.h" #include "CCGL.h" // support #include "CCTexture2D.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include //According to some tests GL_TRIANGLE_STRIP is slower, MUCH slower. Probably I'm doing something very wrong diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index afed7e16dc..4c1bb6436a 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -28,7 +28,7 @@ THE SOFTWARE. #define __CCTEXTURE_ATLAS_H__ #include "ccTypes.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "ccConfig.h" #include diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 82fc78cbe7..95c02f8ff4 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -35,9 +35,9 @@ THE SOFTWARE. #include "CCDirector.h" #include "platform/CCFileUtils.h" #include "platform/CCThread.h" -#include "support/ccUtils.h" +#include "ccUtils.h" #include "CCScheduler.h" -#include "cocoa/CCString.h" +#include "CCString.h" #ifdef EMSCRIPTEN diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index c1c403f12c..ec87d891d8 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -35,8 +35,8 @@ THE SOFTWARE. #include #include -#include "cocoa/CCObject.h" -#include "textures/CCTexture2D.h" +#include "CCObject.h" +#include "CCTexture2D.h" #include "platform/CCImage.h" #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/cocos/2d/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp index 0863c2f097..9b7bc85ad3 100644 --- a/cocos/2d/CCTileMapAtlas.cpp +++ b/cocos/2d/CCTileMapAtlas.cpp @@ -25,11 +25,11 @@ THE SOFTWARE. ****************************************************************************/ #include "CCTileMapAtlas.h" #include "platform/CCFileUtils.h" -#include "textures/CCTextureAtlas.h" -#include "support/image_support/TGAlib.h" +#include "CCTextureAtlas.h" +#include "TGAlib.h" #include "ccConfig.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCInteger.h" +#include "CCDictionary.h" +#include "CCInteger.h" #include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h index 86d7e8a06d..865f47295a 100644 --- a/cocos/2d/CCTileMapAtlas.h +++ b/cocos/2d/CCTileMapAtlas.h @@ -27,7 +27,7 @@ THE SOFTWARE. #define __CCTILE_MAP_ATLAS__ -#include "base_nodes/CCAtlasNode.h" +#include "CCAtlasNode.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTouch.h b/cocos/2d/CCTouch.h index 9cc22ef498..1ed19d3112 100644 --- a/cocos/2d/CCTouch.h +++ b/cocos/2d/CCTouch.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CC_TOUCH_H__ #define __CC_TOUCH_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTransition.cpp b/cocos/2d/CCTransition.cpp index 7232645d2a..5dea9ae721 100644 --- a/cocos/2d/CCTransition.cpp +++ b/cocos/2d/CCTransition.cpp @@ -27,14 +27,14 @@ THE SOFTWARE. #include "CCTransition.h" #include "CCCamera.h" #include "CCDirector.h" -#include "actions/CCActionInterval.h" -#include "actions/CCActionInstant.h" -#include "actions/CCActionEase.h" -#include "actions/CCActionCamera.h" -#include "actions/CCActionTiledGrid.h" -#include "actions/CCActionGrid.h" +#include "CCActionInterval.h" +#include "CCActionInstant.h" +#include "CCActionEase.h" +#include "CCActionCamera.h" +#include "CCActionTiledGrid.h" +#include "CCActionGrid.h" #include "CCLayer.h" -#include "misc_nodes/CCRenderTexture.h" +#include "CCRenderTexture.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index 58bf240123..3bde055c59 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -25,10 +25,10 @@ THE SOFTWARE. #include "CCTransitionPageTurn.h" #include "CCDirector.h" -#include "actions/CCActionInterval.h" -#include "actions/CCActionInstant.h" -#include "actions/CCActionGrid.h" -#include "actions/CCActionPageTurn3D.h" +#include "CCActionInterval.h" +#include "CCActionInstant.h" +#include "CCActionGrid.h" +#include "CCActionPageTurn3D.h" NS_CC_BEGIN diff --git a/cocos/2d/CCTransitionProgress.cpp b/cocos/2d/CCTransitionProgress.cpp index fc6a79ca87..1d53f9cbed 100644 --- a/cocos/2d/CCTransitionProgress.cpp +++ b/cocos/2d/CCTransitionProgress.cpp @@ -27,11 +27,11 @@ THE SOFTWARE. #include "CCTransitionProgress.h" #include "CCDirector.h" -#include "misc_nodes/CCRenderTexture.h" -#include "misc_nodes/CCProgressTimer.h" +#include "CCRenderTexture.h" +#include "CCProgressTimer.h" #include "CCLayer.h" -#include "actions/CCActionInstant.h" -#include "actions/CCActionProgressTimer.h" +#include "CCActionInstant.h" +#include "CCActionProgressTimer.h" NS_CC_BEGIN diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index 63997ac1f9..ab30c805a0 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -24,8 +24,8 @@ THE SOFTWARE. #include "CCUserDefault.h" #include "platform/CCCommon.h" #include "platform/CCFileUtils.h" -#include "../tinyxml2/tinyxml2.h" -#include "support/base64.h" +#include "tinyxml2.h" +#include "base64.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) diff --git a/cocos/2d/CCUserDefault.h b/cocos/2d/CCUserDefault.h index 89609e1559..a18fb00b6a 100644 --- a/cocos/2d/CCUserDefault.h +++ b/cocos/2d/CCUserDefault.h @@ -24,9 +24,9 @@ THE SOFTWARE. #ifndef __SUPPORT_CCUSERDEFAULT_H__ #define __SUPPORT_CCUSERDEFAULT_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include -#include "cocoa/CCData.h" +#include "CCData.h" NS_CC_BEGIN diff --git a/cocos/2d/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm index dcf355e6f9..b55acfcf24 100644 --- a/cocos/2d/CCUserDefault.mm +++ b/cocos/2d/CCUserDefault.mm @@ -25,9 +25,9 @@ #import "CCUserDefault.h" #import #import "platform/CCFileUtils.h" -#import "../tinyxml2/tinyxml2.h" -#import "platform/CCPlatformConfig.h" -#import "platform/CCPlatformMacros.h" +#import "tinyxml2.h" +#import "CCPlatformConfig.h" +#import "CCPlatformMacros.h" #import "base64.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 91ef890aed..38c09c2a90 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -22,9 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCUserDefault.h" -#include "platform/CCPlatformConfig.h" +#include "CCPlatformConfig.h" #include "platform/CCCommon.h" -#include "support/base64.h" +#include "base64.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" diff --git a/cocos/2d/TransformUtils.cpp b/cocos/2d/TransformUtils.cpp index d64a63ffd1..85dbfc86e5 100644 --- a/cocos/2d/TransformUtils.cpp +++ b/cocos/2d/TransformUtils.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #include "TransformUtils.h" -#include "cocoa/CCAffineTransform.h" +#include "CCAffineTransform.h" namespace cocos2d { diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index d7202a091d..5564807540 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -25,7 +25,7 @@ THE SOFTWARE. #define __SUPPORT_ZIPUTILS_H__ #include -#include "platform/CCPlatformConfig.h" +#include "CCPlatformConfig.h" #include "CCPlatformDefine.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) diff --git a/cocos/2d/base64.cpp b/cocos/2d/base64.cpp index 6a44597441..131b0d81f7 100644 --- a/cocos/2d/base64.cpp +++ b/cocos/2d/base64.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. #include #include -#include "support/base64.h" +#include "base64.h" namespace cocos2d { diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index 7271675ede..cd8f275311 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #include "ccCArray.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index 0a788769d4..fff5152904 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -43,7 +43,7 @@ THE SOFTWARE. #define CC_ARRAY_H #include "ccMacros.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include #include diff --git a/cocos/2d/ccConfig.h b/cocos/2d/ccConfig.h index ee8fba0828..f801066bfe 100644 --- a/cocos/2d/ccConfig.h +++ b/cocos/2d/ccConfig.h @@ -27,7 +27,7 @@ THE SOFTWARE. #ifndef __CCCONFIG_H__ #define __CCCONFIG_H__ -#include "platform/CCPlatformConfig.h" +#include "CCPlatformConfig.h" /** @file diff --git a/cocos/2d/ccGLStateCache.h b/cocos/2d/ccGLStateCache.h index 3ea973918a..32bf5584be 100644 --- a/cocos/2d/ccGLStateCache.h +++ b/cocos/2d/ccGLStateCache.h @@ -28,7 +28,7 @@ THE SOFTWARE. #define __CCGLSTATE_H__ #include "CCGL.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/ccShaders.h b/cocos/2d/ccShaders.h index f0bcfd4b42..b7bea82383 100644 --- a/cocos/2d/ccShaders.h +++ b/cocos/2d/ccShaders.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCSHADER_H__ #include "CCGL.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/ccTypes.cpp b/cocos/2d/ccTypes.cpp index f669095ea7..adf9677ea2 100644 --- a/cocos/2d/ccTypes.cpp +++ b/cocos/2d/ccTypes.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "include/ccTypes.h" +#include "ccTypes.h" NS_CC_BEGIN diff --git a/cocos/2d/ccTypes.h b/cocos/2d/ccTypes.h index 409b9734a1..f7bb8d19cb 100644 --- a/cocos/2d/ccTypes.h +++ b/cocos/2d/ccTypes.h @@ -28,7 +28,7 @@ THE SOFTWARE. #define __CCTYPES_H__ #include -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include "CCGL.h" diff --git a/cocos/2d/ccUTF8.h b/cocos/2d/ccUTF8.h index 48543dcd17..9bd8b521df 100644 --- a/cocos/2d/ccUTF8.h +++ b/cocos/2d/ccUTF8.h @@ -8,7 +8,7 @@ #ifndef __cocos2dx__ccUTF8__ #define __cocos2dx__ccUTF8__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include NS_CC_BEGIN diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index bb270d265a..9799e0a9fd 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -37,47 +37,47 @@ THE SOFTWARE. #include "ccConfig.h" // actions -#include "actions/CCAction.h" -#include "actions/CCActionInterval.h" -#include "actions/CCActionCamera.h" -#include "actions/CCActionManager.h" -#include "actions/CCActionEase.h" -#include "actions/CCActionPageTurn3D.h" -#include "actions/CCActionGrid.h" -#include "actions/CCActionProgressTimer.h" -#include "actions/CCActionGrid3D.h" -#include "actions/CCActionTiledGrid.h" -#include "actions/CCActionInstant.h" -#include "actions/CCActionTween.h" -#include "actions/CCActionCatmullRom.h" +#include "CCAction.h" +#include "CCActionInterval.h" +#include "CCActionCamera.h" +#include "CCActionManager.h" +#include "CCActionEase.h" +#include "CCActionPageTurn3D.h" +#include "CCActionGrid.h" +#include "CCActionProgressTimer.h" +#include "CCActionGrid3D.h" +#include "CCActionTiledGrid.h" +#include "CCActionInstant.h" +#include "CCActionTween.h" +#include "CCActionCatmullRom.h" // base_nodes -#include "base_nodes/CCNode.h" -#include "base_nodes/CCAtlasNode.h" +#include "CCNode.h" +#include "CCAtlasNode.h" // cocoa -#include "cocoa/CCAffineTransform.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCObject.h" -#include "cocoa/CCArray.h" -#include "cocoa/CCGeometry.h" -#include "cocoa/CCSet.h" -#include "cocoa/CCAutoreleasePool.h" -#include "cocoa/CCInteger.h" -#include "cocoa/CCFloat.h" -#include "cocoa/CCDouble.h" -#include "cocoa/CCBool.h" -#include "cocoa/CCString.h" -#include "cocoa/CCNS.h" -#include "cocoa/CCData.h" +#include "CCAffineTransform.h" +#include "CCDictionary.h" +#include "CCObject.h" +#include "CCArray.h" +#include "CCGeometry.h" +#include "CCSet.h" +#include "CCAutoreleasePool.h" +#include "CCInteger.h" +#include "CCFloat.h" +#include "CCDouble.h" +#include "CCBool.h" +#include "CCString.h" +#include "CCNS.h" +#include "CCData.h" // draw nodes -#include "draw_nodes/CCDrawingPrimitives.h" -#include "draw_nodes/CCDrawNode.h" +#include "CCDrawingPrimitives.h" +#include "CCDrawNode.h" // effects -#include "effects/CCGrabber.h" -#include "effects/CCGrid.h" +#include "CCGrabber.h" +#include "CCGrid.h" // include #include "CCEventType.h" @@ -87,40 +87,40 @@ THE SOFTWARE. #include "ccTypes.h" // label_nodes -#include "label_nodes/CCLabelAtlas.h" -#include "label_nodes/CCLabelTTF.h" -#include "label_nodes/CCLabelBMFont.h" -#include "label_nodes/CCLabel.h" +#include "CCLabelAtlas.h" +#include "CCLabelTTF.h" +#include "CCLabelBMFont.h" +#include "CCLabel.h" // layers_scenes_transitions_nodes -#include "layers_scenes_transitions_nodes/CCLayer.h" -#include "layers_scenes_transitions_nodes/CCScene.h" -#include "layers_scenes_transitions_nodes/CCTransition.h" -#include "layers_scenes_transitions_nodes/CCTransitionPageTurn.h" -#include "layers_scenes_transitions_nodes/CCTransitionProgress.h" +#include "CCLayer.h" +#include "CCScene.h" +#include "CCTransition.h" +#include "CCTransitionPageTurn.h" +#include "CCTransitionProgress.h" // menu_nodes -#include "menu_nodes/CCMenu.h" -#include "menu_nodes/CCMenuItem.h" +#include "CCMenu.h" +#include "CCMenuItem.h" // misc_nodes -#include "misc_nodes/CCClippingNode.h" -#include "misc_nodes/CCMotionStreak.h" -#include "misc_nodes/CCProgressTimer.h" -#include "misc_nodes/CCRenderTexture.h" +#include "CCClippingNode.h" +#include "CCMotionStreak.h" +#include "CCProgressTimer.h" +#include "CCRenderTexture.h" // particle_nodes -#include "particle_nodes/CCParticleBatchNode.h" -#include "particle_nodes/CCParticleSystem.h" -#include "particle_nodes/CCParticleExamples.h" -#include "particle_nodes/CCParticleSystemQuad.h" +#include "CCParticleBatchNode.h" +#include "CCParticleSystem.h" +#include "CCParticleExamples.h" +#include "CCParticleSystemQuad.h" // physics -#include "physics/CCPhysicsBody.h" -#include "physics/CCPhysicsContact.h" -#include "physics/CCPhysicsShape.h" -#include "physics/CCPhysicsJoint.h" -#include "physics/CCPhysicsWorld.h" +#include "CCPhysicsBody.h" +#include "CCPhysicsContact.h" +#include "CCPhysicsShape.h" +#include "CCPhysicsJoint.h" +#include "CCPhysicsWorld.h" // platform #include "platform/CCDevice.h" @@ -129,8 +129,8 @@ THE SOFTWARE. #include "platform/CCImage.h" #include "platform/CCSAXParser.h" #include "platform/CCThread.h" -#include "platform/CCPlatformConfig.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformConfig.h" +#include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "platform/ios/CCApplication.h" @@ -175,58 +175,57 @@ THE SOFTWARE. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX // script_support -#include "script_support/CCScriptSupport.h" +#include "CCScriptSupport.h" // shaders -#include "shaders/CCGLProgram.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccShaders.h" +#include "CCGLProgram.h" +#include "ccGLStateCache.h" +#include "CCShaderCache.h" +#include "ccShaders.h" // sprite_nodes -#include "sprite_nodes/CCAnimation.h" -#include "sprite_nodes/CCAnimationCache.h" -#include "sprite_nodes/CCSprite.h" -#include "sprite_nodes/CCSpriteBatchNode.h" -#include "sprite_nodes/CCSpriteFrame.h" -#include "sprite_nodes/CCSpriteFrameCache.h" +#include "CCAnimation.h" +#include "CCAnimationCache.h" +#include "CCSprite.h" +#include "CCSpriteBatchNode.h" +#include "CCSpriteFrame.h" +#include "CCSpriteFrameCache.h" // support -#include "support/ccUTF8.h" -#include "support/CCNotificationCenter.h" -#include "support/CCProfiling.h" -#include "support/user_default/CCUserDefault.h" -#include "support/CCVertex.h" -#include "support/tinyxml2/tinyxml2.h" +#include "ccUTF8.h" +#include "CCNotificationCenter.h" +#include "CCProfiling.h" +#include "CCUserDefault.h" +#include "CCVertex.h" // text_input_node -#include "text_input_node/CCIMEDelegate.h" -#include "text_input_node/CCIMEDispatcher.h" -#include "text_input_node/CCTextFieldTTF.h" +#include "CCIMEDelegate.h" +#include "CCIMEDispatcher.h" +#include "CCTextFieldTTF.h" // textures -#include "textures/CCTexture2D.h" -#include "textures/CCTextureAtlas.h" -#include "textures/CCTextureCache.h" +#include "CCTexture2D.h" +#include "CCTextureAtlas.h" +#include "CCTextureCache.h" // tilemap_parallax_nodes -#include "tilemap_parallax_nodes/CCParallaxNode.h" -#include "tilemap_parallax_nodes/CCTMXLayer.h" -#include "tilemap_parallax_nodes/CCTMXObjectGroup.h" -#include "tilemap_parallax_nodes/CCTMXTiledMap.h" -#include "tilemap_parallax_nodes/CCTMXXMLParser.h" -#include "tilemap_parallax_nodes/CCTileMapAtlas.h" +#include "CCParallaxNode.h" +#include "CCTMXLayer.h" +#include "CCTMXObjectGroup.h" +#include "CCTMXTiledMap.h" +#include "CCTMXXMLParser.h" +#include "CCTileMapAtlas.h" // EventDispatcher -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventListenerTouch.h" -#include "event_dispatcher/CCEventTouch.h" -#include "event_dispatcher/CCEventListenerKeyboard.h" -#include "event_dispatcher/CCEventKeyboard.h" -#include "event_dispatcher/CCEventAcceleration.h" -#include "event_dispatcher/CCEventListenerAcceleration.h" -#include "event_dispatcher/CCEventCustom.h" -#include "event_dispatcher/CCEventListenerCustom.h" +#include "CCEventDispatcher.h" +#include "CCEventListenerTouch.h" +#include "CCEventTouch.h" +#include "CCEventListenerKeyboard.h" +#include "CCEventKeyboard.h" +#include "CCEventAcceleration.h" +#include "CCEventListenerAcceleration.h" +#include "CCEventCustom.h" +#include "CCEventListenerCustom.h" // root #include "CCCamera.h" @@ -235,8 +234,8 @@ THE SOFTWARE. #include "CCScheduler.h" // component -#include "support/component/CCComponent.h" -#include "support/component/CCComponentContainer.h" +#include "CCComponent.h" +#include "CCComponentContainer.h" // Deprecated include #include "CCDeprecated.h" diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 870146a2f9..9b1e943019 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -1,8 +1,8 @@ #include "CCEGLViewProtocol.h" -#include "event_dispatcher/CCTouch.h" +#include "CCTouch.h" #include "CCDirector.h" -#include "cocoa/CCSet.h" -#include "event_dispatcher/CCEventDispatcher.h" +#include "CCSet.h" +#include "CCEventDispatcher.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index 718c415850..b8744d0dd1 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -2,7 +2,7 @@ #define __CCEGLVIEWPROTOCOL_H__ #include "ccTypes.h" -#include "event_dispatcher/CCEventTouch.h" +#include "CCEventTouch.h" #include diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 6f286607fb..e9e01589e2 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -24,11 +24,11 @@ THE SOFTWARE. #include "CCFileUtils.h" #include "CCDirector.h" -#include "cocoa/CCDictionary.h" -#include "cocoa/CCString.h" +#include "CCDictionary.h" +#include "CCString.h" #include "CCSAXParser.h" -#include "support/tinyxml2/tinyxml2.h" -#include "support/zip_support/unzip.h" +#include "tinyxml2.h" +#include "unzip.h" #include using namespace std; diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index f6eba03132..25f09dade2 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CC_IMAGE_H__ #define __CC_IMAGE_H__ -#include "cocoa/CCObject.h" -#include "textures/CCTexture2D.h" +#include "CCObject.h" +#include "CCTexture2D.h" // premultiply alpha, or the effect will wrong when want to use other pixel format in Texture2D, // such as RGB888, RGB5A1 diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index 8c62e2288e..be7480a0ae 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -40,25 +40,20 @@ extern "C" #include "etc1.h" #include "jpeglib.h" } -#include "third_party/common/s3tc/s3tc.h" -#include "third_party/common/atitc/atitc.h" -#if defined(__native_client__) || defined(EMSCRIPTEN) -// TODO(sbc): I'm pretty sure all platforms should be including -// webph headers in this way. -#include "webp/decode.h" -#else +#include "s3tc.h" +#include "atitc.h" + #include "decode.h" -#endif #include "ccMacros.h" -#include "platform/CCCommon.h" +#include "CCCommon.h" #include "CCStdC.h" #include "CCFileUtils.h" #include "CCConfiguration.h" -#include "support/ccUtils.h" -#include "support/zip_support/ZipUtils.h" +#include "ccUtils.h" +#include "ZipUtils.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -#include "platform/android/CCFileUtilsAndroid.h" +#include "android/CCFileUtilsAndroid.h" #endif #define CC_GL_ATC_RGB_AMD 0x8C92 diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 7a857452e0..0f823f938d 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -23,9 +23,9 @@ ****************************************************************************/ #include "CCSAXParser.h" -#include "cocoa/CCDictionary.h" +#include "CCDictionary.h" #include "CCFileUtils.h" -#include "support/tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include // because its based on windows 8 build :P diff --git a/cocos/2d/platform/android/Android.mk b/cocos/2d/platform/android/Android.mk index a599507dc3..2aca5c8ed3 100644 --- a/cocos/2d/platform/android/Android.mk +++ b/cocos/2d/platform/android/Android.mk @@ -24,9 +24,9 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) LOCAL_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../.. \ - $(LOCAL_PATH)/../../include \ - $(LOCAL_PATH)/../../kazmath/include \ - $(LOCAL_PATH)/../../platform/third_party/common/etc + $(LOCAL_PATH)/../../../base \ + $(LOCAL_PATH)/../../../math/kazmath/include \ + $(LOCAL_PATH)/../../../physics LOCAL_LDLIBS := -lGLESv1_CM \ -lGLESv2 \ @@ -47,8 +47,8 @@ LOCAL_WHOLE_STATIC_LIBRARIES := android_native_app_glue cocos_libpng_static coco include $(BUILD_STATIC_LIBRARY) -$(call import-module,libjpeg) -$(call import-module,libpng) -$(call import-module,libtiff) -$(call import-module,libwebp) +$(call import-module,jpeg/prebuilt/android) +$(call import-module,png/prebuilt/android) +$(call import-module,tiff/prebuilt/android) +$(call import-module,webp/prebuilt/android) $(call import-module,android/native_app_glue) diff --git a/cocos/2d/platform/android/CCEGLView.cpp b/cocos/2d/platform/android/CCEGLView.cpp index 384773f119..0347d70a87 100644 --- a/cocos/2d/platform/android/CCEGLView.cpp +++ b/cocos/2d/platform/android/CCEGLView.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCEGLView.h" -#include "cocoa/CCSet.h" +#include "CCSet.h" #include "CCDirector.h" #include "ccMacros.h" #include "jni/IMEJni.h" diff --git a/cocos/2d/platform/android/CCEGLView.h b/cocos/2d/platform/android/CCEGLView.h index 2432a2cee7..cab0754d3e 100644 --- a/cocos/2d/platform/android/CCEGLView.h +++ b/cocos/2d/platform/android/CCEGLView.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_EGLVIEW_ANDROID_H__ #define __CC_EGLVIEW_ANDROID_H__ -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include "platform/CCEGLViewProtocol.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index a0e020bc85..87a2445f48 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -25,7 +25,7 @@ #define __CC_FILEUTILS_ANDROID_H__ #include "platform/CCFileUtils.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "ccTypes.h" #include #include diff --git a/cocos/2d/platform/android/CCImage.cpp b/cocos/2d/platform/android/CCImage.cpp index 8c4c636422..0fdfe6445e 100644 --- a/cocos/2d/platform/android/CCImage.cpp +++ b/cocos/2d/platform/android/CCImage.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CC_PLATFORM_IMAGE_CPP__ #include "platform/CCImageCommon_cpp.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "platform/CCImage.h" #include "platform/CCFileUtils.h" #include "jni/JniHelper.h" diff --git a/cocos/2d/platform/android/CCStdC.h b/cocos/2d/platform/android/CCStdC.h index 16fb8d768b..475142b51a 100644 --- a/cocos/2d/platform/android/CCStdC.h +++ b/cocos/2d/platform/android/CCStdC.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #include #include diff --git a/cocos/2d/platform/android/jni/IMEJni.cpp b/cocos/2d/platform/android/jni/IMEJni.cpp index e9b0f0321c..1529374275 100644 --- a/cocos/2d/platform/android/jni/IMEJni.cpp +++ b/cocos/2d/platform/android/jni/IMEJni.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "IMEJni.h" -#include "text_input_node/CCIMEDispatcher.h" +#include "CCIMEDispatcher.h" #include "JniHelper.h" #include diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp index 21977aadd1..5ed0fc7279 100644 --- a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp @@ -4,7 +4,7 @@ #include "../CCApplication.h" #include "platform/CCFileUtils.h" #include "CCEventType.h" -#include "support/CCNotificationCenter.h" +#include "CCNotificationCenter.h" #include using namespace cocos2d; diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp index afcc4b7d3e..6af1c6b1f7 100644 --- a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp @@ -3,7 +3,7 @@ #include #include #include "JniHelper.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include "Java_org_cocos2dx_lib_Cocos2dxHelper.h" #define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp" diff --git a/cocos/2d/platform/android/jni/JniHelper.h b/cocos/2d/platform/android/jni/JniHelper.h index fe1bf38814..20955acf7e 100644 --- a/cocos/2d/platform/android/jni/JniHelper.h +++ b/cocos/2d/platform/android/jni/JniHelper.h @@ -26,7 +26,7 @@ THE SOFTWARE. #include #include -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index b591953fb8..fa4fb434d4 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -16,17 +16,17 @@ #include "CCDirector.h" #include "CCApplication.h" #include "CCEventType.h" -#include "support/CCNotificationCenter.h" +#include "CCNotificationCenter.h" #include "CCFileUtilsAndroid.h" #include "jni/JniHelper.h" #include "CCEGLView.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "shaders/CCShaderCache.h" -#include "textures/CCTextureCache.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventAcceleration.h" -#include "event_dispatcher/CCEventKeyboard.h" +#include "CCDrawingPrimitives.h" +#include "CCShaderCache.h" +#include "CCTextureCache.h" +#include "CCEventDispatcher.h" +#include "CCEventAcceleration.h" +#include "CCEventKeyboard.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.mm b/cocos/2d/platform/apple/CCFileUtilsApple.mm index 34de65fee6..811a4189b1 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -26,12 +26,12 @@ THE SOFTWARE. #include #include -#include "cocoa/CCString.h" +#include "CCString.h" #include "CCFileUtils.h" #include "CCDirector.h" #include "CCSAXParser.h" #include "CCDictionary.h" -#include "support/zip_support/unzip.h" +#include "unzip.h" #include "CCFileUtilsApple.h" diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index e84eb4196d..83212d575d 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -1,7 +1,7 @@ #include "CCDevice.h" #include "ccTypes.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventAcceleration.h" +#include "CCEventDispatcher.h" +#include "CCEventAcceleration.h" #import diff --git a/cocos/2d/platform/ios/CCStdC.h b/cocos/2d/platform/ios/CCStdC.h index 16fb8d768b..475142b51a 100644 --- a/cocos/2d/platform/ios/CCStdC.h +++ b/cocos/2d/platform/ios/CCStdC.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #include #include diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 384bd05796..452d5738a3 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -9,10 +9,10 @@ #include "CCGL.h" #include "ccMacros.h" #include "CCDirector.h" -#include "event_dispatcher/CCTouch.h" -#include "text_input_node/CCIMEDispatcher.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventKeyboard.h" +#include "CCTouch.h" +#include "/CCIMEDispatcher.h" +#include "CCEventDispatcher.h" +#include "CCEventKeyboard.h" #include NS_CC_BEGIN diff --git a/cocos/2d/platform/linux/CCEGLView.h b/cocos/2d/platform/linux/CCEGLView.h index 5dae9ec609..9d29d9c188 100644 --- a/cocos/2d/platform/linux/CCEGLView.h +++ b/cocos/2d/platform/linux/CCEGLView.h @@ -9,7 +9,7 @@ #define EGLVIEW_H_ #include "platform/CCCommon.h" -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include "platform/CCEGLViewProtocol.h" #include "platform/third_party/linux/glfw/glfw3.h" #include diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp index 13a88a1c3d..227c59b0ba 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp @@ -8,7 +8,7 @@ #include "platform/CCCommon.h" #include "ccMacros.h" #include "CCApplication.h" -#include "cocoa/CCString.h" +#include "CCString.h" #include #include #include diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.h b/cocos/2d/platform/linux/CCFileUtilsLinux.h index 9aed872e80..366f8d08f5 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.h +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.h @@ -25,7 +25,7 @@ #define __CC_FILEUTILS_LINUX_H__ #include "platform/CCFileUtils.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "ccTypes.h" #include #include diff --git a/cocos/2d/platform/linux/CCImage.cpp b/cocos/2d/platform/linux/CCImage.cpp index 9c70245d19..551595c709 100644 --- a/cocos/2d/platform/linux/CCImage.cpp +++ b/cocos/2d/platform/linux/CCImage.cpp @@ -7,7 +7,7 @@ #include #include "platform/CCFileUtils.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #define __CC_PLATFORM_IMAGE_CPP__ #include "platform/CCImageCommon_cpp.h" #include "platform/CCImage.h" diff --git a/cocos/2d/platform/linux/CCStdC.h b/cocos/2d/platform/linux/CCStdC.h index 399de60778..7fd6339bef 100644 --- a/cocos/2d/platform/linux/CCStdC.h +++ b/cocos/2d/platform/linux/CCStdC.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #include diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index 3c371b2457..d8dce7ba57 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -25,9 +25,9 @@ #include "EAGLView.h" #include "CCDirector.h" #include "CCSet.h" -#include "event_dispatcher/CCTouch.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventKeyboard.h" +#include "CCTouch.h" +#include "CCEventDispatcher.h" +#include "CCEventKeyboard.h" #include "CCIMEDispatcher.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/mac/CCEventDispatcher.mm b/cocos/2d/platform/mac/CCEventDispatcher.mm index f316b170c7..6487d877a1 100644 --- a/cocos/2d/platform/mac/CCEventDispatcher.mm +++ b/cocos/2d/platform/mac/CCEventDispatcher.mm @@ -29,7 +29,7 @@ #import "CCEventDispatcher.h" #import "ccConfig.h" -#include "support/data_support/utlist.h" +#include "utlist.h" #include "CCDirector.h" #include "platform/mac/CCEventDispatcher.h" diff --git a/cocos/2d/platform/mac/CCStdC.h b/cocos/2d/platform/mac/CCStdC.h index 16fb8d768b..475142b51a 100644 --- a/cocos/2d/platform/mac/CCStdC.h +++ b/cocos/2d/platform/mac/CCStdC.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #include #include diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index cefcc9f038..4099331cf9 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -23,14 +23,14 @@ THE SOFTWARE. ****************************************************************************/ #include "CCEGLView.h" -#include "cocoa/CCSet.h" +#include "CCSet.h" #include "ccMacros.h" #include "CCDirector.h" -#include "text_input_node/CCIMEDispatcher.h" +#include "/CCIMEDispatcher.h" #include "CCApplication.h" -#include "event_dispatcher/CCTouch.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventKeyboard.h" +#include "CCTouch.h" +#include "CCEventDispatcher.h" +#include "CCEventKeyboard.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/win32/CCEGLView.h b/cocos/2d/platform/win32/CCEGLView.h index 5c5a2b4407..643b500c66 100644 --- a/cocos/2d/platform/win32/CCEGLView.h +++ b/cocos/2d/platform/win32/CCEGLView.h @@ -27,7 +27,7 @@ THE SOFTWARE. #include "CCStdC.h" #include "platform/CCCommon.h" -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include "platform/CCEGLViewProtocol.h" #include "platform/third_party/win32/GLFW/glfw3.h" diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.h b/cocos/2d/platform/win32/CCFileUtilsWin32.h index bd52a82ede..4f01adabeb 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.h +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.h @@ -25,7 +25,7 @@ #define __CC_FILEUTILS_WIN32_H__ #include "platform/CCFileUtils.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "ccTypes.h" #include #include diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index a361e5b056..4716dc6524 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include // for math.h on win32 platform diff --git a/cocos/audio/android/Android.mk b/cocos/audio/android/Android.mk index 2704964c93..ed44e77cf7 100644 --- a/cocos/audio/android/Android.mk +++ b/cocos/audio/android/Android.mk @@ -13,10 +13,11 @@ LOCAL_SRC_FILES := cddSimpleAudioEngine.cpp \ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \ - $(LOCAL_PATH)/../../cocos2dx \ - $(LOCAL_PATH)/../../cocos2dx/include \ - $(LOCAL_PATH)/../../cocos2dx/kazmath/include \ - $(LOCAL_PATH)/../../cocos2dx/platform/android + $(LOCAL_PATH)/../../math/kazmath/include \ + $(LOCAL_PATH)/../../2d \ + $(LOCAL_PATH)/../../2d/platform/android \ + $(LOCAL_PATH)/../../base \ + $(LOCAL_PATH)/../../physics LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi diff --git a/cocos/base/cocoa/CCAffineTransform.cpp b/cocos/base/CCAffineTransform.cpp similarity index 100% rename from cocos/base/cocoa/CCAffineTransform.cpp rename to cocos/base/CCAffineTransform.cpp diff --git a/cocos/base/cocoa/CCAffineTransform.h b/cocos/base/CCAffineTransform.h similarity index 98% rename from cocos/base/cocoa/CCAffineTransform.h rename to cocos/base/CCAffineTransform.h index 667b5d9b46..66c76fc5f0 100644 --- a/cocos/base/cocoa/CCAffineTransform.h +++ b/cocos/base/CCAffineTransform.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __COCOA_CGAFFINETRANSFORM_H__ #include "CCGeometry.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/base/cocoa/CCArray.cpp b/cocos/base/CCArray.cpp similarity index 100% rename from cocos/base/cocoa/CCArray.cpp rename to cocos/base/CCArray.cpp diff --git a/cocos/base/cocoa/CCArray.h b/cocos/base/CCArray.h similarity index 99% rename from cocos/base/cocoa/CCArray.h rename to cocos/base/CCArray.h index 4f5beea501..7f67569faa 100644 --- a/cocos/base/cocoa/CCArray.h +++ b/cocos/base/CCArray.h @@ -30,10 +30,10 @@ THE SOFTWARE. #if CC_USE_ARRAY_VECTOR #include #include -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "ccMacros.h" #else -#include "support/data_support/ccCArray.h" +#include "ccCArray.h" #endif diff --git a/cocos/base/cocoa/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp similarity index 100% rename from cocos/base/cocoa/CCAutoreleasePool.cpp rename to cocos/base/CCAutoreleasePool.cpp diff --git a/cocos/base/cocoa/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h similarity index 100% rename from cocos/base/cocoa/CCAutoreleasePool.h rename to cocos/base/CCAutoreleasePool.h diff --git a/cocos/base/cocoa/CCBool.h b/cocos/base/CCBool.h similarity index 100% rename from cocos/base/cocoa/CCBool.h rename to cocos/base/CCBool.h diff --git a/cocos/base/cocoa/CCData.cpp b/cocos/base/CCData.cpp similarity index 100% rename from cocos/base/cocoa/CCData.cpp rename to cocos/base/CCData.cpp diff --git a/cocos/base/cocoa/CCData.h b/cocos/base/CCData.h similarity index 98% rename from cocos/base/cocoa/CCData.h rename to cocos/base/CCData.h index 889a2d557b..27cb43da61 100644 --- a/cocos/base/cocoa/CCData.h +++ b/cocos/base/CCData.h @@ -25,7 +25,7 @@ #ifndef __CCDATA_H__ #define __CCDATA_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/base/cocoa/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp similarity index 100% rename from cocos/base/cocoa/CCDataVisitor.cpp rename to cocos/base/CCDataVisitor.cpp diff --git a/cocos/base/cocoa/CCDataVisitor.h b/cocos/base/CCDataVisitor.h similarity index 98% rename from cocos/base/cocoa/CCDataVisitor.h rename to cocos/base/CCDataVisitor.h index 3395b43dea..93d2463f29 100644 --- a/cocos/base/cocoa/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -25,7 +25,7 @@ #ifndef __CCDATAVISITOR_H__ #define __CCDATAVISITOR_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include NS_CC_BEGIN diff --git a/cocos/base/cocoa/CCDictionary.cpp b/cocos/base/CCDictionary.cpp similarity index 100% rename from cocos/base/cocoa/CCDictionary.cpp rename to cocos/base/CCDictionary.cpp diff --git a/cocos/base/cocoa/CCDictionary.h b/cocos/base/CCDictionary.h similarity index 99% rename from cocos/base/cocoa/CCDictionary.h rename to cocos/base/CCDictionary.h index b0f1c98a9c..63082109b3 100644 --- a/cocos/base/cocoa/CCDictionary.h +++ b/cocos/base/CCDictionary.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCDICTIONARY_H__ #define __CCDICTIONARY_H__ -#include "support/data_support/uthash.h" +#include "uthash.h" #include "CCObject.h" #include "CCArray.h" #include "CCString.h" diff --git a/cocos/base/cocoa/CCDouble.h b/cocos/base/CCDouble.h similarity index 100% rename from cocos/base/cocoa/CCDouble.h rename to cocos/base/CCDouble.h diff --git a/cocos/base/cocoa/CCFloat.h b/cocos/base/CCFloat.h similarity index 100% rename from cocos/base/cocoa/CCFloat.h rename to cocos/base/CCFloat.h diff --git a/cocos/base/cocoa/CCGeometry.cpp b/cocos/base/CCGeometry.cpp similarity index 100% rename from cocos/base/cocoa/CCGeometry.cpp rename to cocos/base/CCGeometry.cpp diff --git a/cocos/base/cocoa/CCGeometry.h b/cocos/base/CCGeometry.h similarity index 99% rename from cocos/base/cocoa/CCGeometry.h rename to cocos/base/CCGeometry.h index 47e2fdf9ac..ac9f08ec03 100644 --- a/cocos/base/cocoa/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -28,7 +28,7 @@ THE SOFTWARE. #include #include -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "CCObject.h" #include "ccMacros.h" diff --git a/cocos/base/cocoa/CCInteger.h b/cocos/base/CCInteger.h similarity index 100% rename from cocos/base/cocoa/CCInteger.h rename to cocos/base/CCInteger.h diff --git a/cocos/base/cocoa/CCNS.cpp b/cocos/base/CCNS.cpp similarity index 100% rename from cocos/base/cocoa/CCNS.cpp rename to cocos/base/CCNS.cpp diff --git a/cocos/base/cocoa/CCNS.h b/cocos/base/CCNS.h similarity index 100% rename from cocos/base/cocoa/CCNS.h rename to cocos/base/CCNS.h diff --git a/cocos/base/cocoa/CCObject.cpp b/cocos/base/CCObject.cpp similarity index 98% rename from cocos/base/cocoa/CCObject.cpp rename to cocos/base/CCObject.cpp index 13fa0e3236..75d01c5937 100644 --- a/cocos/base/cocoa/CCObject.cpp +++ b/cocos/base/CCObject.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCObject.h" #include "CCAutoreleasePool.h" #include "ccMacros.h" -#include "script_support/CCScriptSupport.h" +#include "CCScriptSupport.h" NS_CC_BEGIN diff --git a/cocos/base/cocoa/CCObject.h b/cocos/base/CCObject.h similarity index 99% rename from cocos/base/cocoa/CCObject.h rename to cocos/base/CCObject.h index 8de1ff9d8b..3c3e6c5321 100644 --- a/cocos/base/cocoa/CCObject.h +++ b/cocos/base/CCObject.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCOBJECT_H__ #define __CCOBJECT_H__ -#include "cocoa/CCDataVisitor.h" +#include "CCDataVisitor.h" #include "ccMacros.h" #ifdef EMSCRIPTEN diff --git a/cocos/base/cocoa/CCSet.cpp b/cocos/base/CCSet.cpp similarity index 100% rename from cocos/base/cocoa/CCSet.cpp rename to cocos/base/CCSet.cpp diff --git a/cocos/base/cocoa/CCSet.h b/cocos/base/CCSet.h similarity index 100% rename from cocos/base/cocoa/CCSet.h rename to cocos/base/CCSet.h diff --git a/cocos/base/cocoa/CCString.cpp b/cocos/base/CCString.cpp similarity index 100% rename from cocos/base/cocoa/CCString.cpp rename to cocos/base/CCString.cpp diff --git a/cocos/base/cocoa/CCString.h b/cocos/base/CCString.h similarity index 100% rename from cocos/base/cocoa/CCString.h rename to cocos/base/CCString.h diff --git a/cocos/base/atitc/atitc.cpp b/cocos/base/atitc.cpp similarity index 100% rename from cocos/base/atitc/atitc.cpp rename to cocos/base/atitc.cpp diff --git a/cocos/base/atitc/atitc.h b/cocos/base/atitc.h similarity index 100% rename from cocos/base/atitc/atitc.h rename to cocos/base/atitc.h diff --git a/cocos/base/etc1/etc1.cpp b/cocos/base/etc1.cpp similarity index 100% rename from cocos/base/etc1/etc1.cpp rename to cocos/base/etc1.cpp diff --git a/cocos/base/etc1/etc1.h b/cocos/base/etc1.h similarity index 100% rename from cocos/base/etc1/etc1.h rename to cocos/base/etc1.h diff --git a/cocos/base/s3tc/s3tc.cpp b/cocos/base/s3tc.cpp similarity index 100% rename from cocos/base/s3tc/s3tc.cpp rename to cocos/base/s3tc.cpp diff --git a/cocos/base/s3tc/s3tc.h b/cocos/base/s3tc.h similarity index 100% rename from cocos/base/s3tc/s3tc.h rename to cocos/base/s3tc.h diff --git a/cocos/math/kazmath/include/kazmath/GL/matrix.h b/cocos/math/kazmath/include/kazmath/GL/matrix.h index a1c95f8bf9..8b624a9868 100644 --- a/cocos/math/kazmath/include/kazmath/GL/matrix.h +++ b/cocos/math/kazmath/include/kazmath/GL/matrix.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef KM_GL_MATRIX_H_INCLUDED #define KM_GL_MATRIX_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #define KM_GL_MODELVIEW 0x1700 #define KM_GL_PROJECTION 0x1701 diff --git a/cocos/math/kazmath/include/kazmath/aabb.h b/cocos/math/kazmath/include/kazmath/aabb.h index 629889cef1..e26d9771da 100644 --- a/cocos/math/kazmath/include/kazmath/aabb.h +++ b/cocos/math/kazmath/include/kazmath/aabb.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef KAZMATH_AABB_H_INCLUDED #define KAZMATH_AABB_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "vec3.h" #include "utility.h" diff --git a/cocos/math/kazmath/include/kazmath/mat3.h b/cocos/math/kazmath/include/kazmath/mat3.h index 4d22dfb28a..fc0668b20d 100644 --- a/cocos/math/kazmath/include/kazmath/mat3.h +++ b/cocos/math/kazmath/include/kazmath/mat3.h @@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MAT3_H_INCLUDED #define MAT3_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" struct kmVec3; diff --git a/cocos/math/kazmath/include/kazmath/mat4.h b/cocos/math/kazmath/include/kazmath/mat4.h index 241a0b9ec0..f8ad019d5f 100644 --- a/cocos/math/kazmath/include/kazmath/mat4.h +++ b/cocos/math/kazmath/include/kazmath/mat4.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MAT4_H_INCLUDED #define MAT4_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" struct kmVec3; diff --git a/cocos/math/kazmath/include/kazmath/plane.h b/cocos/math/kazmath/include/kazmath/plane.h index c4e4fe5b7e..a01d5fd744 100644 --- a/cocos/math/kazmath/include/kazmath/plane.h +++ b/cocos/math/kazmath/include/kazmath/plane.h @@ -33,7 +33,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define KM_PLANE_NEAR 4 #define KM_PLANE_FAR 5 -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" struct kmVec3; diff --git a/cocos/math/kazmath/include/kazmath/quaternion.h b/cocos/math/kazmath/include/kazmath/quaternion.h index a3632f0ff9..2e9bb582c4 100644 --- a/cocos/math/kazmath/include/kazmath/quaternion.h +++ b/cocos/math/kazmath/include/kazmath/quaternion.h @@ -30,7 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern "C" { #endif -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" struct kmMat4; diff --git a/cocos/math/kazmath/include/kazmath/ray2.h b/cocos/math/kazmath/include/kazmath/ray2.h index 6734a95611..c93c3b4a4e 100644 --- a/cocos/math/kazmath/include/kazmath/ray2.h +++ b/cocos/math/kazmath/include/kazmath/ray2.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RAY_2_H #define RAY_2_H -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" #include "vec2.h" diff --git a/cocos/math/kazmath/include/kazmath/utility.h b/cocos/math/kazmath/include/kazmath/utility.h index ed6bff6854..62b196be1c 100644 --- a/cocos/math/kazmath/include/kazmath/utility.h +++ b/cocos/math/kazmath/include/kazmath/utility.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef UTILITY_H_INCLUDED #define UTILITY_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #ifndef kmScalar diff --git a/cocos/math/kazmath/include/kazmath/vec2.h b/cocos/math/kazmath/include/kazmath/vec2.h index 6c29d4005f..d8fdf82e41 100644 --- a/cocos/math/kazmath/include/kazmath/vec2.h +++ b/cocos/math/kazmath/include/kazmath/vec2.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef VEC2_H_INCLUDED #define VEC2_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" struct kmMat3; diff --git a/cocos/math/kazmath/include/kazmath/vec3.h b/cocos/math/kazmath/include/kazmath/vec3.h index eb74d41b61..d8c8641cf4 100644 --- a/cocos/math/kazmath/include/kazmath/vec3.h +++ b/cocos/math/kazmath/include/kazmath/vec3.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef VEC3_H_INCLUDED #define VEC3_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include #ifndef kmScalar diff --git a/cocos/math/kazmath/include/kazmath/vec4.h b/cocos/math/kazmath/include/kazmath/vec4.h index 7956d2a794..ffdb70423d 100644 --- a/cocos/math/kazmath/include/kazmath/vec4.h +++ b/cocos/math/kazmath/include/kazmath/vec4.h @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef VEC4_H_INCLUDED #define VEC4_H_INCLUDED -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "utility.h" struct kmMat4; diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index e477c31a01..412ec6b963 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" #include "CCPhysicsShape.h" diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 605a6dcf80..86c39a05eb 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 73383c39b6..7b78e1a089 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4915035521..6ff731f273 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 7ede980f53..1777a395f0 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -48,9 +48,9 @@ #include "Box2D/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsHelper.h" -#include "draw_nodes/CCDrawNode.h" -#include "cocoa/CCArray.h" -#include "layers_scenes_transitions_nodes/CCScene.h" +#include "CCDrawNode.h" +#include "CCArray.h" +#include "CCScene.h" #include "CCDirector.h" #include diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index d7a30f37cf..da6a7477c6 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -30,8 +30,8 @@ #include -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" +#include "CCObject.h" +#include "CCGeometry.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.h b/cocos/physics/box2d/CCPhysicsBodyInfo.h index 730837ed9d..5c89ac5f19 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo.h @@ -27,7 +27,7 @@ #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsBodyInfo diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.h b/cocos/physics/box2d/CCPhysicsContactInfo.h index b592caa0af..f1e41ef572 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo.h @@ -27,7 +27,7 @@ #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsContactInfo diff --git a/cocos/physics/box2d/CCPhysicsHelper.h b/cocos/physics/box2d/CCPhysicsHelper.h index 86ef7d74ee..61dd2b6e4c 100644 --- a/cocos/physics/box2d/CCPhysicsHelper.h +++ b/cocos/physics/box2d/CCPhysicsHelper.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_HELPER_H__ #define __CCPHYSICS_HELPER_H__ -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" +#include "CCPlatformMacros.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.h b/cocos/physics/box2d/CCPhysicsJointInfo.h index abcf089387..a60ecdb97e 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo.h @@ -27,7 +27,7 @@ #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsJointInfo diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.h b/cocos/physics/box2d/CCPhysicsShapeInfo.h index 9091001887..8608f0bad1 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo.h @@ -27,7 +27,7 @@ #ifndef __CCPHYSICS_SHAPE_INFO_H__ #define __CCPHYSICS_SHAPE_INFO_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsShapeInfo diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.h b/cocos/physics/box2d/CCPhysicsWorldInfo.h index bcc09124db..662fa19843 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo.h @@ -27,7 +27,7 @@ #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsWorldInfo diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h index 0faef2eb49..03a8e0fee4 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h @@ -28,8 +28,8 @@ #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCObject.h" +#include "CCPlatformMacros.h" +#include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo.h index 5033a2181d..6c302947b7 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo.h @@ -28,7 +28,7 @@ #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsContact; diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index a026d632b7..8c3bed53ef 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -29,8 +29,8 @@ #define __CCPHYSICS_HELPER_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" +#include "CCPlatformMacros.h" +#include "CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo.h index 47b1fc6141..9e09abf52b 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo.h @@ -28,7 +28,7 @@ #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsJointInfo diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h index 5e9f2a73e3..61da25d63b 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h @@ -31,7 +31,7 @@ #include #include #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h index 3bc0cf2bc4..71d56f0a5b 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h @@ -28,7 +28,7 @@ #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsWorldInfo diff --git a/extensions/Android.mk b/extensions/Android.mk index 8c0b1e2591..6a5bf063d7 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -6,138 +6,31 @@ LOCAL_MODULE := cocos_extension_static LOCAL_MODULE_FILENAME := libextension LOCAL_SRC_FILES := \ -CCDeprecated-ext.cpp \ -AssetsManager/AssetsManager.cpp \ -CCBReader/CCBAnimationManager.cpp \ -CCBReader/CCBFileLoader.cpp \ -CCBReader/CCBKeyframe.cpp \ -CCBReader/CCBReader.cpp \ -CCBReader/CCBSequence.cpp \ -CCBReader/CCBSequenceProperty.cpp \ -CCBReader/CCBValue.cpp \ -CCBReader/CCControlButtonLoader.cpp \ -CCBReader/CCControlLoader.cpp \ -CCBReader/CCLabelBMFontLoader.cpp \ -CCBReader/CCLabelTTFLoader.cpp \ -CCBReader/CCLayerColorLoader.cpp \ -CCBReader/CCLayerGradientLoader.cpp \ -CCBReader/CCLayerLoader.cpp \ -CCBReader/CCMenuItemImageLoader.cpp \ -CCBReader/CCMenuItemLoader.cpp \ -CCBReader/CCNode+CCBRelativePositioning.cpp \ -CCBReader/CCNodeLoader.cpp \ -CCBReader/CCNodeLoaderLibrary.cpp \ -CCBReader/CCParticleSystemQuadLoader.cpp \ -CCBReader/CCScale9SpriteLoader.cpp \ -CCBReader/CCScrollViewLoader.cpp \ -CCBReader/CCSpriteLoader.cpp \ -CocoStudio/Action/CCActionFrame.cpp \ -CocoStudio/Action/CCActionFrameEasing.cpp \ -CocoStudio/Action/CCActionManagerEx.cpp \ -CocoStudio/Action/CCActionNode.cpp \ -CocoStudio/Action/CCActionObject.cpp \ -CocoStudio/Armature/CCArmature.cpp \ -CocoStudio/Armature/CCBone.cpp \ -CocoStudio/Armature/animation/CCArmatureAnimation.cpp \ -CocoStudio/Armature/animation/CCProcessBase.cpp \ -CocoStudio/Armature/animation/CCTween.cpp \ -CocoStudio/Armature/datas/CCDatas.cpp \ -CocoStudio/Armature/display/CCBatchNode.cpp \ -CocoStudio/Armature/display/CCDecorativeDisplay.cpp \ -CocoStudio/Armature/display/CCDisplayFactory.cpp \ -CocoStudio/Armature/display/CCDisplayManager.cpp \ -CocoStudio/Armature/display/CCSkin.cpp \ -CocoStudio/Armature/physics/CCColliderDetector.cpp \ -CocoStudio/Armature/utils/CCArmatureDataManager.cpp \ -CocoStudio/Armature/utils/CCArmatureDefine.cpp \ -CocoStudio/Armature/utils/CCDataReaderHelper.cpp \ -CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.cpp \ -CocoStudio/Armature/utils/CCTransformHelp.cpp \ -CocoStudio/Armature/utils/CCTweenFunction.cpp \ -CocoStudio/Armature/utils/CCUtilMath.cpp \ -CocoStudio/Components/CCComAttribute.cpp \ -CocoStudio/Components/CCComAudio.cpp \ -CocoStudio/Components/CCComController.cpp \ -CocoStudio/Components/CCComRender.cpp \ -CocoStudio/Components/CCInputDelegate.cpp \ -CocoStudio/GUI/BaseClasses/UIRootWidget.cpp \ -CocoStudio/GUI/BaseClasses/UIWidget.cpp \ -CocoStudio/GUI/Layouts/Layout.cpp \ -CocoStudio/GUI/Layouts/LayoutParameter.cpp \ -CocoStudio/GUI/Layouts/UILayoutDefine.cpp \ -CocoStudio/GUI/System/CocosGUI.cpp \ -CocoStudio/GUI/System/UIHelper.cpp \ -CocoStudio/GUI/System/UIInputManager.cpp \ -CocoStudio/GUI/System/UILayer.cpp \ -CocoStudio/GUI/UIWidgets/UIButton.cpp \ -CocoStudio/GUI/UIWidgets/UICheckBox.cpp \ -CocoStudio/GUI/UIWidgets/UIImageView.cpp \ -CocoStudio/GUI/UIWidgets/UILabel.cpp \ -CocoStudio/GUI/UIWidgets/UILabelAtlas.cpp \ -CocoStudio/GUI/UIWidgets/UILabelBMFont.cpp \ -CocoStudio/GUI/UIWidgets/UILoadingBar.cpp \ -CocoStudio/GUI/UIWidgets/UISlider.cpp \ -CocoStudio/GUI/UIWidgets/UITextField.cpp \ -CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.cpp \ -CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.cpp \ -CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.cpp \ -CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.cpp \ -CocoStudio/Json/CSContentJsonDictionary.cpp \ -CocoStudio/Json/DictionaryHelper.cpp \ -CocoStudio/Json/lib_json/json_reader.cpp \ -CocoStudio/Json/lib_json/json_value.cpp \ -CocoStudio/Json/lib_json/json_writer.cpp \ -CocoStudio/Reader/CCSGUIReader.cpp \ -CocoStudio/Reader/CCSSceneReader.cpp \ -GUI/CCControlExtension/CCControl.cpp \ -GUI/CCControlExtension/CCControlButton.cpp \ -GUI/CCControlExtension/CCControlColourPicker.cpp \ -GUI/CCControlExtension/CCControlHuePicker.cpp \ -GUI/CCControlExtension/CCControlPotentiometer.cpp \ -GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -GUI/CCControlExtension/CCControlSlider.cpp \ -GUI/CCControlExtension/CCControlStepper.cpp \ -GUI/CCControlExtension/CCControlSwitch.cpp \ -GUI/CCControlExtension/CCControlUtils.cpp \ -GUI/CCControlExtension/CCInvocation.cpp \ -GUI/CCControlExtension/CCScale9Sprite.cpp \ -GUI/CCEditBox/CCEditBox.cpp \ -GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ -GUI/CCEditBox/CCEditBoxImplNone.cpp \ -GUI/CCEditBox/CCEditBoxImplTizen.cpp \ -GUI/CCEditBox/CCEditBoxImplWin.cpp \ -GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ -GUI/CCScrollView/CCTableView.cpp \ -GUI/CCScrollView/CCTableViewCell.cpp \ -LocalStorage/LocalStorage.cpp \ -LocalStorage/LocalStorageAndroid.cpp \ -network/HttpClient.cpp \ -network/SocketIO.cpp \ -network/WebSocket.cpp \ -physics_nodes/CCPhysicsDebugNode.cpp \ -physics_nodes/CCPhysicsSprite.cpp \ -spine/Animation.cpp \ -spine/AnimationState.cpp \ -spine/AnimationStateData.cpp \ -spine/Atlas.cpp \ -spine/AtlasAttachmentLoader.cpp \ -spine/Attachment.cpp \ -spine/AttachmentLoader.cpp \ -spine/Bone.cpp \ -spine/BoneData.cpp \ -spine/CCSkeleton.cpp \ -spine/CCSkeletonAnimation.cpp \ -spine/extension.cpp \ -spine/Json.cpp \ -spine/RegionAttachment.cpp \ -spine/Skeleton.cpp \ -spine/SkeletonData.cpp \ -spine/SkeletonJson.cpp \ -spine/Skin.cpp \ -spine/Slot.cpp \ -spine/SlotData.cpp \ -spine/spine-cocos2dx.cpp +$(LOCAL_PATH)/CCDeprecated-ext.cpp \ +$(LOCAL_PATH)/assets-manager/AssetsManager.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControl.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlButton.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlColourPicker.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlHuePicker.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlPotentiometer.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSlider.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlStepper.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSwitch.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCControlUtils.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCInvocation.cpp \ +$(LOCAL_PATH)/GUI/CCControlExtension/CCScale9Sprite.cpp \ +$(LOCAL_PATH)/GUI/CCEditBox/CCEditBox.cpp \ +$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ +$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplNone.cpp \ +$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplTizen.cpp \ +$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplWin.cpp \ +$(LOCAL_PATH)/GUI/CCScrollView/CCScrollView.cpp \ +$(LOCAL_PATH)/GUI/CCScrollView/CCSorting.cpp \ +$(LOCAL_PATH)/GUI/CCScrollView/CCTableView.cpp \ +$(LOCAL_PATH)/GUI/CCScrollView/CCTableViewCell.cpp \ +$(LOCAL_PATH)/physics-nodes/CCPhysicsDebugNode.cpp \ +$(LOCAL_PATH)/physics-nodes/CCPhysicsSprite.cpp LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static diff --git a/external/Box2D/Android.mk b/external/Box2D/Android.mk index c366750c01..5172a998e7 100644 --- a/external/Box2D/Android.mk +++ b/external/Box2D/Android.mk @@ -7,51 +7,51 @@ LOCAL_MODULE := box2d_static LOCAL_MODULE_FILENAME := libbox2d LOCAL_SRC_FILES := \ -Collision/b2BroadPhase.cpp \ -Collision/b2CollideCircle.cpp \ -Collision/b2CollideEdge.cpp \ -Collision/b2CollidePolygon.cpp \ -Collision/b2Collision.cpp \ -Collision/b2Distance.cpp \ -Collision/b2DynamicTree.cpp \ -Collision/b2TimeOfImpact.cpp \ -Collision/Shapes/b2ChainShape.cpp \ -Collision/Shapes/b2CircleShape.cpp \ -Collision/Shapes/b2EdgeShape.cpp \ -Collision/Shapes/b2PolygonShape.cpp \ -Common/b2BlockAllocator.cpp \ -Common/b2Draw.cpp \ -Common/b2Math.cpp \ -Common/b2Settings.cpp \ -Common/b2StackAllocator.cpp \ -Common/b2Timer.cpp \ -Dynamics/b2Body.cpp \ -Dynamics/b2ContactManager.cpp \ -Dynamics/b2Fixture.cpp \ -Dynamics/b2Island.cpp \ -Dynamics/b2World.cpp \ -Dynamics/b2WorldCallbacks.cpp \ -Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -Dynamics/Contacts/b2CircleContact.cpp \ -Dynamics/Contacts/b2Contact.cpp \ -Dynamics/Contacts/b2ContactSolver.cpp \ -Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -Dynamics/Contacts/b2PolygonContact.cpp \ -Dynamics/Joints/b2DistanceJoint.cpp \ -Dynamics/Joints/b2FrictionJoint.cpp \ -Dynamics/Joints/b2GearJoint.cpp \ -Dynamics/Joints/b2Joint.cpp \ -Dynamics/Joints/b2MouseJoint.cpp \ -Dynamics/Joints/b2PrismaticJoint.cpp \ -Dynamics/Joints/b2PulleyJoint.cpp \ -Dynamics/Joints/b2RevoluteJoint.cpp \ -Dynamics/Joints/b2RopeJoint.cpp \ -Dynamics/Joints/b2WeldJoint.cpp \ -Dynamics/Joints/b2WheelJoint.cpp \ -Rope/b2Rope.cpp +$(LOCAL_PATH)/Collision/b2BroadPhase.cpp \ +$(LOCAL_PATH)/Collision/b2CollideCircle.cpp \ +$(LOCAL_PATH)/Collision/b2CollideEdge.cpp \ +$(LOCAL_PATH)/Collision/b2CollidePolygon.cpp \ +$(LOCAL_PATH)/Collision/b2Collision.cpp \ +$(LOCAL_PATH)/Collision/b2Distance.cpp \ +$(LOCAL_PATH)/Collision/b2DynamicTree.cpp \ +$(LOCAL_PATH)/Collision/b2TimeOfImpact.cpp \ +$(LOCAL_PATH)/Collision/Shapes/b2ChainShape.cpp \ +$(LOCAL_PATH)/Collision/Shapes/b2CircleShape.cpp \ +$(LOCAL_PATH)/Collision/Shapes/b2EdgeShape.cpp \ +$(LOCAL_PATH)/Collision/Shapes/b2PolygonShape.cpp \ +$(LOCAL_PATH)/Common/b2BlockAllocator.cpp \ +$(LOCAL_PATH)/Common/b2Draw.cpp \ +$(LOCAL_PATH)/Common/b2Math.cpp \ +$(LOCAL_PATH)/Common/b2Settings.cpp \ +$(LOCAL_PATH)/Common/b2StackAllocator.cpp \ +$(LOCAL_PATH)/Common/b2Timer.cpp \ +$(LOCAL_PATH)/Dynamics/b2Body.cpp \ +$(LOCAL_PATH)/Dynamics/b2ContactManager.cpp \ +$(LOCAL_PATH)/Dynamics/b2Fixture.cpp \ +$(LOCAL_PATH)/Dynamics/b2Island.cpp \ +$(LOCAL_PATH)/Dynamics/b2World.cpp \ +$(LOCAL_PATH)/Dynamics/b2WorldCallbacks.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2CircleContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2Contact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2ContactSolver.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +$(LOCAL_PATH)/Dynamics/Contacts/b2PolygonContact.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2DistanceJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2FrictionJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2GearJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2Joint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2MouseJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2PrismaticJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2PulleyJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2RevoluteJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2RopeJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2WeldJoint.cpp \ +$(LOCAL_PATH)/Dynamics/Joints/b2WheelJoint.cpp \ +$(LOCAL_PATH)/Rope/b2Rope.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. diff --git a/external/chipmunk/Android.mk b/external/chipmunk/Android.mk index e8441cd0d7..e8013df8c3 100644 --- a/external/chipmunk/Android.mk +++ b/external/chipmunk/Android.mk @@ -7,35 +7,35 @@ LOCAL_MODULE := chipmunk_static LOCAL_MODULE_FILENAME := libchipmunk LOCAL_SRC_FILES := \ -src/chipmunk.c \ -src/cpArbiter.c \ -src/cpArray.c \ -src/cpBB.c \ -src/cpBBTree.c \ -src/cpBody.c \ -src/cpCollision.c \ -src/cpHashSet.c \ -src/cpPolyShape.c \ -src/cpShape.c \ -src/cpSpace.c \ -src/cpSpaceComponent.c \ -src/cpSpaceHash.c \ -src/cpSpaceQuery.c \ -src/cpSpaceStep.c \ -src/cpSpatialIndex.c \ -src/cpSweep1D.c \ -src/cpVect.c \ -src/constraints/cpConstraint.c \ -src/constraints/cpDampedRotarySpring.c \ -src/constraints/cpDampedSpring.c \ -src/constraints/cpGearJoint.c \ -src/constraints/cpGrooveJoint.c \ -src/constraints/cpPinJoint.c \ -src/constraints/cpPivotJoint.c \ -src/constraints/cpRatchetJoint.c \ -src/constraints/cpRotaryLimitJoint.c \ -src/constraints/cpSimpleMotor.c \ -src/constraints/cpSlideJoint.c +$(LOCAL_PATH)/src/chipmunk.c \ +$(LOCAL_PATH)/src/cpArbiter.c \ +$(LOCAL_PATH)/src/cpArray.c \ +$(LOCAL_PATH)/src/cpBB.c \ +$(LOCAL_PATH)/src/cpBBTree.c \ +$(LOCAL_PATH)/src/cpBody.c \ +$(LOCAL_PATH)/src/cpCollision.c \ +$(LOCAL_PATH)/src/cpHashSet.c \ +$(LOCAL_PATH)/src/cpPolyShape.c \ +$(LOCAL_PATH)/src/cpShape.c \ +$(LOCAL_PATH)/src/cpSpace.c \ +$(LOCAL_PATH)/src/cpSpaceComponent.c \ +$(LOCAL_PATH)/src/cpSpaceHash.c \ +$(LOCAL_PATH)/src/cpSpaceQuery.c \ +$(LOCAL_PATH)/src/cpSpaceStep.c \ +$(LOCAL_PATH)/src/cpSpatialIndex.c \ +$(LOCAL_PATH)/src/cpSweep1D.c \ +$(LOCAL_PATH)/src/cpVect.c \ +$(LOCAL_PATH)/src/constraints/cpConstraint.c \ +$(LOCAL_PATH)/src/constraints/cpDampedRotarySpring.c \ +$(LOCAL_PATH)/src/constraints/cpDampedSpring.c \ +$(LOCAL_PATH)/src/constraints/cpGearJoint.c \ +$(LOCAL_PATH)/src/constraints/cpGrooveJoint.c \ +$(LOCAL_PATH)/src/constraints/cpPinJoint.c \ +$(LOCAL_PATH)/src/constraints/cpPivotJoint.c \ +$(LOCAL_PATH)/src/constraints/cpRatchetJoint.c \ +$(LOCAL_PATH)/src/constraints/cpRotaryLimitJoint.c \ +$(LOCAL_PATH)/src/constraints/cpSimpleMotor.c \ +$(LOCAL_PATH)/src/constraints/cpSlideJoint.c LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk diff --git a/external/curl/include/andorid/curl.h b/external/curl/include/android/curl.h similarity index 100% rename from external/curl/include/andorid/curl.h rename to external/curl/include/android/curl.h diff --git a/external/curl/include/andorid/curlbuild.h b/external/curl/include/android/curlbuild.h similarity index 100% rename from external/curl/include/andorid/curlbuild.h rename to external/curl/include/android/curlbuild.h diff --git a/external/curl/include/andorid/curlrules.h b/external/curl/include/android/curlrules.h similarity index 100% rename from external/curl/include/andorid/curlrules.h rename to external/curl/include/android/curlrules.h diff --git a/external/curl/include/andorid/curlver.h b/external/curl/include/android/curlver.h similarity index 100% rename from external/curl/include/andorid/curlver.h rename to external/curl/include/android/curlver.h diff --git a/external/curl/include/andorid/easy.h b/external/curl/include/android/easy.h similarity index 100% rename from external/curl/include/andorid/easy.h rename to external/curl/include/android/easy.h diff --git a/external/curl/include/andorid/mprintf.h b/external/curl/include/android/mprintf.h similarity index 100% rename from external/curl/include/andorid/mprintf.h rename to external/curl/include/android/mprintf.h diff --git a/external/curl/include/andorid/multi.h b/external/curl/include/android/multi.h similarity index 100% rename from external/curl/include/andorid/multi.h rename to external/curl/include/android/multi.h diff --git a/external/curl/include/andorid/stdcheaders.h b/external/curl/include/android/stdcheaders.h similarity index 100% rename from external/curl/include/andorid/stdcheaders.h rename to external/curl/include/android/stdcheaders.h diff --git a/external/curl/include/andorid/typecheck-gcc.h b/external/curl/include/android/typecheck-gcc.h similarity index 100% rename from external/curl/include/andorid/typecheck-gcc.h rename to external/curl/include/android/typecheck-gcc.h diff --git a/external/curl/include/andorid/types.h b/external/curl/include/android/types.h similarity index 100% rename from external/curl/include/andorid/types.h rename to external/curl/include/android/types.h diff --git a/external/curl/prebuilt/andorid/Android.mk b/external/curl/prebuilt/android/Android.mk similarity index 57% rename from external/curl/prebuilt/andorid/Android.mk rename to external/curl/prebuilt/android/Android.mk index 8d0c18d79f..daa087ec8e 100644 --- a/external/curl/prebuilt/andorid/Android.mk +++ b/external/curl/prebuilt/android/Android.mk @@ -3,6 +3,6 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_curl_static LOCAL_MODULE_FILENAME := curl -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libcurl.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcurl.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/curl/prebuilt/andorid/armeabi-v7a/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id similarity index 100% rename from external/curl/prebuilt/andorid/armeabi-v7a/libcurl.a.REMOVED.git-id rename to external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id diff --git a/external/curl/prebuilt/andorid/armeabi/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/android/armeabi/libcurl.a.REMOVED.git-id similarity index 100% rename from external/curl/prebuilt/andorid/armeabi/libcurl.a.REMOVED.git-id rename to external/curl/prebuilt/android/armeabi/libcurl.a.REMOVED.git-id diff --git a/external/curl/prebuilt/andorid/x86/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/android/x86/libcurl.a.REMOVED.git-id similarity index 100% rename from external/curl/prebuilt/andorid/x86/libcurl.a.REMOVED.git-id rename to external/curl/prebuilt/android/x86/libcurl.a.REMOVED.git-id diff --git a/external/freetype2/include/andorid/freetype2/freetype/config/ftconfig.h b/external/freetype2/include/android/freetype2/freetype/config/ftconfig.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/config/ftconfig.h rename to external/freetype2/include/android/freetype2/freetype/config/ftconfig.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/config/ftheader.h b/external/freetype2/include/android/freetype2/freetype/config/ftheader.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/config/ftheader.h rename to external/freetype2/include/android/freetype2/freetype/config/ftheader.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/config/ftmodule.h b/external/freetype2/include/android/freetype2/freetype/config/ftmodule.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/config/ftmodule.h rename to external/freetype2/include/android/freetype2/freetype/config/ftmodule.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/config/ftoption.h b/external/freetype2/include/android/freetype2/freetype/config/ftoption.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/config/ftoption.h rename to external/freetype2/include/android/freetype2/freetype/config/ftoption.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/config/ftstdlib.h b/external/freetype2/include/android/freetype2/freetype/config/ftstdlib.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/config/ftstdlib.h rename to external/freetype2/include/android/freetype2/freetype/config/ftstdlib.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/freetype.h.REMOVED.git-id b/external/freetype2/include/android/freetype2/freetype/freetype.h.REMOVED.git-id similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/freetype.h.REMOVED.git-id rename to external/freetype2/include/android/freetype2/freetype/freetype.h.REMOVED.git-id diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftadvanc.h b/external/freetype2/include/android/freetype2/freetype/ftadvanc.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftadvanc.h rename to external/freetype2/include/android/freetype2/freetype/ftadvanc.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftautoh.h b/external/freetype2/include/android/freetype2/freetype/ftautoh.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftautoh.h rename to external/freetype2/include/android/freetype2/freetype/ftautoh.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftbbox.h b/external/freetype2/include/android/freetype2/freetype/ftbbox.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftbbox.h rename to external/freetype2/include/android/freetype2/freetype/ftbbox.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftbdf.h b/external/freetype2/include/android/freetype2/freetype/ftbdf.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftbdf.h rename to external/freetype2/include/android/freetype2/freetype/ftbdf.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftbitmap.h b/external/freetype2/include/android/freetype2/freetype/ftbitmap.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftbitmap.h rename to external/freetype2/include/android/freetype2/freetype/ftbitmap.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftbzip2.h b/external/freetype2/include/android/freetype2/freetype/ftbzip2.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftbzip2.h rename to external/freetype2/include/android/freetype2/freetype/ftbzip2.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftcache.h b/external/freetype2/include/android/freetype2/freetype/ftcache.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftcache.h rename to external/freetype2/include/android/freetype2/freetype/ftcache.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftcffdrv.h b/external/freetype2/include/android/freetype2/freetype/ftcffdrv.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftcffdrv.h rename to external/freetype2/include/android/freetype2/freetype/ftcffdrv.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftchapters.h b/external/freetype2/include/android/freetype2/freetype/ftchapters.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftchapters.h rename to external/freetype2/include/android/freetype2/freetype/ftchapters.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftcid.h b/external/freetype2/include/android/freetype2/freetype/ftcid.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftcid.h rename to external/freetype2/include/android/freetype2/freetype/ftcid.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/fterrdef.h b/external/freetype2/include/android/freetype2/freetype/fterrdef.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/fterrdef.h rename to external/freetype2/include/android/freetype2/freetype/fterrdef.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/fterrors.h b/external/freetype2/include/android/freetype2/freetype/fterrors.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/fterrors.h rename to external/freetype2/include/android/freetype2/freetype/fterrors.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftgasp.h b/external/freetype2/include/android/freetype2/freetype/ftgasp.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftgasp.h rename to external/freetype2/include/android/freetype2/freetype/ftgasp.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftglyph.h b/external/freetype2/include/android/freetype2/freetype/ftglyph.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftglyph.h rename to external/freetype2/include/android/freetype2/freetype/ftglyph.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftgxval.h b/external/freetype2/include/android/freetype2/freetype/ftgxval.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftgxval.h rename to external/freetype2/include/android/freetype2/freetype/ftgxval.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftgzip.h b/external/freetype2/include/android/freetype2/freetype/ftgzip.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftgzip.h rename to external/freetype2/include/android/freetype2/freetype/ftgzip.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftimage.h b/external/freetype2/include/android/freetype2/freetype/ftimage.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftimage.h rename to external/freetype2/include/android/freetype2/freetype/ftimage.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftincrem.h b/external/freetype2/include/android/freetype2/freetype/ftincrem.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftincrem.h rename to external/freetype2/include/android/freetype2/freetype/ftincrem.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftlcdfil.h b/external/freetype2/include/android/freetype2/freetype/ftlcdfil.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftlcdfil.h rename to external/freetype2/include/android/freetype2/freetype/ftlcdfil.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftlist.h b/external/freetype2/include/android/freetype2/freetype/ftlist.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftlist.h rename to external/freetype2/include/android/freetype2/freetype/ftlist.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftlzw.h b/external/freetype2/include/android/freetype2/freetype/ftlzw.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftlzw.h rename to external/freetype2/include/android/freetype2/freetype/ftlzw.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftmac.h b/external/freetype2/include/android/freetype2/freetype/ftmac.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftmac.h rename to external/freetype2/include/android/freetype2/freetype/ftmac.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftmm.h b/external/freetype2/include/android/freetype2/freetype/ftmm.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftmm.h rename to external/freetype2/include/android/freetype2/freetype/ftmm.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftmodapi.h b/external/freetype2/include/android/freetype2/freetype/ftmodapi.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftmodapi.h rename to external/freetype2/include/android/freetype2/freetype/ftmodapi.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftmoderr.h b/external/freetype2/include/android/freetype2/freetype/ftmoderr.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftmoderr.h rename to external/freetype2/include/android/freetype2/freetype/ftmoderr.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftotval.h b/external/freetype2/include/android/freetype2/freetype/ftotval.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftotval.h rename to external/freetype2/include/android/freetype2/freetype/ftotval.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftoutln.h b/external/freetype2/include/android/freetype2/freetype/ftoutln.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftoutln.h rename to external/freetype2/include/android/freetype2/freetype/ftoutln.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftpfr.h b/external/freetype2/include/android/freetype2/freetype/ftpfr.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftpfr.h rename to external/freetype2/include/android/freetype2/freetype/ftpfr.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftrender.h b/external/freetype2/include/android/freetype2/freetype/ftrender.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftrender.h rename to external/freetype2/include/android/freetype2/freetype/ftrender.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftsizes.h b/external/freetype2/include/android/freetype2/freetype/ftsizes.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftsizes.h rename to external/freetype2/include/android/freetype2/freetype/ftsizes.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftsnames.h b/external/freetype2/include/android/freetype2/freetype/ftsnames.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftsnames.h rename to external/freetype2/include/android/freetype2/freetype/ftsnames.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftstroke.h b/external/freetype2/include/android/freetype2/freetype/ftstroke.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftstroke.h rename to external/freetype2/include/android/freetype2/freetype/ftstroke.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftsynth.h b/external/freetype2/include/android/freetype2/freetype/ftsynth.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftsynth.h rename to external/freetype2/include/android/freetype2/freetype/ftsynth.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftsystem.h b/external/freetype2/include/android/freetype2/freetype/ftsystem.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftsystem.h rename to external/freetype2/include/android/freetype2/freetype/ftsystem.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/fttrigon.h b/external/freetype2/include/android/freetype2/freetype/fttrigon.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/fttrigon.h rename to external/freetype2/include/android/freetype2/freetype/fttrigon.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftttdrv.h b/external/freetype2/include/android/freetype2/freetype/ftttdrv.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftttdrv.h rename to external/freetype2/include/android/freetype2/freetype/ftttdrv.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/fttypes.h b/external/freetype2/include/android/freetype2/freetype/fttypes.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/fttypes.h rename to external/freetype2/include/android/freetype2/freetype/fttypes.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftwinfnt.h b/external/freetype2/include/android/freetype2/freetype/ftwinfnt.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftwinfnt.h rename to external/freetype2/include/android/freetype2/freetype/ftwinfnt.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ftxf86.h b/external/freetype2/include/android/freetype2/freetype/ftxf86.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ftxf86.h rename to external/freetype2/include/android/freetype2/freetype/ftxf86.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/t1tables.h b/external/freetype2/include/android/freetype2/freetype/t1tables.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/t1tables.h rename to external/freetype2/include/android/freetype2/freetype/t1tables.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ttnameid.h b/external/freetype2/include/android/freetype2/freetype/ttnameid.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ttnameid.h rename to external/freetype2/include/android/freetype2/freetype/ttnameid.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/tttables.h b/external/freetype2/include/android/freetype2/freetype/tttables.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/tttables.h rename to external/freetype2/include/android/freetype2/freetype/tttables.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/tttags.h b/external/freetype2/include/android/freetype2/freetype/tttags.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/tttags.h rename to external/freetype2/include/android/freetype2/freetype/tttags.h diff --git a/external/freetype2/include/andorid/freetype2/freetype/ttunpat.h b/external/freetype2/include/android/freetype2/freetype/ttunpat.h similarity index 100% rename from external/freetype2/include/andorid/freetype2/freetype/ttunpat.h rename to external/freetype2/include/android/freetype2/freetype/ttunpat.h diff --git a/external/freetype2/include/andorid/ft2build.h b/external/freetype2/include/android/ft2build.h similarity index 100% rename from external/freetype2/include/andorid/ft2build.h rename to external/freetype2/include/android/ft2build.h diff --git a/external/freetype2/prebuilt/andorid/Android.mk b/external/freetype2/prebuilt/android/Android.mk similarity index 50% rename from external/freetype2/prebuilt/andorid/Android.mk rename to external/freetype2/prebuilt/android/Android.mk index 3a4dee0520..958d27f3a0 100644 --- a/external/freetype2/prebuilt/andorid/Android.mk +++ b/external/freetype2/prebuilt/android/Android.mk @@ -3,6 +3,6 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_freetype2_static LOCAL_MODULE_FILENAME := freetype2 -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libfreetype.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/include/freetype2 +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libfreetype.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android $(LOCAL_PATH)/../../include/android/freetype2 include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/freetype2/prebuilt/andorid/armeabi-v7a/libfreetype.a.REMOVED.git-id b/external/freetype2/prebuilt/android/armeabi-v7a/libfreetype.a.REMOVED.git-id similarity index 100% rename from external/freetype2/prebuilt/andorid/armeabi-v7a/libfreetype.a.REMOVED.git-id rename to external/freetype2/prebuilt/android/armeabi-v7a/libfreetype.a.REMOVED.git-id diff --git a/external/freetype2/prebuilt/andorid/armeabi/libfreetype.a.REMOVED.git-id b/external/freetype2/prebuilt/android/armeabi/libfreetype.a.REMOVED.git-id similarity index 100% rename from external/freetype2/prebuilt/andorid/armeabi/libfreetype.a.REMOVED.git-id rename to external/freetype2/prebuilt/android/armeabi/libfreetype.a.REMOVED.git-id diff --git a/external/freetype2/prebuilt/andorid/x86/libfreetype.a.REMOVED.git-id b/external/freetype2/prebuilt/android/x86/libfreetype.a.REMOVED.git-id similarity index 100% rename from external/freetype2/prebuilt/andorid/x86/libfreetype.a.REMOVED.git-id rename to external/freetype2/prebuilt/android/x86/libfreetype.a.REMOVED.git-id diff --git a/external/jpeg/include/andorid/jconfig.h b/external/jpeg/include/android/jconfig.h similarity index 100% rename from external/jpeg/include/andorid/jconfig.h rename to external/jpeg/include/android/jconfig.h diff --git a/external/jpeg/include/andorid/jerror.h b/external/jpeg/include/android/jerror.h similarity index 100% rename from external/jpeg/include/andorid/jerror.h rename to external/jpeg/include/android/jerror.h diff --git a/external/jpeg/include/andorid/jmorecfg.h b/external/jpeg/include/android/jmorecfg.h similarity index 100% rename from external/jpeg/include/andorid/jmorecfg.h rename to external/jpeg/include/android/jmorecfg.h diff --git a/external/jpeg/include/andorid/jpeglib.h b/external/jpeg/include/android/jpeglib.h similarity index 100% rename from external/jpeg/include/andorid/jpeglib.h rename to external/jpeg/include/android/jpeglib.h diff --git a/external/jpeg/prebuilt/andorid/Android.mk b/external/jpeg/prebuilt/android/Android.mk similarity index 57% rename from external/jpeg/prebuilt/andorid/Android.mk rename to external/jpeg/prebuilt/android/Android.mk index b8786d07df..74af61ea2a 100644 --- a/external/jpeg/prebuilt/andorid/Android.mk +++ b/external/jpeg/prebuilt/android/Android.mk @@ -3,6 +3,6 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_jpeg_static LOCAL_MODULE_FILENAME := jpeg -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libjpeg.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libjpeg.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/jpeg/prebuilt/andorid/armeabi-v7a/libjpeg.a.REMOVED.git-id b/external/jpeg/prebuilt/android/armeabi-v7a/libjpeg.a.REMOVED.git-id similarity index 100% rename from external/jpeg/prebuilt/andorid/armeabi-v7a/libjpeg.a.REMOVED.git-id rename to external/jpeg/prebuilt/android/armeabi-v7a/libjpeg.a.REMOVED.git-id diff --git a/external/jpeg/prebuilt/andorid/armeabi/libjpeg.a.REMOVED.git-id b/external/jpeg/prebuilt/android/armeabi/libjpeg.a.REMOVED.git-id similarity index 100% rename from external/jpeg/prebuilt/andorid/armeabi/libjpeg.a.REMOVED.git-id rename to external/jpeg/prebuilt/android/armeabi/libjpeg.a.REMOVED.git-id diff --git a/external/jpeg/prebuilt/andorid/x86/libjpeg.a.REMOVED.git-id b/external/jpeg/prebuilt/android/x86/libjpeg.a.REMOVED.git-id similarity index 100% rename from external/jpeg/prebuilt/andorid/x86/libjpeg.a.REMOVED.git-id rename to external/jpeg/prebuilt/android/x86/libjpeg.a.REMOVED.git-id diff --git a/external/png/include/andorid/png.h.REMOVED.git-id b/external/png/include/android/png.h.REMOVED.git-id similarity index 100% rename from external/png/include/andorid/png.h.REMOVED.git-id rename to external/png/include/android/png.h.REMOVED.git-id diff --git a/external/png/include/andorid/pngconf.h b/external/png/include/android/pngconf.h similarity index 100% rename from external/png/include/andorid/pngconf.h rename to external/png/include/android/pngconf.h diff --git a/external/png/include/andorid/pnglibconf.h b/external/png/include/android/pnglibconf.h similarity index 100% rename from external/png/include/andorid/pnglibconf.h rename to external/png/include/android/pnglibconf.h diff --git a/external/png/prebuilt/andorid/Android.mk b/external/png/prebuilt/android/Android.mk similarity index 58% rename from external/png/prebuilt/andorid/Android.mk rename to external/png/prebuilt/android/Android.mk index b15dc34b96..41a0f91322 100644 --- a/external/png/prebuilt/andorid/Android.mk +++ b/external/png/prebuilt/android/Android.mk @@ -3,6 +3,6 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_libpng_static LOCAL_MODULE_FILENAME := png -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libpng.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libpng.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/png/prebuilt/andorid/armeabi-v7a/libpng.a.REMOVED.git-id b/external/png/prebuilt/android/armeabi-v7a/libpng.a.REMOVED.git-id similarity index 100% rename from external/png/prebuilt/andorid/armeabi-v7a/libpng.a.REMOVED.git-id rename to external/png/prebuilt/android/armeabi-v7a/libpng.a.REMOVED.git-id diff --git a/external/png/prebuilt/andorid/armeabi/libpng.a.REMOVED.git-id b/external/png/prebuilt/android/armeabi/libpng.a.REMOVED.git-id similarity index 100% rename from external/png/prebuilt/andorid/armeabi/libpng.a.REMOVED.git-id rename to external/png/prebuilt/android/armeabi/libpng.a.REMOVED.git-id diff --git a/external/png/prebuilt/andorid/x86/libpng.a.REMOVED.git-id b/external/png/prebuilt/android/x86/libpng.a.REMOVED.git-id similarity index 100% rename from external/png/prebuilt/andorid/x86/libpng.a.REMOVED.git-id rename to external/png/prebuilt/android/x86/libpng.a.REMOVED.git-id diff --git a/external/spidermonkey/include/andorid/js-config.h b/external/spidermonkey/include/android/js-config.h similarity index 100% rename from external/spidermonkey/include/andorid/js-config.h rename to external/spidermonkey/include/android/js-config.h diff --git a/external/spidermonkey/include/andorid/js.msg b/external/spidermonkey/include/android/js.msg similarity index 100% rename from external/spidermonkey/include/andorid/js.msg rename to external/spidermonkey/include/android/js.msg diff --git a/external/spidermonkey/include/andorid/js/Anchor.h b/external/spidermonkey/include/android/js/Anchor.h similarity index 100% rename from external/spidermonkey/include/andorid/js/Anchor.h rename to external/spidermonkey/include/android/js/Anchor.h diff --git a/external/spidermonkey/include/andorid/js/CallArgs.h b/external/spidermonkey/include/android/js/CallArgs.h similarity index 100% rename from external/spidermonkey/include/andorid/js/CallArgs.h rename to external/spidermonkey/include/android/js/CallArgs.h diff --git a/external/spidermonkey/include/andorid/js/CharacterEncoding.h b/external/spidermonkey/include/android/js/CharacterEncoding.h similarity index 100% rename from external/spidermonkey/include/andorid/js/CharacterEncoding.h rename to external/spidermonkey/include/android/js/CharacterEncoding.h diff --git a/external/spidermonkey/include/andorid/js/Date.h b/external/spidermonkey/include/android/js/Date.h similarity index 100% rename from external/spidermonkey/include/andorid/js/Date.h rename to external/spidermonkey/include/android/js/Date.h diff --git a/external/spidermonkey/include/andorid/js/GCAPI.h b/external/spidermonkey/include/android/js/GCAPI.h similarity index 100% rename from external/spidermonkey/include/andorid/js/GCAPI.h rename to external/spidermonkey/include/android/js/GCAPI.h diff --git a/external/spidermonkey/include/andorid/js/HashTable.h b/external/spidermonkey/include/android/js/HashTable.h similarity index 100% rename from external/spidermonkey/include/andorid/js/HashTable.h rename to external/spidermonkey/include/android/js/HashTable.h diff --git a/external/spidermonkey/include/andorid/js/HeapAPI.h b/external/spidermonkey/include/android/js/HeapAPI.h similarity index 100% rename from external/spidermonkey/include/andorid/js/HeapAPI.h rename to external/spidermonkey/include/android/js/HeapAPI.h diff --git a/external/spidermonkey/include/andorid/js/LegacyIntTypes.h b/external/spidermonkey/include/android/js/LegacyIntTypes.h similarity index 100% rename from external/spidermonkey/include/andorid/js/LegacyIntTypes.h rename to external/spidermonkey/include/android/js/LegacyIntTypes.h diff --git a/external/spidermonkey/include/andorid/js/MemoryMetrics.h b/external/spidermonkey/include/android/js/MemoryMetrics.h similarity index 100% rename from external/spidermonkey/include/andorid/js/MemoryMetrics.h rename to external/spidermonkey/include/android/js/MemoryMetrics.h diff --git a/external/spidermonkey/include/andorid/js/PropertyKey.h b/external/spidermonkey/include/android/js/PropertyKey.h similarity index 100% rename from external/spidermonkey/include/andorid/js/PropertyKey.h rename to external/spidermonkey/include/android/js/PropertyKey.h diff --git a/external/spidermonkey/include/andorid/js/RequiredDefines.h b/external/spidermonkey/include/android/js/RequiredDefines.h similarity index 100% rename from external/spidermonkey/include/andorid/js/RequiredDefines.h rename to external/spidermonkey/include/android/js/RequiredDefines.h diff --git a/external/spidermonkey/include/andorid/js/RootingAPI.h b/external/spidermonkey/include/android/js/RootingAPI.h similarity index 100% rename from external/spidermonkey/include/andorid/js/RootingAPI.h rename to external/spidermonkey/include/android/js/RootingAPI.h diff --git a/external/spidermonkey/include/andorid/js/TemplateLib.h b/external/spidermonkey/include/android/js/TemplateLib.h similarity index 100% rename from external/spidermonkey/include/andorid/js/TemplateLib.h rename to external/spidermonkey/include/android/js/TemplateLib.h diff --git a/external/spidermonkey/include/andorid/js/Utility.h b/external/spidermonkey/include/android/js/Utility.h similarity index 100% rename from external/spidermonkey/include/andorid/js/Utility.h rename to external/spidermonkey/include/android/js/Utility.h diff --git a/external/spidermonkey/include/andorid/js/Value.h b/external/spidermonkey/include/android/js/Value.h similarity index 100% rename from external/spidermonkey/include/andorid/js/Value.h rename to external/spidermonkey/include/android/js/Value.h diff --git a/external/spidermonkey/include/andorid/js/Vector.h b/external/spidermonkey/include/android/js/Vector.h similarity index 100% rename from external/spidermonkey/include/andorid/js/Vector.h rename to external/spidermonkey/include/android/js/Vector.h diff --git a/external/spidermonkey/include/andorid/jsalloc.h b/external/spidermonkey/include/android/jsalloc.h similarity index 100% rename from external/spidermonkey/include/andorid/jsalloc.h rename to external/spidermonkey/include/android/jsalloc.h diff --git a/external/spidermonkey/include/andorid/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id similarity index 100% rename from external/spidermonkey/include/andorid/jsapi.h.REMOVED.git-id rename to external/spidermonkey/include/android/jsapi.h.REMOVED.git-id diff --git a/external/spidermonkey/include/andorid/jsclass.h b/external/spidermonkey/include/android/jsclass.h similarity index 100% rename from external/spidermonkey/include/andorid/jsclass.h rename to external/spidermonkey/include/android/jsclass.h diff --git a/external/spidermonkey/include/andorid/jsclist.h b/external/spidermonkey/include/android/jsclist.h similarity index 100% rename from external/spidermonkey/include/andorid/jsclist.h rename to external/spidermonkey/include/android/jsclist.h diff --git a/external/spidermonkey/include/andorid/jscpucfg.h b/external/spidermonkey/include/android/jscpucfg.h similarity index 100% rename from external/spidermonkey/include/andorid/jscpucfg.h rename to external/spidermonkey/include/android/jscpucfg.h diff --git a/external/spidermonkey/include/andorid/jsdbgapi.h b/external/spidermonkey/include/android/jsdbgapi.h similarity index 100% rename from external/spidermonkey/include/andorid/jsdbgapi.h rename to external/spidermonkey/include/android/jsdbgapi.h diff --git a/external/spidermonkey/include/andorid/jsdhash.h b/external/spidermonkey/include/android/jsdhash.h similarity index 100% rename from external/spidermonkey/include/andorid/jsdhash.h rename to external/spidermonkey/include/android/jsdhash.h diff --git a/external/spidermonkey/include/andorid/jsfriendapi.h b/external/spidermonkey/include/android/jsfriendapi.h similarity index 100% rename from external/spidermonkey/include/andorid/jsfriendapi.h rename to external/spidermonkey/include/android/jsfriendapi.h diff --git a/external/spidermonkey/include/andorid/jslock.h b/external/spidermonkey/include/android/jslock.h similarity index 100% rename from external/spidermonkey/include/andorid/jslock.h rename to external/spidermonkey/include/android/jslock.h diff --git a/external/spidermonkey/include/andorid/json.h b/external/spidermonkey/include/android/json.h similarity index 100% rename from external/spidermonkey/include/andorid/json.h rename to external/spidermonkey/include/android/json.h diff --git a/external/spidermonkey/include/andorid/jsperf.h b/external/spidermonkey/include/android/jsperf.h similarity index 100% rename from external/spidermonkey/include/andorid/jsperf.h rename to external/spidermonkey/include/android/jsperf.h diff --git a/external/spidermonkey/include/andorid/jsprf.h b/external/spidermonkey/include/android/jsprf.h similarity index 100% rename from external/spidermonkey/include/andorid/jsprf.h rename to external/spidermonkey/include/android/jsprf.h diff --git a/external/spidermonkey/include/andorid/jsprototypes.h b/external/spidermonkey/include/android/jsprototypes.h similarity index 100% rename from external/spidermonkey/include/andorid/jsprototypes.h rename to external/spidermonkey/include/android/jsprototypes.h diff --git a/external/spidermonkey/include/andorid/jsproxy.h b/external/spidermonkey/include/android/jsproxy.h similarity index 100% rename from external/spidermonkey/include/andorid/jsproxy.h rename to external/spidermonkey/include/android/jsproxy.h diff --git a/external/spidermonkey/include/andorid/jsprvtd.h b/external/spidermonkey/include/android/jsprvtd.h similarity index 100% rename from external/spidermonkey/include/andorid/jsprvtd.h rename to external/spidermonkey/include/android/jsprvtd.h diff --git a/external/spidermonkey/include/andorid/jspubtd.h b/external/spidermonkey/include/android/jspubtd.h similarity index 100% rename from external/spidermonkey/include/andorid/jspubtd.h rename to external/spidermonkey/include/android/jspubtd.h diff --git a/external/spidermonkey/include/andorid/jstypes.h b/external/spidermonkey/include/android/jstypes.h similarity index 100% rename from external/spidermonkey/include/andorid/jstypes.h rename to external/spidermonkey/include/android/jstypes.h diff --git a/external/spidermonkey/include/andorid/jsutil.h b/external/spidermonkey/include/android/jsutil.h similarity index 100% rename from external/spidermonkey/include/andorid/jsutil.h rename to external/spidermonkey/include/android/jsutil.h diff --git a/external/spidermonkey/include/andorid/jsversion.h b/external/spidermonkey/include/android/jsversion.h similarity index 100% rename from external/spidermonkey/include/andorid/jsversion.h rename to external/spidermonkey/include/android/jsversion.h diff --git a/external/spidermonkey/include/andorid/jswrapper.h b/external/spidermonkey/include/android/jswrapper.h similarity index 100% rename from external/spidermonkey/include/andorid/jswrapper.h rename to external/spidermonkey/include/android/jswrapper.h diff --git a/external/spidermonkey/include/andorid/mozilla/Assertions.h b/external/spidermonkey/include/android/mozilla/Assertions.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Assertions.h rename to external/spidermonkey/include/android/mozilla/Assertions.h diff --git a/external/spidermonkey/include/andorid/mozilla/Attributes.h b/external/spidermonkey/include/android/mozilla/Attributes.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Attributes.h rename to external/spidermonkey/include/android/mozilla/Attributes.h diff --git a/external/spidermonkey/include/andorid/mozilla/BloomFilter.h b/external/spidermonkey/include/android/mozilla/BloomFilter.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/BloomFilter.h rename to external/spidermonkey/include/android/mozilla/BloomFilter.h diff --git a/external/spidermonkey/include/andorid/mozilla/Casting.h b/external/spidermonkey/include/android/mozilla/Casting.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Casting.h rename to external/spidermonkey/include/android/mozilla/Casting.h diff --git a/external/spidermonkey/include/andorid/mozilla/Char16.h b/external/spidermonkey/include/android/mozilla/Char16.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Char16.h rename to external/spidermonkey/include/android/mozilla/Char16.h diff --git a/external/spidermonkey/include/andorid/mozilla/CheckedInt.h b/external/spidermonkey/include/android/mozilla/CheckedInt.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/CheckedInt.h rename to external/spidermonkey/include/android/mozilla/CheckedInt.h diff --git a/external/spidermonkey/include/andorid/mozilla/Compiler.h b/external/spidermonkey/include/android/mozilla/Compiler.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Compiler.h rename to external/spidermonkey/include/android/mozilla/Compiler.h diff --git a/external/spidermonkey/include/andorid/mozilla/Constants.h b/external/spidermonkey/include/android/mozilla/Constants.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Constants.h rename to external/spidermonkey/include/android/mozilla/Constants.h diff --git a/external/spidermonkey/include/andorid/mozilla/DebugOnly.h b/external/spidermonkey/include/android/mozilla/DebugOnly.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/DebugOnly.h rename to external/spidermonkey/include/android/mozilla/DebugOnly.h diff --git a/external/spidermonkey/include/andorid/mozilla/Decimal.h b/external/spidermonkey/include/android/mozilla/Decimal.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Decimal.h rename to external/spidermonkey/include/android/mozilla/Decimal.h diff --git a/external/spidermonkey/include/andorid/mozilla/Endian.h b/external/spidermonkey/include/android/mozilla/Endian.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Endian.h rename to external/spidermonkey/include/android/mozilla/Endian.h diff --git a/external/spidermonkey/include/andorid/mozilla/EnumSet.h b/external/spidermonkey/include/android/mozilla/EnumSet.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/EnumSet.h rename to external/spidermonkey/include/android/mozilla/EnumSet.h diff --git a/external/spidermonkey/include/andorid/mozilla/FloatingPoint.h b/external/spidermonkey/include/android/mozilla/FloatingPoint.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/FloatingPoint.h rename to external/spidermonkey/include/android/mozilla/FloatingPoint.h diff --git a/external/spidermonkey/include/andorid/mozilla/GuardObjects.h b/external/spidermonkey/include/android/mozilla/GuardObjects.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/GuardObjects.h rename to external/spidermonkey/include/android/mozilla/GuardObjects.h diff --git a/external/spidermonkey/include/andorid/mozilla/HashFunctions.h b/external/spidermonkey/include/android/mozilla/HashFunctions.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/HashFunctions.h rename to external/spidermonkey/include/android/mozilla/HashFunctions.h diff --git a/external/spidermonkey/include/andorid/mozilla/Likely.h b/external/spidermonkey/include/android/mozilla/Likely.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Likely.h rename to external/spidermonkey/include/android/mozilla/Likely.h diff --git a/external/spidermonkey/include/andorid/mozilla/LinkedList.h b/external/spidermonkey/include/android/mozilla/LinkedList.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/LinkedList.h rename to external/spidermonkey/include/android/mozilla/LinkedList.h diff --git a/external/spidermonkey/include/andorid/mozilla/MSStdInt.h b/external/spidermonkey/include/android/mozilla/MSStdInt.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/MSStdInt.h rename to external/spidermonkey/include/android/mozilla/MSStdInt.h diff --git a/external/spidermonkey/include/andorid/mozilla/MathAlgorithms.h b/external/spidermonkey/include/android/mozilla/MathAlgorithms.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/MathAlgorithms.h rename to external/spidermonkey/include/android/mozilla/MathAlgorithms.h diff --git a/external/spidermonkey/include/andorid/mozilla/MemoryChecking.h b/external/spidermonkey/include/android/mozilla/MemoryChecking.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/MemoryChecking.h rename to external/spidermonkey/include/android/mozilla/MemoryChecking.h diff --git a/external/spidermonkey/include/andorid/mozilla/NullPtr.h b/external/spidermonkey/include/android/mozilla/NullPtr.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/NullPtr.h rename to external/spidermonkey/include/android/mozilla/NullPtr.h diff --git a/external/spidermonkey/include/andorid/mozilla/PodOperations.h b/external/spidermonkey/include/android/mozilla/PodOperations.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/PodOperations.h rename to external/spidermonkey/include/android/mozilla/PodOperations.h diff --git a/external/spidermonkey/include/andorid/mozilla/Poison.h b/external/spidermonkey/include/android/mozilla/Poison.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Poison.h rename to external/spidermonkey/include/android/mozilla/Poison.h diff --git a/external/spidermonkey/include/andorid/mozilla/Range.h b/external/spidermonkey/include/android/mozilla/Range.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Range.h rename to external/spidermonkey/include/android/mozilla/Range.h diff --git a/external/spidermonkey/include/andorid/mozilla/RangedPtr.h b/external/spidermonkey/include/android/mozilla/RangedPtr.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/RangedPtr.h rename to external/spidermonkey/include/android/mozilla/RangedPtr.h diff --git a/external/spidermonkey/include/andorid/mozilla/RefPtr.h b/external/spidermonkey/include/android/mozilla/RefPtr.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/RefPtr.h rename to external/spidermonkey/include/android/mozilla/RefPtr.h diff --git a/external/spidermonkey/include/andorid/mozilla/SHA1.h b/external/spidermonkey/include/android/mozilla/SHA1.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/SHA1.h rename to external/spidermonkey/include/android/mozilla/SHA1.h diff --git a/external/spidermonkey/include/andorid/mozilla/Scoped.h b/external/spidermonkey/include/android/mozilla/Scoped.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Scoped.h rename to external/spidermonkey/include/android/mozilla/Scoped.h diff --git a/external/spidermonkey/include/andorid/mozilla/SplayTree.h b/external/spidermonkey/include/android/mozilla/SplayTree.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/SplayTree.h rename to external/spidermonkey/include/android/mozilla/SplayTree.h diff --git a/external/spidermonkey/include/andorid/mozilla/StandardInteger.h b/external/spidermonkey/include/android/mozilla/StandardInteger.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/StandardInteger.h rename to external/spidermonkey/include/android/mozilla/StandardInteger.h diff --git a/external/spidermonkey/include/andorid/mozilla/ThreadLocal.h b/external/spidermonkey/include/android/mozilla/ThreadLocal.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/ThreadLocal.h rename to external/spidermonkey/include/android/mozilla/ThreadLocal.h diff --git a/external/spidermonkey/include/andorid/mozilla/TypeTraits.h b/external/spidermonkey/include/android/mozilla/TypeTraits.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/TypeTraits.h rename to external/spidermonkey/include/android/mozilla/TypeTraits.h diff --git a/external/spidermonkey/include/andorid/mozilla/TypedEnum.h b/external/spidermonkey/include/android/mozilla/TypedEnum.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/TypedEnum.h rename to external/spidermonkey/include/android/mozilla/TypedEnum.h diff --git a/external/spidermonkey/include/andorid/mozilla/Types.h b/external/spidermonkey/include/android/mozilla/Types.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Types.h rename to external/spidermonkey/include/android/mozilla/Types.h diff --git a/external/spidermonkey/include/andorid/mozilla/Util.h b/external/spidermonkey/include/android/mozilla/Util.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/Util.h rename to external/spidermonkey/include/android/mozilla/Util.h diff --git a/external/spidermonkey/include/andorid/mozilla/WeakPtr.h b/external/spidermonkey/include/android/mozilla/WeakPtr.h similarity index 100% rename from external/spidermonkey/include/andorid/mozilla/WeakPtr.h rename to external/spidermonkey/include/android/mozilla/WeakPtr.h diff --git a/external/spidermonkey/prebuilt/andorid/Android.mk b/external/spidermonkey/prebuilt/android/Android.mk similarity index 100% rename from external/spidermonkey/prebuilt/andorid/Android.mk rename to external/spidermonkey/prebuilt/android/Android.mk diff --git a/external/spidermonkey/prebuilt/andorid/armeabi-v7a/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id similarity index 100% rename from external/spidermonkey/prebuilt/andorid/armeabi-v7a/libjs_static.a.REMOVED.git-id rename to external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id diff --git a/external/spidermonkey/prebuilt/andorid/armeabi/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id similarity index 100% rename from external/spidermonkey/prebuilt/andorid/armeabi/libjs_static.a.REMOVED.git-id rename to external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id diff --git a/external/spidermonkey/prebuilt/andorid/x86/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id similarity index 100% rename from external/spidermonkey/prebuilt/andorid/x86/libjs_static.a.REMOVED.git-id rename to external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id diff --git a/external/tiff/include/andorid/tiff.h b/external/tiff/include/android/tiff.h similarity index 100% rename from external/tiff/include/andorid/tiff.h rename to external/tiff/include/android/tiff.h diff --git a/external/tiff/include/andorid/tiffconf.h b/external/tiff/include/android/tiffconf.h similarity index 100% rename from external/tiff/include/andorid/tiffconf.h rename to external/tiff/include/android/tiffconf.h diff --git a/external/tiff/include/andorid/tiffio.h b/external/tiff/include/android/tiffio.h similarity index 100% rename from external/tiff/include/andorid/tiffio.h rename to external/tiff/include/android/tiffio.h diff --git a/external/tiff/include/andorid/tiffvers.h b/external/tiff/include/android/tiffvers.h similarity index 100% rename from external/tiff/include/andorid/tiffvers.h rename to external/tiff/include/android/tiffvers.h diff --git a/external/tiff/prebuilt/andorid/Android.mk b/external/tiff/prebuilt/android/Android.mk similarity index 58% rename from external/tiff/prebuilt/andorid/Android.mk rename to external/tiff/prebuilt/android/Android.mk index 9d8e36d5fa..40af980160 100644 --- a/external/tiff/prebuilt/andorid/Android.mk +++ b/external/tiff/prebuilt/android/Android.mk @@ -3,6 +3,6 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_libtiff_static LOCAL_MODULE_FILENAME := tiff -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libtiff.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libtiff.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/tiff/prebuilt/andorid/armeabi-v7a/libtiff.a.REMOVED.git-id b/external/tiff/prebuilt/android/armeabi-v7a/libtiff.a.REMOVED.git-id similarity index 100% rename from external/tiff/prebuilt/andorid/armeabi-v7a/libtiff.a.REMOVED.git-id rename to external/tiff/prebuilt/android/armeabi-v7a/libtiff.a.REMOVED.git-id diff --git a/external/tiff/prebuilt/andorid/armeabi/libtiff.a.REMOVED.git-id b/external/tiff/prebuilt/android/armeabi/libtiff.a.REMOVED.git-id similarity index 100% rename from external/tiff/prebuilt/andorid/armeabi/libtiff.a.REMOVED.git-id rename to external/tiff/prebuilt/android/armeabi/libtiff.a.REMOVED.git-id diff --git a/external/tiff/prebuilt/andorid/x86/libtiff.a.REMOVED.git-id b/external/tiff/prebuilt/android/x86/libtiff.a.REMOVED.git-id similarity index 100% rename from external/tiff/prebuilt/andorid/x86/libtiff.a.REMOVED.git-id rename to external/tiff/prebuilt/android/x86/libtiff.a.REMOVED.git-id diff --git a/external/tinyxml2/tinyxml2.h b/external/tinyxml2/tinyxml2.h index eeffa1096f..b188feb1f5 100644 --- a/external/tinyxml2/tinyxml2.h +++ b/external/tinyxml2/tinyxml2.h @@ -24,8 +24,8 @@ distribution. #ifndef TINYXML2_INCLUDED #define TINYXML2_INCLUDED -#include "platform/CCPlatformConfig.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformConfig.h" +#include "CCPlatformMacros.h" #if defined(ANDROID_NDK) || defined(__BORLANDC__) || (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) # include diff --git a/external/unzip/ioapi.h b/external/unzip/ioapi.h index 575f44ece4..47cafee504 100644 --- a/external/unzip/ioapi.h +++ b/external/unzip/ioapi.h @@ -21,7 +21,7 @@ #ifndef _ZLIBIOAPI64_H #define _ZLIBIOAPI64_H -#include "platform/CCPlatformConfig.h" +#include "CCPlatformConfig.h" #if (!defined(_WIN32)) && (!defined(WIN32)) diff --git a/external/webp/include/andorid/decode.h b/external/webp/include/android/decode.h similarity index 100% rename from external/webp/include/andorid/decode.h rename to external/webp/include/android/decode.h diff --git a/external/webp/include/andorid/encode.h b/external/webp/include/android/encode.h similarity index 100% rename from external/webp/include/andorid/encode.h rename to external/webp/include/android/encode.h diff --git a/external/webp/include/andorid/types.h b/external/webp/include/android/types.h similarity index 100% rename from external/webp/include/andorid/types.h rename to external/webp/include/android/types.h diff --git a/external/webp/prebuilt/andorid/Android.mk b/external/webp/prebuilt/android/Android.mk similarity index 74% rename from external/webp/prebuilt/andorid/Android.mk rename to external/webp/prebuilt/android/Android.mk index ff7dea31f0..e102ac2511 100644 --- a/external/webp/prebuilt/andorid/Android.mk +++ b/external/webp/prebuilt/android/Android.mk @@ -3,8 +3,8 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := cocos_libwebp_static LOCAL_MODULE_FILENAME := webp -LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libwebp.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libwebp.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android LOCAL_WHOLE_STATIC_LIBRARIES := cpufeatures diff --git a/external/webp/prebuilt/andorid/armeabi-v7a/libwebp.a.REMOVED.git-id b/external/webp/prebuilt/android/armeabi-v7a/libwebp.a.REMOVED.git-id similarity index 100% rename from external/webp/prebuilt/andorid/armeabi-v7a/libwebp.a.REMOVED.git-id rename to external/webp/prebuilt/android/armeabi-v7a/libwebp.a.REMOVED.git-id diff --git a/external/webp/prebuilt/andorid/armeabi/libwebp.a.REMOVED.git-id b/external/webp/prebuilt/android/armeabi/libwebp.a.REMOVED.git-id similarity index 100% rename from external/webp/prebuilt/andorid/armeabi/libwebp.a.REMOVED.git-id rename to external/webp/prebuilt/android/armeabi/libwebp.a.REMOVED.git-id diff --git a/external/webp/prebuilt/andorid/x86/libwebp.a.REMOVED.git-id b/external/webp/prebuilt/android/x86/libwebp.a.REMOVED.git-id similarity index 100% rename from external/webp/prebuilt/andorid/x86/libwebp.a.REMOVED.git-id rename to external/webp/prebuilt/android/x86/libwebp.a.REMOVED.git-id diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp index 58aee740a3..077a92aa11 100644 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp @@ -1,7 +1,7 @@ #include "HelloWorldScene.h" #include "AppMacros.h" -#include "event_dispatcher/CCEventListenerTouch.h" +#include "CCEventListenerTouch.h" USING_NS_CC; diff --git a/samples/Cpp/HelloCpp/proj.android/build_native.sh b/samples/Cpp/HelloCpp/proj.android/build_native.sh index 684f0d9886..cfd49f5d79 100755 --- a/samples/Cpp/HelloCpp/proj.android/build_native.sh +++ b/samples/Cpp/HelloCpp/proj.android/build_native.sh @@ -97,10 +97,11 @@ if [[ "$buildexternalsfromsource" ]]; then echo "Building external dependencies from source" set -x "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" else echo "Using prebuilt externals" set -x "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" + fi diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk b/samples/Cpp/HelloCpp/proj.android/jni/Android.mk index 6ffd7d62ef..cfd4cb14b5 100644 --- a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk +++ b/samples/Cpp/HelloCpp/proj.android/jni/Android.mk @@ -12,10 +12,9 @@ LOCAL_SRC_FILES := hellocpp/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocos2dxandroid_static cocosdenshion_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static include $(BUILD_SHARED_LIBRARY) -$(call import-module,cocos2dx) +$(call import-module,2d) $(call import-module,audio/android) -$(call import-module,cocos2dx/platform/android) diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index ff687de48a..fb39932e2e 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -7,137 +7,137 @@ LOCAL_MODULE := cocos_testcpp_common LOCAL_MODULE_FILENAME := libtestcppcommon LOCAL_SRC_FILES := \ -Classes/AppDelegate.cpp \ -Classes/BaseTest.cpp \ -Classes/controller.cpp \ -Classes/testBasic.cpp \ -Classes/VisibleRect.cpp \ -Classes/AccelerometerTest/AccelerometerTest.cpp \ -Classes/ActionManagerTest/ActionManagerTest.cpp \ -Classes/ActionsEaseTest/ActionsEaseTest.cpp \ -Classes/ActionsProgressTest/ActionsProgressTest.cpp \ -Classes/ActionsTest/ActionsTest.cpp \ -Classes/Box2DTest/Box2dTest.cpp \ -Classes/Box2DTestBed/Box2dView.cpp \ -Classes/Box2DTestBed/GLES-Render.cpp \ -Classes/Box2DTestBed/Test.cpp \ -Classes/Box2DTestBed/TestEntries.cpp \ -Classes/BugsTest/Bug-1159.cpp \ -Classes/BugsTest/Bug-1174.cpp \ -Classes/BugsTest/Bug-350.cpp \ -Classes/BugsTest/Bug-422.cpp \ -Classes/BugsTest/Bug-624.cpp \ -Classes/BugsTest/Bug-886.cpp \ -Classes/BugsTest/Bug-899.cpp \ -Classes/BugsTest/Bug-914.cpp \ -Classes/BugsTest/BugsTest.cpp \ -Classes/BugsTest/Bug-458/Bug-458.cpp \ -Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ -Classes/ChipmunkTest/ChipmunkTest.cpp \ -Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ -Classes/ClippingNodeTest/ClippingNodeTest.cpp \ -Classes/CocosDenshionTest/CocosDenshionTest.cpp \ -Classes/ConfigurationTest/ConfigurationTest.cpp \ -Classes/CurlTest/CurlTest.cpp \ -Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ -Classes/DataVisitorTest/DataVisitorTest.cpp \ -Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ -Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ -Classes/EffectsTest/EffectsTest.cpp \ -Classes/ExtensionsTest/ExtensionsTest.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ -Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ -Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ -Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ -Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ -Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ -Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ -Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ -Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ -Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ -Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ -Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ -Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ -Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ -Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ -Classes/FileUtilsTest/FileUtilsTest.cpp \ -Classes/FontTest/FontTest.cpp \ -Classes/IntervalTest/IntervalTest.cpp \ -Classes/KeyboardTest/KeyboardTest.cpp \ -Classes/KeypadTest/KeypadTest.cpp \ -Classes/LabelTest/LabelTest.cpp \ -Classes/LabelTest/LabelTestNew.cpp \ -Classes/LayerTest/LayerTest.cpp \ -Classes/MenuTest/MenuTest.cpp \ -Classes/MotionStreakTest/MotionStreakTest.cpp \ -Classes/MutiTouchTest/MutiTouchTest.cpp \ -Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ -Classes/NodeTest/NodeTest.cpp \ -Classes/ParallaxTest/ParallaxTest.cpp \ -Classes/ParticleTest/ParticleTest.cpp \ -Classes/PerformanceTest/PerformanceAllocTest.cpp \ -Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ -Classes/PerformanceTest/PerformanceParticleTest.cpp \ -Classes/PerformanceTest/PerformanceSpriteTest.cpp \ -Classes/PerformanceTest/PerformanceTest.cpp \ -Classes/PerformanceTest/PerformanceTextureTest.cpp \ -Classes/PerformanceTest/PerformanceTouchesTest.cpp \ -Classes/PhysicsTest/PhysicsTest.cpp \ -Classes/RenderTextureTest/RenderTextureTest.cpp \ -Classes/RotateWorldTest/RotateWorldTest.cpp \ -Classes/SceneTest/SceneTest.cpp \ -Classes/SchedulerTest/SchedulerTest.cpp \ -Classes/ShaderTest/ShaderTest.cpp \ -Classes/ShaderTest/ShaderTest2.cpp \ -Classes/SpineTest/SpineTest.cpp \ -Classes/SpriteTest/SpriteTest.cpp \ -Classes/TextInputTest/TextInputTest.cpp \ -Classes/Texture2dTest/Texture2dTest.cpp \ -Classes/TextureCacheTest/TextureCacheTest.cpp \ -Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ -Classes/TileMapTest/TileMapTest.cpp \ -Classes/TouchesTest/Ball.cpp \ -Classes/TouchesTest/Paddle.cpp \ -Classes/TouchesTest/TouchesTest.cpp \ -Classes/TransitionsTest/TransitionsTest.cpp \ -Classes/UserDefaultTest/UserDefaultTest.cpp \ -Classes/ZwoptexTest/ZwoptexTest.cpp +$(LOCAL_PATH)/Classes/AppDelegate.cpp \ +$(LOCAL_PATH)/Classes/BaseTest.cpp \ +$(LOCAL_PATH)/Classes/controller.cpp \ +$(LOCAL_PATH)/Classes/testBasic.cpp \ +$(LOCAL_PATH)/Classes/VisibleRect.cpp \ +$(LOCAL_PATH)/Classes/AccelerometerTest/AccelerometerTest.cpp \ +$(LOCAL_PATH)/Classes/ActionManagerTest/ActionManagerTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsEaseTest/ActionsEaseTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsProgressTest/ActionsProgressTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsTest/ActionsTest.cpp \ +$(LOCAL_PATH)/Classes/Box2DTest/Box2dTest.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/Box2dView.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/GLES-Render.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/Test.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/TestEntries.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-1159.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-1174.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-350.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-422.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-624.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-886.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-899.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-914.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/BugsTest.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-458/Bug-458.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ +$(LOCAL_PATH)/Classes/ChipmunkTest/ChipmunkTest.cpp \ +$(LOCAL_PATH)/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ +$(LOCAL_PATH)/Classes/ClippingNodeTest/ClippingNodeTest.cpp \ +$(LOCAL_PATH)/Classes/CocosDenshionTest/CocosDenshionTest.cpp \ +$(LOCAL_PATH)/Classes/ConfigurationTest/ConfigurationTest.cpp \ +$(LOCAL_PATH)/Classes/CurlTest/CurlTest.cpp \ +$(LOCAL_PATH)/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ +$(LOCAL_PATH)/Classes/DataVisitorTest/DataVisitorTest.cpp \ +$(LOCAL_PATH)/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ +$(LOCAL_PATH)/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ +$(LOCAL_PATH)/Classes/EffectsTest/EffectsTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ExtensionsTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ +$(LOCAL_PATH)/Classes/FileUtilsTest/FileUtilsTest.cpp \ +$(LOCAL_PATH)/Classes/FontTest/FontTest.cpp \ +$(LOCAL_PATH)/Classes/IntervalTest/IntervalTest.cpp \ +$(LOCAL_PATH)/Classes/KeyboardTest/KeyboardTest.cpp \ +$(LOCAL_PATH)/Classes/KeypadTest/KeypadTest.cpp \ +$(LOCAL_PATH)/Classes/LabelTest/LabelTest.cpp \ +$(LOCAL_PATH)/Classes/LabelTest/LabelTestNew.cpp \ +$(LOCAL_PATH)/Classes/LayerTest/LayerTest.cpp \ +$(LOCAL_PATH)/Classes/MenuTest/MenuTest.cpp \ +$(LOCAL_PATH)/Classes/MotionStreakTest/MotionStreakTest.cpp \ +$(LOCAL_PATH)/Classes/MutiTouchTest/MutiTouchTest.cpp \ +$(LOCAL_PATH)/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ +$(LOCAL_PATH)/Classes/NodeTest/NodeTest.cpp \ +$(LOCAL_PATH)/Classes/ParallaxTest/ParallaxTest.cpp \ +$(LOCAL_PATH)/Classes/ParticleTest/ParticleTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceAllocTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceParticleTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceSpriteTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTextureTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTouchesTest.cpp \ +$(LOCAL_PATH)/Classes/PhysicsTest/PhysicsTest.cpp \ +$(LOCAL_PATH)/Classes/RenderTextureTest/RenderTextureTest.cpp \ +$(LOCAL_PATH)/Classes/RotateWorldTest/RotateWorldTest.cpp \ +$(LOCAL_PATH)/Classes/SceneTest/SceneTest.cpp \ +$(LOCAL_PATH)/Classes/SchedulerTest/SchedulerTest.cpp \ +$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest.cpp \ +$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest2.cpp \ +$(LOCAL_PATH)/Classes/SpineTest/SpineTest.cpp \ +$(LOCAL_PATH)/Classes/SpriteTest/SpriteTest.cpp \ +$(LOCAL_PATH)/Classes/TextInputTest/TextInputTest.cpp \ +$(LOCAL_PATH)/Classes/Texture2dTest/Texture2dTest.cpp \ +$(LOCAL_PATH)/Classes/TextureCacheTest/TextureCacheTest.cpp \ +$(LOCAL_PATH)/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ +$(LOCAL_PATH)/Classes/TileMapTest/TileMapTest.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/Ball.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/Paddle.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/TouchesTest.cpp \ +$(LOCAL_PATH)/Classes/TransitionsTest/TransitionsTest.cpp \ +$(LOCAL_PATH)/Classes/UserDefaultTest/UserDefaultTest.cpp \ +$(LOCAL_PATH)/Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes diff --git a/tools/android-mk-generator/android_mk_generator.py b/tools/android-mk-generator/android_mk_generator.py index 3aabfae992..3e42d908d5 100755 --- a/tools/android-mk-generator/android_mk_generator.py +++ b/tools/android-mk-generator/android_mk_generator.py @@ -24,7 +24,7 @@ def gen_android_mk(mkfile, pathes, suffix = ("c", "cpp",), exclude = ()): filestrio = cStringIO.StringIO() for filename in filelst: filestrio.write(' \\\n') - filestrio.write(os.path.relpath(filename, os.path.dirname(os.path.join(COCOS_ROOT, mkfile)))) + filestrio.write("$(LOCAL_PATH)/"+os.path.relpath(filename, os.path.dirname(os.path.join(COCOS_ROOT, mkfile)))) filestrio.write('\n') # read mk file diff --git a/tools/android-mk-generator/config.py b/tools/android-mk-generator/config.py index fdce1bf352..f7cdc3f389 100644 --- a/tools/android-mk-generator/config.py +++ b/tools/android-mk-generator/config.py @@ -1,8 +1,8 @@ [ { - 'mkfile' : 'cocos2dx/Android.mk', - 'pathes' : ("cocos2dx/",), - 'exclude' : ("cocos2dx/platform/android", "cocos2dx/platform/emscripten", "cocos2dx/platform/ios", "cocos2dx/platform/apple", "cocos2dx/platform/linux", "cocos2dx/platform/mac", "cocos2dx/platform/nacl", "cocos2dx/platform/qt5", "cocos2dx/platform/tizen", "cocos2dx/platform/win32", "cocos2dx/label_nodes/CCFontCache.cpp", "cocos2dx/base_nodes/CCGLBufferedNode.cpp","cocos2dx/support/user_default/CCUserDefault.cpp") + 'mkfile' : 'cocos/2d/Android.mk', + 'pathes' : ("cocos/2d/","cocos/base","cocos/math","cocos/physics","external/tinyxml2","external/unzip"), + 'exclude' : ("cocos/2d/platform/android", "cocos/2d/platform/emscripten", "cocos/2d/platform/ios", "cocos/2d/platform/apple", "cocos/2d/platform/linux", "cocos/2d/platform/mac", "cocos/2d/platform/win32") }, { 'mkfile' : 'samples/Cpp/TestCpp/Android.mk', From c5a4addf97a36d7ff63fdc81d7edfc40a2432e9a Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 14 Oct 2013 14:05:57 +0800 Subject: [PATCH 131/557] issue #2771: add addMass() and addMoment() to body. --- cocos2dx/physics/CCPhysicsBody.cpp | 29 +++------------------- cocos2dx/physics/CCPhysicsShape.cpp | 38 +++++++++++++++++++++++------ cocos2dx/physics/CCPhysicsShape.h | 1 - 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index eb98bef258..3d963922eb 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -294,33 +294,10 @@ void PhysicsBody::addShape(PhysicsShape* shape) shape->setBody(this); _shapes.push_back(shape); - // calculate the mass, area and desity + // calculate the area, mass, and desity + // area must update before mass, because the density changes depend on it. _area += shape->getArea(); - if (_mass == PHYSICS_INFINITY || shape->getMass() == PHYSICS_INFINITY) - { - _mass = PHYSICS_INFINITY; - _massDefault = false; - }else - { - if (shape->getMass() > 0) - { - _mass = (_massDefault ? 0 : _mass) + shape->getMass(); - _massDefault = false; - } - } - cpBodySetMass(_info->body, _mass); - - if (!_massDefault) - { - if (_mass == PHYSICS_INFINITY) - { - _density = PHYSICS_INFINITY; - }else - { - _density = _mass / _area; - } - } - + addMass(shape->getMass()); addMoment(shape->getMoment()); if (_world != nullptr) _world->addShape(shape); diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index 05bf303f91..bdfc931101 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -71,11 +71,6 @@ bool PhysicsShape::init(Type type, PhysicsMaterial material/* = MaterialDefault* return true; } -void PhysicsShape::setMass(float mass) -{ - -} - void PhysicsShape::setEnable(bool enable) { if (_enable != enable) @@ -95,9 +90,38 @@ void PhysicsShape::setEnable(bool enable) } } -void PhysicsShape::addToBody() +void PhysicsShape::setMass(float mass) { - if(_body != nullptr) _body->addShape(this); + if (mass < 0) + { + return; + } + + + if (_body) + { + _body->addMass(-_mass); + _body->addMass(mass); + }; + + _mass = mass; +} + +void PhysicsShape::setMoment(float moment) +{ + if (moment < 0) + { + return; + } + + + if (_body) + { + _body->addMoment(-_moment); + _body->addMoment(moment); + }; + + _moment = moment; } PhysicsBodyInfo* PhysicsShape::bodyInfo() const diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 688ccad2a6..0aa7a160b6 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -85,7 +85,6 @@ public: inline int getTag() { return _tag; } void setEnable(bool enable); inline bool isEnable() { return _enable; } - void addToBody(); inline float getMass() { return _mass; } void setMass(float mass); From 92e0dbe0c156c5d82125d7d82ebbada3425cea19 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 14 Oct 2013 14:56:57 +0800 Subject: [PATCH 132/557] issue #2905:add ccUtils.cpp --- cocos/2d/ccUtils.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 cocos/2d/ccUtils.cpp diff --git a/cocos/2d/ccUtils.cpp b/cocos/2d/ccUtils.cpp new file mode 100644 index 0000000000..d78324565b --- /dev/null +++ b/cocos/2d/ccUtils.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "ccUtils.h" + +namespace cocos2d { + +unsigned long ccNextPOT(unsigned long x) +{ + x = x - 1; + x = x | (x >> 1); + x = x | (x >> 2); + x = x | (x >> 4); + x = x | (x >> 8); + x = x | (x >>16); + return x + 1; +} + +} \ No newline at end of file From 438fe702872dac7ed79cb53c7abbe51e1dbc3b26 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 14 Oct 2013 15:53:14 +0800 Subject: [PATCH 133/557] issue #2905: [iOS, Mac] HelloCpp works now. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/platform/ios/CCESRenderer.h | 2 +- cocos/2d/platform/mac/CCEGLView.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index ea4a9890a6..1ffb09c3a2 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -cef7f2eb0a7ce536df264b4b3fa72470af8213d0 \ No newline at end of file +9e303a34aef39593ada75e90ae8d0829f0096abe \ No newline at end of file diff --git a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id index a1c65992b0..ebc2c0f549 100644 --- a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -f3d0c334145f571e5338f3e0fa051f7713668e3f \ No newline at end of file +aa360e1cdcaf0d2ca399aebe9b7c8786e80abde8 \ No newline at end of file diff --git a/cocos/2d/platform/ios/CCESRenderer.h b/cocos/2d/platform/ios/CCESRenderer.h index 7dfb474c8e..944be4926a 100644 --- a/cocos/2d/platform/ios/CCESRenderer.h +++ b/cocos/2d/platform/ios/CCESRenderer.h @@ -28,7 +28,7 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #import #import diff --git a/cocos/2d/platform/mac/CCEGLView.h b/cocos/2d/platform/mac/CCEGLView.h index 222bba5348..5f001b9061 100644 --- a/cocos/2d/platform/mac/CCEGLView.h +++ b/cocos/2d/platform/mac/CCEGLView.h @@ -27,7 +27,7 @@ #include "platform/CCCommon.h" #include "platform/CCEGLViewProtocol.h" -#include "platform/third_party/mac/glfw/glfw3.h" +#include "glfw3.h" NS_CC_BEGIN From 16c88363f56f1a915534c1df29b5fdcbd6899079 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 14 Oct 2013 17:16:39 +0800 Subject: [PATCH 134/557] issue #2905: Updating project configuration for SimpleGame. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 1ffb09c3a2..f6b6061df1 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -9e303a34aef39593ada75e90ae8d0829f0096abe \ No newline at end of file +1513bb8f2a786cfa406d2d6d9001e99abdd009ac \ No newline at end of file diff --git a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id index ebc2c0f549..9087c4bab5 100644 --- a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -aa360e1cdcaf0d2ca399aebe9b7c8786e80abde8 \ No newline at end of file +6d2fc1b611662a4fc4261eb2dc30dc6a96473bb2 \ No newline at end of file From 9f89879e5efe8a3fdc600846aeeb156fc6295007 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 14 Oct 2013 17:43:59 +0800 Subject: [PATCH 135/557] issue #2905: [iOS, Mac] Always search user path. --- build/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id index 9087c4bab5..3fe3b732a7 100644 --- a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -6d2fc1b611662a4fc4261eb2dc30dc6a96473bb2 \ No newline at end of file +561cdc247f0444ca86efc535600901b035e19ffa \ No newline at end of file From 613bb8912030ebc67d0d4ce49300b3d89145e9db Mon Sep 17 00:00:00 2001 From: Toru Matsuoka Date: Mon, 14 Oct 2013 20:19:21 +0900 Subject: [PATCH 136/557] Make "rename" setting usable. --- tools/project-creator/create_project.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tools/project-creator/create_project.py b/tools/project-creator/create_project.py index 966baaeaff..e55d7aa081 100755 --- a/tools/project-creator/create_project.py +++ b/tools/project-creator/create_project.py @@ -111,6 +111,14 @@ def processPlatformProjects(context, platform): java_package_path = os.path.join(*dst_pkg) + # rename files and folders + for item in data["rename"]: + tmp = item.replace("PACKAGE_PATH", java_package_path) + src = tmp.replace("PROJECT_NAME", context["src_project_name"]) + dst = tmp.replace("PROJECT_NAME", context["dst_project_name"]) + if os.path.exists(os.path.join(proj_path, src)): + os.rename(os.path.join(proj_path, src), os.path.join(proj_path, dst)) + # remove useless files and folders for item in data["remove"]: dst = item.replace("PROJECT_NAME", context["dst_project_name"]) From de9e831e350f9625e33c08092384756058716aec Mon Sep 17 00:00:00 2001 From: Toru Matsuoka Date: Mon, 14 Oct 2013 20:24:28 +0900 Subject: [PATCH 137/557] Fix definition of platform for ios and mac. Remove unnecessary files --- tools/project-creator/create_project.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/project-creator/create_project.py b/tools/project-creator/create_project.py index e55d7aa081..be6e38babc 100755 --- a/tools/project-creator/create_project.py +++ b/tools/project-creator/create_project.py @@ -6,9 +6,9 @@ # define global variables PLATFORMS = { - "cpp" : ["ios", "android", "win32", "mac", "linux"], - "lua" : ["ios", "android", "win32", "mac", "linux"], - "javascript" : ["ios", "android", "win32", "mac"] + "cpp" : ["ios_mac", "android", "win32", "linux"], + "lua" : ["ios_mac", "android", "win32", "linux"], + "javascript" : ["ios_mac", "android", "win32"] } From 2865ad798ba10d2971ad46522a6bc0e16350970f Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 15 Oct 2013 10:18:37 +0800 Subject: [PATCH 141/557] issues #2905:Updating project configuration for folder change. --- build/cocos2d-win32.vc2012.sln | 176 +- cocos/2d/cocos2d.vcxproj | 658 +++--- cocos/2d/cocos2d.vcxproj.filters | 1849 ++++++++--------- cocos/2d/platform/win32/CCEGLView.cpp | 2 +- cocos/2d/platform/win32/CCEGLView.h | 2 +- cocos/audio/proj.win32/CocosDenshion.vcxproj | 4 +- extensions/proj.win32/libExtensions.vcxproj | 194 +- .../proj.win32/libExtensions.vcxproj.filters | 535 +++-- .../Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj | 15 +- .../Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 10 +- 10 files changed, 1654 insertions(+), 1791 deletions(-) diff --git a/build/cocos2d-win32.vc2012.sln b/build/cocos2d-win32.vc2012.sln index 497a1d991c..d8c443ec6d 100644 --- a/build/cocos2d-win32.vc2012.sln +++ b/build/cocos2d-win32.vc2012.sln @@ -1,98 +1,19 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "audio", "..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "audio", "audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - EndProjectSection +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "..\samples\Cpp\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "scripting\lua\proj.win32\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "samples\Cpp\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CocosDragonJS", "samples\Javascript\CocosDragonJS\proj.win32\CocosDragonJS.vcxproj", "{68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "samples\Javascript\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "samples\Javascript\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WatermelonWithMe", "samples\Javascript\WatermelonWithMe\proj.win32\WatermelonWithMe.vcxproj", "{BE092D9E-95AE-4F86-84CE-F4519E4F3F15}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "samples\Lua\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "samples\Lua\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {DDC3E27F-004D-4DD4-9DD3-931A013D2159} = {DDC3E27F-004D-4DD4-9DD3-931A013D2159} - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrystalCraze", "samples\Javascript\CrystalCraze\proj.win32\CrystalCraze.vcxproj", "{9A17D9A4-4B11-4E32-94F6-895FF4909EC5}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetsManagerTest", "samples\Cpp\AssetsManagerTest\proj.win32\AssetsManagerTest.vcxproj", "{6D37505F-A890-441D-BD3F-A61E2C0469CE}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - EndProjectSection +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -100,14 +21,6 @@ Global Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.ActiveCfg = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.Build.0 = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 @@ -116,81 +29,30 @@ Global {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.ActiveCfg = Debug|Win32 {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.Build.0 = Debug|Win32 {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.ActiveCfg = Release|Win32 {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.Build.0 = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.ActiveCfg = Debug|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.Build.0 = Debug|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.ActiveCfg = Debug|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.Build.0 = Debug|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.ActiveCfg = Release|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.Build.0 = Release|Win32 - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Debug|Win32.ActiveCfg = Debug|Win32 - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Debug|Win32.Build.0 = Debug|Win32 - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Release|Win32.ActiveCfg = Release|Win32 - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Release|Win32.Build.0 = Release|Win32 - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.ActiveCfg = Debug|Win32 - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.Build.0 = Debug|Win32 - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.ActiveCfg = Release|Win32 - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.Build.0 = Release|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.ActiveCfg = Debug|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.Build.0 = Debug|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.ActiveCfg = Release|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.Build.0 = Release|Win32 - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Debug|Win32.ActiveCfg = Debug|Win32 - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Debug|Win32.Build.0 = Debug|Win32 - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Release|Win32.ActiveCfg = Release|Win32 - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Release|Win32.Build.0 = Release|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.ActiveCfg = Debug|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.Build.0 = Debug|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.ActiveCfg = Release|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.Build.0 = Release|Win32 - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.ActiveCfg = Debug|Win32 - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.Build.0 = Debug|Win32 - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.ActiveCfg = Release|Win32 - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.Build.0 = Release|Win32 - {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|Win32.ActiveCfg = Debug|Win32 - {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|Win32.Build.0 = Debug|Win32 - {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.ActiveCfg = Release|Win32 - {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.Build.0 = Release|Win32 - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Debug|Win32.ActiveCfg = Debug|Win32 - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Debug|Win32.Build.0 = Debug|Win32 - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Release|Win32.ActiveCfg = Release|Win32 - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Release|Win32.Build.0 = Release|Win32 - {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Debug|Win32.ActiveCfg = Debug|Win32 - {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Debug|Win32.Build.0 = Debug|Win32 - {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Release|Win32.ActiveCfg = Release|Win32 - {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {F51B8DCB-62CD-441F-B85D-43BD8EA432F1} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F51B8DCB-62CD-441F-B85D-43BD8EA432F1} - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {F51B8DCB-62CD-441F-B85D-43BD8EA432F1} - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {F51B8DCB-62CD-441F-B85D-43BD8EA432F1} - {929480E7-23C0-4DF6-8456-096D71547116} = {F51B8DCB-62CD-441F-B85D-43BD8EA432F1} - {13E55395-94A2-4CD9-BFC2-1A051F80C17D} = {69C8AC8E-8B5C-474C-950D-1DB7F367E22C} - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED} = {69C8AC8E-8B5C-474C-950D-1DB7F367E22C} - {DDC3E27F-004D-4DD4-9DD3-931A013D2159} = {69C8AC8E-8B5C-474C-950D-1DB7F367E22C} - {76A39BB2-9B84-4C65-98A5-654D86B86F2A} = {8DFE8821-1A1A-4894-9EA1-2A211F8CEDEA} - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB} = {8DFE8821-1A1A-4894-9EA1-2A211F8CEDEA} - {6D37505F-A890-441D-BD3F-A61E2C0469CE} = {8DFE8821-1A1A-4894-9EA1-2A211F8CEDEA} - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - {D0F06A44-A245-4D13-A498-0120C203B539} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - {39379840-825A-45A0-B363-C09FFEF864BD} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5} = {42FCBD79-852E-4A68-9C3F-51200BAF5732} - EndGlobalSection GlobalSection(DPCodeReviewSolutionGUID) = preSolution DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} EndGlobalSection diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 46a695d1e2..0c421489f9 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -69,7 +69,7 @@ Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir)..;$(ProjectDir)..\platform\win32;$(ProjectDir)..\platform\third_party\win32\iconv;$(ProjectDir)..\platform\third_party\win32\zlib;$(ProjectDir)..\platform\third_party\win32\libpng;$(ProjectDir)..\platform\third_party\win32\libjpeg;$(ProjectDir)..\platform\third_party\win32\libtiff;$(ProjectDir)..\platform\third_party\win32\libwebp;$(ProjectDir)..\platform\third_party\win32\libfreetype2;$(ProjectDir)..\platform\third_party\win32\OGLES;..\include;$(ProjectDir)..\kazmath\include;$(ProjectDir)..\platform\third_party\common\etc;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir);$(ProjectDir)..\physics;$(ProjectDir)..\..\external\glfw3\include\win32;$(ProjectDir)..\base;$(ProjectDir)..\..\external\unzip;$(ProjectDir)..\..\external\tinyxml2;$(ProjectDir)platform\win32;$(ProjectDir)..\..\external\win32-specific\icon\include;$(ProjectDir)..\..\external\win32-specific\zlib\include;$(ProjectDir)..\..\external\png\include\win32;$(ProjectDir)..\..\external\jpeg\include\win32;$(ProjectDir)..\..\external\tiff\include\win32;$(ProjectDir)..\..\external\webp\include\win32;$(ProjectDir)..\..\external\freetype2\include\win32;$(ProjectDir)..\..\external\win32-specific\gles\include\OGLES;$(ProjectDir)..\math\kazmath\include;$(ProjectDir)platform\third_party\common\etc;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -83,7 +83,16 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\freetype2\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\glfw3\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\curl\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\jpeg\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\png\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\tiff\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\webp\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\zlib\prebuilt\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\icon\prebuilt\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(OutDir)" @@ -119,7 +128,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external*\win32\*.*" "$(OutDir)" @@ -140,79 +149,36 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -228,162 +194,158 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -402,101 +364,147 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 391517347c..2028e708c8 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -4,9 +4,6 @@ {cc64f5ad-2234-494c-9c51-b7a20c8887aa} - - {aec8225f-81a7-4213-b97b-7004d5535398} - {736cf4ab-e0d6-40ba-912a-b062d28d318a} @@ -67,21 +64,6 @@ {7751500e-ac9e-4604-a96d-670b30b7d8bd} - - {b38113b1-3d59-4f6e-ac5a-f43921f6ed09} - - - {569c49c9-27eb-456e-a3f4-9f403e28a3a1} - - - {191b3e94-47dc-4054-b1cb-bf145d281521} - - - {a91a4cc0-41e6-43e9-80c0-2c9101924386} - - - {e278b354-1e41-4e92-95b3-7f661ba67140} - {163895ae-8a8e-46bf-bdf2-98bb2c1347fc} @@ -112,397 +94,26 @@ {b9880458-36e5-4f28-a34b-d01d9512a395} + + {05e27e68-7574-4a8b-af68-553dd3bafdfa} + + + {b797075f-7437-46d5-b4ee-2aa2c108e98f} + + + {c755509d-1610-4e6c-b01b-e01d4d0de46e} + + + {e1b64497-c099-4f06-8d61-9d4c6b7a215a} + + + {7c71abeb-8b4b-4be8-a23c-e32fedc65fc9} + + + {aec8225f-81a7-4213-b97b-7004d5535398} + - - base_nodes - - - base_nodes - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - effects - - - effects - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - label_nodes - - - label_nodes - - - label_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - menu_nodes - - - menu_nodes - - - misc_nodes - - - misc_nodes - - - misc_nodes - - - particle_nodes - - - particle_nodes - - - particle_nodes - - - particle_nodes - - - platform - - - platform - - - platform - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - support - - - support - - - support - - - support - - - support - - - support - - - support\data_support - - - support\image_support - - - support\zip_support - - - support\zip_support - - - support\zip_support - - - textures - - - textures - - - textures - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - text_input_node - - - text_input_node - - - script_support - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src - - - kazmath\src\GL - - - kazmath\src\GL - - - - - - - - draw_nodes - - - draw_nodes - - - misc_nodes - - - shaders - - - shaders - - - shaders - - - shaders - - - platform\win32 - - - platform - - - platform\win32 - - - support - - - support\user_default - - - support\tinyxml2 - - - cocoa - - - - support\component - - - support\component - - - - platform\etc - - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - platform - - - platform - - - event_dispatcher - - - event_dispatcher - - - event_dispatcher - - - event_dispatcher - physics @@ -548,535 +159,421 @@ physics\Box2D - + + base_nodes + + + base_nodes + + + effects + + + effects + + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher + + event_dispatcher + + + event_dispatcher + + + event_dispatcher + + + event_dispatcher + + + kazmath\src\GL + + + kazmath\src\GL + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + kazmath\src + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + menu_nodes + + + menu_nodes + + + misc_nodes + + + misc_nodes + + + misc_nodes + + + misc_nodes + + + particle_nodes + + + particle_nodes + + + particle_nodes + + + particle_nodes + + + script_support + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + draw_nodes + + + draw_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + platform\etc + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + shaders + + + shaders + + + shaders + + + shaders + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + text_input_node + + + text_input_node + + + textures + + + textures + + + textures + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + + + + + + + + + support + + + support + + + support + + + support + + + support + + + support + + + support\component + + + support\component + + + support\data_support + + + support\image_support + + + support\tinyxml2 + + + support\user_default + + + support\zip_support + + + support\zip_support + + + support\zip_support + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + support + - - base_nodes - - - base_nodes - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - effects - - - effects - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - actions - - - include - - - include - - - include - - - include - - - include - - - include - - - label_nodes - - - label_nodes - - - label_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - layers_scenes_transitions_nodes - - - menu_nodes - - - menu_nodes - - - misc_nodes - - - misc_nodes - - - misc_nodes - - - particle_nodes - - - particle_nodes - - - particle_nodes - - - particle_nodes - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - platform\win32 - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - sprite_nodes - - - support - - - support - - - support - - - support - - - support - - - support - - - support\data_support - - - support\data_support - - - support\data_support - - - support\image_support - - - support\zip_support - - - support\zip_support - - - support\zip_support - - - textures - - - textures - - - textures - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - tilemap_parallax_nodes - - - text_input_node - - - text_input_node - - - text_input_node - - - script_support - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath - - - kazmath\include\kazmath\GL - - - kazmath\include\kazmath\GL - - - - - - - draw_nodes - - - draw_nodes - - - misc_nodes - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - shaders - - - platform\win32 - - - support - - - support\user_default - - - support\tinyxml2 - - - cocoa - - - cocoa - - - cocoa - - - cocoa - - - - support\component - - - support\component - - - include - - - platform\etc - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - label_nodes - - - platform - - - platform - - - platform - - - event_dispatcher - - - event_dispatcher - - - event_dispatcher - - - event_dispatcher - physics @@ -1131,29 +628,529 @@ physics\Box2D - + + base_nodes + + + base_nodes + + + effects + + + effects + + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher - + event_dispatcher + + event_dispatcher + + + event_dispatcher + + + event_dispatcher + + + event_dispatcher + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath + + + kazmath\include\kazmath\GL + + + kazmath\include\kazmath\GL + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + layers_scenes_transitions_nodes + + + menu_nodes + + + menu_nodes + + + misc_nodes + + + misc_nodes + + + misc_nodes + + + misc_nodes + + + particle_nodes + + + particle_nodes + + + particle_nodes + + + particle_nodes + + + script_support + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + actions + + + draw_nodes + + + draw_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + label_nodes + + + platform\etc + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform\win32 + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + platform + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + shaders + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + sprite_nodes + + + text_input_node + + + text_input_node + + + text_input_node + + + textures + + + textures + + + textures + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + tilemap_parallax_nodes + + + + + + + + support + + + support + + + support + + + support + + + support + + + support + + + support + + + support\component + + + support\component + + + support\data_support + + + support\data_support + + + support\data_support + + + support\image_support + + + support\tinyxml2 + + + support\user_default + + + support\zip_support + + + support\zip_support + + + support\zip_support + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + + + base + \ No newline at end of file diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 4099331cf9..d5b2ba0202 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCSet.h" #include "ccMacros.h" #include "CCDirector.h" -#include "/CCIMEDispatcher.h" +#include "CCIMEDispatcher.h" #include "CCApplication.h" #include "CCTouch.h" #include "CCEventDispatcher.h" diff --git a/cocos/2d/platform/win32/CCEGLView.h b/cocos/2d/platform/win32/CCEGLView.h index 643b500c66..59432e27ba 100644 --- a/cocos/2d/platform/win32/CCEGLView.h +++ b/cocos/2d/platform/win32/CCEGLView.h @@ -30,7 +30,7 @@ THE SOFTWARE. #include "CCGeometry.h" #include "platform/CCEGLViewProtocol.h" -#include "platform/third_party/win32/GLFW/glfw3.h" +#include "glfw3.h" NS_CC_BEGIN diff --git a/cocos/audio/proj.win32/CocosDenshion.vcxproj b/cocos/audio/proj.win32/CocosDenshion.vcxproj index d5a959c878..b59c65d98c 100644 --- a/cocos/audio/proj.win32/CocosDenshion.vcxproj +++ b/cocos/audio/proj.win32/CocosDenshion.vcxproj @@ -11,7 +11,7 @@ - libCocosDenshion + audio {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} CocosDenshion.win32 Win32Proj @@ -65,7 +65,7 @@ Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(ProjectDir)..\..\cocos2dx;$(ProjectDir)..\..\cocos2dx\include;$(ProjectDir)..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(ProjectDir)..\..\physics;$(ProjectDir)..\..\base;$(ProjectDir)..\..\2d;$(ProjectDir)..\..\2d\platform\win32;$(ProjectDir)..\..\math\kazmath\include;$(ProjectDir)..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\external\win32-specific\gles\include\OGLES;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks diff --git a/extensions/proj.win32/libExtensions.vcxproj b/extensions/proj.win32/libExtensions.vcxproj index e1c2ea14a1..25597c43e3 100644 --- a/extensions/proj.win32/libExtensions.vcxproj +++ b/extensions/proj.win32/libExtensions.vcxproj @@ -92,36 +92,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - @@ -141,11 +153,6 @@ - - - - - @@ -168,13 +175,6 @@ - - - - - - - @@ -223,39 +223,58 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -275,11 +294,6 @@ - - - - - @@ -303,20 +317,6 @@ - - - - - - - - - - - - - - @@ -372,10 +372,10 @@ - - - - + + + + diff --git a/extensions/proj.win32/libExtensions.vcxproj.filters b/extensions/proj.win32/libExtensions.vcxproj.filters index e6d6f2354c..766af1001f 100644 --- a/extensions/proj.win32/libExtensions.vcxproj.filters +++ b/extensions/proj.win32/libExtensions.vcxproj.filters @@ -102,75 +102,6 @@ GUI\CCScrollView - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - GUI\CCControlExtension @@ -225,9 +156,6 @@ GUI\CCEditBox - - AssetsManager - spine @@ -298,18 +226,6 @@ network - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - CocoStudio\Armature\animation @@ -364,27 +280,6 @@ CocoStudio\Armature - - CocoStudio\Json - - - CocoStudio\Json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Reader - - - CocoStudio\Components - CocoStudio\Armature\utils @@ -454,9 +349,6 @@ CocoStudio\GUI\System - - CocoStudio\Reader - CocoStudio\GUI\UIWidgets\ScrollWidget @@ -505,9 +397,6 @@ CocoStudio\GUI\Layouts - - CocoStudio\GUI\Layouts - CocoStudio\GUI\Layouts @@ -529,21 +418,129 @@ CocoStudio\Reader - + + AssetsManager + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + CocoStudio\Action - + CocoStudio\Action - + CocoStudio\Action - + CocoStudio\Action - + CocoStudio\Action + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Reader + + + CocoStudio\Reader + + + CocoStudio\Json + + + CocoStudio\Json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + @@ -569,87 +566,6 @@ GUI\CCScrollView - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - GUI\CCControlExtension @@ -710,9 +626,6 @@ GUI\CCEditBox - - AssetsManager - spine @@ -785,18 +698,6 @@ network - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - CocoStudio\Armature\animation @@ -854,48 +755,6 @@ CocoStudio\Armature - - CocoStudio\Json - - - CocoStudio\Json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Reader - - - CocoStudio\Components - CocoStudio\GUI\UIWidgets\ScrollWidget @@ -965,36 +824,174 @@ CocoStudio\GUI\System - + + AssetsManager + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CCBReader + + + CocoStudio\Action + + + CocoStudio\Action + + + CocoStudio\Action + + + CocoStudio\Action + + + CocoStudio\Action + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + + CocoStudio\Components + + CocoStudio\Reader - - CocoStudio\Action + + CocoStudio\Reader - - CocoStudio\Action + + CocoStudio\Json - - CocoStudio\Action + + CocoStudio\Json - - CocoStudio\Action + + CocoStudio\Json\lib_json - - CocoStudio\Action + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json + + + CocoStudio\Json\lib_json - + CocoStudio\Json\lib_json - + CocoStudio\Json\lib_json - + CocoStudio\Json\lib_json - + CocoStudio\Json\lib_json diff --git a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj index 1f00dbf6ea..233a21ce9c 100644 --- a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj +++ b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj @@ -36,11 +36,10 @@ - + - - - + + @@ -67,7 +66,7 @@ Disabled - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;..\Classes;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\base;$(ProjectDir)..\..\..\..\cocos\physics;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;..\Classes;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) true EnableFastChecks @@ -95,7 +94,7 @@ MaxSpeed true - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;..\Classes;%(AdditionalIncludeDirectories) + $(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\2d\include;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;..\Classes;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -132,11 +131,11 @@ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 95e857631c..d9227050c3 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -36,11 +36,11 @@ - + - + @@ -67,7 +67,7 @@ Disabled - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\audio\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\extensions\network;..\Classes;..;%(AdditionalIncludeDirectories) + $(ProjectDir)..\..\..\..\cocos\physics;$(ProjectDir)..\..\..\..\cocos\base;$(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\..\external\websockets\win32\include;$(ProjectDir)..\..\..\..\cocos\audio\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\cocos\network;..\Classes;..;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL @@ -459,11 +459,11 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false From f7dc3bb98f606bc493a644796ef5446557525927 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 15 Oct 2013 13:48:01 +0800 Subject: [PATCH 142/557] issue #2771: migrate the PhysicsShape definition --- cocos2dx/cocoa/CCGeometry.cpp | 24 ++ cocos2dx/cocoa/CCGeometry.h | 20 ++ cocos2dx/physics/CCPhysicsBody.cpp | 8 +- cocos2dx/physics/CCPhysicsShape.cpp | 349 ++++++++++++++++---- cocos2dx/physics/CCPhysicsShape.h | 84 ++++- cocos2dx/physics/CCPhysicsWorld.cpp | 5 +- cocos2dx/physics/chipmunk/CCPhysicsHelper.h | 2 +- 7 files changed, 402 insertions(+), 90 deletions(-) diff --git a/cocos2dx/cocoa/CCGeometry.cpp b/cocos2dx/cocoa/CCGeometry.cpp index cfce9d3fa7..1d5c4896c6 100644 --- a/cocos2dx/cocoa/CCGeometry.cpp +++ b/cocos2dx/cocoa/CCGeometry.cpp @@ -62,16 +62,40 @@ Point Point::operator+(const Point& right) const return Point(this->x + right.x, this->y + right.y); } +Point& Point::operator+=(const Point& right) +{ + this->x += right.x; + this->y += right.y; + return *this; +} + Point Point::operator-(const Point& right) const { return Point(this->x - right.x, this->y - right.y); } +Point& Point::operator-=(const Point& right) +{ + this->x -= right.x; + this->y -= right.y; + return *this; +} + Point Point::operator-() const { return Point(-x, -y); } +bool Point::operator==(const Point& right) +{ + return this->x == right.x && this->y == right.y; +} + +bool Point::operator!=(const Point& right) +{ + return this->x != right.x || this->y != right.y; +} + Point Point::operator*(float a) const { return Point(this->x * a, this->y * a); diff --git a/cocos2dx/cocoa/CCGeometry.h b/cocos2dx/cocoa/CCGeometry.h index 47e2fdf9ac..94bbf3fb10 100644 --- a/cocos2dx/cocoa/CCGeometry.h +++ b/cocos2dx/cocoa/CCGeometry.h @@ -93,16 +93,36 @@ public: * @lua NA */ Point operator+(const Point& right) const; + /** + * @js NA + * @lua NA + */ + Point& operator+=(const Point& right); /** * @js NA * @lua NA */ Point operator-(const Point& right) const; + /** + * @js NA + * @lua NA + */ + Point& operator-=(const Point& right); /** * @js NA * @lua NA */ Point operator-() const; + /** + * @js NA + * @lua NA + */ + bool operator==(const Point& right); + /** + * @js NA + * @lua NA + */ + bool operator!=(const Point& right); /** * @js NA * @lua NA diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 3d963922eb..fee8712353 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -364,7 +364,7 @@ void PhysicsBody::addMass(float mass) { if (mass == PHYSICS_INFINITY) { - mass = PHYSICS_INFINITY; + _mass = PHYSICS_INFINITY; _massDefault = false; _density = PHYSICS_INFINITY; } @@ -398,6 +398,8 @@ void PhysicsBody::addMass(float mass) _density = 0; } } + + cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMoment(float moment) @@ -436,7 +438,7 @@ void PhysicsBody::addMoment(float moment) } } - cpBodySetMoment(_info->body, moment); + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); } void PhysicsBody::setVelocity(Point velocity) @@ -454,7 +456,7 @@ void PhysicsBody::setMoment(float moment) _moment = moment; _momentDefault = false; - cpBodySetMoment(_info->body, _moment); + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); } PhysicsShape* PhysicsBody::getShapeByTag(int tag) diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index bdfc931101..abc4b4691b 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -50,7 +50,6 @@ PhysicsShape::PhysicsShape() , _mass(0) , _moment(0) , _tag(0) -, _enable(true) { } @@ -60,36 +59,16 @@ PhysicsShape::~PhysicsShape() CC_SAFE_DELETE(_info); } -bool PhysicsShape::init(Type type, PhysicsMaterial material/* = MaterialDefault*/) +bool PhysicsShape::init(Type type) { _info = new PhysicsShapeInfo(this); if (_info == nullptr) return false; _type = type; - _material = material; return true; } -void PhysicsShape::setEnable(bool enable) -{ - if (_enable != enable) - { - _enable = enable; - - if (_body->getWorld() && _body->isEnable()) - { - if (enable) - { - _body->getWorld()->addShape(this); - }else - { - _body->getWorld()->removeShape(this); - } - } - } -} - void PhysicsShape::setMass(float mass) { if (mass < 0) @@ -97,7 +76,6 @@ void PhysicsShape::setMass(float mass) return; } - if (_body) { _body->addMass(-_mass); @@ -114,7 +92,6 @@ void PhysicsShape::setMoment(float moment) return; } - if (_body) { _body->addMoment(-_moment); @@ -124,6 +101,13 @@ void PhysicsShape::setMoment(float moment) _moment = moment; } +void PhysicsShape::setMaterial(PhysicsMaterial material) +{ + setDensity(material.density); + setRestitution(material.restitution); + setFriction(material.friction); +} + PhysicsBodyInfo* PhysicsShape::bodyInfo() const { if (_body != nullptr) @@ -206,32 +190,72 @@ PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment() } #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -void PhysicsShape::initEnd() +void PhysicsShape::setDensity(float density) { - for (auto shape : _info->shapes) + if (density < 0) { - cpShapeSetElasticity(shape, _material.elasticity); - cpShapeSetFriction(shape, _material.friction); + return; + } + + _material.density = density; + + if (_material.density == PHYSICS_INFINITY) + { + setMass(PHYSICS_INFINITY); + }else if (_area > 0) + { + setMass(PhysicsHelper::float2cpfloat(_material.density * _area)); } } -void PhysicsShape::setElasticity(float elasticity) +void PhysicsShape::setRestitution(float restitution) { + _material.restitution = restitution; + for (cpShape* shape : _info->shapes) { - cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(elasticity)); + cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution)); } } void PhysicsShape::setFriction(float friction) { + _material.friction = friction; + for (cpShape* shape : _info->shapes) { cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); } } + +Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) +{ + cpVect* cpvs = new cpVect[count]; + cpRecenterPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); + PhysicsHelper::cpvs2points(cpvs, points, count); + delete[] cpvs; + + if (center != Point::ZERO) + { + for (int i = 0; i < count; ++i) + { + points[i] += center; + } + } + + return points; +} + +Point PhysicsShape::getPolyonCenter(Point* points, int count) +{ + cpVect* cpvs = new cpVect[count]; + cpVect center = cpCentroidForPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); + delete[] cpvs; + + return PhysicsHelper::cpv2point(center); +} + // PhysicsShapeCircle PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { @@ -250,25 +274,65 @@ bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = Materia { do { - CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); - _area = PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); - _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForCircle(_mass, 0, radius, PhysicsHelper::point2cpv(offset)); - _info->add(shape); - initEnd(); + _area = calculateDefaultArea(); + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _moment = calculateDefaultMoment(); + + setMaterial(material); return true; } while (false); return false; } +float PhysicsShapeCircle::calculateArea(float radius) +{ + return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); +} + +float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset) +{ + return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), + 0, + PhysicsHelper::float2cpfloat(radius), + PhysicsHelper::point2cpv(offset))); +} + +float PhysicsShapeCircle::calculateDefaultArea() +{ + return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->shapes.front()))); +} + +float PhysicsShapeCircle::calculateDefaultMoment() +{ + cpShape* shape = _info->shapes.front(); + + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), + 0, + cpCircleShapeGetRadius(shape), + cpCircleShapeGetOffset(shape))); +} + +float PhysicsShapeCircle::getRadius() +{ + return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); +} + +Point PhysicsShapeCircle::getOffset() +{ + return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->shapes.front())); +} + // PhysicsShapeEdgeSegment PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { @@ -287,7 +351,7 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* { do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); cpShape* shape = cpSegmentShapeNew(_info->shareBody, PhysicsHelper::point2cpv(a), @@ -296,12 +360,14 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* CC_BREAK_IF(shape == nullptr); - _mass = PHYSICS_INFINITY; - _moment = PHYSICS_INFINITY; - _info->add(shape); - initEnd(); + _mass = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; + _center = a.getMidpoint(b); + + + setMaterial(material); return true; } while (false); @@ -309,6 +375,21 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* return false; } +Point PhysicsShapeEdgeSegment::getPointA() +{ + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); +} + +Point PhysicsShapeEdgeSegment::getPointB() +{ + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); +} + +Point PhysicsShapeEdgeSegment::getCenter() +{ + return _center; +} + // PhysicsShapeBox PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { @@ -327,19 +408,26 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau { do { - CC_BREAK_IF(!PhysicsShape::init(Type::BOX, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::BOX)); - cpShape* shape = cpBoxShapeNew(_info->shareBody, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); + cpVect wh = PhysicsHelper::size2cpv(size); + cpVect vec[4] = + { + {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} + }; + + cpShape* shape = cpPolyShapeNew(_info->shareBody, 4, vec, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); - _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(4, ((cpPolyShape*)shape)->verts)); - _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForBox(_mass, PhysicsHelper::float2cpfloat(size.width), PhysicsHelper::float2cpfloat(size.height)); - _info->add(shape); - initEnd(); + _offset = offset; + _area = calculateDefaultArea(); + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _moment = calculateDefaultMoment(); + + setMaterial(material); return true; } while (false); @@ -347,7 +435,60 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau return false; } -// PhysicsShapeCircle +float PhysicsShapeBox::calculateArea(Size size) +{ + cpVect wh = PhysicsHelper::size2cpv(size); + cpVect vec[4] = + { + {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} + }; + return PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec)); +} + +float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) +{ + cpVect wh = PhysicsHelper::size2cpv(size); + cpVect vec[4] = + { + {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} + }; + + return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForPoly(PhysicsHelper::float2cpfloat(mass), + 4, + vec, + PhysicsHelper::point2cpv(offset))); +} + +float PhysicsShapeBox::calculateDefaultArea() +{ + cpShape* shape = _info->shapes.front(); + return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); +} + +float PhysicsShapeBox::calculateDefaultMoment() +{ + cpShape* shape = _info->shapes.front(); + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); +} + +Point* PhysicsShapeBox::getPoints(Point* points) +{ + cpShape* shape = _info->shapes.front(); + return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); + + return points; +} + +Size PhysicsShapeBox::getSize() +{ + cpShape* shape = _info->shapes.front(); + return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), + cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)))); +} + +// PhysicsShapePolygon PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); @@ -361,11 +502,11 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, Physi return nullptr; } -bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { do { - CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN)); cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -374,13 +515,14 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia CC_BREAK_IF(shape == nullptr); - _area = PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); - _mass = _material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : _material.density * _area; - _moment = _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, PhysicsHelper::point2cpv(offset)); - _info->add(shape); - initEnd(); + _area = calculateDefaultArea(); + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _moment = calculateDefaultMoment(); + _center = PhysicsHelper::cpv2point(cpCentroidForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); + + setMaterial(material); return true; } while (false); @@ -388,6 +530,56 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia return false; } +float PhysicsShapePolygon::calculateArea(Point* points, int count) +{ + cpVect* vecs = new cpVect[count]; + PhysicsHelper::points2cpvs(points, vecs, count); + float area = PhysicsHelper::cpfloat2float(cpAreaForPoly(count, vecs)); + CC_SAFE_DELETE(vecs); + + return area; +} + +float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, Point offset) +{ + cpVect* vecs = new cpVect[count]; + PhysicsHelper::points2cpvs(points, vecs, count); + float moment = mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForPoly(mass, count, vecs, PhysicsHelper::point2cpv(offset))); + CC_SAFE_DELETE(vecs); + + return moment; +} + +float PhysicsShapePolygon::calculateDefaultArea() +{ + cpShape* shape = _info->shapes.front(); + return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); +} + +float PhysicsShapePolygon::calculateDefaultMoment() +{ + cpShape* shape = _info->shapes.front(); + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); +} + +Point* PhysicsShapePolygon::getPoints(Point* points) +{ + cpShape* shape = _info->shapes.front(); + return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); +} + +int PhysicsShapePolygon::getPointsCount() +{ + return ((cpPolyShape*)_info->shapes.front())->numVerts; +} + +Point PhysicsShapePolygon::getCenter() +{ + return _center; +} + // PhysicsShapeEdgeBox PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/* = Point(0, 0)*/) { @@ -406,7 +598,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD { do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX)); cpVect vec[4] = {}; vec[0] = PhysicsHelper::point2cpv(Point(-size.width/2+offset.x, -size.height/2+offset.y)); @@ -424,10 +616,11 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD } CC_BREAK_IF(i < 4); + _offset = offset; _mass = PHYSICS_INFINITY; _moment = PHYSICS_INFINITY; - initEnd(); + setMaterial(material); return true; } while (false); @@ -454,10 +647,11 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); + _center = PhysicsHelper::cpv2point(cpCentroidForPoly(count, vec)); int i = 0; for (; i < count; ++i) @@ -469,23 +663,33 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat cpShapeSetFriction(shape, 1.0f); _info->add(shape); } - CC_SAFE_DELETE(vec); + CC_SAFE_DELETE_ARRAY(vec); CC_BREAK_IF(i < count); _mass = PHYSICS_INFINITY; _moment = PHYSICS_INFINITY; - initEnd(); + setMaterial(material); return true; } while (false); - if (vec != nullptr) delete[] vec; + CC_SAFE_DELETE_ARRAY(vec); return false; } +Point PhysicsShapeEdgePolygon::getCenter() +{ + return _center; +} + +int PhysicsShapeEdgePolygon::getPointsCount() +{ + return _info->shapes.size() + 1; +} + // PhysicsShapeEdgeChain PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) { @@ -505,10 +709,11 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater cpVect* vec = nullptr; do { - CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN, material)); + CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN)); vec = new cpVect[count]; PhysicsHelper::points2cpvs(points, vec, count); + _center = PhysicsHelper::cpv2point(cpCentroidForPoly(count, vec)); int i = 0; for (; i < count - 1; ++i) @@ -520,22 +725,32 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater cpShapeSetFriction(shape, 1.0f); _info->add(shape); } - if (vec != nullptr) delete[] vec; + CC_SAFE_DELETE_ARRAY(vec); CC_BREAK_IF(i < count); _mass = PHYSICS_INFINITY; _moment = PHYSICS_INFINITY; - initEnd(); + setMaterial(material); return true; } while (false); - if (vec != nullptr) delete[] vec; + CC_SAFE_DELETE_ARRAY(vec); return false; } +Point PhysicsShapeEdgeChain::getCenter() +{ + return _center; +} + +int PhysicsShapeEdgeChain::getPointsCount() +{ + return _info->shapes.size() + 1; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 0aa7a160b6..30a186aa6b 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -41,17 +41,17 @@ class PhysicsBodyInfo; typedef struct PhysicsMaterial { float density; - float elasticity; + float restitution; float friction; PhysicsMaterial() : density(0.0f) - , elasticity(0.0f) + , restitution(0.0f) , friction(0.0f){} - PhysicsMaterial(float density, float elasticity, float friction) + PhysicsMaterial(float density, float restitution, float friction) : density(density) - , elasticity(elasticity) + , restitution(restitution) , friction(friction){} }PhysicsMaterial; @@ -83,19 +83,25 @@ public: void setMoment(float moment); inline void setTag(int tag) { _tag = tag; } inline int getTag() { return _tag; } - void setEnable(bool enable); - inline bool isEnable() { return _enable; } inline float getMass() { return _mass; } void setMass(float mass); inline float getDensity() { return _material.density; } void setDensity(float density); - void setElasticity(float elasticity); + void setRestitution(float restitution); void setFriction(float friction); + void setMaterial(PhysicsMaterial material); + + virtual float calculateDefaultMoment() { return 0; } + virtual float calculateDefaultArea() { return 0; } + virtual Point getOffset() { return Point::ZERO; } + virtual Point getCenter() { return getOffset(); } + + static Point* recenterPoints(Point* points, int count, Point center); + static Point getPolyonCenter(Point* points, int count); protected: - bool init(Type type, PhysicsMaterial material); - void initEnd(); + bool init(Type type); /** * @brief PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. @@ -117,7 +123,6 @@ protected: float _moment; PhysicsMaterial _material; int _tag; - bool _enable; friend class PhysicsWorld; friend class PhysicsBody; @@ -128,15 +133,20 @@ class PhysicsShapeCircle : public PhysicsShape { public: static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static float calculateArea(float radius); + static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); + float calculateDefaultArea() override; + float calculateDefaultMoment() override; + + float getRadius(); + Point getOffset(); protected: bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); protected: PhysicsShapeCircle(); - virtual ~PhysicsShapeCircle(); - - friend class PhysicsBody; + ~PhysicsShapeCircle(); }; /** A box shape */ @@ -144,6 +154,15 @@ class PhysicsShapeBox : public PhysicsShape { public: static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static float calculateArea(Size size); + static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); + + float calculateDefaultArea() override; + float calculateDefaultMoment() override; + + Point* getPoints(Point* points); + Size getSize(); + Point getOffset() override { return _offset; } protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -152,7 +171,8 @@ protected: PhysicsShapeBox(); virtual ~PhysicsShapeBox(); - friend class PhysicsBody; +protected: + Point _offset; }; /** A polygon shape */ @@ -160,7 +180,15 @@ class PhysicsShapePolygon : public PhysicsShape { public: static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static float calculateArea(Point* points, int count); + static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); + float calculateDefaultArea() override; + float calculateDefaultMoment() override; + + Point* getPoints(Point* points); + int getPointsCount(); + Point getCenter() override; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -168,7 +196,8 @@ protected: PhysicsShapePolygon(); virtual ~PhysicsShapePolygon(); - friend class PhysicsBody; +protected: + Point _center; }; /** A segment shape */ @@ -177,6 +206,10 @@ class PhysicsShapeEdgeSegment : public PhysicsShape public: static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + Point getPointA(); + Point getPointB(); + Point getCenter() override; + protected: bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -184,6 +217,9 @@ protected: PhysicsShapeEdgeSegment(); virtual ~PhysicsShapeEdgeSegment(); +protected: + Point _center; + friend class PhysicsBody; }; @@ -192,6 +228,9 @@ class PhysicsShapeEdgeBox : public PhysicsShape { public: static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); + Point getOffset() override { return _offset; } + Point* getPoints(Point* points); + int getPointsCount(); protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); @@ -200,6 +239,9 @@ protected: PhysicsShapeEdgeBox(); virtual ~PhysicsShapeEdgeBox(); +protected: + Point _offset; + friend class PhysicsBody; }; @@ -208,6 +250,9 @@ class PhysicsShapeEdgePolygon : public PhysicsShape { public: static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + Point getCenter() override; + Point* getPoints(Point* points); + int getPointsCount(); protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -217,6 +262,9 @@ protected: virtual ~PhysicsShapeEdgePolygon(); friend class PhysicsBody; + +protected: + Point _center; }; /** a chain shape */ @@ -224,6 +272,9 @@ class PhysicsShapeEdgeChain : public PhysicsShape { public: static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + Point getCenter() override; + Point* getPoints(Point* points); + int getPointsCount(); protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -232,6 +283,9 @@ protected: PhysicsShapeEdgeChain(); virtual ~PhysicsShapeEdgeChain(); +protected: + Point _center; + friend class PhysicsBody; }; diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 7ede980f53..4819ff743b 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -175,10 +175,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) // add shapes to space for (auto shape : body->getShapes()) { - if (shape->isEnable()) - { - addShape(shape); - } + addShape(shape); } } diff --git a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h index a026d632b7..704500c901 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h @@ -44,7 +44,7 @@ public: static float cpfloat2float(cpFloat f) { return f; } static cpFloat float2cpfloat(float f) { return f; } - static void cpvs2points(const cpVect* cpvs, Point* points, int count) + static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) { for (int i = 0; i < count; ++i) { From d1fead368dd292a7d7169e078f8a76dcf6a957de Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 15 Oct 2013 16:55:08 +0800 Subject: [PATCH 143/557] issue #2771: migrate the PhysicsBody definition --- cocos2dx/base_nodes/CCNode.cpp | 2 +- cocos2dx/physics/CCPhysicsBody.cpp | 121 ++++++++++++++++-- cocos2dx/physics/CCPhysicsBody.h | 26 +++- cocos2dx/physics/CCPhysicsWorld.cpp | 43 ++++++- cocos2dx/physics/chipmunk/CCPhysicsHelper.h | 2 + .../Classes/PhysicsTest/PhysicsTest.cpp | 11 +- 6 files changed, 186 insertions(+), 19 deletions(-) diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp index 47174c5790..4c3168fde4 100644 --- a/cocos2dx/base_nodes/CCNode.cpp +++ b/cocos2dx/base_nodes/CCNode.cpp @@ -897,7 +897,7 @@ void Node::transformAncestors() #ifdef CC_USE_PHYSICS void Node::updatePhysicsTransform() { - if (_physicsBody) + if (_physicsBody && _physicsBody->isEnable() && !_physicsBody->isResting()) { _position = _physicsBody->getPosition(); _rotationX = _rotationY = _physicsBody->getRotation(); diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index fee8712353..4fd1e45c62 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -65,12 +65,16 @@ PhysicsBody::PhysicsBody() , _info(nullptr) , _dynamic(true) , _enable(true) +, _rotationEnable(true) +, _gravityEnable(true) , _massDefault(true) , _momentDefault(true) , _mass(MASS_DEFAULT) -, _area(0.0) -, _density(0) +, _area(0.0f) +, _density(0.0f) , _moment(MOMENT_DEFAULT) +, _linearDamping(0.0f) +, _angularDamping(0.0f) , _tag(0) { } @@ -104,6 +108,11 @@ PhysicsBody* PhysicsBody::create() return nullptr; } +void update(float delta) +{ + +} + PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); @@ -229,17 +238,46 @@ void PhysicsBody::setDynamic(bool dynamic) { if (dynamic != _dynamic) { - if (dynamic) + _dynamic = dynamic; + if (_world != nullptr) { - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); - }else - { - cpBodySetMass(_info->body, PHYSICS_INFINITY); - cpBodySetMoment(_info->body, PHYSICS_INFINITY); + if (dynamic) + { + cpSpaceAddBody(_world->_info->space, _info->body); + }else + { + cpSpaceRemoveBody(_world->_info->space, _info->body); + } } - _dynamic = dynamic; + } +} + +void PhysicsBody::setRotationEnable(bool enable) +{ + if (_rotationEnable != enable) + { + cpBodySetMoment(_info->body, enable ? _moment : PHYSICS_INFINITY); + _rotationEnable = enable; + } +} + +void PhysicsBody::setGravityEnable(bool enable) +{ + if (_gravityEnable != enable) + { + _gravityEnable = enable; + + if (_world != nullptr) + { + if (enable) + { + applyForce(_world->getGravity()); + }else + { + applyForce(-_world->getGravity()); + } + } } } @@ -300,7 +338,10 @@ void PhysicsBody::addShape(PhysicsShape* shape) addMass(shape->getMass()); addMoment(shape->getMoment()); - if (_world != nullptr) _world->addShape(shape); + if (_world != nullptr) + { + _world->addShape(shape); + } shape->retain(); } @@ -308,7 +349,7 @@ void PhysicsBody::addShape(PhysicsShape* shape) void PhysicsBody::applyForce(Point force) { - applyForce(force, Point()); + applyForce(force, Point::ZERO); } void PhysicsBody::applyForce(Point force, Point offset) @@ -438,7 +479,10 @@ void PhysicsBody::addMoment(float moment) } } - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + if (_rotationEnable) + { + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + } } void PhysicsBody::setVelocity(Point velocity) @@ -451,12 +495,45 @@ Point PhysicsBody::getVelocity() return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); } +void PhysicsBody::setAngularVelocity(float velocity) +{ + cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); +} + +float PhysicsBody::getAngularVelocity() +{ + return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->body)); +} + +void PhysicsBody::setVelocityLimit(float limit) +{ + cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); +} + +float PhysicsBody::getVelocityLimit() +{ + return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->body)); +} + +void PhysicsBody::setAngularVelocityLimit(float limit) +{ + cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); +} + +float PhysicsBody::getAngularVelocityLimit() +{ + return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->body)); +} + void PhysicsBody::setMoment(float moment) { _moment = moment; _momentDefault = false; - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + if (_rotationEnable) + { + cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + } } PhysicsShape* PhysicsBody::getShapeByTag(int tag) @@ -542,6 +619,22 @@ void PhysicsBody::setEnable(bool enable) } } +bool PhysicsBody::isResting() +{ + return cpBodyIsSleeping(_info->body) == cpTrue; +} + +void PhysicsBody::update(float delta) +{ + // damping compute + if (_dynamic) + { + _info->body->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->body->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->body->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); + } +} + //Clonable* PhysicsBody::clone() const //{ // PhysicsBody* body = new PhysicsBody(); diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 84507cfb00..904d94a1bf 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -109,6 +109,12 @@ public: virtual void setVelocity(Point velocity); virtual Point getVelocity(); + virtual void setAngularVelocity(float velocity); + virtual float getAngularVelocity(); + virtual void setVelocityLimit(float limit); + virtual float getVelocityLimit(); + virtual void setAngularVelocityLimit(float limit); + virtual float getAngularVelocityLimit(); /* * @brief get the body shapes. @@ -214,13 +220,24 @@ public: /* * @brief get angular damping. */ - //inline float getAngularDamping() { return _angularDamping; } + inline float getLinearDamping() { return _linearDamping; } + inline void setLinearDamping(float damping) { _linearDamping = damping; } + inline float getAngularDamping() { return _angularDamping; } + inline void setAngularDamping(float damping) { _angularDamping = damping; } //virtual Clonable* clone() const override; + bool isResting(); inline bool isEnable() { return _enable; } void setEnable(bool enable); + inline bool isRotationEnable() { return _rotationEnable; } + void setRotationEnable(bool enable); + + inline bool isGravityEnable() { return _gravityEnable; } + void setGravityEnable(bool enable); + + inline int getTag() { return _tag; } inline void setTag(int tag) { _tag = tag; } @@ -232,6 +249,8 @@ protected: virtual void setPosition(Point position); virtual void setRotation(float rotation); + virtual void update(float delta) override; + protected: PhysicsBody(); virtual ~PhysicsBody(); @@ -244,13 +263,16 @@ protected: PhysicsBodyInfo* _info; bool _dynamic; bool _enable; + bool _rotationEnable; + bool _gravityEnable; bool _massDefault; bool _momentDefault; float _mass; float _area; float _density; float _moment; - //float _angularDamping; + float _linearDamping; + float _angularDamping; int _tag; int _categoryBitmask; diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 4819ff743b..1fda32540f 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -164,8 +164,16 @@ void PhysicsWorld::addShape(PhysicsShape* shape) void PhysicsWorld::addBody(PhysicsBody* body) { + CCASSERT(body != nullptr, "the body can not be nullptr"); + if (body->isEnable()) { + //is gravity enable + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + // add body to space if (body->isDynamic()) { @@ -191,6 +199,18 @@ void PhysicsWorld::addBody(PhysicsBody* body) void PhysicsWorld::removeBody(PhysicsBody* body) { + CCASSERT(body != nullptr, "the body can not be nullptr"); + + if (body->getWorld() == this) + { + // reset the gravity + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + } + + // remove shaps for (auto shape : body->getShapes()) { for (auto cps : shape->_info->shapes) @@ -202,6 +222,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) } } + // remove body if (cpSpaceContainsBody(_info->space, body->_info->body)) { cpSpaceRemoveBody(_info->space, body->_info->body); @@ -239,6 +260,11 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) void PhysicsWorld::update(float delta) { + for (auto body : *_bodys) + { + body->update(delta); + } + cpSpaceStep(_info->space, delta); if (_drawNode) @@ -370,8 +396,23 @@ void PhysicsWorld::collisionSeparateCallback(const PhysicsContact& contact) void PhysicsWorld::setGravity(Point gravity) { + if (_bodys != nullptr) + { + for (auto child : *_bodys) + { + PhysicsBody* body = dynamic_cast(child); + + // reset gravity for body + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + body->applyForce(gravity); + } + } + } + _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h index 704500c901..9334d87124 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h @@ -50,6 +50,8 @@ public: { points[i] = cpv2point(cpvs[i]); } + + return points; } static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 91c67da54d..5791cee7bc 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -169,7 +169,16 @@ void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); sp->setScale(scale); - sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); + auto body = PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale)); + + static int abc = 0; + + if (abc++ > 0) + { + body->setGravityEnable(false); + } + + sp->setPhysicsBody(body); this->addChild(sp); sp->setPosition(p); #endif From 6fc2be62f595a5fd303d3da1f1f0e4d30b086da0 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 15 Oct 2013 18:00:03 +0800 Subject: [PATCH 144/557] issue #2905: testcpp bild ok on Android --- cocos/2d/cocos2d.h | 4 + cocos/editor-support/cocosbuilder/Android.mk | 48 + .../cocosbuilder/CCBAnimationManager.cpp | 5 +- .../cocosbuilder/CCBAnimationManager.h | 122 +-- .../cocosbuilder/CCBFileLoader.cpp | 5 +- .../cocosbuilder/CCBFileLoader.h | 6 +- .../cocosbuilder/CCBKeyframe.cpp | 4 +- .../editor-support/cocosbuilder/CCBKeyframe.h | 13 +- .../cocosbuilder/CCBMemberVariableAssigner.h | 8 +- .../editor-support/cocosbuilder/CCBReader.cpp | 6 +- cocos/editor-support/cocosbuilder/CCBReader.h | 83 +- .../cocosbuilder/CCBSelectorResolver.h | 13 +- .../cocosbuilder/CCBSequence.cpp | 4 +- .../editor-support/cocosbuilder/CCBSequence.h | 7 +- .../cocosbuilder/CCBSequenceProperty.cpp | 4 +- .../cocosbuilder/CCBSequenceProperty.h | 11 +- .../editor-support/cocosbuilder/CCBValue.cpp | 6 +- cocos/editor-support/cocosbuilder/CCBValue.h | 21 +- .../cocosbuilder/CCControlButtonLoader.cpp | 6 +- .../cocosbuilder/CCControlButtonLoader.h | 24 +- .../cocosbuilder/CCControlLoader.cpp | 6 +- .../cocosbuilder/CCControlLoader.h | 12 +- .../cocosbuilder/CCLabelBMFontLoader.cpp | 6 +- .../cocosbuilder/CCLabelBMFontLoader.h | 16 +- .../cocosbuilder/CCLabelTTFLoader.cpp | 6 +- .../cocosbuilder/CCLabelTTFLoader.h | 22 +- .../cocosbuilder/CCLayerColorLoader.cpp | 6 +- .../cocosbuilder/CCLayerColorLoader.h | 12 +- .../cocosbuilder/CCLayerGradientLoader.cpp | 6 +- .../cocosbuilder/CCLayerGradientLoader.h | 14 +- .../cocosbuilder/CCLayerLoader.cpp | 8 +- .../cocosbuilder/CCLayerLoader.h | 8 +- .../cocosbuilder/CCMenuItemImageLoader.cpp | 6 +- .../cocosbuilder/CCMenuItemImageLoader.h | 8 +- .../cocosbuilder/CCMenuItemLoader.cpp | 6 +- .../cocosbuilder/CCMenuItemLoader.h | 10 +- .../cocosbuilder/CCMenuLoader.h | 6 +- .../CCNode+CCBRelativePositioning.cpp | 6 +- .../CCNode+CCBRelativePositioning.h | 9 +- .../cocosbuilder/CCNodeLoader.cpp | 6 +- .../cocosbuilder/CCNodeLoader.h | 146 +-- .../cocosbuilder/CCNodeLoaderLibrary.cpp | 6 +- .../cocosbuilder/CCNodeLoaderLibrary.h | 6 +- .../cocosbuilder/CCNodeLoaderListener.h | 6 +- .../CCParticleSystemQuadLoader.cpp | 6 +- .../cocosbuilder/CCParticleSystemQuadLoader.h | 24 +- .../cocosbuilder/CCScale9SpriteLoader.cpp | 7 +- .../cocosbuilder/CCScale9SpriteLoader.h | 20 +- .../cocosbuilder/CCScrollViewLoader.cpp | 7 +- .../cocosbuilder/CCScrollViewLoader.h | 18 +- .../cocosbuilder/CCSpriteLoader.cpp | 6 +- .../cocosbuilder/CCSpriteLoader.h | 16 +- .../cocosbuilder/CocosBuilder.h | 32 + cocos/editor-support/cocostudio/Android.mk | 64 ++ cocos/editor-support/cocostudio/CocoStudio.h | 62 ++ .../cocostudio/action/CCActionFrame.cpp | 6 +- .../cocostudio/action/CCActionFrame.h | 31 +- .../cocostudio/action/CCActionFrameEasing.cpp | 6 +- .../cocostudio/action/CCActionFrameEasing.h | 7 +- .../cocostudio/action/CCActionManagerEx.cpp | 12 +- .../cocostudio/action/CCActionManagerEx.h | 13 +- .../cocostudio/action/CCActionNode.cpp | 17 +- .../cocostudio/action/CCActionNode.h | 29 +- .../cocostudio/action/CCActionObject.cpp | 12 +- .../cocostudio/action/CCActionObject.h | 13 +- .../cocostudio/armature/CCArmature.cpp | 6 +- .../cocostudio/armature/CCArmature.h | 26 +- .../cocostudio/armature/CCBone.cpp | 6 +- .../cocostudio/armature/CCBone.h | 18 +- .../animation/CCArmatureAnimation.cpp | 16 +- .../armature/animation/CCArmatureAnimation.h | 18 +- .../armature/animation/CCProcessBase.cpp | 8 +- .../armature/animation/CCProcessBase.h | 10 +- .../cocostudio/armature/animation/CCTween.cpp | 14 +- .../cocostudio/armature/animation/CCTween.h | 6 +- .../cocostudio/armature/datas/CCDatas.cpp | 10 +- .../cocostudio/armature/datas/CCDatas.h | 48 +- .../armature/display/CCBatchNode.cpp | 10 +- .../cocostudio/armature/display/CCBatchNode.h | 12 +- .../armature/display/CCDecorativeDisplay.cpp | 6 +- .../armature/display/CCDecorativeDisplay.h | 12 +- .../armature/display/CCDisplayFactory.cpp | 18 +- .../armature/display/CCDisplayFactory.h | 14 +- .../armature/display/CCDisplayManager.cpp | 14 +- .../armature/display/CCDisplayManager.h | 32 +- .../cocostudio/armature/display/CCSkin.cpp | 12 +- .../cocostudio/armature/display/CCSkin.h | 16 +- .../armature/physics/CCColliderDetector.cpp | 9 +- .../armature/physics/CCColliderDetector.h | 20 +- .../armature/utils/CCArmatureDataManager.cpp | 5 +- .../armature/utils/CCArmatureDataManager.h | 24 +- .../armature/utils/CCArmatureDefine.cpp | 4 +- .../armature/utils/CCArmatureDefine.h | 9 +- .../armature/utils/CCDataReaderHelper.cpp | 56 +- .../armature/utils/CCDataReaderHelper.h | 38 +- .../utils/CCSpriteFrameCacheHelper.cpp | 6 +- .../armature/utils/CCSpriteFrameCacheHelper.h | 8 +- .../armature/utils/CCTransformHelp.cpp | 6 +- .../armature/utils/CCTransformHelp.h | 18 +- .../armature/utils/CCTweenFunction.cpp | 4 +- .../armature/utils/CCTweenFunction.h | 4 +- .../cocostudio/armature/utils/CCUtilMath.cpp | 6 +- .../cocostudio/armature/utils/CCUtilMath.h | 14 +- .../cocostudio/components/CCComAttribute.cpp | 9 +- .../cocostudio/components/CCComAttribute.h | 15 +- .../cocostudio/components/CCComAudio.cpp | 4 +- .../cocostudio/components/CCComAudio.h | 5 +- .../cocostudio/components/CCComController.cpp | 4 +- .../cocostudio/components/CCComController.h | 4 +- .../cocostudio/components/CCComRender.cpp | 4 +- .../cocostudio/components/CCComRender.h | 6 +- .../cocostudio/components/CCInputDelegate.cpp | 6 +- .../cocostudio/components/CCInputDelegate.h | 57 +- .../editor-support/cocostudio/json/.DS_Store | Bin 0 -> 6148 bytes .../json/CSContentJsonDictionary.cpp | 50 +- .../cocostudio/json/CSContentJsonDictionary.h | 12 +- .../cocostudio/json/DictionaryHelper.cpp | 28 +- .../cocostudio/json/DictionaryHelper.h | 31 +- .../cocostudio/reader/CCSGUIReader.cpp | 103 +- .../cocostudio/reader/CCSGUIReader.h | 54 +- .../cocostudio/reader/CCSSceneReader.cpp | 36 +- .../cocostudio/reader/CCSSceneReader.h | 11 +- cocos/editor-support/spine/Android.mk | 42 + cocos/editor-support/spine/Animation.cpp | 4 +- cocos/editor-support/spine/Animation.h | 4 +- cocos/editor-support/spine/AnimationState.cpp | 4 +- cocos/editor-support/spine/AnimationState.h | 4 +- .../spine/AnimationStateData.cpp | 4 +- .../editor-support/spine/AnimationStateData.h | 4 +- cocos/editor-support/spine/Atlas.cpp | 4 +- cocos/editor-support/spine/Atlas.h | 4 +- .../spine/AtlasAttachmentLoader.cpp | 4 +- .../spine/AtlasAttachmentLoader.h | 4 +- cocos/editor-support/spine/Attachment.cpp | 4 +- cocos/editor-support/spine/Attachment.h | 4 +- .../editor-support/spine/AttachmentLoader.cpp | 4 +- cocos/editor-support/spine/AttachmentLoader.h | 4 +- cocos/editor-support/spine/Bone.cpp | 4 +- cocos/editor-support/spine/Bone.h | 4 +- cocos/editor-support/spine/BoneData.cpp | 4 +- cocos/editor-support/spine/BoneData.h | 4 +- cocos/editor-support/spine/CCSkeleton.cpp | 4 +- cocos/editor-support/spine/CCSkeleton.h | 5 +- .../spine/CCSkeletonAnimation.cpp | 4 +- .../spine/CCSkeletonAnimation.h | 4 +- cocos/editor-support/spine/Json.cpp | 4 +- cocos/editor-support/spine/Json.h | 4 +- .../editor-support/spine/RegionAttachment.cpp | 4 +- cocos/editor-support/spine/RegionAttachment.h | 4 +- cocos/editor-support/spine/Skeleton.cpp | 4 +- cocos/editor-support/spine/Skeleton.h | 4 +- cocos/editor-support/spine/SkeletonData.cpp | 4 +- cocos/editor-support/spine/SkeletonData.h | 4 +- cocos/editor-support/spine/SkeletonJson.cpp | 4 +- cocos/editor-support/spine/SkeletonJson.h | 4 +- cocos/editor-support/spine/Skin.cpp | 4 +- cocos/editor-support/spine/Skin.h | 4 +- cocos/editor-support/spine/Slot.cpp | 4 +- cocos/editor-support/spine/Slot.h | 4 +- cocos/editor-support/spine/SlotData.cpp | 4 +- cocos/editor-support/spine/SlotData.h | 4 +- cocos/editor-support/spine/extension.cpp | 4 +- cocos/editor-support/spine/extension.h | 4 +- cocos/editor-support/spine/spine-cocos2dx.cpp | 4 +- cocos/editor-support/spine/spine-cocos2dx.h | 4 +- cocos/gui/Android.mk | 50 + cocos/gui/base-classes/UIRootWidget.cpp | 6 +- cocos/gui/base-classes/UIRootWidget.h | 6 +- cocos/gui/base-classes/UIWidget.cpp | 12 +- cocos/gui/base-classes/UIWidget.h | 117 ++- cocos/gui/layouts/Layout.cpp | 15 +- cocos/gui/layouts/Layout.h | 50 +- cocos/gui/layouts/LayoutParameter.cpp | 4 +- cocos/gui/layouts/LayoutParameter.h | 6 +- cocos/gui/layouts/UILayoutDefine.cpp | 4 +- cocos/gui/layouts/UILayoutDefine.h | 5 +- cocos/gui/system/CocosGUI.cpp | 4 +- cocos/gui/system/CocosGUI.h | 38 +- cocos/gui/system/UIHelper.cpp | 12 +- cocos/gui/system/UIHelper.h | 10 +- cocos/gui/system/UIInputManager.cpp | 6 +- cocos/gui/system/UIInputManager.h | 32 +- cocos/gui/system/UILayer.cpp | 6 +- cocos/gui/system/UILayer.h | 19 +- cocos/gui/widgets/UIButton.cpp | 9 +- cocos/gui/widgets/UIButton.h | 48 +- cocos/gui/widgets/UICheckBox.cpp | 6 +- cocos/gui/widgets/UICheckBox.h | 32 +- cocos/gui/widgets/UIImageView.cpp | 9 +- cocos/gui/widgets/UIImageView.h | 26 +- cocos/gui/widgets/UILabel.cpp | 6 +- cocos/gui/widgets/UILabel.h | 20 +- cocos/gui/widgets/UILabelAtlas.cpp | 6 +- cocos/gui/widgets/UILabelAtlas.h | 16 +- cocos/gui/widgets/UILabelBMFont.cpp | 8 +- cocos/gui/widgets/UILabelBMFont.h | 14 +- cocos/gui/widgets/UILoadingBar.cpp | 9 +- cocos/gui/widgets/UILoadingBar.h | 18 +- cocos/gui/widgets/UISlider.cpp | 9 +- cocos/gui/widgets/UISlider.h | 48 +- cocos/gui/widgets/UITextField.cpp | 6 +- cocos/gui/widgets/UITextField.h | 34 +- .../UIDragPanel.cpp | 8 +- .../UIDragPanel.h | 70 +- .../UIListView.cpp | 6 +- .../UIListView.h | 44 +- .../UIPageView.cpp | 6 +- .../UIPageView.h | 34 +- .../UIScrollInterface.h | 14 +- .../UIScrollView.cpp | 8 +- .../UIScrollView.h | 40 +- cocos/network/Android.mk | 28 + cocos/network/HttpClient.cpp | 6 +- cocos/network/HttpClient.h | 8 +- cocos/network/HttpRequest.h | 23 +- cocos/network/HttpResponse.h | 9 +- cocos/network/SocketIO.cpp | 30 +- cocos/network/SocketIO.h | 9 +- cocos/network/WebSocket.cpp | 6 +- cocos/network/WebSocket.h | 5 +- cocos/storage/local-storage/Android.mk | 19 + extensions/Android.mk | 14 +- extensions/CCDeprecated-ext.cpp | 31 - extensions/CCDeprecated-ext.h | 278 ----- .../GUI/CCControlExtension/CCControl.cpp | 8 +- .../CCControlExtension/CCControlButton.cpp | 8 +- .../CCControlColourPicker.cpp | 4 +- .../CCControlExtension/CCControlSlider.cpp | 2 +- .../GUI/CCControlExtension/CCControlUtils.h | 2 +- .../GUI/CCControlExtension/CCInvocation.h | 2 +- extensions/GUI/CCScrollView/CCSorting.cpp | 2 +- extensions/GUI/CCScrollView/CCSorting.h | 2 +- extensions/GUI/CCScrollView/CCTableView.cpp | 4 +- .../GUI/CCScrollView/CCTableViewCell.cpp | 2 +- extensions/GUI/CCScrollView/CCTableViewCell.h | 2 +- extensions/assets-manager/AssetsManager.cpp | 2 +- extensions/cocos-ext.h | 72 +- .../physics-nodes/CCPhysicsDebugNode.cpp | 2 +- .../curl/include/android/{ => curl}/curl.h | 0 .../include/android/{ => curl}/curlbuild.h | 0 .../include/android/{ => curl}/curlrules.h | 0 .../curl/include/android/{ => curl}/curlver.h | 0 .../curl/include/android/{ => curl}/easy.h | 0 .../curl/include/android/{ => curl}/mprintf.h | 0 .../curl/include/android/{ => curl}/multi.h | 0 .../include/android/{ => curl}/stdcheaders.h | 0 .../android/{ => curl}/typecheck-gcc.h | 0 .../curl/include/android/{ => curl}/types.h | 0 external/curl/include/ios/{ => curl}/curl.h | 0 .../curl/include/ios/{ => curl}/curlbuild.h | 0 .../curl/include/ios/{ => curl}/curlrules.h | 0 .../curl/include/ios/{ => curl}/curlver.h | 0 external/curl/include/ios/{ => curl}/easy.h | 0 .../curl/include/ios/{ => curl}/mprintf.h | 0 external/curl/include/ios/{ => curl}/multi.h | 0 .../curl/include/ios/{ => curl}/stdcheaders.h | 0 .../include/ios/{ => curl}/typecheck-gcc.h | 0 .../include/linux/32-bit/{ => curl}/curl.h | 0 .../linux/32-bit/{ => curl}/curlbuild.h | 0 .../linux/32-bit/{ => curl}/curlrules.h | 0 .../include/linux/32-bit/{ => curl}/curlver.h | 0 .../include/linux/32-bit/{ => curl}/easy.h | 0 .../include/linux/32-bit/{ => curl}/mprintf.h | 0 .../include/linux/32-bit/{ => curl}/multi.h | 0 .../linux/32-bit/{ => curl}/stdcheaders.h | 0 .../linux/32-bit/{ => curl}/typecheck-gcc.h | 0 .../include/linux/64-bit/{ => curl}/curl.h | 0 .../linux/64-bit/{ => curl}/curlbuild.h | 0 .../linux/64-bit/{ => curl}/curlrules.h | 0 .../include/linux/64-bit/{ => curl}/curlver.h | 0 .../include/linux/64-bit/{ => curl}/easy.h | 0 .../include/linux/64-bit/{ => curl}/mprintf.h | 0 .../include/linux/64-bit/{ => curl}/multi.h | 0 .../linux/64-bit/{ => curl}/stdcheaders.h | 0 external/curl/include/win32/{ => curl}/curl.h | 0 .../curl/include/win32/{ => curl}/curlbuild.h | 0 .../curl/include/win32/{ => curl}/curlrules.h | 0 .../curl/include/win32/{ => curl}/curlver.h | 0 external/curl/include/win32/{ => curl}/easy.h | 0 .../curl/include/win32/{ => curl}/mprintf.h | 0 .../curl/include/win32/{ => curl}/multi.h | 0 .../include/win32/{ => curl}/stdcheaders.h | 0 .../include/win32/{ => curl}/typecheck-gcc.h | 0 external/{jsoncpp => json}/autolink.h | 5 - external/json/config.h | 43 + external/{jsoncpp => json}/features.h | 11 +- external/{jsoncpp => json}/forwards.h | 15 +- external/json/json.h | 10 + .../{jsoncpp => json}/json_batchallocator.h | 9 +- .../{jsoncpp => json}/json_internalarray.inl | 10 +- .../{jsoncpp => json}/json_internalmap.inl | 12 +- external/{jsoncpp => json}/json_reader.cpp | 113 +- external/{jsoncpp => json}/json_value.cpp | 483 ++++----- .../{jsoncpp => json}/json_valueiterator.inl | 9 +- external/{jsoncpp => json}/json_writer.cpp | 85 +- external/{jsoncpp => json}/reader.h | 40 +- external/{jsoncpp => json}/sconscript | 0 external/{jsoncpp => json}/value.h | 132 +-- external/{jsoncpp => json}/writer.h | 17 +- external/jsoncpp/config.h | 96 -- external/jsoncpp/json_lib.h | 15 - external/jsoncpp/json_tool.h | 93 -- .../android}/libwebsockets.h | 0 .../include => include/ios}/libwebsockets.h | 0 .../include => include/mac}/libwebsockets.h | 0 .../include => include/win32}/libwebsockets.h | 0 .../win32}/win32helpers/gettimeofday.h | 0 .../win32}/win32helpers/websock-w32.h | 0 .../{ => prebuilt}/android/Android.mk | 4 +- .../ios}/libwebsockets.a.REMOVED.git-id | 0 .../mac}/libwebsockets.a.REMOVED.git-id | 0 .../websockets/tizen/include/libwebsockets.h | 977 ------------------ .../lib/armv7l/libwebsockets.a.REMOVED.git-id | 1 - .../lib/x86/libwebsockets.a.REMOVED.git-id | 1 - samples/Cpp/TestCpp/Android.mk | 18 +- samples/Cpp/TestCpp/Classes/AppDelegate.cpp | 3 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 3 +- .../CocoStudioArmatureTest/ArmatureScene.h | 27 +- .../ComponentsTestScene.cpp | 1 + .../EnemyController.cpp | 1 + .../EnemyController.h | 3 +- .../PlayerController.cpp | 2 +- .../PlayerController.h | 3 +- .../ProjectileController.cpp | 1 + .../ProjectileController.h | 4 +- .../SceneController.cpp | 1 + .../SceneController.h | 6 +- .../CocoStudioGUITest/CocosGUIScene.cpp | 7 +- .../CocoStudioGUITest/CocosGUIScene.h | 2 + .../UIButtonTest/UIButtonTest.cpp | 24 +- .../UICheckBoxTest/UICheckBoxTest.cpp | 4 +- .../CocoStudioGUITest/UIScene.cpp | 2 + .../CocoStudioGUITest/UIScene.h | 2 + .../UITextButtonTest/UITextButtonTest.cpp | 16 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 13 +- .../AnimationsTest/AnimationsLayerLoader.h | 2 +- .../AnimationsTest/AnimationsTestLayer.cpp | 3 +- .../AnimationsTest/AnimationsTestLayer.h | 9 +- .../ButtonTest/ButtonTestLayer.cpp | 3 +- .../ButtonTest/ButtonTestLayer.h | 5 +- .../ButtonTest/ButtonTestLayerLoader.h | 2 +- .../CocosBuilderTest/CocosBuilderTest.cpp | 3 +- .../HelloCocosBuilderLayer.cpp | 23 +- .../HelloCocosBuilderLayer.h | 13 +- .../HelloCocosBuilderLayerLoader.h | 2 +- .../LabelTest/LabelTestLayerLoader.h | 2 +- .../MenuTest/MenuTestLayer.cpp | 1 + .../CocosBuilderTest/MenuTest/MenuTestLayer.h | 5 +- .../MenuTest/MenuTestLayerLoader.h | 2 +- .../ParticleSystemTestLayerLoader.h | 2 +- .../ScrollViewTestLayerLoader.h | 2 +- .../SpriteTest/SpriteTestLayerLoader.h | 2 +- .../TestHeader/TestHeaderLayer.cpp | 3 +- .../TestHeader/TestHeaderLayer.h | 7 +- .../TestHeader/TestHeaderLayerLoader.h | 2 +- .../TimelineCallbackLayerLoader.h | 2 +- .../TimelineCallbackTestLayer.cpp | 1 + .../TimelineCallbackTestLayer.h | 5 +- .../NetworkTest/HttpClientTest.cpp | 1 + .../NetworkTest/HttpClientTest.h | 3 +- .../NetworkTest/SocketIOTest.cpp | 9 +- .../ExtensionsTest/NetworkTest/SocketIOTest.h | 18 +- .../NetworkTest/WebSocketTest.cpp | 9 +- .../NetworkTest/WebSocketTest.h | 18 +- .../NotificationCenterTest.cpp | 2 +- .../PerformanceTest/PerformanceAllocTest.h | 2 +- .../PerformanceNodeChildrenTest.h | 2 +- .../TestCpp/Classes/SpineTest/SpineTest.cpp | 3 +- .../Cpp/TestCpp/Classes/SpineTest/SpineTest.h | 2 +- .../TextureAtlasEncryptionTest.cpp | 2 +- samples/Cpp/TestCpp/Classes/testBasic.cpp | 3 +- .../Cpp/TestCpp/proj.android/build_native.sh | 2 +- .../Cpp/TestCpp/proj.android/jni/Android.mk | 11 - 373 files changed, 2568 insertions(+), 3844 deletions(-) create mode 100644 cocos/editor-support/cocosbuilder/Android.mk create mode 100644 cocos/editor-support/cocosbuilder/CocosBuilder.h create mode 100644 cocos/editor-support/cocostudio/Android.mk create mode 100644 cocos/editor-support/cocostudio/CocoStudio.h create mode 100644 cocos/editor-support/cocostudio/json/.DS_Store create mode 100644 cocos/editor-support/spine/Android.mk create mode 100644 cocos/gui/Android.mk rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIDragPanel.cpp (99%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIDragPanel.h (80%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIListView.cpp (99%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIListView.h (84%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIPageView.cpp (99%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIPageView.h (84%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIScrollInterface.h (82%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIScrollView.cpp (99%) rename cocos/gui/widgets/{ScrollWidget => scroll-widget}/UIScrollView.h (85%) create mode 100644 cocos/network/Android.mk create mode 100644 cocos/storage/local-storage/Android.mk delete mode 100644 extensions/CCDeprecated-ext.cpp delete mode 100644 extensions/CCDeprecated-ext.h rename external/curl/include/android/{ => curl}/curl.h (100%) rename external/curl/include/android/{ => curl}/curlbuild.h (100%) rename external/curl/include/android/{ => curl}/curlrules.h (100%) rename external/curl/include/android/{ => curl}/curlver.h (100%) rename external/curl/include/android/{ => curl}/easy.h (100%) rename external/curl/include/android/{ => curl}/mprintf.h (100%) rename external/curl/include/android/{ => curl}/multi.h (100%) rename external/curl/include/android/{ => curl}/stdcheaders.h (100%) rename external/curl/include/android/{ => curl}/typecheck-gcc.h (100%) rename external/curl/include/android/{ => curl}/types.h (100%) rename external/curl/include/ios/{ => curl}/curl.h (100%) rename external/curl/include/ios/{ => curl}/curlbuild.h (100%) rename external/curl/include/ios/{ => curl}/curlrules.h (100%) rename external/curl/include/ios/{ => curl}/curlver.h (100%) rename external/curl/include/ios/{ => curl}/easy.h (100%) rename external/curl/include/ios/{ => curl}/mprintf.h (100%) rename external/curl/include/ios/{ => curl}/multi.h (100%) rename external/curl/include/ios/{ => curl}/stdcheaders.h (100%) rename external/curl/include/ios/{ => curl}/typecheck-gcc.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/curl.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/curlbuild.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/curlrules.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/curlver.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/easy.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/mprintf.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/multi.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/stdcheaders.h (100%) rename external/curl/include/linux/32-bit/{ => curl}/typecheck-gcc.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/curl.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/curlbuild.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/curlrules.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/curlver.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/easy.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/mprintf.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/multi.h (100%) rename external/curl/include/linux/64-bit/{ => curl}/stdcheaders.h (100%) rename external/curl/include/win32/{ => curl}/curl.h (100%) rename external/curl/include/win32/{ => curl}/curlbuild.h (100%) rename external/curl/include/win32/{ => curl}/curlrules.h (100%) rename external/curl/include/win32/{ => curl}/curlver.h (100%) rename external/curl/include/win32/{ => curl}/easy.h (100%) rename external/curl/include/win32/{ => curl}/mprintf.h (100%) rename external/curl/include/win32/{ => curl}/multi.h (100%) rename external/curl/include/win32/{ => curl}/stdcheaders.h (100%) rename external/curl/include/win32/{ => curl}/typecheck-gcc.h (100%) rename external/{jsoncpp => json}/autolink.h (65%) create mode 100644 external/json/config.h rename external/{jsoncpp => json}/features.h (78%) rename external/{jsoncpp => json}/forwards.h (61%) create mode 100644 external/json/json.h rename external/{jsoncpp => json}/json_batchallocator.h (93%) rename external/{jsoncpp => json}/json_internalarray.inl (97%) rename external/{jsoncpp => json}/json_internalmap.inl (98%) rename external/{jsoncpp => json}/json_reader.cpp (89%) rename external/{jsoncpp => json}/json_value.cpp (79%) rename external/{jsoncpp => json}/json_valueiterator.inl (96%) rename external/{jsoncpp => json}/json_writer.cpp (93%) rename external/{jsoncpp => json}/reader.h (82%) rename external/{jsoncpp => json}/sconscript (100%) rename external/{jsoncpp => json}/value.h (90%) rename external/{jsoncpp => json}/writer.h (91%) delete mode 100644 external/jsoncpp/config.h delete mode 100644 external/jsoncpp/json_lib.h delete mode 100644 external/jsoncpp/json_tool.h rename external/websockets/{android/include => include/android}/libwebsockets.h (100%) rename external/websockets/{ios/include => include/ios}/libwebsockets.h (100%) rename external/websockets/{mac/include => include/mac}/libwebsockets.h (100%) rename external/websockets/{win32/include => include/win32}/libwebsockets.h (100%) rename external/websockets/{win32/include => include/win32}/win32helpers/gettimeofday.h (100%) rename external/websockets/{win32/include => include/win32}/win32helpers/websock-w32.h (100%) rename external/websockets/{ => prebuilt}/android/Android.mk (69%) rename external/websockets/{ios/lib => prebuilt/ios}/libwebsockets.a.REMOVED.git-id (100%) rename external/websockets/{mac/lib => prebuilt/mac}/libwebsockets.a.REMOVED.git-id (100%) delete mode 100644 external/websockets/tizen/include/libwebsockets.h delete mode 100644 external/websockets/tizen/lib/armv7l/libwebsockets.a.REMOVED.git-id delete mode 100644 external/websockets/tizen/lib/x86/libwebsockets.a.REMOVED.git-id diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index 9799e0a9fd..a1a28e7f0c 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -122,6 +122,10 @@ THE SOFTWARE. #include "CCPhysicsJoint.h" #include "CCPhysicsWorld.h" +// kazmath +#include "kazmath/kazmath.h" +#include "kazmath/GL/matrix.h" + // platform #include "platform/CCDevice.h" #include "platform/CCCommon.h" diff --git a/cocos/editor-support/cocosbuilder/Android.mk b/cocos/editor-support/cocosbuilder/Android.mk new file mode 100644 index 0000000000..dd6b2b3b77 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/Android.mk @@ -0,0 +1,48 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := cocosbuilder_static + +LOCAL_MODULE_FILENAME := libcocosbuilder + +LOCAL_SRC_FILES := CCBAnimationManager.cpp \ +CCBFileLoader.cpp \ +CCBKeyframe.cpp \ +CCBReader.cpp \ +CCBSequence.cpp \ +CCBSequenceProperty.cpp \ +CCBValue.cpp \ +CCControlButtonLoader.cpp \ +CCControlLoader.cpp \ +CCLabelBMFontLoader.cpp \ +CCLabelTTFLoader.cpp \ +CCLayerColorLoader.cpp \ +CCLayerGradientLoader.cpp \ +CCLayerLoader.cpp \ +CCMenuItemImageLoader.cpp \ +CCMenuItemLoader.cpp \ +CCNode+CCBRelativePositioning.cpp \ +CCNodeLoader.cpp \ +CCNodeLoaderLibrary.cpp \ +CCParticleSystemQuadLoader.cpp \ +CCScale9SpriteLoader.cpp \ +CCScrollViewLoader.cpp \ +CCSpriteLoader.cpp + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/ \ +$(LOCAL_PATH)/../../.. + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ +$(LOCAL_PATH) \ +$(LOCAL_PATH)/../../.. + +LOCAL_CFLAGS += -Wno-psabi +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,2d) +$(call import-module,extensions) diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index 819986e00a..13b039dcac 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -11,8 +11,9 @@ using namespace cocos2d; using namespace std; +using namespace cocos2d::extension; -NS_CC_EXT_BEGIN +namespace cocosbuilder { // Implementation of CCBAinmationManager @@ -1292,4 +1293,4 @@ void CCBEaseInstant::update(float dt) } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h index ca679ee1e9..83d962ffef 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h @@ -6,9 +6,9 @@ #include "CCBSequence.h" #include "CCBValue.h" #include "CCBSequenceProperty.h" -#include "GUI/CCControlExtension/CCControl.h" +#include "extensions/GUI/CCControlExtension/CCControl.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { class CCBAnimationManagerDelegate { @@ -16,7 +16,7 @@ public: virtual void completedAnimationSequenceNamed(const char *name) = 0; }; -class CCBAnimationManager : public Object +class CCBAnimationManager : public cocos2d::Object { public: bool _jsControlled; @@ -31,54 +31,54 @@ public: ~CCBAnimationManager(); - Object *_owner; + cocos2d::Object *_owner; virtual bool init(); - Array* getSequences(); - void setSequences(Array* seq); + cocos2d::Array* getSequences(); + void setSequences(cocos2d::Array* seq); int getAutoPlaySequenceId(); void setAutoPlaySequenceId(int autoPlaySequenceId); - Node* getRootNode(); - void setRootNode(Node* pRootNode); // weak reference + cocos2d::Node* getRootNode(); + void setRootNode(cocos2d::Node* pRootNode); // weak reference - void addDocumentCallbackNode(Node *node); + void addDocumentCallbackNode(cocos2d::Node *node); void addDocumentCallbackName(std::string name); - void addDocumentCallbackControlEvents(Control::EventType eventType); + void addDocumentCallbackControlEvents(cocos2d::extension::Control::EventType eventType); - void addDocumentOutletNode(Node *node); + void addDocumentOutletNode(cocos2d::Node *node); void addDocumentOutletName(std::string name); void setDocumentControllerName(const std::string &name); std::string getDocumentControllerName(); - Array* getDocumentCallbackNames(); - Array* getDocumentCallbackNodes(); - Array* getDocumentCallbackControlEvents(); + cocos2d::Array* getDocumentCallbackNames(); + cocos2d::Array* getDocumentCallbackNodes(); + cocos2d::Array* getDocumentCallbackControlEvents(); - Array* getDocumentOutletNames(); - Array* getDocumentOutletNodes(); + cocos2d::Array* getDocumentOutletNames(); + cocos2d::Array* getDocumentOutletNodes(); std::string getLastCompletedSequenceName(); - Array* getKeyframeCallbacks(); + cocos2d::Array* getKeyframeCallbacks(); - const Size& getRootContainerSize(); - void setRootContainerSize(const Size &rootContainerSize); + const cocos2d::Size& getRootContainerSize(); + void setRootContainerSize(const cocos2d::Size &rootContainerSize); CCBAnimationManagerDelegate* getDelegate(); void setDelegate(CCBAnimationManagerDelegate* pDelegate); // retain const char* getRunningSequenceName(); - const Size& getContainerSize(Node* pNode); + const cocos2d::Size& getContainerSize(cocos2d::Node* pNode); - void addNode(Node *pNode, Dictionary *pSeq); - void setBaseValue(Object *pValue, Node *pNode, const char *propName); - void moveAnimationsFromNode(Node* fromNode, Node* toNode); + void addNode(cocos2d::Node *pNode, cocos2d::Dictionary *pSeq); + void setBaseValue(cocos2d::Object *pValue, cocos2d::Node *pNode, const char *propName); + void moveAnimationsFromNode(cocos2d::Node* fromNode, cocos2d::Node* toNode); /** @deprecated This interface will be deprecated sooner or later.*/ CC_DEPRECATED_ATTRIBUTE void runAnimations(const char *pName, float fTweenDuration); @@ -94,16 +94,16 @@ public: * when this function bound to js ,the second param are callfunc_selector * @lua NA */ - void setAnimationCompletedCallback(Object *target, SEL_CallFunc callbackFunc); + void setAnimationCompletedCallback(cocos2d::Object *target, cocos2d::SEL_CallFunc callbackFunc); void debug(); /** * @js setCallFuncForJSCallbackNamed */ - void setCallFunc(CallFunc *callFunc, const std::string &callbackNamed); + void setCallFunc(cocos2d::CallFunc *callFunc, const std::string &callbackNamed); - Object* actionForCallbackChannel(CCBSequenceProperty* channel); - Object* actionForSoundChannel(CCBSequenceProperty* channel); + cocos2d::Object* actionForCallbackChannel(CCBSequenceProperty* channel); + cocos2d::Object* actionForSoundChannel(CCBSequenceProperty* channel); // return -1 if timeline not exsit int getSequenceId(const char* pSequenceName); @@ -112,55 +112,55 @@ public: float getSequenceDuration(const char* pSequenceName); private: - Object* getBaseValue(Node *pNode, const char* propName); + cocos2d::Object* getBaseValue(cocos2d::Node *pNode, const char* propName); CCBSequence* getSequence(int nSequenceId); - ActionInterval* getAction(CCBKeyframe *pKeyframe0, CCBKeyframe *pKeyframe1, const char *propName, Node *pNode); - void setAnimatedProperty(const char *propName, Node *pNode, Object *pValue, float fTweenDuraion); - void setFirstFrame(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); - ActionInterval* getEaseAction(ActionInterval *pAction, CCBKeyframe::EasingType easingType, float fEasingOpt); - void runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); + cocos2d::ActionInterval* getAction(CCBKeyframe *pKeyframe0, CCBKeyframe *pKeyframe1, const char *propName, cocos2d::Node *pNode); + void setAnimatedProperty(const char *propName,cocos2d::Node *pNode, Object *pValue, float fTweenDuraion); + void setFirstFrame(cocos2d::Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); + cocos2d::ActionInterval* getEaseAction(cocos2d::ActionInterval *pAction, CCBKeyframe::EasingType easingType, float fEasingOpt); + void runAction(cocos2d::Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); void sequenceCompleted(); private: - Array *_sequences; - Dictionary *_nodeSequences; - Dictionary *_baseValues; + cocos2d::Array *_sequences; + cocos2d::Dictionary *_nodeSequences; + cocos2d::Dictionary *_baseValues; int _autoPlaySequenceId; - Node *_rootNode; + cocos2d::Node *_rootNode; - Size _rootContainerSize; + cocos2d::Size _rootContainerSize; CCBAnimationManagerDelegate *_delegate; CCBSequence *_runningSequence; - Array *_documentOutletNames; - Array *_documentOutletNodes; - Array *_documentCallbackNames; - Array *_documentCallbackNodes; - Array *_documentCallbackControlEvents; - Array *_keyframeCallbacks; - Dictionary *_keyframeCallFuncs; + cocos2d::Array *_documentOutletNames; + cocos2d::Array *_documentOutletNodes; + cocos2d::Array *_documentCallbackNames; + cocos2d::Array *_documentCallbackNodes; + cocos2d::Array *_documentCallbackControlEvents; + cocos2d::Array *_keyframeCallbacks; + cocos2d::Dictionary *_keyframeCallFuncs; std::string _documentControllerName; std::string _lastCompletedSequenceName; - SEL_CallFunc _animationCompleteCallbackFunc; - Object *_target; + cocos2d::SEL_CallFunc _animationCompleteCallbackFunc; + cocos2d::Object *_target; }; -class CCBSetSpriteFrame : public ActionInstant +class CCBSetSpriteFrame : public cocos2d::ActionInstant { public: /** creates a Place action with a position */ - static CCBSetSpriteFrame* create(SpriteFrame *pSpriteFrame); + static CCBSetSpriteFrame* create(cocos2d::SpriteFrame *pSpriteFrame); /** * @js NA * @lua NA */ ~CCBSetSpriteFrame(); - bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); + bool initWithSpriteFrame(cocos2d::SpriteFrame *pSpriteFrame); // Overrides virtual void update(float time) override; @@ -168,11 +168,11 @@ public: virtual CCBSetSpriteFrame* reverse() const override; private: - SpriteFrame *_spriteFrame; + cocos2d::SpriteFrame *_spriteFrame; }; -class CCBSoundEffect : public ActionInstant +class CCBSoundEffect : public cocos2d::ActionInstant { public: static CCBSoundEffect* actionWithSoundFile(const std::string &file, float pitch, float pan, float gain); @@ -194,7 +194,7 @@ private: }; -class CCBRotateTo : public ActionInterval +class CCBRotateTo : public cocos2d::ActionInterval { public: static CCBRotateTo* create(float fDuration, float fAngle); @@ -204,7 +204,7 @@ public: virtual void update(float time) override; virtual CCBRotateTo* clone() const override; virtual CCBRotateTo* reverse() const override; - virtual void startWithTarget(Node *pNode) override; + virtual void startWithTarget(cocos2d::Node *pNode) override; private: float _startAngle; @@ -213,14 +213,14 @@ private: }; -class CCBRotateXTo: public ActionInterval +class CCBRotateXTo: public cocos2d::ActionInterval { public: static CCBRotateXTo* create(float fDuration, float fAngle); bool initWithDuration(float fDuration, float fAngle); // Overrides - virtual void startWithTarget(Node *pNode) override; + virtual void startWithTarget(cocos2d::Node *pNode) override; virtual CCBRotateXTo* clone() const override; virtual CCBRotateXTo* reverse() const override; virtual void update(float time) override; @@ -232,14 +232,14 @@ private: }; -class CCBRotateYTo: public ActionInterval +class CCBRotateYTo: public cocos2d::ActionInterval { public: static CCBRotateYTo* create(float fDuration, float fAngle); bool initWithDuration(float fDuration, float fAngle); // Override - virtual void startWithTarget(Node *pNode) override; + virtual void startWithTarget(cocos2d::Node *pNode) override; virtual CCBRotateYTo* clone() const override; virtual CCBRotateYTo* reverse() const override; virtual void update(float time) override; @@ -251,10 +251,10 @@ private: }; -class CCBEaseInstant : public ActionEase +class CCBEaseInstant : public cocos2d::ActionEase { public: - static CCBEaseInstant* create(ActionInterval *pAction); + static CCBEaseInstant* create(cocos2d::ActionInterval *pAction); virtual CCBEaseInstant* clone() const override; virtual CCBEaseInstant* reverse() const override; @@ -262,6 +262,6 @@ public: }; -NS_CC_EXT_END +} #endif // __CCB_CCBANIMATION_MANAGER_H__ diff --git a/cocos/editor-support/cocosbuilder/CCBFileLoader.cpp b/cocos/editor-support/cocosbuilder/CCBFileLoader.cpp index 12af936847..549b369f4e 100644 --- a/cocos/editor-support/cocosbuilder/CCBFileLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBFileLoader.cpp @@ -1,8 +1,9 @@ #include "CCBFileLoader.h" +using namespace cocos2d; -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define PROPERTY_CCBFILE "ccbFile" @@ -14,4 +15,4 @@ void CCBFileLoader::onHandlePropTypeCCBFile(Node * pNode, Node * pParent, const } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCBFileLoader.h b/cocos/editor-support/cocosbuilder/CCBFileLoader.h index aa2aeff982..51e675b00e 100644 --- a/cocos/editor-support/cocosbuilder/CCBFileLoader.h +++ b/cocos/editor-support/cocosbuilder/CCBFileLoader.h @@ -4,7 +4,7 @@ #include "CCNodeLoader.h" #include "CCBReader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -25,9 +25,9 @@ class CCBFileLoader : public NodeLoader { protected: CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCBFile); - virtual void onHandlePropTypeCCBFile(Node * pNode, Node * pParent, const char * pPropertyName, Node * pCCBFileNode, CCBReader * ccbReader); + virtual void onHandlePropTypeCCBFile(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Node * pCCBFileNode, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCBKeyframe.cpp b/cocos/editor-support/cocosbuilder/CCBKeyframe.cpp index d2f3c5dc87..e2f97806b0 100644 --- a/cocos/editor-support/cocosbuilder/CCBKeyframe.cpp +++ b/cocos/editor-support/cocosbuilder/CCBKeyframe.cpp @@ -2,7 +2,7 @@ using namespace cocos2d; -NS_CC_EXT_BEGIN +namespace cocosbuilder { CCBKeyframe::CCBKeyframe() : _value(NULL) @@ -58,4 +58,4 @@ void CCBKeyframe::setEasingOpt(float fEasingOpt) _easingOpt = fEasingOpt; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCBKeyframe.h b/cocos/editor-support/cocosbuilder/CCBKeyframe.h index 925e8bd23d..706ab32efc 100644 --- a/cocos/editor-support/cocosbuilder/CCBKeyframe.h +++ b/cocos/editor-support/cocosbuilder/CCBKeyframe.h @@ -2,11 +2,10 @@ #define __CCB_KEYFRAME_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { -class CCBKeyframe : public Object +class CCBKeyframe : public cocos2d::Object { public: enum class EasingType @@ -41,8 +40,8 @@ public: */ ~CCBKeyframe(); - Object* getValue(); - void setValue(Object *pValue); // retain + cocos2d::Object* getValue(); + void setValue(cocos2d::Object *pValue); // retain float getTime(); void setTime(float fTime); @@ -54,12 +53,12 @@ public: void setEasingOpt(float fEasingOpt); private: - Object *_value; + cocos2d::Object *_value; float _time; EasingType _easingType; float _easingOpt; }; -NS_CC_EXT_END +} #endif // __CCB_KEYFRAME_H__ diff --git a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h index 940d300c45..044f3e5059 100644 --- a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h +++ b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h @@ -4,7 +4,7 @@ #include "cocos2d.h" #include "CCBValue.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define CCB_MEMBERVARIABLEASSIGNER_GLUE(TARGET, MEMBERVARIABLENAME, MEMBERVARIABLETYPE, MEMBERVARIABLE) \ if (pTarget == TARGET && 0 == strcmp(pMemberVariableName, (MEMBERVARIABLENAME))) { \ @@ -41,7 +41,7 @@ class CCBMemberVariableAssigner { * @param node The member variable. * @return Whether the assignment was successful. */ - virtual bool onAssignCCBMemberVariable(Object* target, const char* memberVariableName, Node* node) = 0; + virtual bool onAssignCCBMemberVariable(cocos2d::Object* target, const char* memberVariableName, cocos2d::Node* node) = 0; /** * The callback function of assigning custom properties. @@ -51,9 +51,9 @@ class CCBMemberVariableAssigner { * @param value The value of the property. * @return Whether the assignment was successful. */ - virtual bool onAssignCCBCustomProperty(Object* target, const char* memberVariableName, CCBValue* value) { return false; }; + virtual bool onAssignCCBCustomProperty(cocos2d::Object* target, const char* memberVariableName, CCBValue* value) { return false; }; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 7397489fc9..d2f57ecf88 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -15,8 +15,10 @@ #include using namespace std; +using namespace cocos2d; +using namespace cocos2d::extension; -NS_CC_EXT_BEGIN; +namespace cocosbuilder {; /************************************************************************* Implementation of CCBFile @@ -1108,4 +1110,4 @@ void CCBReader::setResolutionScale(float scale) __ccbResolutionScale = scale; } -NS_CC_EXT_END; +}; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index e3423a0736..211ea18de4 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -2,11 +2,10 @@ #define _CCB_CCBREADER_H_ #include "cocos2d.h" -#include "ExtensionMacros.h" #include #include #include "CCBSequence.h" -#include "GUI/CCControlExtension/CCControl.h" +#include "extensions/GUI/CCControlExtension/CCControl.h" #define CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(T, METHOD) static T * METHOD() { \ T * ptr = new T(); \ @@ -30,24 +29,24 @@ #define CCB_VERSION 5 -NS_CC_EXT_BEGIN +namespace cocosbuilder { /** * @addtogroup cocosbuilder * @{ */ -class CCBFile : public Node +class CCBFile : public cocos2d::Node { private: - Node *_CCBFileNode; + cocos2d::Node *_CCBFileNode; public: CCBFile(); static CCBFile* create(); - Node* getCCBFileNode(); + cocos2d::Node* getCCBFileNode(); void setCCBFileNode(Node *pNode); // retain }; @@ -63,7 +62,7 @@ class CCBKeyframe; /** * @brief Parse CCBI file which is generated by CocosBuilder */ -class CCBReader : public Object +class CCBReader : public cocos2d::Object { public: enum class PropertyType { @@ -167,27 +166,27 @@ public: void setCCBRootPath(const char* ccbRootPath); const std::string& getCCBRootPath() const; - Node* readNodeGraphFromFile(const char *pCCBFileName); - Node* readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner); - Node* readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, const Size &parentSize); + cocos2d::Node* readNodeGraphFromFile(const char *pCCBFileName); + cocos2d::Node* readNodeGraphFromFile(const char *pCCBFileName, cocos2d::Object *pOwner); + cocos2d::Node* readNodeGraphFromFile(const char *pCCBFileName, cocos2d::Object *pOwner, const cocos2d::Size &parentSize); /** * @js NA * @lua NA */ - Node* readNodeGraphFromData(Data *pData, Object *pOwner, const Size &parentSize); + cocos2d::Node* readNodeGraphFromData(cocos2d::Data *pData, cocos2d::Object *pOwner, const cocos2d::Size &parentSize); /** @lua NA */ - Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName); + cocos2d::Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName); /** @lua NA */ - Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, Object *pOwner); + cocos2d::Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, cocos2d::Object *pOwner); /** @lua NA */ - Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, const Size &parentSize); + cocos2d::Scene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, cocos2d::Object *pOwner, const cocos2d::Size &parentSize); /** * @js NA @@ -225,7 +224,7 @@ public: * @js NA * @lua NA */ - Object* getOwner(); + cocos2d::Object* getOwner(); /* Utility methods. * @js NA @@ -283,24 +282,24 @@ public: bool readCallbackKeyframesForSeq(CCBSequence* seq); bool readSoundKeyframesForSeq(CCBSequence* seq); - Array* getOwnerCallbackNames(); - Array* getOwnerCallbackNodes(); - Array* getOwnerCallbackControlEvents(); + cocos2d::Array* getOwnerCallbackNames(); + cocos2d::Array* getOwnerCallbackNodes(); + cocos2d::Array* getOwnerCallbackControlEvents(); - Array* getOwnerOutletNames(); - Array* getOwnerOutletNodes(); - Array* getNodesWithAnimationManagers(); - Array* getAnimationManagersForNodes(); + cocos2d::Array* getOwnerOutletNames(); + cocos2d::Array* getOwnerOutletNodes(); + cocos2d::Array* getNodesWithAnimationManagers(); + cocos2d::Array* getAnimationManagersForNodes(); /** * @js NA * @lua NA */ - Dictionary* getAnimationManagers(); + cocos2d::Dictionary* getAnimationManagers(); /** * @js NA * @lua NA */ - void setAnimationManagers(Dictionary* x); // weak reference + void setAnimationManagers(cocos2d::Dictionary* x); // weak reference /** * @js NA * @lua NA @@ -310,8 +309,8 @@ public: * @js NA * @lua NA */ - void addOwnerCallbackNode(Node *node); - void addOwnerCallbackControlEvents(Control::EventType type); + void addOwnerCallbackNode(cocos2d::Node *node); + void addOwnerCallbackControlEvents(cocos2d::extension::Control::EventType type); /** * @js NA * @lua NA @@ -321,8 +320,8 @@ public: * @js NA * @lua NA */ - void addDocumentCallbackNode(Node *node); - void addDocumentCallbackControlEvents(Control::EventType eventType); + void addDocumentCallbackNode(cocos2d::Node *node); + void addDocumentCallbackControlEvents(cocos2d::extension::Control::EventType eventType); /** * @js NA * @lua NA @@ -333,21 +332,21 @@ public: * @js NA * @lua NA */ - Node* readFileWithCleanUp(bool bCleanUp, Dictionary* am); + cocos2d::Node* readFileWithCleanUp(bool bCleanUp, cocos2d::Dictionary* am); void addOwnerOutletName(std::string name); - void addOwnerOutletNode(Node *node); + void addOwnerOutletNode(cocos2d::Node *node); private: - void cleanUpNodeGraph(Node *pNode); + void cleanUpNodeGraph(cocos2d::Node *pNode); bool readSequences(); CCBKeyframe* readKeyframe(PropertyType type); bool readHeader(); bool readStringCache(); //void readStringCacheEntry(); - Node* readNodeGraph(); - Node* readNodeGraph(Node * pParent); + cocos2d::Node* readNodeGraph(); + cocos2d::Node* readNodeGraph(cocos2d::Node * pParent); bool getBit(); void alignBits(); @@ -357,7 +356,7 @@ private: friend class NodeLoader; private: - Data *_data; + cocos2d::Data *_data; unsigned char *_bytes; int _currentByte; int _currentBit; @@ -365,10 +364,10 @@ private: std::vector _stringCache; std::set _loadedSpriteSheets; - Object *_owner; + cocos2d::Object *_owner; CCBAnimationManager *_actionManager; //retain - Dictionary* _actionManagers; + cocos2d::Dictionary* _actionManagers; std::set *_animatedProps; @@ -378,13 +377,13 @@ private: CCBSelectorResolver *_CCBSelectorResolver; std::vector _ownerOutletNames; - Array* _ownerOutletNodes; - Array* _nodesWithAnimationManagers; - Array* _animationManagersForNodes; + cocos2d::Array* _ownerOutletNodes; + cocos2d::Array* _nodesWithAnimationManagers; + cocos2d::Array* _animationManagersForNodes; std::vector _ownerCallbackNames; - Array* _ownerCallbackNodes; - Array* _ownerOwnerCallbackControlEvents; + cocos2d::Array* _ownerCallbackNodes; + cocos2d::Array* _ownerOwnerCallbackControlEvents; std::string _CCBRootPath; bool _jsControlled; @@ -393,6 +392,6 @@ private: // end of effects group /// @} -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h index 94ea8d333b..f054c284c5 100644 --- a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h +++ b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h @@ -2,11 +2,10 @@ #define _CCB_CCBSELECTORRESOLVER_H_ #include "cocos2d.h" -#include "ExtensionMacros.h" -#include "../GUI/CCControlExtension/CCInvocation.h" +#include "extensions//GUI/CCControlExtension/CCInvocation.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(TARGET, SELECTORNAME, METHOD) if(pTarget == TARGET && strcmp(pSelectorName, SELECTORNAME) == 0) { \ return menu_selector(METHOD); \ @@ -27,9 +26,9 @@ class CCBSelectorResolver { * @lua NA */ virtual ~CCBSelectorResolver() {}; - virtual SEL_MenuHandler onResolveCCBCCMenuItemSelector(Object * pTarget, const char* pSelectorName) = 0; - virtual SEL_CallFuncN onResolveCCBCCCallFuncSelector(Object * pTarget, const char* pSelectorName) { return NULL; }; - virtual Control::Handler onResolveCCBCCControlSelector(Object * pTarget, const char* pSelectorName) = 0; + virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, const char* pSelectorName) = 0; + virtual cocos2d::SEL_CallFuncN onResolveCCBCCCallFuncSelector(cocos2d::Object * pTarget, const char* pSelectorName) { return NULL; }; + virtual cocos2d::extension::Control::Handler onResolveCCBCCControlSelector(cocos2d::Object * pTarget, const char* pSelectorName) = 0; }; @@ -43,6 +42,6 @@ public: virtual CCBSelectorResolver * createNew() = 0; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCBSequence.cpp b/cocos/editor-support/cocosbuilder/CCBSequence.cpp index 07e8d96189..20a7c49ab0 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequence.cpp +++ b/cocos/editor-support/cocosbuilder/CCBSequence.cpp @@ -4,7 +4,7 @@ using namespace cocos2d; using namespace std; -NS_CC_EXT_BEGIN +namespace cocosbuilder { CCBSequence::CCBSequence() : _duration(0.0f) @@ -86,4 +86,4 @@ void CCBSequence::setChainedSequenceId(int nChainedSequenceId) mChainedSequenceId = nChainedSequenceId; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCBSequence.h b/cocos/editor-support/cocosbuilder/CCBSequence.h index 5fd8739f34..dd7c1a899f 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequence.h +++ b/cocos/editor-support/cocosbuilder/CCBSequence.h @@ -3,12 +3,11 @@ #include #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCBSequenceProperty.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { -class CCBSequence : public Object +class CCBSequence : public cocos2d::Object { public: CCBSequence(); @@ -45,7 +44,7 @@ private: }; -NS_CC_EXT_END +} #endif // __CCB_CCSEQUENCE_H__ diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp index bd308d64e5..a091adaad1 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp @@ -3,7 +3,7 @@ using namespace cocos2d; using namespace std; -NS_CC_EXT_BEGIN +namespace cocosbuilder { CCBSequenceProperty::CCBSequenceProperty() : _name("") @@ -50,4 +50,4 @@ Array* CCBSequenceProperty::getKeyframes() return _keyframes; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h index 4fd0767ab0..cd097c2356 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h @@ -2,12 +2,11 @@ #define __CCB_SEQUENCE_PROPERTY_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCBKeyframe.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { -class CCBSequenceProperty : public Object +class CCBSequenceProperty : public cocos2d::Object { public: /** @@ -28,14 +27,14 @@ public: int getType(); void setType(int type); - Array* getKeyframes(); + cocos2d::Array* getKeyframes(); private: std::string _name; int _type; - Array *_keyframes; + cocos2d::Array *_keyframes; }; -NS_CC_EXT_END +} #endif // __CCB_SEQUENCE_PROPERTY_H__ diff --git a/cocos/editor-support/cocosbuilder/CCBValue.cpp b/cocos/editor-support/cocosbuilder/CCBValue.cpp index 051100383d..f9a7547102 100644 --- a/cocos/editor-support/cocosbuilder/CCBValue.cpp +++ b/cocos/editor-support/cocosbuilder/CCBValue.cpp @@ -1,6 +1,8 @@ #include "CCBValue.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace cocosbuilder { // Implementation of Color3BWapper @@ -154,4 +156,4 @@ CCBValue::Type CCBValue::getType() return _type; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCBValue.h b/cocos/editor-support/cocosbuilder/CCBValue.h index 267ed5809a..0d05cb6a69 100644 --- a/cocos/editor-support/cocosbuilder/CCBValue.h +++ b/cocos/editor-support/cocosbuilder/CCBValue.h @@ -2,28 +2,27 @@ #define __CCB_VALUE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" /* These classes are wrapper of basic types, such as Color3B */ -NS_CC_EXT_BEGIN +namespace cocosbuilder { -class Color3BWapper : public Object +class Color3BWapper : public cocos2d::Object { public: - static Color3BWapper* create(const Color3B& color); + static Color3BWapper* create(const cocos2d::Color3B& color); - const Color3B& getColor() const; + const cocos2d::Color3B& getColor() const; private: - Color3B color; + cocos2d::Color3B color; }; -class CCBValue : public Object +class CCBValue : public cocos2d::Object { public: @@ -42,7 +41,7 @@ public: static CCBValue* create(float fValue); static CCBValue* create(unsigned char byte); static CCBValue* create(const char* pStr); - static CCBValue* create(Array* pArr); + static CCBValue* create(cocos2d::Array* pArr); int getIntValue(); @@ -50,7 +49,7 @@ public: bool getBoolValue(); unsigned char getByteValue(); const char* getStringValue(); - Array *getArrayValue(); + cocos2d::Array *getArrayValue(); Type getType(); @@ -62,10 +61,10 @@ private: } _value; std::string _strValue; - Array* _arrValue; + cocos2d::Array* _arrValue; Type _type; }; -NS_CC_EXT_END +} #endif // __CCB_VALUE_H__ diff --git a/cocos/editor-support/cocosbuilder/CCControlButtonLoader.cpp b/cocos/editor-support/cocosbuilder/CCControlButtonLoader.cpp index 6b76adf3ec..c72b9723a2 100644 --- a/cocos/editor-support/cocosbuilder/CCControlButtonLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCControlButtonLoader.cpp @@ -1,7 +1,9 @@ #include "CCControlButtonLoader.h" +using namespace cocos2d; +using namespace cocos2d::extension; -NS_CC_EXT_BEGIN; +namespace cocosbuilder {; #define PROPERTY_ZOOMONTOUCHDOWN "zoomOnTouchDown" #define PROPERTY_TITLE_NORMAL "title|1" @@ -112,4 +114,4 @@ void ControlButtonLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, c } } -NS_CC_EXT_END; \ No newline at end of file +}; \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCControlButtonLoader.h b/cocos/editor-support/cocosbuilder/CCControlButtonLoader.h index 601e61c4d6..c6d420a161 100644 --- a/cocos/editor-support/cocosbuilder/CCControlButtonLoader.h +++ b/cocos/editor-support/cocosbuilder/CCControlButtonLoader.h @@ -2,9 +2,9 @@ #define _CCB_CCCONTROLBUTTONLOADER_H_ #include "CCControlLoader.h" -#include "../GUI/CCControlExtension/CCControlButton.h" +#include "extensions//GUI/CCControlExtension/CCControlButton.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -23,18 +23,18 @@ class ControlButtonLoader : public ControlLoader { CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ControlButtonLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(ControlButton); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::extension::ControlButton); - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); - virtual void onHandlePropTypeString(Node * pNode, Node * pParent, const char * pPropertyName, const char * pString, CCBReader * ccbReader); - virtual void onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader); - virtual void onHandlePropTypeFloatScale(Node * pNode, Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader); - virtual void onHandlePropTypePoint(Node * pNode, Node * pParent, const char * pPropertyName, Point pPoint, CCBReader * ccbReader); - virtual void onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader); - virtual void onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeString(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char * pString, CCBReader * ccbReader); + virtual void onHandlePropTypeFontTTF(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatScale(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader); + virtual void onHandlePropTypePoint(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Point pPoint, CCBReader * ccbReader); + virtual void onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader); + virtual void onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCControlLoader.cpp b/cocos/editor-support/cocosbuilder/CCControlLoader.cpp index aff1fd2f11..9125f8d193 100644 --- a/cocos/editor-support/cocosbuilder/CCControlLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCControlLoader.cpp @@ -1,7 +1,9 @@ #include "CCControlLoader.h" +using namespace cocos2d; +using namespace cocos2d::extension; -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define PROPERTY_ENABLED "enabled" #define PROPERTY_SELECTED "selected" @@ -25,4 +27,4 @@ void ControlLoader::onHandlePropTypeBlockControl(Node * pNode, Node * pParent, c } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCControlLoader.h b/cocos/editor-support/cocosbuilder/CCControlLoader.h index 07b1eaaa72..83e2306e39 100644 --- a/cocos/editor-support/cocosbuilder/CCControlLoader.h +++ b/cocos/editor-support/cocosbuilder/CCControlLoader.h @@ -2,9 +2,9 @@ #define _CCB_CCCONTROLLOADER_H_ #include "CCNodeLoader.h" -#include "../GUI/CCControlExtension/CCControl.h" +#include "extensions/GUI/CCControlExtension/CCControl.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,12 +18,12 @@ public: virtual ~ControlLoader() {}; protected: - CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Control); + CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::extension::Control); - virtual void onHandlePropTypeBlockControl(Node * pNode, Node * pParent, const char * pPropertyName, BlockControlData * pBlockControlData, CCBReader * ccbReader); - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeBlockControl(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, BlockControlData * pBlockControlData, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.cpp b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.cpp index 52230fb282..df96cccc77 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.cpp @@ -1,8 +1,8 @@ #include "CCLabelBMFontLoader.h" +using namespace cocos2d; - -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define PROPERTY_COLOR "color" #define PROPERTY_OPACITY "opacity" @@ -50,4 +50,4 @@ void LabelBMFontLoader::onHandlePropTypeText(Node * pNode, Node * pParent, const } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h index a6027cb4af..ae5cb20011 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h @@ -3,7 +3,7 @@ #include "CCNodeLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,15 +18,15 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LabelBMFontLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(LabelBMFont); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::LabelBMFont); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); - virtual void onHandlePropTypeFntFile(Node * pNode, Node * pParent, const char * pPropertyName, const char* pFntFile, CCBReader * ccbReader); - virtual void onHandlePropTypeText(Node * pNode, Node * pParent, const char * pPropertyName, const char* pText, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeFntFile(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char* pFntFile, CCBReader * ccbReader); + virtual void onHandlePropTypeText(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char* pText, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp index 470698fd8a..2ed3010e1f 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp @@ -1,6 +1,6 @@ #include "CCLabelTTFLoader.h" - +using namespace cocos2d; #define PROPERTY_COLOR "color" #define PROPERTY_OPACITY "opacity" @@ -12,7 +12,7 @@ #define PROPERTY_STRING "string" #define PROPERTY_DIMENSIONS "dimensions" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void LabelTTFLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_COLOR) == 0) { @@ -80,4 +80,4 @@ void LabelTTFLoader::onHandlePropTypeSize(Node * pNode, Node * pParent, const ch } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h index d5405d34f0..de0ca00d42 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h @@ -3,7 +3,7 @@ #include "CCNodeLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,18 +18,18 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LabelTTFLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(LabelTTF); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::LabelTTF); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); - virtual void onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader); - virtual void onHandlePropTypeText(Node * pNode, Node * pParent, const char * pPropertyName, const char * pText, CCBReader * ccbReader); - virtual void onHandlePropTypeFloatScale(Node * pNode, Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader); - virtual void onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); - virtual void onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeFontTTF(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader); + virtual void onHandlePropTypeText(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, const char * pText, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatScale(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader); + virtual void onHandlePropTypeIntegerLabeled(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); + virtual void onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCLayerColorLoader.cpp b/cocos/editor-support/cocosbuilder/CCLayerColorLoader.cpp index abac77efdf..02c7f610ae 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerColorLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLayerColorLoader.cpp @@ -1,8 +1,8 @@ #include "CCLayerColorLoader.h" +using namespace cocos2d; - -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define PROPERTY_COLOR "color" #define PROPERTY_OPACITY "opacity" @@ -32,4 +32,4 @@ void LayerColorLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, c } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCLayerColorLoader.h b/cocos/editor-support/cocosbuilder/CCLayerColorLoader.h index e9618ed075..acea8b64da 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerColorLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLayerColorLoader.h @@ -3,7 +3,7 @@ #include "CCLayerLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,13 +18,13 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LayerColorLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(LayerColor); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::LayerColor); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.cpp b/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.cpp index a14bfac0f7..95d93e554b 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.cpp @@ -1,6 +1,6 @@ #include "CCLayerGradientLoader.h" - +using namespace cocos2d; #define PROPERTY_STARTCOLOR "startColor" #define PROPERTY_ENDCOLOR "endColor" @@ -9,7 +9,7 @@ #define PROPERTY_VECTOR "vector" #define PROPERTY_BLENDFUNC "blendFunc" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void LayerGradientLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_STARTCOLOR) == 0) { @@ -51,4 +51,4 @@ void LayerGradientLoader::onHandlePropTypePoint(Node * pNode, Node * pParent, co } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.h b/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.h index 1361369600..5ec0c8fcc3 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLayerGradientLoader.h @@ -3,7 +3,7 @@ #include "CCLayerLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,14 +18,14 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LayerGradientLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(LayerGradient); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::LayerGradient); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypePoint(Node * pNode, Node * pParent, const char * pPropertyName, Point pPoint, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypePoint(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Point pPoint, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp b/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp index d5f353d0f5..f13cf610f6 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp @@ -1,14 +1,16 @@ #include "CCLayerLoader.h" - +using namespace cocos2d; #define PROPERTY_TOUCH_ENABLED "isTouchEnabled" #define PROPERTY_ACCELEROMETER_ENABLED "isAccelerometerEnabled" #define PROPERTY_MOUSE_ENABLED "isMouseEnabled" #define PROPERTY_KEYBOARD_ENABLED "isKeyboardEnabled" -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace cocosbuilder { void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_TOUCH_ENABLED) == 0) { @@ -27,4 +29,4 @@ void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCLayerLoader.h b/cocos/editor-support/cocosbuilder/CCLayerLoader.h index 835d77b4ba..9d7f41fa25 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLayerLoader.h @@ -3,7 +3,7 @@ #include "CCNodeLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -18,11 +18,11 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LayerLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Layer); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::Layer); - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.cpp b/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.cpp index 169d2a469a..21bb3b0b6b 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.cpp @@ -1,12 +1,12 @@ #include "CCMenuItemImageLoader.h" - +using namespace cocos2d; #define PROPERTY_NORMALDISPLAYFRAME "normalSpriteFrame" #define PROPERTY_SELECTEDDISPLAYFRAME "selectedSpriteFrame" #define PROPERTY_DISABLEDDISPLAYFRAME "disabledSpriteFrame" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void MenuItemImageLoader::onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_NORMALDISPLAYFRAME) == 0) { @@ -26,4 +26,4 @@ void MenuItemImageLoader::onHandlePropTypeSpriteFrame(Node * pNode, Node * pPare } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.h b/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.h index 5c56e3c178..d1c680227f 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuItemImageLoader.h @@ -3,7 +3,7 @@ #include "CCMenuItemLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -26,14 +26,14 @@ protected: * @js NA * @lua NA */ - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(MenuItemImage); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::MenuItemImage); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader); + virtual void onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.cpp b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.cpp index d6dd6f2ecd..2a85d0c4e1 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.cpp @@ -1,11 +1,11 @@ #include "CCMenuItemLoader.h" - +using namespace cocos2d; #define PROPERTY_BLOCK "block" #define PROPERTY_ISENABLED "isEnabled" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void MenuItemLoader::onHandlePropTypeBlock(Node * pNode, Node * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_BLOCK) == 0) { @@ -27,4 +27,4 @@ void MenuItemLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const c } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h index ec334bc093..5db15eacba 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h @@ -3,7 +3,7 @@ #include "CCLayerLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -21,19 +21,19 @@ protected: * @js NA * @lua NA */ - CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(MenuItem); + CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::MenuItem); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeBlock(Node * pNode, Node * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * ccbReader); + virtual void onHandlePropTypeBlock(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode,cocos2d:: Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCMenuLoader.h b/cocos/editor-support/cocosbuilder/CCMenuLoader.h index 107fc2e27d..851913c74c 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuLoader.h @@ -3,7 +3,7 @@ #include "CCLayerLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -22,9 +22,9 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(MenuLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Menu); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::Menu); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.cpp b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.cpp index 4797b8ad2d..fd941dfbfa 100644 --- a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.cpp +++ b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.cpp @@ -1,7 +1,9 @@ #include "CCNode+CCBRelativePositioning.h" #include "CCBReader.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace cocosbuilder { Point getAbsolutePosition(const Point &pt, CCBReader::PositionType type, const Size &containerSize, const char *propName) { @@ -57,4 +59,4 @@ void setRelativeScale(Node *pNode, float scaleX, float scaleY, CCBReader::ScaleT pNode->setScaleY(scaleY); } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h index 7e8a8e7baa..0220eccafc 100644 --- a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h +++ b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h @@ -2,15 +2,14 @@ #define __CCB_CCNODE_RELATIVEPOSITIONING_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCBReader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { -extern Point getAbsolutePosition(const Point &pt, CCBReader::PositionType type, const Size &containerSize, const char *propName); +extern cocos2d::Point getAbsolutePosition(const cocos2d::Point &pt, CCBReader::PositionType type, const cocos2d::Size &containerSize, const char *propName); -extern void setRelativeScale(Node *node, float scaleX, float scaleY, CCBReader::ScaleType type, const char* propName); +extern void setRelativeScale(cocos2d::Node *node, float scaleX, float scaleY, CCBReader::ScaleType type, const char* propName); -NS_CC_EXT_END +} #endif // __CCB_CCNODE_RELATIVEPOSITIONING_H__ diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index eef0acfb96..f1aedc7104 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -5,8 +5,10 @@ #include "CCNode+CCBRelativePositioning.h" using namespace std; +using namespace cocos2d; +using namespace cocos2d::extension; -NS_CC_EXT_BEGIN +namespace cocosbuilder { NodeLoader::NodeLoader() { @@ -1156,4 +1158,4 @@ void NodeLoader::onHandlePropTypeCCBFile(Node * pNode, Node * pParent, const cha ASSERT_FAIL_UNEXPECTED_PROPERTY(pPropertyName); } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.h b/cocos/editor-support/cocosbuilder/CCNodeLoader.h index a3ec6ee7a8..bc798a1c89 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.h @@ -1,13 +1,13 @@ #ifndef _CCB_CCNODELOADER_H_ #define _CCB_CCNODELOADER_H_ -#include "../GUI/CCControlExtension/CCInvocation.h" +#include "extensions/GUI/CCControlExtension/CCInvocation.h" #include "cocos2d.h" #include "CCBReader.h" #include "CCBValue.h" -#include "../GUI/CCControlExtension/CCControl.h" +#include "extensions/GUI/CCControlExtension/CCControl.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { #define PROPERTY_POSITION "position" #define PROPERTY_CONTENTSIZE "contentSize" @@ -24,27 +24,27 @@ NS_CC_EXT_BEGIN #define ASSERT_FAIL_UNEXPECTED_PROPERTY(PROPERTY) cocos2d::log("Unexpected property: '%s'!\n", PROPERTY); assert(false) #define ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE(PROPERTYTYPE) cocos2d::log("Unexpected property type: '%d'!\n", PROPERTYTYPE); assert(false) -#define CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createNode(cocos2d::Node * pParent, cocos2d::extension::CCBReader * ccbReader) { \ +#define CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createNode(cocos2d::Node * pParent, cocosbuilder::CCBReader * ccbReader) { \ return T::create(); \ } -#define CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createNode(cocos2d::Node * pParent, cocos2d::extension::CCBReader * ccbReader) = 0 +#define CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createNode(cocos2d::Node * pParent, cocosbuilder::CCBReader * ccbReader) = 0 struct BlockData { - SEL_MenuHandler mSELMenuHandler; - Object * _target; + cocos2d::SEL_MenuHandler mSELMenuHandler; + cocos2d::Object * _target; }; struct BlockControlData { - Control::Handler mSELControlHandler; - Object * _target; - Control::EventType mControlEvents; + cocos2d::extension::Control::Handler mSELControlHandler; + cocos2d::Object * _target; + cocos2d::extension::Control::EventType mControlEvents; }; /* Forward declaration. */ class CCBReader; -class NodeLoader : public Object { +class NodeLoader : public cocos2d::Object { public: /** * @js NA @@ -65,85 +65,85 @@ class NodeLoader : public Object { * @js NA * @lua NA */ - virtual Node * loadNode(Node *, CCBReader * ccbReader); + virtual cocos2d::Node * loadNode(cocos2d::Node *, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void parseProperties(Node * pNode, Node * pParent, CCBReader * ccbReader); + virtual void parseProperties(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual Dictionary* getCustomProperties(); + virtual cocos2d::Dictionary* getCustomProperties(); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Node); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::Node); - virtual Point parsePropTypePosition(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual Point parsePropTypePoint(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual Point parsePropTypePointLock(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual Size parsePropTypeSize(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual float * parsePropTypeScaleLock(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual float parsePropTypeFloat(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual float parsePropTypeDegrees(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual float parsePropTypeFloatScale(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual int parsePropTypeInteger(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual int parsePropTypeIntegerLabeled(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual float * parsePropTypeFloatVar(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual bool parsePropTypeCheck(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual SpriteFrame * parsePropTypeSpriteFrame(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual Animation * parsePropTypeAnimation(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual Texture2D * parsePropTypeTexture(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual unsigned char parsePropTypeByte(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual Color3B parsePropTypeColor3(Node * pNode, Node * pParent, CCBReader * ccbReader, const char *pPropertyName); - virtual Color4F * parsePropTypeColor4FVar(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual bool * parsePropTypeFlip(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual BlendFunc parsePropTypeBlendFunc(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual std::string parsePropTypeFntFile(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual std::string parsePropTypeString(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual std::string parsePropTypeText(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual std::string parsePropTypeFontTTF(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual BlockData * parsePropTypeBlock(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual BlockControlData * parsePropTypeBlockControl(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual Node * parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader * ccbReader); - virtual float * parsePropTypeFloatXY(Node * pNode, Node * pParent, CCBReader * ccbReader); + virtual cocos2d::Point parsePropTypePosition(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual cocos2d::Point parsePropTypePoint(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual cocos2d::Point parsePropTypePointLock(cocos2d::Node * pNode,cocos2d:: Node * pParent, CCBReader * ccbReader); + virtual cocos2d::Size parsePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual float * parsePropTypeScaleLock(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual float parsePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual float parsePropTypeDegrees(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual float parsePropTypeFloatScale(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual int parsePropTypeInteger(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual int parsePropTypeIntegerLabeled(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual float * parsePropTypeFloatVar(cocos2d::Node * pNode,cocos2d::Node * pParent, CCBReader * ccbReader); + virtual bool parsePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual cocos2d::SpriteFrame * parsePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual cocos2d::Animation * parsePropTypeAnimation(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual cocos2d::Texture2D * parsePropTypeTexture(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual unsigned char parsePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual cocos2d::Color3B parsePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader, const char *pPropertyName); + virtual cocos2d::Color4F * parsePropTypeColor4FVar(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual bool * parsePropTypeFlip(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual cocos2d::BlendFunc parsePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual std::string parsePropTypeFntFile(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual std::string parsePropTypeString(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual std::string parsePropTypeText(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual std::string parsePropTypeFontTTF(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual BlockData * parsePropTypeBlock(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual BlockControlData * parsePropTypeBlockControl(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual cocos2d::Node * parsePropTypeCCBFile(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); + virtual float * parsePropTypeFloatXY(cocos2d::Node * pNode, cocos2d::Node * pParent, CCBReader * ccbReader); - virtual void onHandlePropTypePosition(Node * pNode, Node * pParent, const char* pPropertyName, Point pPosition, CCBReader * ccbReader); - virtual void onHandlePropTypePoint(Node * pNode, Node * pParent, const char* pPropertyName, Point pPoint, CCBReader * ccbReader); - virtual void onHandlePropTypePointLock(Node * pNode, Node * pParent, const char* pPropertyName, Point pPointLock, CCBReader * ccbReader); - virtual void onHandlePropTypeSize(Node * pNode, Node * pParent, const char* pPropertyName, Size pSize, CCBReader * ccbReader); - virtual void onHandlePropTypeScaleLock(Node * pNode, Node * pParent, const char* pPropertyName, float * pScaleLock, CCBReader * ccbReader); - virtual void onHandlePropTypeFloat(Node * pNode, Node * pParent, const char* pPropertyName, float pFloat, CCBReader * ccbReader); - virtual void onHandlePropTypeDegrees(Node * pNode, Node * pParent, const char* pPropertyName, float pDegrees, CCBReader * ccbReader); - virtual void onHandlePropTypeFloatScale(Node * pNode, Node * pParent, const char* pPropertyName, float pFloatScale, CCBReader * ccbReader); - virtual void onHandlePropTypeInteger(Node * pNode, Node * pParent, const char* pPropertyName, int pInteger, CCBReader * ccbReader); - virtual void onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char* pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); - virtual void onHandlePropTypeFloatVar(Node * pNode, Node * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * ccbReader); - virtual void onHandlePropTypeFloatXY(Node * pNode, Node * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * ccbReader); + virtual void onHandlePropTypePosition(cocos2d::Node * pNode,cocos2d:: Node * pParent, const char* pPropertyName, cocos2d::Point pPosition, CCBReader * ccbReader); + virtual void onHandlePropTypePoint(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Point pPoint, CCBReader * ccbReader); + virtual void onHandlePropTypePointLock(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Point pPointLock, CCBReader * ccbReader); + virtual void onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader); + virtual void onHandlePropTypeScaleLock(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float * pScaleLock, CCBReader * ccbReader); + virtual void onHandlePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float pFloat, CCBReader * ccbReader); + virtual void onHandlePropTypeDegrees(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float pDegrees, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatScale(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float pFloatScale, CCBReader * ccbReader); + virtual void onHandlePropTypeInteger(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, int pInteger, CCBReader * ccbReader); + virtual void onHandlePropTypeIntegerLabeled(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatVar(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatXY(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * ccbReader); - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char* pPropertyName, bool pCheck, CCBReader * ccbReader); - virtual void onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char* pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader); - virtual void onHandlePropTypeAnimation(Node * pNode, Node * pParent, const char* pPropertyName, Animation * pAnimation, CCBReader * ccbReader); - virtual void onHandlePropTypeTexture(Node * pNode, Node * pParent, const char* pPropertyName, Texture2D * pTexture2D, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char* pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char* pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeColor4FVar(Node * pNode, Node * pParent, const char* pPropertyName, Color4F * pColor4FVar, CCBReader * ccbReader); - virtual void onHandlePropTypeFlip(Node * pNode, Node * pParent, const char* pPropertyName, bool * pFlip, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char* pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); - virtual void onHandlePropTypeFntFile(Node * pNode, Node * pParent, const char* pPropertyName, const char * pFntFile, CCBReader * ccbReader); - virtual void onHandlePropTypeString(Node * pNode, Node * pParent, const char* pPropertyName, const char * pString, CCBReader * ccbReader); - virtual void onHandlePropTypeText(Node * pNode, Node * pParent, const char* pPropertyName, const char * pText, CCBReader * ccbReader); - virtual void onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const char* pPropertyName, const char * pFontTTF, CCBReader * ccbReader); - virtual void onHandlePropTypeBlock(Node * pNode, Node * pParent, const char* pPropertyName, BlockData * pBlockData, CCBReader * ccbReader); - virtual void onHandlePropTypeBlockControl(Node * pNode, Node * pParent, const char* pPropertyName, BlockControlData * pBlockControlData, CCBReader * ccbReader); - virtual void onHandlePropTypeCCBFile(Node * pNode, Node * pParent, const char* pPropertyName, Node * pCCBFileNode, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader); + virtual void onHandlePropTypeAnimation(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Animation * pAnimation, CCBReader * ccbReader); + virtual void onHandlePropTypeTexture(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Texture2D * pTexture2D, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeColor4FVar(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Color4F * pColor4FVar, CCBReader * ccbReader); + virtual void onHandlePropTypeFlip(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, bool * pFlip, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeFntFile(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, const char * pFntFile, CCBReader * ccbReader); + virtual void onHandlePropTypeString(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, const char * pString, CCBReader * ccbReader); + virtual void onHandlePropTypeText(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, const char * pText, CCBReader * ccbReader); + virtual void onHandlePropTypeFontTTF(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, const char * pFontTTF, CCBReader * ccbReader); + virtual void onHandlePropTypeBlock(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, BlockData * pBlockData, CCBReader * ccbReader); + virtual void onHandlePropTypeBlockControl(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, BlockControlData * pBlockControlData, CCBReader * ccbReader); + virtual void onHandlePropTypeCCBFile(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, cocos2d::Node * pCCBFileNode, CCBReader * ccbReader); protected: - Dictionary* _customProperties; + cocos2d::Dictionary* _customProperties; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.cpp index c7d61b24ec..48979ee0bc 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.cpp @@ -15,9 +15,9 @@ #include "CCParticleSystemQuadLoader.h" #include "CCScrollViewLoader.h" +using namespace cocos2d; - -NS_CC_EXT_BEGIN +namespace cocosbuilder { NodeLoaderLibrary::NodeLoaderLibrary() { @@ -102,4 +102,4 @@ NodeLoaderLibrary * NodeLoaderLibrary::newDefaultNodeLoaderLibrary() { return ccNodeLoaderLibrary; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h index dcb49dbaaf..c75276d22f 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h @@ -4,14 +4,14 @@ #include "cocos2d.h" #include "CCBReader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { class NodeLoader; typedef std::map NodeLoaderMap; typedef std::pair NodeLoaderMapEntry; -class NodeLoaderLibrary : public Object +class NodeLoaderLibrary : public cocos2d::Object { public: /** @@ -114,6 +114,6 @@ private: NodeLoaderMap _nodeLoaders; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h index 0ff35b2bee..cf6c53e543 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h @@ -3,7 +3,7 @@ #include "cocos2d.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { class NodeLoaderListener { public: @@ -16,9 +16,9 @@ class NodeLoaderListener { * @js NA * @lua NA */ - virtual void onNodeLoaded(Node * pNode, NodeLoader * pNodeLoader) = 0; + virtual void onNodeLoaded(cocos2d::Node * pNode, NodeLoader * pNodeLoader) = 0; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.cpp b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.cpp index 8f94db33ad..472d1e8d91 100644 --- a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.cpp @@ -1,6 +1,6 @@ #include "CCParticleSystemQuadLoader.h" - +using namespace cocos2d; #define PROPERTY_EMITERMODE "emitterMode" #define PROPERTY_POSVAR "posVar" @@ -25,7 +25,7 @@ #define PROPERTY_ENDRADIUS "endRadius" #define PROPERTY_ROTATEPERSECOND "rotatePerSecond" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void ParticleSystemQuadLoader::onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_EMITERMODE) == 0) { @@ -133,4 +133,4 @@ void ParticleSystemQuadLoader::onHandlePropTypeTexture(Node * pNode, Node * pPar } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h index cf8324fbb3..feced7312e 100644 --- a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h +++ b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h @@ -3,7 +3,7 @@ #include "CCNodeLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -19,56 +19,56 @@ public: * @js NA * @lua NA */ - CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ParticleSystemQuadLoader, loader); + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(cocosbuilder::ParticleSystemQuadLoader, loader); protected: /** * @js NA * @lua NA */ - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(ParticleSystemQuad); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::ParticleSystemQuad); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); + virtual void onHandlePropTypeIntegerLabeled(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypePoint(Node * pNode, Node * pParent, const char * pPropertyName, Point pPoint, CCBReader * ccbReader); + virtual void onHandlePropTypePoint(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Point pPoint, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeFloat(Node * pNode, Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); + virtual void onHandlePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeInteger(Node * pNode, Node * pParent, const char * pPropertyName, int pInteger, CCBReader * ccbReader); + virtual void onHandlePropTypeInteger(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, int pInteger, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeFloatVar(Node * pNode, Node * pParent, const char * pPropertyName, float * pFloatVar, CCBReader * ccbReader); + virtual void onHandlePropTypeFloatVar(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float * pFloatVar, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeColor4FVar(Node * pNode, Node * pParent, const char * pPropertyName, Color4F * pColor4FVar, CCBReader * ccbReader); + virtual void onHandlePropTypeColor4FVar(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color4F * pColor4FVar, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeTexture(Node * pNode, Node * pParent, const char * pPropertyName, Texture2D * pTexture2D, CCBReader * ccbReader); + virtual void onHandlePropTypeTexture(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Texture2D * pTexture2D, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.cpp b/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.cpp index b2172bf855..ac9bfd7ca7 100644 --- a/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.cpp @@ -1,6 +1,7 @@ #include "CCScale9SpriteLoader.h" - +using namespace cocos2d; +using namespace cocos2d::extension; #define PROPERTY_CONTENTSIZE "contentSize" #define PROPERTY_SPRITEFRAME "spriteFrame" @@ -13,7 +14,7 @@ #define PROPERTY_INSETRIGHT "insetRight" #define PROPERTY_INSETBOTTOM "insetBottom" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void Scale9SpriteLoader::onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_SPRITEFRAME) == 0) { @@ -72,4 +73,4 @@ void Scale9SpriteLoader::onHandlePropTypeFloat(Node * pNode, Node * pParent, con } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.h b/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.h index 18692fdef7..b4ec05c92f 100644 --- a/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.h +++ b/cocos/editor-support/cocosbuilder/CCScale9SpriteLoader.h @@ -3,9 +3,9 @@ #include "CCNodeLoader.h" #include "CCScale9SpriteLoader.h" -#include "../GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -28,39 +28,39 @@ protected: * @js NA * @lua NA */ - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Scale9Sprite); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::extension::Scale9Sprite); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pBlendFunc, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader); + virtual void onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader); + virtual void onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader); /** * @js NA * @lua NA */ - virtual void onHandlePropTypeFloat(Node * pNode, Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); + virtual void onHandlePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCScrollViewLoader.cpp b/cocos/editor-support/cocosbuilder/CCScrollViewLoader.cpp index 5006a5fd89..32301942c8 100644 --- a/cocos/editor-support/cocosbuilder/CCScrollViewLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCScrollViewLoader.cpp @@ -1,6 +1,7 @@ #include "CCScrollViewLoader.h" - +using namespace cocos2d; +using namespace cocos2d::extension; #define PROPERTY_CONTAINER "container" #define PROPERTY_DIRECTION "direction" @@ -8,7 +9,7 @@ #define PROPERTY_BOUNCES "bounces" #define PROPERTY_SCALE "scale" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void ScrollViewLoader::onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_CONTENTSIZE) == 0) { @@ -53,4 +54,4 @@ void ScrollViewLoader::onHandlePropTypeIntegerLabeled(Node * pNode, Node * pPare } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CCScrollViewLoader.h b/cocos/editor-support/cocosbuilder/CCScrollViewLoader.h index c21b502bc8..30ede8a8d2 100644 --- a/cocos/editor-support/cocosbuilder/CCScrollViewLoader.h +++ b/cocos/editor-support/cocosbuilder/CCScrollViewLoader.h @@ -2,9 +2,9 @@ #define _CCB_CCSCROLLVIEWLOADER_H_ #include "CCNodeLoader.h" -#include "../GUI/CCScrollView/CCScrollView.h" +#include "extensions/GUI/CCScrollView/CCScrollView.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -23,14 +23,14 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ScrollViewLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(ScrollView); - virtual void onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader); - virtual void onHandlePropTypeCCBFile(Node * pNode, Node * pParent, const char * pPropertyName, Node * pCCBFileNode, CCBReader * ccbReader); - virtual void onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); - virtual void onHandlePropTypeFloat(Node * pNode, Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); - virtual void onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::extension::ScrollView); + virtual void onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader); + virtual void onHandlePropTypeCCBFile(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Node * pCCBFileNode, CCBReader * ccbReader); + virtual void onHandlePropTypeCheck(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader); + virtual void onHandlePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader); + virtual void onHandlePropTypeIntegerLabeled(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CCSpriteLoader.cpp b/cocos/editor-support/cocosbuilder/CCSpriteLoader.cpp index 0432658189..34a2e7f549 100644 --- a/cocos/editor-support/cocosbuilder/CCSpriteLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCSpriteLoader.cpp @@ -1,12 +1,14 @@ #include "CCSpriteLoader.h" +using namespace cocos2d; + #define PROPERTY_FLIP "flip" #define PROPERTY_DISPLAYFRAME "displayFrame" #define PROPERTY_COLOR "color" #define PROPERTY_OPACITY "opacity" #define PROPERTY_BLENDFUNC "blendFunc" -NS_CC_EXT_BEGIN +namespace cocosbuilder { void SpriteLoader::onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_DISPLAYFRAME) == 0) { @@ -53,4 +55,4 @@ void SpriteLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const } } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocosbuilder/CCSpriteLoader.h b/cocos/editor-support/cocosbuilder/CCSpriteLoader.h index 308b6165c6..466ee836bc 100644 --- a/cocos/editor-support/cocosbuilder/CCSpriteLoader.h +++ b/cocos/editor-support/cocosbuilder/CCSpriteLoader.h @@ -3,7 +3,7 @@ #include "CCNodeLoader.h" -NS_CC_EXT_BEGIN +namespace cocosbuilder { /* Forward declaration. */ class CCBReader; @@ -22,15 +22,15 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(SpriteLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(Sprite); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::Sprite); - virtual void onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader); - virtual void onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); - virtual void onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pCCBBlendFunc, CCBReader * ccbReader); - virtual void onHandlePropTypeSpriteFrame(Node * pNode, Node * pParent, const char * pPropertyName, SpriteFrame * pSpriteFrame, CCBReader * ccbReader); - virtual void onHandlePropTypeFlip(Node * pNode, Node * pParent, const char * pPropertyName, bool * pFlip, CCBReader * ccbReader); + virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); + virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); + virtual void onHandlePropTypeBlendFunc(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::BlendFunc pCCBBlendFunc, CCBReader * ccbReader); + virtual void onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader); + virtual void onHandlePropTypeFlip(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, bool * pFlip, CCBReader * ccbReader); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocosbuilder/CocosBuilder.h b/cocos/editor-support/cocosbuilder/CocosBuilder.h new file mode 100644 index 0000000000..6baa5d2ddc --- /dev/null +++ b/cocos/editor-support/cocosbuilder/CocosBuilder.h @@ -0,0 +1,32 @@ +#ifndef __EDITOR_SUPPORT_COCOSBUILDER_H__ +#define __EDITOR_SUPPORT_COCOSBUILDER_H__ + +#include "cocosbuilder/CCBAnimationManager.h" +#include "cocosbuilder/CCBFileLoader.h" +#include "cocosbuilder/CCBKeyframe.h" +#include "cocosbuilder/CCBMemberVariableAssigner.h" +#include "cocosbuilder/CCBReader.h" +#include "cocosbuilder/CCBSelectorResolver.h" +#include "cocosbuilder/CCBSequence.h" +#include "cocosbuilder/CCBSequenceProperty.h" +#include "cocosbuilder/CCBValue.h" +#include "cocosbuilder/CCControlButtonLoader.h" +#include "cocosbuilder/CCControlLoader.h" +#include "cocosbuilder/CCLabelBMFontLoader.h" +#include "cocosbuilder/CCLabelTTFLoader.h" +#include "cocosbuilder/CCLayerColorLoader.h" +#include "cocosbuilder/CCLayerGradientLoader.h" +#include "cocosbuilder/CCLayerLoader.h" +#include "cocosbuilder/CCMenuItemImageLoader.h" +#include "cocosbuilder/CCMenuItemLoader.h" +#include "cocosbuilder/CCMenuLoader.h" +#include "cocosbuilder/CCNode+CCBRelativePositioning.h" +#include "cocosbuilder/CCNodeLoader.h" +#include "cocosbuilder/CCNodeLoaderLibrary.h" +#include "cocosbuilder/CCNodeLoaderListener.h" +#include "cocosbuilder/CCParticleSystemQuadLoader.h" +#include "cocosbuilder/CCScale9SpriteLoader.h" +#include "cocosbuilder/CCScrollViewLoader.h" +#include "cocosbuilder/CCSpriteLoader.h" + +#endif // __EDITOR_SUPPORT_COCOSBUILDER_H__ diff --git a/cocos/editor-support/cocostudio/Android.mk b/cocos/editor-support/cocostudio/Android.mk new file mode 100644 index 0000000000..15b18c83d7 --- /dev/null +++ b/cocos/editor-support/cocostudio/Android.mk @@ -0,0 +1,64 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := cocostudio_static + +LOCAL_MODULE_FILENAME := libcocostudio + +LOCAL_SRC_FILES := action/CCActionFrame.cpp \ +action/CCActionFrameEasing.cpp \ +action/CCActionManagerEx.cpp \ +action/CCActionNode.cpp \ +action/CCActionObject.cpp \ +armature/CCArmature.cpp \ +armature/CCBone.cpp \ +armature/animation/CCArmatureAnimation.cpp \ +armature/animation/CCProcessBase.cpp \ +armature/animation/CCTween.cpp \ +armature/datas/CCDatas.cpp \ +armature/display/CCBatchNode.cpp \ +armature/display/CCDecorativeDisplay.cpp \ +armature/display/CCDisplayFactory.cpp \ +armature/display/CCDisplayManager.cpp \ +armature/display/CCSkin.cpp \ +armature/physics/CCColliderDetector.cpp \ +armature/utils/CCArmatureDataManager.cpp \ +armature/utils/CCArmatureDefine.cpp \ +armature/utils/CCDataReaderHelper.cpp \ +armature/utils/CCSpriteFrameCacheHelper.cpp \ +armature/utils/CCTransformHelp.cpp \ +armature/utils/CCTweenFunction.cpp \ +armature/utils/CCUtilMath.cpp \ +components/CCComAttribute.cpp \ +components/CCComAudio.cpp \ +components/CCComController.cpp \ +components/CCComRender.cpp \ +components/CCInputDelegate.cpp \ +json/CSContentJsonDictionary.cpp \ +json/DictionaryHelper.cpp \ +reader/CCSGUIReader.cpp \ +reader/CCSSceneReader.cpp \ +../../../external/json/json_reader.cpp \ +../../../external/json/json_value.cpp \ +../../../external/json/json_writer.cpp + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ +$(LOCAL_PATH)/../../../external/json + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ +$(LOCAL_PATH)/../../../external/json \ +$(LOCAL_PATH) \ +$(LOCAL_PATH)/../../gui \ +$(LOCAL_PATH)/../../../external + +LOCAL_CFLAGS += -Wno-psabi -fexceptions +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,2d) +$(call import-module,audio/android) + diff --git a/cocos/editor-support/cocostudio/CocoStudio.h b/cocos/editor-support/cocostudio/CocoStudio.h new file mode 100644 index 0000000000..be6d9d807b --- /dev/null +++ b/cocos/editor-support/cocostudio/CocoStudio.h @@ -0,0 +1,62 @@ +/**************************************************************************** + 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 __EDITOR_SUPPORT_COCOSTUDIO_H__ +#define __EDITOR_SUPPORT_COCOSTUDIO_H__ + +#include "action/CCActionFrame.h" +#include "action/CCActionFrameEasing.h" +#include "action/CCActionManagerEx.h" +#include "action/CCActionNode.h" +#include "action/CCActionObject.h" +#include "armature/CCArmature.h" +#include "armature/CCBone.h" +#include "armature/animation/CCArmatureAnimation.h" +#include "armature/animation/CCProcessBase.h" +#include "armature/animation/CCTween.h" +#include "armature/datas/CCDatas.h" +#include "armature/display/CCBatchNode.h" +#include "armature/display/CCDecorativeDisplay.h" +#include "armature/display/CCDisplayFactory.h" +#include "armature/display/CCDisplayManager.h" +#include "armature/display/CCSkin.h" +#include "armature/physics/CCColliderDetector.h" +#include "armature/utils/CCArmatureDataManager.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/utils/CCDataReaderHelper.h" +#include "armature/utils/CCSpriteFrameCacheHelper.h" +#include "armature/utils/CCTransformHelp.h" +#include "armature/utils/CCTweenFunction.h" +#include "armature/utils/CCUtilMath.h" +#include "components/CCComAttribute.h" +#include "components/CCComAudio.h" +#include "components/CCComController.h" +#include "components/CCComRender.h" +#include "components/CCInputDelegate.h" +#include "json/CSContentJsonDictionary.h" +#include "json/DictionaryHelper.h" +#include "reader/CCSGUIReader.h" +#include "reader/CCSSceneReader.h" + +#endif diff --git a/cocos/editor-support/cocostudio/action/CCActionFrame.cpp b/cocos/editor-support/cocostudio/action/CCActionFrame.cpp index 5973f73196..724ed9a075 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrame.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionFrame.cpp @@ -24,7 +24,9 @@ #include "CCActionFrame.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace cocostudio { ActionFrame::ActionFrame() : _frameType(0) @@ -222,4 +224,4 @@ Action* ActionTintFrame::getAction(float fDuration) } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/action/CCActionFrame.h b/cocos/editor-support/cocostudio/action/CCActionFrame.h index 30902a90bf..c928db23cd 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrame.h +++ b/cocos/editor-support/cocostudio/action/CCActionFrame.h @@ -26,9 +26,8 @@ #define __ActionFRAME_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace cocostudio { enum FrameType { @@ -40,7 +39,7 @@ enum FrameType kKeyframeMax }; -class ActionFrame:public Object +class ActionFrame:public cocos2d::Object { public: @@ -118,7 +117,7 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: int _frameType; int _easingType; @@ -145,14 +144,14 @@ public: * * @param the move action position. */ - void setPosition(Point pos); + void setPosition(cocos2d::Point pos); /** * Gets the move action position. * * @return the move action position. */ - Point getPosition(); + cocos2d::Point getPosition(); /** * Gets the CCAction of ActionFrame. @@ -161,9 +160,9 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: - Point _position; + cocos2d::Point _position; }; class ActionScaleFrame:public ActionFrame @@ -215,7 +214,7 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: float _scaleX; float _scaleY; @@ -256,7 +255,7 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: float _rotation; }; @@ -296,7 +295,7 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: float _opacity; }; @@ -321,14 +320,14 @@ public: * * @param ccolor the tint action color */ - void setColor(Color3B ccolor); + void setColor(cocos2d::Color3B ccolor); /** * Gets the tint action color. * * @return the tint action color. */ - Color3B getColor(); + cocos2d::Color3B getColor(); /** * Gets the CCAction of ActionFrame. @@ -337,11 +336,11 @@ public: * * @return CCAction */ - virtual Action* getAction(float fDuration); + virtual cocos2d::Action* getAction(float fDuration); protected: - Color3B _color; + cocos2d::Color3B _color; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp index 8b235160d8..1e6513b56c 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp @@ -24,8 +24,8 @@ #include #include "CCActionFrameEasing.h" -#include "../Json/DictionaryHelper.h" -NS_CC_EXT_BEGIN +#include "json/DictionaryHelper.h" +namespace cocostudio { #ifndef M_PI_X_2 #define M_PI_X_2 (float)M_PI * 2.0f @@ -186,4 +186,4 @@ float ActionFrameEasing::easeValue(float t) return 0; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h index 66c8aaea0f..aa6fd570e4 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h +++ b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h @@ -26,10 +26,9 @@ #define __ActionFrameEasing_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -#include "../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { enum FrameEasingType { @@ -68,6 +67,6 @@ public: float easeValue(float t); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp index 3f927c1b84..8d842715b1 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp @@ -23,9 +23,11 @@ ****************************************************************************/ #include "CCActionManagerEx.h" -#include "../Json/DictionaryHelper.h" +#include "json/DictionaryHelper.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace cocostudio { static ActionManagerEx* sharedActionManager = NULL; @@ -55,7 +57,7 @@ ActionManagerEx::~ActionManagerEx() _pActionDic->release(); } -void ActionManagerEx::initWithDictionary(const char* jsonName,cs::JsonDictionary *dic,Object* root) +void ActionManagerEx::initWithDictionary(const char* jsonName,JsonDictionary *dic,Object* root) { std::string path = jsonName; int pos = path.find_last_of("/"); @@ -66,7 +68,7 @@ void ActionManagerEx::initWithDictionary(const char* jsonName,cs::JsonDictionary for (int i=0; iautorelease(); - cs::JsonDictionary* actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); + JsonDictionary* actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); action->initWithDictionary(actionDic,root); actionList->addObject(action); CC_SAFE_DELETE(actionDic); @@ -108,4 +110,4 @@ void ActionManagerEx::releaseActions() } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h b/cocos/editor-support/cocostudio/action/CCActionManagerEx.h index 21ae504718..4c757dfa37 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/action/CCActionManagerEx.h @@ -26,13 +26,12 @@ #define __ActionMANAGER_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCActionObject.h" -#include "../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { -class ActionManagerEx:public Object +class ActionManagerEx:public cocos2d::Object { public: @@ -77,7 +76,7 @@ public: void playActionByName(const char* jsonName,const char* actionName); /*init properties with json dictionay*/ - void initWithDictionary(const char* jsonName,cs::JsonDictionary* dic,Object* root); + void initWithDictionary(const char* jsonName,JsonDictionary* dic,cocos2d::Object* root); /** * Release all actions. @@ -86,9 +85,9 @@ public: void releaseActions(); protected: - Dictionary* _pActionDic; + cocos2d::Dictionary* _pActionDic; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.cpp b/cocos/editor-support/cocostudio/action/CCActionNode.cpp index 31d6e7fe6e..ca7db6cc5f 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionNode.cpp @@ -24,11 +24,14 @@ THE SOFTWARE. #include "CCActionNode.h" #include "CCActionFrameEasing.h" -#include "../GUI/BaseClasses/UIWidget.h" -#include "../GUI/System/UIHelper.h" -#include "../Json/DictionaryHelper.h" +#include "base-classes/UIWidget.h" +#include "system/UIHelper.h" +#include "json/DictionaryHelper.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; +using namespace gui; + +namespace cocostudio { ActionNode::ActionNode() : _currentFrameIndex(0) @@ -70,13 +73,13 @@ ActionNode::~ActionNode() } } -void ActionNode::initWithDictionary(cs::JsonDictionary *dic,Object* root) +void ActionNode::initWithDictionary(JsonDictionary *dic,Object* root) { setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag")); int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist"); for (int i=0; igetDictionaryFromArray_json(dic, "actionframelist", i); + JsonDictionary* actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i); int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid"); bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx"); @@ -477,4 +480,4 @@ void ActionNode::easingToFrame(float duration,float delayTime,ActionFrame* destF cAction->update(delayTime); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.h b/cocos/editor-support/cocostudio/action/CCActionNode.h index 377ef603b3..9e69981bbb 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.h +++ b/cocos/editor-support/cocostudio/action/CCActionNode.h @@ -26,13 +26,12 @@ #define __ActionNODE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCActionFrame.h" -#include "../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { -class ActionNode:public Object +class ActionNode:public cocos2d::Object { public: @@ -77,14 +76,14 @@ public: * * @param node which will run a action */ - void setObject(Object* node); + void setObject(cocos2d::Object* node); /** * Gets node which will run a action. * * @return node which will run a action */ - Object* getObject(); + cocos2d::Object* getObject(); /** * Insets a ActionFrame to ActionNode. @@ -148,7 +147,7 @@ public: virtual void stopAction(); /*init properties with a json dictionary*/ - virtual void initWithDictionary(cs::JsonDictionary* dic,Object* root); + virtual void initWithDictionary(JsonDictionary* dic,cocos2d::Object* root); protected: int _currentFrameIndex; int _destFrameIndex; @@ -156,21 +155,21 @@ protected: float _fUnitTime; int _actionTag; - Spawn * _actionSpawn; - Action* _action; - Object* _object; + cocos2d::Spawn * _actionSpawn; + cocos2d::Action* _action; + cocos2d::Object* _object; - Array* _frameArray; + cocos2d::Array* _frameArray; int _frameArrayNum; protected: - virtual Node* getActionNode(); - virtual Spawn * refreshActionProperty(); + virtual cocos2d::Node* getActionNode(); + virtual cocos2d::Spawn * refreshActionProperty(); virtual void runAction(); - virtual void initActionNodeFromRoot(Object* root); + virtual void initActionNodeFromRoot(cocos2d::Object* root); virtual void easingToFrame(float duration,float delayTime,ActionFrame* destFrame); }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.cpp b/cocos/editor-support/cocostudio/action/CCActionObject.cpp index 3d8ba4f0ea..c649268a23 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionObject.cpp @@ -23,9 +23,11 @@ ****************************************************************************/ #include "CCActionObject.h" -#include "../Json/DictionaryHelper.h" +#include "json/DictionaryHelper.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace cocostudio { ActionObject::ActionObject() : _actionNodeList(NULL) @@ -94,7 +96,7 @@ bool ActionObject::isPlaying() return _bPlaying; } -void ActionObject::initWithDictionary(cs::JsonDictionary *dic,Object* root) +void ActionObject::initWithDictionary(JsonDictionary *dic,Object* root) { setName(DICTOOL->getStringValue_json(dic, "name")); setLoop(DICTOOL->getBooleanValue_json(dic, "loop")); @@ -103,7 +105,7 @@ void ActionObject::initWithDictionary(cs::JsonDictionary *dic,Object* root) for (int i=0; iautorelease(); - cs::JsonDictionary* actionNodeDic = DICTOOL->getDictionaryFromArray_json(dic, "actionnodelist", i); + JsonDictionary* actionNodeDic = DICTOOL->getDictionaryFromArray_json(dic, "actionnodelist", i); actionNode->initWithDictionary(actionNodeDic,root); actionNode->setUnitTime(getUnitTime()); _actionNodeList->addObject(actionNode); @@ -172,4 +174,4 @@ void ActionObject::updateToFrameByTime(float fTime) } } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.h b/cocos/editor-support/cocostudio/action/CCActionObject.h index d17f5658b4..34807e2127 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.h +++ b/cocos/editor-support/cocostudio/action/CCActionObject.h @@ -26,13 +26,12 @@ #define __ActionObject_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "CCActionNode.h" -#include "../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { -class ActionObject:public Object +class ActionObject:public cocos2d::Object { public: @@ -142,10 +141,10 @@ public: void updateToFrameByTime(float fTime); /*init properties with a json dictionary*/ - void initWithDictionary(cs::JsonDictionary* dic,Object* root); + void initWithDictionary(JsonDictionary* dic,cocos2d::Object* root); protected: - Array* _actionNodeList;/*actionnode*/ + cocos2d::Array* _actionNodeList;/*actionnode*/ std::string _name; bool _loop; bool _bPause; @@ -154,6 +153,6 @@ protected: float _currentTime; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/cocostudio/armature/CCArmature.cpp b/cocos/editor-support/cocostudio/armature/CCArmature.cpp index d7817b16b1..7d4777d3f3 100644 --- a/cocos/editor-support/cocostudio/armature/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/armature/CCArmature.cpp @@ -35,8 +35,10 @@ THE SOFTWARE. #include "chipmunk.h" #endif +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN + +namespace cocostudio { Armature *Armature::create() { @@ -788,4 +790,4 @@ cpShape *Armature::getShapeList() #endif -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/CCArmature.h b/cocos/editor-support/cocostudio/armature/CCArmature.h index 204ab34d8a..bc0843c540 100644 --- a/cocos/editor-support/cocostudio/armature/CCArmature.h +++ b/cocos/editor-support/cocostudio/armature/CCArmature.h @@ -35,7 +35,7 @@ THE SOFTWARE. class b2Body; struct cpBody; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { CC_DEPRECATED_ATTRIBUTE typedef ProcessBase CCProcessBase; CC_DEPRECATED_ATTRIBUTE typedef BaseData CCBaseData; @@ -66,7 +66,7 @@ CC_DEPRECATED_ATTRIBUTE typedef ArmatureAnimation CCArmatureAnimation; CC_DEPRECATED_ATTRIBUTE typedef Armature CCArmature; CC_DEPRECATED_ATTRIBUTE typedef ArmatureDataManager CCArmatureDataManager; -class Armature : public NodeRGBA, public BlendProtocol +class Armature : public cocos2d::NodeRGBA, public cocos2d::BlendProtocol { public: @@ -139,12 +139,12 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - Dictionary *getBoneDic(); + cocos2d::Dictionary *getBoneDic(); /** * This boundingBox will calculate all bones' boundingBox every time */ - virtual Rect getBoundingBox() const; + virtual cocos2d::Rect getBoundingBox() const; Bone *getBoneAtPoint(float x, float y); @@ -157,10 +157,10 @@ public: virtual void update(float dt) override; virtual void draw() override; - virtual const AffineTransform& getNodeToParentTransform() const override; + virtual const cocos2d::AffineTransform& getNodeToParentTransform() const override; - inline void setBlendFunc(const BlendFunc &blendFunc) override { _blendFunc = blendFunc; } - inline const BlendFunc &getBlendFunc(void) const override{ return _blendFunc; } + inline void setBlendFunc(const cocos2d::BlendFunc &blendFunc) override { _blendFunc = blendFunc; } + inline const cocos2d::BlendFunc &getBlendFunc(void) const override{ return _blendFunc; } /** @@ -195,7 +195,7 @@ protected: CC_SYNTHESIZE(std::string, _name, Name); - CC_SYNTHESIZE(TextureAtlas *, _atlas, TextureAtlas); + CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); CC_SYNTHESIZE(Bone *, _parentBone, ParentBone); @@ -204,13 +204,13 @@ protected: protected: mutable bool _armatureTransformDirty; - Dictionary *_boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. + cocos2d::Dictionary *_boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. - Array *_topBoneList; + cocos2d::Array *_topBoneList; - BlendFunc _blendFunc; //! It's required for CCTextureProtocol inheritance + cocos2d::BlendFunc _blendFunc; //! It's required for CCTextureProtocol inheritance - Point _offsetPoint; + cocos2d::Point _offsetPoint; ArmatureAnimation *_animation; @@ -221,6 +221,6 @@ protected: #endif }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCARMATURE_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/CCBone.cpp b/cocos/editor-support/cocostudio/armature/CCBone.cpp index e6063e51c3..52dea85860 100644 --- a/cocos/editor-support/cocostudio/armature/CCBone.cpp +++ b/cocos/editor-support/cocostudio/armature/CCBone.cpp @@ -29,7 +29,9 @@ THE SOFTWARE. #include "utils/CCTransformHelp.h" #include "display/CCDisplayManager.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { Bone *Bone::create() { @@ -373,4 +375,4 @@ Array *Bone::getColliderBodyList() } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/CCBone.h b/cocos/editor-support/cocostudio/armature/CCBone.h index 9f979e616a..85edc0f5b1 100644 --- a/cocos/editor-support/cocostudio/armature/CCBone.h +++ b/cocos/editor-support/cocostudio/armature/CCBone.h @@ -31,12 +31,12 @@ THE SOFTWARE. #include "display/CCDecorativeDisplay.h" #include "display/CCDisplayManager.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class Armature; -class Bone : public NodeRGBA +class Bone : public cocos2d::NodeRGBA { public: /** @@ -84,7 +84,7 @@ public: */ void addDisplay(DisplayData *displayData, int index); - void addDisplay(Node *display, int index); + void addDisplay(cocos2d::Node *display, int index); void changeDisplayByIndex(int index, bool force); @@ -124,7 +124,7 @@ public: void update(float delta); - void updateDisplayedColor(const Color3B &parentColor); + void updateDisplayedColor(const cocos2d::Color3B &parentColor); void updateDisplayedOpacity(GLubyte parentOpacity); //! Update color to render display @@ -144,15 +144,15 @@ public: virtual bool isTransformDirty(); - virtual AffineTransform getNodeToArmatureTransform() const; - virtual AffineTransform getNodeToWorldTransform() const override; + virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; + virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; Node *getDisplayRenderNode(); /* * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. */ - virtual Array *getColliderBodyList(); + virtual cocos2d::Array *getColliderBodyList(); public: /* @@ -188,9 +188,9 @@ protected: bool _boneTransformDirty; //! Whether or not transform dirty //! self Transform, use this to change display's state - AffineTransform _worldTransform; + cocos2d::AffineTransform _worldTransform; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCBONE_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp index 02c0e8d688..4c42af7d1e 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp @@ -23,14 +23,16 @@ THE SOFTWARE. ****************************************************************************/ #include "CCArmatureAnimation.h" -#include "../CCArmature.h" -#include "../CCBone.h" -#include "../utils/CCArmatureDefine.h" -#include "../utils/CCUtilMath.h" -#include "../datas/CCDatas.h" +#include "armature/CCArmature.h" +#include "armature/CCBone.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/utils/CCUtilMath.h" +#include "armature/datas/CCDatas.h" + +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { ArmatureAnimation *ArmatureAnimation::create(Armature *armature) { @@ -403,4 +405,4 @@ void ArmatureAnimation::frameEvent(Bone *bone, const char *frameEventName, int o (_frameEventTarget->*_frameEventCallFunc)(bone, frameEventName, originFrameIndex, currentFrameIndex); } } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h index 967878874a..b9ac3d4200 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCProcessBase.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { enum MovementEventType @@ -42,8 +42,8 @@ enum MovementEventType class Armature; class Bone; -typedef void (Object::*SEL_MovementEventCallFunc)(Armature *, MovementEventType, const char *); -typedef void (Object::*SEL_FrameEventCallFunc)(Bone *, const char *, int, int); +typedef void (cocos2d::Object::*SEL_MovementEventCallFunc)(Armature *, MovementEventType, const char *); +typedef void (cocos2d::Object::*SEL_FrameEventCallFunc)(Bone *, const char *, int, int); #define movementEvent_selector(_SELECTOR) (SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (SEL_FrameEventCallFunc)(&_SELECTOR) @@ -158,13 +158,13 @@ public: * Set armature's movement event callback function * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); */ - void setMovementEventCallFunc(Object *target, SEL_MovementEventCallFunc callFunc); + void setMovementEventCallFunc(cocos2d::Object *target, SEL_MovementEventCallFunc callFunc); /** * Set armature's frame event callback function * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); */ - void setFrameEventCallFunc(Object *target, SEL_FrameEventCallFunc callFunc); + void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); protected: @@ -199,7 +199,7 @@ protected: int _toIndex; //! The frame index in MovementData->m_pMovFrameDataArr, it's different from m_iFrameIndex. - Array *_tweenList; + cocos2d::Array *_tweenList; protected: /** @@ -220,10 +220,10 @@ protected: SEL_FrameEventCallFunc _frameEventCallFunc; - Object *_movementEventTarget; - Object *_frameEventTarget; + cocos2d::Object *_movementEventTarget; + cocos2d::Object *_frameEventTarget; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCANIMATION_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp index 00609f83b8..a30f68abd4 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp @@ -23,9 +23,11 @@ THE SOFTWARE. ****************************************************************************/ #include "CCProcessBase.h" -#include "../utils/CCUtilMath.h" +#include "armature/utils/CCUtilMath.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { ProcessBase::ProcessBase(void) : _processScale(1) @@ -149,4 +151,4 @@ int ProcessBase::getCurrentFrameIndex() return _curFrameIndex; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h index 5ee5a1ca01..dbde23dd1f 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h @@ -26,10 +26,10 @@ THE SOFTWARE. #ifndef __CCPROCESSBASE_H__ #define __CCPROCESSBASE_H__ -#include "../utils/CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/datas/CCDatas.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { enum AnimationType { @@ -47,7 +47,7 @@ enum AnimationType }; -class ProcessBase : public Object +class ProcessBase : public cocos2d::Object { public: /** @@ -169,6 +169,6 @@ protected: bool _isLoopBack; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCPROCESSBASE_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp b/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp index b66e33465f..23896d1e8b 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp @@ -25,14 +25,14 @@ THE SOFTWARE. #include "CCTween.h" #include "CCArmatureAnimation.h" -#include "../CCBone.h" -#include "../CCArmature.h" -#include "../utils/CCUtilMath.h" -#include "../utils/CCTweenFunction.h" -#include "../utils/CCTransformHelp.h" +#include "armature/CCBone.h" +#include "armature/CCArmature.h" +#include "armature/utils/CCUtilMath.h" +#include "armature/utils/CCTweenFunction.h" +#include "armature/utils/CCTransformHelp.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { Tween *Tween::create(Bone *bone) { @@ -462,4 +462,4 @@ float Tween::updateFrameData(float currentPercent) return currentPercent; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.h b/cocos/editor-support/cocostudio/armature/animation/CCTween.h index b4a64bc3ef..bcbdde822c 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCTween.h @@ -27,9 +27,9 @@ THE SOFTWARE. #define __CCTWEEN_H__ #include "CCProcessBase.h" -#include "../utils/CCTweenFunction.h" +#include "armature/utils/CCTweenFunction.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class Bone; class ArmatureAnimation; @@ -147,6 +147,6 @@ protected: }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCTWEEN_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp b/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp index 38c31db4b7..e03213ab8a 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp +++ b/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp @@ -23,10 +23,12 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDatas.h" -#include "../utils/CCUtilMath.h" -#include "../utils/CCTransformHelp.h" +#include "armature/utils/CCUtilMath.h" +#include "armature/utils/CCTransformHelp.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { BaseData::BaseData() @@ -425,4 +427,4 @@ ContourData *TextureData::getContourData(int index) } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h b/cocos/editor-support/cocostudio/armature/datas/CCDatas.h index be2b67e45c..81fca8ebcb 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h +++ b/cocos/editor-support/cocostudio/armature/datas/CCDatas.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCARMATURE_DATAS_H__ #define __CCARMATURE_DATAS_H__ -#include "../utils/CCArmatureDefine.h" -#include "../utils/CCTweenFunction.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/utils/CCTweenFunction.h" #define CC_CREATE_NO_PARAM_NO_INIT(varType)\ @@ -55,12 +55,12 @@ public: \ return NULL;\ } -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { /** * The base node include a lot of attributes. */ -class BaseData : public Object +class BaseData : public cocos2d::Object { public: CC_CREATE_NO_PARAM_NO_INIT(BaseData) @@ -89,8 +89,8 @@ public: */ virtual void subtract(BaseData *from, BaseData *to, bool limit); - virtual void setColor(const Color4B &color); - virtual Color4B getColor(); + virtual void setColor(const cocos2d::Color4B &color); + virtual cocos2d::Color4B getColor(); public: float x; //! position x attribute float y; //! position y attribute @@ -126,7 +126,7 @@ enum DisplayType CS_DISPLAY_MAX }; -class DisplayData : public Object +class DisplayData : public cocos2d::Object { public: CC_CREATE_NO_PARAM_NO_INIT(DisplayData) @@ -269,8 +269,8 @@ public: public: std::string name; //! the bone's name std::string parentName; //! the bone parent's name - Array displayDataList; //! save DisplayData informations for the Bone - AffineTransform boneDataTransform; + cocos2d::Array displayDataList; //! save DisplayData informations for the Bone + cocos2d::AffineTransform boneDataTransform; }; @@ -279,7 +279,7 @@ public: * When we create a Armature, we need to get each Bone's BoneData as it's init information. * So we can get a BoneData from the Dictionary saved in the ArmatureData. */ -class ArmatureData : public Object +class ArmatureData : public cocos2d::Object { public: CC_CREATE_NO_PARAM(ArmatureData) @@ -299,7 +299,7 @@ public: BoneData *getBoneData(const char *boneName); public: std::string name; - Dictionary boneDataDic; + cocos2d::Dictionary boneDataDic; float dataVersion; }; @@ -362,7 +362,7 @@ public: }; -class MovementBoneData : public Object +class MovementBoneData : public cocos2d::Object { public: CC_CREATE_NO_PARAM(MovementBoneData) @@ -387,11 +387,11 @@ public: float duration; //! this Bone in this movement will last m_iDuration frames std::string name; //! bone name - Array frameList; + cocos2d::Array frameList; }; -class MovementData : public Object +class MovementData : public cocos2d::Object { public: CC_CREATE_NO_PARAM_NO_INIT(MovementData) @@ -442,7 +442,7 @@ public: * @key const char * * @value MovementBoneData * */ - Dictionary movBoneDataDic; + cocos2d::Dictionary movBoneDataDic; }; @@ -451,7 +451,7 @@ public: * The struct is AnimationData -> MovementData -> MovementBoneData -> FrameData * -> MovementFrameData */ -class AnimationData : public Object +class AnimationData : public cocos2d::Object { public: CC_CREATE_NO_PARAM_NO_INIT(AnimationData) @@ -471,12 +471,12 @@ public: int getMovementCount(); public: std::string name; - Dictionary movementDataDic; + cocos2d::Dictionary movementDataDic; std::vector movementNames; }; -struct ContourVertex2 : public Object +struct ContourVertex2 : public cocos2d::Object { ContourVertex2(float x, float y) { @@ -491,7 +491,7 @@ struct ContourVertex2 : public Object /* * ContourData include a contour vertex information */ -class ContourData : public Object +class ContourData : public cocos2d::Object { public: CC_CREATE_NO_PARAM(ContourData) @@ -507,9 +507,9 @@ public: ~ContourData(void); virtual bool init(); - virtual void addVertex(Point *vertex); + virtual void addVertex(cocos2d::Point *vertex); public: - Array vertexList; //! Save contour vertex info, vertex saved in a Point + cocos2d::Array vertexList; //! Save contour vertex info, vertex saved in a Point }; @@ -518,7 +518,7 @@ public: /* * TextureData include a texture's information */ -class TextureData : public Object +class TextureData : public cocos2d::Object { public: CC_CREATE_NO_PARAM(TextureData) @@ -547,10 +547,10 @@ public: std::string name; //! The texture's name - Array contourDataList; + cocos2d::Array contourDataList; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCARMATURE_DATAS_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp index 16dd1b449b..04ae69a524 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp @@ -23,10 +23,12 @@ THE SOFTWARE. ****************************************************************************/ #include "CCBatchNode.h" -#include "../utils/CCArmatureDefine.h" -#include "../CCArmature.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/CCArmature.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { BatchNode *BatchNode::create() { @@ -117,4 +119,4 @@ void BatchNode::draw() } } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h index b79fc97d5d..fac221adb6 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h @@ -25,11 +25,11 @@ THE SOFTWARE. #ifndef __CCBATCHNODE_H__ #define __CCBATCHNODE_H__ -#include "../utils/CCArmatureDefine.h" +#include "armature/utils/CCArmatureDefine.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { -class BatchNode : public Node +class BatchNode : public cocos2d::Node { public: static BatchNode *create(); @@ -40,14 +40,14 @@ public: BatchNode(); virtual bool init(); - virtual void addChild(Node *child, int zOrder, int tag); + virtual void addChild(cocos2d::Node *child, int zOrder, int tag); virtual void visit(); void draw(); protected: - TextureAtlas *_atlas; + cocos2d::TextureAtlas *_atlas; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCBATCHNODE_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp index d92fef659b..0213219ddb 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp @@ -24,7 +24,9 @@ THE SOFTWARE. #include "CCDecorativeDisplay.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { DecorativeDisplay *DecorativeDisplay::create() { @@ -64,4 +66,4 @@ bool DecorativeDisplay::init() return true; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h index 2b08dce2a8..3b42c9c64e 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h @@ -25,18 +25,18 @@ THE SOFTWARE. #ifndef __CCDECORATIVEDISPLAY_H__ #define __CCDECORATIVEDISPLAY_H__ -#include "../utils/CCArmatureDefine.h" +#include "armature/utils/CCArmatureDefine.h" #include "CCDisplayFactory.h" -#include "../datas/CCDatas.h" +#include "armature/datas/CCDatas.h" #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT #include "../physics/CCColliderDetector.h" #endif -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { -class DecorativeDisplay: public Object +class DecorativeDisplay: public cocos2d::Object { public: static DecorativeDisplay *create(); @@ -55,7 +55,7 @@ public: protected: - CC_SYNTHESIZE_RETAIN(Node *, _display, Display); + CC_SYNTHESIZE_RETAIN(cocos2d::Node *, _display, Display); CC_SYNTHESIZE_RETAIN(DisplayData *, _displayData, DisplayData); #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT @@ -63,6 +63,6 @@ protected: #endif }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCDECORATIVEDISPLAY_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp index 4cef6fad53..30d3184ff8 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp @@ -23,14 +23,16 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDisplayFactory.h" -#include "../CCBone.h" -#include "../CCArmature.h" -#include "../display/CCSkin.h" -#include "../utils/CCSpriteFrameCacheHelper.h" -#include "../utils/CCArmatureDataManager.h" -#include "../utils/CCTransformHelp.h" +#include "armature/CCBone.h" +#include "armature/CCArmature.h" +#include "armature/display/CCSkin.h" +#include "armature/utils/CCSpriteFrameCacheHelper.h" +#include "armature/utils/CCArmatureDataManager.h" +#include "armature/utils/CCTransformHelp.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { void DisplayFactory::addDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { @@ -272,4 +274,4 @@ void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt, } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h index 6df1fff7bb..80aa33680d 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h @@ -25,10 +25,10 @@ THE SOFTWARE. #ifndef __CCDISPLAYFACTORY_H__ #define __CCDISPLAYFACTORY_H__ -#include "../utils/CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/datas/CCDatas.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class Skin; class Bone; @@ -45,19 +45,19 @@ public: static void addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay); static void initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin); - static void updateSpriteDisplay(Bone *bone, Node *display, float dt, bool dirty); + static void updateSpriteDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); static void addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateArmatureDisplay(Bone *bone, Node *display, float dt, bool dirty); + static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); static void addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateParticleDisplay(Bone *bone, Node *display, float dt, bool dirty); + static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCDISPLAYFACTORY_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp index a0c89f45cd..da87bea351 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp @@ -23,12 +23,14 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDisplayManager.h" -#include "../CCBone.h" -#include "../CCArmature.h" -#include "../utils/CCUtilMath.h" -#include "../display/CCSkin.h" +#include "armature/CCBone.h" +#include "armature/CCArmature.h" +#include "armature/utils/CCUtilMath.h" +#include "armature/display/CCSkin.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { DisplayManager *DisplayManager::create(Bone *bone) { @@ -392,4 +394,4 @@ Point DisplayManager::getAnchorPointInPoints() } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h index 94933f96b5..2e9eb217fc 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h @@ -25,16 +25,16 @@ THE SOFTWARE. #ifndef __CCDISPLAYMANAGER_H__ #define __CCDISPLAYMANAGER_H__ -#include "../utils/CCArmatureDefine.h" -#include "../display/CCDecorativeDisplay.h" -#include "../datas/CCDatas.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/display/CCDecorativeDisplay.h" +#include "armature/datas/CCDatas.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class Bone; //! DisplayManager manages Bone's display -class DisplayManager : public Object +class DisplayManager : public cocos2d::Object { public: static DisplayManager *create(Bone *bone); @@ -72,11 +72,11 @@ public: */ void addDisplay(DisplayData *displayData, int index); - void addDisplay(Node *display, int index); + void addDisplay(cocos2d::Node *display, int index); void removeDisplay(int index); - Array *getDecorativeDisplayList(); + cocos2d::Array *getDecorativeDisplayList(); /** * Change display by index. You can just use this method to change display in the display list. @@ -90,7 +90,7 @@ public: void changeDisplayByIndex(int index, bool force); - Node *getDisplayRenderNode(); + cocos2d::Node *getDisplayRenderNode(); int getCurrentDisplayIndex(); @@ -113,16 +113,16 @@ public: */ virtual bool isVisible(); - Size getContentSize(); - Rect getBoundingBox(); + cocos2d::Size getContentSize(); + cocos2d::Rect getBoundingBox(); - Point getAnchorPoint(); - Point getAnchorPointInPoints(); + cocos2d::Point getAnchorPoint(); + cocos2d::Point getAnchorPointInPoints(); /** * Check if the position is inside the bone. */ - virtual bool containPoint(Point &_point); + virtual bool containPoint(cocos2d::Point &_point); /** * Check if the position is inside the bone. @@ -130,9 +130,9 @@ public: virtual bool containPoint(float x, float y); protected: - Array *_decoDisplayList; + cocos2d::Array *_decoDisplayList; //! Display render node. - Node *_displayRenderNode; + cocos2d::Node *_displayRenderNode; //! Include current display information, like contour sprite, etc. DecorativeDisplay *_currentDecoDisplay; //! Current display index @@ -146,6 +146,6 @@ protected: Bone *_bone; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCDISPLAYMANAGER_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp b/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp index 2fdf2b24af..cd91c18ef4 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp @@ -23,11 +23,13 @@ THE SOFTWARE. ****************************************************************************/ #include "CCSkin.h" -#include "../utils/CCTransformHelp.h" -#include "../utils/CCSpriteFrameCacheHelper.h" -#include "../CCArmature.h" +#include "armature/utils/CCTransformHelp.h" +#include "armature/utils/CCSpriteFrameCacheHelper.h" +#include "armature/CCArmature.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { #if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL #define RENDER_IN_SUBPIXEL @@ -201,4 +203,4 @@ AffineTransform Skin::getNodeToWorldTransformAR() const return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.h b/cocos/editor-support/cocostudio/armature/display/CCSkin.h index 26453ece1a..4c20063bed 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.h +++ b/cocos/editor-support/cocostudio/armature/display/CCSkin.h @@ -25,12 +25,12 @@ THE SOFTWARE. #ifndef __CCSKIN_H__ #define __CCSKIN_H__ -#include "../utils/CCArmatureDefine.h" -#include "../CCBone.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/CCBone.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { -class Skin : public Sprite +class Skin : public cocos2d::Sprite { public: static Skin *create(); @@ -45,17 +45,17 @@ public: void updateArmatureTransform(); void updateTransform(); - AffineTransform getNodeToWorldTransform() const; - AffineTransform getNodeToWorldTransformAR() const; + cocos2d::AffineTransform getNodeToWorldTransform() const; + cocos2d::AffineTransform getNodeToWorldTransformAR() const; CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); CC_SYNTHESIZE(Bone *, _bone, Bone); protected: - AffineTransform _skinTransform; + cocos2d::AffineTransform _skinTransform; CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCSKIN_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp index 798a9b83b5..8d4dbf60cd 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCColliderDetector.h" -#include "../CCBone.h" -#include "../utils/CCTransformHelp.h" +#include "armature/CCBone.h" +#include "armature/utils/CCTransformHelp.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" @@ -32,8 +32,9 @@ THE SOFTWARE. #include "chipmunk.h" #endif +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { #if ENABLE_PHYSICS_BOX2D_DETECT @@ -393,4 +394,4 @@ cpBody *ColliderDetector::getBody() #endif -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h index 63990d3bf9..725036fddf 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCCOLLIDERDETECTOR_H__ #define __CCCOLLIDERDETECTOR_H__ -#include "../utils/CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/utils/CCArmatureDefine.h" +#include "armature/datas/CCDatas.h" #ifndef PT_RATIO #define PT_RATIO 32 @@ -40,11 +40,11 @@ struct b2Filter; struct cpBody; struct cpShape; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class Bone; -class ColliderBody : public Object +class ColliderBody : public cocos2d::Object { public: #if ENABLE_PHYSICS_BOX2D_DETECT @@ -70,7 +70,7 @@ private: /* * @brief ContourSprite used to draw the contour of the display */ -class ColliderDetector : public Object +class ColliderDetector : public cocos2d::Object { public: static ColliderDetector *create(); @@ -90,20 +90,20 @@ public: virtual bool init(Bone *bone); void addContourData(ContourData *contourData); - void addContourDataList(Array *contourDataList); + void addContourDataList(cocos2d::Array *contourDataList); void removeContourData(ContourData *contourData); void removeAll(); - void updateTransform(AffineTransform &t); + void updateTransform(cocos2d::AffineTransform &t); void setActive(bool active); bool getActive(); - Array *getColliderBodyList(); + cocos2d::Array *getColliderBodyList(); protected: - Array *_colliderBodyList; + cocos2d::Array *_colliderBodyList; CC_SYNTHESIZE(Bone *, _bone, Bone); #if ENABLE_PHYSICS_BOX2D_DETECT @@ -116,6 +116,6 @@ protected: bool _active; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCCOLLIDERDETECTOR_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp index e67f9a72e4..2d507f6b69 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp @@ -28,8 +28,9 @@ THE SOFTWARE. #include "CCDataReaderHelper.h" #include "CCSpriteFrameCacheHelper.h" +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { static ArmatureDataManager *s_sharedArmatureDataManager = NULL; @@ -245,4 +246,4 @@ Dictionary *ArmatureDataManager::getTextureDatas() const return _textureDatas; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h index 5b7d534d44..b3122d34f2 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h @@ -26,15 +26,15 @@ THE SOFTWARE. #define __CCARMATUREDATAMANAGER_H__ #include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/datas/CCDatas.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { /** * @brief format and manage armature configuration and armature animation */ -class ArmatureDataManager : public Object +class ArmatureDataManager : public cocos2d::Object { public: /** @deprecated Use getInstance() instead */ @@ -133,7 +133,7 @@ public: * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector); + void addArmatureFileInfoAsync(const char *configFilePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. @@ -144,7 +144,7 @@ public: * @brief Add ArmatureFileInfo, it is managed by ArmatureDataManager. * It will load data in a new thread */ - void addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector); + void addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name @@ -163,35 +163,35 @@ public: bool isAutoLoadSpriteFile(); - Dictionary *getArmatureDatas() const; - Dictionary *getAnimationDatas() const; - Dictionary *getTextureDatas() const; + cocos2d::Dictionary *getArmatureDatas() const; + cocos2d::Dictionary *getAnimationDatas() const; + cocos2d::Dictionary *getTextureDatas() const; private: /** * @brief save amature datas * @key std::string * @value ArmatureData * */ - Dictionary *_armarureDatas; + cocos2d::Dictionary *_armarureDatas; /** * @brief save animation datas * @key std::string * @value AnimationData * */ - Dictionary *_animationDatas; + cocos2d::Dictionary *_animationDatas; /** * @brief save texture datas * @key std::string * @value TextureData * */ - Dictionary *_textureDatas; + cocos2d::Dictionary *_textureDatas; bool _autoLoadSpriteFile; }; -NS_CC_EXT_ARMATURE_END +} #endif/*__CCARMATUREDATAMANAGER_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp index cbd53fe1e0..7ed21c9a3c 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp @@ -24,11 +24,11 @@ THE SOFTWARE. #include "CCArmatureDefine.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { const char *armatureVersion() { return "0.4.0.0"; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h index fdf82a43c0..8b7cb42312 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h @@ -27,7 +27,6 @@ THE SOFTWARE. #include "cocos2d.h" -#include "ExtensionMacros.h" #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f @@ -48,14 +47,10 @@ THE SOFTWARE. #define CS_RETURN_IF(cond) if (cond) return #define CS_RETURN_NULL_IF(cond) if (cond) return NULL; -#define NS_CC_EXT_ARMATURE_BEGIN namespace cocos2d { namespace extension { namespace armature { -#define NS_CC_EXT_ARMATURE_END }}} -#define USING_NS_CC_EXT_ARMATURE using namespace cocos2d::extension::armature - -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { const char *armatureVersion(); -NS_CC_EXT_ARMATURE_END +} #endif /*__CCARMATUREDEFINE_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp index 563526570c..67d0264825 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp @@ -22,13 +22,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "support/tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "CCDataReaderHelper.h" #include "CCArmatureDataManager.h" #include "CCTransformHelp.h" #include "CCUtilMath.h" #include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/datas/CCDatas.h" + +using namespace cocos2d; static const char *VERSION = "version"; @@ -133,7 +135,7 @@ static const char *COLOR_INFO = "color"; static const char *CONFIG_FILE_PATH = "config_file_path"; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { std::vector s_arrConfigFileList; @@ -1118,14 +1120,14 @@ ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo) { - cs::JsonDictionary json; + JsonDictionary json; json.initWithDescription(fileContent); // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); + JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); ArmatureData *armatureData = decodeArmature(*armatureDic); if (dataInfo) @@ -1145,7 +1147,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d length = json.getArrayItemCount(ANIMATION_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); + JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); AnimationData *animationData = decodeAnimation(*animationDic); if (dataInfo) @@ -1165,7 +1167,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d length = json.getArrayItemCount(TEXTURE_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); + JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); TextureData *textureData = decodeTexture(*textureDic); if (dataInfo) @@ -1213,7 +1215,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } } -ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json) +ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); @@ -1229,7 +1231,7 @@ ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json) int length = json.getArrayItemCount(BONE_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); BoneData *boneData = decodeBone(*dic); armatureData->addBoneData(boneData); boneData->release(); @@ -1240,7 +1242,7 @@ ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json) return armatureData; } -BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json) +BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) { BoneData *boneData = new BoneData(); boneData->init(); @@ -1263,7 +1265,7 @@ BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json) for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); DisplayData *displayData = decodeBoneDisplay(*dic); boneData->addDisplayData(displayData); displayData->release(); @@ -1274,7 +1276,7 @@ BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json) return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json) +DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); @@ -1292,7 +1294,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json) ((SpriteDisplayData *)displayData)->displayName = name; } - cs::JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); + JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); if (dic != NULL) { SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; @@ -1341,7 +1343,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json) return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json) +AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) { AnimationData *aniData = new AnimationData(); @@ -1355,7 +1357,7 @@ AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json) for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); MovementData *movementData = decodeMovement(*dic); aniData->addMovement(movementData); movementData->release(); @@ -1366,7 +1368,7 @@ AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json) return aniData; } -MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json) +MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) { MovementData *movementData = new MovementData(); @@ -1386,7 +1388,7 @@ MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json) int length = json.getArrayItemCount(MOVEMENT_BONE_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); MovementBoneData *movementBoneData = decodeMovementBone(*dic); movementData->addMovementBoneData(movementBoneData); movementBoneData->release(); @@ -1397,7 +1399,7 @@ MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json) return movementData; } -MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) +MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) { MovementBoneData *movementBoneData = new MovementBoneData(); movementBoneData->init(); @@ -1413,7 +1415,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) int length = json.getArrayItemCount(FRAME_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); FrameData *frameData = decodeFrame(*dic); movementBoneData->addFrameData(frameData); @@ -1469,7 +1471,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) return movementBoneData; } -FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) +FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json) { FrameData *frameData = new FrameData(); @@ -1498,7 +1500,7 @@ FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) return frameData; } -TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) +TextureData *DataReaderHelper::decodeTexture(JsonDictionary &json) { TextureData *textureData = new TextureData(); textureData->init(); @@ -1517,7 +1519,7 @@ TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) int length = json.getArrayItemCount(CONTOUR_DATA); for (int i = 0; i < length; i++) { - cs::JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); + JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); ContourData *contourData = decodeContour(*dic); textureData->contourDataList.addObject(contourData); contourData->release(); @@ -1528,7 +1530,7 @@ TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) return textureData; } -ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) +ContourData *DataReaderHelper::decodeContour(JsonDictionary &json) { ContourData *contourData = new ContourData(); contourData->init(); @@ -1536,7 +1538,7 @@ ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) int length = json.getArrayItemCount(VERTEX_POINT); for (int i = length - 1; i >= 0; i--) { - cs::JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); + JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); ContourVertex2 *vertex = new ContourVertex2(0, 0); @@ -1552,7 +1554,7 @@ ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) return contourData; } -void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json) +void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json) { node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; @@ -1563,7 +1565,7 @@ void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json) node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - cs::JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); if (colorDic) { @@ -1579,4 +1581,4 @@ void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json) } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h index 2389245c20..d7f8a9f19e 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h @@ -26,9 +26,9 @@ THE SOFTWARE. #define __CCDATAREADERHELPER_H__ #include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" -#include "../CCArmature.h" -#include "../../Json/CSContentJsonDictionary.h" +#include "armature/datas/CCDatas.h" +#include "armature/CCArmature.h" +#include "json/CSContentJsonDictionary.h" #include #include @@ -41,10 +41,10 @@ namespace tinyxml2 class XMLElement; } -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { -class DataReaderHelper : Object +class DataReaderHelper : cocos2d::Object { protected: @@ -60,8 +60,8 @@ protected: std::string fileContent; ConfigType configType; std::string baseFilePath; - Object *target; - SEL_SCHEDULE selector; + cocos2d::Object *target; + cocos2d::SEL_SCHEDULE selector; bool autoLoadSpriteFile; } AsyncStruct; @@ -99,7 +99,7 @@ public: ~DataReaderHelper(); void addDataFromFile(const char *filePath); - void addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector); + void addDataFromFileAsync(const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); @@ -145,20 +145,20 @@ public: public: static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); - static ArmatureData *decodeArmature(cs::JsonDictionary &json); - static BoneData *decodeBone(cs::JsonDictionary &json); - static DisplayData *decodeBoneDisplay(cs::JsonDictionary &json); + static ArmatureData *decodeArmature(JsonDictionary &json); + static BoneData *decodeBone(JsonDictionary &json); + static DisplayData *decodeBoneDisplay(JsonDictionary &json); - static AnimationData *decodeAnimation(cs::JsonDictionary &json); - static MovementData *decodeMovement(cs::JsonDictionary &json); - static MovementBoneData *decodeMovementBone(cs::JsonDictionary &json); - static FrameData *decodeFrame(cs::JsonDictionary &json); + static AnimationData *decodeAnimation(JsonDictionary &json); + static MovementData *decodeMovement(JsonDictionary &json); + static MovementBoneData *decodeMovementBone(JsonDictionary &json); + static FrameData *decodeFrame(JsonDictionary &json); - static TextureData *decodeTexture(cs::JsonDictionary &json); + static TextureData *decodeTexture(JsonDictionary &json); - static ContourData *decodeContour(cs::JsonDictionary &json); + static ContourData *decodeContour(JsonDictionary &json); - static void decodeNode(BaseData *node, cs::JsonDictionary &json); + static void decodeNode(BaseData *node, JsonDictionary &json); protected: void loadData(); @@ -190,6 +190,6 @@ protected: static DataReaderHelper *_dataReaderHelper; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCDATAREADERHELPER_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp index acbdf4c542..d17dab4fa2 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp @@ -24,8 +24,10 @@ THE SOFTWARE. #include "CCSpriteFrameCacheHelper.h" +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN + +namespace cocostudio { SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = NULL; @@ -72,4 +74,4 @@ SpriteFrameCacheHelper::~SpriteFrameCacheHelper() CC_SAFE_RELEASE_NULL(_textureAtlasDic); } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h index 257cf49cd8..6e1a4fe094 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h @@ -29,7 +29,7 @@ THE SOFTWARE. using namespace std; -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { class SpriteFrameCacheHelper { @@ -47,7 +47,7 @@ public: */ void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); - TextureAtlas *getTexureAtlasWithTexture(Texture2D *texture); + cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); private: /** @@ -60,11 +60,11 @@ private: */ ~SpriteFrameCacheHelper(); - Dictionary *_textureAtlasDic; + cocos2d::Dictionary *_textureAtlasDic; static SpriteFrameCacheHelper *_spriteFrameCacheHelper; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCSPRITEFRAMECACHEHELPER_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp index 081b160b26..133dbba1d2 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp @@ -25,7 +25,9 @@ THE SOFTWARE. #include "CCTransformHelp.h" #include "CCUtilMath.h" -NS_CC_EXT_ARMATURE_BEGIN +using namespace cocos2d; + +namespace cocostudio { AffineTransform TransformHelp::helpMatrix1; AffineTransform TransformHelp::helpMatrix2; @@ -149,4 +151,4 @@ void TransformHelp::nodeSub(BaseData &target, BaseData &source) target.scaleY -= source.scaleY; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h index 5542691616..540b62f1a3 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h @@ -26,9 +26,9 @@ THE SOFTWARE. #define __CCTRANSFORMHELP_H__ #include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" +#include "armature/datas/CCDatas.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { /* * use to calculate the matrix of node from parent node @@ -44,19 +44,19 @@ public: static void transformFromParentWithoutScale(BaseData &node, const BaseData &parentNode); static void transformToParentWithoutScale(BaseData &node, const BaseData &parentNode); - static void nodeToMatrix(const BaseData &_node, AffineTransform &_matrix); - static void matrixToNode(const AffineTransform &_matrix, BaseData &_node); + static void nodeToMatrix(const BaseData &_node, cocos2d::AffineTransform &_matrix); + static void matrixToNode(const cocos2d::AffineTransform &_matrix, BaseData &_node); static void nodeConcat(BaseData &target, BaseData &source); static void nodeSub(BaseData &target, BaseData &source); public: - static AffineTransform helpMatrix1; - static AffineTransform helpMatrix2; + static cocos2d::AffineTransform helpMatrix1; + static cocos2d::AffineTransform helpMatrix2; - static Point helpPoint1; - static Point helpPoint2; + static cocos2d::Point helpPoint1; + static cocos2d::Point helpPoint2; }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCTRANSFORMHELP_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp b/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp index 8546a88d27..21b20e6f1a 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. #include "CCTweenFunction.h" #include "CCUtilMath.h" -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { float TweenFunction::tweenTo(float from, float change, float time, float duration, CCTweenType tweenType) { @@ -411,4 +411,4 @@ float TweenFunction::bounceEaseInOut(float t, float b, float c, float d) } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h b/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h index d0c76e8cc1..0951bf1eea 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include "CCArmatureDefine.h" #include -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { enum CCTweenType { @@ -131,6 +131,6 @@ public: }; -NS_CC_EXT_ARMATURE_END +} #endif /*__CCTWEENFUNCTION_H__*/ diff --git a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp b/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp index 7197aa1fd4..c696e2a6fe 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp @@ -24,8 +24,10 @@ THE SOFTWARE. #include "CCUtilMath.h" +using namespace cocos2d; -NS_CC_EXT_ARMATURE_BEGIN + +namespace cocostudio { bool isSpriteContainPoint(Sprite *sprite, Point point, Point &outPoint) { @@ -75,4 +77,4 @@ Point circleTo(float t, Point ¢er, float radius, float fromRadian, float rad return p; } -NS_CC_EXT_ARMATURE_END +} diff --git a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h b/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h index 376e02b522..b767cdcc58 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCArmatureDefine.h" #include -NS_CC_EXT_ARMATURE_BEGIN +namespace cocostudio { #define CC_DOUBLE_PI (M_PI*2) @@ -36,20 +36,20 @@ NS_CC_EXT_ARMATURE_BEGIN //! hit test function -bool isSpriteContainPoint(Sprite *sprite, Point point); -bool isSpriteContainPoint(Sprite *sprite, Point point, Point &outPoint); +bool isSpriteContainPoint(cocos2d::Sprite *sprite, cocos2d::Point point); +bool isSpriteContainPoint(cocos2d::Sprite *sprite, cocos2d::Point point, cocos2d::Point &outPoint); #define CC_SPRITE_CONTAIN_POINT(sprite, point) isSpriteContainPoint((sprite), (point)) #define CC_SPRITE_CONTAIN_POINT_WITH_RETURN(sprite, point, outPoint) isSpriteContainPoint((sprite), (point), outPoint) //! motion curve function -Point bezierTo(float t, Point &point1, Point &point2, Point &point3); -Point bezierTo(float t, Point &point1, Point &point2, Point &point3, Point &point4); +cocos2d::Point bezierTo(float t, cocos2d::Point &point1, cocos2d::Point &point2, cocos2d::Point &point3); +cocos2d::Point bezierTo(float t, cocos2d::Point &point1, cocos2d::Point &point2, cocos2d::Point &point3, cocos2d::Point &point4); -Point circleTo(float t, Point ¢er, float radius, float fromRadian, float radianDif); +cocos2d::Point circleTo(float t, cocos2d::Point ¢er, float radius, float fromRadian, float radianDif); -NS_CC_EXT_ARMATURE_END +} #endif /*__CCUTILMATH_H__*/ diff --git a/cocos/editor-support/cocostudio/components/CCComAttribute.cpp b/cocos/editor-support/cocostudio/components/CCComAttribute.cpp index 30505ab486..5f73dfeacc 100644 --- a/cocos/editor-support/cocostudio/components/CCComAttribute.cpp +++ b/cocos/editor-support/cocostudio/components/CCComAttribute.cpp @@ -23,8 +23,9 @@ THE SOFTWARE. ****************************************************************************/ #include "CCComAttribute.h" +using namespace cocos2d; -NS_CC_EXT_BEGIN +namespace cocostudio { ComAttribute::ComAttribute(void) : _attributes(NULL) @@ -44,7 +45,7 @@ bool ComAttribute::init() _attributes = Dictionary::create(); _attributes->retain(); - _jsonDict = new cs::JsonDictionary(); + _jsonDict = new JsonDictionary(); return true; } @@ -184,9 +185,9 @@ Object* ComAttribute::getObject(const char *key) const return _attributes->objectForKey(key); } -cs::JsonDictionary* ComAttribute::getDict() const +JsonDictionary* ComAttribute::getDict() const { return _jsonDict; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/components/CCComAttribute.h b/cocos/editor-support/cocostudio/components/CCComAttribute.h index 78d9828f85..d36ce4ebb2 100644 --- a/cocos/editor-support/cocostudio/components/CCComAttribute.h +++ b/cocos/editor-support/cocostudio/components/CCComAttribute.h @@ -26,11 +26,10 @@ THE SOFTWARE. #define __CC_EXTENTIONS_CCCOMATTRIBUTE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include -#include "../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class ComAttribute : public cocos2d::Component { @@ -61,15 +60,15 @@ public: float getFloat(const char *key) const; bool getBool(const char *key) const; const char* getCString(const char *key) const; - Object* getObject(const char *key) const; + cocos2d::Object* getObject(const char *key) const; - cs::JsonDictionary* getDict() const; + JsonDictionary* getDict() const; private: - Dictionary *_attributes; - cs::JsonDictionary *_jsonDict; + cocos2d::Dictionary *_attributes; + JsonDictionary *_jsonDict; }; -NS_CC_EXT_END +} #endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/cocos/editor-support/cocostudio/components/CCComAudio.cpp b/cocos/editor-support/cocostudio/components/CCComAudio.cpp index 87afa64348..29fcc308f4 100644 --- a/cocos/editor-support/cocostudio/components/CCComAudio.cpp +++ b/cocos/editor-support/cocostudio/components/CCComAudio.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. #include "CCComAudio.h" #include "SimpleAudioEngine.h" -NS_CC_EXT_BEGIN +namespace cocostudio { ComAudio::ComAudio(void) : _filePath("") @@ -223,4 +223,4 @@ bool ComAudio::isLoop() return _loop; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/components/CCComAudio.h b/cocos/editor-support/cocostudio/components/CCComAudio.h index 259227462f..0968a3d76b 100644 --- a/cocos/editor-support/cocostudio/components/CCComAudio.h +++ b/cocos/editor-support/cocostudio/components/CCComAudio.h @@ -26,9 +26,8 @@ THE SOFTWARE. #define __CC_EXTENTIONS_CCCOMAUDIO_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class ComAudio : public cocos2d::Component { @@ -95,6 +94,6 @@ private: bool _loop; }; -NS_CC_EXT_END +} #endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/cocos/editor-support/cocostudio/components/CCComController.cpp b/cocos/editor-support/cocostudio/components/CCComController.cpp index 5213927f4e..8bc321a1de 100644 --- a/cocos/editor-support/cocostudio/components/CCComController.cpp +++ b/cocos/editor-support/cocostudio/components/CCComController.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. #include "CCComController.h" -NS_CC_EXT_BEGIN +namespace cocostudio { ComController::ComController(void) { @@ -76,4 +76,4 @@ ComController* ComController::create(void) return pRet; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/components/CCComController.h b/cocos/editor-support/cocostudio/components/CCComController.h index 7122fb190c..8fcb1c8879 100644 --- a/cocos/editor-support/cocostudio/components/CCComController.h +++ b/cocos/editor-support/cocostudio/components/CCComController.h @@ -28,7 +28,7 @@ THE SOFTWARE. #include "cocos2d.h" #include "CCInputDelegate.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class ComController : public cocos2d::Component, public InputDelegate { @@ -59,6 +59,6 @@ public: static ComController* create(void); }; -NS_CC_EXT_END +} #endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/cocos/editor-support/cocostudio/components/CCComRender.cpp b/cocos/editor-support/cocostudio/components/CCComRender.cpp index 4dbc18c464..bfd19a48ab 100644 --- a/cocos/editor-support/cocostudio/components/CCComRender.cpp +++ b/cocos/editor-support/cocostudio/components/CCComRender.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. #include "CCComRender.h" -NS_CC_EXT_BEGIN +namespace cocostudio { ComRender::ComRender(void) : _render(NULL) @@ -76,4 +76,4 @@ ComRender* ComRender::create(cocos2d::Node *pNode, const char *comName) return pRet; } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/components/CCComRender.h b/cocos/editor-support/cocostudio/components/CCComRender.h index cf98c4c3f8..08c9eff8d9 100644 --- a/cocos/editor-support/cocostudio/components/CCComRender.h +++ b/cocos/editor-support/cocostudio/components/CCComRender.h @@ -26,10 +26,8 @@ THE SOFTWARE. #define __CC_EXTENTIONS_CCCOMNODE_H__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class ComRender : public cocos2d::Component { @@ -61,5 +59,5 @@ private: cocos2d::Node *_render; }; -NS_CC_EXT_END +} #endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp index 84694e0619..65664400c7 100644 --- a/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp @@ -24,7 +24,9 @@ THE SOFTWARE. #include "CCInputDelegate.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace cocostudio { InputDelegate::InputDelegate(void) : _touchEnabled(false) @@ -228,4 +230,4 @@ void InputDelegate::setKeypadEnabled(bool enabled) } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/components/CCInputDelegate.h b/cocos/editor-support/cocostudio/components/CCInputDelegate.h index 94bff421ce..12d9f50041 100644 --- a/cocos/editor-support/cocostudio/components/CCInputDelegate.h +++ b/cocos/editor-support/cocostudio/components/CCInputDelegate.h @@ -26,9 +26,8 @@ THE SOFTWARE. #define __CC_EXTENTIONS_CCINPUTDELEGATE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class InputDelegate { @@ -79,12 +78,12 @@ public: * @js NA * @lua NA */ - virtual void setTouchMode(Touch::DispatchMode mode); + virtual void setTouchMode(cocos2d::Touch::DispatchMode mode); /** * @js NA * @lua NA */ - virtual Touch::DispatchMode getTouchMode() const; + virtual cocos2d::Touch::DispatchMode getTouchMode() const; /** * @js NA * @lua NA @@ -96,44 +95,44 @@ public: */ virtual int getTouchPriority() const; /** @deprecated Please override onAcceleration */ - CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(Acceleration* accelerationValue) final { CC_UNUSED_PARAM(accelerationValue); }; + CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(cocos2d::Acceleration* accelerationValue) final { CC_UNUSED_PARAM(accelerationValue); }; // Deprecated touch callbacks. - CC_DEPRECATED_ATTRIBUTE virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual bool ccTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchMoved(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchEnded(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchCancelled(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(cocos2d::Set *pTouches, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(cocos2d::Set *pTouches, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(cocos2d::Set *pTouches, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(cocos2d::Set *pTouches, cocos2d::Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - virtual void onAcceleration(Acceleration* acc, Event* event) {}; + virtual void onAcceleration(cocos2d::Acceleration* acc, cocos2d::Event* event) {}; - virtual void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) {}; - virtual void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) {}; + virtual void onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event) {}; + virtual void onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event) {}; - virtual bool onTouchBegan(Touch *touch, Event *event); - virtual void onTouchMoved(Touch *touch, Event *event); - virtual void onTouchEnded(Touch *touch, Event *event); - virtual void onTouchCancelled(Touch *touch, Event *event); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); - virtual void onTouchesCancelled(const std::vector& touches, Event *event); + virtual bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event); + virtual void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event); + virtual void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event); + virtual void onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *event); + virtual void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + virtual void onTouchesCancelled(const std::vector& touches, cocos2d::Event *event); protected: bool _touchEnabled; - EventListener* _touchListener; + cocos2d::EventListener* _touchListener; bool _accelerometerEnabled; - EventListener* _accelerometerListener; + cocos2d::EventListener* _accelerometerListener; bool _keypadEnabled; - EventListener* _keyboardListener; + cocos2d::EventListener* _keyboardListener; private: int _touchPriority; - Touch::DispatchMode _touchMode; + cocos2d::Touch::DispatchMode _touchMode; }; -NS_CC_EXT_END +} #endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/cocos/editor-support/cocostudio/json/.DS_Store b/cocos/editor-support/cocostudio/json/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 #include "CSContentJsonDictionary.h" -namespace cs { +namespace cocostudio { JsonDictionary::JsonDictionary() { @@ -43,7 +43,7 @@ namespace cs { void JsonDictionary::initWithDescription(const char *pszDescription) { - CSJson::Reader cReader; + Json::Reader cReader; m_cValue.clear(); if (pszDescription && *pszDescription) { @@ -53,7 +53,7 @@ namespace cs { } - void JsonDictionary::initWithValue(CSJson::Value& value) + void JsonDictionary::initWithValue(Json::Value& value) { m_cValue = value; } @@ -151,8 +151,8 @@ namespace cs { JsonDictionary * pNewDictionary; if (!isKeyValidate(pszKey, m_cValue) || (!m_cValue[pszKey].isArray() && !m_cValue[pszKey].isObject() && - !m_cValue[pszKey].isConvertibleTo(CSJson::arrayValue) && - !m_cValue[pszKey].isConvertibleTo(CSJson::objectValue))) + !m_cValue[pszKey].isConvertibleTo(Json::arrayValue) && + !m_cValue[pszKey].isConvertibleTo(Json::objectValue))) { pNewDictionary = NULL; } @@ -174,10 +174,10 @@ namespace cs { bool JsonDictionary::insertItemToArray(const char *pszArrayKey, int nValue) { - CSJson::Value array; + Json::Value array; if(m_cValue.isMember(pszArrayKey)) { - if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue)) + if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue)) return false; array = m_cValue[pszArrayKey]; @@ -192,10 +192,10 @@ namespace cs { bool JsonDictionary::insertItemToArray(const char *pszArrayKey, double fValue) { - CSJson::Value array; + Json::Value array; if(m_cValue.isMember(pszArrayKey)) { - if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue)) + if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue)) return false; array = m_cValue[pszArrayKey]; @@ -210,10 +210,10 @@ namespace cs { bool JsonDictionary::insertItemToArray(const char *pszArrayKey, const char * pszValue) { - CSJson::Value array; + Json::Value array; if(m_cValue.isMember(pszArrayKey)) { - if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue)) + if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue)) return false; array = m_cValue[pszArrayKey]; @@ -228,10 +228,10 @@ namespace cs { bool JsonDictionary::insertItemToArray(const char *pszArrayKey, JsonDictionary * subDictionary) { - CSJson::Value array; + Json::Value array; if(m_cValue.isMember(pszArrayKey)) { - if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue)) + if (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue)) return false; array = m_cValue[pszArrayKey]; @@ -272,13 +272,13 @@ namespace cs { int nRet = 0; if (!isKeyValidate(pszArrayKey, m_cValue) || (!m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isObject() && - !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue) && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::objectValue))) + !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue) && !m_cValue[pszArrayKey].isConvertibleTo(Json::objectValue))) { nRet = 0; } else { - CSJson::Value arrayValue = m_cValue[pszArrayKey]; + Json::Value arrayValue = m_cValue[pszArrayKey]; nRet = arrayValue.size(); } @@ -289,7 +289,7 @@ namespace cs { int JsonDictionary::getIntValueFromArray(const char *pszArrayKey, int nIndex, int nDefaultValue) { int nRet = nDefaultValue; - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) { if ((*arrayValue)[nIndex].isNumeric()) @@ -303,7 +303,7 @@ namespace cs { double JsonDictionary::getFloatValueFromArray(const char *pszArrayKey, int nIndex, double fDefaultValue) { double fRet = fDefaultValue; - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) { if ((*arrayValue)[nIndex].isNumeric()) @@ -316,7 +316,7 @@ namespace cs { bool JsonDictionary::getBoolValueFromArray(const char *pszArrayKey, int nIndex, bool bDefaultValue) { bool bRet = bDefaultValue; - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) { if ((*arrayValue)[nIndex].isNumeric()) @@ -329,7 +329,7 @@ namespace cs { const char * JsonDictionary::getStringValueFromArray(const char *pszArrayKey, int nIndex) { - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) { if ((*arrayValue)[nIndex].isString()) @@ -342,7 +342,7 @@ namespace cs { JsonDictionary * JsonDictionary::getSubItemFromArray(const char *pszArrayKey, int nIndex) { - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) { if ((*arrayValue)[nIndex].isArray() || (*arrayValue)[nIndex].isObject()) @@ -359,15 +359,15 @@ namespace cs { DicItemType JsonDictionary::getItemTypeFromArray(const char *pszArrayKey, int nIndex) { - CSJson::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); + Json::Value * arrayValue = validateArrayItem(pszArrayKey, nIndex); if (arrayValue) return (DicItemType)((*arrayValue)[nIndex].type()); - return (DicItemType)CSJson::nullValue; + return (DicItemType)Json::nullValue; } - inline bool JsonDictionary::isKeyValidate(const char *pszKey, CSJson::Value& root) + inline bool JsonDictionary::isKeyValidate(const char *pszKey, Json::Value& root) { if (root.isNull() || !root.isMember(pszKey)) return false; @@ -376,9 +376,9 @@ namespace cs { } - inline CSJson::Value * JsonDictionary::validateArrayItem(const char *pszArrayKey, int nIndex) + inline Json::Value * JsonDictionary::validateArrayItem(const char *pszArrayKey, int nIndex) { - if (!isKeyValidate(pszArrayKey, m_cValue) && !m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(CSJson::arrayValue)) + if (!isKeyValidate(pszArrayKey, m_cValue) && !m_cValue[pszArrayKey].isArray() && !m_cValue[pszArrayKey].isConvertibleTo(Json::arrayValue)) return NULL; if (!m_cValue[pszArrayKey].isValidIndex(nIndex)) return NULL; diff --git a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h b/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h index 3908e71545..e3815ae2a6 100644 --- a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h +++ b/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h @@ -28,11 +28,11 @@ #define COCOSTUDIO_CSCONTENTJSONDICTIONARY_H -#include "lib_json/json_lib.h" +#include "json.h" #include #include -namespace cs { +namespace cocostudio { typedef enum _DicItemType { @@ -90,12 +90,12 @@ namespace cs { std::vector getAllMemberNames(); protected: - CSJson::Value m_cValue; + Json::Value m_cValue; private: - void initWithValue(CSJson::Value& value); - inline bool isKeyValidate(const char *pszKey, CSJson::Value& root); - inline CSJson::Value * validateArrayItem(const char *pszArrayKey, int nIndex); + void initWithValue(Json::Value& value); + inline bool isKeyValidate(const char *pszKey, Json::Value& root); + inline Json::Value * validateArrayItem(const char *pszArrayKey, int nIndex); }; } diff --git a/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp b/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp index ca8dfd8594..ab72de178e 100644 --- a/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp +++ b/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp @@ -24,7 +24,7 @@ #include "DictionaryHelper.h" -NS_CC_EXT_BEGIN +namespace cocostudio { static DictionaryHelper* sharedHelper = NULL; @@ -178,7 +178,7 @@ cocos2d::Array* DictionaryHelper::objectToCCArray(cocos2d::Object *obj) return array; } -cs::JsonDictionary* DictionaryHelper::getSubDictionary_json(cs::JsonDictionary* root,const char* key) +JsonDictionary* DictionaryHelper::getSubDictionary_json(JsonDictionary* root,const char* key) { if (!root) { @@ -187,7 +187,7 @@ cs::JsonDictionary* DictionaryHelper::getSubDictionary_json(cs::JsonDictionary* return root->getSubDictionary(key); } -int DictionaryHelper::getIntValue_json(cs::JsonDictionary* root,const char* key) +int DictionaryHelper::getIntValue_json(JsonDictionary* root,const char* key) { if (!root) { @@ -196,7 +196,7 @@ int DictionaryHelper::getIntValue_json(cs::JsonDictionary* root,const char* key) return root->getItemIntValue(key, 0); } -float DictionaryHelper::getFloatValue_json(cs::JsonDictionary* root,const char* key) +float DictionaryHelper::getFloatValue_json(JsonDictionary* root,const char* key) { if (!root) { @@ -205,7 +205,7 @@ float DictionaryHelper::getFloatValue_json(cs::JsonDictionary* root,const char* return root->getItemFloatValue(key, 0.0); } -const char* DictionaryHelper::getStringValue_json(cs::JsonDictionary* root,const char* key) +const char* DictionaryHelper::getStringValue_json(JsonDictionary* root,const char* key) { if (!root) { @@ -214,7 +214,7 @@ const char* DictionaryHelper::getStringValue_json(cs::JsonDictionary* root,const return root->getItemStringValue(key); } -bool DictionaryHelper::getBooleanValue_json(cs::JsonDictionary* root,const char* key) +bool DictionaryHelper::getBooleanValue_json(JsonDictionary* root,const char* key) { if (!root) { @@ -223,7 +223,7 @@ bool DictionaryHelper::getBooleanValue_json(cs::JsonDictionary* root,const char* return root->getItemBoolvalue(key, false); } -int DictionaryHelper::getArrayCount_json(cs::JsonDictionary* root,const char* key) +int DictionaryHelper::getArrayCount_json(JsonDictionary* root,const char* key) { if (!root) { @@ -232,7 +232,7 @@ int DictionaryHelper::getArrayCount_json(cs::JsonDictionary* root,const char* ke return root->getArrayItemCount(key); } -int DictionaryHelper::getIntValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx) +int DictionaryHelper::getIntValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx) { if (!root) { @@ -241,7 +241,7 @@ int DictionaryHelper::getIntValueFromArray_json(cs::JsonDictionary* root,const c return root->getIntValueFromArray(arrayKey, idx, 0); } -float DictionaryHelper::getFloatValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx) +float DictionaryHelper::getFloatValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx) { if (!root) { @@ -250,7 +250,7 @@ float DictionaryHelper::getFloatValueFromArray_json(cs::JsonDictionary* root,con return root->getFloatValueFromArray(arrayKey, idx, 0.0); } -bool DictionaryHelper::getBoolValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx) +bool DictionaryHelper::getBoolValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx) { if (!root) { @@ -259,7 +259,7 @@ bool DictionaryHelper::getBoolValueFromArray_json(cs::JsonDictionary* root,const return root->getBoolValueFromArray(arrayKey, idx, false); } -const char* DictionaryHelper::getStringValueFromArray_json(cs::JsonDictionary *root, const char *arrayKey, int idx) +const char* DictionaryHelper::getStringValueFromArray_json(JsonDictionary *root, const char *arrayKey, int idx) { if (!root) { @@ -268,7 +268,7 @@ const char* DictionaryHelper::getStringValueFromArray_json(cs::JsonDictionary *r return root->getStringValueFromArray(arrayKey, idx); } -cs::JsonDictionary* DictionaryHelper::getDictionaryFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx) +JsonDictionary* DictionaryHelper::getDictionaryFromArray_json(JsonDictionary* root,const char* arrayKey,int idx) { if (!root) { @@ -277,7 +277,7 @@ cs::JsonDictionary* DictionaryHelper::getDictionaryFromArray_json(cs::JsonDictio return root->getSubItemFromArray(arrayKey, idx); } -bool DictionaryHelper::checkObjectExist_json(cs::JsonDictionary *root, const char *key) +bool DictionaryHelper::checkObjectExist_json(JsonDictionary *root, const char *key) { if (!root) { @@ -286,4 +286,4 @@ bool DictionaryHelper::checkObjectExist_json(cs::JsonDictionary *root, const cha return root->isKeyValidate(key); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/json/DictionaryHelper.h b/cocos/editor-support/cocostudio/json/DictionaryHelper.h index a5570ef11a..e3f34e54ed 100644 --- a/cocos/editor-support/cocostudio/json/DictionaryHelper.h +++ b/cocos/editor-support/cocostudio/json/DictionaryHelper.h @@ -26,12 +26,11 @@ #define __DICTIONARYHELPER_H__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "ExtensionMacros.h" +#include "CSContentJsonDictionary.h" #define DICTOOL DictionaryHelper::shareHelper() -NS_CC_EXT_BEGIN +namespace cocostudio { class DictionaryHelper { @@ -53,20 +52,20 @@ public: bool objectToBooleanValue(cocos2d::Object* obj); cocos2d::Array* objectToCCArray(cocos2d::Object* obj); - cs::JsonDictionary* getSubDictionary_json(cs::JsonDictionary* root,const char* key); - int getIntValue_json(cs::JsonDictionary* root,const char* key); - float getFloatValue_json(cs::JsonDictionary* root,const char* key); - const char* getStringValue_json(cs::JsonDictionary* root,const char* key); - bool getBooleanValue_json(cs::JsonDictionary* root,const char* key); - int getArrayCount_json(cs::JsonDictionary* root,const char* key); - int getIntValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx); - float getFloatValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx); - bool getBoolValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx); - const char* getStringValueFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx); - cs::JsonDictionary* getDictionaryFromArray_json(cs::JsonDictionary* root,const char* arrayKey,int idx); - bool checkObjectExist_json(cs::JsonDictionary* root,const char* key); + JsonDictionary* getSubDictionary_json(JsonDictionary* root,const char* key); + int getIntValue_json(JsonDictionary* root,const char* key); + float getFloatValue_json(JsonDictionary* root,const char* key); + const char* getStringValue_json(JsonDictionary* root,const char* key); + bool getBooleanValue_json(JsonDictionary* root,const char* key); + int getArrayCount_json(JsonDictionary* root,const char* key); + int getIntValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx); + float getFloatValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx); + bool getBoolValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx); + const char* getStringValueFromArray_json(JsonDictionary* root,const char* arrayKey,int idx); + JsonDictionary* getDictionaryFromArray_json(JsonDictionary* root,const char* arrayKey,int idx); + bool checkObjectExist_json(JsonDictionary* root,const char* key); }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__DictionaryHelper__) */ diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp index 57778d758a..3ee822c330 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp @@ -22,14 +22,17 @@ THE SOFTWARE. ****************************************************************************/ -#include "../GUI/System/CocosGUI.h" -#include "../Json/DictionaryHelper.h" -#include "../Action/CCActionManagerEx.h" +#include "system/CocosGUI.h" +#include "json/DictionaryHelper.h" +#include "action/CCActionManagerEx.h" #include #include + using namespace gui; + using namespace cocos2d; -NS_CC_EXT_BEGIN + +namespace cocostudio { static CCSGUIReader* sharedReader = NULL; @@ -94,11 +97,11 @@ int CCSGUIReader::getVersionInteger(const char *str) /************************/ } -UIWidget* CCSGUIReader::widgetFromJsonDictionary(cs::JsonDictionary* data) +UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) { UIWidget* widget = NULL; const char* classname = DICTOOL->getStringValue_json(data, "classname"); - cs::JsonDictionary* uiOptions = DICTOOL->getSubDictionary_json(data, "options"); + JsonDictionary* uiOptions = DICTOOL->getSubDictionary_json(data, "options"); if (classname && strcmp(classname, "Button") == 0) { widget = UIButton::create(); @@ -181,7 +184,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(cs::JsonDictionary* data) int childrenCount = DICTOOL->getArrayCount_json(data, "children"); for (int i=0;igetDictionaryFromArray_json(data, "children", i); + JsonDictionary* subData = DICTOOL->getDictionaryFromArray_json(data, "children", i); UIWidget* child = widgetFromJsonDictionary(subData); if (child) { @@ -201,7 +204,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) m_bOlderVersion = false; const char *des = NULL; std::string jsonpath; - cs::JsonDictionary *jsonDict = NULL; + JsonDictionary *jsonDict = NULL; jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); unsigned long size = 0; @@ -212,7 +215,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) return NULL; } std::string strDes(des); - jsonDict = new cs::JsonDictionary(); + jsonDict = new JsonDictionary(); jsonDict->initWithDescription(strDes.c_str()); const char* fileVersion = DICTOOL->getStringValue_json(jsonDict, "version"); @@ -244,7 +247,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) CCUIHELPER->setFileDesignWidth(fileDesignWidth); CCUIHELPER->setFileDesignHeight(fileDesignHeight); } - cs::JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); + JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); /* *********temp********* */ @@ -256,7 +259,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) /* ********************** */ // widget->setFileDesignSize(CCSizeMake(fileDesignWidth, fileDesignHeight)); - cs::JsonDictionary* actions = DICTOOL->getSubDictionary_json(jsonDict, "animation"); + JsonDictionary* actions = DICTOOL->getSubDictionary_json(jsonDict, "animation"); /* *********temp********* */ // ActionManager::shareManager()->releaseActions(); /* ********************** */ @@ -270,7 +273,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) return widget; } -void CCSGUIReader::setPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary *options) +void CCSGUIReader::setPropsForWidgetFromJsonDictionary(UIWidget*widget,JsonDictionary *options) { bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, "ignoreSize"); if (ignoreSizeExsit) @@ -316,7 +319,7 @@ void CCSGUIReader::setPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonD widget->setZOrder(z); } -void CCSGUIReader::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { bool op = DICTOOL->checkObjectExist_json(options, "opacity"); if (op) @@ -341,7 +344,7 @@ void CCSGUIReader::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, cs widget->setFlipY(flipY); } -void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -407,7 +410,7 @@ void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonD bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); button->setScale9Enabled(scale9Enable); - cs::JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "normalData"); + JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "normalData"); int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); switch (normalType) { @@ -429,7 +432,7 @@ void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonD break; } CC_SAFE_DELETE(normalDic); - cs::JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "pressedData"); + JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "pressedData"); int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); switch (pressedType) { @@ -451,7 +454,7 @@ void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonD break; } CC_SAFE_DELETE(pressedDic); - cs::JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "disabledData"); + JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "disabledData"); int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); switch (disabledType) { @@ -494,7 +497,7 @@ void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonD } } -void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -536,7 +539,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso setPropsForWidgetFromJsonDictionary(widget, options); UICheckBox* checkBox = (UICheckBox*)widget; - cs::JsonDictionary* backGroundDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxData"); + JsonDictionary* backGroundDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxData"); int backGroundType = DICTOOL->getIntValue_json(backGroundDic, "resourceType"); switch (backGroundType) { @@ -559,7 +562,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso } CC_SAFE_DELETE(backGroundDic); - cs::JsonDictionary* backGroundSelectedDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxSelectedData"); + JsonDictionary* backGroundSelectedDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxSelectedData"); int backGroundSelectedType = DICTOOL->getIntValue_json(backGroundSelectedDic, "resourceType"); switch (backGroundSelectedType) { @@ -582,7 +585,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso } CC_SAFE_DELETE(backGroundSelectedDic); - cs::JsonDictionary* frontCrossDic = DICTOOL->getSubDictionary_json(options, "frontCrossData"); + JsonDictionary* frontCrossDic = DICTOOL->getSubDictionary_json(options, "frontCrossData"); int frontCrossType = DICTOOL->getIntValue_json(frontCrossDic, "resourceType"); switch (frontCrossType) { @@ -605,7 +608,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso } CC_SAFE_DELETE(frontCrossDic); - cs::JsonDictionary* backGroundDisabledDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxDisabledData"); + JsonDictionary* backGroundDisabledDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxDisabledData"); int backGroundDisabledType = DICTOOL->getIntValue_json(backGroundDisabledDic, "resourceType"); switch (backGroundDisabledType) { @@ -628,7 +631,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso } CC_SAFE_DELETE(backGroundDisabledDic); - cs::JsonDictionary* frontCrossDisabledDic = DICTOOL->getSubDictionary_json(options, "frontCrossDisabledData"); + JsonDictionary* frontCrossDisabledDic = DICTOOL->getSubDictionary_json(options, "frontCrossDisabledData"); int frontCrossDisabledType = DICTOOL->getIntValue_json(frontCrossDisabledDic, "resourceType"); switch (frontCrossDisabledType) { @@ -655,7 +658,7 @@ void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::Jso } } -void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -725,7 +728,7 @@ void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::Js UIImageView* imageView = (UIImageView*)widget; - cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); + JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); switch (imageFileNameType) { @@ -784,7 +787,7 @@ void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::Js } } -void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForWidgetFromJsonDictionary(widget, options); UILabel* label = (UILabel*)widget; @@ -813,7 +816,7 @@ void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,cs::JsonDi setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -847,7 +850,7 @@ void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::J if (sv && cmf && iw && ih && scm) { - cs::JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "charMapFileData"); + JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "charMapFileData"); int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); switch (cmfType) { @@ -871,7 +874,7 @@ void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::J } } -void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForWidgetFromJsonDictionary(widget, options); Layout* containerWidget = (Layout*)widget; @@ -884,7 +887,7 @@ void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -987,7 +990,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDi // panel->setSize(CCSizeMake(w, h)); - cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "backGroundImageData"); + JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "backGroundImageData"); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); switch (imageFileNameType) { @@ -1022,7 +1025,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDi } } -void CCSGUIReader::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForPanelFromJsonDictionary(widget, options); UIScrollView* scrollView = (UIScrollView*)widget; @@ -1036,7 +1039,7 @@ void CCSGUIReader::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,cs::J setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { if (m_bOlderVersion) { @@ -1128,7 +1131,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD if (barTextureScale9Enable) { - cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); + JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); switch (imageFileType) { @@ -1155,7 +1158,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD } else { - cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); + JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); switch (imageFileType) { @@ -1199,7 +1202,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD // slider->setSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); // } - cs::JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "ballNormalData"); + JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "ballNormalData"); int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); switch (normalType) { @@ -1222,7 +1225,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD } CC_SAFE_DELETE(normalDic); - cs::JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "ballPressedData"); + JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "ballPressedData"); int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); switch (pressedType) { @@ -1245,7 +1248,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD } CC_SAFE_DELETE(pressedDic); - cs::JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "ballDisabledData"); + JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "ballDisabledData"); int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); switch (disabledType) { @@ -1270,7 +1273,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD slider->setPercent(DICTOOL->getIntValue_json(options, "percent")); - cs::JsonDictionary* progressBarDic = DICTOOL->getSubDictionary_json(options, "progressBarData"); + JsonDictionary* progressBarDic = DICTOOL->getSubDictionary_json(options, "progressBarData"); int progressBarType = DICTOOL->getIntValue_json(progressBarDic, "resourceType"); switch (progressBarType) { @@ -1295,7 +1298,7 @@ void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonD } } -void CCSGUIReader::setPropsForTextAreaFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForTextAreaFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForWidgetFromJsonDictionary(widget, options); UILabel* textArea = (UILabel*)widget; @@ -1330,7 +1333,7 @@ void CCSGUIReader::setPropsForTextAreaFromJsonDictionary(UIWidget*widget,cs::Jso setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForTextButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForTextButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForButtonFromJsonDictionary(widget, options); @@ -1357,7 +1360,7 @@ void CCSGUIReader::setPropsForTextButtonFromJsonDictionary(UIWidget*widget,cs::J setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForWidgetFromJsonDictionary(widget, options); UITextField* textField = (UITextField*)widget; @@ -1407,7 +1410,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,cs::Js setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { if (m_bOlderVersion) { @@ -1434,7 +1437,7 @@ void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, cs: setPropsForWidgetFromJsonDictionary(widget, options); UILoadingBar* loadingBar = (UILoadingBar*)widget; - cs::JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "textureData"); + JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "textureData"); int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); switch (imageFileNameType) { @@ -1486,18 +1489,18 @@ void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, cs: } } -void CCSGUIReader::setPropsForListViewFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setPropsForListViewFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForScrollViewFromJsonDictionary(widget, options); } -void CCSGUIReader::setPropsForPageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options) +void CCSGUIReader::setPropsForPageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { setPropsForPanelFromJsonDictionary(widget, options); setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { if (m_bOlderVersion) { @@ -1523,7 +1526,7 @@ void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, cs UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; - cs::JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); + JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); switch (cmfType) { @@ -1550,7 +1553,7 @@ void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, cs } } -void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, cs::JsonDictionary *options) +void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForPanelFromJsonDictionary(widget, options); @@ -1566,4 +1569,4 @@ void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, cs:: setColorPropsForWidgetFromJsonDictionary(widget, options); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h b/cocos/editor-support/cocostudio/reader/CCSGUIReader.h index 75aa04981e..43c0c9693c 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/reader/CCSGUIReader.h @@ -25,13 +25,13 @@ #ifndef __CCSGUIREADER_H__ #define __CCSGUIREADER_H__ -#include "../GUI/BaseClasses/UIWidget.h" -#include "../Json/CSContentJsonDictionary.h" +#include "base-classes/UIWidget.h" +#include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { #define kCCSVersion 1.0 -class CCSGUIReader : Object +class CCSGUIReader : cocos2d::Object { public: CCSGUIReader(); @@ -39,38 +39,38 @@ public: static CCSGUIReader* shareReader(); static void purgeCCSGUIReader(); - UIWidget* widgetFromJsonFile(const char* fileName); - UIWidget* widgetFromJsonDictionary(cs::JsonDictionary* data); + gui::UIWidget* widgetFromJsonFile(const char* fileName); + gui::UIWidget* widgetFromJsonDictionary(JsonDictionary* data); int getVersionInteger(const char* str); - void setPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setColorPropsForWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForImageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForLabelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForContainerWidgetFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForScrollViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForSliderFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForTextAreaFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForTextButtonFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForTextFieldFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForLoadingBarFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForImageButtonFromJsonDictionary(UIWidget* widget, cs::JsonDictionary* options); - void setPropsForListViewFromJsonDictionary(UIWidget* widget, cs::JsonDictionary* options); - void setPropsForPageViewFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForLabelBMFontFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); - void setPropsForDragPanelFromJsonDictionary(UIWidget*widget,cs::JsonDictionary* options); + void setPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setColorPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForCheckBoxFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForImageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForLabelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForLabelAtlasFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForContainerWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForScrollViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForSliderFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForTextAreaFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForTextButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForTextFieldFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForLoadingBarFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForImageButtonFromJsonDictionary(gui::UIWidget* widget, JsonDictionary* options); + void setPropsForListViewFromJsonDictionary(gui::UIWidget* widget, JsonDictionary* options); + void setPropsForPageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void setPropsForDragPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); protected: std::string m_strFilePath; bool m_bOlderVersion; }; -NS_CC_EXT_END +} #endif /* defined(__CCSGUIReader__) */ diff --git a/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp index a83ef909ac..a32572d791 100644 --- a/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp @@ -23,9 +23,13 @@ ****************************************************************************/ #include "CCSSceneReader.h" -#include "cocos-ext.h" +#include "CocoStudio.h" +#include "system/CocosGUI.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; +using namespace gui; + +namespace cocostudio { SceneReader* SceneReader::s_sharedReader = NULL; @@ -51,7 +55,7 @@ NS_CC_EXT_BEGIN CC_BREAK_IF(pszFileName == NULL); pData = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pszFileName, "r", &size)); CC_BREAK_IF(pData == NULL || strcmp(pData, "") == 0); - cs::JsonDictionary *jsonDict = new cs::JsonDictionary(); + JsonDictionary *jsonDict = new JsonDictionary(); jsonDict->initWithDescription(pData); pNode = createObject(jsonDict,NULL); CC_SAFE_DELETE(jsonDict); @@ -60,7 +64,7 @@ NS_CC_EXT_BEGIN return pNode; } - Node* SceneReader::createObject(cs::JsonDictionary * inputFiles, Node* parenet) + Node* SceneReader::createObject(JsonDictionary * inputFiles, Node* parenet) { const char *className = inputFiles->getItemStringValue("classname"); if(strcmp(className, "CCNode") == 0) @@ -81,7 +85,7 @@ NS_CC_EXT_BEGIN int count = inputFiles->getArrayItemCount("components"); for (int i = 0; i < count; i++) { - cs::JsonDictionary * subDict = inputFiles->getSubItemFromArray("components", i); + JsonDictionary * subDict = inputFiles->getSubItemFromArray("components", i); if (!subDict) { CC_SAFE_DELETE(subDict); @@ -90,7 +94,7 @@ NS_CC_EXT_BEGIN const char *comName = subDict->getItemStringValue("classname"); const char *pComName = subDict->getItemStringValue("name"); - cs::JsonDictionary *fileData = subDict->getSubDictionary("fileData"); + JsonDictionary *fileData = subDict->getSubDictionary("fileData"); std::string pPath; std::string pPlistFile; int nResType = 0; @@ -212,7 +216,7 @@ NS_CC_EXT_BEGIN } unsigned long size = 0; const char *des = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pPath.c_str(),"r" , &size)); - cs::JsonDictionary *jsonDict = new cs::JsonDictionary(); + JsonDictionary *jsonDict = new JsonDictionary(); jsonDict->initWithDescription(des); if(NULL == des || strcmp(des, "") == 0) { @@ -220,7 +224,7 @@ NS_CC_EXT_BEGIN } int childrenCount = DICTOOL->getArrayCount_json(jsonDict, "armature_data"); - cs::JsonDictionary* subData = DICTOOL->getDictionaryFromArray_json(jsonDict, "armature_data", 0); + JsonDictionary* subData = DICTOOL->getDictionaryFromArray_json(jsonDict, "armature_data", 0); const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); @@ -238,11 +242,11 @@ NS_CC_EXT_BEGIN textupath += file_path; textupath.append(textureFileName); - cocos2d::extension::armature::ArmatureDataManager::getInstance()->addArmatureFileInfo(textupath.c_str(), plistpath.c_str(), pPath.c_str()); + ArmatureDataManager::getInstance()->addArmatureFileInfo(textupath.c_str(), plistpath.c_str(), pPath.c_str()); } - cocos2d::extension::armature::Armature *pAr = cocos2d::extension::armature::Armature::create(name); + Armature *pAr = Armature::create(name); ComRender *pRender = ComRender::create(pAr, "CCArmature"); if (pComName != NULL) { @@ -315,9 +319,9 @@ NS_CC_EXT_BEGIN } else if(comName != NULL && strcmp(comName, "GUIComponent") == 0) { - cocos2d::extension::UILayer *pLayer = cocos2d::extension::UILayer::create(); + gui::UILayer *pLayer = gui::UILayer::create(); pLayer->scheduleUpdate(); - UIWidget* widget=cocos2d::extension::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); + UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); pLayer->addWidget(widget); ComRender *pRender = ComRender::create(pLayer, "GUIComponent"); if (pComName != NULL) @@ -332,7 +336,7 @@ NS_CC_EXT_BEGIN for (int i = 0; i < inputFiles->getArrayItemCount("gameobjects"); i++) { - cs::JsonDictionary * subDict = inputFiles->getSubItemFromArray("gameobjects", i); + JsonDictionary * subDict = inputFiles->getSubItemFromArray("gameobjects", i); if (!subDict) { break; @@ -348,7 +352,7 @@ NS_CC_EXT_BEGIN } - void SceneReader::setPropertyFromJsonDict(cocos2d::Node *node, cs::JsonDictionary* dict) + void SceneReader::setPropertyFromJsonDict(cocos2d::Node *node, JsonDictionary* dict) { int x = dict->getItemIntValue("x", 0); int y = dict->getItemIntValue("y", 0); @@ -384,7 +388,7 @@ NS_CC_EXT_BEGIN void SceneReader::purgeSceneReader() { CC_SAFE_DELETE(s_sharedReader); - cocos2d::extension::DictionaryHelper::shareHelper()->purgeDictionaryHelper(); + DictionaryHelper::shareHelper()->purgeDictionaryHelper(); } -NS_CC_EXT_END +} diff --git a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h b/cocos/editor-support/cocostudio/reader/CCSSceneReader.h index c0c88ae660..ca95088c59 100644 --- a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/reader/CCSSceneReader.h @@ -26,10 +26,9 @@ #define __CCSSCENEREADER_H__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "ExtensionMacros.h" + #include "json/CSContentJsonDictionary.h" -NS_CC_EXT_BEGIN +namespace cocostudio { class SceneReader { @@ -51,14 +50,14 @@ public: cocos2d::Node* createNodeWithSceneFile(const char *pszFileName); private: - cocos2d::Node* createObject(cs::JsonDictionary * inputFiles, cocos2d::Node* parent); - void setPropertyFromJsonDict(cocos2d::Node *node, cs::JsonDictionary* dict); + cocos2d::Node* createObject(JsonDictionary * inputFiles, cocos2d::Node* parent); + void setPropertyFromJsonDict(cocos2d::Node *node, JsonDictionary* dict); private: static SceneReader* s_sharedReader; }; -NS_CC_EXT_END +} #endif diff --git a/cocos/editor-support/spine/Android.mk b/cocos/editor-support/spine/Android.mk new file mode 100644 index 0000000000..35ad40845d --- /dev/null +++ b/cocos/editor-support/spine/Android.mk @@ -0,0 +1,42 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := spine_static + +LOCAL_MODULE_FILENAME := libspine + +LOCAL_SRC_FILES := Animation.cpp \ +AnimationState.cpp \ +AnimationStateData.cpp \ +Atlas.cpp \ +AtlasAttachmentLoader.cpp \ +Attachment.cpp \ +AttachmentLoader.cpp \ +Bone.cpp \ +BoneData.cpp \ +CCSkeleton.cpp \ +CCSkeletonAnimation.cpp \ +Json.cpp \ +RegionAttachment.cpp \ +Skeleton.cpp \ +SkeletonData.cpp \ +SkeletonJson.cpp \ +Skin.cpp \ +Slot.cpp \ +SlotData.cpp \ +extension.cpp \ +spine-cocos2dx.cpp + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ +$(LOCAL_PATH)/.. + +LOCAL_CFLAGS += -Wno-psabi +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,2d) diff --git a/cocos/editor-support/spine/Animation.cpp b/cocos/editor-support/spine/Animation.cpp index f60aae6f2c..655e80be06 100644 --- a/cocos/editor-support/spine/Animation.cpp +++ b/cocos/editor-support/spine/Animation.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { Animation* Animation_create (const char* name, int timelineCount) { Animation* self = NEW(Animation); @@ -496,4 +496,4 @@ void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, floa self->attachmentNames[frameIndex] = 0; } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/Animation.h b/cocos/editor-support/spine/Animation.h index b7d922ca95..992e414da9 100644 --- a/cocos/editor-support/spine/Animation.h +++ b/cocos/editor-support/spine/Animation.h @@ -26,7 +26,7 @@ #ifndef SPINE_ANIMATION_H_ #define SPINE_ANIMATION_H_ -namespace cocos2d { namespace extension { +namespace spine { typedef struct Timeline Timeline; struct Skeleton; @@ -127,6 +127,6 @@ AttachmentTimeline* AttachmentTimeline_create (int frameCount); /* @param attachmentName May be 0. */ void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, float time, const char* attachmentName); -}} // namespace cocos2d { namespace extension { +} #endif /* SPINE_ANIMATION_H_ */ diff --git a/cocos/editor-support/spine/AnimationState.cpp b/cocos/editor-support/spine/AnimationState.cpp index be2bde367d..f118528523 100644 --- a/cocos/editor-support/spine/AnimationState.cpp +++ b/cocos/editor-support/spine/AnimationState.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct _Entry _Entry; struct _Entry { @@ -175,4 +175,4 @@ int/*bool*/AnimationState_isComplete (AnimationState* self) { return !self->animation || self->time >= self->animation->duration; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/AnimationState.h b/cocos/editor-support/spine/AnimationState.h index 5362281660..5d6047b7c7 100644 --- a/cocos/editor-support/spine/AnimationState.h +++ b/cocos/editor-support/spine/AnimationState.h @@ -28,7 +28,7 @@ #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { AnimationStateData* const data; @@ -61,6 +61,6 @@ void AnimationState_clearAnimation (AnimationState* self); int/*bool*/AnimationState_isComplete (AnimationState* self); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ANIMATIONSTATE_H_ */ diff --git a/cocos/editor-support/spine/AnimationStateData.cpp b/cocos/editor-support/spine/AnimationStateData.cpp index b467dbfb7f..5f282a1d75 100644 --- a/cocos/editor-support/spine/AnimationStateData.cpp +++ b/cocos/editor-support/spine/AnimationStateData.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct _ToEntry _ToEntry; struct _ToEntry { @@ -147,4 +147,4 @@ float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Anim return 0; } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/AnimationStateData.h b/cocos/editor-support/spine/AnimationStateData.h index ea45653ed7..8b4284c8dc 100644 --- a/cocos/editor-support/spine/AnimationStateData.h +++ b/cocos/editor-support/spine/AnimationStateData.h @@ -29,7 +29,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { SkeletonData* const skeletonData; @@ -44,6 +44,6 @@ void AnimationStateData_setMix (AnimationStateData* self, Animation* from, Anima /* Returns 0 if there is no mixing between the animations. */ float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Animation* to); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ANIMATIONSTATEDATA_H_ */ diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index 8b9861463f..1a2293bacb 100644 --- a/cocos/editor-support/spine/Atlas.cpp +++ b/cocos/editor-support/spine/Atlas.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { AtlasPage* AtlasPage_create (const char* name) { AtlasPage* self = NEW(AtlasPage); @@ -336,4 +336,4 @@ AtlasRegion* Atlas_findRegion (const Atlas* self, const char* name) { return 0; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Atlas.h b/cocos/editor-support/spine/Atlas.h index ea5ca9b781..066bf7af8b 100644 --- a/cocos/editor-support/spine/Atlas.h +++ b/cocos/editor-support/spine/Atlas.h @@ -26,7 +26,7 @@ #ifndef SPINE_ATLAS_H_ #define SPINE_ATLAS_H_ -namespace cocos2d { namespace extension { +namespace spine { typedef enum { ATLAS_ALPHA, ATLAS_INTENSITY, ATLAS_LUMINANCE_ALPHA, ATLAS_RGB565, ATLAS_RGBA4444, ATLAS_RGB888, ATLAS_RGBA8888 @@ -101,6 +101,6 @@ void Atlas_dispose (Atlas* atlas); /* Returns 0 if the region was not found. */ AtlasRegion* Atlas_findRegion (const Atlas* self, const char* name); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ATLAS_H_ */ diff --git a/cocos/editor-support/spine/AtlasAttachmentLoader.cpp b/cocos/editor-support/spine/AtlasAttachmentLoader.cpp index ce064df6eb..4a70175912 100644 --- a/cocos/editor-support/spine/AtlasAttachmentLoader.cpp +++ b/cocos/editor-support/spine/AtlasAttachmentLoader.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { Attachment* _AtlasAttachmentLoader_newAttachment (AttachmentLoader* loader, Skin* skin, AttachmentType type, const char* name) { AtlasAttachmentLoader* self = SUB_CAST(AtlasAttachmentLoader, loader); @@ -62,4 +62,4 @@ AtlasAttachmentLoader* AtlasAttachmentLoader_create (Atlas* atlas) { return self; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/AtlasAttachmentLoader.h b/cocos/editor-support/spine/AtlasAttachmentLoader.h index 20e90464e2..7dcd266400 100644 --- a/cocos/editor-support/spine/AtlasAttachmentLoader.h +++ b/cocos/editor-support/spine/AtlasAttachmentLoader.h @@ -29,7 +29,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { AttachmentLoader super; @@ -38,6 +38,6 @@ typedef struct { AtlasAttachmentLoader* AtlasAttachmentLoader_create (Atlas* atlas); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ATLASATTACHMENTLOADER_H_ */ diff --git a/cocos/editor-support/spine/Attachment.cpp b/cocos/editor-support/spine/Attachment.cpp index 50e158b676..3844e4eefb 100644 --- a/cocos/editor-support/spine/Attachment.cpp +++ b/cocos/editor-support/spine/Attachment.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct _AttachmentVtable { void (*dispose) (Attachment* self); @@ -53,4 +53,4 @@ void Attachment_dispose (Attachment* self) { FREE(self); } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/Attachment.h b/cocos/editor-support/spine/Attachment.h index 7be7cf0dc5..868de80cb1 100644 --- a/cocos/editor-support/spine/Attachment.h +++ b/cocos/editor-support/spine/Attachment.h @@ -26,7 +26,7 @@ #ifndef SPINE_ATTACHMENT_H_ #define SPINE_ATTACHMENT_H_ -namespace cocos2d { namespace extension { +namespace spine { struct Slot; @@ -44,6 +44,6 @@ struct Attachment { void Attachment_dispose (Attachment* self); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ATTACHMENT_H_ */ diff --git a/cocos/editor-support/spine/AttachmentLoader.cpp b/cocos/editor-support/spine/AttachmentLoader.cpp index 8e712a9c5e..9ebac1eb8c 100644 --- a/cocos/editor-support/spine/AttachmentLoader.cpp +++ b/cocos/editor-support/spine/AttachmentLoader.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct _AttachmentLoaderVtable { Attachment* (*newAttachment) (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name); @@ -74,4 +74,4 @@ void _AttachmentLoader_setUnknownTypeError (AttachmentLoader* self, AttachmentTy _AttachmentLoader_setError(self, "Unknown attachment type: ", buffer); } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/AttachmentLoader.h b/cocos/editor-support/spine/AttachmentLoader.h index 5fd81f5eb8..09934f97d1 100644 --- a/cocos/editor-support/spine/AttachmentLoader.h +++ b/cocos/editor-support/spine/AttachmentLoader.h @@ -29,7 +29,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct AttachmentLoader AttachmentLoader; struct AttachmentLoader { @@ -47,6 +47,6 @@ void AttachmentLoader_dispose (AttachmentLoader* 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); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_ATTACHMENTLOADER_H_ */ diff --git a/cocos/editor-support/spine/Bone.cpp b/cocos/editor-support/spine/Bone.cpp index 17030f6405..9fda530792 100644 --- a/cocos/editor-support/spine/Bone.cpp +++ b/cocos/editor-support/spine/Bone.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { static int yDown; @@ -96,4 +96,4 @@ void Bone_updateWorldTransform (Bone* self, int flipX, int flipY) { } } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Bone.h b/cocos/editor-support/spine/Bone.h index 3f4688a728..b03b54d197 100644 --- a/cocos/editor-support/spine/Bone.h +++ b/cocos/editor-support/spine/Bone.h @@ -28,7 +28,7 @@ #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct Bone Bone; struct Bone { @@ -54,6 +54,6 @@ void Bone_setToSetupPose (Bone* self); void Bone_updateWorldTransform (Bone* self, int/*bool*/flipX, int/*bool*/flipY); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_BONE_H_ */ diff --git a/cocos/editor-support/spine/BoneData.cpp b/cocos/editor-support/spine/BoneData.cpp index 09c356bb3d..5197d7f114 100644 --- a/cocos/editor-support/spine/BoneData.cpp +++ b/cocos/editor-support/spine/BoneData.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { BoneData* BoneData_create (const char* name, BoneData* parent) { BoneData* self = NEW(BoneData); @@ -42,4 +42,4 @@ void BoneData_dispose (BoneData* self) { FREE(self); } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/BoneData.h b/cocos/editor-support/spine/BoneData.h index 54126a700d..f2d63430fb 100644 --- a/cocos/editor-support/spine/BoneData.h +++ b/cocos/editor-support/spine/BoneData.h @@ -26,7 +26,7 @@ #ifndef SPINE_BONEDATA_H_ #define SPINE_BONEDATA_H_ -namespace cocos2d { namespace extension { +namespace spine { typedef struct BoneData BoneData; struct BoneData { @@ -41,6 +41,6 @@ struct BoneData { BoneData* BoneData_create (const char* name, BoneData* parent); void BoneData_dispose (BoneData* self); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_BONEDATA_H_ */ diff --git a/cocos/editor-support/spine/CCSkeleton.cpp b/cocos/editor-support/spine/CCSkeleton.cpp index 9b961fb4f5..760dd6702c 100644 --- a/cocos/editor-support/spine/CCSkeleton.cpp +++ b/cocos/editor-support/spine/CCSkeleton.cpp @@ -30,7 +30,7 @@ USING_NS_CC; using std::min; using std::max; -namespace cocos2d { namespace extension { +namespace spine { CCSkeleton* CCSkeleton::createWithData (SkeletonData* skeletonData, bool ownsSkeletonData) { CCSkeleton* node = new CCSkeleton(skeletonData, ownsSkeletonData); @@ -287,4 +287,4 @@ bool CCSkeleton::isOpacityModifyRGB () const { return premultipliedAlpha; } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/CCSkeleton.h b/cocos/editor-support/spine/CCSkeleton.h index 70e76a8e02..ede5f9ae21 100644 --- a/cocos/editor-support/spine/CCSkeleton.h +++ b/cocos/editor-support/spine/CCSkeleton.h @@ -27,9 +27,10 @@ #define SPINE_CCSKELETON_H_ #include + #include "RegionAttachment.h" #include "cocos2d.h" -namespace cocos2d { namespace extension { +namespace spine { /** Draws a skeleton. @@ -107,6 +108,6 @@ private: void initialize (); }; -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_CCSKELETON_H_ */ diff --git a/cocos/editor-support/spine/CCSkeletonAnimation.cpp b/cocos/editor-support/spine/CCSkeletonAnimation.cpp index ad789fd5fc..8cf2a75e9a 100644 --- a/cocos/editor-support/spine/CCSkeletonAnimation.cpp +++ b/cocos/editor-support/spine/CCSkeletonAnimation.cpp @@ -32,7 +32,7 @@ using std::min; using std::max; using std::vector; -namespace cocos2d { namespace extension { +namespace spine { CCSkeletonAnimation* CCSkeletonAnimation::createWithData (SkeletonData* skeletonData) { CCSkeletonAnimation* node = new CCSkeletonAnimation(skeletonData); @@ -139,4 +139,4 @@ void CCSkeletonAnimation::clearAnimation (int stateIndex) { AnimationState_clearAnimation(states[stateIndex]); } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/CCSkeletonAnimation.h b/cocos/editor-support/spine/CCSkeletonAnimation.h index 82b9feece2..4fdbd6f8a7 100644 --- a/cocos/editor-support/spine/CCSkeletonAnimation.h +++ b/cocos/editor-support/spine/CCSkeletonAnimation.h @@ -30,7 +30,7 @@ #include #include "cocos2d.h" -namespace cocos2d { namespace extension { +namespace spine { /** Draws an animated skeleton, providing a simple API for applying one or more animations and queuing animations to be played later. @@ -79,6 +79,6 @@ private: void initialize (); }; -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_CCSKELETONANIMATION_H_ */ diff --git a/cocos/editor-support/spine/Json.cpp b/cocos/editor-support/spine/Json.cpp index 656b8e52bb..d94c74ffe9 100644 --- a/cocos/editor-support/spine/Json.cpp +++ b/cocos/editor-support/spine/Json.cpp @@ -29,7 +29,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { static const char* ep; @@ -372,4 +372,4 @@ int Json_getInt (Json* value, const char* name, int defaultValue) { return value ? (int)value->valuefloat : defaultValue; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Json.h b/cocos/editor-support/spine/Json.h index 35cccd6655..fef6afb552 100644 --- a/cocos/editor-support/spine/Json.h +++ b/cocos/editor-support/spine/Json.h @@ -25,7 +25,7 @@ #ifndef SPINE_JSON_H_ #define SPINE_JSON_H_ -namespace cocos2d { namespace extension { +namespace spine { /* Json Types: */ #define Json_False 0 @@ -72,6 +72,6 @@ int Json_getInt (Json* json, const char* name, int defaultValue); /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when Json_create() returns 0. 0 when Json_create() succeeds. */ const char* Json_getError (void); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_JSON_H_ */ diff --git a/cocos/editor-support/spine/RegionAttachment.cpp b/cocos/editor-support/spine/RegionAttachment.cpp index 585df7af8f..c4c07d9832 100644 --- a/cocos/editor-support/spine/RegionAttachment.cpp +++ b/cocos/editor-support/spine/RegionAttachment.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { RegionAttachment* RegionAttachment_create (const char* name) { RegionAttachment* self = NEW(RegionAttachment); @@ -106,4 +106,4 @@ void RegionAttachment_computeVertices (RegionAttachment* self, float x, float y, vertices[VERTEX_Y4] = offset[VERTEX_X4] * bone->m10 + offset[VERTEX_Y4] * bone->m11 + y; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/RegionAttachment.h b/cocos/editor-support/spine/RegionAttachment.h index 8374c812b2..03dd5c7c7f 100644 --- a/cocos/editor-support/spine/RegionAttachment.h +++ b/cocos/editor-support/spine/RegionAttachment.h @@ -30,7 +30,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef enum { VERTEX_X1 = 0, VERTEX_Y1, VERTEX_X2, VERTEX_Y2, VERTEX_X3, VERTEX_Y3, VERTEX_X4, VERTEX_Y4 @@ -55,6 +55,6 @@ void RegionAttachment_setUVs (RegionAttachment* self, float u, float v, float u2 void RegionAttachment_updateOffset (RegionAttachment* self); void RegionAttachment_computeVertices (RegionAttachment* self, float x, float y, Bone* bone, float* vertices); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_REGIONATTACHMENT_H_ */ diff --git a/cocos/editor-support/spine/Skeleton.cpp b/cocos/editor-support/spine/Skeleton.cpp index 033e46bf02..145487f710 100644 --- a/cocos/editor-support/spine/Skeleton.cpp +++ b/cocos/editor-support/spine/Skeleton.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { Skeleton* Skeleton_create (SkeletonData* data) { int i, ii; @@ -199,4 +199,4 @@ void Skeleton_update (Skeleton* self, float deltaTime) { self->time += deltaTime; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Skeleton.h b/cocos/editor-support/spine/Skeleton.h index 54fa5aa0d4..61b1814c99 100644 --- a/cocos/editor-support/spine/Skeleton.h +++ b/cocos/editor-support/spine/Skeleton.h @@ -30,7 +30,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct Skeleton Skeleton; struct Skeleton { @@ -87,6 +87,6 @@ int Skeleton_setAttachment (Skeleton* self, const char* slotName, const char* at void Skeleton_update (Skeleton* self, float deltaTime); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SKELETON_H_*/ diff --git a/cocos/editor-support/spine/SkeletonData.cpp b/cocos/editor-support/spine/SkeletonData.cpp index 9f781dc4f2..c891494c72 100644 --- a/cocos/editor-support/spine/SkeletonData.cpp +++ b/cocos/editor-support/spine/SkeletonData.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { SkeletonData* SkeletonData_create () { return NEW(SkeletonData); @@ -96,4 +96,4 @@ Animation* SkeletonData_findAnimation (const SkeletonData* self, const char* ani return 0; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/SkeletonData.h b/cocos/editor-support/spine/SkeletonData.h index b05bc4574a..1b97de972b 100644 --- a/cocos/editor-support/spine/SkeletonData.h +++ b/cocos/editor-support/spine/SkeletonData.h @@ -31,7 +31,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { int boneCount; @@ -61,6 +61,6 @@ Skin* SkeletonData_findSkin (const SkeletonData* self, const char* skinName); Animation* SkeletonData_findAnimation (const SkeletonData* self, const char* animationName); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SKELETONDATA_H_ */ diff --git a/cocos/editor-support/spine/SkeletonJson.cpp b/cocos/editor-support/spine/SkeletonJson.cpp index 35a0daa787..98e4be4334 100644 --- a/cocos/editor-support/spine/SkeletonJson.cpp +++ b/cocos/editor-support/spine/SkeletonJson.cpp @@ -32,7 +32,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { SkeletonJson super; @@ -414,4 +414,4 @@ SkeletonData* SkeletonJson_readSkeletonData (SkeletonJson* self, const char* jso return skeletonData; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/SkeletonJson.h b/cocos/editor-support/spine/SkeletonJson.h index 1fd9b2875a..235a09b1af 100644 --- a/cocos/editor-support/spine/SkeletonJson.h +++ b/cocos/editor-support/spine/SkeletonJson.h @@ -32,7 +32,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { float scale; @@ -47,6 +47,6 @@ void SkeletonJson_dispose (SkeletonJson* self); SkeletonData* SkeletonJson_readSkeletonData (SkeletonJson* self, const char* json); SkeletonData* SkeletonJson_readSkeletonDataFile (SkeletonJson* self, const char* path); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SKELETONJSON_H_ */ diff --git a/cocos/editor-support/spine/Skin.cpp b/cocos/editor-support/spine/Skin.cpp index d689c472ab..cd8b736d4f 100644 --- a/cocos/editor-support/spine/Skin.cpp +++ b/cocos/editor-support/spine/Skin.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct _Entry _Entry; struct _Entry { @@ -115,4 +115,4 @@ void Skin_attachAll (const Skin* self, Skeleton* skeleton, const Skin* oldSkin) } } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Skin.h b/cocos/editor-support/spine/Skin.h index f8d76a56f8..4dba09e524 100644 --- a/cocos/editor-support/spine/Skin.h +++ b/cocos/editor-support/spine/Skin.h @@ -28,7 +28,7 @@ #include -namespace cocos2d { namespace extension { +namespace spine { struct Skeleton; @@ -50,6 +50,6 @@ const char* Skin_getAttachmentName (const Skin* self, int slotIndex, int attachm /** Attach each attachment in this skin if the corresponding attachment in oldSkin is currently attached. */ void Skin_attachAll (const Skin* self, struct Skeleton* skeleton, const Skin* oldSkin); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SKIN_H_ */ diff --git a/cocos/editor-support/spine/Slot.cpp b/cocos/editor-support/spine/Slot.cpp index a17fdc1d78..47ed9d3f61 100644 --- a/cocos/editor-support/spine/Slot.cpp +++ b/cocos/editor-support/spine/Slot.cpp @@ -27,7 +27,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { Slot super; @@ -80,4 +80,4 @@ void Slot_setToSetupPose (Slot* self) { Slot_setAttachment(self, attachment); } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/Slot.h b/cocos/editor-support/spine/Slot.h index 47b2a7f05d..44f2f48694 100644 --- a/cocos/editor-support/spine/Slot.h +++ b/cocos/editor-support/spine/Slot.h @@ -30,7 +30,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { struct Skeleton; @@ -53,6 +53,6 @@ float Slot_getAttachmentTime (const Slot* self); void Slot_setToSetupPose (Slot* self); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SLOT_H_ */ diff --git a/cocos/editor-support/spine/SlotData.cpp b/cocos/editor-support/spine/SlotData.cpp index 5f1478e6d2..fe0609edfe 100644 --- a/cocos/editor-support/spine/SlotData.cpp +++ b/cocos/editor-support/spine/SlotData.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { SlotData* SlotData_create (const char* name, BoneData* boneData) { SlotData* self = NEW(SlotData); @@ -53,4 +53,4 @@ void SlotData_setAttachmentName (SlotData* self, const char* attachmentName) { CONST_CAST(char*, self->attachmentName) = 0; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/SlotData.h b/cocos/editor-support/spine/SlotData.h index 660c30695c..b49efb86c9 100644 --- a/cocos/editor-support/spine/SlotData.h +++ b/cocos/editor-support/spine/SlotData.h @@ -28,7 +28,7 @@ #include -namespace cocos2d { namespace extension { +namespace spine { typedef struct { const char* const name; @@ -43,6 +43,6 @@ void SlotData_dispose (SlotData* self); /* @param attachmentName May be 0 for no setup pose attachment. */ void SlotData_setAttachmentName (SlotData* self, const char* attachmentName); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_SLOTDATA_H_ */ diff --git a/cocos/editor-support/spine/extension.cpp b/cocos/editor-support/spine/extension.cpp index dfdda7a96e..3fa34170b9 100644 --- a/cocos/editor-support/spine/extension.cpp +++ b/cocos/editor-support/spine/extension.cpp @@ -26,7 +26,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { static void* (*mallocFunc) (size_t size) = malloc; static void (*freeFunc) (void* ptr) = free; @@ -71,4 +71,4 @@ char* _readFile (const char* path, int* length) { return data; } -}} // namespace cocos2d { namespace extension { +} // namespace spine { diff --git a/cocos/editor-support/spine/extension.h b/cocos/editor-support/spine/extension.h index 37ae496e4b..019b7350d7 100644 --- a/cocos/editor-support/spine/extension.h +++ b/cocos/editor-support/spine/extension.h @@ -88,7 +88,7 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { /* * Functions that must be implemented: @@ -140,6 +140,6 @@ void _CurveTimeline_init (CurveTimeline* self, int frameCount, /**/ void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)); void _CurveTimeline_deinit (CurveTimeline* self); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_EXTENSION_H_ */ diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index 74421b4390..cd9ea67e30 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -28,7 +28,7 @@ USING_NS_CC; -namespace cocos2d { namespace extension { +namespace spine { void _AtlasPage_createTexture (AtlasPage* self, const char* path) { Texture2D* texture = TextureCache::getInstance()->addImage(path); @@ -106,4 +106,4 @@ void RegionAttachment_updateQuad (RegionAttachment* self, Slot* slot, V3F_C4B_T2 quad->br.texCoords.v = self->uvs[VERTEX_Y4]; } -}} // namespace cocos2d { namespace extension { \ No newline at end of file +} // namespace spine { \ No newline at end of file diff --git a/cocos/editor-support/spine/spine-cocos2dx.h b/cocos/editor-support/spine/spine-cocos2dx.h index 234af2ecf1..d7d87b2bcc 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.h +++ b/cocos/editor-support/spine/spine-cocos2dx.h @@ -31,10 +31,10 @@ #include #include -namespace cocos2d { namespace extension { +namespace spine { void RegionAttachment_updateQuad (RegionAttachment* self, Slot* slot, cocos2d::V3F_C4B_T2F_Quad* quad, bool premultiplied = false); -}} // namespace cocos2d { namespace extension { +} // namespace spine { #endif /* SPINE_COCOS2DX_H_ */ diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk new file mode 100644 index 0000000000..b34d108585 --- /dev/null +++ b/cocos/gui/Android.mk @@ -0,0 +1,50 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := gui_static + +LOCAL_MODULE_FILENAME := libgui + +LOCAL_SRC_FILES := base-classes/UIRootWidget.cpp \ +base-classes/UIWidget.cpp \ +layouts/Layout.cpp \ +layouts/LayoutParameter.cpp \ +layouts/UILayoutDefine.cpp \ +system/CocosGUI.cpp \ +system/UIHelper.cpp \ +system/UIInputManager.cpp \ +system/UILayer.cpp \ +widgets/scroll-widget/UIDragPanel.cpp \ +widgets/scroll-widget/UIListView.cpp \ +widgets/scroll-widget/UIPageView.cpp \ +widgets/scroll-widget/UIScrollView.cpp \ +widgets/UIButton.cpp \ +widgets/UICheckBox.cpp \ +widgets/UIImageView.cpp \ +widgets/UILabel.cpp \ +widgets/UILabelAtlas.cpp \ +widgets/UILabelBMFont.cpp \ +widgets/UILoadingBar.cpp \ +widgets/UISlider.cpp \ +widgets/UITextField.cpp + + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ +$(LOCAL_PATH) \ +$(LOCAL_PATH)/.. + +LOCAL_CFLAGS += -Wno-psabi +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +LOCAL_WHOLE_STATIC_LIBRARIES := cocostudio_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static + +include $(BUILD_STATIC_LIBRARY) + + +$(call import-module,extensions) +$(call import-module,editor-support/cocostudio) +$(call import-module,2d) diff --git a/cocos/gui/base-classes/UIRootWidget.cpp b/cocos/gui/base-classes/UIRootWidget.cpp index bc34480328..8e87225f14 100644 --- a/cocos/gui/base-classes/UIRootWidget.cpp +++ b/cocos/gui/base-classes/UIRootWidget.cpp @@ -24,7 +24,9 @@ #include "UIRootWidget.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIRootWidget::UIRootWidget() { @@ -61,4 +63,4 @@ const char* UIRootWidget::getDescription() const return "RootWidget"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/base-classes/UIRootWidget.h b/cocos/gui/base-classes/UIRootWidget.h index c08a75f457..2a32c6c070 100644 --- a/cocos/gui/base-classes/UIRootWidget.h +++ b/cocos/gui/base-classes/UIRootWidget.h @@ -25,9 +25,9 @@ #ifndef __UIROOTWIDGET_H__ #define __UIROOTWIDGET_H__ -#include "../Layouts/Layout.h" +#include "layouts/Layout.h" -NS_CC_EXT_BEGIN +namespace gui { class UIRootWidget : public Layout { @@ -56,6 +56,6 @@ protected: virtual bool init(); }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__RootWidget__) */ diff --git a/cocos/gui/base-classes/UIWidget.cpp b/cocos/gui/base-classes/UIWidget.cpp index e120e12186..f8462f239b 100644 --- a/cocos/gui/base-classes/UIWidget.cpp +++ b/cocos/gui/base-classes/UIWidget.cpp @@ -23,11 +23,13 @@ ****************************************************************************/ #include "UIWidget.h" -#include "../System/UILayer.h" -#include "../Layouts/Layout.h" -#include "../System/UIHelper.h" +#include "system/UILayer.h" +#include "layouts/Layout.h" +#include "system/UIHelper.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { #define DYNAMIC_CAST_CCBLENDPROTOCOL dynamic_cast(_renderer) @@ -1215,4 +1217,4 @@ void GUIRenderer::visit() NodeRGBA::visit(); } -NS_CC_EXT_END +} diff --git a/cocos/gui/base-classes/UIWidget.h b/cocos/gui/base-classes/UIWidget.h index e0163645cd..d0a83fb286 100644 --- a/cocos/gui/base-classes/UIWidget.h +++ b/cocos/gui/base-classes/UIWidget.h @@ -26,10 +26,9 @@ #define __UIWIDGET_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -#include "../Layouts/UILayoutDefine.h" -#include "../Layouts/LayoutParameter.h" -NS_CC_EXT_BEGIN +#include "layouts/UILayoutDefine.h" +#include "layouts/LayoutParameter.h" +namespace gui { typedef enum @@ -71,14 +70,14 @@ typedef enum POSITION_PERCENT }PositionType; -typedef void (Object::*SEL_TouchEvent)(Object*,TouchEventType); -#define toucheventselector(_SELECTOR) (cocos2d::extension::SEL_TouchEvent)(&_SELECTOR) +typedef void (cocos2d::Object::*SEL_TouchEvent)(cocos2d::Object*,TouchEventType); +#define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) //class UILayer; /*temp action*/ class UIActionNode; -class UIWidget : public Object +class UIWidget : public cocos2d::Object { public: /** @@ -300,7 +299,7 @@ public: * * @return An array of children */ - virtual Array* getChildren(); + virtual cocos2d::Array* getChildren(); /** * Gets the renderer of widget @@ -309,7 +308,7 @@ public: * * @return a CCNode object */ - Node* getRenderer(); + cocos2d::Node* getRenderer(); /** * Add a CCNode for rendering. @@ -320,7 +319,7 @@ public: * * @param zOrder Z order for drawing priority. Please refer to CCNode::setZOrder(int) */ - void addRenderer(Node* renderer, int zOrder); + void addRenderer(cocos2d::Node* renderer, int zOrder); /** * Remove a CCNode from widget. @@ -331,7 +330,7 @@ public: * * @param cleanup true if all running actions and callbacks on the render node will be cleanup, false otherwise. */ - void removeRenderer(Node* renderer, bool cleanup); + void removeRenderer(cocos2d::Node* renderer, bool cleanup); /** * Sets the parent widget @@ -352,7 +351,7 @@ public: /** * Sets the touch event target/selector of the menu item */ - void addTouchEventListener(Object* target,SEL_TouchEvent selector); + void addTouchEventListener(cocos2d::Object* target,SEL_TouchEvent selector); //cocos2d property @@ -365,7 +364,7 @@ public: * * @param position The position (x,y) of the widget in OpenGL coordinates */ - void setPosition(const Point &pos); + void setPosition(const cocos2d::Point &pos); /** * Changes the position (x,y) of the widget in OpenGL coordinates @@ -375,7 +374,7 @@ public: * * @param percent The percent (x,y) of the widget in OpenGL coordinates */ - void setPositionPercent(const Point &percent); + void setPositionPercent(const cocos2d::Point &percent); /** * Gets the position (x,y) of the widget in OpenGL coordinates @@ -384,7 +383,7 @@ public: * * @return The position (x,y) of the widget in OpenGL coordinates */ - const Point& getPosition(); + const cocos2d::Point& getPosition(); /** * Gets the percent (x,y) of the widget in OpenGL coordinates @@ -393,7 +392,7 @@ public: * * @return The percent (x,y) of the widget in OpenGL coordinates */ - const Point& getPositionPercent(); + const cocos2d::Point& getPositionPercent(); /** * Changes the position type of the widget @@ -424,7 +423,7 @@ public: * * @param anchorPoint The anchor point of widget. */ - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); /** * Returns the anchor point in percent. @@ -433,7 +432,7 @@ public: * * @return The anchor point of widget. */ - const Point& getAnchorPoint(); + const cocos2d::Point& getAnchorPoint(); /** * Changes both X and Y scale factor of the widget. @@ -592,14 +591,14 @@ public: * * @param color */ - virtual void setColor(const Color3B &color); + virtual void setColor(const cocos2d::Color3B &color); /** * Gets color of widget * * @return color */ - virtual const Color3B& getColor(); + virtual const cocos2d::Color3B& getColor(); /** * Sets opacity to widget @@ -620,16 +619,16 @@ public: virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); virtual bool isCascadeColorEnabled(); virtual void setCascadeColorEnabled(bool cascadeColorEnabled); - void setBlendFunc(BlendFunc blendFunc); + void setBlendFunc(cocos2d::BlendFunc blendFunc); //cocos action - virtual void setActionManager(ActionManager* actionManager); - virtual ActionManager* getActionManager(); - Action* runAction(Action* action); + virtual void setActionManager(cocos2d::ActionManager* actionManager); + virtual cocos2d::ActionManager* getActionManager(); + cocos2d::Action* runAction(cocos2d::Action* action); void stopAllActions(void); - void stopAction(Action* action); + void stopAction(cocos2d::Action* action); void stopActionByTag(int tag); - Action* getActionByTag(int tag); + cocos2d::Action* getActionByTag(int tag); /** * A call back function when widget lost of focus. @@ -643,33 +642,33 @@ public: * * @return true if the point is in parent's area, flase otherwise. */ - bool clippingParentAreaContainPoint(const Point &pt); + bool clippingParentAreaContainPoint(const cocos2d::Point &pt); /* * Sends the touch event to widget's parent */ - virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); /* * Gets the touch began point of widget when widget is selected. * * @return the touch began point. */ - const Point& getTouchStartPos(); + const cocos2d::Point& getTouchStartPos(); /* * Gets the touch move point of widget when widget is selected. * * @return the touch move point. */ - const Point& getTouchMovePos(); + const cocos2d::Point& getTouchMovePos(); /* * Gets the touch end point of widget when widget is selected. * * @return the touch end point. */ - const Point& getTouchEndPos(); + const cocos2d::Point& getTouchEndPos(); /** * Changes the tag that is used to identify the widget easily. @@ -717,14 +716,14 @@ public: * * @param size that is widget's size */ - virtual void setSize(const Size &size); + virtual void setSize(const cocos2d::Size &size); /** * Changes the percent that is widget's percent size * * @param percent that is widget's percent size */ - virtual void setSizePercent(const Point &percent); + virtual void setSizePercent(const cocos2d::Point &percent); /** * Changes the size type of widget. @@ -749,14 +748,14 @@ public: * * @return size */ - const Size& getSize() const; + const cocos2d::Size& getSize() const; /** * Returns size percent of widget * * @return size percent */ - const Point& getSizePercent() const; + const cocos2d::Point& getSizePercent() const; /** * Checks a point if is in widget's space @@ -765,7 +764,7 @@ public: * * @return true if the point is in widget's space, flase otherwise. */ - virtual bool hitTest(const Point &pt); + virtual bool hitTest(const cocos2d::Point &pt); /** * A call back function called when widget is selected, and on touch began. @@ -774,35 +773,35 @@ public: * * @return true if the event should be pass to parent, flase otherwise. */ - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); /** * A call back function called when widget is selected, and on touch moved. * * @param touch point */ - virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); /** * A call back function called when widget is selected, and on touch ended. * * @param touch point */ - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); /** * A call back function called when widget is selected, and on touch canceled. * * @param touch point */ - virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); /** * A call back function called when widget is selected, and on touch long clicked. * * @param touch point */ - virtual void onTouchLongClicked(const Point &touchPoint); + virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); /** * Sets a LayoutParameter to widget. @@ -839,12 +838,12 @@ public: * * @return world position of widget. */ - Point getWorldPosition(); + cocos2d::Point getWorldPosition(); /** * Converts a Point to world space coordinates. The result is in Points. */ - Point convertToWorldSpace(const Point& pt); + cocos2d::Point convertToWorldSpace(const cocos2d::Point& pt); /** * Gets the Virtual Renderer of widget. @@ -853,7 +852,7 @@ public: * * @return CCNode pointer. */ - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Schedules the "update" method. @@ -870,7 +869,7 @@ public: * * Content size is widget's texture size. */ - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; virtual void onEnter(); virtual void onExit(); @@ -922,16 +921,16 @@ protected: bool _touchPassedEnabled; ///< is the touch event should be passed bool _focus; ///< is the widget on focus int _widgetZOrder; ///< z-order value that affects the draw order and touch order - Point _anchorPoint; ///< anchor point normalized + cocos2d::Point _anchorPoint; ///< anchor point normalized UIWidget* _widgetParent; ///< parent of widget BrightStyle _brightStyle; ///< bright style bool _updateEnabled; ///< is "update" method scheduled - Node* _renderer; ///< base renderer - Point _touchStartPos; ///< touch began point - Point _touchMovePos; ///< touch moved point - Point _touchEndPos; ///< touch ended point + cocos2d::Node* _renderer; ///< base renderer + cocos2d::Point _touchStartPos; ///< touch began point + cocos2d::Point _touchMovePos; ///< touch moved point + cocos2d::Point _touchEndPos; ///< touch ended point - Object* _touchEventListener; + cocos2d::Object* _touchEventListener; SEL_TouchEvent _touchEventSelector; @@ -940,23 +939,23 @@ protected: std::string _name; WidgetType _widgetType; int _actionTag; - Size _size; - Size _customSize; + cocos2d::Size _size; + cocos2d::Size _customSize; LayoutParameter* _layoutParameter; bool _ignoreSize; - Array* _children; + cocos2d::Array* _children; bool _affectByClipping; - Scheduler* _scheduler; + cocos2d::Scheduler* _scheduler; SizeType _sizeType; - Point _sizePercent; + cocos2d::Point _sizePercent; PositionType _positionType; - Point _positionPercent; + cocos2d::Point _positionPercent; bool _isRunning; }; -class GUIRenderer : public NodeRGBA +class GUIRenderer : public cocos2d::NodeRGBA { public: GUIRenderer(); @@ -969,6 +968,6 @@ protected: bool _enabled; }; -NS_CC_EXT_END +} #endif /* defined(__UIWidget__) */ diff --git a/cocos/gui/layouts/Layout.cpp b/cocos/gui/layouts/Layout.cpp index 3492de9486..6403262bd9 100644 --- a/cocos/gui/layouts/Layout.cpp +++ b/cocos/gui/layouts/Layout.cpp @@ -22,12 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "Layout.h" -#include "../System/UILayer.h" -#include "../System/UIHelper.h" -#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" +#include "layout.h" +#include "system/UILayer.h" +#include "system/UIHelper.h" +#include "GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + using namespace cocos2d::extension; + +namespace gui { #define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) @@ -779,4 +782,4 @@ bool RectClippingNode::isEnabled() const return _enabled; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/layouts/Layout.h b/cocos/gui/layouts/Layout.h index bf8719a06d..c448036642 100644 --- a/cocos/gui/layouts/Layout.h +++ b/cocos/gui/layouts/Layout.h @@ -25,9 +25,9 @@ #ifndef __LAYOUT_H__ #define __LAYOUT_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { @@ -63,7 +63,7 @@ public: static Layout* create(); //override "hitTest" method of widget. - virtual bool hitTest(const Point &pt); + virtual bool hitTest(const cocos2d::Point &pt); //background /** @@ -81,7 +81,7 @@ public: * @param capinsets of background image. * */ - void setBackGroundImageCapInsets(const Rect& capInsets); + void setBackGroundImageCapInsets(const cocos2d::Rect& capInsets); /** * Sets Color Type for layout. @@ -102,7 +102,7 @@ public: * * @param color */ - void setBackGroundColor(const Color3B &color); + void setBackGroundColor(const cocos2d::Color3B &color); /** * Sets background color for layout, if color type is LAYOUT_COLOR_GRADIENT @@ -111,7 +111,7 @@ public: * * @param end color */ - void setBackGroundColor(const Color3B &startColor, const Color3B &endColor); + void setBackGroundColor(const cocos2d::Color3B &startColor, const cocos2d::Color3B &endColor); /** * Sets background opacity layout. @@ -125,10 +125,10 @@ public: * * @param vector */ - void setBackGroundColorVector(const Point &vector); + void setBackGroundColorVector(const cocos2d::Point &vector); //override "setColor" method of widget. - virtual void setColor(const Color3B &color); + virtual void setColor(const cocos2d::Color3B &color); //override "setOpacity" method of widget. virtual void setOpacity(int opacity); @@ -143,7 +143,7 @@ public: * * @return background image texture size. */ - const Size& getBackGroundImageTextureSize() const; + const cocos2d::Size& getBackGroundImageTextureSize() const; /** * Changes if layout can clip it's content and child. @@ -166,7 +166,7 @@ public: * * Content size is widget's texture size. */ - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; /** * Sets LayoutType. @@ -209,43 +209,43 @@ protected: //background bool _backGroundScale9Enabled; - Node* _backGroundImage; + cocos2d::Node* _backGroundImage; std::string _backGroundImageFileName; - Rect _backGroundImageCapInsets; + cocos2d::Rect _backGroundImageCapInsets; LayoutBackGroundColorType _colorType; TextureResType _bgImageTexType; - LayerColor* _colorRender; - LayerGradient* _gradientRender; - Color3B _cColor; - Color3B _gStartColor; - Color3B _gEndColor; - Point _alongVector; + cocos2d::LayerColor* _colorRender; + cocos2d::LayerGradient* _gradientRender; + cocos2d::Color3B _cColor; + cocos2d::Color3B _gStartColor; + cocos2d::Color3B _gEndColor; + cocos2d::Point _alongVector; int _cOpacity; - Size _backGroundImageTextureSize; + cocos2d::Size _backGroundImageTextureSize; LayoutType _layoutType; }; -class RectClippingNode : public ClippingNode +class RectClippingNode : public cocos2d::ClippingNode { public: virtual ~RectClippingNode(); virtual bool init(); static RectClippingNode* create(); - void setClippingSize(const Size& size); + void setClippingSize(const cocos2d::Size& size); void setClippingEnabled(bool enabled); virtual void visit(); void setEnabled(bool enabled); bool isEnabled() const; protected: - DrawNode* m_pInnerStencil; + cocos2d::DrawNode* m_pInnerStencil; bool _enabled; private: RectClippingNode(); - Point rect[4]; - Size _clippingSize; + cocos2d::Point rect[4]; + cocos2d::Size _clippingSize; bool _clippingEnabled; }; -NS_CC_EXT_END +} #endif /* defined(__Layout__) */ diff --git a/cocos/gui/layouts/LayoutParameter.cpp b/cocos/gui/layouts/LayoutParameter.cpp index 209979cdb9..d8cf87085a 100644 --- a/cocos/gui/layouts/LayoutParameter.cpp +++ b/cocos/gui/layouts/LayoutParameter.cpp @@ -25,7 +25,7 @@ #include "LayoutParameter.h" #include "Layout.h" -NS_CC_EXT_BEGIN +namespace gui { LayoutParameter* LayoutParameter::create() { @@ -118,4 +118,4 @@ const char* RelativeLayoutParameter::getRelativeName() const return _relativeLayoutName.c_str(); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/layouts/LayoutParameter.h b/cocos/gui/layouts/LayoutParameter.h index 50d55c6586..f1e5433be6 100644 --- a/cocos/gui/layouts/LayoutParameter.h +++ b/cocos/gui/layouts/LayoutParameter.h @@ -27,7 +27,7 @@ #include "UILayoutDefine.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { @@ -36,7 +36,7 @@ typedef enum LAYOUT_PARAMETER_RELATIVE }LayoutParameterType; -class LayoutParameter : public Object +class LayoutParameter : public cocos2d::Object { public: /** @@ -196,6 +196,6 @@ protected: std::string _relativeLayoutName; }; -NS_CC_EXT_END +} #endif /* defined(__LayoutParameter__) */ diff --git a/cocos/gui/layouts/UILayoutDefine.cpp b/cocos/gui/layouts/UILayoutDefine.cpp index 54b8451c78..b6b785a47d 100644 --- a/cocos/gui/layouts/UILayoutDefine.cpp +++ b/cocos/gui/layouts/UILayoutDefine.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "UILayoutDefine.h" -NS_CC_EXT_BEGIN +namespace gui { UIMargin::UIMargin(void) : left(0), top(0), right(0), bottom(0) @@ -57,4 +57,4 @@ bool UIMargin::equals(const UIMargin &target) const return (left == target.left && top == target.top && right == target.right && bottom == target.bottom); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/layouts/UILayoutDefine.h b/cocos/gui/layouts/UILayoutDefine.h index ac2df8ca65..1d0bd716bf 100644 --- a/cocos/gui/layouts/UILayoutDefine.h +++ b/cocos/gui/layouts/UILayoutDefine.h @@ -26,9 +26,8 @@ #define __UILAYOUTDEFINE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace gui { class UIMargin { @@ -83,6 +82,6 @@ typedef enum RELATIVE_LOCATION_BELOW_RIGHTALIGN }UIRelativeAlign; -NS_CC_EXT_END +} #endif /* defined(__UILayoutDefine__) */ diff --git a/cocos/gui/system/CocosGUI.cpp b/cocos/gui/system/CocosGUI.cpp index 2a0ebe9ebd..783041a335 100644 --- a/cocos/gui/system/CocosGUI.cpp +++ b/cocos/gui/system/CocosGUI.cpp @@ -24,11 +24,11 @@ #include "CocosGUI.h" -NS_CC_EXT_BEGIN +namespace gui { const char* CocosGUIVersion() { return "CocosGUI v1.0.0.0"; } -NS_CC_EXT_END +} diff --git a/cocos/gui/system/CocosGUI.h b/cocos/gui/system/CocosGUI.h index ca080ea059..97046adde2 100644 --- a/cocos/gui/system/CocosGUI.h +++ b/cocos/gui/system/CocosGUI.h @@ -26,29 +26,29 @@ #define __COCOSGUI_H__ -#include "../BaseClasses/UIWidget.h" -#include "../Layouts/Layout.h" -#include "../BaseClasses/UIRootWidget.h" -#include "../UIWidgets/UIButton.h" -#include "../UIWidgets/UICheckBox.h" -#include "../UIWidgets/UIImageView.h" -#include "../UIWidgets/UILabel.h" -#include "../UIWidgets/UILabelAtlas.h" -#include "../UIWidgets/UILoadingBar.h" -#include "../UIWidgets/ScrollWidget/UIScrollView.h" -#include "../UIWidgets/UISlider.h" -#include "../UIWidgets/UITextField.h" -#include "../UIWidgets/ScrollWidget/UIListView.h" -#include "../UIWidgets/ScrollWidget/UIDragPanel.h" -#include "../UIWidgets/UILabelBMFont.h" -#include "../UIWidgets/ScrollWidget/UIPageView.h" +#include "base-classes/UIWidget.h" +#include "layouts/Layout.h" +#include "base-classes/UIRootWidget.h" +#include "widgets/UIButton.h" +#include "widgets/UICheckBox.h" +#include "widgets/UIImageView.h" +#include "widgets/UILabel.h" +#include "widgets/UILabelAtlas.h" +#include "widgets/UILoadingBar.h" +#include "widgets/scroll-widget/UIScrollView.h" +#include "widgets/UISlider.h" +#include "widgets/UITextField.h" +#include "widgets/scroll-widget/UIListView.h" +#include "widgets/scroll-widget/UIDragPanel.h" +#include "widgets/UILabelBMFont.h" +#include "widgets/scroll-widget/UIPageView.h" #include "UIHelper.h" -#include "../../Reader/CCSGUIReader.h" +#include "reader/CCSGUIReader.h" #include "UILayer.h" -NS_CC_EXT_BEGIN +namespace gui { const char* CocosGUIVersion(); -NS_CC_EXT_END +} #endif /* defined(__CocosGUITest__Cocos__) */ diff --git a/cocos/gui/system/UIHelper.cpp b/cocos/gui/system/UIHelper.cpp index 188147e480..c023bf23bf 100644 --- a/cocos/gui/system/UIHelper.cpp +++ b/cocos/gui/system/UIHelper.cpp @@ -23,12 +23,14 @@ ****************************************************************************/ #include "UIHelper.h" -#include "../../Json/DictionaryHelper.h" +#include "json/DictionaryHelper.h" #include "cocos2d.h" -#include "../../Reader/CCSGUIReader.h" +#include "reader/CCSGUIReader.h" +using namespace cocos2d; +using namespace cocostudio; -NS_CC_EXT_BEGIN +namespace gui { static UIHelper* helperInstance = NULL; @@ -59,7 +61,7 @@ _fileDesignWidth(0.0f) UIHelper::~UIHelper() { - cocos2d::extension::CCSGUIReader::purgeCCSGUIReader(); + cocostudio::CCSGUIReader::purgeCCSGUIReader(); } void UIHelper::init() @@ -238,4 +240,4 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) return NULL; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/system/UIHelper.h b/cocos/gui/system/UIHelper.h index 5446271b9b..15487fbf60 100644 --- a/cocos/gui/system/UIHelper.h +++ b/cocos/gui/system/UIHelper.h @@ -26,12 +26,12 @@ #define __UIHELPER_H__ #include "UIInputManager.h" -#include "../../Json/CSContentJsonDictionary.h" +#include "json/CSContentJsonDictionary.h" -#define CCUIHELPER cocos2d::extension::UIHelper::instance() +#define CCUIHELPER gui::UIHelper::instance() -NS_CC_EXT_BEGIN +namespace gui { class UIHelper { @@ -116,9 +116,9 @@ protected: float _fileDesignWidth; float _fileDesignHeight; //texture - Array* _textureFiles; + cocos2d::Array* _textureFiles; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UISystem__) */ diff --git a/cocos/gui/system/UIInputManager.cpp b/cocos/gui/system/UIInputManager.cpp index 21371d481a..4972f6da4b 100644 --- a/cocos/gui/system/UIInputManager.cpp +++ b/cocos/gui/system/UIInputManager.cpp @@ -25,7 +25,9 @@ #include "UIInputManager.h" #include "UIHelper.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIInputManager::UIInputManager(): _manageredWidget(NULL), @@ -205,4 +207,4 @@ UIWidget* UIInputManager::getRootWidget() return _rootWidget; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/system/UIInputManager.h b/cocos/gui/system/UIInputManager.h index d0a178ae82..36f5f780df 100644 --- a/cocos/gui/system/UIInputManager.h +++ b/cocos/gui/system/UIInputManager.h @@ -26,9 +26,9 @@ #define __UIINPUTMANAGER_H__ #include "cocos2d.h" -#include "../Layouts/Layout.h" +#include "layouts/Layout.h" -NS_CC_EXT_BEGIN +namespace gui { class UIInputManager { @@ -64,34 +64,34 @@ public: * * @return true that find a widget selected, false otherwise. */ - bool checkEventWidget(const Point &touchPoint); + bool checkEventWidget(const cocos2d::Point &touchPoint); void update(float dt); - bool onTouchBegan(Touch* touch); - void onTouchMoved(Touch* touch); - void onTouchEnd(Touch* touch); - void onTouchCancelled(Touch* touch); + bool onTouchBegan(cocos2d::Touch* touch); + void onTouchMoved(cocos2d::Touch* touch); + void onTouchEnd(cocos2d::Touch* touch); + void onTouchCancelled(cocos2d::Touch* touch); void setRootWidget(UIWidget* root); UIWidget* getRootWidget(); void addCheckedDoubleClickWidget(UIWidget* widget); protected: - bool checkTouchEvent(UIWidget* root, const Point& touchPoint); + bool checkTouchEvent(UIWidget* root, const cocos2d::Point& touchPoint); protected: - Array* _manageredWidget; - Array* _selectedWidgets; - Point _touchBeganedPoint; - Point _touchMovedPoint; - Point _touchEndedPoint; - Point _touchCanceledPoint; + cocos2d::Array* _manageredWidget; + cocos2d::Array* _selectedWidgets; + cocos2d::Point _touchBeganedPoint; + cocos2d::Point _touchMovedPoint; + cocos2d::Point _touchEndedPoint; + cocos2d::Point _touchCanceledPoint; bool _touchDown; float _longClickTime; float _longClickRecordTime; - Array* _checkedDoubleClickWidget; + cocos2d::Array* _checkedDoubleClickWidget; UIWidget* _rootWidget; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UIInputManager__) */ diff --git a/cocos/gui/system/UILayer.cpp b/cocos/gui/system/UILayer.cpp index 917241f494..1136656881 100644 --- a/cocos/gui/system/UILayer.cpp +++ b/cocos/gui/system/UILayer.cpp @@ -25,7 +25,9 @@ #include "UILayer.h" #include "UIHelper.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UILayer::UILayer(): _rootWidget(NULL), @@ -162,4 +164,4 @@ void UILayer::onTouchCancelled(Touch *pTouch, Event *pEvent) _inputManager->onTouchCancelled(pTouch); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/system/UILayer.h b/cocos/gui/system/UILayer.h index 7108d6b757..cf6fe9c43a 100644 --- a/cocos/gui/system/UILayer.h +++ b/cocos/gui/system/UILayer.h @@ -27,14 +27,13 @@ #define __UILAYER_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -#include "../BaseClasses/UIRootWidget.h" -#include "../System/UIInputManager.h" +#include "base-classes/UIRootWidget.h" +#include "system/UIInputManager.h" -NS_CC_EXT_BEGIN +namespace gui { -class UILayer : public Layer +class UILayer : public cocos2d::Layer { public: @@ -60,10 +59,10 @@ public: virtual void onExit(); virtual void onEnterTransitionDidFinish(); - virtual bool onTouchBegan(Touch *pTouch, Event *pEvent); - virtual void onTouchMoved(Touch *pTouch, Event *pEvent); - virtual void onTouchEnded(Touch *pTouch, Event *pEvent); - virtual void onTouchCancelled(Touch *pTouch, Event *pEvent); + virtual bool onTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent); + virtual void onTouchMoved(cocos2d::Touch *pTouch, cocos2d::Event *pEvent); + virtual void onTouchEnded(cocos2d::Touch *pTouch, cocos2d::Event *pEvent); + virtual void onTouchCancelled(cocos2d::Touch *pTouch, cocos2d::Event *pEvent); /** * Add a widget to UILayer, for drawing. @@ -130,7 +129,7 @@ protected: UIInputManager* _inputManager; }; -NS_CC_EXT_END +} diff --git a/cocos/gui/widgets/UIButton.cpp b/cocos/gui/widgets/UIButton.cpp index 7273378c0f..7325007d27 100644 --- a/cocos/gui/widgets/UIButton.cpp +++ b/cocos/gui/widgets/UIButton.cpp @@ -23,9 +23,12 @@ ****************************************************************************/ #include "UIButton.h" -#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" +#include "GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + using namespace cocos2d::extension; + +namespace gui { #define NORMALRENDERERZ (0) #define PRESSEDRENDERERZ (0) @@ -614,4 +617,4 @@ const char* UIButton::getDescription() const return "Button"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UIButton.h b/cocos/gui/widgets/UIButton.h index f44e897a90..5e9ba1c011 100644 --- a/cocos/gui/widgets/UIButton.h +++ b/cocos/gui/widgets/UIButton.h @@ -25,9 +25,9 @@ #ifndef __UIBUTTON_H__ #define __UIBUTTON_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { class UIButton : public UIWidget { @@ -92,31 +92,31 @@ public: * * @param capInsets capinsets for button */ - void setCapInsets(const Rect &capInsets); + void setCapInsets(const cocos2d::Rect &capInsets); /** * Sets capinsets for button, if button is using scale9 renderer. * * @param capInsets capinsets for button */ - void setCapInsetsNormalRenderer(const Rect &capInsets); + void setCapInsetsNormalRenderer(const cocos2d::Rect &capInsets); /** * Sets capinsets for button, if button is using scale9 renderer. * * @param capInsets capinsets for button */ - void setCapInsetsPressedRenderer(const Rect &capInsets); + void setCapInsetsPressedRenderer(const cocos2d::Rect &capInsets); /** * Sets capinsets for button, if button is using scale9 renderer. * * @param capInsets capinsets for button */ - void setCapInsetsDisabledRenderer(const Rect &capInsets); + void setCapInsetsDisabledRenderer(const cocos2d::Rect &capInsets); //override "setAnchorPoint" of widget. - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); /** * Sets if button is using scale9 renderer. @@ -148,10 +148,10 @@ public: virtual void ignoreContentAdaptWithSize(bool ignore); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Sets color to widget @@ -160,12 +160,12 @@ public: * * @param color */ - virtual void setColor(const Color3B &color); + virtual void setColor(const cocos2d::Color3B &color); void setTitleText(const char* text); const char* getTitleText() const; - void setTitleColor(const Color3B& color); - const Color3B& getTitleColor() const; + void setTitleColor(const cocos2d::Color3B& color); + const cocos2d::Color3B& getTitleColor() const; void setTitleFontSize(float size); float getTitleFontSize() const; void setTitleFontName(const char* fontName); @@ -187,28 +187,28 @@ protected: void pressedTextureScaleChangedWithSize(); void disabledTextureScaleChangedWithSize(); protected: - Node* _buttonNormalRenderer; - Node* _buttonClickedRenderer; - Node* _buttonDisableRenderer; - LabelTTF* _titleRenderer; + cocos2d::Node* _buttonNormalRenderer; + cocos2d::Node* _buttonClickedRenderer; + cocos2d::Node* _buttonDisableRenderer; + cocos2d::LabelTTF* _titleRenderer; std::string _normalFileName; std::string _clickedFileName; std::string _disabledFileName; bool _prevIgnoreSize; bool _scale9Enabled; - Rect _capInsetsNormal; - Rect _capInsetsPressed; - Rect _capInsetsDisabled; + cocos2d::Rect _capInsetsNormal; + cocos2d::Rect _capInsetsPressed; + cocos2d::Rect _capInsetsDisabled; TextureResType _normalTexType; TextureResType _pressedTexType; TextureResType _disabledTexType; - Size _normalTextureSize; - Size _pressedTextureSize; - Size _disabledTextureSize; + cocos2d::Size _normalTextureSize; + cocos2d::Size _pressedTextureSize; + cocos2d::Size _disabledTextureSize; bool _pressedActionEnabled; - Color3B _titleColor; + cocos2d::Color3B _titleColor; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UIButton__) */ diff --git a/cocos/gui/widgets/UICheckBox.cpp b/cocos/gui/widgets/UICheckBox.cpp index 588ff138e1..ff41697418 100644 --- a/cocos/gui/widgets/UICheckBox.cpp +++ b/cocos/gui/widgets/UICheckBox.cpp @@ -24,7 +24,9 @@ #include "UICheckBox.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UICheckBox::UICheckBox(): _backGroundBoxRenderer(NULL), @@ -461,4 +463,4 @@ const char* UICheckBox::getDescription() const return "CheckBox"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UICheckBox.h b/cocos/gui/widgets/UICheckBox.h index 89f7473f05..408ef6b76a 100644 --- a/cocos/gui/widgets/UICheckBox.h +++ b/cocos/gui/widgets/UICheckBox.h @@ -25,9 +25,9 @@ #ifndef __UICHECKBOX_H__ #define __UICHECKBOX_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { @@ -35,8 +35,8 @@ typedef enum CHECKBOX_STATE_EVENT_UNSELECTED }CheckBoxEventType; -typedef void (CCObject::*SEL_SelectedStateEvent)(Object*,CheckBoxEventType); -#define checkboxselectedeventselector(_SELECTOR) (cocos2d::extension::SEL_SelectedStateEvent)(&_SELECTOR) +typedef void (cocos2d::CCObject::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); +#define checkboxselectedeventselector(_SELECTOR) (SEL_SelectedStateEvent)(&_SELECTOR) class UICheckBox : public UIWidget { @@ -131,10 +131,10 @@ public: bool getSelectedState(); //override "setAnchorPoint" method of widget. - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); //add a call back function would called when checkbox is selected or unselected. - void addEventListener(Object* target,SEL_SelectedStateEvent selector); + void addEventListener(cocos2d::Object* target,SEL_SelectedStateEvent selector); //override "setFlipX" method of widget. virtual void setFlipX(bool flipX); @@ -149,13 +149,13 @@ public: virtual bool isFlipY(); //override "onTouchEnded" method of widget. - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. @@ -176,14 +176,14 @@ protected: void backGroundDisabledTextureScaleChangedWithSize(); void frontCrossDisabledTextureScaleChangedWithSize(); protected: - Sprite* _backGroundBoxRenderer; - Sprite* _backGroundSelectedBoxRenderer; - Sprite* _frontCrossRenderer; - Sprite* _backGroundBoxDisabledRenderer; - Sprite* _frontCrossDisabledRenderer; + cocos2d::Sprite* _backGroundBoxRenderer; + cocos2d::Sprite* _backGroundSelectedBoxRenderer; + cocos2d::Sprite* _frontCrossRenderer; + cocos2d::Sprite* _backGroundBoxDisabledRenderer; + cocos2d::Sprite* _frontCrossDisabledRenderer; bool _isSelected; - Object* _selectedStateEventListener; + cocos2d::Object* _selectedStateEventListener; SEL_SelectedStateEvent _selectedStateEventSelector; TextureResType _backGroundTexType; @@ -193,6 +193,6 @@ protected: TextureResType _frontCrossDisabledTexType; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UICheckBox__) */ diff --git a/cocos/gui/widgets/UIImageView.cpp b/cocos/gui/widgets/UIImageView.cpp index 23db5afef3..89491f8141 100644 --- a/cocos/gui/widgets/UIImageView.cpp +++ b/cocos/gui/widgets/UIImageView.cpp @@ -23,9 +23,12 @@ ****************************************************************************/ #include "UIImageView.h" -#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" +#include "GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + using namespace cocos2d::extension; + +namespace gui { #define DYNAMIC_CAST_CCSPRITE dynamic_cast(_imageRenderer) #define DYNAMIC_CAST_SCALE9SPRITE dynamic_cast(_imageRenderer) @@ -373,4 +376,4 @@ const char* UIImageView::getDescription() const return "ImageView"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UIImageView.h b/cocos/gui/widgets/UIImageView.h index 89e73d3fc4..a218ce492c 100644 --- a/cocos/gui/widgets/UIImageView.h +++ b/cocos/gui/widgets/UIImageView.h @@ -25,9 +25,9 @@ #ifndef __UIIMAGEVIEW_H__ #define __UIIMAGEVIEW_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { class UIImageView : public UIWidget { @@ -60,7 +60,7 @@ public: * Updates the texture rect of the UIImageView in points. * It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. */ - void setTextureRect(const Rect& rect); + void setTextureRect(const cocos2d::Rect& rect); /** * Sets if imageview is using scale9 renderer. @@ -74,7 +74,7 @@ public: * * @param capInsets capinsets for imageview */ - void setCapInsets(const Rect &capInsets); + void setCapInsets(const cocos2d::Rect &capInsets); //override "setFlipX" method of widget. virtual void setFlipX(bool flipX); @@ -89,13 +89,13 @@ public: virtual bool isFlipY(); //override "setAnchorPoint" method of widget. - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); //override "onTouchBegan" method of widget. - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); //override "onTouchEnded" method of widget. - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); @@ -105,8 +105,8 @@ public: void setDoubleClickEnabled(bool able); void doubleClickEvent(); void checkDoubleClick(float dt); - virtual const Size& getContentSize() const; - virtual Node* getVirtualRenderer(); + virtual const cocos2d::Size& getContentSize() const; + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. @@ -124,13 +124,13 @@ protected: bool _doubleClickEnabled; bool _scale9Enabled; bool _prevIgnoreSize; - Rect _capInsets; - Node* _imageRenderer; + cocos2d::Rect _capInsets; + cocos2d::Node* _imageRenderer; std::string _textureFile; TextureResType _imageTexType; - Size _imageTextureSize; + cocos2d::Size _imageTextureSize; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UIImageView__) */ diff --git a/cocos/gui/widgets/UILabel.cpp b/cocos/gui/widgets/UILabel.cpp index 0bc0da834d..a5b468c5d2 100644 --- a/cocos/gui/widgets/UILabel.cpp +++ b/cocos/gui/widgets/UILabel.cpp @@ -24,7 +24,9 @@ #include "UILabel.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UILabel::UILabel(): _touchScaleChangeEnabled(false), @@ -228,4 +230,4 @@ const char* UILabel::getDescription() const return "Label"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UILabel.h b/cocos/gui/widgets/UILabel.h index 68b764595e..4f5a4794da 100644 --- a/cocos/gui/widgets/UILabel.h +++ b/cocos/gui/widgets/UILabel.h @@ -25,9 +25,9 @@ #ifndef __UILABEL_H__ #define __UILABEL_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { class UILabel : public UIWidget { @@ -109,22 +109,22 @@ public: virtual bool isFlipY(); //override "setAnchorPoint" method of widget. - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; - void setTextAreaSize(const Size &size); - void setTextHorizontalAlignment(TextHAlignment alignment); - void setTextVerticalAlignment(TextVAlignment alignment); + void setTextAreaSize(const cocos2d::Size &size); + void setTextHorizontalAlignment(cocos2d::TextHAlignment alignment); + void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); void setTouchScaleChangeAble(bool able){setTouchScaleChangeEnabled(able);}; @@ -144,9 +144,9 @@ protected: std::string _fontName; int _fontSize; float _onSelectedScaleOffset; - LabelTTF* _labelRenderer; + cocos2d::LabelTTF* _labelRenderer; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__Label__) */ diff --git a/cocos/gui/widgets/UILabelAtlas.cpp b/cocos/gui/widgets/UILabelAtlas.cpp index c4ba1922a7..9122960f8a 100644 --- a/cocos/gui/widgets/UILabelAtlas.cpp +++ b/cocos/gui/widgets/UILabelAtlas.cpp @@ -24,7 +24,9 @@ #include "UILabelAtlas.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UICCLabelAtlas::UICCLabelAtlas() { @@ -172,4 +174,4 @@ const char* UILabelAtlas::getDescription() const return "LabelAtlase"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UILabelAtlas.h b/cocos/gui/widgets/UILabelAtlas.h index 6ff0b65a1e..b9251fa3c4 100644 --- a/cocos/gui/widgets/UILabelAtlas.h +++ b/cocos/gui/widgets/UILabelAtlas.h @@ -25,11 +25,11 @@ #ifndef __UILABELATLAS_H__ #define __UILABELATLAS_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { -class UICCLabelAtlas : public LabelAtlas +class UICCLabelAtlas : public cocos2d::LabelAtlas { public: /** @@ -47,7 +47,7 @@ public: */ static UICCLabelAtlas* create(); void setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); - void setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; @@ -80,13 +80,13 @@ public: const char* getStringValue(); //override "setAnchorPoint" method of widget. - virtual void setAnchorPoint(const Point &pt); + virtual void setAnchorPoint(const cocos2d::Point &pt); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. @@ -100,6 +100,6 @@ protected: UICCLabelAtlas* _laberAtlasRenderer; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UILabelAtlas__) */ diff --git a/cocos/gui/widgets/UILabelBMFont.cpp b/cocos/gui/widgets/UILabelBMFont.cpp index 23b0a2a1fc..4f18161f95 100644 --- a/cocos/gui/widgets/UILabelBMFont.cpp +++ b/cocos/gui/widgets/UILabelBMFont.cpp @@ -24,7 +24,9 @@ #include "UILabelBMFont.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UILabelBMFont::UILabelBMFont(): _labelBMFontRenderer(NULL), @@ -58,7 +60,7 @@ void UILabelBMFont::initRenderer() void UILabelBMFont::setFntFile(const char *fileName) { - if (!fileName || std::strcmp(fileName, "") == 0) + if (!fileName || strcmp(fileName, "") == 0) { return; } @@ -132,4 +134,4 @@ const char* UILabelBMFont::getDescription() const } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UILabelBMFont.h b/cocos/gui/widgets/UILabelBMFont.h index a1eab88e2d..7e41307133 100644 --- a/cocos/gui/widgets/UILabelBMFont.h +++ b/cocos/gui/widgets/UILabelBMFont.h @@ -25,9 +25,9 @@ #ifndef __UILABELBMFONT_H__ #define __UILABELBMFONT_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { class UILabelBMFont : public UIWidget { @@ -55,9 +55,9 @@ public: /** get string value for labelbmfont*/ const char* getStringValue(); - virtual void setAnchorPoint(const Point &pt); - virtual const Size& getContentSize() const; - virtual Node* getVirtualRenderer(); + virtual void setAnchorPoint(const cocos2d::Point &pt); + virtual const cocos2d::Size& getContentSize() const; + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. @@ -68,10 +68,10 @@ protected: virtual void onSizeChanged(); void labelBMFontScaleChangedWithSize(); protected: - LabelBMFont* _labelBMFontRenderer; + cocos2d::LabelBMFont* _labelBMFontRenderer; bool _fntFileHasInit; }; -NS_CC_EXT_END +} #endif /* defined(__UILabelBMFont__) */ diff --git a/cocos/gui/widgets/UILoadingBar.cpp b/cocos/gui/widgets/UILoadingBar.cpp index ac53cf28ec..8037d1df33 100644 --- a/cocos/gui/widgets/UILoadingBar.cpp +++ b/cocos/gui/widgets/UILoadingBar.cpp @@ -23,9 +23,12 @@ ****************************************************************************/ #include "UILoadingBar.h" -#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" +#include "GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + using namespace cocos2d::extension; + +namespace gui { #define DYNAMIC_CAST_CCSPRITE dynamic_cast(_barRenderer) @@ -336,4 +339,4 @@ const char* UILoadingBar::getDescription() const return "LoadingBar"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UILoadingBar.h b/cocos/gui/widgets/UILoadingBar.h index 5bf38a203a..02a9e2b5c6 100644 --- a/cocos/gui/widgets/UILoadingBar.h +++ b/cocos/gui/widgets/UILoadingBar.h @@ -25,9 +25,9 @@ #ifndef __UILOADINGBAR_H__ #define __UILOADINGBAR_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { @@ -106,16 +106,16 @@ public: * * @param capInsets capinsets for loadingbar */ - void setCapInsets(const Rect &capInsets); + void setCapInsets(const cocos2d::Rect &capInsets); //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); /** * Returns the "class name" of widget. @@ -130,15 +130,15 @@ protected: LoadingBarType _barType; int _percent; float _totalLength; - Node* _barRenderer; + cocos2d::Node* _barRenderer; TextureResType _renderBarTexType; - Size _barRendererTextureSize; + cocos2d::Size _barRendererTextureSize; bool _scale9Enabled; bool _prevIgnoreSize; - Rect _capInsets; + cocos2d::Rect _capInsets; std::string _textureFile; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UILoadingBar__) */ diff --git a/cocos/gui/widgets/UISlider.cpp b/cocos/gui/widgets/UISlider.cpp index 022646033f..dcadbc2132 100644 --- a/cocos/gui/widgets/UISlider.cpp +++ b/cocos/gui/widgets/UISlider.cpp @@ -23,9 +23,12 @@ ****************************************************************************/ #include "UISlider.h" -#include "../../../GUI/CCControlExtension/CCScale9Sprite.h" +#include "GUI/CCControlExtension/CCScale9Sprite.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; +using namespace cocos2d::extension; + +namespace gui { UISlider::UISlider(): _barRenderer(NULL), @@ -541,4 +544,4 @@ const char* UISlider::getDescription() const return "Slider"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UISlider.h b/cocos/gui/widgets/UISlider.h index 39b912fbe6..6e87dc1f9f 100644 --- a/cocos/gui/widgets/UISlider.h +++ b/cocos/gui/widgets/UISlider.h @@ -25,16 +25,16 @@ #ifndef __UISLIDER_H__ #define __UISLIDER_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { SLIDER_PERCENTCHANGED }SliderEventType; -typedef void (CCObject::*SEL_SlidPercentChangedEvent)(Object*,SliderEventType); +typedef void (cocos2d::CCObject::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); #define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) class UISlider : public UIWidget @@ -76,21 +76,21 @@ public: * * @param capInsets capinsets for slider */ - void setCapInsets(const Rect &capInsets); + void setCapInsets(const cocos2d::Rect &capInsets); /** * Sets capinsets for slider, if slider is using scale9 renderer. * * @param capInsets capinsets for slider */ - void setCapInsetsBarRenderer(const Rect &capInsets); + void setCapInsetsBarRenderer(const cocos2d::Rect &capInsets); /** * Sets capinsets for slider, if slider is using scale9 renderer. * * @param capInsets capinsets for slider */ - void setCapInsetProgressBarRebderer(const Rect &capInsets); + void setCapInsetProgressBarRebderer(const cocos2d::Rect &capInsets); /** * Load textures for slider ball. @@ -158,25 +158,25 @@ public: /** * Add call back function called when slider's percent has changed to slider. */ - void addEventListener(Object* target,SEL_SlidPercentChangedEvent selector); + void addEventListener(cocos2d::Object* target,SEL_SlidPercentChangedEvent selector); //override "onTouchBegan" method of widget. - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); //override "onTouchMoved" method of widget. - virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); //override "onTouchEnded" method of widget. - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); //override "onTouchCancelled" method of widget. - virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); //override "getContentSize" method of widget. - virtual const Size& getContentSize() const; + virtual const cocos2d::Size& getContentSize() const; //override "getVirtualRenderer" method of widget. - virtual Node* getVirtualRenderer(); + virtual cocos2d::Node* getVirtualRenderer(); //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); @@ -196,14 +196,14 @@ protected: void barRendererScaleChangedWithSize(); void progressBarRendererScaleChangedWithSize(); protected: - Node* _barRenderer; - Node* _progressBarRenderer; - Size _progressBarTextureSize; + cocos2d::Node* _barRenderer; + cocos2d::Node* _progressBarRenderer; + cocos2d::Size _progressBarTextureSize; - Sprite* _slidBallNormalRenderer; - Sprite* _slidBallPressedRenderer; - Sprite* _slidBallDisabledRenderer; - Node* _slidBallRenderer; + cocos2d::Sprite* _slidBallNormalRenderer; + cocos2d::Sprite* _slidBallPressedRenderer; + cocos2d::Sprite* _slidBallDisabledRenderer; + cocos2d::Node* _slidBallRenderer; float _barLength; int _percent; @@ -216,10 +216,10 @@ protected: std::string _slidBallPressedTextureFile; std::string _slidBallDisabledTextureFile; - Rect _capInsetsBarRenderer; - Rect _capInsetsProgressBarRenderer; + cocos2d::Rect _capInsetsBarRenderer; + cocos2d::Rect _capInsetsProgressBarRenderer; - Object* _slidPercentListener; + cocos2d::Object* _slidPercentListener; SEL_SlidPercentChangedEvent _slidPercentSelector; TextureResType _barTexType; TextureResType _progressBarTexType; @@ -228,6 +228,6 @@ protected: TextureResType _ballDTexType; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UISlider__) */ diff --git a/cocos/gui/widgets/UITextField.cpp b/cocos/gui/widgets/UITextField.cpp index a3fb9d07c7..f82b3e248c 100644 --- a/cocos/gui/widgets/UITextField.cpp +++ b/cocos/gui/widgets/UITextField.cpp @@ -24,7 +24,9 @@ #include "UITextField.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UICCTextField::UICCTextField() : m_bMaxLengthEnabled(false) @@ -565,4 +567,4 @@ const char* UITextField::getDescription() const return "TextField"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/UITextField.h b/cocos/gui/widgets/UITextField.h index 4a2db5c68a..b5951f056b 100644 --- a/cocos/gui/widgets/UITextField.h +++ b/cocos/gui/widgets/UITextField.h @@ -25,12 +25,12 @@ #ifndef __UITEXTFIELD_H__ #define __UITEXTFIELD_H__ -#include "../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { -class UICCTextField: public TextFieldTTF, public TextFieldDelegate +class UICCTextField: public cocos2d::TextFieldTTF, public cocos2d::TextFieldDelegate { public: UICCTextField(); @@ -42,10 +42,10 @@ public: static UICCTextField* create(const char *placeholder, const char *fontName, float fontSize); // CCTextFieldDelegate - virtual bool onTextFieldAttachWithIME(TextFieldTTF *pSender); - virtual bool onTextFieldDetachWithIME(TextFieldTTF * pSender); - virtual bool onTextFieldInsertText(TextFieldTTF * pSender, const char * text, int nLen); - virtual bool onTextFieldDeleteBackward(TextFieldTTF * pSender, const char * delText, int nLen); + virtual bool onTextFieldAttachWithIME(cocos2d::TextFieldTTF *pSender); + virtual bool onTextFieldDetachWithIME(cocos2d::TextFieldTTF * pSender); + virtual bool onTextFieldInsertText(cocos2d::TextFieldTTF * pSender, const char * text, int nLen); + virtual bool onTextFieldDeleteBackward(cocos2d::TextFieldTTF * pSender, const char * delText, int nLen); void insertText(const char* text, int len); void deleteBackward(); @@ -92,7 +92,7 @@ typedef enum TEXTFIELD_EVENT_DELETE_BACKWARD, }TextFiledEventType; -typedef void (Object::*SEL_TextFieldEvent)(Object*, TextFiledEventType); +typedef void (cocos2d::Object::*SEL_TextFieldEvent)(cocos2d::Object*, TextFiledEventType); #define textfieldeventselector(_SELECTOR) (SEL_TextFieldEvent)(&_SELECTOR) //class UITextField : public UIWidget @@ -104,14 +104,14 @@ public: static UITextField* create(); virtual bool init(); virtual void initRenderer(); - void setTouchSize(const Size &size); + void setTouchSize(const cocos2d::Size &size); void setText(const char* text); void setPlaceHolder(const char* value); void setFontSize(int size); void setFontName(const char* name); virtual void didNotSelectSelf(); const char* getStringValue(); - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); void setMaxLengthEnabled(bool enable); bool isMaxLengthEnabled(); void setMaxLength(int length); @@ -128,9 +128,9 @@ public: void setInsertText(bool insertText); bool getDeleteBackward(); void setDeleteBackward(bool deleteBackward); - void addEventListener(Object* target, SEL_TextFieldEvent selecor); - virtual void setAnchorPoint(const Point &pt); - virtual void setColor(const Color3B &color); + void addEventListener(cocos2d::Object* target, SEL_TextFieldEvent selecor); + virtual void setAnchorPoint(const cocos2d::Point &pt); + virtual void setColor(const cocos2d::Color3B &color); virtual void setOpacity(int opacity); /** * Returns the "class name" of widget. @@ -143,8 +143,8 @@ public: void setMaxLengthEnable(bool is){setMaxLengthEnabled(is);}; void setPasswordEnable(bool is){setPasswordEnabled(is);}; /************/ - virtual const Size& getContentSize() const; - virtual Node* getVirtualRenderer(); + virtual const cocos2d::Size& getContentSize() const; + virtual cocos2d::Node* getVirtualRenderer(); protected: // event void attachWithIMEEvent(); @@ -160,11 +160,11 @@ protected: float _touchHeight; bool _useTouchArea; - Object* _eventListener; + cocos2d::Object* _eventListener; SEL_TextFieldEvent _eventSelector; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UITextField__) */ diff --git a/cocos/gui/widgets/ScrollWidget/UIDragPanel.cpp b/cocos/gui/widgets/scroll-widget/UIDragPanel.cpp similarity index 99% rename from cocos/gui/widgets/ScrollWidget/UIDragPanel.cpp rename to cocos/gui/widgets/scroll-widget/UIDragPanel.cpp index e21d59e1b8..3953d13d0b 100644 --- a/cocos/gui/widgets/ScrollWidget/UIDragPanel.cpp +++ b/cocos/gui/widgets/scroll-widget/UIDragPanel.cpp @@ -23,9 +23,11 @@ ****************************************************************************/ #include "UIDragPanel.h" -#include "../../System/UILayer.h" +#include "system/UILayer.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIDragPanel::UIDragPanel() : _innerContainer(NULL) @@ -1264,4 +1266,4 @@ const char* UIDragPanel::getDescription() const return "DragPanel"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/ScrollWidget/UIDragPanel.h b/cocos/gui/widgets/scroll-widget/UIDragPanel.h similarity index 80% rename from cocos/gui/widgets/ScrollWidget/UIDragPanel.h rename to cocos/gui/widgets/scroll-widget/UIDragPanel.h index dc05b53d21..0402f0e03e 100644 --- a/cocos/gui/widgets/ScrollWidget/UIDragPanel.h +++ b/cocos/gui/widgets/scroll-widget/UIDragPanel.h @@ -25,10 +25,10 @@ #ifndef __UIDRAGPANEL_H__ #define __UIDRAGPANEL_H__ -#include "../../Layouts/Layout.h" +#include "layouts/Layout.h" #include "UIScrollInterface.h" -NS_CC_EXT_BEGIN +namespace gui { /** * drag panel move type @@ -95,7 +95,7 @@ typedef enum /** * dragpanel event */ -typedef void (Object::*SEL_DragPanelEvent)(Object*, DragPanelEventType); +typedef void (cocos2d::Object::*SEL_DragPanelEvent)(cocos2d::Object*, DragPanelEventType); #define dragpaneleventselector(_SELECTOR)(SEL_DragPanelEvent)(&_SELECTOR) class UIDragPanel : public Layout, public UIScrollInterface @@ -106,11 +106,11 @@ public: static UIDragPanel* create(); - virtual bool onTouchBegan(const Point &touchPoint); - virtual void onTouchMoved(const Point &touchPoint); - virtual void onTouchEnded(const Point &touchPoint); - virtual void onTouchCancelled(const Point &touchPoint); - virtual void onTouchLongClicked(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); + virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); virtual void update(float dt); @@ -129,22 +129,22 @@ public: /** * get widget children of inner container */ - virtual Array* getChildren(); + virtual cocos2d::Array* getChildren(); /* gui mark */ /** * get and set inner container size */ - const Size& getInnerContainerSize() const; - void setInnerContainerSize(const Size &size); + const cocos2d::Size& getInnerContainerSize() const; + void setInnerContainerSize(const cocos2d::Size &size); /** * get and set inner container position */ - const Point& getInnerContainerPosition() const; - void setInnerContainerPosition(const Point& point, bool animated); + const cocos2d::Point& getInnerContainerPosition() const; + void setInnerContainerPosition(const cocos2d::Point& point, bool animated); /** * set inner container offset */ - void setInnerContainerOffset(const Point& offset, bool animated); + void setInnerContainerOffset(const cocos2d::Point& offset, bool animated); /**/ // auto move @@ -166,7 +166,7 @@ public: /** * event */ - void addEventListener(Object* target, SEL_DragPanelEvent selector); + void addEventListener(cocos2d::Object* target, SEL_DragPanelEvent selector); /** * get and set bounce enable @@ -221,26 +221,26 @@ protected: virtual void initRenderer(); virtual void releaseResoures(); - virtual void handlePressLogic(const Point &touchPoint); - virtual void handleMoveLogic(const Point &touchPoint); - virtual void handleReleaseLogic(const Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender, const Point &touchPoint); + virtual void handlePressLogic(const cocos2d::Point &touchPoint); + virtual void handleMoveLogic(const cocos2d::Point &touchPoint); + virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint); /* gui mark */ // virtual bool isInScrollDegreeRange(UIWidget* widget); /**/ - virtual void checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint); + virtual void checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint); // void updateWidthAndHeight(); void recordSlidTime(float dt); /* gui mark */ - void setInnerContainerOffset(const Point& offset); + void setInnerContainerOffset(const cocos2d::Point& offset); /**/ // check if dragpanel rect contain inner rect bool checkContainInnerRect(); // move - void moveWithDelta(const Point& delta); + void moveWithDelta(const cocos2d::Point& delta); // auto move void autoMove(); @@ -250,10 +250,10 @@ protected: // berth // check if move to boundary with update - bool checkToBoundaryWithDeltaPosition(const Point& delta); + bool checkToBoundaryWithDeltaPosition(const cocos2d::Point& delta); // calculate to boundary delta - Point calculateToBoundaryDeltaPosition(const Point& paramDelta); + cocos2d::Point calculateToBoundaryDeltaPosition(const cocos2d::Point& paramDelta); // check berth bool checkBerth(); @@ -292,10 +292,10 @@ protected: void actionUpdate(float dt); void actionStop(); void actionDone(); - void moveByWithDuration(float duration, const Point& deltaPosition); + void moveByWithDuration(float duration, const cocos2d::Point& deltaPosition); void moveByInit(); void moveByUpdate(float t); - void moveToWithDuration(float duration, const Point& position); + void moveToWithDuration(float duration, const cocos2d::Point& position); void moveToInit(); void moveToUpdate(float t); virtual void onSizeChanged(); @@ -319,9 +319,9 @@ protected: bool _touchReleased; bool _touchCanceld; // check touch out of drag panel boundary - Point _touchStartNodeSpace; - Point _touchStartWorldSpace; - Point _touchEndWorldSpace; + cocos2d::Point _touchStartNodeSpace; + cocos2d::Point _touchStartWorldSpace; + cocos2d::Point _touchEndWorldSpace; float _slidTime; @@ -333,7 +333,7 @@ protected: float _autoMoveEaseRate; // event - Object* _eventLister; + cocos2d::Object* _eventLister; SEL_DragPanelEvent _eventSelector; // berth @@ -355,13 +355,13 @@ protected: float _elapsed; bool _firstTick; - Point _positionDelta; - Point _startPosition; - Point _previousPosition; + cocos2d::Point _positionDelta; + cocos2d::Point _startPosition; + cocos2d::Point _previousPosition; - Point _endPosition; + cocos2d::Point _endPosition; }; -NS_CC_EXT_END +} #endif /* defined(__TestCpp__UIDragPanel__) */ diff --git a/cocos/gui/widgets/ScrollWidget/UIListView.cpp b/cocos/gui/widgets/scroll-widget/UIListView.cpp similarity index 99% rename from cocos/gui/widgets/ScrollWidget/UIListView.cpp rename to cocos/gui/widgets/scroll-widget/UIListView.cpp index 27775474c5..123146b127 100644 --- a/cocos/gui/widgets/ScrollWidget/UIListView.cpp +++ b/cocos/gui/widgets/scroll-widget/UIListView.cpp @@ -24,7 +24,9 @@ #include "UIListView.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIListView::UIListView() : _direction(LISTVIEW_DIR_VERTICAL) @@ -1455,4 +1457,4 @@ const char* UIListView::getDescription() const } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/ScrollWidget/UIListView.h b/cocos/gui/widgets/scroll-widget/UIListView.h similarity index 84% rename from cocos/gui/widgets/ScrollWidget/UIListView.h rename to cocos/gui/widgets/scroll-widget/UIListView.h index 2bbbae212c..872f591876 100644 --- a/cocos/gui/widgets/ScrollWidget/UIListView.h +++ b/cocos/gui/widgets/scroll-widget/UIListView.h @@ -26,10 +26,10 @@ #define __UILISTVIEW_H__ /* gui mark */ -#include "../../Layouts/Layout.h" +#include "layouts/Layout.h" /**/ -NS_CC_EXT_BEGIN +namespace gui { /** * list view direction @@ -62,7 +62,7 @@ typedef enum /** * list view event */ -typedef void (Object::*SEL_ListViewEvent)(Object*, ListViewEventType); +typedef void (cocos2d::Object::*SEL_ListViewEvent)(cocos2d::Object*, ListViewEventType); #define listvieweventselector(_SELECTOR)(SEL_ListViewEvent)(&_SELECTOR) class UIListView : public Layout @@ -85,11 +85,11 @@ public: */ virtual bool removeChild(UIWidget* child); - virtual bool onTouchBegan(const Point &touchPoint); - virtual void onTouchMoved(const Point &touchPoint); - virtual void onTouchEnded(const Point &touchPoint); - virtual void onTouchCancelled(const Point &touchPoint); - virtual void onTouchLongClicked(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); + virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); /** * set and get direction @@ -155,14 +155,14 @@ protected: virtual void resetProperty(); - virtual void handlePressLogic(const Point &touchPoint); - virtual void handleMoveLogic(const Point &touchPoint); - virtual void handleReleaseLogic(const Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender,const Point &touchPoint); + virtual void handlePressLogic(const cocos2d::Point &touchPoint); + virtual void handleMoveLogic(const cocos2d::Point &touchPoint); + virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); /* gui mark */ // virtual bool isInScrollDegreeRange(UIWidget* widget); /**/ - virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); void moveChildren(float offset); virtual bool scrollChildren(float touchOffset); @@ -212,14 +212,14 @@ protected: bool _bePressed; float _slidTime; - Point _moveChildPoint; + cocos2d::Point _moveChildPoint; float _childFocusCancelOffset; - Object* _eventListener; + cocos2d::Object* _eventListener; SEL_ListViewEvent _eventSelector; - Array* _childPool; - Array* _updatePool; + cocos2d::Array* _childPool; + cocos2d::Array* _updatePool; int _dataLength; int _begin; @@ -228,10 +228,10 @@ protected: int _updateDataIndex; bool _updateSuccess; - Array* _overTopArray; - Array* _overBottomArray; - Array* _overLeftArray; - Array* _overRightArray; + cocos2d::Array* _overTopArray; + cocos2d::Array* _overBottomArray; + cocos2d::Array* _overLeftArray; + cocos2d::Array* _overRightArray; float _disBoundaryToChild_0; float _disBetweenChild; @@ -241,7 +241,7 @@ protected: /**/ }; -NS_CC_EXT_END +} #endif /* defined(__Test__UIListView__) */ diff --git a/cocos/gui/widgets/ScrollWidget/UIPageView.cpp b/cocos/gui/widgets/scroll-widget/UIPageView.cpp similarity index 99% rename from cocos/gui/widgets/ScrollWidget/UIPageView.cpp rename to cocos/gui/widgets/scroll-widget/UIPageView.cpp index 0313820ee7..000a6128c2 100644 --- a/cocos/gui/widgets/ScrollWidget/UIPageView.cpp +++ b/cocos/gui/widgets/scroll-widget/UIPageView.cpp @@ -24,7 +24,9 @@ #include "UIPageView.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIPageView::UIPageView(): _curPageIdx(0), @@ -570,4 +572,4 @@ const char* UIPageView::getDescription() const return "PageView"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/ScrollWidget/UIPageView.h b/cocos/gui/widgets/scroll-widget/UIPageView.h similarity index 84% rename from cocos/gui/widgets/ScrollWidget/UIPageView.h rename to cocos/gui/widgets/scroll-widget/UIPageView.h index 6644ce5cd0..ab19f5e8e5 100644 --- a/cocos/gui/widgets/ScrollWidget/UIPageView.h +++ b/cocos/gui/widgets/scroll-widget/UIPageView.h @@ -25,17 +25,17 @@ #ifndef __UIPAGEVIEW_H__ #define __UIPAGEVIEW_H__ -#include "../../Layouts/Layout.h" +#include "layouts/Layout.h" #include "UIScrollInterface.h" -NS_CC_EXT_BEGIN +namespace gui { typedef enum { PAGEVIEW_EVENT_TURNING, }PageViewEventType; -typedef void (Object::*SEL_PageViewEvent)(Object*, PageViewEventType); +typedef void (cocos2d::Object::*SEL_PageViewEvent)(cocos2d::Object*, PageViewEventType); #define pagevieweventselector(_SELECTOR)(SEL_PageViewEvent)(&_SELECTOR) typedef enum { @@ -116,7 +116,7 @@ public: int getCurPageIndex() const; // event - void addEventListener(Object *target, SEL_PageViewEvent selector); + void addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector); //override "removeChild" method of widget. virtual bool removeChild(UIWidget* widget); @@ -125,16 +125,16 @@ public: virtual void removeAllChildren(); //override "onTouchBegan" method of widget. - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); //override "onTouchMoved" method of widget. - virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); //override "onTouchEnded" method of widget. - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); //override "onTouchCancelled" method of widget. - virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); //override "update" method of widget. virtual void update(float dt); @@ -151,11 +151,11 @@ protected: Layout* createPage(); float getPositionXByIndex(int idx); void updateBoundaryPages(); - virtual void handlePressLogic(const Point &touchPoint); - virtual void handleMoveLogic(const Point &touchPoint); - virtual void handleReleaseLogic(const Point &touchPoint); - virtual void interceptTouchEvent(int handleState, UIWidget* sender, const Point &touchPoint); - virtual void checkChildInfo(int handleState, UIWidget* sender, const Point &touchPoint); + virtual void handlePressLogic(const cocos2d::Point &touchPoint); + virtual void handleMoveLogic(const cocos2d::Point &touchPoint); + virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); + virtual void interceptTouchEvent(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint); + virtual void checkChildInfo(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint); virtual bool scrollPages(float touchOffset); void movePages(float offset); void pageTurningEvent(); @@ -166,12 +166,12 @@ protected: virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; protected: int _curPageIdx; - Array* _pages; + cocos2d::Array* _pages; PVTouchDir _touchMoveDir; float _touchStartLocation; float _touchEndLocation; float _touchMoveStartLocation; - Point _movePagePoint; + cocos2d::Point _movePagePoint; UIWidget* _leftChild; UIWidget* _rightChild; float _leftBoundary; @@ -181,10 +181,10 @@ protected: float _autoScrollSpeed; int _autoScrollDir; float _childFocusCancelOffset; - Object* _eventListener; + cocos2d::Object* _eventListener; SEL_PageViewEvent _eventSelector; }; -NS_CC_EXT_END +} #endif /* defined(__UIPageView__) */ diff --git a/cocos/gui/widgets/ScrollWidget/UIScrollInterface.h b/cocos/gui/widgets/scroll-widget/UIScrollInterface.h similarity index 82% rename from cocos/gui/widgets/ScrollWidget/UIScrollInterface.h rename to cocos/gui/widgets/scroll-widget/UIScrollInterface.h index df8566fc53..ffaa590309 100644 --- a/cocos/gui/widgets/ScrollWidget/UIScrollInterface.h +++ b/cocos/gui/widgets/scroll-widget/UIScrollInterface.h @@ -25,20 +25,20 @@ #ifndef __UISCROLLDELEGATE_H__ #define __UISCROLLDELEGATE_H__ -#include "../../BaseClasses/UIWidget.h" +#include "base-classes/UIWidget.h" -NS_CC_EXT_BEGIN +namespace gui { class UIScrollInterface { protected: - virtual void handlePressLogic(const Point &touchPoint) = 0; - virtual void handleMoveLogic(const Point &touchPoint) = 0; - virtual void handleReleaseLogic(const Point &touchPoint) = 0; - virtual void interceptTouchEvent(int handleState, UIWidget* sender, const Point &touchPoint) = 0; + virtual void handlePressLogic(const cocos2d::Point &touchPoint) = 0; + virtual void handleMoveLogic(const cocos2d::Point &touchPoint) = 0; + virtual void handleReleaseLogic(const cocos2d::Point &touchPoint) = 0; + virtual void interceptTouchEvent(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint) = 0; // virtual bool isInScrollDegreeRange(UIWidget* widget) = 0; }; -NS_CC_EXT_END +} #endif /* defined(__UIScrollDelegate__) */ diff --git a/cocos/gui/widgets/ScrollWidget/UIScrollView.cpp b/cocos/gui/widgets/scroll-widget/UIScrollView.cpp similarity index 99% rename from cocos/gui/widgets/ScrollWidget/UIScrollView.cpp rename to cocos/gui/widgets/scroll-widget/UIScrollView.cpp index 4575c6b832..1de739a0f2 100644 --- a/cocos/gui/widgets/ScrollWidget/UIScrollView.cpp +++ b/cocos/gui/widgets/scroll-widget/UIScrollView.cpp @@ -23,9 +23,11 @@ ****************************************************************************/ #include "UIScrollView.h" -#include "../../System/UILayer.h" +#include "system/UILayer.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace gui { UIScrollView::UIScrollView(): _innerContainer(NULL), @@ -684,4 +686,4 @@ const char* UIScrollView::getDescription() const return "ScrollView"; } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/gui/widgets/ScrollWidget/UIScrollView.h b/cocos/gui/widgets/scroll-widget/UIScrollView.h similarity index 85% rename from cocos/gui/widgets/ScrollWidget/UIScrollView.h rename to cocos/gui/widgets/scroll-widget/UIScrollView.h index ecf56cadd7..30cc8a4f27 100644 --- a/cocos/gui/widgets/ScrollWidget/UIScrollView.h +++ b/cocos/gui/widgets/scroll-widget/UIScrollView.h @@ -25,10 +25,10 @@ #ifndef __UISCROLLVIEW_H__ #define __UISCROLLVIEW_H__ -#include "../../Layouts/Layout.h" +#include "layouts/Layout.h" #include "UIScrollInterface.h" -NS_CC_EXT_BEGIN +namespace gui { enum SCROLLVIEW_DIR { @@ -54,7 +54,7 @@ typedef enum SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, }ScrollviewEventType; -typedef void (Object::*SEL_ScrollViewEvent)(Object*, ScrollviewEventType); +typedef void (cocos2d::Object::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); #define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) @@ -120,7 +120,7 @@ public: * * @param inner container size. */ - void setInnerContainerSize(const Size &size); + void setInnerContainerSize(const cocos2d::Size &size); /** * Gets inner container size of scrollview. @@ -129,12 +129,12 @@ public: * * @return inner container size. */ - const Size& getInnerContainerSize() const; + const cocos2d::Size& getInnerContainerSize() const; /** * Add call back function called scrollview event triggered */ - void addEventListener(Object* target, SEL_ScrollViewEvent selector); + void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); //override "addChild" method of widget. virtual bool addChild(UIWidget* widget); @@ -146,22 +146,22 @@ public: virtual bool removeChild(UIWidget* child); //override "getChildren" method of widget. - virtual Array* getChildren(); + virtual cocos2d::Array* getChildren(); //override "onTouchBegan" method of widget. - virtual bool onTouchBegan(const Point &touchPoint); + virtual bool onTouchBegan(const cocos2d::Point &touchPoint); //override "onTouchMoved" method of widget. - virtual void onTouchMoved(const Point &touchPoint); + virtual void onTouchMoved(const cocos2d::Point &touchPoint); //override "onTouchEnded" method of widget. - virtual void onTouchEnded(const Point &touchPoint); + virtual void onTouchEnded(const cocos2d::Point &touchPoint); //override "onTouchCancelled" method of widget. - virtual void onTouchCancelled(const Point &touchPoint); + virtual void onTouchCancelled(const cocos2d::Point &touchPoint); //override "onTouchLongClicked" method of widget. - virtual void onTouchLongClicked(const Point &touchPoint); + virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); virtual void update(float dt); @@ -200,11 +200,11 @@ protected: virtual bool scrollChildren(float touchOffset); void startRecordSlidAction(); virtual void endRecordSlidAction(); - virtual void handlePressLogic(const Point &touchPoint); - virtual void handleMoveLogic(const Point &touchPoint); - virtual void handleReleaseLogic(const Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender,const Point &touchPoint); - virtual void checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint); + virtual void handlePressLogic(const cocos2d::Point &touchPoint); + virtual void handleMoveLogic(const cocos2d::Point &touchPoint); + virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); + virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); + virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); void recordSlidTime(float dt); //override "releaseResoures" method of widget. virtual void releaseResoures(); @@ -242,14 +242,14 @@ protected: bool _bePressed; float _slidTime; - Point _moveChildPoint; + cocos2d::Point _moveChildPoint; float _childFocusCancelOffset; - Object* _eventListener; + cocos2d::Object* _eventListener; SEL_ScrollViewEvent _eventSelector; }; -NS_CC_EXT_END +} #endif /* defined(__CocoGUI__UIScrollView__) */ diff --git a/cocos/network/Android.mk b/cocos/network/Android.mk new file mode 100644 index 0000000000..c6b158aef4 --- /dev/null +++ b/cocos/network/Android.mk @@ -0,0 +1,28 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := network_static + +LOCAL_MODULE_FILENAME := libnetwork + +LOCAL_SRC_FILES := HttpClient.cpp \ +SocketIO.cpp \ +WebSocket.cpp + + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d + +LOCAL_CFLAGS += -Wno-psabi +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static +LOCAL_WHOLE_STATIC_LIBRARIES += libwebsockets_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,2d) +$(call import-module,curl/prebuilt/android) +$(call import-module, websockets/prebuilt/android) diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 252102fcab..e2ecc1c80c 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -32,7 +32,9 @@ #include "platform/CCFileUtils.h" -NS_CC_EXT_BEGIN + using namespace cocos2d; + +namespace network { static std::mutex s_requestQueueMutex; static std::mutex s_responseQueueMutex; @@ -514,6 +516,6 @@ void HttpClient::dispatchResponseCallbacks(float delta) } -NS_CC_EXT_END +} diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index b41ba226be..919e06f872 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -27,12 +27,12 @@ #define __CCHTTPREQUEST_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "HttpRequest.h" #include "HttpResponse.h" + #include "HttpClient.h" -NS_CC_EXT_BEGIN +namespace network { /** * @addtogroup Network @@ -43,7 +43,7 @@ NS_CC_EXT_BEGIN /** @brief Singleton that handles asynchrounous http requests * Once the request completed, a callback will issued in main thread when it provided during make request */ -class HttpClient : public Object +class HttpClient : public cocos2d::Object { public: /** Return the shared instance **/ @@ -112,6 +112,6 @@ private: // end of Network group /// @} -NS_CC_EXT_END +} #endif //__CCHTTPREQUEST_H__ diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 0bf8d82eb5..273a87b53e 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -26,14 +26,13 @@ #define __HTTP_REQUEST_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" -NS_CC_EXT_BEGIN +namespace network { class HttpClient; class HttpResponse; -typedef void (Object::*SEL_HttpResponse)(HttpClient* client, HttpResponse* response); -#define httpresponse_selector(_SELECTOR) (cocos2d::extension::SEL_HttpResponse)(&_SELECTOR) +typedef void (cocos2d::Object::*SEL_HttpResponse)(HttpClient* client, HttpResponse* response); +#define httpresponse_selector(_SELECTOR) (SEL_HttpResponse)(&_SELECTOR) /** @brief defines the object which users must packed for HttpClient::send(HttpRequest*) method. @@ -41,7 +40,7 @@ typedef void (Object::*SEL_HttpResponse)(HttpClient* client, HttpResponse* respo @since v2.0.2 */ -class HttpRequest : public Object +class HttpRequest : public cocos2d::Object { public: /** Use this enum type as param in setReqeustType(param) */ @@ -81,7 +80,7 @@ public: }; /** Override autorelease method to avoid developers to call it */ - Object* autorelease(void) + cocos2d::Object* autorelease(void) { CCASSERT(false, "HttpResponse is used between network thread and ui thread \ therefore, autorelease is forbidden here"); @@ -163,12 +162,12 @@ public: /** Required field. You should set the callback selector function at ack the http request completed */ - CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(Object* pTarget, SEL_CallFuncND pSelector) + CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(cocos2d::Object* pTarget, cocos2d::SEL_CallFuncND pSelector) { setResponseCallback(pTarget, (SEL_HttpResponse) pSelector); } - inline void setResponseCallback(Object* pTarget, SEL_HttpResponse pSelector) + inline void setResponseCallback(cocos2d::Object* pTarget, SEL_HttpResponse pSelector) { _pTarget = pTarget; _pSelector = pSelector; @@ -179,7 +178,7 @@ public: } } /** Get the target of callback selector funtion, mainly used by HttpClient */ - inline Object* getTarget() + inline cocos2d::Object* getTarget() { return _pTarget; } @@ -192,7 +191,7 @@ public: _prxy( SEL_HttpResponse cb ) :_cb(cb) {} ~_prxy(){}; operator SEL_HttpResponse() const { return _cb; } - CC_DEPRECATED_ATTRIBUTE operator SEL_CallFuncND() const { return (SEL_CallFuncND) _cb; } + CC_DEPRECATED_ATTRIBUTE operator cocos2d::SEL_CallFuncND() const { return (cocos2d::SEL_CallFuncND) _cb; } protected: SEL_HttpResponse _cb; }; @@ -221,12 +220,12 @@ protected: std::string _url; /// target url that this request is sent to std::vector _requestData; /// used for POST std::string _tag; /// user defined tag, to identify different requests in response callback - Object* _pTarget; /// callback target of pSelector function + cocos2d::Object* _pTarget; /// callback target of pSelector function SEL_HttpResponse _pSelector; /// callback function, e.g. MyLayer::onHttpResponse(HttpClient *sender, HttpResponse * response) void* _pUserData; /// You can add your customed data here std::vector _headers; /// custom http headers }; -NS_CC_EXT_END +} #endif //__HTTP_REQUEST_H__ diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 3d6a848a4e..2a16fc4d52 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -26,17 +26,16 @@ #define __HTTP_RESPONSE__ #include "cocos2d.h" -#include "ExtensionMacros.h" #include "HttpRequest.h" -NS_CC_EXT_BEGIN +namespace network { /** @brief defines the object which users will receive at onHttpCompleted(sender, HttpResponse) callback Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample @since v2.0.2 */ -class HttpResponse : public Object +class HttpResponse : public cocos2d::Object { public: /** Constructor, it's used by HttpClient internal, users don't need to create HttpResponse manually @@ -67,7 +66,7 @@ public: } /** Override autorelease method to prevent developers from calling it */ - Object* autorelease(void) + cocos2d::Object* autorelease(void) { CCASSERT(false, "HttpResponse is used between network thread and ui thread \ therefore, autorelease is forbidden here"); @@ -178,6 +177,6 @@ protected: }; -NS_CC_EXT_END +} #endif //__HTTP_RESPONSE_H__ diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index 7510ce8d74..bb9acff3e1 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -28,11 +28,13 @@ ****************************************************************************/ #include "SocketIO.h" -#include "cocos-ext.h" -#include "network/WebSocket.h" +#include "WebSocket.h" +#include "HttpClient.h" #include -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace network { //class declarations @@ -41,7 +43,7 @@ NS_CC_EXT_BEGIN * Clients/endpoints may share the same impl to accomplish multiplexing on the same websocket */ class SIOClientImpl : - public Object, + public cocos2d::Object, public WebSocket::Delegate { private: @@ -51,7 +53,7 @@ private: WebSocket *_ws; - Dictionary* _clients; + cocos2d::Dictionary* _clients; public: SIOClientImpl(const std::string& host, int port); @@ -59,10 +61,10 @@ public: static SIOClientImpl* create(const std::string& host, int port); - virtual void onOpen(cocos2d::extension::WebSocket* ws); - virtual void onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data); - virtual void onClose(cocos2d::extension::WebSocket* ws); - virtual void onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error); + virtual void onOpen(WebSocket* ws); + virtual void onMessage(WebSocket* ws, const WebSocket::Data& data); + virtual void onClose(WebSocket* ws); + virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error); void connect(); void disconnect(); @@ -350,7 +352,7 @@ void SIOClientImpl::emit(std::string endpoint, std::string eventname, std::strin _ws->send(msg); } -void SIOClientImpl::onOpen(cocos2d::extension::WebSocket* ws) +void SIOClientImpl::onOpen(WebSocket* ws) { _connected = true; @@ -370,7 +372,7 @@ void SIOClientImpl::onOpen(cocos2d::extension::WebSocket* ws) log("SIOClientImpl::onOpen socket connected!"); } -void SIOClientImpl::onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data) +void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) { log("SIOClientImpl::onMessage received: %s", data.bytes); @@ -467,7 +469,7 @@ void SIOClientImpl::onMessage(cocos2d::extension::WebSocket* ws, const cocos2d:: return; } -void SIOClientImpl::onClose(cocos2d::extension::WebSocket* ws) +void SIOClientImpl::onClose(WebSocket* ws) { if(_clients->count() > 0) { @@ -484,7 +486,7 @@ void SIOClientImpl::onClose(cocos2d::extension::WebSocket* ws) this->release(); } -void SIOClientImpl::onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error) +void SIOClientImpl::onError(WebSocket* ws, const WebSocket::ErrorCode& error) { } @@ -698,4 +700,4 @@ void SocketIO::removeSocket(const std::string& uri) _sockets->removeObjectForKey(uri); } -NS_CC_EXT_END \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/network/SocketIO.h b/cocos/network/SocketIO.h index 23badd8907..5ec76bcb9b 100644 --- a/cocos/network/SocketIO.h +++ b/cocos/network/SocketIO.h @@ -59,10 +59,9 @@ in the onClose method the pointer should be set to NULL or used to connect to a #ifndef __CC_SOCKETIO_H__ #define __CC_SOCKETIO_H__ -#include "ExtensionMacros.h" #include "cocos2d.h" -NS_CC_EXT_BEGIN +namespace network { //forward declarations class SIOClientImpl; @@ -104,7 +103,7 @@ private: static SocketIO *_inst; - Dictionary* _sockets; + cocos2d::Dictionary* _sockets; SIOClientImpl* getSocket(const std::string& uri); void addSocket(const std::string& uri, SIOClientImpl* socket); @@ -123,7 +122,7 @@ typedef std::map EventRegistry; * @brief A single connection to a socket.io endpoint */ class SIOClient - : public Object + : public cocos2d::Object { private: int _port; @@ -182,6 +181,6 @@ public: }; -NS_CC_EXT_END +} #endif /* defined(__CC_JSB_SOCKETIO_H__) */ diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 46ef29641a..883c1d8554 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -37,7 +37,9 @@ #include "libwebsockets.h" -NS_CC_EXT_BEGIN +using namespace cocos2d; + +namespace network { class WsMessage { @@ -645,4 +647,4 @@ void WebSocket::onUIThreadReceiveMessage(WsMessage* msg) } } -NS_CC_EXT_END +} diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index 8256dc5ebd..da9a497b71 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -30,7 +30,6 @@ #ifndef __CC_WEBSOCKET_H__ #define __CC_WEBSOCKET_H__ -#include "ExtensionMacros.h" #include "cocos2d.h" #include @@ -38,7 +37,7 @@ struct libwebsocket; struct libwebsocket_context; struct libwebsocket_protocols; -NS_CC_EXT_BEGIN +namespace network { class WsThreadHelper; class WsMessage; @@ -162,6 +161,6 @@ private: struct libwebsocket_protocols* _wsProtocols; }; -NS_CC_EXT_END +} #endif /* defined(__CC_JSB_WEBSOCKET_H__) */ diff --git a/cocos/storage/local-storage/Android.mk b/cocos/storage/local-storage/Android.mk new file mode 100644 index 0000000000..67db9c191b --- /dev/null +++ b/cocos/storage/local-storage/Android.mk @@ -0,0 +1,19 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE := localstorage_static + +LOCAL_MODULE_FILENAME := liblocalstorage + +LOCAL_SRC_FILES := LocalStorage.cpp +LocalStorageAndroid.cpp \ + + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d + +LOCAL_CFLAGS += -Wno-psabi +LOCAL_EXPORT_CFLAGS += -Wno-psabi + +include $(BUILD_STATIC_LIBRARY) diff --git a/extensions/Android.mk b/extensions/Android.mk index 6a5bf063d7..ce0ddb9bb8 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -6,7 +6,6 @@ LOCAL_MODULE := cocos_extension_static LOCAL_MODULE_FILENAME := libextension LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/CCDeprecated-ext.cpp \ $(LOCAL_PATH)/assets-manager/AssetsManager.cpp \ $(LOCAL_PATH)/GUI/CCControlExtension/CCControl.cpp \ $(LOCAL_PATH)/GUI/CCControlExtension/CCControlButton.cpp \ @@ -47,15 +46,12 @@ LOCAL_EXPORT_CFLAGS += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/CCBReader \ $(LOCAL_PATH)/GUI/CCControlExtension \ - $(LOCAL_PATH)/GUI/CCScrollView \ - $(LOCAL_PATH)/network \ - $(LOCAL_PATH)/LocalStorage + $(LOCAL_PATH)/GUI/CCScrollView include $(BUILD_STATIC_LIBRARY) -$(call import-module,cocos2dx) +$(call import-module,2d) $(call import-module,audio/android) -$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) -$(call import-module,external/Box2D) -$(call import-module,external/chipmunk) -$(call import-module,external/libwebsockets/android) +$(call import-module,Box2D) +$(call import-module,chipmunk) +$(call import-module,websockets/prebuilt/android) diff --git a/extensions/CCDeprecated-ext.cpp b/extensions/CCDeprecated-ext.cpp deleted file mode 100644 index 383fe7bf00..0000000000 --- a/extensions/CCDeprecated-ext.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "cocos-ext.h" - -NS_CC_EXT_BEGIN - - - -NS_CC_EXT_END diff --git a/extensions/CCDeprecated-ext.h b/extensions/CCDeprecated-ext.h deleted file mode 100644 index 5aded2b4f4..0000000000 --- a/extensions/CCDeprecated-ext.h +++ /dev/null @@ -1,278 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** Add deprecated global functions and variables here - */ - -#ifndef COCOS2D_CCDEPRECATED_EXT_H__ -#define COCOS2D_CCDEPRECATED_EXT_H__ - -NS_CC_EXT_BEGIN - -CC_DEPRECATED_ATTRIBUTE typedef TableView CCTableView; -CC_DEPRECATED_ATTRIBUTE typedef TableViewCell CCTableViewCell; -CC_DEPRECATED_ATTRIBUTE typedef TableViewDelegate CCTableViewDelegate; -CC_DEPRECATED_ATTRIBUTE typedef TableViewDataSource CCTableViewDataSource; -CC_DEPRECATED_ATTRIBUTE typedef TableView CCTableView; -CC_DEPRECATED_ATTRIBUTE typedef ScrollView CCScrollView; -CC_DEPRECATED_ATTRIBUTE typedef ScrollViewDelegate CCScrollViewDelegate; -CC_DEPRECATED_ATTRIBUTE typedef ScrollView CCScrollView; -CC_DEPRECATED_ATTRIBUTE typedef SortableObject CCSortableObject; -CC_DEPRECATED_ATTRIBUTE typedef ArrayForObjectSorting CCArrayForObjectSorting; -CC_DEPRECATED_ATTRIBUTE typedef TableViewCell CCTableViewCell; -CC_DEPRECATED_ATTRIBUTE typedef EditBox CCEditBox; -CC_DEPRECATED_ATTRIBUTE typedef EditBoxDelegate CCEditBoxDelegate; - -CC_DEPRECATED_ATTRIBUTE typedef Color3bObject CCColor3bObject; -CC_DEPRECATED_ATTRIBUTE typedef ControlUtils CCControlUtils; -CC_DEPRECATED_ATTRIBUTE typedef Scale9Sprite CCScale9Sprite; -CC_DEPRECATED_ATTRIBUTE typedef ControlSwitchSprite CCControlSwitchSprite; -CC_DEPRECATED_ATTRIBUTE typedef ControlHuePicker CCControlHuePicker; -CC_DEPRECATED_ATTRIBUTE typedef Invocation CCInvocation; -CC_DEPRECATED_ATTRIBUTE typedef ControlSaturationBrightnessPicker CCControlSaturationBrightnessPicker; -CC_DEPRECATED_ATTRIBUTE typedef ControlStepper CCControlStepper; -CC_DEPRECATED_ATTRIBUTE typedef ControlPotentiometer CCControlPotentiometer; -CC_DEPRECATED_ATTRIBUTE typedef ControlSwitchSprite CCControlSwitchSprite; -CC_DEPRECATED_ATTRIBUTE typedef ControlSwitch CCControlSwitch; -CC_DEPRECATED_ATTRIBUTE typedef ControlButton CCControlButton; -CC_DEPRECATED_ATTRIBUTE typedef ControlSlider CCControlSlider; -CC_DEPRECATED_ATTRIBUTE typedef Control CCControl; -CC_DEPRECATED_ATTRIBUTE typedef ControlLoader CCControlLoader; -CC_DEPRECATED_ATTRIBUTE typedef ControlColourPicker CCControlColourPicker; - -CC_DEPRECATED_ATTRIBUTE typedef LabelBMFontLoader CCLabelBMFontLoader; -CC_DEPRECATED_ATTRIBUTE typedef ScrollViewLoader CCScrollViewLoader; -CC_DEPRECATED_ATTRIBUTE typedef SpriteLoader CCSpriteLoader; -CC_DEPRECATED_ATTRIBUTE typedef NodeLoader CCNodeLoader; -CC_DEPRECATED_ATTRIBUTE typedef NodeLoaderLibrary CCNodeLoaderLibrary; -CC_DEPRECATED_ATTRIBUTE typedef NodeLoaderListener CCNodeLoaderListener; -CC_DEPRECATED_ATTRIBUTE typedef LayerLoader CCLayerLoader; -CC_DEPRECATED_ATTRIBUTE typedef MenuLoader CCMenuLoader; -CC_DEPRECATED_ATTRIBUTE typedef Color3BWapper CCColor3BWapper; -CC_DEPRECATED_ATTRIBUTE typedef ParticleSystemQuadLoader CCParticleSystemQuadLoader; -CC_DEPRECATED_ATTRIBUTE typedef MenuItemImageLoader CCMenuItemImageLoader; -CC_DEPRECATED_ATTRIBUTE typedef ControlButtonLoader CCControlButtonLoader; -CC_DEPRECATED_ATTRIBUTE typedef LayerGradientLoader CCLayerGradientLoader; -CC_DEPRECATED_ATTRIBUTE typedef Scale9SpriteLoader CCScale9SpriteLoader; -CC_DEPRECATED_ATTRIBUTE typedef NodeLoaderLibrary CCNodeLoaderLibrary; -CC_DEPRECATED_ATTRIBUTE typedef MenuItemLoader CCMenuItemLoader; -CC_DEPRECATED_ATTRIBUTE typedef LayerColorLoader CCLayerColorLoader; -CC_DEPRECATED_ATTRIBUTE typedef LabelTTFLoader CCLabelTTFLoader; - - -#if CC_ENABLE_BOX2D_INTEGRATION || CC_ENABLE_CHIPMUNK_INTEGRATION -CC_DEPRECATED_ATTRIBUTE typedef PhysicsSprite CCPhysicsSprite; -#endif - -#if CC_ENABLE_CHIPMUNK_INTEGRATION -CC_DEPRECATED_ATTRIBUTE typedef PhysicsDebugNode CCPhysicsDebugNode; -#endif - -CC_DEPRECATED_ATTRIBUTE typedef ComController CCComController; -CC_DEPRECATED_ATTRIBUTE typedef ComAttribute CCComAttribute; -CC_DEPRECATED_ATTRIBUTE typedef InputDelegate CCInputDelegate; -CC_DEPRECATED_ATTRIBUTE typedef ComAudio CCComAudio; - -CC_DEPRECATED_ATTRIBUTE typedef HttpClient CCHttpClient; -CC_DEPRECATED_ATTRIBUTE typedef HttpResponse CCHttpResponse; -CC_DEPRECATED_ATTRIBUTE typedef HttpRequest CCHttpRequest; -CC_DEPRECATED_ATTRIBUTE typedef Skin CCSkin; - -CC_DEPRECATED_ATTRIBUTE typedef AtlasFormat CCAtlasFormat; -CC_DEPRECATED_ATTRIBUTE typedef AtlasFilter CCAtlasFilter; -CC_DEPRECATED_ATTRIBUTE typedef AtlasWrap CCAtlasWrap; -CC_DEPRECATED_ATTRIBUTE typedef AtlasPage CCAtlasPage; -CC_DEPRECATED_ATTRIBUTE typedef AtlasRegion CCAtlasRegion; -CC_DEPRECATED_ATTRIBUTE typedef Atlas CCAtlas; -CC_DEPRECATED_ATTRIBUTE typedef AnimationStateData CCAnimationStateData; -CC_DEPRECATED_ATTRIBUTE typedef SlotData CCSlotData; -CC_DEPRECATED_ATTRIBUTE typedef AttachmentLoader CCAttachmentLoader; -CC_DEPRECATED_ATTRIBUTE typedef AnimationState CCAnimationState; -CC_DEPRECATED_ATTRIBUTE typedef SkeletonJson CCSkeletonJson; -CC_DEPRECATED_ATTRIBUTE typedef Timeline CCTimeline; -CC_DEPRECATED_ATTRIBUTE typedef CurveTimeline CCCurveTimeline; -CC_DEPRECATED_ATTRIBUTE typedef RotateTimeline CCRotateTimeline; -CC_DEPRECATED_ATTRIBUTE typedef TranslateTimeline CCTranslateTimeline; -CC_DEPRECATED_ATTRIBUTE typedef ScaleTimeline CCScaleTimeline; -CC_DEPRECATED_ATTRIBUTE typedef ColorTimeline CCColorTimeline; -CC_DEPRECATED_ATTRIBUTE typedef AttachmentTimeline CCAttachmentTimeline; -CC_DEPRECATED_ATTRIBUTE typedef AtlasAttachmentLoader CCAtlasAttachmentLoader; -CC_DEPRECATED_ATTRIBUTE typedef VertexIndex CCVertexIndex; -CC_DEPRECATED_ATTRIBUTE typedef RegionAttachment CCRegionAttachment; - -CC_DEPRECATED_ATTRIBUTE typedef NodeLoaderMap CCNodeLoaderMap; -CC_DEPRECATED_ATTRIBUTE typedef NodeLoaderMapEntry CCNodeLoaderMapEntry; -CC_DEPRECATED_ATTRIBUTE typedef EventRegistry CCEventRegistry; -CC_DEPRECATED_ATTRIBUTE typedef AttachmentType CCAttachmentType; - - -CC_DEPRECATED_ATTRIBUTE const ScrollView::Direction kCCScrollViewDirectionNone = ScrollView::Direction::NONE; -CC_DEPRECATED_ATTRIBUTE const ScrollView::Direction kCCScrollViewDirectionHorizontal = ScrollView::Direction::HORIZONTAL; -CC_DEPRECATED_ATTRIBUTE const ScrollView::Direction kCCScrollViewDirectionVertical = ScrollView::Direction::VERTICAL; -CC_DEPRECATED_ATTRIBUTE const ScrollView::Direction kCCScrollViewDirectionBoth = ScrollView::Direction::BOTH; -CC_DEPRECATED_ATTRIBUTE typedef ScrollView::Direction CCScrollViewDirection; - -CC_DEPRECATED_ATTRIBUTE const TableView::VerticalFillOrder kCCTableViewFillTopDown = TableView::VerticalFillOrder::TOP_DOWN; -CC_DEPRECATED_ATTRIBUTE const TableView::VerticalFillOrder kCCTableViewFillBottomUp = TableView::VerticalFillOrder::BOTTOM_UP; -CC_DEPRECATED_ATTRIBUTE typedef TableView::VerticalFillOrder CCTableViewVerticalFillOrder; - -CC_DEPRECATED_ATTRIBUTE const EditBox::KeyboardReturnType kKeyboardReturnTypeDefault = EditBox::KeyboardReturnType::DEFAULT; -CC_DEPRECATED_ATTRIBUTE const EditBox::KeyboardReturnType kKeyboardReturnTypeDone = EditBox::KeyboardReturnType::DONE; -CC_DEPRECATED_ATTRIBUTE const EditBox::KeyboardReturnType kKeyboardReturnTypeSend = EditBox::KeyboardReturnType::SEND; -CC_DEPRECATED_ATTRIBUTE const EditBox::KeyboardReturnType kKeyboardReturnTypeSearch = EditBox::KeyboardReturnType::SEARCH; -CC_DEPRECATED_ATTRIBUTE const EditBox::KeyboardReturnType kKeyboardReturnTypeGo = EditBox::KeyboardReturnType::GO; - -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeAny = EditBox::InputMode::ANY; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeEmailAddr = EditBox::InputMode::EMAIL_ADDRESS; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeNumeric = EditBox::InputMode::NUMERIC; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModePhoneNumber = EditBox::InputMode::PHONE_NUMBER; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeUrl = EditBox::InputMode::URL; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeDecimal = EditBox::InputMode::DECIMAL; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputMode kEditBoxInputModeSingleLine = EditBox::InputMode::SINGLE_LINE; - -CC_DEPRECATED_ATTRIBUTE const EditBox::InputFlag kEditBoxInputFlagPassword = EditBox::InputFlag::PASSWORD; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputFlag kEditBoxInputFlagSensitive = EditBox::InputFlag::SENSITIVE; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputFlag kEditBoxInputFlagInitialCapsWord = EditBox::InputFlag::INITIAL_CAPS_WORD; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputFlag kEditBoxInputFlagInitialCapsSentence = EditBox::InputFlag::INITIAL_CAPS_SENTENCE; -CC_DEPRECATED_ATTRIBUTE const EditBox::InputFlag kEditBoxInputFlagInitialCapsAllCharacters = EditBox::InputFlag::INTIAL_CAPS_ALL_CHARACTERS; - -CC_DEPRECATED_ATTRIBUTE typedef EditBox::KeyboardReturnType KeyboardReturnType; -CC_DEPRECATED_ATTRIBUTE typedef EditBox::InputMode EditBoxInputMode; -CC_DEPRECATED_ATTRIBUTE typedef EditBox::InputFlag EditBoxInputFlag; - -CC_DEPRECATED_ATTRIBUTE typedef ControlStepper::Part ControlStepperPart; -CC_DEPRECATED_ATTRIBUTE const ControlStepper::Part kCCControlStepperPartMinus = ControlStepper::Part::MINUS; -CC_DEPRECATED_ATTRIBUTE const ControlStepper::Part kCCControlStepperPartPlus = ControlStepper::Part::PLUS; -CC_DEPRECATED_ATTRIBUTE const ControlStepper::Part kCCControlStepperPartNone = ControlStepper::Part::NONE; - -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchDown = Control::EventType::TOUCH_DOWN; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchDragInside = Control::EventType::DRAG_INSIDE; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchDragOutside = Control::EventType::DRAG_OUTSIDE; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchDragEnter = Control::EventType::DRAG_ENTER; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchDragExit = Control::EventType::DRAG_EXIT; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchUpInside = Control::EventType::TOUCH_UP_INSIDE; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchUpOutside = Control::EventType::TOUCH_UP_OUTSIDE; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventTouchCancel = Control::EventType::TOUCH_CANCEL; -CC_DEPRECATED_ATTRIBUTE const Control::EventType CCControlEventValueChanged = Control::EventType::VALUE_CHANGED; - -CC_DEPRECATED_ATTRIBUTE typedef Control::EventType CCControlEvent; - -CC_DEPRECATED_ATTRIBUTE const Control::State CCControlStateNormal = Control::State::NORMAL; -CC_DEPRECATED_ATTRIBUTE const Control::State CCControlStateHighlighted = Control::State::HIGH_LIGHTED; -CC_DEPRECATED_ATTRIBUTE const Control::State CCControlStateDisabled = Control::State::DISABLED; -CC_DEPRECATED_ATTRIBUTE const Control::State CCControlStateSelected = Control::State::SELECTED; -CC_DEPRECATED_ATTRIBUTE typedef Control::State CCControlState; - -CC_DEPRECATED_ATTRIBUTE typedef Control::Handler SEL_CCControlHandler; - -// For CCBReader - -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kIntValue = CCBValue::Type::INT; -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kFloatValue = CCBValue::Type::FLOAT; -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kBoolValue = CCBValue::Type::BOOL; -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kUnsignedCharValue = CCBValue::Type::UNSIGNED_CHAR; -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kStringValue = CCBValue::Type::STRING; -CC_DEPRECATED_ATTRIBUTE const CCBValue::Type kArrayValue = CCBValue::Type::ARRAY; - - -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypePosition = CCBReader::PropertyType::POSITION; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeSize = CCBReader::PropertyType::SIZE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypePoint = CCBReader::PropertyType::POINT; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypePointLock = CCBReader::PropertyType::POINT_LOCK; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeScaleLock = CCBReader::PropertyType::SCALE_LOCK; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeDegrees = CCBReader::PropertyType::DEGREES; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeInteger = CCBReader::PropertyType::INTEGER; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFloat = CCBReader::PropertyType::FLOAT; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFloatVar = CCBReader::PropertyType::FLOAT_VAR; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeCheck = CCBReader::PropertyType::CHECK; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeSpriteFrame = CCBReader::PropertyType::SPRITEFRAME; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeTexture = CCBReader::PropertyType::TEXTURE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeByte = CCBReader::PropertyType::BYTE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeColor3 = CCBReader::PropertyType::COLOR3; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeColor4FVar = CCBReader::PropertyType::COLOR4F_VAR; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFlip = CCBReader::PropertyType::FLIP; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeBlendmode = CCBReader::PropertyType::BLEND_MODE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFntFile = CCBReader::PropertyType::FNT_FILE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeText = CCBReader::PropertyType::TEXT; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFontTTF = CCBReader::PropertyType::FONT_TTF; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeIntegerLabeled = CCBReader::PropertyType::INTEGER_LABELED; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeBlock = CCBReader::PropertyType::BLOCK; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeAnimation = CCBReader::PropertyType::ANIMATION; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeCCBFile = CCBReader::PropertyType::CCB_FILE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeString = CCBReader::PropertyType::STRING; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeBlockCCControl = CCBReader::PropertyType::BLOCK_CONTROL; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFloatScale = CCBReader::PropertyType::FLOAT_SCALE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PropertyType kCCBPropTypeFloatXY = CCBReader::PropertyType::FLOAT_XY; - -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloat0 = CCBReader::FloatType::_0; -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloat1 = CCBReader::FloatType::_1; -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloatMinus1 = CCBReader::FloatType::MINUS1; -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloat05 = CCBReader::FloatType::_05; -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloatInteger = CCBReader::FloatType::INTEGER; -CC_DEPRECATED_ATTRIBUTE const CCBReader::FloatType kCCBFloatFull = CCBReader::FloatType::FULL; - -CC_DEPRECATED_ATTRIBUTE const CCBReader::PlatformType kCCBPlatformAll = CCBReader::PlatformType::ALL; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PlatformType kCCBPlatformIOS = CCBReader::PlatformType::IOS; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PlatformType kCCBPlatformMac = CCBReader::PlatformType::MAC; - -CC_DEPRECATED_ATTRIBUTE const CCBReader::TargetType kCCBTargetTypeNone = CCBReader::TargetType::NONE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::TargetType kCCBTargetTypeDocumentRoot = CCBReader::TargetType::DOCUMENT_ROOT; -CC_DEPRECATED_ATTRIBUTE const CCBReader::TargetType kCCBTargetTypeOwner = CCBReader::TargetType::OWNER; - -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingInstant = CCBKeyframe::EasingType::INSTANT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingLinear = CCBKeyframe::EasingType::LINEAR ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingCubicIn = CCBKeyframe::EasingType::CUBIC_IN ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingCubicOut = CCBKeyframe::EasingType::CUBIC_OUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingCubicInOut = CCBKeyframe::EasingType::CUBIC_INOUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingElasticIn = CCBKeyframe::EasingType::ELASTIC_IN ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingElasticOut = CCBKeyframe::EasingType::ELASTIC_OUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingElasticInOut = CCBKeyframe::EasingType::ELASTIC_INOUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBounceIn = CCBKeyframe::EasingType::BOUNCE_IN ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBounceOut = CCBKeyframe::EasingType::BOUNCE_OUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBounceInOut = CCBKeyframe::EasingType::BOUNCE_INOUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBackIn = CCBKeyframe::EasingType::BACK_IN ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBackOut = CCBKeyframe::EasingType::BACK_OUT ; -CC_DEPRECATED_ATTRIBUTE const CCBKeyframe::EasingType kCCBKeyframeEasingBackInOut = CCBKeyframe::EasingType::BACK_INOUT ; - -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypeRelativeBottomLeft = CCBReader::PositionType::RELATIVE_BOTTOM_LEFT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypeRelativeTopLeft = CCBReader::PositionType::RELATIVE_TOP_LEFT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypeRelativeTopRight = CCBReader::PositionType::RELATIVE_TOP_RIGHT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypeRelativeBottomRight = CCBReader::PositionType::RELATIVE_BOTTOM_RIGHT; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypePercent = CCBReader::PositionType::PERCENT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::PositionType kCCBPositionTypeMultiplyResolution = CCBReader::PositionType::MULTIPLY_RESOLUTION ; -; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypeAbsolute = CCBReader::SizeType::ABSOLUTE ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypePercent = CCBReader::SizeType::PERCENT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypeRelativeContainer = CCBReader::SizeType::RELATIVE_CONTAINER ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypeHorizontalPercent = CCBReader::SizeType::HORIZONTAL_PERCENT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypeVerticalPercent = CCBReader::SizeType::VERTICAL_PERCENT ; -CC_DEPRECATED_ATTRIBUTE const CCBReader::SizeType kCCBSizeTypeMultiplyResolution = CCBReader::SizeType::MULTIPLY_RESOLUTION; - - -CC_DEPRECATED_ATTRIBUTE const CCBReader::ScaleType kCCBScaleTypeAbsolute = CCBReader::ScaleType::ABSOLUTE; -CC_DEPRECATED_ATTRIBUTE const CCBReader::ScaleType kCCBScaleTypeMultiplyResolution = CCBReader::ScaleType::MULTIPLY_RESOLUTION; - -NS_CC_EXT_END - -#endif // COCOS2D_CCDEPRECATED_EXT_H__ diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 6ead6baf9d..d12859b703 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -29,11 +29,11 @@ #include "CCControl.h" #include "CCDirector.h" -#include "menu_nodes/CCMenu.h" -#include "event_dispatcher/CCTouch.h" +#include "CCMenu.h" +#include "CCTouch.h" #include "CCInvocation.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEventListenerTouch.h" +#include "CCEventDispatcher.h" +#include "CCEventListenerTouch.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 247634a72c..4f889f7066 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -27,10 +27,10 @@ #include "CCControlButton.h" #include "CCScale9Sprite.h" -#include "label_nodes/CCLabelTTF.h" -#include "label_nodes/CCLabelBMFont.h" -#include "actions/CCAction.h" -#include "actions/CCActionInterval.h" +#include "CCLabelTTF.h" +#include "CCLabelBMFont.h" +#include "CCAction.h" +#include "CCActionInterval.h" using namespace std; diff --git a/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp b/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp index 26d7bbf694..18da7f0abf 100644 --- a/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp +++ b/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp @@ -30,8 +30,8 @@ */ #include "CCControlColourPicker.h" -#include "sprite_nodes/CCSpriteFrameCache.h" -#include "sprite_nodes/CCSpriteBatchNode.h" +#include "CCSpriteFrameCache.h" +#include "CCSpriteBatchNode.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlSlider.cpp b/extensions/GUI/CCControlExtension/CCControlSlider.cpp index 80840c4482..1ba96962b6 100644 --- a/extensions/GUI/CCControlExtension/CCControlSlider.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSlider.cpp @@ -28,7 +28,7 @@ */ #include "CCControlSlider.h" -#include "event_dispatcher/CCTouch.h" +#include "CCTouch.h" #include "CCDirector.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlUtils.h b/extensions/GUI/CCControlExtension/CCControlUtils.h index 6520cf9a4a..8739883f0c 100644 --- a/extensions/GUI/CCControlExtension/CCControlUtils.h +++ b/extensions/GUI/CCControlExtension/CCControlUtils.h @@ -34,7 +34,7 @@ #ifndef __CCCONTROL_UTILS_H__ #define __CCCONTROL_UTILS_H__ -#include "sprite_nodes/CCSprite.h" +#include "CCSprite.h" #include "../../ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCInvocation.h b/extensions/GUI/CCControlExtension/CCInvocation.h index 36b64850e2..215f2b1ebd 100644 --- a/extensions/GUI/CCControlExtension/CCInvocation.h +++ b/extensions/GUI/CCControlExtension/CCInvocation.h @@ -30,7 +30,7 @@ #ifndef __CCINVOCATION_H__ #define __CCINVOCATION_H__ -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "../../ExtensionMacros.h" #include "CCControl.h" diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp index a9c6e522a8..fd9d80f32c 100644 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "CCSorting.h" -#include "support/data_support/ccCArray.h" +#include "ccCArray.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h index 4e41f6e238..eca6fafc4a 100644 --- a/extensions/GUI/CCScrollView/CCSorting.h +++ b/extensions/GUI/CCScrollView/CCSorting.h @@ -26,7 +26,7 @@ #ifndef __CCSORTING_H__ #define __CCSORTING_H__ -#include "cocoa/CCArray.h" +#include "CCArray.h" #include "ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index 55c803ffd9..b7ce17b1c3 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -26,9 +26,9 @@ #include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" -#include "menu_nodes/CCMenu.h" +#include "CCMenu.h" #include "CCSorting.h" -#include "layers_scenes_transitions_nodes/CCLayer.h" +#include "CCLayer.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.cpp b/extensions/GUI/CCScrollView/CCTableViewCell.cpp index 3bab98917e..936dccb450 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.cpp +++ b/extensions/GUI/CCScrollView/CCTableViewCell.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "CCTableViewCell.h" -#include "support/data_support/ccCArray.h" +#include "ccCArray.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 3d5d6f2139..bef117d3b9 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -26,7 +26,7 @@ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ -#include "base_nodes/CCNode.h" +#include "CCNode.h" #include "CCSorting.h" NS_CC_EXT_BEGIN diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 3dbbc80fdc..31795c4f39 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -38,7 +38,7 @@ #endif -#include "support/zip_support/unzip.h" +#include "unzip.h" using namespace cocos2d; using namespace std; diff --git a/extensions/cocos-ext.h b/extensions/cocos-ext.h index de56b38f0e..8c3f242643 100644 --- a/extensions/cocos-ext.h +++ b/extensions/cocos-ext.h @@ -3,84 +3,18 @@ #include "ExtensionMacros.h" -#include "CCBReader/CCBFileLoader.h" -#include "CCBReader/CCBMemberVariableAssigner.h" -#include "CCBReader/CCBReader.h" -#include "CCBReader/CCBSelectorResolver.h" -#include "CCBReader/CCControlButtonLoader.h" -#include "CCBReader/CCControlLoader.h" -#include "CCBReader/CCLabelBMFontLoader.h" -#include "CCBReader/CCLabelTTFLoader.h" -#include "CCBReader/CCLayerColorLoader.h" -#include "CCBReader/CCLayerGradientLoader.h" -#include "CCBReader/CCLayerLoader.h" -#include "CCBReader/CCMenuItemImageLoader.h" -#include "CCBReader/CCMenuItemLoader.h" -#include "CCBReader/CCMenuLoader.h" -#include "CCBReader/CCNodeLoader.h" -#include "CCBReader/CCNodeLoaderLibrary.h" -#include "CCBReader/CCNodeLoaderListener.h" -#include "CCBReader/CCParticleSystemQuadLoader.h" -#include "CCBReader/CCScale9SpriteLoader.h" -#include "CCBReader/CCScrollViewLoader.h" -#include "CCBReader/CCSpriteLoader.h" -#include "CCBReader/CCBAnimationManager.h" -#include "CCBReader/CCBKeyframe.h" -#include "CCBReader/CCBSequence.h" -#include "CCBReader/CCBSequenceProperty.h" -#include "CCBReader/CCBValue.h" -#include "CCBReader/CCNode+CCBRelativePositioning.h" #include "GUI/CCControlExtension/CCControlExtensions.h" #include "GUI/CCScrollView/CCScrollView.h" #include "GUI/CCScrollView/CCTableView.h" #include "GUI/CCEditBox/CCEditBox.h" -#include "network/HttpRequest.h" -#include "network/HttpResponse.h" -#include "network/HttpClient.h" -#include "network/WebSocket.h" -#include "network/SocketIO.h" - // Physics integration #if CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION -#include "physics_nodes/CCPhysicsDebugNode.h" -#include "physics_nodes/CCPhysicsSprite.h" +#include "physics-nodes/CCPhysicsDebugNode.h" +#include "physics-nodes/CCPhysicsSprite.h" #endif -#include "spine/spine-cocos2dx.h" - -#include "CocoStudio/Armature/CCArmature.h" -#include "CocoStudio/Armature/CCBone.h" -#include "CocoStudio/Armature/animation/CCArmatureAnimation.h" -#include "CocoStudio/Armature/datas/CCDatas.h" -#include "CocoStudio/Armature/display/CCBatchNode.h" -#include "CocoStudio/Armature/display/CCDecorativeDisplay.h" -#include "CocoStudio/Armature/display/CCDisplayManager.h" -#include "CocoStudio/Armature/display/CCSkin.h" -#include "CocoStudio/Armature/physics/CCColliderDetector.h" -#include "CocoStudio/Armature/utils/CCArmatureDataManager.h" -#include "CocoStudio/Armature/utils/CCDataReaderHelper.h" -#include "CocoStudio/Armature/utils/CCTweenFunction.h" -#include "CocoStudio/Armature/utils/CCArmatureDataManager.h" - -#include "CocoStudio/Components/CCComAttribute.h" -#include "CocoStudio/Components/CCComAudio.h" -#include "CocoStudio/Components/CCComController.h" -#include "CocoStudio/Components/CCComRender.h" - -#include "CocoStudio/GUI/System/CocosGUI.h" - -#include "CocoStudio/Json/CSContentJsonDictionary.h" -#include "CocoStudio/Json/DictionaryHelper.h" - -#include "CocoStudio/Reader/CCSSceneReader.h" -#include "CocoStudio/Reader/CCSGUIReader.h" - -#include "CocoStudio/Action/CCActionManagerEx.h" - -#include "CCDeprecated-ext.h" - -#include "AssetsManager/AssetsManager.h" +#include "assets-manager/AssetsManager.h" #endif /* __COCOS2D_EXT_H__ */ diff --git a/extensions/physics-nodes/CCPhysicsDebugNode.cpp b/extensions/physics-nodes/CCPhysicsDebugNode.cpp index 40c2c7d4ea..357092b62f 100644 --- a/extensions/physics-nodes/CCPhysicsDebugNode.cpp +++ b/extensions/physics-nodes/CCPhysicsDebugNode.cpp @@ -24,7 +24,7 @@ #if CC_ENABLE_CHIPMUNK_INTEGRATION #include "ccTypes.h" -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" #include #include diff --git a/external/curl/include/android/curl.h b/external/curl/include/android/curl/curl.h similarity index 100% rename from external/curl/include/android/curl.h rename to external/curl/include/android/curl/curl.h diff --git a/external/curl/include/android/curlbuild.h b/external/curl/include/android/curl/curlbuild.h similarity index 100% rename from external/curl/include/android/curlbuild.h rename to external/curl/include/android/curl/curlbuild.h diff --git a/external/curl/include/android/curlrules.h b/external/curl/include/android/curl/curlrules.h similarity index 100% rename from external/curl/include/android/curlrules.h rename to external/curl/include/android/curl/curlrules.h diff --git a/external/curl/include/android/curlver.h b/external/curl/include/android/curl/curlver.h similarity index 100% rename from external/curl/include/android/curlver.h rename to external/curl/include/android/curl/curlver.h diff --git a/external/curl/include/android/easy.h b/external/curl/include/android/curl/easy.h similarity index 100% rename from external/curl/include/android/easy.h rename to external/curl/include/android/curl/easy.h diff --git a/external/curl/include/android/mprintf.h b/external/curl/include/android/curl/mprintf.h similarity index 100% rename from external/curl/include/android/mprintf.h rename to external/curl/include/android/curl/mprintf.h diff --git a/external/curl/include/android/multi.h b/external/curl/include/android/curl/multi.h similarity index 100% rename from external/curl/include/android/multi.h rename to external/curl/include/android/curl/multi.h diff --git a/external/curl/include/android/stdcheaders.h b/external/curl/include/android/curl/stdcheaders.h similarity index 100% rename from external/curl/include/android/stdcheaders.h rename to external/curl/include/android/curl/stdcheaders.h diff --git a/external/curl/include/android/typecheck-gcc.h b/external/curl/include/android/curl/typecheck-gcc.h similarity index 100% rename from external/curl/include/android/typecheck-gcc.h rename to external/curl/include/android/curl/typecheck-gcc.h diff --git a/external/curl/include/android/types.h b/external/curl/include/android/curl/types.h similarity index 100% rename from external/curl/include/android/types.h rename to external/curl/include/android/curl/types.h diff --git a/external/curl/include/ios/curl.h b/external/curl/include/ios/curl/curl.h similarity index 100% rename from external/curl/include/ios/curl.h rename to external/curl/include/ios/curl/curl.h diff --git a/external/curl/include/ios/curlbuild.h b/external/curl/include/ios/curl/curlbuild.h similarity index 100% rename from external/curl/include/ios/curlbuild.h rename to external/curl/include/ios/curl/curlbuild.h diff --git a/external/curl/include/ios/curlrules.h b/external/curl/include/ios/curl/curlrules.h similarity index 100% rename from external/curl/include/ios/curlrules.h rename to external/curl/include/ios/curl/curlrules.h diff --git a/external/curl/include/ios/curlver.h b/external/curl/include/ios/curl/curlver.h similarity index 100% rename from external/curl/include/ios/curlver.h rename to external/curl/include/ios/curl/curlver.h diff --git a/external/curl/include/ios/easy.h b/external/curl/include/ios/curl/easy.h similarity index 100% rename from external/curl/include/ios/easy.h rename to external/curl/include/ios/curl/easy.h diff --git a/external/curl/include/ios/mprintf.h b/external/curl/include/ios/curl/mprintf.h similarity index 100% rename from external/curl/include/ios/mprintf.h rename to external/curl/include/ios/curl/mprintf.h diff --git a/external/curl/include/ios/multi.h b/external/curl/include/ios/curl/multi.h similarity index 100% rename from external/curl/include/ios/multi.h rename to external/curl/include/ios/curl/multi.h diff --git a/external/curl/include/ios/stdcheaders.h b/external/curl/include/ios/curl/stdcheaders.h similarity index 100% rename from external/curl/include/ios/stdcheaders.h rename to external/curl/include/ios/curl/stdcheaders.h diff --git a/external/curl/include/ios/typecheck-gcc.h b/external/curl/include/ios/curl/typecheck-gcc.h similarity index 100% rename from external/curl/include/ios/typecheck-gcc.h rename to external/curl/include/ios/curl/typecheck-gcc.h diff --git a/external/curl/include/linux/32-bit/curl.h b/external/curl/include/linux/32-bit/curl/curl.h similarity index 100% rename from external/curl/include/linux/32-bit/curl.h rename to external/curl/include/linux/32-bit/curl/curl.h diff --git a/external/curl/include/linux/32-bit/curlbuild.h b/external/curl/include/linux/32-bit/curl/curlbuild.h similarity index 100% rename from external/curl/include/linux/32-bit/curlbuild.h rename to external/curl/include/linux/32-bit/curl/curlbuild.h diff --git a/external/curl/include/linux/32-bit/curlrules.h b/external/curl/include/linux/32-bit/curl/curlrules.h similarity index 100% rename from external/curl/include/linux/32-bit/curlrules.h rename to external/curl/include/linux/32-bit/curl/curlrules.h diff --git a/external/curl/include/linux/32-bit/curlver.h b/external/curl/include/linux/32-bit/curl/curlver.h similarity index 100% rename from external/curl/include/linux/32-bit/curlver.h rename to external/curl/include/linux/32-bit/curl/curlver.h diff --git a/external/curl/include/linux/32-bit/easy.h b/external/curl/include/linux/32-bit/curl/easy.h similarity index 100% rename from external/curl/include/linux/32-bit/easy.h rename to external/curl/include/linux/32-bit/curl/easy.h diff --git a/external/curl/include/linux/32-bit/mprintf.h b/external/curl/include/linux/32-bit/curl/mprintf.h similarity index 100% rename from external/curl/include/linux/32-bit/mprintf.h rename to external/curl/include/linux/32-bit/curl/mprintf.h diff --git a/external/curl/include/linux/32-bit/multi.h b/external/curl/include/linux/32-bit/curl/multi.h similarity index 100% rename from external/curl/include/linux/32-bit/multi.h rename to external/curl/include/linux/32-bit/curl/multi.h diff --git a/external/curl/include/linux/32-bit/stdcheaders.h b/external/curl/include/linux/32-bit/curl/stdcheaders.h similarity index 100% rename from external/curl/include/linux/32-bit/stdcheaders.h rename to external/curl/include/linux/32-bit/curl/stdcheaders.h diff --git a/external/curl/include/linux/32-bit/typecheck-gcc.h b/external/curl/include/linux/32-bit/curl/typecheck-gcc.h similarity index 100% rename from external/curl/include/linux/32-bit/typecheck-gcc.h rename to external/curl/include/linux/32-bit/curl/typecheck-gcc.h diff --git a/external/curl/include/linux/64-bit/curl.h b/external/curl/include/linux/64-bit/curl/curl.h similarity index 100% rename from external/curl/include/linux/64-bit/curl.h rename to external/curl/include/linux/64-bit/curl/curl.h diff --git a/external/curl/include/linux/64-bit/curlbuild.h b/external/curl/include/linux/64-bit/curl/curlbuild.h similarity index 100% rename from external/curl/include/linux/64-bit/curlbuild.h rename to external/curl/include/linux/64-bit/curl/curlbuild.h diff --git a/external/curl/include/linux/64-bit/curlrules.h b/external/curl/include/linux/64-bit/curl/curlrules.h similarity index 100% rename from external/curl/include/linux/64-bit/curlrules.h rename to external/curl/include/linux/64-bit/curl/curlrules.h diff --git a/external/curl/include/linux/64-bit/curlver.h b/external/curl/include/linux/64-bit/curl/curlver.h similarity index 100% rename from external/curl/include/linux/64-bit/curlver.h rename to external/curl/include/linux/64-bit/curl/curlver.h diff --git a/external/curl/include/linux/64-bit/easy.h b/external/curl/include/linux/64-bit/curl/easy.h similarity index 100% rename from external/curl/include/linux/64-bit/easy.h rename to external/curl/include/linux/64-bit/curl/easy.h diff --git a/external/curl/include/linux/64-bit/mprintf.h b/external/curl/include/linux/64-bit/curl/mprintf.h similarity index 100% rename from external/curl/include/linux/64-bit/mprintf.h rename to external/curl/include/linux/64-bit/curl/mprintf.h diff --git a/external/curl/include/linux/64-bit/multi.h b/external/curl/include/linux/64-bit/curl/multi.h similarity index 100% rename from external/curl/include/linux/64-bit/multi.h rename to external/curl/include/linux/64-bit/curl/multi.h diff --git a/external/curl/include/linux/64-bit/stdcheaders.h b/external/curl/include/linux/64-bit/curl/stdcheaders.h similarity index 100% rename from external/curl/include/linux/64-bit/stdcheaders.h rename to external/curl/include/linux/64-bit/curl/stdcheaders.h diff --git a/external/curl/include/win32/curl.h b/external/curl/include/win32/curl/curl.h similarity index 100% rename from external/curl/include/win32/curl.h rename to external/curl/include/win32/curl/curl.h diff --git a/external/curl/include/win32/curlbuild.h b/external/curl/include/win32/curl/curlbuild.h similarity index 100% rename from external/curl/include/win32/curlbuild.h rename to external/curl/include/win32/curl/curlbuild.h diff --git a/external/curl/include/win32/curlrules.h b/external/curl/include/win32/curl/curlrules.h similarity index 100% rename from external/curl/include/win32/curlrules.h rename to external/curl/include/win32/curl/curlrules.h diff --git a/external/curl/include/win32/curlver.h b/external/curl/include/win32/curl/curlver.h similarity index 100% rename from external/curl/include/win32/curlver.h rename to external/curl/include/win32/curl/curlver.h diff --git a/external/curl/include/win32/easy.h b/external/curl/include/win32/curl/easy.h similarity index 100% rename from external/curl/include/win32/easy.h rename to external/curl/include/win32/curl/easy.h diff --git a/external/curl/include/win32/mprintf.h b/external/curl/include/win32/curl/mprintf.h similarity index 100% rename from external/curl/include/win32/mprintf.h rename to external/curl/include/win32/curl/mprintf.h diff --git a/external/curl/include/win32/multi.h b/external/curl/include/win32/curl/multi.h similarity index 100% rename from external/curl/include/win32/multi.h rename to external/curl/include/win32/curl/multi.h diff --git a/external/curl/include/win32/stdcheaders.h b/external/curl/include/win32/curl/stdcheaders.h similarity index 100% rename from external/curl/include/win32/stdcheaders.h rename to external/curl/include/win32/curl/stdcheaders.h diff --git a/external/curl/include/win32/typecheck-gcc.h b/external/curl/include/win32/curl/typecheck-gcc.h similarity index 100% rename from external/curl/include/win32/typecheck-gcc.h rename to external/curl/include/win32/curl/typecheck-gcc.h diff --git a/external/jsoncpp/autolink.h b/external/json/autolink.h similarity index 65% rename from external/jsoncpp/autolink.h rename to external/json/autolink.h index 02328d1f1a..37c9258ed5 100644 --- a/external/jsoncpp/autolink.h +++ b/external/json/autolink.h @@ -1,8 +1,3 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef JSON_AUTOLINK_H_INCLUDED # define JSON_AUTOLINK_H_INCLUDED diff --git a/external/json/config.h b/external/json/config.h new file mode 100644 index 0000000000..5d334cbc5e --- /dev/null +++ b/external/json/config.h @@ -0,0 +1,43 @@ +#ifndef JSON_CONFIG_H_INCLUDED +# define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 +/// If defined, indicates that Json specific container should be used +/// (hash table & simple deque container with customizable allocator). +/// THIS FEATURE IS STILL EXPERIMENTAL! +//# define JSON_VALUE_USE_INTERNAL_MAP 1 +/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. +/// The memory pools allocator used optimization (initializing Value and ValueInternalLink +/// as if it was a POD) that may cause some validation tool to report errors. +/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. +//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 + +/// If defined, indicates that Json use exception to report invalid type manipulation +/// instead of C assert macro. +# define JSON_USE_EXCEPTION 1 + +# ifdef JSON_IN_CPPTL +# include +# ifndef JSON_USE_CPPTL +# define JSON_USE_CPPTL 1 +# endif +# endif + +# ifdef JSON_IN_CPPTL +# define JSON_API CPPTL_API +# elif defined(JSON_DLL_BUILD) +# define JSON_API __declspec(dllexport) +# elif defined(JSON_DLL) +# define JSON_API __declspec(dllimport) +# else +# define JSON_API +# endif + +#endif // JSON_CONFIG_H_INCLUDED diff --git a/external/jsoncpp/features.h b/external/json/features.h similarity index 78% rename from external/jsoncpp/features.h rename to external/json/features.h index 03be3313bf..5a9adec118 100644 --- a/external/jsoncpp/features.h +++ b/external/json/features.h @@ -1,16 +1,9 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef CPPTL_JSON_FEATURES_H_INCLUDED # define CPPTL_JSON_FEATURES_H_INCLUDED -#if !defined(JSON_IS_AMALGAMATION) # include "forwards.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -namespace CSJson { +namespace Json { /** \brief Configuration passed to reader and writer. * This configuration object can be used to force the Reader or Writer @@ -44,6 +37,6 @@ namespace CSJson { bool strictRoot_; }; -} // namespace CSJson +} // namespace Json #endif // CPPTL_JSON_FEATURES_H_INCLUDED diff --git a/external/jsoncpp/forwards.h b/external/json/forwards.h similarity index 61% rename from external/jsoncpp/forwards.h rename to external/json/forwards.h index 4af4eebdb5..d0ce8300ce 100644 --- a/external/jsoncpp/forwards.h +++ b/external/json/forwards.h @@ -1,16 +1,9 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef JSON_FORWARDS_H_INCLUDED # define JSON_FORWARDS_H_INCLUDED -#if !defined(JSON_IS_AMALGAMATION) # include "config.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -namespace CSJson { +namespace Json { // writer.h class FastWriter; @@ -23,7 +16,8 @@ namespace CSJson { class Features; // value.h - typedef unsigned int ArrayIndex; + typedef int Int; + typedef unsigned int UInt; class StaticString; class Path; class PathArgument; @@ -32,13 +26,14 @@ namespace CSJson { class ValueIterator; class ValueConstIterator; #ifdef JSON_VALUE_USE_INTERNAL_MAP + class ValueAllocator; class ValueMapAllocator; class ValueInternalLink; class ValueInternalArray; class ValueInternalMap; #endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP -} // namespace CSJson +} // namespace Json #endif // JSON_FORWARDS_H_INCLUDED diff --git a/external/json/json.h b/external/json/json.h new file mode 100644 index 0000000000..c71ed65abf --- /dev/null +++ b/external/json/json.h @@ -0,0 +1,10 @@ +#ifndef JSON_JSON_H_INCLUDED +# define JSON_JSON_H_INCLUDED + +# include "autolink.h" +# include "value.h" +# include "reader.h" +# include "writer.h" +# include "features.h" + +#endif // JSON_JSON_H_INCLUDED diff --git a/external/jsoncpp/json_batchallocator.h b/external/json/json_batchallocator.h similarity index 93% rename from external/jsoncpp/json_batchallocator.h rename to external/json/json_batchallocator.h index 14b4d36839..87ea5ed807 100644 --- a/external/jsoncpp/json_batchallocator.h +++ b/external/json/json_batchallocator.h @@ -1,8 +1,3 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED # define JSONCPP_BATCHALLOCATOR_H_INCLUDED @@ -11,7 +6,7 @@ # ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION -namespace CSJson { +namespace Json { /* Fast memory allocator. * @@ -122,7 +117,7 @@ private: }; -} // namespace CSJson +} // namespace Json # endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION diff --git a/external/jsoncpp/json_internalarray.inl b/external/json/json_internalarray.inl similarity index 97% rename from external/jsoncpp/json_internalarray.inl rename to external/json/json_internalarray.inl index 5bce163b9c..9b985d2585 100644 --- a/external/jsoncpp/json_internalarray.inl +++ b/external/json/json_internalarray.inl @@ -1,11 +1,5 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - // included by json_value.cpp - -namespace CSJson { +// everything is within Json namespace // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// @@ -452,5 +446,3 @@ ValueInternalArray::compare( const ValueInternalArray &other ) const } return 0; } - -} // namespace CSJson diff --git a/external/jsoncpp/json_internalmap.inl b/external/json/json_internalmap.inl similarity index 98% rename from external/jsoncpp/json_internalmap.inl rename to external/json/json_internalmap.inl index 755eeb941a..19771488d6 100644 --- a/external/jsoncpp/json_internalmap.inl +++ b/external/json/json_internalmap.inl @@ -1,11 +1,5 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - // included by json_value.cpp - -namespace CSJson { +// everything is within Json namespace // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// @@ -421,7 +415,7 @@ ValueInternalMap::setNewItem( const char *key, ValueInternalLink *link, BucketIndex index ) { - char *duplicatedKey = makeMemberName( key ); + char *duplicatedKey = valueAllocator()->makeMemberName( key ); ++itemCount_; link->keys_[index] = duplicatedKey; link->items_[index].setItemUsed(); @@ -611,5 +605,3 @@ ValueInternalMap::distance( const IteratorState &x, const IteratorState &y ) increment( it ); return offset; } - -} // namespace CSJson diff --git a/external/jsoncpp/json_reader.cpp b/external/json/json_reader.cpp similarity index 89% rename from external/jsoncpp/json_reader.cpp rename to external/json/json_reader.cpp index 5d336cf2a7..4eb2d11fd3 100644 --- a/external/jsoncpp/json_reader.cpp +++ b/external/json/json_reader.cpp @@ -1,27 +1,17 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -# include "reader.h" -# include "value.h" -# include "json_tool.h" -#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include #include #include #include #include #include #include -#include -#include #if _MSC_VER >= 1400 // VC++ 8.0 #pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. #endif -namespace CSJson { +namespace Json { // Implementation of class Features // //////////////////////////////// @@ -76,6 +66,42 @@ containsNewLine( Reader::Location begin, return false; } +static std::string codePointToUTF8(unsigned int cp) +{ + std::string result; + + // based on description from http://en.wikipedia.org/wiki/UTF-8 + + if (cp <= 0x7f) + { + result.resize(1); + result[0] = static_cast(cp); + } + else if (cp <= 0x7FF) + { + result.resize(2); + result[1] = static_cast(0x80 | (0x3f & cp)); + result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); + } + else if (cp <= 0xFFFF) + { + result.resize(3); + result[2] = static_cast(0x80 | (0x3f & cp)); + result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); + result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); + } + else if (cp <= 0x10FFFF) + { + result.resize(4); + result[3] = static_cast(0x80 | (0x3f & cp)); + result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); + result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); + result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); + } + + return result; +} + // Class Reader // ////////////////////////////////////////////////////////////////// @@ -451,7 +477,7 @@ Reader::readString() bool -Reader::readObject( Token &/*tokenStart*/ ) +Reader::readObject( Token &tokenStart ) { Token tokenName; std::string name; @@ -490,7 +516,7 @@ Reader::readObject( Token &/*tokenStart*/ ) if ( !readToken( comma ) || ( comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && - comma.type_ != tokenComment ) ) + comma.type_ != tokenComment ) ) { return addErrorAndRecover( "Missing ',' or '}' in object declaration", comma, @@ -510,7 +536,7 @@ Reader::readObject( Token &/*tokenStart*/ ) bool -Reader::readArray( Token &/*tokenStart*/ ) +Reader::readArray( Token &tokenStart ) { currentValue() = Value( arrayValue ); skipSpaces(); @@ -521,7 +547,7 @@ Reader::readArray( Token &/*tokenStart*/ ) return true; } int index = 0; - for (;;) + while ( true ) { Value &value = currentValue()[ index++ ]; nodes_.push( &value ); @@ -537,8 +563,8 @@ Reader::readArray( Token &/*tokenStart*/ ) { ok = readToken( token ); } - bool badTokenType = ( token.type_ != tokenArraySeparator && - token.type_ != tokenArrayEnd ); + bool badTokenType = ( token.type_ == tokenArraySeparator && + token.type_ == tokenArrayEnd ); if ( !ok || badTokenType ) { return addErrorAndRecover( "Missing ',' or ']' in array declaration", @@ -564,41 +590,26 @@ Reader::decodeNumber( Token &token ) } if ( isDouble ) return decodeDouble( token ); - // Attempts to parse the number as an integer. If the number is - // larger than the maximum supported value of an integer then - // we decode the number as a double. Location current = token.start_; bool isNegative = *current == '-'; if ( isNegative ) ++current; - Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) - : Value::maxLargestUInt; - Value::LargestUInt threshold = maxIntegerValue / 10; - Value::UInt lastDigitThreshold = Value::UInt( maxIntegerValue % 10 ); - assert( lastDigitThreshold >=0 && lastDigitThreshold <= 9 ); - Value::LargestUInt value = 0; + Value::UInt threshold = (isNegative ? Value::UInt(-Value::minInt) + : Value::maxUInt) / 10; + Value::UInt value = 0; while ( current < token.end_ ) { Char c = *current++; if ( c < '0' || c > '9' ) return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); - Value::UInt digit(c - '0'); if ( value >= threshold ) - { - // If the current digit is not the last one, or if it is - // greater than the last digit of the maximum integer value, - // the parse the number as a double. - if ( current != token.end_ || digit > lastDigitThreshold ) - { - return decodeDouble( token ); - } - } - value = value * 10 + digit; + return decodeDouble( token ); + value = value * 10 + Value::UInt(c - '0'); } if ( isNegative ) - currentValue() = -Value::LargestInt( value ); - else if ( value <= Value::LargestUInt(Value::maxInt) ) - currentValue() = Value::LargestInt( value ); + currentValue() = -Value::Int( value ); + else if ( value <= Value::UInt(Value::maxInt) ) + currentValue() = Value::Int( value ); else currentValue() = value; return true; @@ -614,7 +625,7 @@ Reader::decodeDouble( Token &token ) int length = int(token.end_ - token.start_); if ( length <= bufferSize ) { - Char buffer[bufferSize+1]; + Char buffer[bufferSize]; memcpy( buffer, token.start_, length ); buffer[length] = 0; count = sscanf( buffer, "%lf", &value ); @@ -764,7 +775,7 @@ Reader::recoverFromError( TokenType skipUntilToken ) { int errorCount = int(errors_.size()); Token skip; - for (;;) + while ( true ) { if ( !readToken(skip) ) errors_.resize( errorCount ); // discard errors caused by recovery @@ -843,16 +854,8 @@ Reader::getLocationLineAndColumn( Location location ) const } -// Deprecated. Preserved for backward compatibility std::string Reader::getFormatedErrorMessages() const -{ - return getFormattedErrorMessages(); -} - - -std::string -Reader::getFormattedErrorMessages() const { std::string formattedMessage; for ( Errors::const_iterator itError = errors_.begin(); @@ -871,12 +874,12 @@ Reader::getFormattedErrorMessages() const std::istream& operator>>( std::istream &sin, Value &root ) { - CSJson::Reader reader; + Json::Reader reader; bool ok = reader.parse(sin, root, true); //JSON_ASSERT( ok ); - if (!ok) throw std::runtime_error(reader.getFormattedErrorMessages()); + if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages()); return sin; } -} // namespace CSJson +} // namespace Json diff --git a/external/jsoncpp/json_value.cpp b/external/json/json_value.cpp similarity index 79% rename from external/jsoncpp/json_value.cpp rename to external/json/json_value.cpp index e62b9c36a1..573205f13e 100644 --- a/external/jsoncpp/json_value.cpp +++ b/external/json/json_value.cpp @@ -1,16 +1,6 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -# include "value.h" -# include "writer.h" -# ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR -# include "json_batchallocator.h" -# endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR -#endif // if !defined(JSON_IS_AMALGAMATION) #include +#include +#include #include #include #include @@ -19,63 +9,106 @@ # include #endif #include // size_t - -#include +#ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +# include "json_batchallocator.h" +#endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR #define JSON_ASSERT_UNREACHABLE assert( false ) #define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw -#define JSON_FAIL_MESSAGE( message ) throw std::runtime_error( message ); -#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) JSON_FAIL_MESSAGE( message ) +#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) throw std::runtime_error( message ); -namespace CSJson { +namespace Json { -const Value Value::jsonNull; +const Value Value::null; const Int Value::minInt = Int( ~(UInt(-1)/2) ); const Int Value::maxInt = Int( UInt(-1)/2 ); const UInt Value::maxUInt = UInt(-1); -const Int64 Value::minInt64 = Int64( ~(UInt64(-1)/2) ); -const Int64 Value::maxInt64 = Int64( UInt64(-1)/2 ); -const UInt64 Value::maxUInt64 = UInt64(-1); -const LargestInt Value::minLargestInt = LargestInt( ~(LargestUInt(-1)/2) ); -const LargestInt Value::maxLargestInt = LargestInt( LargestUInt(-1)/2 ); -const LargestUInt Value::maxLargestUInt = LargestUInt(-1); +// A "safe" implementation of strdup. Allow null pointer to be passed. +// Also avoid warning on msvc80. +// +//inline char *safeStringDup( const char *czstring ) +//{ +// if ( czstring ) +// { +// const size_t length = (unsigned int)( strlen(czstring) + 1 ); +// char *newString = static_cast( malloc( length ) ); +// memcpy( newString, czstring, length ); +// return newString; +// } +// return 0; +//} +// +//inline char *safeStringDup( const std::string &str ) +//{ +// if ( !str.empty() ) +// { +// const size_t length = str.length(); +// char *newString = static_cast( malloc( length + 1 ) ); +// memcpy( newString, str.c_str(), length ); +// newString[length] = 0; +// return newString; +// } +// return 0; +//} -/// Unknown size marker -static const unsigned int unknown = (unsigned)-1; - - -/** Duplicates the specified string value. - * @param value Pointer to the string to duplicate. Must be zero-terminated if - * length is "unknown". - * @param length Length of the value. if equals to unknown, then it will be - * computed using strlen(value). - * @return Pointer on the duplicate instance of string. - */ -static inline char * -duplicateStringValue( const char *value, - unsigned int length = unknown ) +ValueAllocator::~ValueAllocator() { - if ( length == unknown ) - length = (unsigned int)strlen(value); - char *newString = static_cast( malloc( length + 1 ) ); - JSON_ASSERT_MESSAGE( newString != 0, "Failed to allocate string value buffer" ); - memcpy( newString, value, length ); - newString[length] = 0; - return newString; } - -/** Free the string duplicated by duplicateStringValue(). - */ -static inline void -releaseStringValue( char *value ) +class DefaultValueAllocator : public ValueAllocator { - if ( value ) - free( value ); +public: + virtual ~DefaultValueAllocator() + { + } + + virtual char *makeMemberName( const char *memberName ) + { + return duplicateStringValue( memberName ); + } + + virtual void releaseMemberName( char *memberName ) + { + releaseStringValue( memberName ); + } + + virtual char *duplicateStringValue( const char *value, + unsigned int length = unknown ) + { + //@todo invesgate this old optimization + //if ( !value || value[0] == 0 ) + // return 0; + + if ( length == unknown ) + length = (unsigned int)strlen(value); + char *newString = static_cast( malloc( length + 1 ) ); + memcpy( newString, value, length ); + newString[length] = 0; + return newString; + } + + virtual void releaseStringValue( char *value ) + { + if ( value ) + free( value ); + } +}; + +static ValueAllocator *&valueAllocator() +{ + static DefaultValueAllocator defaultAllocator; + static ValueAllocator *valueAllocator = &defaultAllocator; + return valueAllocator; } -} // namespace CSJson +static struct DummyValueAllocatorInitializer { + DummyValueAllocatorInitializer() + { + valueAllocator(); // ensure valueAllocator() statics are initialized before main(). + } +} dummyValueAllocatorInitializer; + // ////////////////////////////////////////////////////////////////// @@ -85,16 +118,13 @@ releaseStringValue( char *value ) // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -#if !defined(JSON_IS_AMALGAMATION) -# ifdef JSON_VALUE_USE_INTERNAL_MAP -# include "json_internalarray.inl" -# include "json_internalmap.inl" -# endif // JSON_VALUE_USE_INTERNAL_MAP +#ifdef JSON_VALUE_USE_INTERNAL_MAP +# include "json_internalarray.inl" +# include "json_internalmap.inl" +#endif // JSON_VALUE_USE_INTERNAL_MAP # include "json_valueiterator.inl" -#endif // if !defined(JSON_IS_AMALGAMATION) -namespace CSJson { // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// @@ -113,7 +143,7 @@ Value::CommentInfo::CommentInfo() Value::CommentInfo::~CommentInfo() { if ( comment_ ) - releaseStringValue( comment_ ); + valueAllocator()->releaseStringValue( comment_ ); } @@ -121,11 +151,11 @@ void Value::CommentInfo::setComment( const char *text ) { if ( comment_ ) - releaseStringValue( comment_ ); - JSON_ASSERT( text != 0 ); + valueAllocator()->releaseStringValue( comment_ ); + JSON_ASSERT( text ); JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); // It seems that /**/ style comments are acceptable as well. - comment_ = duplicateStringValue( text ); + comment_ = valueAllocator()->duplicateStringValue( text ); } @@ -141,14 +171,14 @@ Value::CommentInfo::setComment( const char *text ) // Notes: index_ indicates if the string was allocated when // a string is stored. -Value::CZString::CZString( ArrayIndex index ) +Value::CZString::CZString( int index ) : cstr_( 0 ) , index_( index ) { } Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) - : cstr_( allocate == duplicate ? duplicateStringValue(cstr) + : cstr_( allocate == duplicate ? valueAllocator()->makeMemberName(cstr) : cstr ) , index_( allocate ) { @@ -156,7 +186,7 @@ Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) Value::CZString::CZString( const CZString &other ) : cstr_( other.index_ != noDuplication && other.cstr_ != 0 - ? duplicateStringValue( other.cstr_ ) + ? valueAllocator()->makeMemberName( other.cstr_ ) : other.cstr_ ) , index_( other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_ ) @@ -166,7 +196,7 @@ Value::CZString::CZString( const CZString &other ) Value::CZString::~CZString() { if ( cstr_ && index_ == duplicate ) - releaseStringValue( const_cast( cstr_ ) ); + valueAllocator()->releaseMemberName( const_cast( cstr_ ) ); } void @@ -201,7 +231,7 @@ Value::CZString::operator==( const CZString &other ) const } -ArrayIndex +int Value::CZString::index() const { return index_; @@ -279,17 +309,6 @@ Value::Value( ValueType type ) } -#if defined(JSON_HAS_INT64) -Value::Value( UInt value ) - : type_( uintValue ) - , comments_( 0 ) -# ifdef JSON_VALUE_USE_INTERNAL_MAP - , itemIsUsed_( 0 ) -#endif -{ - value_.uint_ = value; -} - Value::Value( Int value ) : type_( intValue ) , comments_( 0 ) @@ -300,21 +319,8 @@ Value::Value( Int value ) value_.int_ = value; } -#endif // if defined(JSON_HAS_INT64) - -Value::Value( Int64 value ) - : type_( intValue ) - , comments_( 0 ) -# ifdef JSON_VALUE_USE_INTERNAL_MAP - , itemIsUsed_( 0 ) -#endif -{ - value_.int_ = value; -} - - -Value::Value( UInt64 value ) +Value::Value( UInt value ) : type_( uintValue ) , comments_( 0 ) # ifdef JSON_VALUE_USE_INTERNAL_MAP @@ -342,7 +348,7 @@ Value::Value( const char *value ) , itemIsUsed_( 0 ) #endif { - value_.string_ = duplicateStringValue( value ); + value_.string_ = valueAllocator()->duplicateStringValue( value ); } @@ -355,8 +361,8 @@ Value::Value( const char *beginValue, , itemIsUsed_( 0 ) #endif { - value_.string_ = duplicateStringValue( beginValue, - (unsigned int)(endValue - beginValue) ); + value_.string_ = valueAllocator()->duplicateStringValue( beginValue, + UInt(endValue - beginValue) ); } @@ -368,8 +374,8 @@ Value::Value( const std::string &value ) , itemIsUsed_( 0 ) #endif { - value_.string_ = duplicateStringValue( value.c_str(), - (unsigned int)value.length() ); + value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(), + (unsigned int)value.length() ); } @@ -394,7 +400,7 @@ Value::Value( const CppTL::ConstString &value ) , itemIsUsed_( 0 ) #endif { - value_.string_ = duplicateStringValue( value, value.length() ); + value_.string_ = valueAllocator()->duplicateStringValue( value, value.length() ); } # endif @@ -428,7 +434,7 @@ Value::Value( const Value &other ) case stringValue: if ( other.value_.string_ ) { - value_.string_ = duplicateStringValue( other.value_.string_ ); + value_.string_ = valueAllocator()->duplicateStringValue( other.value_.string_ ); allocated_ = true; } else @@ -475,17 +481,12 @@ Value::~Value() break; case stringValue: if ( allocated_ ) - releaseStringValue( value_.string_ ); + valueAllocator()->releaseStringValue( value_.string_ ); break; #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: - if (value_.map_ != NULL) - { - value_.map_->clear(); - delete value_.map_; - value_.map_ = NULL; - } + delete value_.map_; break; #else case arrayValue: @@ -531,15 +532,34 @@ Value::type() const int -Value::compare( const Value &other ) const +Value::compare( const Value &other ) { - if ( *this < other ) - return -1; - if ( *this > other ) - return 1; - return 0; -} + /* + int typeDelta = other.type_ - type_; + switch ( type_ ) + { + case nullValue: + return other.type_ == type_; + case intValue: + if ( other.type_.isNumeric() + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue, + break; + case arrayValue: + delete value_.array_; + break; + case objectValue: + delete value_.map_; + default: + JSON_ASSERT_UNREACHABLE; + } + */ + return 0; // unreachable +} bool Value::operator <( const Value &other ) const @@ -582,13 +602,13 @@ Value::operator <( const Value &other ) const default: JSON_ASSERT_UNREACHABLE; } - return false; // unreachable + return 0; // unreachable } bool Value::operator <=( const Value &other ) const { - return !(other < *this); + return !(other > *this); } bool @@ -644,7 +664,7 @@ Value::operator ==( const Value &other ) const default: JSON_ASSERT_UNREACHABLE; } - return false; // unreachable + return 0; // unreachable } bool @@ -677,7 +697,7 @@ Value::asString() const case realValue: case arrayValue: case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to string" ); + JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" ); default: JSON_ASSERT_UNREACHABLE; } @@ -692,7 +712,6 @@ Value::asConstString() const } # endif - Value::Int Value::asInt() const { @@ -701,11 +720,10 @@ Value::asInt() const case nullValue: return 0; case intValue: - JSON_ASSERT_MESSAGE( value_.int_ >= minInt && value_.int_ <= maxInt, "unsigned integer out of signed int range" ); - return Int(value_.int_); + return value_.int_; case uintValue: - JSON_ASSERT_MESSAGE( value_.uint_ <= UInt(maxInt), "unsigned integer out of signed int range" ); - return Int(value_.uint_); + JSON_ASSERT_MESSAGE( value_.uint_ < (unsigned)maxInt, "integer out of signed integer range" ); + return value_.uint_; case realValue: JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); return Int( value_.real_ ); @@ -714,14 +732,13 @@ Value::asInt() const case stringValue: case arrayValue: case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to int" ); + JSON_ASSERT_MESSAGE( false, "Type is not convertible to int" ); default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } - Value::UInt Value::asUInt() const { @@ -731,11 +748,9 @@ Value::asUInt() const return 0; case intValue: JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); - JSON_ASSERT_MESSAGE( value_.int_ <= maxUInt, "signed integer out of UInt range" ); - return UInt(value_.int_); + return value_.int_; case uintValue: - JSON_ASSERT_MESSAGE( value_.uint_ <= maxUInt, "unsigned integer out of UInt range" ); - return UInt(value_.uint_); + return value_.uint_; case realValue: JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); return UInt( value_.real_ ); @@ -744,95 +759,13 @@ Value::asUInt() const case stringValue: case arrayValue: case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to uint" ); + JSON_ASSERT_MESSAGE( false, "Type is not convertible to uint" ); default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } - -# if defined(JSON_HAS_INT64) - -Value::Int64 -Value::asInt64() const -{ - switch ( type_ ) - { - case nullValue: - return 0; - case intValue: - return value_.int_; - case uintValue: - JSON_ASSERT_MESSAGE( value_.uint_ <= UInt64(maxInt64), "unsigned integer out of Int64 range" ); - return value_.uint_; - case realValue: - JSON_ASSERT_MESSAGE( value_.real_ >= minInt64 && value_.real_ <= maxInt64, "Real out of Int64 range" ); - return Int( value_.real_ ); - case booleanValue: - return value_.bool_ ? 1 : 0; - case stringValue: - case arrayValue: - case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to Int64" ); - default: - JSON_ASSERT_UNREACHABLE; - } - return 0; // unreachable; -} - - -Value::UInt64 -Value::asUInt64() const -{ - switch ( type_ ) - { - case nullValue: - return 0; - case intValue: - JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to UInt64" ); - return value_.int_; - case uintValue: - return value_.uint_; - case realValue: - JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt64, "Real out of UInt64 range" ); - return UInt( value_.real_ ); - case booleanValue: - return value_.bool_ ? 1 : 0; - case stringValue: - case arrayValue: - case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to UInt64" ); - default: - JSON_ASSERT_UNREACHABLE; - } - return 0; // unreachable; -} -# endif // if defined(JSON_HAS_INT64) - - -LargestInt -Value::asLargestInt() const -{ -#if defined(JSON_NO_INT64) - return asInt(); -#else - return asInt64(); -#endif -} - - -LargestUInt -Value::asLargestUInt() const -{ -#if defined(JSON_NO_INT64) - return asUInt(); -#else - return asUInt64(); -#endif -} - - double Value::asDouble() const { @@ -841,13 +774,9 @@ Value::asDouble() const case nullValue: return 0.0; case intValue: - return static_cast( value_.int_ ); + return value_.int_; case uintValue: -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast( value_.uint_ ); -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) + return value_.uint_; case realValue: return value_.real_; case booleanValue: @@ -855,42 +784,13 @@ Value::asDouble() const case stringValue: case arrayValue: case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to double" ); + JSON_ASSERT_MESSAGE( false, "Type is not convertible to double" ); default: JSON_ASSERT_UNREACHABLE; } return 0; // unreachable; } -float -Value::asFloat() const -{ - switch ( type_ ) - { - case nullValue: - return 0.0f; - case intValue: - return static_cast( value_.int_ ); - case uintValue: -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast( value_.uint_ ); -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast( Int(value_.uint_/2) ) * 2 + Int(value_.uint_ & 1); -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - case realValue: - return static_cast( value_.real_ ); - case booleanValue: - return value_.bool_ ? 1.0f : 0.0f; - case stringValue: - case arrayValue: - case objectValue: - JSON_FAIL_MESSAGE( "Type is not convertible to float" ); - default: - JSON_ASSERT_UNREACHABLE; - } - return 0.0f; // unreachable; -} - bool Value::asBool() const { @@ -969,7 +869,7 @@ Value::isConvertibleTo( ValueType other ) const /// Number of values in array or object -ArrayIndex +Value::UInt Value::size() const { switch ( type_ ) @@ -991,7 +891,7 @@ Value::size() const } return 0; case objectValue: - return ArrayIndex( value_.map_->size() ); + return Int( value_.map_->size() ); #else case arrayValue: return Int( value_.array_->size() ); @@ -1032,18 +932,7 @@ Value::clear() #ifndef JSON_VALUE_USE_INTERNAL_MAP case arrayValue: case objectValue: - // value_.map_->clear(); - if (value_.map_ != NULL) - { - value_.map_->clear(); - delete value_.map_; - value_.map_ = NULL; - } - if (value_.string_ != NULL) - { - delete value_.string_; - value_.string_ = NULL; - } + value_.map_->clear(); break; #else case arrayValue: @@ -1059,23 +948,21 @@ Value::clear() } void -Value::resize( ArrayIndex newSize ) +Value::resize( UInt newSize ) { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) *this = Value( arrayValue ); #ifndef JSON_VALUE_USE_INTERNAL_MAP - ArrayIndex oldSize = size(); + UInt oldSize = size(); if ( newSize == 0 ) clear(); else if ( newSize > oldSize ) (*this)[ newSize - 1 ]; else { - for ( ArrayIndex index = newSize; index < oldSize; ++index ) - { + for ( UInt index = newSize; index < oldSize; ++index ) value_.map_->erase( index ); - } assert( size() == newSize ); } #else @@ -1085,7 +972,7 @@ Value::resize( ArrayIndex newSize ) Value & -Value::operator[]( ArrayIndex index ) +Value::operator[]( UInt index ) { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) @@ -1096,7 +983,7 @@ Value::operator[]( ArrayIndex index ) if ( it != value_.map_->end() && (*it).first == key ) return (*it).second; - ObjectValues::value_type defaultValue( key, jsonNull ); + ObjectValues::value_type defaultValue( key, null ); it = value_.map_->insert( it, defaultValue ); return (*it).second; #else @@ -1105,25 +992,17 @@ Value::operator[]( ArrayIndex index ) } -Value & -Value::operator[]( int index ) -{ - JSON_ASSERT( index >= 0 ); - return (*this)[ ArrayIndex(index) ]; -} - - const Value & -Value::operator[]( ArrayIndex index ) const +Value::operator[]( UInt index ) const { JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); if ( type_ == nullValue ) - return jsonNull; + return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString key( index ); ObjectValues::const_iterator it = value_.map_->find( key ); if ( it == value_.map_->end() ) - return jsonNull; + return null; return (*it).second; #else Value *value = value_.array_->find( index ); @@ -1132,14 +1011,6 @@ Value::operator[]( ArrayIndex index ) const } -const Value & -Value::operator[]( int index ) const -{ - JSON_ASSERT( index >= 0 ); - return (*this)[ ArrayIndex(index) ]; -} - - Value & Value::operator[]( const char *key ) { @@ -1161,7 +1032,7 @@ Value::resolveReference( const char *key, if ( it != value_.map_->end() && (*it).first == actualKey ) return (*it).second; - ObjectValues::value_type defaultValue( actualKey, jsonNull ); + ObjectValues::value_type defaultValue( actualKey, null ); it = value_.map_->insert( it, defaultValue ); Value &value = (*it).second; return value; @@ -1172,16 +1043,16 @@ Value::resolveReference( const char *key, Value -Value::get( ArrayIndex index, +Value::get( UInt index, const Value &defaultValue ) const { const Value *value = &((*this)[index]); - return value == &jsonNull ? defaultValue : *value; + return value == &null ? defaultValue : *value; } bool -Value::isValidIndex( ArrayIndex index ) const +Value::isValidIndex( UInt index ) const { return index < size(); } @@ -1193,12 +1064,12 @@ Value::operator[]( const char *key ) const { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) - return jsonNull; + return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString actualKey( key, CZString::noDuplication ); ObjectValues::const_iterator it = value_.map_->find( actualKey ); if ( it == value_.map_->end() ) - return jsonNull; + return null; return (*it).second; #else const Value *value = value_.map_->find( key ); @@ -1255,7 +1126,7 @@ Value::get( const char *key, const Value &defaultValue ) const { const Value *value = &((*this)[key]); - return value == &jsonNull ? defaultValue : *value; + return value == &null ? defaultValue : *value; } @@ -1271,12 +1142,12 @@ Value::removeMember( const char* key ) { JSON_ASSERT( type_ == nullValue || type_ == objectValue ); if ( type_ == nullValue ) - return jsonNull; + return null; #ifndef JSON_VALUE_USE_INTERNAL_MAP CZString actualKey( key, CZString::noDuplication ); ObjectValues::iterator it = value_.map_->find( actualKey ); if ( it == value_.map_->end() ) - return jsonNull; + return null; Value old(it->second); value_.map_->erase(it); return old; @@ -1311,7 +1182,7 @@ bool Value::isMember( const char *key ) const { const Value *value = &((*this)[key]); - return value != &jsonNull; + return value != &null; } @@ -1394,7 +1265,7 @@ Value::isBool() const } -bool +bool Value::isInt() const { return type_ == intValue; @@ -1644,7 +1515,7 @@ PathArgument::PathArgument() } -PathArgument::PathArgument( ArrayIndex index ) +PathArgument::PathArgument( Value::UInt index ) : index_( index ) , kind_( kindIndex ) { @@ -1700,9 +1571,9 @@ Path::makePath( const std::string &path, addPathInArg( path, in, itInArg, PathArgument::kindIndex ); else { - ArrayIndex index = 0; + Value::UInt index = 0; for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) - index = index * 10 + ArrayIndex(*current - '0'); + index = index * 10 + Value::UInt(*current - '0'); args_.push_back( index ); } if ( current == end || *current++ != ']' ) @@ -1779,7 +1650,7 @@ Path::resolve( const Value &root ) const // Error: unable to resolve path (object value expected at position...) } node = &((*node)[arg.key_]); - if ( node == &Value::jsonNull ) + if ( node == &Value::null ) { // Error: unable to resolve path (object has no member named '' at position...) } @@ -1808,7 +1679,7 @@ Path::resolve( const Value &root, if ( !node->isObject() ) return defaultValue; node = &((*node)[arg.key_]); - if ( node == &Value::jsonNull ) + if ( node == &Value::null ) return defaultValue; } } @@ -1844,4 +1715,4 @@ Path::make( Value &root ) const } -} // namespace CSJson +} // namespace Json diff --git a/external/jsoncpp/json_valueiterator.inl b/external/json/json_valueiterator.inl similarity index 96% rename from external/jsoncpp/json_valueiterator.inl rename to external/json/json_valueiterator.inl index 6cfdc0a812..736e260ea0 100644 --- a/external/jsoncpp/json_valueiterator.inl +++ b/external/json/json_valueiterator.inl @@ -1,11 +1,6 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - // included by json_value.cpp +// everything is within Json namespace -namespace CSJson { // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// @@ -295,5 +290,3 @@ ValueIterator::operator =( const SelfType &other ) copy( other ); return *this; } - -} // namespace CSJson diff --git a/external/jsoncpp/json_writer.cpp b/external/json/json_writer.cpp similarity index 93% rename from external/jsoncpp/json_writer.cpp rename to external/json/json_writer.cpp index a6345ee6ff..cdf4188f2e 100644 --- a/external/jsoncpp/json_writer.cpp +++ b/external/json/json_writer.cpp @@ -1,12 +1,4 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -# include "writer.h" -# include "json_tool.h" -#endif // if !defined(JSON_IS_AMALGAMATION) +#include #include #include #include @@ -19,7 +11,12 @@ #pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. #endif -namespace CSJson { +namespace Json { + +static bool isControlCharacter(char ch) +{ + return ch > 0 && ch <= 0x1F; +} static bool containsControlCharacter( const char* str ) { @@ -30,16 +27,26 @@ static bool containsControlCharacter( const char* str ) } return false; } - - -std::string valueToString( LargestInt value ) +static void uintToString( unsigned int value, + char *¤t ) { - UIntToStringBuffer buffer; + *--current = 0; + do + { + *--current = (value % 10) + '0'; + value /= 10; + } + while ( value != 0 ); +} + +std::string valueToString( Int value ) +{ + char buffer[32]; char *current = buffer + sizeof(buffer); bool isNegative = value < 0; if ( isNegative ) value = -value; - uintToString( LargestUInt(value), current ); + uintToString( UInt(value), current ); if ( isNegative ) *--current = '-'; assert( current >= buffer ); @@ -47,31 +54,15 @@ std::string valueToString( LargestInt value ) } -std::string valueToString( LargestUInt value ) +std::string valueToString( UInt value ) { - UIntToStringBuffer buffer; + char buffer[32]; char *current = buffer + sizeof(buffer); uintToString( value, current ); assert( current >= buffer ); return current; } -#if defined(JSON_HAS_INT64) - -std::string valueToString( Int value ) -{ - return valueToString( LargestInt(value) ); -} - - -std::string valueToString( UInt value ) -{ - return valueToString( LargestUInt(value) ); -} - -#endif // # if defined(JSON_HAS_INT64) - - std::string valueToString( double value ) { char buffer[32]; @@ -125,7 +116,7 @@ std::string valueToQuotedString( const char *value ) // We have to walk value and escape any special characters. // Appending to std::string is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) - std::string::size_type maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL + unsigned maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL std::string result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; @@ -222,10 +213,10 @@ FastWriter::writeValue( const Value &value ) document_ += "null"; break; case intValue: - document_ += valueToString( value.asLargestInt() ); + document_ += valueToString( value.asInt() ); break; case uintValue: - document_ += valueToString( value.asLargestUInt() ); + document_ += valueToString( value.asUInt() ); break; case realValue: document_ += valueToString( value.asDouble() ); @@ -305,10 +296,10 @@ StyledWriter::writeValue( const Value &value ) pushValue( "null" ); break; case intValue: - pushValue( valueToString( value.asLargestInt() ) ); + pushValue( valueToString( value.asInt() ) ); break; case uintValue: - pushValue( valueToString( value.asLargestUInt() ) ); + pushValue( valueToString( value.asUInt() ) ); break; case realValue: pushValue( valueToString( value.asDouble() ) ); @@ -332,7 +323,7 @@ StyledWriter::writeValue( const Value &value ) writeWithIndent( "{" ); indent(); Value::Members::iterator it = members.begin(); - for (;;) + while ( true ) { const std::string &name = *it; const Value &childValue = value[name]; @@ -372,7 +363,7 @@ StyledWriter::writeArrayValue( const Value &value ) indent(); bool hasChildValue = !childValues_.empty(); unsigned index =0; - for (;;) + while ( true ) { const Value &childValue = value[index]; writeCommentBeforeValue( childValue ); @@ -581,10 +572,10 @@ StyledStreamWriter::writeValue( const Value &value ) pushValue( "null" ); break; case intValue: - pushValue( valueToString( value.asLargestInt() ) ); + pushValue( valueToString( value.asInt() ) ); break; case uintValue: - pushValue( valueToString( value.asLargestUInt() ) ); + pushValue( valueToString( value.asUInt() ) ); break; case realValue: pushValue( valueToString( value.asDouble() ) ); @@ -608,7 +599,7 @@ StyledStreamWriter::writeValue( const Value &value ) writeWithIndent( "{" ); indent(); Value::Members::iterator it = members.begin(); - for (;;) + while ( true ) { const std::string &name = *it; const Value &childValue = value[name]; @@ -648,7 +639,7 @@ StyledStreamWriter::writeArrayValue( const Value &value ) indent(); bool hasChildValue = !childValues_.empty(); unsigned index =0; - for (;;) + while ( true ) { const Value &childValue = value[index]; writeCommentBeforeValue( childValue ); @@ -656,7 +647,7 @@ StyledStreamWriter::writeArrayValue( const Value &value ) writeWithIndent( childValues_[index] ); else { - writeIndent(); + writeIndent(); writeValue( childValue ); } if ( ++index == size ) @@ -829,10 +820,10 @@ StyledStreamWriter::normalizeEOL( const std::string &text ) std::ostream& operator<<( std::ostream &sout, const Value &root ) { - CSJson::StyledStreamWriter writer; + Json::StyledStreamWriter writer; writer.write(sout, root); return sout; } -} // namespace CSJson +} // namespace Json diff --git a/external/jsoncpp/reader.h b/external/json/reader.h similarity index 82% rename from external/jsoncpp/reader.h rename to external/json/reader.h index cb58e864a0..ee1d6a2444 100644 --- a/external/jsoncpp/reader.h +++ b/external/json/reader.h @@ -1,21 +1,14 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef CPPTL_JSON_READER_H_INCLUDED # define CPPTL_JSON_READER_H_INCLUDED -#if !defined(JSON_IS_AMALGAMATION) # include "features.h" # include "value.h" -#endif // if !defined(JSON_IS_AMALGAMATION) # include # include # include # include -namespace CSJson { +namespace Json { /** \brief Unserialize a JSON document into a Value. * @@ -51,9 +44,7 @@ namespace CSJson { bool collectComments = true ); /** \brief Read a Value from a JSON document. - * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. - * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. - \ Must be >= beginDoc. + * \param document UTF-8 encoded string containing the document to read. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param collectComments \c true to collect comment and allow writing them back during @@ -67,7 +58,7 @@ namespace CSJson { bool collectComments = true ); /// \brief Parse from input stream. - /// \see CSJson::operator>>(std::istream&, CSJson::Value&). + /// \see Json::operator>>(std::istream&, Json::Value&). bool parse( std::istream &is, Value &root, bool collectComments = true ); @@ -76,18 +67,9 @@ namespace CSJson { * \return Formatted error message with the list of errors with their location in * the parsed document. An empty string is returned if no error occurred * during parsing. - * \deprecated Use getFormattedErrorMessages() instead (typo fix). */ - JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead") std::string getFormatedErrorMessages() const; - /** \brief Returns a user friendly string that list errors in the parsed document. - * \return Formatted error message with the list of errors with their location in - * the parsed document. An empty string is returned if no error occurred - * during parsing. - */ - std::string getFormattedErrorMessages() const; - private: enum TokenType { @@ -190,25 +172,25 @@ namespace CSJson { This can be used to read a file into a particular sub-object. For example: \code - CSJson::Value root; + Json::Value root; cin >> root["dir"]["file"]; cout << root; \endcode Result: \verbatim { - "dir": { - "file": { - // The input stream JSON would be nested here. - } - } + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } } \endverbatim \throw std::exception on parse error. - \see CSJson::operator<<() + \see Json::operator<<() */ std::istream& operator>>( std::istream&, Value& ); -} // namespace CSJson +} // namespace Json #endif // CPPTL_JSON_READER_H_INCLUDED diff --git a/external/jsoncpp/sconscript b/external/json/sconscript similarity index 100% rename from external/jsoncpp/sconscript rename to external/json/sconscript diff --git a/external/jsoncpp/value.h b/external/json/value.h similarity index 90% rename from external/jsoncpp/value.h rename to external/json/value.h index 73c612c94e..58bfd88e7a 100644 --- a/external/jsoncpp/value.h +++ b/external/json/value.h @@ -1,14 +1,7 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef CPPTL_JSON_H_INCLUDED # define CPPTL_JSON_H_INCLUDED -#if !defined(JSON_IS_AMALGAMATION) # include "forwards.h" -#endif // if !defined(JSON_IS_AMALGAMATION) # include # include @@ -23,7 +16,7 @@ /** \brief JSON (JavaScript Object Notation). */ -namespace CSJson { +namespace Json { /** \brief Type of the value held by a Value object. */ @@ -60,8 +53,8 @@ namespace CSJson { * * Example of usage: * \code - * CSJson::Value aValue( StaticString("some text") ); - * CSJson::Value object; + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode @@ -126,38 +119,15 @@ namespace CSJson { typedef std::vector Members; typedef ValueIterator iterator; typedef ValueConstIterator const_iterator; - typedef CSJson::UInt UInt; - typedef CSJson::Int Int; -# if defined(JSON_HAS_INT64) - typedef CSJson::UInt64 UInt64; - typedef CSJson::Int64 Int64; -#endif // defined(JSON_HAS_INT64) - typedef CSJson::LargestInt LargestInt; - typedef CSJson::LargestUInt LargestUInt; - typedef CSJson::ArrayIndex ArrayIndex; + typedef Json::UInt UInt; + typedef Json::Int Int; + typedef UInt ArrayIndex; - static const Value jsonNull; - /// Minimum signed integer value that can be stored in a CSJson::Value. - static const LargestInt minLargestInt; - /// Maximum signed integer value that can be stored in a CSJson::Value. - static const LargestInt maxLargestInt; - /// Maximum unsigned integer value that can be stored in a CSJson::Value. - static const LargestUInt maxLargestUInt; - - /// Minimum signed int value that can be stored in a CSJson::Value. + static const Value null; static const Int minInt; - /// Maximum signed int value that can be stored in a CSJson::Value. static const Int maxInt; - /// Maximum unsigned int value that can be stored in a CSJson::Value. static const UInt maxUInt; - /// Minimum signed 64 bits int value that can be stored in a CSJson::Value. - static const Int64 minInt64; - /// Maximum signed 64 bits int value that can be stored in a CSJson::Value. - static const Int64 maxInt64; - /// Maximum unsigned 64 bits int value that can be stored in a CSJson::Value. - static const UInt64 maxUInt64; - private: #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION # ifndef JSON_VALUE_USE_INTERNAL_MAP @@ -170,20 +140,20 @@ namespace CSJson { duplicate, duplicateOnCopy }; - CZString( ArrayIndex index ); + CZString( int index ); CZString( const char *cstr, DuplicationPolicy allocate ); CZString( const CZString &other ); ~CZString(); CZString &operator =( const CZString &other ); bool operator<( const CZString &other ) const; bool operator==( const CZString &other ) const; - ArrayIndex index() const; + int index() const; const char *c_str() const; bool isStaticString() const; private: void swap( CZString &other ); const char *cstr_; - ArrayIndex index_; + int index_; }; public: @@ -202,22 +172,18 @@ namespace CSJson { To create an empty array, pass arrayValue. To create an empty object, pass objectValue. Another Value can then be set to this one by assignment. - This is useful since clear() and resize() will not alter types. + This is useful since clear() and resize() will not alter types. Examples: - \code - CSJson::Value null_value; // null - CSJson::Value arr_value(Json::arrayValue); // [] - CSJson::Value obj_value(Json::objectValue); // {} - \endcode + \code + Json::Value null_value; // null + Json::Value arr_value(Json::arrayValue); // [] + Json::Value obj_value(Json::objectValue); // {} + \endcode */ Value( ValueType type = nullValue ); Value( Int value ); Value( UInt value ); -#if defined(JSON_HAS_INT64) - Value( Int64 value ); - Value( UInt64 value ); -#endif // if defined(JSON_HAS_INT64) Value( double value ); Value( const char *value ); Value( const char *beginValue, const char *endValue ); @@ -228,7 +194,7 @@ namespace CSJson { * constructor. * Example of usage: * \code - * CSJson::Value aValue( StaticString("some text") ); + * Json::Value aValue( StaticString("some text") ); * \endcode */ Value( const StaticString &value ); @@ -256,7 +222,7 @@ namespace CSJson { bool operator ==( const Value &other ) const; bool operator !=( const Value &other ) const; - int compare( const Value &other ) const; + int compare( const Value &other ); const char *asCString() const; std::string asString() const; @@ -265,11 +231,6 @@ namespace CSJson { # endif Int asInt() const; UInt asUInt() const; - Int64 asInt64() const; - UInt64 asUInt64() const; - LargestInt asLargestInt() const; - LargestUInt asLargestUInt() const; - float asFloat() const; double asDouble() const; bool asBool() const; @@ -287,7 +248,7 @@ namespace CSJson { bool isConvertibleTo( ValueType other ) const; /// Number of values in array or object - ArrayIndex size() const; + UInt size() const; /// \brief Return true if empty array, empty object, or null; /// otherwise, false. @@ -306,38 +267,24 @@ namespace CSJson { /// May only be called on nullValue or arrayValue. /// \pre type() is arrayValue or nullValue /// \post type() is arrayValue - void resize( ArrayIndex size ); + void resize( UInt size ); /// Access an array element (zero based index ). /// If the array contains less than index element, then null value are inserted /// in the array so that its size is index+1. /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) - Value &operator[]( ArrayIndex index ); - - /// Access an array element (zero based index ). - /// If the array contains less than index element, then null value are inserted - /// in the array so that its size is index+1. - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - Value &operator[]( int index ); - + Value &operator[]( UInt index ); /// Access an array element (zero based index ) /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) - const Value &operator[]( ArrayIndex index ) const; - - /// Access an array element (zero based index ) - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - const Value &operator[]( int index ) const; - + const Value &operator[]( UInt index ) const; /// If the array contains at least index+1 elements, returns the element value, /// otherwise returns defaultValue. - Value get( ArrayIndex index, + Value get( UInt index, const Value &defaultValue ) const; /// Return true if index < size(). - bool isValidIndex( ArrayIndex index ) const; + bool isValidIndex( UInt index ) const; /// \brief Append value to array at the end. /// /// Equivalent to jsonvalue[jsonvalue.size()] = value; @@ -357,7 +304,7 @@ namespace CSJson { * the new entry is not duplicated. * Example of use: * \code - * CSJson::Value object; + * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode @@ -477,8 +424,8 @@ namespace CSJson { union ValueHolder { - LargestInt int_; - LargestUInt uint_; + Int int_; + UInt uint_; double real_; bool bool_; char *string_; @@ -507,7 +454,7 @@ namespace CSJson { friend class Path; PathArgument(); - PathArgument( ArrayIndex index ); + PathArgument( UInt index ); PathArgument( const char *key ); PathArgument( const std::string &key ); @@ -519,7 +466,7 @@ namespace CSJson { kindKey }; std::string key_; - ArrayIndex index_; + UInt index_; Kind kind_; }; @@ -566,7 +513,26 @@ namespace CSJson { Args args_; }; + /** \brief Experimental do not use: Allocator to customize member name and string value memory management done by Value. + * + * - makeMemberName() and releaseMemberName() are called to respectively duplicate and + * free an Json::objectValue member name. + * - duplicateStringValue() and releaseStringValue() are called similarly to + * duplicate and free a Json::stringValue value. + */ + class ValueAllocator + { + public: + enum { unknown = (unsigned)-1 }; + virtual ~ValueAllocator(); + + virtual char *makeMemberName( const char *memberName ) = 0; + virtual void releaseMemberName( char *memberName ) = 0; + virtual char *duplicateStringValue( const char *value, + unsigned int length = unknown ) = 0; + virtual void releaseStringValue( char *value ) = 0; + }; #ifdef JSON_VALUE_USE_INTERNAL_MAP /** \brief Allocator to customize Value internal map. @@ -1097,7 +1063,7 @@ public: // overridden from ValueArrayAllocator }; -} // namespace CSJson +} // namespace Json #endif // CPPTL_JSON_H_INCLUDED diff --git a/external/jsoncpp/writer.h b/external/json/writer.h similarity index 91% rename from external/jsoncpp/writer.h rename to external/json/writer.h index d8f057a211..5f4b83be41 100644 --- a/external/jsoncpp/writer.h +++ b/external/json/writer.h @@ -1,19 +1,12 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - #ifndef JSON_WRITER_H_INCLUDED # define JSON_WRITER_H_INCLUDED -#if !defined(JSON_IS_AMALGAMATION) # include "value.h" -#endif // if !defined(JSON_IS_AMALGAMATION) # include # include # include -namespace CSJson { +namespace Json { class Value; @@ -164,21 +157,17 @@ namespace CSJson { bool addChildValues_; }; -# if defined(JSON_HAS_INT64) std::string JSON_API valueToString( Int value ); std::string JSON_API valueToString( UInt value ); -# endif // if defined(JSON_HAS_INT64) - std::string JSON_API valueToString( LargestInt value ); - std::string JSON_API valueToString( LargestUInt value ); std::string JSON_API valueToString( double value ); std::string JSON_API valueToString( bool value ); std::string JSON_API valueToQuotedString( const char *value ); /// \brief Output using the StyledStreamWriter. - /// \see CSJson::operator>>() + /// \see Json::operator>>() std::ostream& operator<<( std::ostream&, const Value &root ); -} // namespace CSJson +} // namespace Json diff --git a/external/jsoncpp/config.h b/external/jsoncpp/config.h deleted file mode 100644 index 16a7e0d2c4..0000000000 --- a/external/jsoncpp/config.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_CONFIG_H_INCLUDED -# define JSON_CONFIG_H_INCLUDED - -/// If defined, indicates that json library is embedded in CppTL library. -//# define JSON_IN_CPPTL 1 - -/// If defined, indicates that json may leverage CppTL library -//# define JSON_USE_CPPTL 1 -/// If defined, indicates that cpptl vector based map should be used instead of std::map -/// as Value container. -//# define JSON_USE_CPPTL_SMALLMAP 1 -/// If defined, indicates that Json specific container should be used -/// (hash table & simple deque container with customizable allocator). -/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332 -//# define JSON_VALUE_USE_INTERNAL_MAP 1 -/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. -/// The memory pools allocator used optimization (initializing Value and ValueInternalLink -/// as if it was a POD) that may cause some validation tool to report errors. -/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. -//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 - -/// If defined, indicates that Json use exception to report invalid type manipulation -/// instead of C assert macro. -# define JSON_USE_EXCEPTION 1 - -/// If defined, indicates that the source file is amalgated -/// to prevent private header inclusion. -/// Remarks: it is automatically defined in the generated amalgated header. -// #define JSON_IS_AMALGAMATION - - -# ifdef JSON_IN_CPPTL -# include -# ifndef JSON_USE_CPPTL -# define JSON_USE_CPPTL 1 -# endif -# endif - -# ifdef JSON_IN_CPPTL -# define JSON_API CPPTL_API -# elif defined(JSON_DLL_BUILD) -# define JSON_API __declspec(dllexport) -# elif defined(JSON_DLL) -# define JSON_API __declspec(dllimport) -# else -# define JSON_API -# endif - -// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer -// Storages, and 64 bits integer support is disabled. -// #define JSON_NO_INT64 1 - -#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6 -// Microsoft Visual Studio 6 only support conversion from __int64 to double -// (no conversion from unsigned __int64). -#define JSON_USE_INT64_DOUBLE_CONVERSION 1 -#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6 - -#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 -/// Indicates that the following function is deprecated. -# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) -#endif - -#if !defined(JSONCPP_DEPRECATED) -# define JSONCPP_DEPRECATED(message) -#endif // if !defined(JSONCPP_DEPRECATED) - -namespace CSJson { - typedef int Int; - typedef unsigned int UInt; -# if defined(JSON_NO_INT64) - typedef int LargestInt; - typedef unsigned int LargestUInt; -# undef JSON_HAS_INT64 -# else // if defined(JSON_NO_INT64) - // For Microsoft Visual use specific types as long long is not supported -# if defined(_MSC_VER) // Microsoft Visual Studio - typedef __int64 Int64; - typedef unsigned __int64 UInt64; -# else // if defined(_MSC_VER) // Other platforms, use long long - typedef long long int Int64; - typedef unsigned long long int UInt64; -# endif // if defined(_MSC_VER) - typedef Int64 LargestInt; - typedef UInt64 LargestUInt; -# define JSON_HAS_INT64 -# endif // if defined(JSON_NO_INT64) -} // end namespace CSJson - - -#endif // JSON_CONFIG_H_INCLUDED diff --git a/external/jsoncpp/json_lib.h b/external/jsoncpp/json_lib.h deleted file mode 100644 index da5fc967eb..0000000000 --- a/external/jsoncpp/json_lib.h +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_JSON_H_INCLUDED -# define JSON_JSON_H_INCLUDED - -# include "autolink.h" -# include "value.h" -# include "reader.h" -# include "writer.h" -# include "features.h" - -#endif // JSON_JSON_H_INCLUDED diff --git a/external/jsoncpp/json_tool.h b/external/jsoncpp/json_tool.h deleted file mode 100644 index 4641ad5953..0000000000 --- a/external/jsoncpp/json_tool.h +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED -# define LIB_JSONCPP_JSON_TOOL_H_INCLUDED - -/* This header provides common string manipulation support, such as UTF-8, - * portable conversion from/to string... - * - * It is an internal header that must not be exposed. - */ - -namespace CSJson { - -/// Converts a unicode code-point to UTF-8. -static inline std::string -codePointToUTF8(unsigned int cp) -{ - std::string result; - - // based on description from http://en.wikipedia.org/wiki/UTF-8 - - if (cp <= 0x7f) - { - result.resize(1); - result[0] = static_cast(cp); - } - else if (cp <= 0x7FF) - { - result.resize(2); - result[1] = static_cast(0x80 | (0x3f & cp)); - result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); - } - else if (cp <= 0xFFFF) - { - result.resize(3); - result[2] = static_cast(0x80 | (0x3f & cp)); - result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); - result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); - } - else if (cp <= 0x10FFFF) - { - result.resize(4); - result[3] = static_cast(0x80 | (0x3f & cp)); - result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); - result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); - result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); - } - - return result; -} - - -/// Returns true if ch is a control character (in range [0,32[). -static inline bool -isControlCharacter(char ch) -{ - return ch > 0 && ch <= 0x1F; -} - - -enum { - /// Constant that specify the size of the buffer that must be passed to uintToString. - uintToStringBufferSize = 3*sizeof(LargestUInt)+1 -}; - -// Defines a char buffer for use with uintToString(). -typedef char UIntToStringBuffer[uintToStringBufferSize]; - - -/** Converts an unsigned integer to string. - * @param value Unsigned interger to convert to string - * @param current Input/Output string buffer. - * Must have at least uintToStringBufferSize chars free. - */ -static inline void -uintToString( LargestUInt value, - char *¤t ) -{ - *--current = 0; - do - { - *--current = char(value % 10) + '0'; - value /= 10; - } - while ( value != 0 ); -} - -} // namespace CSJson { - -#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED diff --git a/external/websockets/android/include/libwebsockets.h b/external/websockets/include/android/libwebsockets.h similarity index 100% rename from external/websockets/android/include/libwebsockets.h rename to external/websockets/include/android/libwebsockets.h diff --git a/external/websockets/ios/include/libwebsockets.h b/external/websockets/include/ios/libwebsockets.h similarity index 100% rename from external/websockets/ios/include/libwebsockets.h rename to external/websockets/include/ios/libwebsockets.h diff --git a/external/websockets/mac/include/libwebsockets.h b/external/websockets/include/mac/libwebsockets.h similarity index 100% rename from external/websockets/mac/include/libwebsockets.h rename to external/websockets/include/mac/libwebsockets.h diff --git a/external/websockets/win32/include/libwebsockets.h b/external/websockets/include/win32/libwebsockets.h similarity index 100% rename from external/websockets/win32/include/libwebsockets.h rename to external/websockets/include/win32/libwebsockets.h diff --git a/external/websockets/win32/include/win32helpers/gettimeofday.h b/external/websockets/include/win32/win32helpers/gettimeofday.h similarity index 100% rename from external/websockets/win32/include/win32helpers/gettimeofday.h rename to external/websockets/include/win32/win32helpers/gettimeofday.h diff --git a/external/websockets/win32/include/win32helpers/websock-w32.h b/external/websockets/include/win32/win32helpers/websock-w32.h similarity index 100% rename from external/websockets/win32/include/win32helpers/websock-w32.h rename to external/websockets/include/win32/win32helpers/websock-w32.h diff --git a/external/websockets/android/Android.mk b/external/websockets/prebuilt/android/Android.mk similarity index 69% rename from external/websockets/android/Android.mk rename to external/websockets/prebuilt/android/Android.mk index 158211b64c..a5f14e0456 100644 --- a/external/websockets/android/Android.mk +++ b/external/websockets/prebuilt/android/Android.mk @@ -3,8 +3,8 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libwebsockets_static LOCAL_MODULE_FILENAME := libwebsockets_static -LOCAL_SRC_FILES := ./lib/$(TARGET_ARCH_ABI)/libwebsockets.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libwebsockets.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android LOCAL_CPPFLAGS := -D__STDC_LIMIT_MACROS=1 LOCAL_EXPORT_CPPFLAGS := -D__STDC_LIMIT_MACROS=1 include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/websockets/ios/lib/libwebsockets.a.REMOVED.git-id b/external/websockets/prebuilt/ios/libwebsockets.a.REMOVED.git-id similarity index 100% rename from external/websockets/ios/lib/libwebsockets.a.REMOVED.git-id rename to external/websockets/prebuilt/ios/libwebsockets.a.REMOVED.git-id diff --git a/external/websockets/mac/lib/libwebsockets.a.REMOVED.git-id b/external/websockets/prebuilt/mac/libwebsockets.a.REMOVED.git-id similarity index 100% rename from external/websockets/mac/lib/libwebsockets.a.REMOVED.git-id rename to external/websockets/prebuilt/mac/libwebsockets.a.REMOVED.git-id diff --git a/external/websockets/tizen/include/libwebsockets.h b/external/websockets/tizen/include/libwebsockets.h deleted file mode 100644 index 28e649c67e..0000000000 --- a/external/websockets/tizen/include/libwebsockets.h +++ /dev/null @@ -1,977 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2013 Andy Green - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#ifndef __LIBWEBSOCKET_H__ -#define __LIBWEBSOCKET_H__ - -#ifdef __cplusplus -extern "C" { -#include -#endif - -#ifdef WIN32 - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -#include -#include "../win32port/win32helpers/websock-w32.h" - -#include "../win32port/win32helpers/gettimeofday.h" - -#define strcasecmp stricmp -#define getdtablesize() 30000 - -typedef int ssize_t; - -#ifdef LWS_DLL -#ifdef LWS_INTERNAL -#define LWS_EXTERN extern __declspec(dllexport) -#else -#define LWS_EXTERN extern __declspec(dllimport) -#endif -#endif - -#else // NOT WIN32 -#include -#include -#endif - -#include - -#ifndef LWS_EXTERN -#define LWS_EXTERN extern -#endif - -#define CONTEXT_PORT_NO_LISTEN 0 -#define MAX_MUX_RECURSION 2 - -enum lws_log_levels { - LLL_ERR = 1 << 0, - LLL_WARN = 1 << 1, - LLL_NOTICE = 1 << 2, - LLL_INFO = 1 << 3, - LLL_DEBUG = 1 << 4, - LLL_PARSER = 1 << 5, - LLL_HEADER = 1 << 6, - LLL_EXT = 1 << 7, - LLL_CLIENT = 1 << 8, - LLL_LATENCY = 1 << 9, - - LLL_COUNT = 10 /* set to count of valid flags */ -}; - -LWS_EXTERN void _lws_log(int filter, const char *format, ...); - -/* notice, warn and log are always compiled in */ -#define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__) -#define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__) -#define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__) -/* - * weaker logging can be deselected at configure time using --disable-debug - * that gets rid of the overhead of checking while keeping _warn and _err - * active - */ -#ifdef _DEBUG - -#define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__) -#define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__) -#define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__) -#define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__) -#define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__) -#define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__) -#define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__) -LWS_EXTERN void lwsl_hexdump(void *buf, size_t len); - -#else /* no debug */ - -#define lwsl_info(...) -#define lwsl_debug(...) -#define lwsl_parser(...) -#define lwsl_header(...) -#define lwsl_ext(...) -#define lwsl_client(...) -#define lwsl_latency(...) -#define lwsl_hexdump(a, b) - -#endif - -enum libwebsocket_context_options { - LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2, - LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = 4, -}; - -enum libwebsocket_callback_reasons { - LWS_CALLBACK_ESTABLISHED, - LWS_CALLBACK_CLIENT_CONNECTION_ERROR, - LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, - LWS_CALLBACK_CLIENT_ESTABLISHED, - LWS_CALLBACK_CLOSED, - LWS_CALLBACK_RECEIVE, - LWS_CALLBACK_CLIENT_RECEIVE, - LWS_CALLBACK_CLIENT_RECEIVE_PONG, - LWS_CALLBACK_CLIENT_WRITEABLE, - LWS_CALLBACK_SERVER_WRITEABLE, - LWS_CALLBACK_HTTP, - LWS_CALLBACK_HTTP_FILE_COMPLETION, - LWS_CALLBACK_HTTP_WRITEABLE, - LWS_CALLBACK_FILTER_NETWORK_CONNECTION, - LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS, - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, - LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION, - LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER, - LWS_CALLBACK_CONFIRM_EXTENSION_OKAY, - LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED, - LWS_CALLBACK_PROTOCOL_INIT, - LWS_CALLBACK_PROTOCOL_DESTROY, - /* external poll() management support */ - LWS_CALLBACK_ADD_POLL_FD, - LWS_CALLBACK_DEL_POLL_FD, - LWS_CALLBACK_SET_MODE_POLL_FD, - LWS_CALLBACK_CLEAR_MODE_POLL_FD, -}; - -#ifndef LWS_NO_EXTENSIONS -enum libwebsocket_extension_callback_reasons { - LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT, - LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT, - LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT, - LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT, - LWS_EXT_CALLBACK_CONSTRUCT, - LWS_EXT_CALLBACK_CLIENT_CONSTRUCT, - LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, - LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION, - LWS_EXT_CALLBACK_DESTROY, - LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, - LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, - LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, - LWS_EXT_CALLBACK_PACKET_TX_PRESEND, - LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, - LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX, - LWS_EXT_CALLBACK_FLUSH_PENDING_TX, - LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX, - LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION, - LWS_EXT_CALLBACK_1HZ, - LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE, - LWS_EXT_CALLBACK_IS_WRITEABLE, - LWS_EXT_CALLBACK_PAYLOAD_TX, - LWS_EXT_CALLBACK_PAYLOAD_RX, -}; -#endif - -enum libwebsocket_write_protocol { - LWS_WRITE_TEXT, - LWS_WRITE_BINARY, - LWS_WRITE_CONTINUATION, - LWS_WRITE_HTTP, - - /* special 04+ opcodes */ - - LWS_WRITE_CLOSE, - LWS_WRITE_PING, - LWS_WRITE_PONG, - - /* flags */ - - LWS_WRITE_NO_FIN = 0x40, - /* - * client packet payload goes out on wire unmunged - * only useful for security tests since normal servers cannot - * decode the content if used - */ - LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80 -}; - -/* - * you need these to look at headers that have been parsed if using the - * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum - * list below is absent, .token = NULL and token_len = 0. Otherwise .token - * points to .token_len chars containing that header content. - */ - -struct lws_tokens { - char *token; - int token_len; -}; - -enum lws_token_indexes { - WSI_TOKEN_GET_URI, - WSI_TOKEN_HOST, - WSI_TOKEN_CONNECTION, - WSI_TOKEN_KEY1, - WSI_TOKEN_KEY2, - WSI_TOKEN_PROTOCOL, - WSI_TOKEN_UPGRADE, - WSI_TOKEN_ORIGIN, - WSI_TOKEN_DRAFT, - WSI_TOKEN_CHALLENGE, - - /* new for 04 */ - WSI_TOKEN_KEY, - WSI_TOKEN_VERSION, - WSI_TOKEN_SWORIGIN, - - /* new for 05 */ - WSI_TOKEN_EXTENSIONS, - - /* client receives these */ - WSI_TOKEN_ACCEPT, - WSI_TOKEN_NONCE, - WSI_TOKEN_HTTP, - WSI_TOKEN_MUXURL, - - /* use token storage to stash these */ - - _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, - _WSI_TOKEN_CLIENT_PEER_ADDRESS, - _WSI_TOKEN_CLIENT_URI, - _WSI_TOKEN_CLIENT_HOST, - _WSI_TOKEN_CLIENT_ORIGIN, - - /* always last real token index*/ - WSI_TOKEN_COUNT, - /* parser state additions */ - WSI_TOKEN_NAME_PART, - WSI_TOKEN_SKIPPING, - WSI_TOKEN_SKIPPING_SAW_CR, - WSI_PARSING_COMPLETE, - WSI_INIT_TOKEN_MUXURL, -}; - -/* - * From RFC 6455 - 1000 - - 1000 indicates a normal closure, meaning that the purpose for - which the connection was established has been fulfilled. - - 1001 - - 1001 indicates that an endpoint is "going away", such as a server - going down or a browser having navigated away from a page. - - 1002 - - 1002 indicates that an endpoint is terminating the connection due - to a protocol error. - - 1003 - - 1003 indicates that an endpoint is terminating the connection - because it has received a type of data it cannot accept (e.g., an - endpoint that understands only text data MAY send this if it - receives a binary message). - - 1004 - - Reserved. The specific meaning might be defined in the future. - - 1005 - - 1005 is a reserved value and MUST NOT be set as a status code in a - Close control frame by an endpoint. It is designated for use in - applications expecting a status code to indicate that no status - code was actually present. - - 1006 - - 1006 is a reserved value and MUST NOT be set as a status code in a - Close control frame by an endpoint. It is designated for use in - applications expecting a status code to indicate that the - connection was closed abnormally, e.g., without sending or - receiving a Close control frame. - - 1007 - - 1007 indicates that an endpoint is terminating the connection - because it has received data within a message that was not - consistent with the type of the message (e.g., non-UTF-8 [RFC3629] - data within a text message). - - 1008 - - 1008 indicates that an endpoint is terminating the connection - because it has received a message that violates its policy. This - is a generic status code that can be returned when there is no - other more suitable status code (e.g., 1003 or 1009) or if there - is a need to hide specific details about the policy. - - 1009 - - 1009 indicates that an endpoint is terminating the connection - because it has received a message that is too big for it to - process. - - 1010 - - 1010 indicates that an endpoint (client) is terminating the - connection because it has expected the server to negotiate one or - more extension, but the server didn't return them in the response - message of the WebSocket handshake. The list of extensions that - are needed SHOULD appear in the /reason/ part of the Close frame. - Note that this status code is not used by the server, because it - can fail the WebSocket handshake instead. - - 1011 - - 1011 indicates that a server is terminating the connection because - it encountered an unexpected condition that prevented it from - fulfilling the request. - - 1015 - - 1015 is a reserved value and MUST NOT be set as a status code in a - Close control frame by an endpoint. It is designated for use in - applications expecting a status code to indicate that the - connection was closed due to a failure to perform a TLS handshake - (e.g., the server certificate can't be verified). -*/ - -enum lws_close_status { - LWS_CLOSE_STATUS_NOSTATUS = 0, - LWS_CLOSE_STATUS_NORMAL = 1000, - LWS_CLOSE_STATUS_GOINGAWAY = 1001, - LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002, - LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003, - LWS_CLOSE_STATUS_RESERVED = 1004, - LWS_CLOSE_STATUS_NO_STATUS = 1005, - LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006, - LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007, - LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008, - LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009, - LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010, - LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011, - LWS_CLOSE_STATUS_TLS_FAILURE = 1015, -}; - -struct libwebsocket; -struct libwebsocket_context; -/* needed even with extensions disabled for create context */ -struct libwebsocket_extension; - -/** - * callback_function() - User server actions - * @context: Websockets context - * @wsi: Opaque websocket instance pointer - * @reason: The reason for the call - * @user: Pointer to per-session user data allocated by library - * @in: Pointer used for some callback reasons - * @len: Length set for some callback reasons - * - * This callback is the way the user controls what is served. All the - * protocol detail is hidden and handled by the library. - * - * For each connection / session there is user data allocated that is - * pointed to by "user". You set the size of this user data area when - * the library is initialized with libwebsocket_create_server. - * - * You get an opportunity to initialize user data when called back with - * LWS_CALLBACK_ESTABLISHED reason. - * - * LWS_CALLBACK_ESTABLISHED: after the server completes a handshake with - * an incoming client - * - * LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has - * been unable to complete a handshake with the remote server - * - * LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: this is the last chance for the - * client user code to examine the http headers - * and decide to reject the connection. If the - * content in the headers is interesting to the - * client (url, etc) it needs to copy it out at - * this point since it will be destroyed before - * the CLIENT_ESTABLISHED call - * - * LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed - * a handshake with the remote server - * - * LWS_CALLBACK_CLOSED: when the websocket session ends - * - * LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a - * remote client, it can be found at *in and is - * len bytes long - * - * LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets, - * they appear with this callback reason. PONG - * packets only exist in 04+ protocol - * - * LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the - * client connection, it can be found at *in and - * is len bytes long - * - * LWS_CALLBACK_HTTP: an http request has come from a client that is not - * asking to upgrade the connection to a websocket - * one. This is a chance to serve http content, - * for example, to send a script to the client - * which will then open the websockets connection. - * @in points to the URI path requested and - * libwebsockets_serve_http_file() makes it very - * simple to send back a file to the client. - * Normally after sending the file you are done - * with the http connection, since the rest of the - * activity will come by websockets from the script - * that was delivered by http, so you will want to - * return 1; to close and free up the connection. - * That's important because it uses a slot in the - * total number of client connections allowed set - * by MAX_CLIENTS. - * - * LWS_CALLBACK_HTTP_WRITEABLE: you can write more down the http protocol - * link now. - * - * LWS_CALLBACK_HTTP_FILE_COMPLETION: a file requested to be send down - * http link has completed. - * - * LWS_CALLBACK_CLIENT_WRITEABLE: - * LWS_CALLBACK_SERVER_WRITEABLE: If you call - * libwebsocket_callback_on_writable() on a connection, you will - * get one of these callbacks coming when the connection socket - * is able to accept another write packet without blocking. - * If it already was able to take another packet without blocking, - * you'll get this callback at the next call to the service loop - * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE - * and servers get LWS_CALLBACK_SERVER_WRITEABLE. - * - * LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to - * the server at network level; the connection is accepted but then - * passed to this callback to decide whether to hang up immediately - * or not, based on the client IP. @in contains the connection - * socket's descriptor. Return non-zero to terminate - * the connection before sending or receiving anything. - * Because this happens immediately after the network connection - * from the client, there's no websocket protocol selected yet so - * this callback is issued only to protocol 0. - * - * LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has - * been received and parsed from the client, but the response is - * not sent yet. Return non-zero to disallow the connection. - * @user is a pointer to an array of struct lws_tokens, you can - * use the header enums lws_token_indexes from libwebsockets.h - * to check for and read the supported header presence and - * content before deciding to allow the handshake to proceed or - * to kill the connection. - * - * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for - * including OpenSSL support, this callback allows your user code - * to perform extra SSL_CTX_load_verify_locations() or similar - * calls to direct OpenSSL where to find certificates the client - * can use to confirm the remote server identity. @user is the - * OpenSSL SSL_CTX* - * - * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for - * including OpenSSL support, this callback allows your user code - * to load extra certifcates into the server which allow it to - * verify the validity of certificates returned by clients. @user - * is the server's OpenSSL SSL_CTX* - * - * LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the - * libwebsockets context was created with the option - * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this - * callback is generated during OpenSSL verification of the cert - * sent from the client. It is sent to protocol[0] callback as - * no protocol has been negotiated on the connection yet. - * Notice that the libwebsockets context and wsi are both NULL - * during this callback. See - * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html - * to understand more detail about the OpenSSL callback that - * generates this libwebsockets callback and the meanings of the - * arguments passed. In this callback, @user is the x509_ctx, - * @in is the ssl pointer and @len is preverify_ok - * Notice that this callback maintains libwebsocket return - * conventions, return 0 to mean the cert is OK or 1 to fail it. - * This also means that if you don't handle this callback then - * the default callback action of returning 0 allows the client - * certificates. - * - * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens - * when a client handshake is being compiled. @user is NULL, - * @in is a char **, it's pointing to a char * which holds the - * next location in the header buffer where you can add - * headers, and @len is the remaining space in the header buffer, - * which is typically some hundreds of bytes. So, to add a canned - * cookie, your handler code might look similar to: - * - * char **p = (char **)in; - * - * if (len < 100) - * return 1; - * - * *p += sprintf(*p, "Cookie: a=b\x0d\x0a"); - * - * return 0; - * - * Notice if you add anything, you just have to take care about - * the CRLF on the line you added. Obviously this callback is - * optional, if you don't handle it everything is fine. - * - * Notice the callback is coming to protocols[0] all the time, - * because there is no specific protocol handshook yet. - * - * LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code - * sees that it does support a requested extension, before - * accepting the extension by additing to the list sent back to - * the client it gives this callback just to check that it's okay - * to use that extension. It calls back to the requested protocol - * and with @in being the extension name, @len is 0 and @user is - * valid. Note though at this time the ESTABLISHED callback hasn't - * happened yet so if you initialize @user content there, @user - * content during this callback might not be useful for anything. - * Notice this callback comes to protocols[0]. - * - * LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED: When a client - * connection is being prepared to start a handshake to a server, - * each supported extension is checked with protocols[0] callback - * with this reason, giving the user code a chance to suppress the - * claim to support that extension by returning non-zero. If - * unhandled, by default 0 will be returned and the extension - * support included in the header to the server. Notice this - * callback comes to protocols[0]. - * - * LWS_CALLBACK_PROTOCOL_INIT: One-time call per protocol so it can - * do initial setup / allocations etc - * - * LWS_CALLBACK_PROTOCOL_DESTROY: One-time call per protocol indicating - * this protocol won't get used at all after this callback, the - * context is getting destroyed. Take the opportunity to - * deallocate everything that was allocated by the protocol. - * - * The next four reasons are optional and only need taking care of if you - * will be integrating libwebsockets sockets into an external polling - * array. - * - * LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop - * internally, but in the case you are integrating with another - * server you will need to have libwebsocket sockets share a - * polling array with the other server. This and the other - * POLL_FD related callbacks let you put your specialized - * poll array interface code in the callback for protocol 0, the - * first protocol you support, usually the HTTP protocol in the - * serving case. This callback happens when a socket needs to be - * added to the polling loop: @in contains the fd, and - * @len is the events bitmap (like, POLLIN). If you are using the - * internal polling loop (the "service" callback), you can just - * ignore these callbacks. - * - * LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor - * needs to be removed from an external polling array. @in is - * the socket desricptor. If you are using the internal polling - * loop, you can just ignore it. - * - * LWS_CALLBACK_SET_MODE_POLL_FD: This callback happens when libwebsockets - * wants to modify the events for the socket descriptor in @in. - * The handler should OR @len on to the events member of the pollfd - * struct for this socket descriptor. If you are using the - * internal polling loop, you can just ignore it. - * - * LWS_CALLBACK_CLEAR_MODE_POLL_FD: This callback occurs when libwebsockets - * wants to modify the events for the socket descriptor in @in. - * The handler should AND ~@len on to the events member of the - * pollfd struct for this socket descriptor. If you are using the - * internal polling loop, you can just ignore it. - */ -LWS_EXTERN int callback(struct libwebsocket_context *context, - struct libwebsocket *wsi, - enum libwebsocket_callback_reasons reason, void *user, - void *in, size_t len); - -typedef int (callback_function)(struct libwebsocket_context *context, - struct libwebsocket *wsi, - enum libwebsocket_callback_reasons reason, void *user, - void *in, size_t len); - -#ifndef LWS_NO_EXTENSIONS -/** - * extension_callback_function() - Hooks to allow extensions to operate - * @context: Websockets context - * @ext: This extension - * @wsi: Opaque websocket instance pointer - * @reason: The reason for the call - * @user: Pointer to per-session user data allocated by library - * @in: Pointer used for some callback reasons - * @len: Length set for some callback reasons - * - * Each extension that is active on a particular connection receives - * callbacks during the connection lifetime to allow the extension to - * operate on websocket data and manage itself. - * - * Libwebsockets takes care of allocating and freeing "user" memory for - * each active extension on each connection. That is what is pointed to - * by the @user parameter. - * - * LWS_EXT_CALLBACK_CONSTRUCT: called when the server has decided to - * select this extension from the list provided by the client, - * just before the server will send back the handshake accepting - * the connection with this extension active. This gives the - * extension a chance to initialize its connection context found - * in @user. - * - * LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT - * but called when client is instantiating this extension. Some - * extensions will work the same on client and server side and then - * you can just merge handlers for both CONSTRUCTS. - * - * LWS_EXT_CALLBACK_DESTROY: called when the connection the extension was - * being used on is about to be closed and deallocated. It's the - * last chance for the extension to deallocate anything it has - * allocated in the user data (pointed to by @user) before the - * user data is deleted. This same callback is used whether you - * are in client or server instantiation context. - * - * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on - * a connection, and a packet of data arrived at the connection, - * it is passed to this callback to give the extension a chance to - * change the data, eg, decompress it. @user is pointing to the - * extension's private connection context data, @in is pointing - * to an lws_tokens struct, it consists of a char * pointer called - * token, and an int called token_len. At entry, these are - * set to point to the received buffer and set to the content - * length. If the extension will grow the content, it should use - * a new buffer allocated in its private user context data and - * set the pointed-to lws_tokens members to point to its buffer. - * - * LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as - * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the - * extension a chance to change websocket data just before it will - * be sent out. Using the same lws_token pointer scheme in @in, - * the extension can change the buffer and the length to be - * transmitted how it likes. Again if it wants to grow the - * buffer safely, it should copy the data into its own buffer and - * set the lws_tokens token pointer to it. - */ -LWS_EXTERN int extension_callback(struct libwebsocket_context *context, - struct libwebsocket_extension *ext, - struct libwebsocket *wsi, - enum libwebsocket_extension_callback_reasons reason, - void *user, void *in, size_t len); - -typedef int (extension_callback_function)(struct libwebsocket_context *context, - struct libwebsocket_extension *ext, - struct libwebsocket *wsi, - enum libwebsocket_extension_callback_reasons reason, - void *user, void *in, size_t len); -#endif - -/** - * struct libwebsocket_protocols - List of protocols and handlers server - * supports. - * @name: Protocol name that must match the one given in the client - * Javascript new WebSocket(url, 'protocol') name - * @callback: The service callback used for this protocol. It allows the - * service action for an entire protocol to be encapsulated in - * the protocol-specific callback - * @per_session_data_size: Each new connection using this protocol gets - * this much memory allocated on connection establishment and - * freed on connection takedown. A pointer to this per-connection - * allocation is passed into the callback in the 'user' parameter - * @rx_buffer_size: if you want atomic frames delivered to the callback, you - * should set this to the size of the biggest legal frame that - * you support. If the frame size is exceeded, there is no - * error, but the buffer will spill to the user callback when - * full, which you can detect by using - * libwebsockets_remaining_packet_payload(). Notice that you - * just talk about frame size here, the LWS_SEND_BUFFER_PRE_PADDING - * and post-padding are automatically also allocated on top. - * @owning_server: the server init call fills in this opaque pointer when - * registering this protocol with the server. - * @protocol_index: which protocol we are starting from zero - * - * This structure represents one protocol supported by the server. An - * array of these structures is passed to libwebsocket_create_server() - * allows as many protocols as you like to be handled by one server. - */ - -struct libwebsocket_protocols { - const char *name; - callback_function *callback; - size_t per_session_data_size; - size_t rx_buffer_size; - - /* - * below are filled in on server init and can be left uninitialized, - * no need for user to use them directly either - */ - - struct libwebsocket_context *owning_server; - int protocol_index; -}; - -#ifndef LWS_NO_EXTENSIONS -/** - * struct libwebsocket_extension - An extension we know how to cope with - * - * @name: Formal extension name, eg, "deflate-stream" - * @callback: Service callback - * @per_session_data_size: Libwebsockets will auto-malloc this much - * memory for the use of the extension, a pointer - * to it comes in the @user callback parameter - * @per_context_private_data: Optional storage for this extension that - * is per-context, so it can track stuff across - * all sessions, etc, if it wants - */ - -struct libwebsocket_extension { - const char *name; - extension_callback_function *callback; - size_t per_session_data_size; - void *per_context_private_data; -}; -#endif - -/** - * struct lws_context_creation_info: parameters to create context with - * - * @port: Port to listen on... you can use 0 to suppress listening on - * any port, that's what you want if you are not running a - * websocket server at all but just using it as a client - * @iface: NULL to bind the listen socket to all interfaces, or the - * interface name, eg, "eth2" - * @protocols: Array of structures listing supported protocols and a protocol- - * specific callback for each one. The list is ended with an - * entry that has a NULL callback pointer. - * It's not const because we write the owning_server member - * @extensions: NULL or array of libwebsocket_extension structs listing the - * extensions this context supports. If you configured with - * --without-extensions, you should give NULL here. - * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want - * to listen using SSL, set to the filepath to fetch the - * server cert from, otherwise NULL for unencrypted - * @ssl_private_key_filepath: filepath to private key if wanting SSL mode, - * else ignored - * @ssl_ca_filepath: CA certificate filepath or NULL - * @ssl_cipher_list: List of valid ciphers to use (eg, - * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL" - * or you can leave it as NULL to get "DEFAULT" - * @gid: group id to change to after setting listen socket, or -1. - * @uid: user id to change to after setting listen socket, or -1. - * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK - * @user: optional user pointer that can be recovered via the context - * pointer using libwebsocket_context_user - * @ka_time: 0 for no keepalive, otherwise apply this keepalive timeout to - * all libwebsocket sockets, client or server - * @ka_probes: if ka_time was nonzero, after the timeout expires how many - * times to try to get a response from the peer before giving up - * and killing the connection - * @ka_interval: if ka_time was nonzero, how long to wait before each ka_probes - * attempt - */ - -struct lws_context_creation_info { - int port; - const char *iface; - struct libwebsocket_protocols *protocols; - struct libwebsocket_extension *extensions; - const char *ssl_cert_filepath; - const char *ssl_private_key_filepath; - const char *ssl_ca_filepath; - const char *ssl_cipher_list; - int gid; - int uid; - unsigned int options; - void *user; - int ka_time; - int ka_probes; - int ka_interval; - -}; - -LWS_EXTERN -void lws_set_log_level(int level, - void (*log_emit_function)(int level, const char *line)); - -LWS_EXTERN void -lwsl_emit_syslog(int level, const char *line); - -LWS_EXTERN struct libwebsocket_context * -libwebsocket_create_context(struct lws_context_creation_info *info); - -LWS_EXTERN void -libwebsocket_context_destroy(struct libwebsocket_context *context); - -LWS_EXTERN int -libwebsocket_service(struct libwebsocket_context *context, int timeout_ms); - -LWS_EXTERN int -libwebsocket_service_fd(struct libwebsocket_context *context, - struct pollfd *pollfd); - -LWS_EXTERN void * -libwebsocket_context_user(struct libwebsocket_context *context); - -/* - * IMPORTANT NOTICE! - * - * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY) - * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE - * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len). - * - * This allows us to add protocol info before and after the data, and send as - * one packet on the network without payload copying, for maximum efficiency. - * - * So for example you need this kind of code to use libwebsocket_write with a - * 128-byte payload - * - * char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING]; - * - * // fill your part of the buffer... for example here it's all zeros - * memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128); - * - * libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128); - * - * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just - * use the whole buffer without taking care of the above. - */ - -/* - * this is the frame nonce plus two header plus 8 length - * there's an additional two for mux extension per mux nesting level - * 2 byte prepend on close will already fit because control frames cannot use - * the big length style - */ - -#define LWS_SEND_BUFFER_PRE_PADDING (4 + 10 + (2 * MAX_MUX_RECURSION)) -#define LWS_SEND_BUFFER_POST_PADDING 4 - -LWS_EXTERN int -libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len, - enum libwebsocket_write_protocol protocol); - -LWS_EXTERN int -libwebsockets_serve_http_file(struct libwebsocket_context *context, - struct libwebsocket *wsi, const char *file, - const char *content_type); -LWS_EXTERN int -libwebsockets_serve_http_file_fragment(struct libwebsocket_context *context, - struct libwebsocket *wsi); - -LWS_EXTERN const struct libwebsocket_protocols * -libwebsockets_get_protocol(struct libwebsocket *wsi); - -LWS_EXTERN int -libwebsocket_callback_on_writable(struct libwebsocket_context *context, - struct libwebsocket *wsi); - -LWS_EXTERN int -libwebsocket_callback_on_writable_all_protocol( - const struct libwebsocket_protocols *protocol); - -LWS_EXTERN int -libwebsocket_get_socket_fd(struct libwebsocket *wsi); - -LWS_EXTERN int -libwebsocket_is_final_fragment(struct libwebsocket *wsi); - -LWS_EXTERN unsigned char -libwebsocket_get_reserved_bits(struct libwebsocket *wsi); - -LWS_EXTERN int -libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable); - -LWS_EXTERN size_t -libwebsockets_remaining_packet_payload(struct libwebsocket *wsi); - -LWS_EXTERN struct libwebsocket * -libwebsocket_client_connect(struct libwebsocket_context *clients, - const char *address, - int port, - int ssl_connection, - const char *path, - const char *host, - const char *origin, - const char *protocol, - int ietf_version_or_minus_one); - -LWS_EXTERN struct libwebsocket * -libwebsocket_client_connect_extended(struct libwebsocket_context *clients, - const char *address, - int port, - int ssl_connection, - const char *path, - const char *host, - const char *origin, - const char *protocol, - int ietf_version_or_minus_one, - void *userdata); - -LWS_EXTERN const char * -libwebsocket_canonical_hostname(struct libwebsocket_context *context); - - -LWS_EXTERN void -libwebsockets_get_peer_addresses(struct libwebsocket_context *context, - struct libwebsocket *wsi, int fd, char *name, int name_len, - char *rip, int rip_len); - -LWS_EXTERN int -libwebsockets_get_random(struct libwebsocket_context *context, - void *buf, int len); - -LWS_EXTERN int -lws_daemonize(const char *_lock_path); - -LWS_EXTERN int -lws_send_pipe_choked(struct libwebsocket *wsi); - -LWS_EXTERN int -lws_frame_is_binary(struct libwebsocket *wsi); - -LWS_EXTERN unsigned char * -libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md); - -LWS_EXTERN int -lws_b64_encode_string(const char *in, int in_len, char *out, int out_size); - -LWS_EXTERN int -lws_b64_decode_string(const char *in, char *out, int out_size); - -LWS_EXTERN const char * -lws_get_library_version(void); - -/* access to headers... only valid while headers valid */ - -LWS_EXTERN int -lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h); - -LWS_EXTERN int -lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len, - enum lws_token_indexes h); - -/* - * Note: this is not normally needed as a user api. It's provided in case it is - * useful when integrating with other app poll loop service code. - */ - -LWS_EXTERN int -libwebsocket_read(struct libwebsocket_context *context, - struct libwebsocket *wsi, - unsigned char *buf, size_t len); - -#ifndef LWS_NO_EXTENSIONS -LWS_EXTERN struct libwebsocket_extension *libwebsocket_get_internal_extensions(); -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/external/websockets/tizen/lib/armv7l/libwebsockets.a.REMOVED.git-id b/external/websockets/tizen/lib/armv7l/libwebsockets.a.REMOVED.git-id deleted file mode 100644 index faa0b3f208..0000000000 --- a/external/websockets/tizen/lib/armv7l/libwebsockets.a.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -aa3206fa03c6719d4daac6f92885d581177ef093 \ No newline at end of file diff --git a/external/websockets/tizen/lib/x86/libwebsockets.a.REMOVED.git-id b/external/websockets/tizen/lib/x86/libwebsockets.a.REMOVED.git-id deleted file mode 100644 index 7e29b6b4fa..0000000000 --- a/external/websockets/tizen/lib/x86/libwebsockets.a.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -2e9ff412352827591ef1389f336b01d179260293 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index fb39932e2e..9ed6038242 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -146,13 +146,25 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static +LOCAL_WHOLE_STATIC_LIBRARIES += spine_static +LOCAL_WHOLE_STATIC_LIBRARIES += gui_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static +LOCAL_WHOLE_STATIC_LIBRARIES += network_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) include $(BUILD_STATIC_LIBRARY) $(call import-module,audio/android) -$(call import-module,external/Box2D) -$(call import-module,external/chipmunk) -$(call import-module,cocos2dx) +$(call import-module,Box2D) +$(call import-module,chipmunk) +$(call import-module,2d) $(call import-module,extensions) +$(call import-module,editor-support/cocosbuilder) +$(call import-module,editor-support/spine) +$(call import-module,gui) +$(call import-module,editor-support/cocostudio) +$(call import-module,network) +$(call import-module,curl/prebuilt/android) diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp index 2dcd3d1558..e2c264c37f 100644 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp +++ b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp @@ -3,6 +3,7 @@ #include "cocos2d.h" #include "controller.h" #include "SimpleAudioEngine.h" +#include "cocostudio/armature/utils/CCArmatureDataManager.h" #include "cocos-ext.h" USING_NS_CC; @@ -15,7 +16,7 @@ AppDelegate::AppDelegate() AppDelegate::~AppDelegate() { // SimpleAudioEngine::end(); - cocos2d::extension::armature::ArmatureDataManager::destoryInstance(); + cocostudio::ArmatureDataManager::destoryInstance(); } bool AppDelegate::applicationDidFinishLaunching() diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 63d44fbea0..63a987f170 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1,9 +1,10 @@ #include "ArmatureScene.h" #include "../../testResource.h" +#include "armature/display/CCSkin.h" using namespace cocos2d; -using namespace cocos2d::extension::armature; +using namespace cocostudio; Layer *NextTest(); Layer *BackTest(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 587938b052..1db21babb0 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -5,6 +5,7 @@ #include "cocos-ext.h" #include "../../VisibleRect.h" #include "../../testBasic.h" +#include "armature/CCArmature.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "../../Box2DTestBed/GLES-Render.h" @@ -96,7 +97,7 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void addArmature(cocos2d::extension::armature::Armature *armature); + virtual void addArmature(cocostudio::Armature *armature); void update(float delta); int armatureCount; @@ -124,11 +125,11 @@ public: virtual void onEnter(); virtual std::string title(); - void animationEvent(cocos2d::extension::armature::Armature *armature, cocos2d::extension::armature::MovementEventType movementType, const char *movementID); + void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const char *movementID); void callback1(); void callback2(); - cocos2d::extension::armature::Armature *armature; + cocostudio::Armature *armature; }; class TestUseMutiplePicture : public ArmatureTestLayer @@ -140,7 +141,7 @@ class TestUseMutiplePicture : public ArmatureTestLayer virtual void onTouchesEnded(const std::vector& touches, Event* event) override; int displayIndex; - cocos2d::extension::armature::Armature *armature; + cocostudio::Armature *armature; }; class TestParticleDisplay : public ArmatureTestLayer @@ -152,7 +153,7 @@ class TestParticleDisplay : public ArmatureTestLayer virtual void onTouchesEnded(const std::vector& touches, Event* event); int animationID; - cocos2d::extension::armature::Armature *armature; + cocostudio::Armature *armature; }; @@ -173,13 +174,13 @@ public: virtual void draw(); virtual void update(float delta); - void onFrameEvent(cocos2d::extension::armature::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); + void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); void initWorld(); - cocos2d::extension::armature::Armature *armature; - cocos2d::extension::armature::Armature *armature2; + cocostudio::Armature *armature; + cocostudio::Armature *armature2; cocos2d::extension::PhysicsSprite *bullet; @@ -202,13 +203,13 @@ public: virtual std::string title(); virtual void update(float delta); - void onFrameEvent(cocos2d::extension::armature::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); + void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); void initWorld(); - cocos2d::extension::armature::Armature *armature; - cocos2d::extension::armature::Armature *armature2; + cocostudio::Armature *armature; + cocostudio::Armature *armature2; cocos2d::extension::PhysicsSprite *bullet; @@ -233,7 +234,7 @@ public: virtual std::string title(); virtual void draw(); - cocos2d::extension::armature::Armature *armature; + cocostudio::Armature *armature; Rect rect; }; @@ -252,7 +253,7 @@ public: virtual std::string title(); virtual void onTouchesEnded(const std::vector& touches, Event* event); - cocos2d::extension::armature::Armature *armature; + cocostudio::Armature *armature; int weaponIndex; }; #endif // __HELLOWORLD_SCENE_H__ \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp index cac0af8b1c..a7325e0663 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp @@ -7,6 +7,7 @@ using namespace cocos2d; using namespace cocos2d::extension; +using namespace cocostudio; ComponentsTestLayer::~ComponentsTestLayer() { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp index 690de6c8ff..9376434f29 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp @@ -2,6 +2,7 @@ #include "SceneController.h" using namespace cocos2d; +using namespace cocostudio; EnemyController::EnemyController(void) { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h index 94c655e31d..891c84cf14 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h @@ -3,9 +3,10 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocoStudio.h" -class EnemyController : public cocos2d::extension::ComController +class EnemyController : public cocostudio::ComController { protected: EnemyController(void); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp index 45ae61cead..83cb56d7df 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp @@ -4,7 +4,7 @@ #include "ProjectileController.h" using namespace cocos2d; -using namespace cocos2d::extension; +using namespace cocostudio; PlayerController::PlayerController(void) { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h index 167454777a..b8baed4f54 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h @@ -3,9 +3,10 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocoStudio.h" -class PlayerController : public cocos2d::extension::ComController +class PlayerController : public cocostudio::ComController { protected: PlayerController(void); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp index 3061326118..101565d4fc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp @@ -3,6 +3,7 @@ #include "EnemyController.h" using namespace cocos2d; +using namespace cocostudio; ProjectileController::ProjectileController(void) { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h index 25bb4c30ec..68c4e1aaf7 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h @@ -3,9 +3,9 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocoStudio.h" - -class ProjectileController : public cocos2d::extension::ComController +class ProjectileController : public cocostudio::ComController { protected: ProjectileController(void); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp index 811423517d..92ee81267f 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp @@ -6,6 +6,7 @@ using namespace cocos2d; using namespace cocos2d::extension; +using namespace cocostudio; SceneController::SceneController(void) : _fAddTargetTime(0.0f) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h index 0fcc2f2bf2..203c74e180 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h @@ -3,9 +3,9 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocoStudio.h" - -class SceneController : public cocos2d::extension::ComController +class SceneController : public cocostudio::ComController { protected: SceneController(void); @@ -32,7 +32,7 @@ public: protected: cocos2d::Array *_targets; - cocos2d::Array *_projectiles; + cocos2d::Array *_projectiles; }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 381a093ff9..8bcdd1e0f4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -2,6 +2,7 @@ #include "UISceneManager.h" //#include "CocosGUIExamplesRegisterScene.h" #include "../ExtensionsTest.h" +#include "CocoStudio.h" const char* gui_scene_names[2] = { @@ -17,9 +18,9 @@ CocosGUITestScene::CocosGUITestScene(bool bPortrait) CocosGUITestScene::~CocosGUITestScene() { - cocos2d::extension::SceneReader::getInstance()->purgeSceneReader(); - cocos2d::extension::ActionManagerEx::purgeActionManager(); - cocos2d::extension::UIHelper::purgeUIHelper(); + cocostudio::SceneReader::getInstance()->purgeSceneReader(); + cocostudio::ActionManagerEx::purgeActionManager(); + gui::UIHelper::purgeUIHelper(); } void CocosGUITestScene::runThisTest() diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h index e1f589eac8..7e2ab4fd00 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h @@ -28,9 +28,11 @@ #include "cocos2d.h" #include "cocos-ext.h" #include "../../testBasic.h" +#include "system/CocosGUI.h" using namespace cocos2d; using namespace cocos2d::extension; +using namespace gui; class CocosGUITestScene : public TestScene { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp index 27ca365d68..b1a288c212 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp @@ -61,19 +61,19 @@ void UIButtonTest::touchEvent(Object *pSender, TouchEventType type) { switch (type) { - case cocos2d::extension::TOUCH_EVENT_BEGAN: + case gui::TOUCH_EVENT_BEGAN: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Down")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_MOVED: + case gui::TOUCH_EVENT_MOVED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Move")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_ENDED: + case gui::TOUCH_EVENT_ENDED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Up")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_CANCELED: + case gui::TOUCH_EVENT_CANCELED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Cancelled")->getCString()); break; @@ -139,19 +139,19 @@ void UIButtonTest_Scale9::touchEvent(Object *pSender, TouchEventType type) { switch (type) { - case cocos2d::extension::TOUCH_EVENT_BEGAN: + case gui::TOUCH_EVENT_BEGAN: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Down")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_MOVED: + case gui::TOUCH_EVENT_MOVED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Move")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_ENDED: + case gui::TOUCH_EVENT_ENDED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Up")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_CANCELED: + case gui::TOUCH_EVENT_CANCELED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Cancelled")->getCString()); break; @@ -213,19 +213,19 @@ void UIButtonTest_PressedAction::touchEvent(Object *pSender, TouchEventType type { switch (type) { - case cocos2d::extension::TOUCH_EVENT_BEGAN: + case gui::TOUCH_EVENT_BEGAN: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Down")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_MOVED: + case gui::TOUCH_EVENT_MOVED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Move")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_ENDED: + case gui::TOUCH_EVENT_ENDED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Up")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_CANCELED: + case gui::TOUCH_EVENT_CANCELED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Cancelled")->getCString()); break; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp index 3855d5afe3..66b0c64a96 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp @@ -67,10 +67,10 @@ bool UICheckBoxTest::init() void UICheckBoxTest::selectedEvent(Object* pSender,CheckBoxEventType type) { switch (type) { - case cocos2d::extension::CHECKBOX_STATE_EVENT_SELECTED: + case gui::CHECKBOX_STATE_EVENT_SELECTED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Selected")->getCString()); break; - case cocos2d::extension::CHECKBOX_STATE_EVENT_UNSELECTED: + case gui::CHECKBOX_STATE_EVENT_UNSELECTED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Unselected")->getCString()); break; default: diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index f1ed704289..3f3cf16873 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -4,6 +4,8 @@ #include "UISceneManager.h" #include "../ExtensionsTest.h" +using namespace gui; + UIScene::UIScene() : m_pSceneTitle(NULL) , m_pUiLayer(NULL) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h index 5e4e724e6c..582964d66a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h @@ -27,9 +27,11 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "system/CocosGUI.h" USING_NS_CC; USING_NS_CC_EXT; +using namespace gui; #define UI_SCENE_CREATE_FUNC(UIScene) \ public: \ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp index 64f7abbd3e..440210eee6 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp @@ -62,19 +62,19 @@ void UITextButtonTest::touchEvent(Object *pSender, TouchEventType type) { switch (type) { - case cocos2d::extension::TOUCH_EVENT_BEGAN: + case gui::TOUCH_EVENT_BEGAN: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Down")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_MOVED: + case gui::TOUCH_EVENT_MOVED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Move")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_ENDED: + case gui::TOUCH_EVENT_ENDED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Up")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_CANCELED: + case gui::TOUCH_EVENT_CANCELED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Cancelled")->getCString()); break; @@ -139,19 +139,19 @@ void UITextButtonTest_Scale9::touchEvent(Object *pSender, TouchEventType type) { switch (type) { - case cocos2d::extension::TOUCH_EVENT_BEGAN: + case gui::TOUCH_EVENT_BEGAN: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Down")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_MOVED: + case gui::TOUCH_EVENT_MOVED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Move")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_ENDED: + case gui::TOUCH_EVENT_ENDED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Up")->getCString()); break; - case cocos2d::extension::TOUCH_EVENT_CANCELED: + case gui::TOUCH_EVENT_CANCELED: m_pDisplayValueLabel->setText(CCString::createWithFormat("Touch Cancelled")->getCString()); break; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index bd85fa7de6..a59f162999 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -2,16 +2,19 @@ #include "cocos-ext.h" #include "../ExtensionsTest.h" #include "SceneEditorTest.h" +#include "CocoStudio.h" +#include "system/CocosGUI.h" using namespace cocos2d; -using namespace cocos2d::extension; +using namespace cocostudio; +using namespace gui; SceneEditorTestLayer::~SceneEditorTestLayer() { - armature::ArmatureDataManager::getInstance()->destoryInstance(); + ArmatureDataManager::getInstance()->destoryInstance(); SceneReader::getInstance()->purgeSceneReader(); - cocos2d::extension::ActionManagerEx::shareManager()->purgeActionManager(); - cocos2d::extension::UIHelper::instance()->purgeUIHelper(); + ActionManagerEx::shareManager()->purgeActionManager(); + UIHelper::instance()->purgeUIHelper(); } SceneEditorTestLayer::SceneEditorTestLayer() @@ -77,7 +80,7 @@ cocos2d::Node* SceneEditorTestLayer::createGameScene() pNode->addChild(menuBack); //ui action - cocos2d::extension::ActionManagerEx::shareManager()->playActionByName("startMenu_1.json","Animation1"); + ActionManagerEx::shareManager()->playActionByName("startMenu_1.json","Animation1"); return pNode; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h index 63c482e972..a477774b8e 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class AnimationsTestLayerLoader : public cocos2d::extension::LayerLoader { +class AnimationsTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(AnimationsTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp index 7224f6dc69..934552aed5 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp @@ -2,6 +2,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; AnimationsTestLayer::AnimationsTestLayer() : mAnimationManager(NULL) @@ -33,7 +34,7 @@ bool AnimationsTestLayer::onAssignCCBMemberVariable(Object * pTarget, const char return false; } -void AnimationsTestLayer::setAnimationManager(cocos2d::extension::CCBAnimationManager *pAnimationManager) +void AnimationsTestLayer::setAnimationManager(cocosbuilder::CCBAnimationManager *pAnimationManager) { CC_SAFE_RELEASE_NULL(mAnimationManager); mAnimationManager = pAnimationManager; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h index 207af01c91..b158784607 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h @@ -3,11 +3,12 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" class AnimationsTestLayer : public cocos2d::Layer -, public cocos2d::extension::CCBSelectorResolver -, public cocos2d::extension::CCBMemberVariableAssigner +, public cocosbuilder::CCBSelectorResolver +, public cocosbuilder::CCBMemberVariableAssigner { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(AnimationsTestLayer, create); @@ -24,10 +25,10 @@ public: void onControlButtonJumpClicked(cocos2d::Object * sender, cocos2d::extension::Control::EventType pControlEvent); void onControlButtonFunkyClicked(cocos2d::Object * sender, cocos2d::extension::Control::EventType pControlEvent); - void setAnimationManager(cocos2d::extension::CCBAnimationManager *pAnimationManager); + void setAnimationManager(cocosbuilder::CCBAnimationManager *pAnimationManager); private: - cocos2d::extension::CCBAnimationManager *mAnimationManager; + cocosbuilder::CCBAnimationManager *mAnimationManager; }; #endif \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp index 17a7ba9d1c..238918e170 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp @@ -2,6 +2,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; ButtonTestLayer::ButtonTestLayer() : mControlEventLabel(NULL) @@ -28,7 +29,7 @@ bool ButtonTestLayer::onAssignCCBMemberVariable(Object * pTarget, const char * p return false; } -void ButtonTestLayer::onControlButtonClicked(cocos2d::Object *pSender, cocos2d::extension::Control::EventType pControlEvent) { +void ButtonTestLayer::onControlButtonClicked(cocos2d::Object *pSender, Control::EventType pControlEvent) { switch(pControlEvent) { case Control::EventType::TOUCH_DOWN: this->mControlEventLabel->setString("Touch Down."); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h index fb56110015..9468229dd8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h @@ -3,11 +3,12 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" class ButtonTestLayer : public cocos2d::Layer - , public cocos2d::extension::CCBMemberVariableAssigner - , public cocos2d::extension::CCBSelectorResolver + , public cocosbuilder::CCBMemberVariableAssigner + , public cocosbuilder::CCBSelectorResolver { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(ButtonTestLayer, create); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h index 76b2798739..2729b0d260 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class ButtonTestLayerLoader : public cocos2d::extension::LayerLoader { +class ButtonTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ButtonTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp index 7efbe7c920..f63af2aca5 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp @@ -28,6 +28,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; void CocosBuilderTestScene::runThisTest() { /* Create an autorelease NodeLoaderLibrary. */ @@ -36,7 +37,7 @@ void CocosBuilderTestScene::runThisTest() { ccNodeLoaderLibrary->registerNodeLoader("HelloCocosBuilderLayer", HelloCocosBuilderLayerLoader::loader()); /* Create an autorelease CCBReader. */ - cocos2d::extension::CCBReader * ccbReader = new cocos2d::extension::CCBReader(ccNodeLoaderLibrary); + cocosbuilder::CCBReader * ccbReader = new cocosbuilder::CCBReader(ccNodeLoaderLibrary); /* Read a ccbi file. */ auto node = ccbReader->readNodeGraphFromFile("ccb/HelloCocosBuilder.ccbi", this); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp index 90deb8a29e..5837fdd368 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp @@ -12,6 +12,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; HelloCocosBuilderLayer::HelloCocosBuilderLayer() : mBurstSprite(NULL) @@ -34,7 +35,7 @@ void HelloCocosBuilderLayer::openTest(const char * pCCBFileName, const char * no } /* Create an autorelease CCBReader. */ - cocos2d::extension::CCBReader * ccbReader = new cocos2d::extension::CCBReader(ccNodeLoaderLibrary); + cocosbuilder::CCBReader * ccbReader = new cocosbuilder::CCBReader(ccNodeLoaderLibrary); ccbReader->autorelease(); /* Read a ccbi file. */ @@ -61,7 +62,7 @@ void HelloCocosBuilderLayer::openTest(const char * pCCBFileName, const char * no } -void HelloCocosBuilderLayer::onNodeLoaded(cocos2d::Node * node, cocos2d::extension::NodeLoader * nodeLoader) { +void HelloCocosBuilderLayer::onNodeLoaded(cocos2d::Node * node, cocosbuilder::NodeLoader * nodeLoader) { auto ccRotateBy = RotateBy::create(20.0f, 360); auto ccRepeatForever = RepeatForever::create(ccRotateBy); this->mBurstSprite->runAction(ccRepeatForever); @@ -91,7 +92,7 @@ bool HelloCocosBuilderLayer::onAssignCCBMemberVariable(Object * pTarget, const c return false; } -bool HelloCocosBuilderLayer::onAssignCCBCustomProperty(Object* pTarget, const char* pMemberVariableName, cocos2d::extension::CCBValue* pCCBValue) +bool HelloCocosBuilderLayer::onAssignCCBCustomProperty(Object* pTarget, const char* pMemberVariableName, cocosbuilder::CCBValue* pCCBValue) { bool bRet = false; if (pTarget == this) @@ -126,19 +127,19 @@ bool HelloCocosBuilderLayer::onAssignCCBCustomProperty(Object* pTarget, const ch return bRet; } -void HelloCocosBuilderLayer::onMenuTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) { +void HelloCocosBuilderLayer::onMenuTestClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestMenus.ccbi", "TestMenusLayer", MenuTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onSpriteTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) { +void HelloCocosBuilderLayer::onSpriteTestClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestSprites.ccbi", "TestSpritesLayer", SpriteTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onButtonTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) { +void HelloCocosBuilderLayer::onButtonTestClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestButtons.ccbi", "TestButtonsLayer", ButtonTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onAnimationsTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) { +void HelloCocosBuilderLayer::onAnimationsTestClicked(Object * sender, Control::EventType pControlEvent) { /* Create an autorelease NodeLoaderLibrary. */ NodeLoaderLibrary * ccNodeLoaderLibrary = NodeLoaderLibrary::newDefaultNodeLoaderLibrary(); @@ -148,7 +149,7 @@ void HelloCocosBuilderLayer::onAnimationsTestClicked(Object * sender, cocos2d::e /* Create an autorelease CCBReader. */ - cocos2d::extension::CCBReader * ccbReader = new cocos2d::extension::CCBReader(ccNodeLoaderLibrary); + cocosbuilder::CCBReader * ccbReader = new cocosbuilder::CCBReader(ccNodeLoaderLibrary); ccbReader->autorelease(); /* Read a ccbi file. */ @@ -179,16 +180,16 @@ void HelloCocosBuilderLayer::onAnimationsTestClicked(Object * sender, cocos2d::e //this->openTest("TestAnimations.ccbi", "TestAnimationsLayer", AnimationsTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onParticleSystemTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) { +void HelloCocosBuilderLayer::onParticleSystemTestClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestParticleSystems.ccbi", "TestParticleSystemsLayer", ParticleSystemTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onScrollViewTestClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) +void HelloCocosBuilderLayer::onScrollViewTestClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestScrollViews.ccbi", "TestScrollViewsLayer", ScrollViewTestLayerLoader::loader()); } -void HelloCocosBuilderLayer::onTimelineCallbackSoundClicked(Object * sender, cocos2d::extension::Control::EventType pControlEvent) +void HelloCocosBuilderLayer::onTimelineCallbackSoundClicked(Object * sender, Control::EventType pControlEvent) { this->openTest("ccb/ccb/TestTimelineCallback.ccbi", "TimelineCallbackTestLayer", TimelineCallbackTestLayerLoader::loader()); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h index 7a1bdd577f..b20072bc30 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h @@ -3,6 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" /* * Note: for some pretty hard fucked up reason, the order of inheritance is important! @@ -16,9 +17,9 @@ */ class HelloCocosBuilderLayer : public cocos2d::Layer -, public cocos2d::extension::CCBSelectorResolver -, public cocos2d::extension::CCBMemberVariableAssigner -, public cocos2d::extension::NodeLoaderListener +, public cocosbuilder::CCBSelectorResolver +, public cocosbuilder::CCBMemberVariableAssigner +, public cocosbuilder::NodeLoaderListener { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(HelloCocosBuilderLayer, create); @@ -26,13 +27,13 @@ class HelloCocosBuilderLayer HelloCocosBuilderLayer(); virtual ~HelloCocosBuilderLayer(); - void openTest(const char * pCCBFileName, const char * nodeName = NULL, cocos2d::extension::NodeLoader * nodeLoader = NULL); + void openTest(const char * pCCBFileName, const char * nodeName = NULL, cocosbuilder::NodeLoader * nodeLoader = NULL); virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, const char * pSelectorName); virtual cocos2d::extension::Control::Handler onResolveCCBCCControlSelector(cocos2d::Object * pTarget, const char * pSelectorName); virtual bool onAssignCCBMemberVariable(cocos2d::Object * pTarget, const char * pMemberVariableName, cocos2d::Node * node); - virtual bool onAssignCCBCustomProperty(Object* pTarget, const char* pMemberVariableName, cocos2d::extension::CCBValue* pCCBValue); - virtual void onNodeLoaded(cocos2d::Node * node, cocos2d::extension::NodeLoader * nodeLoader); + virtual bool onAssignCCBCustomProperty(Object* pTarget, const char* pMemberVariableName, cocosbuilder::CCBValue* pCCBValue); + virtual void onNodeLoaded(cocos2d::Node * node, cocosbuilder::NodeLoader * nodeLoader); void onMenuTestClicked(cocos2d::Object * sender, cocos2d::extension::Control::EventType pControlEvent); void onSpriteTestClicked(cocos2d::Object * sender, cocos2d::extension::Control::EventType pControlEvent); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h index 8c1174d575..60067f2dfa 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class HelloCocosBuilderLayerLoader : public cocos2d::extension::LayerLoader { +class HelloCocosBuilderLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(HelloCocosBuilderLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h index 5ad7f89ac9..acde02a4a2 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class LabelTestLayerLoader : public cocos2d::extension::LayerLoader { +class LabelTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LabelTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp index 5f53a6d61d..f29fd86cad 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp @@ -2,6 +2,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; MenuTestLayer::MenuTestLayer() : mMenuItemStatusLabelBMFont(NULL) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h index 0f0a22d85d..4dfe4468e7 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h @@ -3,11 +3,12 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" class MenuTestLayer : public cocos2d::Layer - , public cocos2d::extension::CCBSelectorResolver - , public cocos2d::extension::CCBMemberVariableAssigner + , public cocosbuilder::CCBSelectorResolver + , public cocosbuilder::CCBMemberVariableAssigner { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(MenuTestLayer, create); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h index d51a2f3ed5..40b40cb7b2 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class MenuTestLayerLoader : public cocos2d::extension::LayerLoader { +class MenuTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(MenuTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h index c2410c7d8e..e3d8457818 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class ParticleSystemTestLayerLoader : public cocos2d::extension::LayerLoader { +class ParticleSystemTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ParticleSystemTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h index 17c736a28c..5a2c604ac4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class ScrollViewTestLayerLoader : public cocos2d::extension::LayerLoader { +class ScrollViewTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(ScrollViewTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h index 47aca5a5de..4fbd717017 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class SpriteTestLayerLoader : public cocos2d::extension::LayerLoader { +class SpriteTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(SpriteTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp index 825c08c27f..e54a947bec 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp @@ -2,6 +2,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; SEL_MenuHandler TestHeaderLayer::onResolveCCBCCMenuItemSelector(Object * pTarget, const char * pSelectorName) { CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "onBackClicked", TestHeaderLayer::onBackClicked); @@ -14,7 +15,7 @@ Control::Handler TestHeaderLayer::onResolveCCBCCControlSelector(Object * pTarget return NULL; } -void TestHeaderLayer::onNodeLoaded(cocos2d::Node * node, cocos2d::extension::NodeLoader * nodeLoader) +void TestHeaderLayer::onNodeLoaded(cocos2d::Node * node, cocosbuilder::NodeLoader * nodeLoader) { CCLOG("TestHeaderLayer::onNodeLoaded"); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h index 936d89d1d6..316f93d62b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h @@ -3,18 +3,19 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" class TestHeaderLayer : public cocos2d::Layer - , public cocos2d::extension::CCBSelectorResolver -, public cocos2d::extension::NodeLoaderListener + , public cocosbuilder::CCBSelectorResolver +, public cocosbuilder::NodeLoaderListener { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(TestHeaderLayer, create); virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, const char * pSelectorName); virtual cocos2d::extension::Control::Handler onResolveCCBCCControlSelector(cocos2d::Object * pTarget, const char * pSelectorName); - virtual void onNodeLoaded(cocos2d::Node * node, cocos2d::extension::NodeLoader * nodeLoader); + virtual void onNodeLoaded(cocos2d::Node * node, cocosbuilder::NodeLoader * nodeLoader); void onBackClicked(cocos2d::Object * sender); }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h index a834494c7e..7217c582c5 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h @@ -6,7 +6,7 @@ /* Forward declaration. */ class CCBReader; -class TestHeaderLayerLoader : public cocos2d::extension::LayerLoader { +class TestHeaderLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(TestHeaderLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h index 4e60a97c38..1b08d786ab 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h @@ -3,7 +3,7 @@ #include "TimelineCallbackTestLayer.h" -class TimelineCallbackTestLayerLoader : public cocos2d::extension::LayerLoader { +class TimelineCallbackTestLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(TimelineCallbackTestLayerLoader, loader); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp index 72c85fe9d8..ba9dcbafe0 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp @@ -3,6 +3,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; TimelineCallbackTestLayer::TimelineCallbackTestLayer() : _helloLabel(NULL) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h index 213c70c1e9..4dd14b8b73 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h @@ -3,11 +3,12 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "CocosBuilder.h" class TimelineCallbackTestLayer : public cocos2d::Layer - , public cocos2d::extension::CCBSelectorResolver - , public cocos2d::extension::CCBMemberVariableAssigner + , public cocosbuilder::CCBSelectorResolver + , public cocosbuilder::CCBMemberVariableAssigner { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(TimelineCallbackTestLayer, create); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp index 2242198904..0704192e5f 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp @@ -4,6 +4,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace network; HttpClientTest::HttpClientTest() : _labelStatusCode(NULL) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h index c838b7c224..ab432491dc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h @@ -3,6 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" +#include "HttpClient.h" class HttpClientTest : public cocos2d::Layer { @@ -19,7 +20,7 @@ public: void onMenuDeleteTestClicked(cocos2d::Object *sender); //Http Response Callback - void onHttpRequestCompleted(cocos2d::extension::HttpClient *sender, cocos2d::extension::HttpResponse *response); + void onHttpRequestCompleted(network::HttpClient *sender, network::HttpResponse *response); private: cocos2d::LabelTTF* _labelStatusCode; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp index 0fea620718..58e9650a12 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp @@ -12,6 +12,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace network; SocketIOTestLayer::SocketIOTestLayer(void) : _sioClient(NULL) @@ -206,7 +207,7 @@ void SocketIOTestLayer::onMenuTestEndpointDisconnectClicked(cocos2d::Object *sen // Delegate methods -void SocketIOTestLayer::onConnect(cocos2d::extension::SIOClient* client) +void SocketIOTestLayer::onConnect(network::SIOClient* client) { log("SocketIOTestLayer::onConnect called"); @@ -216,7 +217,7 @@ void SocketIOTestLayer::onConnect(cocos2d::extension::SIOClient* client) } -void SocketIOTestLayer::onMessage(cocos2d::extension::SIOClient* client, const std::string& data) +void SocketIOTestLayer::onMessage(network::SIOClient* client, const std::string& data) { log("SocketIOTestLayer::onMessage received: %s", data.c_str()); @@ -226,7 +227,7 @@ void SocketIOTestLayer::onMessage(cocos2d::extension::SIOClient* client, const s } -void SocketIOTestLayer::onClose(cocos2d::extension::SIOClient* client) +void SocketIOTestLayer::onClose(network::SIOClient* client) { log("SocketIOTestLayer::onClose called"); @@ -246,7 +247,7 @@ void SocketIOTestLayer::onClose(cocos2d::extension::SIOClient* client) } -void SocketIOTestLayer::onError(cocos2d::extension::SIOClient* client, const std::string& data) +void SocketIOTestLayer::onError(network::SIOClient* client, const std::string& data) { log("SocketIOTestLayer::onError received: %s", data.c_str()); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h index fc1ebd8b2e..596738749c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h @@ -10,20 +10,20 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "network/SocketIO.h" +#include "SocketIO.h" class SocketIOTestLayer : public cocos2d::Layer - , public cocos2d::extension::SocketIO::SIODelegate + , public network::SocketIO::SIODelegate { public: SocketIOTestLayer(void); virtual ~SocketIOTestLayer(void); - virtual void onConnect(cocos2d::extension::SIOClient* client); - virtual void onMessage(cocos2d::extension::SIOClient* client, const std::string& data); - virtual void onClose(cocos2d::extension::SIOClient* client); - virtual void onError(cocos2d::extension::SIOClient* client, const std::string& data); + virtual void onConnect(network::SIOClient* client); + virtual void onMessage(network::SIOClient* client, const std::string& data); + virtual void onClose(network::SIOClient* client); + virtual void onError(network::SIOClient* client, const std::string& data); void toExtensionsMainLayer(cocos2d::Object *sender); @@ -38,10 +38,10 @@ public: void onMenuTestEndpointDisconnectClicked(cocos2d::Object *sender); - void testevent(cocos2d::extension::SIOClient *client, const std::string& data); - void echotest(cocos2d::extension::SIOClient *client, const std::string& data); + void testevent(network::SIOClient *client, const std::string& data); + void echotest(network::SIOClient *client, const std::string& data); - cocos2d::extension::SIOClient *_sioClient, *_sioEndpoint; + network::SIOClient *_sioClient, *_sioEndpoint; cocos2d::LabelTTF *_sioClientStatus; }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp index be60e5405d..39a3ec5cc1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp @@ -11,6 +11,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace network; WebSocketTestLayer::WebSocketTestLayer() : _wsiSendText(NULL) @@ -107,7 +108,7 @@ WebSocketTestLayer::~WebSocketTestLayer() } // Delegate methods -void WebSocketTestLayer::onOpen(cocos2d::extension::WebSocket* ws) +void WebSocketTestLayer::onOpen(network::WebSocket* ws) { log("Websocket (%p) opened", ws); if (ws == _wsiSendText) @@ -124,7 +125,7 @@ void WebSocketTestLayer::onOpen(cocos2d::extension::WebSocket* ws) } } -void WebSocketTestLayer::onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data) +void WebSocketTestLayer::onMessage(network::WebSocket* ws, const network::WebSocket::Data& data) { if (!data.isBinary) { @@ -161,7 +162,7 @@ void WebSocketTestLayer::onMessage(cocos2d::extension::WebSocket* ws, const coco } } -void WebSocketTestLayer::onClose(cocos2d::extension::WebSocket* ws) +void WebSocketTestLayer::onClose(network::WebSocket* ws) { log("websocket instance (%p) closed.", ws); if (ws == _wsiSendText) @@ -180,7 +181,7 @@ void WebSocketTestLayer::onClose(cocos2d::extension::WebSocket* ws) CC_SAFE_DELETE(ws); } -void WebSocketTestLayer::onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error) +void WebSocketTestLayer::onError(network::WebSocket* ws, const network::WebSocket::ErrorCode& error) { log("Error was fired, error code: %d", error); if (ws == _wsiError) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h index 58a781ecf5..7ca1080e40 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h @@ -11,20 +11,20 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "network/WebSocket.h" +#include "WebSocket.h" class WebSocketTestLayer : public cocos2d::Layer -, public cocos2d::extension::WebSocket::Delegate +, public network::WebSocket::Delegate { public: WebSocketTestLayer(); virtual ~WebSocketTestLayer(); - virtual void onOpen(cocos2d::extension::WebSocket* ws); - virtual void onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data); - virtual void onClose(cocos2d::extension::WebSocket* ws); - virtual void onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error); + virtual void onOpen(network::WebSocket* ws); + virtual void onMessage(network::WebSocket* ws, const network::WebSocket::Data& data); + virtual void onClose(network::WebSocket* ws); + virtual void onError(network::WebSocket* ws, const network::WebSocket::ErrorCode& error); void toExtensionsMainLayer(cocos2d::Object *sender); @@ -33,9 +33,9 @@ public: void onMenuSendBinaryClicked(cocos2d::Object *sender); private: - cocos2d::extension::WebSocket* _wsiSendText; - cocos2d::extension::WebSocket* _wsiSendBinary; - cocos2d::extension::WebSocket* _wsiError; + network::WebSocket* _wsiSendText; + network::WebSocket* _wsiSendBinary; + network::WebSocket* _wsiError; cocos2d::LabelTTF* _sendTextStatus; cocos2d::LabelTTF* _sendBinaryStatus; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp index 784b548fa9..f847090b47 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp @@ -1,6 +1,6 @@ #include "NotificationCenterTest.h" #include "../ExtensionsTest.h" -#include "support/CCNotificationCenter.h" +#include "CCNotificationCenter.h" #define kTagLight 100 #define kTagConnect 200 diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h index 5c822fc95a..fcfdba36ec 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h @@ -5,7 +5,7 @@ #define __PERFORMANCE_ALLOC_TEST_H__ #include "PerformanceTest.h" -#include "support/CCProfiling.h" +#include "CCProfiling.h" class AllocBasicLayer : public PerformBasicLayer { diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h index 7c6a1efea4..95ce5914b5 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h @@ -2,7 +2,7 @@ #define __PERFORMANCE_NODE_CHILDREN_TEST_H__ #include "PerformanceTest.h" -#include "support/CCProfiling.h" +#include "CCProfiling.h" class NodeChildrenMenuLayer : public PerformBasicLayer { diff --git a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp b/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp index 0912cb419e..385be5b1c1 100644 --- a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp @@ -27,10 +27,11 @@ #include #include #include + #include "spine/spine.h" using namespace cocos2d; -using namespace cocos2d::extension; using namespace std; +using namespace spine; //------------------------------------------------------------------ // diff --git a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h b/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h index 95f4c9b249..58c4b13d0f 100644 --- a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h +++ b/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h @@ -38,7 +38,7 @@ public: class SpineTestLayer: public cocos2d::Layer { private: - cocos2d::extension::CCSkeletonAnimation* skeletonNode; + spine::CCSkeletonAnimation* skeletonNode; public: diff --git a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp index 0cf00124d1..5aea719250 100644 --- a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp @@ -1,6 +1,6 @@ #include "TextureAtlasEncryptionTest.h" #include "../testResource.h" -#include "support/zip_support/ZipUtils.h" +#include "ZipUtils.h" std::string TextureAtlasEncryptionDemo::title() { diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index 77f3476e51..5892c3e6e2 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -1,6 +1,7 @@ #include "testBasic.h" #include "controller.h" #include "cocos-ext.h" +#include "cocostudio/armature/utils/CCArmatureDataManager.h" TestScene::TestScene(bool bPortrait) { @@ -50,7 +51,7 @@ void TestScene::onEnter() scene->release(); } - cocos2d::extension::armature::ArmatureDataManager::destoryInstance(); + cocostudio::ArmatureDataManager::destoryInstance(); }); auto menu =Menu::create(menuItem, NULL); diff --git a/samples/Cpp/TestCpp/proj.android/build_native.sh b/samples/Cpp/TestCpp/proj.android/build_native.sh index ab5cdc78f8..69464cc437 100755 --- a/samples/Cpp/TestCpp/proj.android/build_native.sh +++ b/samples/Cpp/TestCpp/proj.android/build_native.sh @@ -95,4 +95,4 @@ rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_a8.pvr.gz echo "Using prebuilt externals" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" diff --git a/samples/Cpp/TestCpp/proj.android/jni/Android.mk b/samples/Cpp/TestCpp/proj.android/jni/Android.mk index d72618a488..c3190eef74 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Android.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Android.mk @@ -11,18 +11,7 @@ LOCAL_SRC_FILES := testcpp/main.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_testcpp_common -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static include $(BUILD_SHARED_LIBRARY) $(call import-module,samples/Cpp/TestCpp) -$(call import-module,cocos2dx) -$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) -$(call import-module,audio/android) -$(call import-module,extensions) -$(call import-module,external/Box2D) -$(call import-module,cocos2dx/platform/android) From 8cad67a3e101b6b45ffa01e10e71dfd985e7aff4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 15 Oct 2013 13:36:03 -0700 Subject: [PATCH 145/557] small fixes for the Xcode projects --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 1 + build/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id delete mode 100644 build/samples.xcodeproj/project.pbxproj.REMOVED.git-id diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index f6b6061df1..58407b8dbe 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1513bb8f2a786cfa406d2d6d9001e99abdd009ac \ No newline at end of file +fe809a5d9a1b0e24462a215517e08f6e525cd6b7 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id new file mode 100644 index 0000000000..0bbb816654 --- /dev/null +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -0,0 +1 @@ +71d9dbdbc4e4e33dbb8fb7ad109611f197a0cec7 \ No newline at end of file diff --git a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 3fe3b732a7..0000000000 --- a/build/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -561cdc247f0444ca86efc535600901b035e19ffa \ No newline at end of file From 7dc8aeb156a200d1626a9929d69b682deb6763e7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 11:19:01 +0800 Subject: [PATCH 146/557] issue #2905: Updating include path for 'cocostudio' module, adding 'cocostudio' prefix. --- .../cocostudio/action/CCActionFrameEasing.cpp | 2 +- .../cocostudio/action/CCActionFrameEasing.h | 2 +- .../cocostudio/action/CCActionManagerEx.cpp | 2 +- .../cocostudio/action/CCActionManagerEx.h | 2 +- .../cocostudio/action/CCActionNode.cpp | 2 +- .../cocostudio/action/CCActionNode.h | 2 +- .../cocostudio/action/CCActionObject.cpp | 2 +- .../cocostudio/action/CCActionObject.h | 2 +- .../animation/CCArmatureAnimation.cpp | 10 +- .../armature/animation/CCProcessBase.cpp | 2 +- .../armature/animation/CCProcessBase.h | 4 +- .../cocostudio/armature/animation/CCTween.cpp | 10 +- .../cocostudio/armature/animation/CCTween.h | 2 +- .../cocostudio/armature/datas/CCDatas.cpp | 4 +- .../cocostudio/armature/datas/CCDatas.h | 4 +- .../armature/display/CCBatchNode.cpp | 4 +- .../cocostudio/armature/display/CCBatchNode.h | 2 +- .../armature/display/CCDecorativeDisplay.h | 4 +- .../armature/display/CCDisplayFactory.cpp | 12 +- .../armature/display/CCDisplayFactory.h | 4 +- .../armature/display/CCDisplayManager.cpp | 8 +- .../armature/display/CCDisplayManager.h | 6 +- .../cocostudio/armature/display/CCSkin.cpp | 6 +- .../cocostudio/armature/display/CCSkin.h | 4 +- .../armature/physics/CCColliderDetector.cpp | 4 +- .../armature/physics/CCColliderDetector.h | 4 +- .../armature/utils/CCArmatureDataManager.h | 2 +- .../armature/utils/CCDataReaderHelper.cpp | 2 +- .../armature/utils/CCDataReaderHelper.h | 6 +- .../armature/utils/CCTransformHelp.h | 2 +- .../cocostudio/components/CCComAttribute.h | 2 +- .../cocostudio/json/CSContentJsonDictionary.h | 2 +- .../cocostudio/reader/CCSGUIReader.cpp | 4 +- .../cocostudio/reader/CCSGUIReader.h | 2 +- .../cocostudio/reader/CCSSceneReader.h | 2 +- cocos/gui/layouts/Layout.cpp | 2 +- cocos/gui/system/CocosGUI.h | 2 +- cocos/gui/system/UIHelper.cpp | 4 +- cocos/gui/system/UIHelper.h | 2 +- cocos/gui/widgets/UIButton.cpp | 2 +- cocos/gui/widgets/UIImageView.cpp | 2 +- cocos/gui/widgets/UILoadingBar.cpp | 2 +- cocos/gui/widgets/UISlider.cpp | 2 +- samples/Cpp/TestCpp/Android.mk | 262 +++++++++--------- samples/Cpp/TestCpp/Classes/AppDelegate.cpp | 3 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.h | 2 +- .../EnemyController.h | 2 +- .../PlayerController.h | 2 +- .../ProjectileController.h | 2 +- .../SceneController.h | 2 +- .../CocoStudioGUITest/CocosGUIScene.cpp | 3 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 2 +- .../AnimationsTest/AnimationsTestLayer.h | 2 +- .../ButtonTest/ButtonTestLayer.h | 2 +- .../HelloCocosBuilderLayer.h | 2 +- .../CocosBuilderTest/MenuTest/MenuTestLayer.h | 2 +- .../TestHeader/TestHeaderLayer.h | 2 +- .../TimelineCallbackTestLayer.h | 2 +- samples/Cpp/TestCpp/Classes/testBasic.cpp | 2 +- 60 files changed, 224 insertions(+), 224 deletions(-) diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp index 1e6513b56c..74c7467c71 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp @@ -24,7 +24,7 @@ #include #include "CCActionFrameEasing.h" -#include "json/DictionaryHelper.h" +#include "cocostudio/json/DictionaryHelper.h" namespace cocostudio { #ifndef M_PI_X_2 diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h index aa6fd570e4..74ba932d4c 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h +++ b/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h @@ -26,7 +26,7 @@ #define __ActionFrameEasing_H__ #include "cocos2d.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp index 8d842715b1..b863c1f9a2 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "CCActionManagerEx.h" -#include "json/DictionaryHelper.h" +#include "cocostudio/json/DictionaryHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h b/cocos/editor-support/cocostudio/action/CCActionManagerEx.h index 4c757dfa37..8776fce030 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/action/CCActionManagerEx.h @@ -27,7 +27,7 @@ #include "cocos2d.h" #include "CCActionObject.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.cpp b/cocos/editor-support/cocostudio/action/CCActionNode.cpp index ca7db6cc5f..1390d64ed6 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionNode.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCActionFrameEasing.h" #include "base-classes/UIWidget.h" #include "system/UIHelper.h" -#include "json/DictionaryHelper.h" +#include "cocostudio/json/DictionaryHelper.h" using namespace cocos2d; using namespace gui; diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.h b/cocos/editor-support/cocostudio/action/CCActionNode.h index 9e69981bbb..67a424bda8 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.h +++ b/cocos/editor-support/cocostudio/action/CCActionNode.h @@ -27,7 +27,7 @@ #include "cocos2d.h" #include "CCActionFrame.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.cpp b/cocos/editor-support/cocostudio/action/CCActionObject.cpp index c649268a23..e218dca888 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/action/CCActionObject.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "CCActionObject.h" -#include "json/DictionaryHelper.h" +#include "cocostudio/json/DictionaryHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.h b/cocos/editor-support/cocostudio/action/CCActionObject.h index 34807e2127..7137f57355 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.h +++ b/cocos/editor-support/cocostudio/action/CCActionObject.h @@ -27,7 +27,7 @@ #include "cocos2d.h" #include "CCActionNode.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp index 4c42af7d1e..5490b4f4ee 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ #include "CCArmatureAnimation.h" -#include "armature/CCArmature.h" -#include "armature/CCBone.h" -#include "armature/utils/CCArmatureDefine.h" -#include "armature/utils/CCUtilMath.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/armature/CCBone.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/utils/CCUtilMath.h" +#include "cocostudio/armature/datas/CCDatas.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp index a30f68abd4..e235c1cb1e 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCProcessBase.h" -#include "armature/utils/CCUtilMath.h" +#include "cocostudio/armature/utils/CCUtilMath.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h index dbde23dd1f..3d247e51a4 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h @@ -26,8 +26,8 @@ THE SOFTWARE. #ifndef __CCPROCESSBASE_H__ #define __CCPROCESSBASE_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/datas/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp b/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp index 23896d1e8b..c9ba8cbe6e 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp +++ b/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp @@ -25,11 +25,11 @@ THE SOFTWARE. #include "CCTween.h" #include "CCArmatureAnimation.h" -#include "armature/CCBone.h" -#include "armature/CCArmature.h" -#include "armature/utils/CCUtilMath.h" -#include "armature/utils/CCTweenFunction.h" -#include "armature/utils/CCTransformHelp.h" +#include "cocostudio/armature/CCBone.h" +#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/armature/utils/CCUtilMath.h" +#include "cocostudio/armature/utils/CCTweenFunction.h" +#include "cocostudio/armature/utils/CCTransformHelp.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.h b/cocos/editor-support/cocostudio/armature/animation/CCTween.h index bcbdde822c..f78e7ef927 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCTween.h @@ -27,7 +27,7 @@ THE SOFTWARE. #define __CCTWEEN_H__ #include "CCProcessBase.h" -#include "armature/utils/CCTweenFunction.h" +#include "cocostudio/armature/utils/CCTweenFunction.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp b/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp index e03213ab8a..6d2468cb58 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp +++ b/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDatas.h" -#include "armature/utils/CCUtilMath.h" -#include "armature/utils/CCTransformHelp.h" +#include "cocostudio/armature/utils/CCUtilMath.h" +#include "cocostudio/armature/utils/CCTransformHelp.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h b/cocos/editor-support/cocostudio/armature/datas/CCDatas.h index 81fca8ebcb..2725750c84 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h +++ b/cocos/editor-support/cocostudio/armature/datas/CCDatas.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCARMATURE_DATAS_H__ #define __CCARMATURE_DATAS_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/utils/CCTweenFunction.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/utils/CCTweenFunction.h" #define CC_CREATE_NO_PARAM_NO_INIT(varType)\ diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp index 04ae69a524..ba273731b1 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCBatchNode.h" -#include "armature/utils/CCArmatureDefine.h" -#include "armature/CCArmature.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/CCArmature.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h index fac221adb6..7e0c52bc29 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCBATCHNODE_H__ #define __CCBATCHNODE_H__ -#include "armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h index 3b42c9c64e..f65f143163 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h @@ -25,9 +25,9 @@ THE SOFTWARE. #ifndef __CCDECORATIVEDISPLAY_H__ #define __CCDECORATIVEDISPLAY_H__ -#include "armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" #include "CCDisplayFactory.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/datas/CCDatas.h" #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp index 30d3184ff8..56e5f8c427 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDisplayFactory.h" -#include "armature/CCBone.h" -#include "armature/CCArmature.h" -#include "armature/display/CCSkin.h" -#include "armature/utils/CCSpriteFrameCacheHelper.h" -#include "armature/utils/CCArmatureDataManager.h" -#include "armature/utils/CCTransformHelp.h" +#include "cocostudio/armature/CCBone.h" +#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/armature/display/CCSkin.h" +#include "cocostudio/armature/utils/CCSpriteFrameCacheHelper.h" +#include "cocostudio/armature/utils/CCArmatureDataManager.h" +#include "cocostudio/armature/utils/CCTransformHelp.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h index 80aa33680d..f8f6009ffb 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCDISPLAYFACTORY_H__ #define __CCDISPLAYFACTORY_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/datas/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp index da87bea351..29ae581cbb 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp @@ -23,10 +23,10 @@ THE SOFTWARE. ****************************************************************************/ #include "CCDisplayManager.h" -#include "armature/CCBone.h" -#include "armature/CCArmature.h" -#include "armature/utils/CCUtilMath.h" -#include "armature/display/CCSkin.h" +#include "cocostudio/armature/CCBone.h" +#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/armature/utils/CCUtilMath.h" +#include "cocostudio/armature/display/CCSkin.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h index 2e9eb217fc..fd51ca759b 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h @@ -25,9 +25,9 @@ THE SOFTWARE. #ifndef __CCDISPLAYMANAGER_H__ #define __CCDISPLAYMANAGER_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/display/CCDecorativeDisplay.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/display/CCDecorativeDisplay.h" +#include "cocostudio/armature/datas/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp b/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp index cd91c18ef4..ecc83c7ff6 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ #include "CCSkin.h" -#include "armature/utils/CCTransformHelp.h" -#include "armature/utils/CCSpriteFrameCacheHelper.h" -#include "armature/CCArmature.h" +#include "cocostudio/armature/utils/CCTransformHelp.h" +#include "cocostudio/armature/utils/CCSpriteFrameCacheHelper.h" +#include "cocostudio/armature/CCArmature.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.h b/cocos/editor-support/cocostudio/armature/display/CCSkin.h index 4c20063bed..1915ff550b 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.h +++ b/cocos/editor-support/cocostudio/armature/display/CCSkin.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCSKIN_H__ #define __CCSKIN_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/CCBone.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/CCBone.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp index 8d4dbf60cd..f7e0c1c500 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCColliderDetector.h" -#include "armature/CCBone.h" -#include "armature/utils/CCTransformHelp.h" +#include "cocostudio/armature/CCBone.h" +#include "cocostudio/armature/utils/CCTransformHelp.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h index 725036fddf..5febb92aef 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCCOLLIDERDETECTOR_H__ #define __CCCOLLIDERDETECTOR_H__ -#include "armature/utils/CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/armature/datas/CCDatas.h" #ifndef PT_RATIO #define PT_RATIO 32 diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h index b3122d34f2..016156bec0 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCARMATUREDATAMANAGER_H__ #include "CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/datas/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp index 67d0264825..d1dc3e0655 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCTransformHelp.h" #include "CCUtilMath.h" #include "CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/datas/CCDatas.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h index d7f8a9f19e..be8b4c9297 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h @@ -26,9 +26,9 @@ THE SOFTWARE. #define __CCDATAREADERHELPER_H__ #include "CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" -#include "armature/CCArmature.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/json/CSContentJsonDictionary.h" #include #include diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h index 540b62f1a3..195d5a1468 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h +++ b/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCTRANSFORMHELP_H__ #include "CCArmatureDefine.h" -#include "armature/datas/CCDatas.h" +#include "cocostudio/armature/datas/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComAttribute.h b/cocos/editor-support/cocostudio/components/CCComAttribute.h index d36ce4ebb2..959e8ac1b8 100644 --- a/cocos/editor-support/cocostudio/components/CCComAttribute.h +++ b/cocos/editor-support/cocostudio/components/CCComAttribute.h @@ -27,7 +27,7 @@ THE SOFTWARE. #include "cocos2d.h" #include -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h b/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h index e3815ae2a6..f8f047b19a 100644 --- a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h +++ b/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h @@ -28,7 +28,7 @@ #define COCOSTUDIO_CSCONTENTJSONDICTIONARY_H -#include "json.h" +#include "json/json.h" #include #include diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp index 3ee822c330..ad0eb9ef8d 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp @@ -23,8 +23,8 @@ ****************************************************************************/ #include "system/CocosGUI.h" -#include "json/DictionaryHelper.h" -#include "action/CCActionManagerEx.h" +#include "cocostudio/json/DictionaryHelper.h" +#include "cocostudio/action/CCActionManagerEx.h" #include #include diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h b/cocos/editor-support/cocostudio/reader/CCSGUIReader.h index 43c0c9693c..0041997bcd 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/reader/CCSGUIReader.h @@ -26,7 +26,7 @@ #define __CCSGUIREADER_H__ #include "base-classes/UIWidget.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h b/cocos/editor-support/cocostudio/reader/CCSSceneReader.h index ca95088c59..a042edfbf2 100644 --- a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/reader/CCSSceneReader.h @@ -26,7 +26,7 @@ #define __CCSSCENEREADER_H__ #include "cocos2d.h" - #include "json/CSContentJsonDictionary.h" + #include "cocostudio/json/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/gui/layouts/Layout.cpp b/cocos/gui/layouts/Layout.cpp index 6403262bd9..25e3833bb6 100644 --- a/cocos/gui/layouts/Layout.cpp +++ b/cocos/gui/layouts/Layout.cpp @@ -25,7 +25,7 @@ #include "layout.h" #include "system/UILayer.h" #include "system/UIHelper.h" -#include "GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/gui/system/CocosGUI.h b/cocos/gui/system/CocosGUI.h index 97046adde2..2c7c6c915b 100644 --- a/cocos/gui/system/CocosGUI.h +++ b/cocos/gui/system/CocosGUI.h @@ -43,7 +43,7 @@ #include "widgets/UILabelBMFont.h" #include "widgets/scroll-widget/UIPageView.h" #include "UIHelper.h" -#include "reader/CCSGUIReader.h" +#include "cocostudio/reader/CCSGUIReader.h" #include "UILayer.h" namespace gui { diff --git a/cocos/gui/system/UIHelper.cpp b/cocos/gui/system/UIHelper.cpp index c023bf23bf..fd6326b851 100644 --- a/cocos/gui/system/UIHelper.cpp +++ b/cocos/gui/system/UIHelper.cpp @@ -23,9 +23,9 @@ ****************************************************************************/ #include "UIHelper.h" -#include "json/DictionaryHelper.h" +#include "cocostudio/json/DictionaryHelper.h" #include "cocos2d.h" -#include "reader/CCSGUIReader.h" +#include "cocostudio/reader/CCSGUIReader.h" using namespace cocos2d; using namespace cocostudio; diff --git a/cocos/gui/system/UIHelper.h b/cocos/gui/system/UIHelper.h index 15487fbf60..e13f8d74f3 100644 --- a/cocos/gui/system/UIHelper.h +++ b/cocos/gui/system/UIHelper.h @@ -26,7 +26,7 @@ #define __UIHELPER_H__ #include "UIInputManager.h" -#include "json/CSContentJsonDictionary.h" +#include "cocostudio/json/CSContentJsonDictionary.h" #define CCUIHELPER gui::UIHelper::instance() diff --git a/cocos/gui/widgets/UIButton.cpp b/cocos/gui/widgets/UIButton.cpp index 7325007d27..47b6a03492 100644 --- a/cocos/gui/widgets/UIButton.cpp +++ b/cocos/gui/widgets/UIButton.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "UIButton.h" -#include "GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/gui/widgets/UIImageView.cpp b/cocos/gui/widgets/UIImageView.cpp index 89491f8141..88625107fa 100644 --- a/cocos/gui/widgets/UIImageView.cpp +++ b/cocos/gui/widgets/UIImageView.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "UIImageView.h" -#include "GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/gui/widgets/UILoadingBar.cpp b/cocos/gui/widgets/UILoadingBar.cpp index 8037d1df33..c3f3167d60 100644 --- a/cocos/gui/widgets/UILoadingBar.cpp +++ b/cocos/gui/widgets/UILoadingBar.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "UILoadingBar.h" -#include "GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/gui/widgets/UISlider.cpp b/cocos/gui/widgets/UISlider.cpp index dcadbc2132..8409c0eb3c 100644 --- a/cocos/gui/widgets/UISlider.cpp +++ b/cocos/gui/widgets/UISlider.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "UISlider.h" -#include "GUI/CCControlExtension/CCScale9Sprite.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 9ed6038242..81e523e55f 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -7,137 +7,137 @@ LOCAL_MODULE := cocos_testcpp_common LOCAL_MODULE_FILENAME := libtestcppcommon LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/Classes/AppDelegate.cpp \ -$(LOCAL_PATH)/Classes/BaseTest.cpp \ -$(LOCAL_PATH)/Classes/controller.cpp \ -$(LOCAL_PATH)/Classes/testBasic.cpp \ -$(LOCAL_PATH)/Classes/VisibleRect.cpp \ -$(LOCAL_PATH)/Classes/AccelerometerTest/AccelerometerTest.cpp \ -$(LOCAL_PATH)/Classes/ActionManagerTest/ActionManagerTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsEaseTest/ActionsEaseTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsProgressTest/ActionsProgressTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsTest/ActionsTest.cpp \ -$(LOCAL_PATH)/Classes/Box2DTest/Box2dTest.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/Box2dView.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/GLES-Render.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/Test.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/TestEntries.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-1159.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-1174.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-350.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-422.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-624.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-886.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-899.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-914.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/BugsTest.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-458/Bug-458.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ -$(LOCAL_PATH)/Classes/ChipmunkTest/ChipmunkTest.cpp \ -$(LOCAL_PATH)/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ -$(LOCAL_PATH)/Classes/ClippingNodeTest/ClippingNodeTest.cpp \ -$(LOCAL_PATH)/Classes/CocosDenshionTest/CocosDenshionTest.cpp \ -$(LOCAL_PATH)/Classes/ConfigurationTest/ConfigurationTest.cpp \ -$(LOCAL_PATH)/Classes/CurlTest/CurlTest.cpp \ -$(LOCAL_PATH)/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ -$(LOCAL_PATH)/Classes/DataVisitorTest/DataVisitorTest.cpp \ -$(LOCAL_PATH)/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ -$(LOCAL_PATH)/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ -$(LOCAL_PATH)/Classes/EffectsTest/EffectsTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ExtensionsTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ -$(LOCAL_PATH)/Classes/FileUtilsTest/FileUtilsTest.cpp \ -$(LOCAL_PATH)/Classes/FontTest/FontTest.cpp \ -$(LOCAL_PATH)/Classes/IntervalTest/IntervalTest.cpp \ -$(LOCAL_PATH)/Classes/KeyboardTest/KeyboardTest.cpp \ -$(LOCAL_PATH)/Classes/KeypadTest/KeypadTest.cpp \ -$(LOCAL_PATH)/Classes/LabelTest/LabelTest.cpp \ -$(LOCAL_PATH)/Classes/LabelTest/LabelTestNew.cpp \ -$(LOCAL_PATH)/Classes/LayerTest/LayerTest.cpp \ -$(LOCAL_PATH)/Classes/MenuTest/MenuTest.cpp \ -$(LOCAL_PATH)/Classes/MotionStreakTest/MotionStreakTest.cpp \ -$(LOCAL_PATH)/Classes/MutiTouchTest/MutiTouchTest.cpp \ -$(LOCAL_PATH)/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ -$(LOCAL_PATH)/Classes/NodeTest/NodeTest.cpp \ -$(LOCAL_PATH)/Classes/ParallaxTest/ParallaxTest.cpp \ -$(LOCAL_PATH)/Classes/ParticleTest/ParticleTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceAllocTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceParticleTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceSpriteTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTextureTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTouchesTest.cpp \ -$(LOCAL_PATH)/Classes/PhysicsTest/PhysicsTest.cpp \ -$(LOCAL_PATH)/Classes/RenderTextureTest/RenderTextureTest.cpp \ -$(LOCAL_PATH)/Classes/RotateWorldTest/RotateWorldTest.cpp \ -$(LOCAL_PATH)/Classes/SceneTest/SceneTest.cpp \ -$(LOCAL_PATH)/Classes/SchedulerTest/SchedulerTest.cpp \ -$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest.cpp \ -$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest2.cpp \ -$(LOCAL_PATH)/Classes/SpineTest/SpineTest.cpp \ -$(LOCAL_PATH)/Classes/SpriteTest/SpriteTest.cpp \ -$(LOCAL_PATH)/Classes/TextInputTest/TextInputTest.cpp \ -$(LOCAL_PATH)/Classes/Texture2dTest/Texture2dTest.cpp \ -$(LOCAL_PATH)/Classes/TextureCacheTest/TextureCacheTest.cpp \ -$(LOCAL_PATH)/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ -$(LOCAL_PATH)/Classes/TileMapTest/TileMapTest.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/Ball.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/Paddle.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/TouchesTest.cpp \ -$(LOCAL_PATH)/Classes/TransitionsTest/TransitionsTest.cpp \ -$(LOCAL_PATH)/Classes/UserDefaultTest/UserDefaultTest.cpp \ -$(LOCAL_PATH)/Classes/ZwoptexTest/ZwoptexTest.cpp +./Classes/AppDelegate.cpp \ +./Classes/BaseTest.cpp \ +./Classes/controller.cpp \ +./Classes/testBasic.cpp \ +./Classes/VisibleRect.cpp \ +./Classes/AccelerometerTest/AccelerometerTest.cpp \ +./Classes/ActionManagerTest/ActionManagerTest.cpp \ +./Classes/ActionsEaseTest/ActionsEaseTest.cpp \ +./Classes/ActionsProgressTest/ActionsProgressTest.cpp \ +./Classes/ActionsTest/ActionsTest.cpp \ +./Classes/Box2DTest/Box2dTest.cpp \ +./Classes/Box2DTestBed/Box2dView.cpp \ +./Classes/Box2DTestBed/GLES-Render.cpp \ +./Classes/Box2DTestBed/Test.cpp \ +./Classes/Box2DTestBed/TestEntries.cpp \ +./Classes/BugsTest/Bug-1159.cpp \ +./Classes/BugsTest/Bug-1174.cpp \ +./Classes/BugsTest/Bug-350.cpp \ +./Classes/BugsTest/Bug-422.cpp \ +./Classes/BugsTest/Bug-624.cpp \ +./Classes/BugsTest/Bug-886.cpp \ +./Classes/BugsTest/Bug-899.cpp \ +./Classes/BugsTest/Bug-914.cpp \ +./Classes/BugsTest/BugsTest.cpp \ +./Classes/BugsTest/Bug-458/Bug-458.cpp \ +./Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ +./Classes/ChipmunkTest/ChipmunkTest.cpp \ +./Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ +./Classes/ClippingNodeTest/ClippingNodeTest.cpp \ +./Classes/CocosDenshionTest/CocosDenshionTest.cpp \ +./Classes/ConfigurationTest/ConfigurationTest.cpp \ +./Classes/CurlTest/CurlTest.cpp \ +./Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ +./Classes/DataVisitorTest/DataVisitorTest.cpp \ +./Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ +./Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ +./Classes/EffectsTest/EffectsTest.cpp \ +./Classes/ExtensionsTest/ExtensionsTest.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ +./Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ +./Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ +./Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ +./Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ +./Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ +./Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ +./Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ +./Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ +./Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ +./Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ +./Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ +./Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ +./Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ +./Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ +./Classes/FileUtilsTest/FileUtilsTest.cpp \ +./Classes/FontTest/FontTest.cpp \ +./Classes/IntervalTest/IntervalTest.cpp \ +./Classes/KeyboardTest/KeyboardTest.cpp \ +./Classes/KeypadTest/KeypadTest.cpp \ +./Classes/LabelTest/LabelTest.cpp \ +./Classes/LabelTest/LabelTestNew.cpp \ +./Classes/LayerTest/LayerTest.cpp \ +./Classes/MenuTest/MenuTest.cpp \ +./Classes/MotionStreakTest/MotionStreakTest.cpp \ +./Classes/MutiTouchTest/MutiTouchTest.cpp \ +./Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ +./Classes/NodeTest/NodeTest.cpp \ +./Classes/ParallaxTest/ParallaxTest.cpp \ +./Classes/ParticleTest/ParticleTest.cpp \ +./Classes/PerformanceTest/PerformanceAllocTest.cpp \ +./Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ +./Classes/PerformanceTest/PerformanceParticleTest.cpp \ +./Classes/PerformanceTest/PerformanceSpriteTest.cpp \ +./Classes/PerformanceTest/PerformanceTest.cpp \ +./Classes/PerformanceTest/PerformanceTextureTest.cpp \ +./Classes/PerformanceTest/PerformanceTouchesTest.cpp \ +./Classes/PhysicsTest/PhysicsTest.cpp \ +./Classes/RenderTextureTest/RenderTextureTest.cpp \ +./Classes/RotateWorldTest/RotateWorldTest.cpp \ +./Classes/SceneTest/SceneTest.cpp \ +./Classes/SchedulerTest/SchedulerTest.cpp \ +./Classes/ShaderTest/ShaderTest.cpp \ +./Classes/ShaderTest/ShaderTest2.cpp \ +./Classes/SpineTest/SpineTest.cpp \ +./Classes/SpriteTest/SpriteTest.cpp \ +./Classes/TextInputTest/TextInputTest.cpp \ +./Classes/Texture2dTest/Texture2dTest.cpp \ +./Classes/TextureCacheTest/TextureCacheTest.cpp \ +./Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ +./Classes/TileMapTest/TileMapTest.cpp \ +./Classes/TouchesTest/Ball.cpp \ +./Classes/TouchesTest/Paddle.cpp \ +./Classes/TouchesTest/TouchesTest.cpp \ +./Classes/TransitionsTest/TransitionsTest.cpp \ +./Classes/UserDefaultTest/UserDefaultTest.cpp \ +./Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp index e2c264c37f..515a63c9be 100644 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp +++ b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "controller.h" #include "SimpleAudioEngine.h" -#include "cocostudio/armature/utils/CCArmatureDataManager.h" +#include "cocostudio/CocoStudio.h" #include "cocos-ext.h" USING_NS_CC; @@ -51,6 +51,7 @@ bool AppDelegate::applicationDidFinishLaunching() { searchPaths.push_back("scenetest"); } + pFileUtils->setSearchPaths(searchPaths); EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 63a987f170..66eb20472b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1,6 +1,6 @@ #include "ArmatureScene.h" #include "../../testResource.h" -#include "armature/display/CCSkin.h" +#include "cocostudio/CocoStudio.h" using namespace cocos2d; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 1db21babb0..f6001395c3 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -5,7 +5,7 @@ #include "cocos-ext.h" #include "../../VisibleRect.h" #include "../../testBasic.h" -#include "armature/CCArmature.h" +#include "cocostudio/CocoStudio.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "../../Box2DTestBed/GLES-Render.h" diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h index 891c84cf14..31e3fc5f2d 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" class EnemyController : public cocostudio::ComController diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h index b8baed4f54..9ce5b3b424 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" class PlayerController : public cocostudio::ComController diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h index 68c4e1aaf7..de3c855c86 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" class ProjectileController : public cocostudio::ComController { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h index 203c74e180..f35b663126 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" class SceneController : public cocostudio::ComController { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 8bcdd1e0f4..1ba28914df 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -1,8 +1,7 @@ #include "CocosGUIScene.h" #include "UISceneManager.h" -//#include "CocosGUIExamplesRegisterScene.h" #include "../ExtensionsTest.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" const char* gui_scene_names[2] = { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index a59f162999..dbc04df6ef 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -2,7 +2,7 @@ #include "cocos-ext.h" #include "../ExtensionsTest.h" #include "SceneEditorTest.h" -#include "CocoStudio.h" +#include "cocostudio/CocoStudio.h" #include "system/CocosGUI.h" using namespace cocos2d; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h index b158784607..2fbbd0f427 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" class AnimationsTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h index 9468229dd8..706ec6b2f7 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" class ButtonTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h index b20072bc30..d6ab2071c4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" /* * Note: for some pretty hard fucked up reason, the order of inheritance is important! diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h index 4dfe4468e7..11c12da610 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" class MenuTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h index 316f93d62b..f36dea647e 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" class TestHeaderLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h index 4dd14b8b73..87cf80d7b6 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h @@ -3,7 +3,7 @@ #include "cocos2d.h" #include "cocos-ext.h" -#include "CocosBuilder.h" +#include "cocosbuilder/CocosBuilder.h" class TimelineCallbackTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index 5892c3e6e2..b35170021f 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -1,7 +1,7 @@ #include "testBasic.h" #include "controller.h" #include "cocos-ext.h" -#include "cocostudio/armature/utils/CCArmatureDataManager.h" +#include "cocostudio/CocoStudio.h" TestScene::TestScene(bool bPortrait) { From 65f33461bc49b57e4402e97d75fa8d398f268554 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 11:19:42 +0800 Subject: [PATCH 147/557] issue #2905: [iOS, Mac] Updating project configuration, TestCpp works now. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 58407b8dbe..35cb0ad779 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -fe809a5d9a1b0e24462a215517e08f6e525cd6b7 \ No newline at end of file +c716fb5eae4ef941532f1184de8b414c4cd3261b \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 0bbb816654..983a860ea6 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -71d9dbdbc4e4e33dbb8fb7ad109611f197a0cec7 \ No newline at end of file +d57f7fce48d49b56eb650690a52eaf3abbff7ec4 \ No newline at end of file From 8e80f1d46ab14be39a0c5fb4795c566cd962b19a Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 11:22:58 +0800 Subject: [PATCH 148/557] issue #2905: Reverting TestCpp/Android.mk --- samples/Cpp/TestCpp/Android.mk | 262 ++++++++++++++++----------------- 1 file changed, 131 insertions(+), 131 deletions(-) diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 81e523e55f..9ed6038242 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -7,137 +7,137 @@ LOCAL_MODULE := cocos_testcpp_common LOCAL_MODULE_FILENAME := libtestcppcommon LOCAL_SRC_FILES := \ -./Classes/AppDelegate.cpp \ -./Classes/BaseTest.cpp \ -./Classes/controller.cpp \ -./Classes/testBasic.cpp \ -./Classes/VisibleRect.cpp \ -./Classes/AccelerometerTest/AccelerometerTest.cpp \ -./Classes/ActionManagerTest/ActionManagerTest.cpp \ -./Classes/ActionsEaseTest/ActionsEaseTest.cpp \ -./Classes/ActionsProgressTest/ActionsProgressTest.cpp \ -./Classes/ActionsTest/ActionsTest.cpp \ -./Classes/Box2DTest/Box2dTest.cpp \ -./Classes/Box2DTestBed/Box2dView.cpp \ -./Classes/Box2DTestBed/GLES-Render.cpp \ -./Classes/Box2DTestBed/Test.cpp \ -./Classes/Box2DTestBed/TestEntries.cpp \ -./Classes/BugsTest/Bug-1159.cpp \ -./Classes/BugsTest/Bug-1174.cpp \ -./Classes/BugsTest/Bug-350.cpp \ -./Classes/BugsTest/Bug-422.cpp \ -./Classes/BugsTest/Bug-624.cpp \ -./Classes/BugsTest/Bug-886.cpp \ -./Classes/BugsTest/Bug-899.cpp \ -./Classes/BugsTest/Bug-914.cpp \ -./Classes/BugsTest/BugsTest.cpp \ -./Classes/BugsTest/Bug-458/Bug-458.cpp \ -./Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ -./Classes/ChipmunkTest/ChipmunkTest.cpp \ -./Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ -./Classes/ClippingNodeTest/ClippingNodeTest.cpp \ -./Classes/CocosDenshionTest/CocosDenshionTest.cpp \ -./Classes/ConfigurationTest/ConfigurationTest.cpp \ -./Classes/CurlTest/CurlTest.cpp \ -./Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ -./Classes/DataVisitorTest/DataVisitorTest.cpp \ -./Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ -./Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ -./Classes/EffectsTest/EffectsTest.cpp \ -./Classes/ExtensionsTest/ExtensionsTest.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ -./Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ -./Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ -./Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ -./Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ -./Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ -./Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ -./Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ -./Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ -./Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ -./Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ -./Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ -./Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ -./Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ -./Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ -./Classes/FileUtilsTest/FileUtilsTest.cpp \ -./Classes/FontTest/FontTest.cpp \ -./Classes/IntervalTest/IntervalTest.cpp \ -./Classes/KeyboardTest/KeyboardTest.cpp \ -./Classes/KeypadTest/KeypadTest.cpp \ -./Classes/LabelTest/LabelTest.cpp \ -./Classes/LabelTest/LabelTestNew.cpp \ -./Classes/LayerTest/LayerTest.cpp \ -./Classes/MenuTest/MenuTest.cpp \ -./Classes/MotionStreakTest/MotionStreakTest.cpp \ -./Classes/MutiTouchTest/MutiTouchTest.cpp \ -./Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ -./Classes/NodeTest/NodeTest.cpp \ -./Classes/ParallaxTest/ParallaxTest.cpp \ -./Classes/ParticleTest/ParticleTest.cpp \ -./Classes/PerformanceTest/PerformanceAllocTest.cpp \ -./Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ -./Classes/PerformanceTest/PerformanceParticleTest.cpp \ -./Classes/PerformanceTest/PerformanceSpriteTest.cpp \ -./Classes/PerformanceTest/PerformanceTest.cpp \ -./Classes/PerformanceTest/PerformanceTextureTest.cpp \ -./Classes/PerformanceTest/PerformanceTouchesTest.cpp \ -./Classes/PhysicsTest/PhysicsTest.cpp \ -./Classes/RenderTextureTest/RenderTextureTest.cpp \ -./Classes/RotateWorldTest/RotateWorldTest.cpp \ -./Classes/SceneTest/SceneTest.cpp \ -./Classes/SchedulerTest/SchedulerTest.cpp \ -./Classes/ShaderTest/ShaderTest.cpp \ -./Classes/ShaderTest/ShaderTest2.cpp \ -./Classes/SpineTest/SpineTest.cpp \ -./Classes/SpriteTest/SpriteTest.cpp \ -./Classes/TextInputTest/TextInputTest.cpp \ -./Classes/Texture2dTest/Texture2dTest.cpp \ -./Classes/TextureCacheTest/TextureCacheTest.cpp \ -./Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ -./Classes/TileMapTest/TileMapTest.cpp \ -./Classes/TouchesTest/Ball.cpp \ -./Classes/TouchesTest/Paddle.cpp \ -./Classes/TouchesTest/TouchesTest.cpp \ -./Classes/TransitionsTest/TransitionsTest.cpp \ -./Classes/UserDefaultTest/UserDefaultTest.cpp \ -./Classes/ZwoptexTest/ZwoptexTest.cpp +$(LOCAL_PATH)/Classes/AppDelegate.cpp \ +$(LOCAL_PATH)/Classes/BaseTest.cpp \ +$(LOCAL_PATH)/Classes/controller.cpp \ +$(LOCAL_PATH)/Classes/testBasic.cpp \ +$(LOCAL_PATH)/Classes/VisibleRect.cpp \ +$(LOCAL_PATH)/Classes/AccelerometerTest/AccelerometerTest.cpp \ +$(LOCAL_PATH)/Classes/ActionManagerTest/ActionManagerTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsEaseTest/ActionsEaseTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsProgressTest/ActionsProgressTest.cpp \ +$(LOCAL_PATH)/Classes/ActionsTest/ActionsTest.cpp \ +$(LOCAL_PATH)/Classes/Box2DTest/Box2dTest.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/Box2dView.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/GLES-Render.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/Test.cpp \ +$(LOCAL_PATH)/Classes/Box2DTestBed/TestEntries.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-1159.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-1174.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-350.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-422.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-624.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-886.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-899.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-914.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/BugsTest.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-458/Bug-458.cpp \ +$(LOCAL_PATH)/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ +$(LOCAL_PATH)/Classes/ChipmunkTest/ChipmunkTest.cpp \ +$(LOCAL_PATH)/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ +$(LOCAL_PATH)/Classes/ClippingNodeTest/ClippingNodeTest.cpp \ +$(LOCAL_PATH)/Classes/CocosDenshionTest/CocosDenshionTest.cpp \ +$(LOCAL_PATH)/Classes/ConfigurationTest/ConfigurationTest.cpp \ +$(LOCAL_PATH)/Classes/CurlTest/CurlTest.cpp \ +$(LOCAL_PATH)/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ +$(LOCAL_PATH)/Classes/DataVisitorTest/DataVisitorTest.cpp \ +$(LOCAL_PATH)/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ +$(LOCAL_PATH)/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ +$(LOCAL_PATH)/Classes/EffectsTest/EffectsTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ExtensionsTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ +$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ +$(LOCAL_PATH)/Classes/FileUtilsTest/FileUtilsTest.cpp \ +$(LOCAL_PATH)/Classes/FontTest/FontTest.cpp \ +$(LOCAL_PATH)/Classes/IntervalTest/IntervalTest.cpp \ +$(LOCAL_PATH)/Classes/KeyboardTest/KeyboardTest.cpp \ +$(LOCAL_PATH)/Classes/KeypadTest/KeypadTest.cpp \ +$(LOCAL_PATH)/Classes/LabelTest/LabelTest.cpp \ +$(LOCAL_PATH)/Classes/LabelTest/LabelTestNew.cpp \ +$(LOCAL_PATH)/Classes/LayerTest/LayerTest.cpp \ +$(LOCAL_PATH)/Classes/MenuTest/MenuTest.cpp \ +$(LOCAL_PATH)/Classes/MotionStreakTest/MotionStreakTest.cpp \ +$(LOCAL_PATH)/Classes/MutiTouchTest/MutiTouchTest.cpp \ +$(LOCAL_PATH)/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ +$(LOCAL_PATH)/Classes/NodeTest/NodeTest.cpp \ +$(LOCAL_PATH)/Classes/ParallaxTest/ParallaxTest.cpp \ +$(LOCAL_PATH)/Classes/ParticleTest/ParticleTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceAllocTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceParticleTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceSpriteTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTextureTest.cpp \ +$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTouchesTest.cpp \ +$(LOCAL_PATH)/Classes/PhysicsTest/PhysicsTest.cpp \ +$(LOCAL_PATH)/Classes/RenderTextureTest/RenderTextureTest.cpp \ +$(LOCAL_PATH)/Classes/RotateWorldTest/RotateWorldTest.cpp \ +$(LOCAL_PATH)/Classes/SceneTest/SceneTest.cpp \ +$(LOCAL_PATH)/Classes/SchedulerTest/SchedulerTest.cpp \ +$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest.cpp \ +$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest2.cpp \ +$(LOCAL_PATH)/Classes/SpineTest/SpineTest.cpp \ +$(LOCAL_PATH)/Classes/SpriteTest/SpriteTest.cpp \ +$(LOCAL_PATH)/Classes/TextInputTest/TextInputTest.cpp \ +$(LOCAL_PATH)/Classes/Texture2dTest/Texture2dTest.cpp \ +$(LOCAL_PATH)/Classes/TextureCacheTest/TextureCacheTest.cpp \ +$(LOCAL_PATH)/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ +$(LOCAL_PATH)/Classes/TileMapTest/TileMapTest.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/Ball.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/Paddle.cpp \ +$(LOCAL_PATH)/Classes/TouchesTest/TouchesTest.cpp \ +$(LOCAL_PATH)/Classes/TransitionsTest/TransitionsTest.cpp \ +$(LOCAL_PATH)/Classes/UserDefaultTest/UserDefaultTest.cpp \ +$(LOCAL_PATH)/Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes From 039a2c93e1a9f8b415fa32355e551e583e36238f Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 11:30:56 +0800 Subject: [PATCH 149/557] issue #2905: [iOS Mac]Removing 'include' folder in 'external' group. Otherwise, it will find wrong included file. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 35cb0ad779..b519be8c47 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c716fb5eae4ef941532f1184de8b414c4cd3261b \ No newline at end of file +96d1842580c3571508689be130709cc09771344a \ No newline at end of file From 6fba0dd5db59d23cde47c6e05c0eefba8483c40b Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 15:43:59 +0800 Subject: [PATCH 150/557] issue #2905: [iOS Mac] TestJavascript works now. --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../armature/animation/CCArmatureAnimation.h | 4 +- cocos/network/HttpRequest.h | 2 +- .../javascript/bindings/XMLHTTPRequest.cpp | 10 +- .../javascript/bindings/XMLHTTPRequest.h | 4 +- .../bindings/js_bindings_ccbreader.cpp | 15 +- .../bindings/js_bindings_ccbreader.h | 11 +- .../jsb_cocos2dx_extension_manual.cpp | 17 +- .../javascript/bindings/jsb_websocket.cpp | 4 +- .../obfuscate/obfuscate_exclude_chipmunk.js | 602 ------------------ ...bfuscate_exclude_cocos2d.js.REMOVED.git-id | 1 - .../bindings/spidermonkey_specifics.h | 2 +- .../TestJavascript/Classes/AppDelegate.cpp | 2 +- .../TestJavascript/game.js.REMOVED.git-id | 1 - .../Javascript/TestJavascript/obfuscate.xml | 76 --- tools/tojs/cocos2dx.ini | 6 +- tools/tojs/cocos2dx_extension.ini | 7 +- tools/tojs/genbindings.sh | 4 +- 19 files changed, 47 insertions(+), 725 deletions(-) delete mode 100644 cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_chipmunk.js delete mode 100644 cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_cocos2d.js.REMOVED.git-id delete mode 100644 samples/Javascript/TestJavascript/game.js.REMOVED.git-id delete mode 100644 samples/Javascript/TestJavascript/obfuscate.xml diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b519be8c47..0e61b0c9e8 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -96d1842580c3571508689be130709cc09771344a \ No newline at end of file +c574341d56f31ced16553735ba34a697d1bbac02 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 983a860ea6..5be8a11389 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -d57f7fce48d49b56eb650690a52eaf3abbff7ec4 \ No newline at end of file +eb61a6b65e5947b285b970192a8d0c129f807556 \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h index b9ac3d4200..61096a2033 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h @@ -45,8 +45,8 @@ class Bone; typedef void (cocos2d::Object::*SEL_MovementEventCallFunc)(Armature *, MovementEventType, const char *); typedef void (cocos2d::Object::*SEL_FrameEventCallFunc)(Bone *, const char *, int, int); -#define movementEvent_selector(_SELECTOR) (SEL_MovementEventCallFunc)(&_SELECTOR) -#define frameEvent_selector(_SELECTOR) (SEL_FrameEventCallFunc)(&_SELECTOR) +#define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) +#define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) class ArmatureAnimation : public ProcessBase diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 273a87b53e..81715d7991 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -32,7 +32,7 @@ namespace network { class HttpClient; class HttpResponse; typedef void (cocos2d::Object::*SEL_HttpResponse)(HttpClient* client, HttpResponse* response); -#define httpresponse_selector(_SELECTOR) (SEL_HttpResponse)(&_SELECTOR) +#define httpresponse_selector(_SELECTOR) (network::SEL_HttpResponse)(&_SELECTOR) /** @brief defines the object which users must packed for HttpClient::send(HttpRequest*) method. diff --git a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp index b799f6aacf..2230a4a94d 100644 --- a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp @@ -167,7 +167,7 @@ void MinXmlHttpRequest::_setHttpRequestHeader() * @param sender Object which initialized callback * @param respone Response object */ -void MinXmlHttpRequest::handle_requestResponse(cocos2d::extension::HttpClient *sender, cocos2d::extension::HttpResponse *response) +void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response) { if (0 != strlen(response->getHttpRequest()->getTag())) { @@ -247,7 +247,7 @@ void MinXmlHttpRequest::handle_requestResponse(cocos2d::extension::HttpClient *s void MinXmlHttpRequest::_sendRequest(JSContext *cx) { _httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse)); - cocos2d::extension::HttpClient::getInstance()->send(_httpRequest); + network::HttpClient::getInstance()->send(_httpRequest); _httpRequest->release(); } @@ -261,7 +261,7 @@ MinXmlHttpRequest::MinXmlHttpRequest() : _onreadystateCallback(NULL), _isNetwork _requestHeader.clear(); _withCredentialsValue = true; _cx = ScriptingCore::getInstance()->getGlobalContext(); - _httpRequest = new cocos2d::extension::HttpRequest(); + _httpRequest = new network::HttpRequest(); } /** @@ -622,11 +622,11 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) if (_meth.compare("post") == 0 || _meth.compare("POST") == 0) { - _httpRequest->setRequestType(cocos2d::extension::HttpRequest::Type::POST); + _httpRequest->setRequestType(network::HttpRequest::Type::POST); } else { - _httpRequest->setRequestType(cocos2d::extension::HttpRequest::Type::GET); + _httpRequest->setRequestType(network::HttpRequest::Type::GET); } _httpRequest->setUrl(_url.c_str()); diff --git a/cocos/scripting/javascript/bindings/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/XMLHTTPRequest.h index b94e05e5fe..861e0a2536 100644 --- a/cocos/scripting/javascript/bindings/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/XMLHTTPRequest.h @@ -80,7 +80,7 @@ public: JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader); JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType); - void handle_requestResponse(cocos2d::extension::HttpClient *sender, cocos2d::extension::HttpResponse *response); + void handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response); private: @@ -102,7 +102,7 @@ private: ResponseType _responseType; unsigned _timeout; bool _isAsync; - cocos2d::extension::HttpRequest* _httpRequest; + network::HttpRequest* _httpRequest; bool _isNetwork; bool _withCredentialsValue; std::map _httpHeader; diff --git a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp index 523cdcda10..733ac47b45 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp @@ -12,6 +12,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; static void removeSelector(std::string &str) { size_t found; @@ -79,7 +80,7 @@ JSBool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::CCBAnimationManager *node = (cocos2d::extension::CCBAnimationManager *)(proxy ? proxy->ptr : NULL); + cocosbuilder::CCBAnimationManager *node = (cocosbuilder::CCBAnimationManager *)(proxy ? proxy->ptr : NULL); JSCCBAnimationWrapper *tmpCobj = new JSCCBAnimationWrapper(); tmpCobj->autorelease(); @@ -103,10 +104,10 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *argv = JS_ARGV(cx, vp); JSBool ok = JS_TRUE; JSObject *obj; - cocos2d::extension::CCBReader* cobj; + cocosbuilder::CCBReader* cobj; obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cobj = (cocos2d::extension::CCBReader *)(proxy ? proxy->ptr : NULL); + cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, cobj) if (argc == 2) { @@ -188,10 +189,10 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin jsval *argv = JS_ARGV(cx, vp); JSBool ok = JS_TRUE; JSObject *obj; - cocos2d::extension::CCBReader* cobj; + cocosbuilder::CCBReader* cobj; obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cobj = (cocos2d::extension::CCBReader *)(proxy ? proxy->ptr : NULL); + cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, cobj) if (argc == 2) { @@ -277,7 +278,7 @@ JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) ccNodeLoaderLibrary->registerNodeLoader("", JSLayerLoader::loader()); - cocos2d::extension::CCBReader * ret = new cocos2d::extension::CCBReader(ccNodeLoaderLibrary); + CCBReader * ret = new CCBReader(ccNodeLoaderLibrary); ret->autorelease(); jsval jsret; @@ -287,7 +288,7 @@ JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) jsret = OBJECT_TO_JSVAL(proxy->obj); } else { // create a new js obj of that class - proxy = js_get_or_create_proxy(cx, ret); + proxy = js_get_or_create_proxy(cx, ret); jsret = OBJECT_TO_JSVAL(proxy->obj); } } else { diff --git a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h index e81b9d3be2..8bcdabd044 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h +++ b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h @@ -9,13 +9,12 @@ #define __JS_BINDINGS_CCBREADER_H__ #include "jsapi.h" -#include "cocos-ext.h" #include "cocos2d_specifics.hpp" - +#include "cocosbuilder/CocosBuilder.h" class CCBScriptCallbackProxy: public cocos2d::Layer -, public cocos2d::extension::CCBSelectorResolver -, public cocos2d::extension::CCBMemberVariableAssigner { +, public cocosbuilder::CCBSelectorResolver +, public cocosbuilder::CCBMemberVariableAssigner { std::string callBackProp; jsval owner; @@ -35,7 +34,7 @@ public: virtual bool onAssignCCBMemberVariable(cocos2d::Object * pTarget, const char * pMemberVariableName, cocos2d::Node * pNode); virtual void onNodeLoaded(cocos2d::Node * pNode, - cocos2d::extension::NodeLoader * pNodeLoader); + cocosbuilder::NodeLoader * pNodeLoader); virtual CCBSelectorResolver * createNew(); void menuItemCallback(Object *pSender); @@ -46,7 +45,7 @@ public: }; -class JSLayerLoader : public cocos2d::extension::LayerLoader { +class JSLayerLoader : public cocosbuilder::LayerLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(JSLayerLoader, loader); diff --git a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 3ec02a7d86..7a6d8bfc46 100644 --- a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -9,10 +9,11 @@ #include "cocos-ext.h" #include "ScriptingCore.h" #include "cocos2d_specifics.hpp" +#include "cocostudio/CocoStudio.h" USING_NS_CC; USING_NS_CC_EXT; -using namespace extension::armature; + class JSB_ScrollViewDelegate : public Object @@ -787,8 +788,8 @@ public: virtual void setJSCallbackThis(jsval thisObj); - void movementCallbackFunc(cocos2d::extension::armature::Armature * pArmature, cocos2d::extension::armature::MovementEventType pMovementEventType, const char *pMovementId); - void frameCallbackFunc(cocos2d::extension::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + void movementCallbackFunc(cocostudio::Armature * pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId); + void frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); void addArmatureFileInfoAsyncCallbackFunc(float percent); private: @@ -825,7 +826,7 @@ void JSArmatureWrapper::setJSCallbackThis(jsval _jsThisObj) } } -void JSArmatureWrapper::movementCallbackFunc(cocos2d::extension::armature::Armature *pArmature, cocos2d::extension::armature::MovementEventType pMovementEventType, const char *pMovementId) +void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId) { JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); @@ -865,7 +866,7 @@ void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) } -void JSArmatureWrapper::frameCallbackFunc(cocos2d::extension::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) +void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) { JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); @@ -893,7 +894,7 @@ static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext * { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::armature::ArmatureAnimation* cobj = (cocos2d::extension::armature::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); if (argc == 2) { @@ -917,7 +918,7 @@ static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::armature::ArmatureAnimation* cobj = (cocos2d::extension::armature::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); if (argc == 2) { @@ -941,7 +942,7 @@ static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::armature::ArmatureDataManager* cobj = (cocos2d::extension::armature::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); + cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); if (argc == 3) { diff --git a/cocos/scripting/javascript/bindings/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/jsb_websocket.cpp index 28a01fbc5b..49ecf7e57e 100644 --- a/cocos/scripting/javascript/bindings/jsb_websocket.cpp +++ b/cocos/scripting/javascript/bindings/jsb_websocket.cpp @@ -30,7 +30,7 @@ THE SOFTWARE. #include "ScriptingCore.h" #include "cocos2d_specifics.hpp" -USING_NS_CC_EXT; +using namespace network; /* [Constructor(in DOMString url, in optional DOMString protocols)] @@ -242,7 +242,7 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, JSObject *obj = JS_NewObject(cx, js_cocos2dx_websocket_class, js_cocos2dx_websocket_prototype, NULL); - cocos2d::extension::WebSocket* cobj = new cocos2d::extension::WebSocket(); + WebSocket* cobj = new WebSocket(); JSB_WebSocketDelegate* delegate = new JSB_WebSocketDelegate(); delegate->setJSDelegate(obj); diff --git a/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_chipmunk.js b/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_chipmunk.js deleted file mode 100644 index c2913daba5..0000000000 --- a/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_chipmunk.js +++ /dev/null @@ -1,602 +0,0 @@ -/** - * @fileoverview Java Script Builtins for windows properties. - * - * @externs - */ - -/** - * @see https://cocos2d-x.org - */ - -/** - * for chipmunk api - * @type {string} - */ -var cp = function(){}; - -CSSProperties.prototype.cp; -CSSProperties.prototype.momentForCircle; -CSSProperties.prototype.areaForCircle; -CSSProperties.prototype.momentForSegment; -CSSProperties.prototype.areaForSegment; -CSSProperties.prototype.momentForPoly; -CSSProperties.prototype.areaForPoly; -CSSProperties.prototype.centroidForPoly; -CSSProperties.prototype.recenterPoly; -CSSProperties.prototype.momentForBox; -CSSProperties.prototype.momentForBox2; -CSSProperties.prototype.clamp01; -CSSProperties.prototype.fclamp01; -CSSProperties.prototype.Vect; -CSSProperties.prototype.add; -CSSProperties.prototype.sub; -CSSProperties.prototype.neg; -CSSProperties.prototype.mult; -CSSProperties.prototype.project; -CSSProperties.prototype.rotate; -CSSProperties.prototype.v; -CSSProperties.prototype.dot; -CSSProperties.prototype.len; -CSSProperties.prototype.eql; -CSSProperties.prototype.cross; -CSSProperties.prototype.perp; -CSSProperties.prototype.pvrperp; -CSSProperties.prototype.unrotate; -CSSProperties.prototype.lengthsq; -CSSProperties.prototype.lerp; -CSSProperties.prototype.normalize; -CSSProperties.prototype.normalize_safe; -CSSProperties.prototype.clamp; -CSSProperties.prototype.lerpconst; -CSSProperties.prototype.dist; -CSSProperties.prototype.distsq; -CSSProperties.prototype.near; -CSSProperties.prototype.slerp; -CSSProperties.prototype.slerpconst; -CSSProperties.prototype.forangle; -CSSProperties.prototype.toangle; -CSSProperties.prototype.str; -CSSProperties.prototype.vzero; -CSSProperties.prototype.x; -CSSProperties.prototype.y; -CSSProperties.prototype.BB; -CSSProperties.prototype.bb; -CSSProperties.prototype.NO_GROUP; -CSSProperties.prototype.ALL_LAYERS; -CSSProperties.prototype.resetShapeIdCounter; -CSSProperties.prototype.Shape; -CSSProperties.prototype.setElasticity; -CSSProperties.prototype.setFriction; -CSSProperties.prototype.setLayers; -CSSProperties.prototype.setSensor; -CSSProperties.prototype.setCollisionType; -CSSProperties.prototype.getBody; -CSSProperties.prototype.active; -CSSProperties.prototype.setBody; -CSSProperties.prototype.cacheBB; -CSSProperties.prototype.update; -CSSProperties.prototype.getBB; -CSSProperties.prototype.CircleShape; -CSSProperties.prototype.cacheData; -CSSProperties.prototype.pointQuery; -CSSProperties.prototype.segmentQuery; -CSSProperties.prototype.collisionCode; -CSSProperties.prototype.collisionTable; -CSSProperties.prototype.SegmentShape; -CSSProperties.prototype.setNeighbors; -CSSProperties.prototype.setEndpoints; -CSSProperties.prototype.PolyShape; -CSSProperties.prototype.setVerts; -CSSProperties.prototype.transformVerts; -CSSProperties.prototype.transformAxes; -CSSProperties.prototype.getNumVerts; -CSSProperties.prototype.getVert; -CSSProperties.prototype.valueOnAxis; -CSSProperties.prototype.containsVert; -CSSProperties.prototype.containsVertPartial; -CSSProperties.prototype.BoxShape; -CSSProperties.prototype.BoxShape2; -CSSProperties.prototype.Body; -CSSProperties.prototype.sanityCheck; -CSSProperties.prototype.getPos; -CSSProperties.prototype.getVel; -CSSProperties.prototype.getAngVel; -CSSProperties.prototype.isSleeping; -CSSProperties.prototype.isStatic; -CSSProperties.prototype.isRogue; -CSSProperties.prototype.setMass; -CSSProperties.prototype.setMoment; -CSSProperties.prototype.addShape; -CSSProperties.prototype.removeShape; -CSSProperties.prototype.removeConstraint; -CSSProperties.prototype.setPos; -CSSProperties.prototype.setVel; -CSSProperties.prototype.setAngVel; -CSSProperties.prototype.setAngleInternal; -CSSProperties.prototype.setAngle; -CSSProperties.prototype.velocity_func; -CSSProperties.prototype.position_func; -CSSProperties.prototype.resetForces; -CSSProperties.prototype.applyForce; -CSSProperties.prototype.applyImpulse; -CSSProperties.prototype.getVelAtPoint; -CSSProperties.prototype.getVelAtWorldPoint; -CSSProperties.prototype.getVelAtLocalPoint; -CSSProperties.prototype.eachShape; -CSSProperties.prototype.eachConstraint; -CSSProperties.prototype.eachArbiter; -CSSProperties.prototype.local2World; -CSSProperties.prototype.world2Local; -CSSProperties.prototype.kineticEnergy; -CSSProperties.prototype.activate; -CSSProperties.prototype.activateStatic; -CSSProperties.prototype.pushArbiter; -CSSProperties.prototype.sleep; -CSSProperties.prototype.sleepWithGroup; -CSSProperties.prototype.StaticBody; -CSSProperties.prototype.SpatialIndex; -CSSProperties.prototype.collideStatic; -CSSProperties.prototype.BBTree; -CSSProperties.prototype.getStamp; -CSSProperties.prototype.incrementStamp; -CSSProperties.prototype.insert; -CSSProperties.prototype.remove; -CSSProperties.prototype.contains; -CSSProperties.prototype.reindexQuery; -CSSProperties.prototype.reindex; -CSSProperties.prototype.reindexObject; -CSSProperties.prototype.query; -CSSProperties.prototype.count; -CSSProperties.prototype.each; -CSSProperties.prototype.optimize; -CSSProperties.prototype.log; -CSSProperties.prototype.CollisionHandler; -CSSProperties.prototype.begin; -CSSProperties.prototype.preSolve; -CSSProperties.prototype.postSolve; -CSSProperties.prototype.separate; -CSSProperties.prototype.collideShapes; -CSSProperties.prototype.Space; -CSSProperties.prototype.getCurrentTimeStep; -CSSProperties.prototype.isLocked; -CSSProperties.prototype.addCollisionHandler; -CSSProperties.prototype.removeCollisionHandler; -CSSProperties.prototype.setDefaultCollisionHandler; -CSSProperties.prototype.lookupHandler; -CSSProperties.prototype.addStaticShape; -CSSProperties.prototype.addBody; -CSSProperties.prototype.addConstraint; -CSSProperties.prototype.filterArbiters; -CSSProperties.prototype.removeStaticShape; -CSSProperties.prototype.removeBody; -CSSProperties.prototype.containsShape; -CSSProperties.prototype.containsBody; -CSSProperties.prototype.containsConstraint; -CSSProperties.prototype.uncacheArbiter; -CSSProperties.prototype.eachBody; -CSSProperties.prototype.reindexStatic; -CSSProperties.prototype.reindexShape; -CSSProperties.prototype.reindexShapesForBody; -CSSProperties.prototype.useSpatialHash; -CSSProperties.prototype.activateBody; -CSSProperties.prototype.deactivateBody; -CSSProperties.prototype.processComponents; -CSSProperties.prototype.activateShapesTouchingShape; -CSSProperties.prototype.pointQueryFirst; -CSSProperties.prototype.segmentQueryFirst; -CSSProperties.prototype.bbQuery; -CSSProperties.prototype.shapeQuery; -CSSProperties.prototype.addPostStepCallback; -CSSProperties.prototype.runPostStepCallbacks; -CSSProperties.prototype.lock; -CSSProperties.prototype.unlock; -CSSProperties.prototype.makeCollideShapes; -CSSProperties.prototype.arbiterSetFilter; -CSSProperties.prototype.step; -CSSProperties.prototype.Constraint; -CSSProperties.prototype.activateBodies; -CSSProperties.prototype.preStep; -CSSProperties.prototype.applyCachedImpulse; -CSSProperties.prototype.getImpulse; -CSSProperties.prototype.next; -CSSProperties.prototype.PinJoint; -CSSProperties.prototype.SlideJoint; -CSSProperties.prototype.PivotJoint; -CSSProperties.prototype.GrooveJoint; -CSSProperties.prototype.grooveConstrain; -CSSProperties.prototype.setGrooveA; -CSSProperties.prototype.setGrooveB; -CSSProperties.prototype.DampedSpring; -CSSProperties.prototype.DampedRotarySpring; -CSSProperties.prototype.RotaryLimitJoint; -CSSProperties.prototype.RatchetJoint; -CSSProperties.prototype.GearJoint; -CSSProperties.prototype.setRatio; -CSSProperties.prototype.SimpleMotor; -CSSProperties.prototype.Base; -CSSProperties.prototype._v; -CSSProperties.prototype.vadd; -CSSProperties.prototype.getHandle; -CSSProperties.prototype.getGravity; -CSSProperties.prototype.getIterations; -CSSProperties.prototype.getDamping; -CSSProperties.prototype.getStaticBody; -CSSProperties.prototype.getIdleSpeedThreshold; -CSSProperties.prototype.getSleepTimeThreshold; -CSSProperties.prototype.getCollisionSlop; -CSSProperties.prototype.getCollisionBias; -CSSProperties.prototype.getCollisionPersistence; -CSSProperties.prototype.getEnableContactGraph; -CSSProperties.prototype.getAngle; -CSSProperties.prototype.getAngVel; -CSSProperties.prototype.getPos; -CSSProperties.prototype.getVel; -CSSProperties.prototype.getMoment; -CSSProperties.prototype.getBody; -CSSProperties.prototype.getGroup; -CSSProperties.prototype.getCollisionType; -CSSProperties.prototype.getMaxForce; -CSSProperties.prototype.getAnchr1; -CSSProperties.prototype.getAnchr2; -CSSProperties.prototype.setHandle; -CSSProperties.prototype._setSpace; -CSSProperties.prototype._setCPBody; -CSSProperties.prototype.setGravity; -CSSProperties.prototype.setIterations; -CSSProperties.prototype.setDamping; -CSSProperties.prototype.setStaticBody; -CSSProperties.prototype.setIdleSpeedThreshold; -CSSProperties.prototype.setSleepTimeThreshold; -CSSProperties.prototype.setCollisionSlop; -CSSProperties.prototype.setCollisionBias; -CSSProperties.prototype.setCollisionPersistence; -CSSProperties.prototype.setEnableContactGraph; -CSSProperties.prototype.setAngle; -CSSProperties.prototype.setAngVel; -CSSProperties.prototype.setPos; -CSSProperties.prototype.setVel; -CSSProperties.prototype.setMoment; -CSSProperties.prototype.setBody; -CSSProperties.prototype.setGroup; -CSSProperties.prototype.setCollisionType; -CSSProperties.prototype.setMaxForce; -CSSProperties.prototype.setAnchr1; -CSSProperties.prototype.setAnchr2; -CSSProperties.prototype.vclamp; -CSSProperties.prototype.vcross; -CSSProperties.prototype.vdist; -CSSProperties.prototype.vdistsq; -CSSProperties.prototype.vdot; -CSSProperties.prototype.veql; -CSSProperties.prototype.vforangle; -CSSProperties.prototype.vlength; -CSSProperties.prototype.vlengthsq; -CSSProperties.prototype.vlerp; -CSSProperties.prototype.vlerpconst; -CSSProperties.prototype.vmult; -CSSProperties.prototype.vnear; -CSSProperties.prototype.vneg; -CSSProperties.prototype.vnormalize; -CSSProperties.prototype.vnormalize_safe; -CSSProperties.prototype.vperp; -CSSProperties.prototype.vproject; -CSSProperties.prototype.vrotate; -CSSProperties.prototype.vrperp; -CSSProperties.prototype.vslerp; -CSSProperties.prototype.vslerpconst; -CSSProperties.prototype.vsub; -CSSProperties.prototype.vtoangle; -CSSProperties.prototype.vunrotate; -CSSProperties.prototype.l; -CSSProperties.prototype.b; -CSSProperties.prototype.t; -CSSProperties.prototype.r; -CSSProperties.prototype.a; -CSSProperties.prototype.w; -CSSProperties.prototype.p; -CSSProperties.prototype.i; -CSSProperties.prototype.handle; -CSSProperties.prototype.gravity; -CSSProperties.prototype.iterations; -CSSProperties.prototype.damping; -CSSProperties.prototype.staticBody; -CSSProperties.prototype.idleSpeedThreshold; -CSSProperties.prototype.sleepTimeThreshold; -CSSProperties.prototype.collisionSlop; -CSSProperties.prototype.collisionBias; -CSSProperties.prototype.collisionPersistence; -CSSProperties.prototype.enableContactGraph; -CSSProperties.prototype.group; -CSSProperties.prototype.collision_type; -CSSProperties.prototype.maxForce; -CSSProperties.prototype.anchr1; -CSSProperties.prototype.anchr2; -CSSProperties.prototype.collisionBegin; -CSSProperties.prototype.collisionPre; -CSSProperties.prototype.collisionPost; -CSSProperties.prototype.collisionSeparate; -CSSProperties.prototype.createPhysicsSprite; -CSSProperties.prototype.Arbiter; -CSSProperties.prototype.spaceAddCollisionHandler; -CSSProperties.prototype.spaceRemoveCollisionHandler; -CSSProperties.prototype.arbiterGetBodies; -CSSProperties.prototype.arbiterGetShapes; -CSSProperties.prototype.bodyGetUserData; -CSSProperties.prototype.bodySetUserData; -CSSProperties.prototype.getBodies; -CSSProperties.prototype.getShapes; -CSSProperties.prototype.getUserData; -CSSProperties.prototype.setUserData; -CSSProperties.prototype.arbiterGetCount; -CSSProperties.prototype.arbiterGetDepth; -CSSProperties.prototype.arbiterGetElasticity; -CSSProperties.prototype.arbiterGetFriction; -CSSProperties.prototype.arbiterGetNormal; -CSSProperties.prototype.arbiterGetPoint; -CSSProperties.prototype.arbiterGetSurfaceVelocity; -CSSProperties.prototype.arbiterIgnore; -CSSProperties.prototype.arbiterIsFirstContact; -CSSProperties.prototype.arbiterSetElasticity; -CSSProperties.prototype.arbiterSetFriction; -CSSProperties.prototype.arbiterSetSurfaceVelocity; -CSSProperties.prototype.arbiterTotalImpulse; -CSSProperties.prototype.arbiterTotalImpulseWithFriction; -CSSProperties.prototype.arbiterTotalKE; -CSSProperties.prototype.areaForCircle; -CSSProperties.prototype.areaForSegment; -CSSProperties.prototype.bBArea; -CSSProperties.prototype.bBClampVect; -CSSProperties.prototype.bBContainsBB; -CSSProperties.prototype.bBContainsVect; -CSSProperties.prototype.bBExpand; -CSSProperties.prototype.bBIntersects; -CSSProperties.prototype.bBIntersectsSegment; -CSSProperties.prototype.bBMerge; -CSSProperties.prototype.bBMergedArea; -CSSProperties.prototype.bBNew; -CSSProperties.prototype.bBNewForCircle; -CSSProperties.prototype.bBSegmentQuery; -CSSProperties.prototype.bBWrapVect; -CSSProperties.prototype.bodyActivate; -CSSProperties.prototype.bodyActivateStatic; -CSSProperties.prototype.bodyApplyForce; -CSSProperties.prototype.bodyApplyImpulse; -CSSProperties.prototype.bodyDestroy; -CSSProperties.prototype.bodyFree; -CSSProperties.prototype.bodyGetAngVel; -CSSProperties.prototype.bodyGetAngVelLimit; -CSSProperties.prototype.bodyGetAngle; -CSSProperties.prototype.bodyGetForce; -CSSProperties.prototype.bodyGetMass; -CSSProperties.prototype.bodyGetMoment; -CSSProperties.prototype.bodyGetPos; -CSSProperties.prototype.bodyGetRot; -CSSProperties.prototype.bodyGetSpace; -CSSProperties.prototype.bodyGetTorque; -CSSProperties.prototype.bodyGetVel; -CSSProperties.prototype.bodyGetVelAtLocalPoint; -CSSProperties.prototype.bodyGetVelAtWorldPoint; -CSSProperties.prototype.bodyGetVelLimit; -CSSProperties.prototype.bodyInit; -CSSProperties.prototype.bodyInitStatic; -CSSProperties.prototype.bodyIsRogue; -CSSProperties.prototype.bodyIsSleeping; -CSSProperties.prototype.bodyIsStatic; -CSSProperties.prototype.bodyKineticEnergy; -CSSProperties.prototype.bodyLocal2World; -CSSProperties.prototype.bodyNew; -CSSProperties.prototype.bodyNewStatic; -CSSProperties.prototype.bodyResetForces; -CSSProperties.prototype.bodySetAngVel; -CSSProperties.prototype.bodySetAngVelLimit; -CSSProperties.prototype.bodySetAngle; -CSSProperties.prototype.bodySetForce; -CSSProperties.prototype.bodySetMass; -CSSProperties.prototype.bodySetMoment; -CSSProperties.prototype.bodySetPos; -CSSProperties.prototype.bodySetTorque; -CSSProperties.prototype.bodySetVel; -CSSProperties.prototype.bodySetVelLimit; -CSSProperties.prototype.bodySleep; -CSSProperties.prototype.bodySleepWithGroup; -CSSProperties.prototype.bodyUpdatePosition; -CSSProperties.prototype.bodyUpdateVelocity; -CSSProperties.prototype.bodyWorld2Local; -CSSProperties.prototype.boxShapeNew; -CSSProperties.prototype.boxShapeNew2; -CSSProperties.prototype.circleShapeGetOffset; -CSSProperties.prototype.circleShapeGetRadius; -CSSProperties.prototype.circleShapeNew; -CSSProperties.prototype.constraintActivateBodies; -CSSProperties.prototype.constraintDestroy; -CSSProperties.prototype.constraintFree; -CSSProperties.prototype.constraintGetA; -CSSProperties.prototype.constraintGetB; -CSSProperties.prototype.constraintGetErrorBias; -CSSProperties.prototype.constraintGetImpulse; -CSSProperties.prototype.constraintGetMaxBias; -CSSProperties.prototype.constraintGetMaxForce; -CSSProperties.prototype.constraintGetSpace; -CSSProperties.prototype.constraintSetErrorBias; -CSSProperties.prototype.constraintSetMaxBias; -CSSProperties.prototype.constraintSetMaxForce; -CSSProperties.prototype.dampedRotarySpringGetDamping; -CSSProperties.prototype.dampedRotarySpringGetRestAngle; -CSSProperties.prototype.dampedRotarySpringGetStiffness; -CSSProperties.prototype.dampedRotarySpringNew; -CSSProperties.prototype.dampedRotarySpringSetDamping; -CSSProperties.prototype.dampedRotarySpringSetRestAngle; -CSSProperties.prototype.dampedRotarySpringSetStiffness; -CSSProperties.prototype.dampedSpringGetAnchr1; -CSSProperties.prototype.dampedSpringGetAnchr2; -CSSProperties.prototype.dampedSpringGetDamping; -CSSProperties.prototype.dampedSpringGetRestLength; -CSSProperties.prototype.dampedSpringGetStiffness; -CSSProperties.prototype.dampedSpringNew; -CSSProperties.prototype.dampedSpringSetAnchr1; -CSSProperties.prototype.dampedSpringSetAnchr2; -CSSProperties.prototype.dampedSpringSetDamping; -CSSProperties.prototype.dampedSpringSetRestLength; -CSSProperties.prototype.dampedSpringSetStiffness; -CSSProperties.prototype.gearJointGetPhase; -CSSProperties.prototype.gearJointGetRatio; -CSSProperties.prototype.gearJointNew; -CSSProperties.prototype.gearJointSetPhase; -CSSProperties.prototype.gearJointSetRatio; -CSSProperties.prototype.grooveJointGetAnchr2; -CSSProperties.prototype.grooveJointGetGrooveA; -CSSProperties.prototype.grooveJointGetGrooveB; -CSSProperties.prototype.grooveJointNew; -CSSProperties.prototype.grooveJointSetAnchr2; -CSSProperties.prototype.grooveJointSetGrooveA; -CSSProperties.prototype.grooveJointSetGrooveB; -CSSProperties.prototype.initChipmunk; -CSSProperties.prototype.momentForBox; -CSSProperties.prototype.momentForBox2; -CSSProperties.prototype.momentForCircle; -CSSProperties.prototype.momentForSegment; -CSSProperties.prototype.pinJointGetAnchr1; -CSSProperties.prototype.pinJointGetAnchr2; -CSSProperties.prototype.pinJointGetDist; -CSSProperties.prototype.pinJointNew; -CSSProperties.prototype.pinJointSetAnchr1; -CSSProperties.prototype.pinJointSetAnchr2; -CSSProperties.prototype.pinJointSetDist; -CSSProperties.prototype.pivotJointGetAnchr1; -CSSProperties.prototype.pivotJointGetAnchr2; -CSSProperties.prototype.pivotJointNew; -CSSProperties.prototype.pivotJointNew2; -CSSProperties.prototype.pivotJointSetAnchr1; -CSSProperties.prototype.pivotJointSetAnchr2; -CSSProperties.prototype.polyShapeGetNumVerts; -CSSProperties.prototype.polyShapeGetVert; -CSSProperties.prototype.ratchetJointGetAngle; -CSSProperties.prototype.ratchetJointGetPhase; -CSSProperties.prototype.ratchetJointGetRatchet; -CSSProperties.prototype.ratchetJointNew; -CSSProperties.prototype.ratchetJointSetAngle; -CSSProperties.prototype.ratchetJointSetPhase; -CSSProperties.prototype.ratchetJointSetRatchet; -CSSProperties.prototype.resetShapeIdCounter; -CSSProperties.prototype.rotaryLimitJointGetMax; -CSSProperties.prototype.rotaryLimitJointGetMin; -CSSProperties.prototype.rotaryLimitJointNew; -CSSProperties.prototype.rotaryLimitJointSetMax; -CSSProperties.prototype.rotaryLimitJointSetMin; -CSSProperties.prototype.segmentShapeGetA; -CSSProperties.prototype.segmentShapeGetB; -CSSProperties.prototype.segmentShapeGetNormal; -CSSProperties.prototype.segmentShapeGetRadius; -CSSProperties.prototype.segmentShapeNew; -CSSProperties.prototype.segmentShapeSetNeighbors; -CSSProperties.prototype.shapeCacheBB; -CSSProperties.prototype.shapeDestroy; -CSSProperties.prototype.shapeFree; -CSSProperties.prototype.shapeGetBB; -CSSProperties.prototype.shapeGetBody; -CSSProperties.prototype.shapeGetCollisionType; -CSSProperties.prototype.shapeGetElasticity; -CSSProperties.prototype.shapeGetFriction; -CSSProperties.prototype.shapeGetGroup; -CSSProperties.prototype.shapeGetLayers; -CSSProperties.prototype.shapeGetSensor; -CSSProperties.prototype.shapeGetSurfaceVelocity; -CSSProperties.prototype.shapePointQuery; -CSSProperties.prototype.shapeSetBody; -CSSProperties.prototype.shapeSetCollisionType; -CSSProperties.prototype.shapeSetElasticity; -CSSProperties.prototype.shapeSetFriction; -CSSProperties.prototype.shapeSetGroup; -CSSProperties.prototype.shapeSetLayers; -CSSProperties.prototype.shapeSetSensor; -CSSProperties.prototype.shapeSetSurfaceVelocity; -CSSProperties.prototype.shapeUpdate; -CSSProperties.prototype.simpleMotorGetRate; -CSSProperties.prototype.simpleMotorNew; -CSSProperties.prototype.simpleMotorSetRate; -CSSProperties.prototype.slideJointGetAnchr1; -CSSProperties.prototype.slideJointGetAnchr2; -CSSProperties.prototype.slideJointGetMax; -CSSProperties.prototype.slideJointGetMin; -CSSProperties.prototype.slideJointNew; -CSSProperties.prototype.slideJointSetAnchr1; -CSSProperties.prototype.slideJointSetAnchr2; -CSSProperties.prototype.slideJointSetMax; -CSSProperties.prototype.slideJointSetMin; -CSSProperties.prototype.spaceActivateShapesTouchingShape; -CSSProperties.prototype.spaceAddBody; -CSSProperties.prototype.spaceAddConstraint; -CSSProperties.prototype.spaceAddShape; -CSSProperties.prototype.spaceAddStaticShape; -CSSProperties.prototype.spaceContainsBody; -CSSProperties.prototype.spaceContainsConstraint; -CSSProperties.prototype.spaceContainsShape; -CSSProperties.prototype.spaceDestroy; -CSSProperties.prototype.spaceFree; -CSSProperties.prototype.spaceGetCollisionBias; -CSSProperties.prototype.spaceGetCollisionPersistence; -CSSProperties.prototype.spaceGetCollisionSlop; -CSSProperties.prototype.spaceGetCurrentTimeStep; -CSSProperties.prototype.spaceGetDamping; -CSSProperties.prototype.spaceGetEnableContactGraph; -CSSProperties.prototype.spaceGetGravity; -CSSProperties.prototype.spaceGetIdleSpeedThreshold; -CSSProperties.prototype.spaceGetIterations; -CSSProperties.prototype.spaceGetSleepTimeThreshold; -CSSProperties.prototype.spaceGetStaticBody; -CSSProperties.prototype.spaceInit; -CSSProperties.prototype.spaceIsLocked; -CSSProperties.prototype.spaceNew; -CSSProperties.prototype.spacePointQueryFirst; -CSSProperties.prototype.spaceReindexShape; -CSSProperties.prototype.spaceReindexShapesForBody; -CSSProperties.prototype.spaceReindexStatic; -CSSProperties.prototype.spaceRemoveBody; -CSSProperties.prototype.spaceRemoveConstraint; -CSSProperties.prototype.spaceRemoveShape; -CSSProperties.prototype.spaceRemoveStaticShape; -CSSProperties.prototype.spaceSetCollisionBias; -CSSProperties.prototype.spaceSetCollisionPersistence; -CSSProperties.prototype.spaceSetCollisionSlop; -CSSProperties.prototype.spaceSetDamping; -CSSProperties.prototype.spaceSetEnableContactGraph; -CSSProperties.prototype.spaceSetGravity; -CSSProperties.prototype.spaceSetIdleSpeedThreshold; -CSSProperties.prototype.spaceSetIterations; -CSSProperties.prototype.spaceSetSleepTimeThreshold; -CSSProperties.prototype.spaceStep; -CSSProperties.prototype.spaceUseSpatialHash; -CSSProperties.prototype.fabs; -CSSProperties.prototype.fclamp; -CSSProperties.prototype.fclamp01; -CSSProperties.prototype.flerp; -CSSProperties.prototype.shapeGetSpace; -CSSProperties.prototype.flerpconst; -CSSProperties.prototype.fmax; -CSSProperties.prototype.fmin; -CSSProperties.prototype.vadd; -CSSProperties.prototype.vclamp; -CSSProperties.prototype.vcross; -CSSProperties.prototype.vdist; -CSSProperties.prototype.vdistsq; -CSSProperties.prototype.vdot; -CSSProperties.prototype.veql; -CSSProperties.prototype.vforangle; -CSSProperties.prototype.vlength; -CSSProperties.prototype.vlengthsq; -CSSProperties.prototype.vlerp; -CSSProperties.prototype.vlerpconst; -CSSProperties.prototype.vmult; -CSSProperties.prototype.vnear; -CSSProperties.prototype.vneg; -CSSProperties.prototype.vnormalize; -CSSProperties.prototype.vnormalize_safe; -CSSProperties.prototype.vperp; -CSSProperties.prototype.vproject; -CSSProperties.prototype.vrotate; -CSSProperties.prototype.vrperp; -CSSProperties.prototype.vslerp; -CSSProperties.prototype.vslerpconst; -CSSProperties.prototype.vsub; -CSSProperties.prototype.vtoangle; -CSSProperties.prototype.vunrotate; \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_cocos2d.js.REMOVED.git-id b/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_cocos2d.js.REMOVED.git-id deleted file mode 100644 index deca174a3f..0000000000 --- a/cocos/scripting/javascript/bindings/obfuscate/obfuscate_exclude_cocos2d.js.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d62414960a7cab961eb6e4aebefe7d21828bd8e5 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h index 6cb006b358..be9c709c49 100644 --- a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h +++ b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h @@ -2,7 +2,7 @@ #define __SPIDERMONKEY_SPECIFICS_H__ #include "jsapi.h" -#include "support/data_support/uthash.h" +#include "uthash.h" typedef struct js_proxy { void *ptr; diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp index 5d81a72e32..51ebd8d85f 100644 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp +++ b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp @@ -42,7 +42,7 @@ bool AppDelegate::applicationDidFinishLaunching() pDirector->setAnimationInterval(1.0 / 60); FileUtils::getInstance()->addSearchPath("res"); - FileUtils::getInstance()->addSearchPath("js"); + FileUtils::getInstance()->addSearchPath("script"); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); diff --git a/samples/Javascript/TestJavascript/game.js.REMOVED.git-id b/samples/Javascript/TestJavascript/game.js.REMOVED.git-id deleted file mode 100644 index fffc005595..0000000000 --- a/samples/Javascript/TestJavascript/game.js.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d6662088eb795b38f78febad2e46bd92ef24fb56 \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/obfuscate.xml b/samples/Javascript/TestJavascript/obfuscate.xml deleted file mode 100644 index 8c16f77347..0000000000 --- a/samples/Javascript/TestJavascript/obfuscate.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index f1075ca4a0..510440e508 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -13,16 +13,16 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos2dx/include -I%(cocosdir)s/cocos2dx/platform -I%(cocosdir)s/cocos2dx/platform/android -I%(cocosdir)s/cocos2dx -I%(cocosdir)s/cocos2dx/kazmath/include +cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT -cxxgenerator_headers = -I%(cxxgeneratordir)s/targets/spidermonkey/common +cxxgenerator_headers = # extra arguments for clang extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/cocos2dx/include/cocos2d.h %(cocosdir)s/audio/include/SimpleAudioEngine.h +headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/SimpleAudioEngine.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". diff --git a/tools/tojs/cocos2dx_extension.ini b/tools/tojs/cocos2dx_extension.ini index a5170a5d86..1519b2eb92 100644 --- a/tools/tojs/cocos2dx_extension.ini +++ b/tools/tojs/cocos2dx_extension.ini @@ -13,16 +13,17 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos2dx/include -I%(cocosdir)s/cocos2dx/platform -I%(cocosdir)s/cocos2dx/platform/android -I%(cocosdir)s/cocos2dx -I%(cocosdir)s/cocos2dx/kazmath/include -I%(cocosdir)s/extensions +cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT -cxxgenerator_headers = -I%(cxxgeneratordir)s/targets/spidermonkey/common +cxxgenerator_headers = # extra arguments for clang extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h +headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". diff --git a/tools/tojs/genbindings.sh b/tools/tojs/genbindings.sh index 8801c65d1f..56b1b4500f 100755 --- a/tools/tojs/genbindings.sh +++ b/tools/tojs/genbindings.sh @@ -80,7 +80,7 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${COCOS2DX_ROOT}/scripting/auto-generated/js-bindings -n jsb_cocos2dx_auto +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto From 00ee4160064f682a436eb4e1c6386f5bdad51d55 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 16:21:55 +0800 Subject: [PATCH 151/557] issue #2905: [iOS Mac] All js games work now. --- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp | 2 ++ samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp | 3 ++- samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp | 2 +- samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp | 2 ++ 5 files changed, 8 insertions(+), 3 deletions(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 5be8a11389..cc5cbe86bf 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -eb61a6b65e5947b285b970192a8d0c129f807556 \ No newline at end of file +a4c6fec549057de458346127f489e6e6bea2f0d1 \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp index 3530e7e4fe..3276d5deda 100644 --- a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp +++ b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp @@ -36,6 +36,8 @@ bool AppDelegate::applicationDidFinishLaunching() pDirector->setProjection(Director::Projection::_2D); + FileUtils::getInstance()->addSearchPath("script"); + auto screenSize = EGLView::getInstance()->getFrameSize(); auto designSize = Size(320, 480); diff --git a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp index 5b607d407c..27520db220 100644 --- a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp +++ b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp @@ -31,13 +31,14 @@ bool AppDelegate::applicationDidFinishLaunching() pDirector->setOpenGLView(EGLView::getInstance()); pDirector->setProjection(Director::Projection::_2D); + FileUtils::getInstance()->addSearchPath("script"); auto screenSize = EGLView::getInstance()->getFrameSize(); auto designSize = Size(320, 480); auto resourceSize = Size(320, 480); - std::vector searchPaths; + std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); std::vector resDirOrders; Application::Platform platform = Application::getInstance()->getTargetPlatform(); diff --git a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp index 0f69f2cff7..7e7a33a156 100644 --- a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp +++ b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp @@ -40,7 +40,7 @@ bool AppDelegate::applicationDidFinishLaunching() // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); - FileUtils::getInstance()->addSearchPath("js"); + FileUtils::getInstance()->addSearchPath("script"); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); diff --git a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp index dcfdb8e970..3e9c616b35 100644 --- a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp +++ b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp @@ -38,6 +38,8 @@ bool AppDelegate::applicationDidFinishLaunching() EGLView::getInstance()->setDesignResolutionSize(480, 320, ResolutionPolicy::FIXED_HEIGHT); + FileUtils::getInstance()->addSearchPath("script"); + ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_all_cocos2dx_extension); From 5c5f2d84e2a1d4018fa5311c029a9b5591bf79c3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 16:27:45 +0800 Subject: [PATCH 152/557] issue #2905: Updating tolua settings. --- tools/tolua/cocos2dx.ini | 6 +++--- tools/tolua/cocos2dx_extension.ini | 6 +++--- tools/tolua/genbindings.sh | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index cc59df0bdb..8721cdba4f 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -13,16 +13,16 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos2dx/include -I%(cocosdir)s/cocos2dx/platform -I%(cocosdir)s/cocos2dx/platform/android -I%(cocosdir)s/cocos2dx -I%(cocosdir)s/cocos2dx/kazmath/include +cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT -cxxgenerator_headers = -I%(cxxgeneratordir)s/targets/spidermonkey/common +cxxgenerator_headers = # extra arguments for clang extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/cocos2dx/include/cocos2d.h %(cocosdir)s/audio/include/SimpleAudioEngine.h +headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/SimpleAudioEngine.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index ce914cf508..67d87c51d6 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,16 +13,16 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos2dx/include -I%(cocosdir)s/cocos2dx/platform -I%(cocosdir)s/cocos2dx/platform/android -I%(cocosdir)s/cocos2dx -I%(cocosdir)s/cocos2dx/kazmath/include -I%(cocosdir)s/extensions +cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT -cxxgenerator_headers = -I%(cxxgeneratordir)s/targets/spidermonkey/common +cxxgenerator_headers = # extra arguments for clang extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h +headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index ba6033c7fc..b236c43ae8 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -80,7 +80,7 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto From 352d1f676808706e1ec032f3ec1801c584614e4a Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 16:40:07 +0800 Subject: [PATCH 153/557] issue #2905: Renaming lua/cocos2dx_support to lua/bindings. --- cocos/scripting/lua/{proj.linux => bindings}/.cproject | 0 cocos/scripting/lua/{proj.linux => bindings}/.project | 0 cocos/scripting/lua/{proj.android => bindings}/Android.mk | 0 .../lua/{cocos2dx_support => bindings}/CCBProxy.cpp | 0 .../lua/{cocos2dx_support => bindings}/CCBProxy.h | 0 .../lua/{cocos2dx_support => bindings}/CCLuaBridge.cpp | 0 .../lua/{cocos2dx_support => bindings}/CCLuaBridge.h | 0 .../lua/{cocos2dx_support => bindings}/CCLuaEngine.cpp | 0 .../lua/{cocos2dx_support => bindings}/CCLuaEngine.h | 0 .../lua/{cocos2dx_support => bindings}/CCLuaStack.cpp | 0 .../lua/{cocos2dx_support => bindings}/CCLuaStack.h | 0 .../lua/{cocos2dx_support => bindings}/CCLuaValue.cpp | 0 .../lua/{cocos2dx_support => bindings}/CCLuaValue.h | 0 .../{cocos2dx_support => bindings}/Cocos2dxLuaLoader.cpp | 0 .../lua/{cocos2dx_support => bindings}/Cocos2dxLuaLoader.h | 0 .../{cocos2dx_support => bindings}/LuaBasicConversions.cpp | 0 .../{cocos2dx_support => bindings}/LuaBasicConversions.h | 0 .../LuaOpengl.cpp.REMOVED.git-id | 0 .../lua/{cocos2dx_support => bindings}/LuaOpengl.h | 0 .../{cocos2dx_support => bindings}/LuaScriptHandlerMgr.cpp | 0 .../{cocos2dx_support => bindings}/LuaScriptHandlerMgr.h | 0 .../lua/{cocos2dx_support => bindings}/Lua_web_socket.cpp | 0 .../lua/{cocos2dx_support => bindings}/Lua_web_socket.h | 0 cocos/scripting/lua/{proj.linux => bindings}/Makefile | 0 .../scripting/lua/{proj.win32 => bindings}/liblua.vcxproj | 0 .../lua/{proj.win32 => bindings}/liblua.vcxproj.filters | 0 .../lua/{proj.win32 => bindings}/liblua.vcxproj.user | 0 .../lua_cocos2dx_deprecated.cpp.REMOVED.git-id | 0 .../lua_cocos2dx_deprecated.h | 0 .../lua_cocos2dx_extension_manual.cpp | 0 .../lua_cocos2dx_extension_manual.h | 0 .../{cocos2dx_support => bindings}/lua_cocos2dx_manual.cpp | 0 .../{cocos2dx_support => bindings}/lua_cocos2dx_manual.hpp | 0 .../platform/android/CCLuaJavaBridge.cpp | 0 .../platform/android/CCLuaJavaBridge.h | 0 .../jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp | 0 .../jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h | 0 .../platform/ios/CCLuaObjcBridge.h | 0 .../platform/ios/CCLuaObjcBridge.mm | 0 .../lua/{cocos2dx_support => bindings}/tolua_fix.c | 0 .../lua/{cocos2dx_support => bindings}/tolua_fix.h | 0 cocos/scripting/lua/proj.ios/luabindings-Prefix.pch | 7 ------- {cocos/scripting => external}/lua/lua/lapi.c | 0 {cocos/scripting => external}/lua/lua/lapi.h | 0 {cocos/scripting => external}/lua/lua/lauxlib.c | 0 {cocos/scripting => external}/lua/lua/lauxlib.h | 0 {cocos/scripting => external}/lua/lua/lbaselib.c | 0 {cocos/scripting => external}/lua/lua/lcode.c | 0 {cocos/scripting => external}/lua/lua/lcode.h | 0 {cocos/scripting => external}/lua/lua/ldblib.c | 0 {cocos/scripting => external}/lua/lua/ldebug.c | 0 {cocos/scripting => external}/lua/lua/ldebug.h | 0 {cocos/scripting => external}/lua/lua/ldo.c | 0 {cocos/scripting => external}/lua/lua/ldo.h | 0 {cocos/scripting => external}/lua/lua/ldump.c | 0 {cocos/scripting => external}/lua/lua/lfunc.c | 0 {cocos/scripting => external}/lua/lua/lfunc.h | 0 {cocos/scripting => external}/lua/lua/lgc.c | 0 {cocos/scripting => external}/lua/lua/lgc.h | 0 {cocos/scripting => external}/lua/lua/linit.c | 0 {cocos/scripting => external}/lua/lua/liolib.c | 0 {cocos/scripting => external}/lua/lua/llex.c | 0 {cocos/scripting => external}/lua/lua/llex.h | 0 {cocos/scripting => external}/lua/lua/llimits.h | 0 {cocos/scripting => external}/lua/lua/lmathlib.c | 0 {cocos/scripting => external}/lua/lua/lmem.c | 0 {cocos/scripting => external}/lua/lua/lmem.h | 0 {cocos/scripting => external}/lua/lua/loadlib.c | 0 {cocos/scripting => external}/lua/lua/lobject.c | 0 {cocos/scripting => external}/lua/lua/lobject.h | 0 {cocos/scripting => external}/lua/lua/lopcodes.c | 0 {cocos/scripting => external}/lua/lua/lopcodes.h | 0 {cocos/scripting => external}/lua/lua/loslib.c | 0 {cocos/scripting => external}/lua/lua/lparser.c | 0 {cocos/scripting => external}/lua/lua/lparser.h | 0 {cocos/scripting => external}/lua/lua/lstate.c | 0 {cocos/scripting => external}/lua/lua/lstate.h | 0 {cocos/scripting => external}/lua/lua/lstring.c | 0 {cocos/scripting => external}/lua/lua/lstring.h | 0 {cocos/scripting => external}/lua/lua/lstrlib.c | 0 {cocos/scripting => external}/lua/lua/ltable.c | 0 {cocos/scripting => external}/lua/lua/ltable.h | 0 {cocos/scripting => external}/lua/lua/ltablib.c | 0 {cocos/scripting => external}/lua/lua/ltm.c | 0 {cocos/scripting => external}/lua/lua/ltm.h | 0 {cocos/scripting => external}/lua/lua/lua.c | 0 {cocos/scripting => external}/lua/lua/lua.h | 0 {cocos/scripting => external}/lua/lua/luaconf.h | 0 {cocos/scripting => external}/lua/lua/lualib.h | 0 {cocos/scripting => external}/lua/lua/lundump.c | 0 {cocos/scripting => external}/lua/lua/lundump.h | 0 {cocos/scripting => external}/lua/lua/lvm.c | 0 {cocos/scripting => external}/lua/lua/lvm.h | 0 {cocos/scripting => external}/lua/lua/lzio.c | 0 {cocos/scripting => external}/lua/lua/lzio.h | 0 {cocos/scripting => external}/lua/lua/print.c | 0 {cocos/scripting => external}/lua/luajit/Android.mk | 0 .../lua/luajit/LuaJIT-2.0.1/COPYRIGHT | 0 .../lua/luajit/LuaJIT-2.0.1/Makefile | 0 .../scripting => external}/lua/luajit/LuaJIT-2.0.1/README | 0 .../lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css | 0 .../lua/luajit/LuaJIT-2.0.1/doc/bluequad.css | 0 .../lua/luajit/LuaJIT-2.0.1/doc/changes.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/contact.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/extensions.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/faq.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/install.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/luajit.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/running.html | 0 .../lua/luajit/LuaJIT-2.0.1/doc/status.html | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua | 0 .../lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua | 0 .../lua/luajit/LuaJIT-2.0.1/etc/luajit.1 | 0 .../lua/luajit/LuaJIT-2.0.1/etc/luajit.pc | 0 .../lua/luajit/LuaJIT-2.0.1/src/Makefile | 0 .../lua/luajit/LuaJIT-2.0.1/src/Makefile.dep | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/README | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua | 0 .../luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/jit/v.lua | 0 .../lua/luajit/LuaJIT-2.0.1/src/lauxlib.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_aux.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_base.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_bit.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_debug.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_init.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_io.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_jit.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_math.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_os.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_package.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_string.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lib_table.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj.supp | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_api.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_arch.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_bc.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_bc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_carith.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_carith.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_char.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_char.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_clib.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_clib.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_debug.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_debug.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_def.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_err.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_err.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ff.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_frame.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_func.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_func.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_gc.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_gc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ir.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ir.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_jit.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_lex.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_lex.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_lib.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_lib.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_load.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_meta.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_meta.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_obj.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_obj.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_parse.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_parse.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_record.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_record.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_snap.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_snap.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_state.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_state.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_str.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_str.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_tab.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_tab.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_target.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_trace.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_trace.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_udata.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_udata.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_vm.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/ljamalg.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/lua.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lua.hpp | 0 .../lua/luajit/LuaJIT-2.0.1/src/luaconf.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/luajit.c | 0 .../lua/luajit/LuaJIT-2.0.1/src/luajit.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/lualib.h | 0 .../lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat | 0 .../lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id | 0 .../luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id | 0 .../lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id | 0 .../luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id | 0 .../lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id | 0 .../lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat | 0 .../lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch | 0 .../luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id | 0 .../lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id | 0 .../lua/luajit/android/x86/libluajit.a.REMOVED.git-id | 0 {cocos/scripting => external}/lua/luajit/build_android.sh | 0 {cocos/scripting => external}/lua/luajit/build_ios.sh | 0 {cocos/scripting => external}/lua/luajit/build_mac.sh | 0 {cocos/scripting => external}/lua/luajit/include/lauxlib.h | 0 {cocos/scripting => external}/lua/luajit/include/lua.h | 0 {cocos/scripting => external}/lua/luajit/include/luaconf.h | 0 {cocos/scripting => external}/lua/luajit/include/lualib.h | 0 .../lua/luajit/ios/libluajit.a.REMOVED.git-id | 0 .../lua/luajit/mac/libluajit.a.REMOVED.git-id | 0 .../lua/luajit/win32/lua51.dll.REMOVED.git-id | 0 {cocos/scripting => external}/lua/tolua/tolua++.h | 0 {cocos/scripting => external}/lua/tolua/tolua_event.c | 0 {cocos/scripting => external}/lua/tolua/tolua_event.h | 0 {cocos/scripting => external}/lua/tolua/tolua_is.c | 0 {cocos/scripting => external}/lua/tolua/tolua_map.c | 0 {cocos/scripting => external}/lua/tolua/tolua_push.c | 0 {cocos/scripting => external}/lua/tolua/tolua_to.c | 0 308 files changed, 7 deletions(-) rename cocos/scripting/lua/{proj.linux => bindings}/.cproject (100%) rename cocos/scripting/lua/{proj.linux => bindings}/.project (100%) rename cocos/scripting/lua/{proj.android => bindings}/Android.mk (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCBProxy.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCBProxy.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaBridge.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaBridge.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaEngine.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaEngine.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaStack.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaStack.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaValue.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/CCLuaValue.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/Cocos2dxLuaLoader.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/Cocos2dxLuaLoader.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaBasicConversions.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaBasicConversions.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaOpengl.cpp.REMOVED.git-id (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaOpengl.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaScriptHandlerMgr.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/LuaScriptHandlerMgr.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/Lua_web_socket.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/Lua_web_socket.h (100%) rename cocos/scripting/lua/{proj.linux => bindings}/Makefile (100%) rename cocos/scripting/lua/{proj.win32 => bindings}/liblua.vcxproj (100%) rename cocos/scripting/lua/{proj.win32 => bindings}/liblua.vcxproj.filters (100%) rename cocos/scripting/lua/{proj.win32 => bindings}/liblua.vcxproj.user (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_deprecated.cpp.REMOVED.git-id (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_deprecated.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_extension_manual.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_extension_manual.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_manual.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/lua_cocos2dx_manual.hpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/android/CCLuaJavaBridge.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/android/CCLuaJavaBridge.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/ios/CCLuaObjcBridge.h (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/platform/ios/CCLuaObjcBridge.mm (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/tolua_fix.c (100%) rename cocos/scripting/lua/{cocos2dx_support => bindings}/tolua_fix.h (100%) delete mode 100644 cocos/scripting/lua/proj.ios/luabindings-Prefix.pch rename {cocos/scripting => external}/lua/lua/lapi.c (100%) rename {cocos/scripting => external}/lua/lua/lapi.h (100%) rename {cocos/scripting => external}/lua/lua/lauxlib.c (100%) rename {cocos/scripting => external}/lua/lua/lauxlib.h (100%) rename {cocos/scripting => external}/lua/lua/lbaselib.c (100%) rename {cocos/scripting => external}/lua/lua/lcode.c (100%) rename {cocos/scripting => external}/lua/lua/lcode.h (100%) rename {cocos/scripting => external}/lua/lua/ldblib.c (100%) rename {cocos/scripting => external}/lua/lua/ldebug.c (100%) rename {cocos/scripting => external}/lua/lua/ldebug.h (100%) rename {cocos/scripting => external}/lua/lua/ldo.c (100%) rename {cocos/scripting => external}/lua/lua/ldo.h (100%) rename {cocos/scripting => external}/lua/lua/ldump.c (100%) rename {cocos/scripting => external}/lua/lua/lfunc.c (100%) rename {cocos/scripting => external}/lua/lua/lfunc.h (100%) rename {cocos/scripting => external}/lua/lua/lgc.c (100%) rename {cocos/scripting => external}/lua/lua/lgc.h (100%) rename {cocos/scripting => external}/lua/lua/linit.c (100%) rename {cocos/scripting => external}/lua/lua/liolib.c (100%) rename {cocos/scripting => external}/lua/lua/llex.c (100%) rename {cocos/scripting => external}/lua/lua/llex.h (100%) rename {cocos/scripting => external}/lua/lua/llimits.h (100%) rename {cocos/scripting => external}/lua/lua/lmathlib.c (100%) rename {cocos/scripting => external}/lua/lua/lmem.c (100%) rename {cocos/scripting => external}/lua/lua/lmem.h (100%) rename {cocos/scripting => external}/lua/lua/loadlib.c (100%) rename {cocos/scripting => external}/lua/lua/lobject.c (100%) rename {cocos/scripting => external}/lua/lua/lobject.h (100%) rename {cocos/scripting => external}/lua/lua/lopcodes.c (100%) rename {cocos/scripting => external}/lua/lua/lopcodes.h (100%) rename {cocos/scripting => external}/lua/lua/loslib.c (100%) rename {cocos/scripting => external}/lua/lua/lparser.c (100%) rename {cocos/scripting => external}/lua/lua/lparser.h (100%) rename {cocos/scripting => external}/lua/lua/lstate.c (100%) rename {cocos/scripting => external}/lua/lua/lstate.h (100%) rename {cocos/scripting => external}/lua/lua/lstring.c (100%) rename {cocos/scripting => external}/lua/lua/lstring.h (100%) rename {cocos/scripting => external}/lua/lua/lstrlib.c (100%) rename {cocos/scripting => external}/lua/lua/ltable.c (100%) rename {cocos/scripting => external}/lua/lua/ltable.h (100%) rename {cocos/scripting => external}/lua/lua/ltablib.c (100%) rename {cocos/scripting => external}/lua/lua/ltm.c (100%) rename {cocos/scripting => external}/lua/lua/ltm.h (100%) rename {cocos/scripting => external}/lua/lua/lua.c (100%) rename {cocos/scripting => external}/lua/lua/lua.h (100%) rename {cocos/scripting => external}/lua/lua/luaconf.h (100%) rename {cocos/scripting => external}/lua/lua/lualib.h (100%) rename {cocos/scripting => external}/lua/lua/lundump.c (100%) rename {cocos/scripting => external}/lua/lua/lundump.h (100%) rename {cocos/scripting => external}/lua/lua/lvm.c (100%) rename {cocos/scripting => external}/lua/lua/lvm.h (100%) rename {cocos/scripting => external}/lua/lua/lzio.c (100%) rename {cocos/scripting => external}/lua/lua/lzio.h (100%) rename {cocos/scripting => external}/lua/lua/print.c (100%) rename {cocos/scripting => external}/lua/luajit/Android.mk (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/COPYRIGHT (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/Makefile (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/README (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/bluequad.css (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/changes.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/contact.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/extensions.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/faq.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/install.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/luajit.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/running.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/doc/status.html (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/etc/luajit.1 (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/etc/luajit.pc (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/Makefile (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/Makefile.dep (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/README (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/jit/v.lua (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lauxlib.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_aux.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_base.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_bit.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_debug.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_init.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_io.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_jit.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_math.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_os.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_package.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_string.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lib_table.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj.supp (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_api.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_arch.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_bc.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_bc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_carith.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_carith.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_char.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_char.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_clib.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_clib.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_debug.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_debug.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_def.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_err.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_err.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ff.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_frame.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_func.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_func.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_gc.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_gc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ir.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ir.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_jit.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_lex.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_lex.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_lib.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_lib.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_load.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_meta.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_meta.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_obj.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_obj.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_parse.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_parse.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_record.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_record.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_snap.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_snap.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_state.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_state.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_str.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_str.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_tab.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_tab.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_target.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_trace.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_trace.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_udata.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_udata.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_vm.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/ljamalg.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lua.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lua.hpp (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/luaconf.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/luajit.c (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/luajit.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/lualib.h (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat (100%) rename {cocos/scripting => external}/lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch (100%) rename {cocos/scripting => external}/lua/luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/android/x86/libluajit.a.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/build_android.sh (100%) rename {cocos/scripting => external}/lua/luajit/build_ios.sh (100%) rename {cocos/scripting => external}/lua/luajit/build_mac.sh (100%) rename {cocos/scripting => external}/lua/luajit/include/lauxlib.h (100%) rename {cocos/scripting => external}/lua/luajit/include/lua.h (100%) rename {cocos/scripting => external}/lua/luajit/include/luaconf.h (100%) rename {cocos/scripting => external}/lua/luajit/include/lualib.h (100%) rename {cocos/scripting => external}/lua/luajit/ios/libluajit.a.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/mac/libluajit.a.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/luajit/win32/lua51.dll.REMOVED.git-id (100%) rename {cocos/scripting => external}/lua/tolua/tolua++.h (100%) rename {cocos/scripting => external}/lua/tolua/tolua_event.c (100%) rename {cocos/scripting => external}/lua/tolua/tolua_event.h (100%) rename {cocos/scripting => external}/lua/tolua/tolua_is.c (100%) rename {cocos/scripting => external}/lua/tolua/tolua_map.c (100%) rename {cocos/scripting => external}/lua/tolua/tolua_push.c (100%) rename {cocos/scripting => external}/lua/tolua/tolua_to.c (100%) diff --git a/cocos/scripting/lua/proj.linux/.cproject b/cocos/scripting/lua/bindings/.cproject similarity index 100% rename from cocos/scripting/lua/proj.linux/.cproject rename to cocos/scripting/lua/bindings/.cproject diff --git a/cocos/scripting/lua/proj.linux/.project b/cocos/scripting/lua/bindings/.project similarity index 100% rename from cocos/scripting/lua/proj.linux/.project rename to cocos/scripting/lua/bindings/.project diff --git a/cocos/scripting/lua/proj.android/Android.mk b/cocos/scripting/lua/bindings/Android.mk similarity index 100% rename from cocos/scripting/lua/proj.android/Android.mk rename to cocos/scripting/lua/bindings/Android.mk diff --git a/cocos/scripting/lua/cocos2dx_support/CCBProxy.cpp b/cocos/scripting/lua/bindings/CCBProxy.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCBProxy.cpp rename to cocos/scripting/lua/bindings/CCBProxy.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/CCBProxy.h b/cocos/scripting/lua/bindings/CCBProxy.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCBProxy.h rename to cocos/scripting/lua/bindings/CCBProxy.h diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaBridge.cpp b/cocos/scripting/lua/bindings/CCLuaBridge.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaBridge.cpp rename to cocos/scripting/lua/bindings/CCLuaBridge.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaBridge.h b/cocos/scripting/lua/bindings/CCLuaBridge.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaBridge.h rename to cocos/scripting/lua/bindings/CCLuaBridge.h diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaEngine.cpp rename to cocos/scripting/lua/bindings/CCLuaEngine.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaEngine.h b/cocos/scripting/lua/bindings/CCLuaEngine.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaEngine.h rename to cocos/scripting/lua/bindings/CCLuaEngine.h diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaStack.cpp rename to cocos/scripting/lua/bindings/CCLuaStack.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaStack.h b/cocos/scripting/lua/bindings/CCLuaStack.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaStack.h rename to cocos/scripting/lua/bindings/CCLuaStack.h diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaValue.cpp b/cocos/scripting/lua/bindings/CCLuaValue.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaValue.cpp rename to cocos/scripting/lua/bindings/CCLuaValue.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/CCLuaValue.h b/cocos/scripting/lua/bindings/CCLuaValue.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/CCLuaValue.h rename to cocos/scripting/lua/bindings/CCLuaValue.h diff --git a/cocos/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.cpp b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.cpp rename to cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.h b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/Cocos2dxLuaLoader.h rename to cocos/scripting/lua/bindings/Cocos2dxLuaLoader.h diff --git a/cocos/scripting/lua/cocos2dx_support/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaBasicConversions.cpp rename to cocos/scripting/lua/bindings/LuaBasicConversions.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaBasicConversions.h rename to cocos/scripting/lua/bindings/LuaBasicConversions.h diff --git a/cocos/scripting/lua/cocos2dx_support/LuaOpengl.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaOpengl.cpp.REMOVED.git-id rename to cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id diff --git a/cocos/scripting/lua/cocos2dx_support/LuaOpengl.h b/cocos/scripting/lua/bindings/LuaOpengl.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaOpengl.h rename to cocos/scripting/lua/bindings/LuaOpengl.h diff --git a/cocos/scripting/lua/cocos2dx_support/LuaScriptHandlerMgr.cpp b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaScriptHandlerMgr.cpp rename to cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/LuaScriptHandlerMgr.h rename to cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h diff --git a/cocos/scripting/lua/cocos2dx_support/Lua_web_socket.cpp b/cocos/scripting/lua/bindings/Lua_web_socket.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/Lua_web_socket.cpp rename to cocos/scripting/lua/bindings/Lua_web_socket.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/Lua_web_socket.h b/cocos/scripting/lua/bindings/Lua_web_socket.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/Lua_web_socket.h rename to cocos/scripting/lua/bindings/Lua_web_socket.h diff --git a/cocos/scripting/lua/proj.linux/Makefile b/cocos/scripting/lua/bindings/Makefile similarity index 100% rename from cocos/scripting/lua/proj.linux/Makefile rename to cocos/scripting/lua/bindings/Makefile diff --git a/cocos/scripting/lua/proj.win32/liblua.vcxproj b/cocos/scripting/lua/bindings/liblua.vcxproj similarity index 100% rename from cocos/scripting/lua/proj.win32/liblua.vcxproj rename to cocos/scripting/lua/bindings/liblua.vcxproj diff --git a/cocos/scripting/lua/proj.win32/liblua.vcxproj.filters b/cocos/scripting/lua/bindings/liblua.vcxproj.filters similarity index 100% rename from cocos/scripting/lua/proj.win32/liblua.vcxproj.filters rename to cocos/scripting/lua/bindings/liblua.vcxproj.filters diff --git a/cocos/scripting/lua/proj.win32/liblua.vcxproj.user b/cocos/scripting/lua/bindings/liblua.vcxproj.user similarity index 100% rename from cocos/scripting/lua/proj.win32/liblua.vcxproj.user rename to cocos/scripting/lua/bindings/liblua.vcxproj.user diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_deprecated.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_deprecated.cpp.REMOVED.git-id rename to cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp.REMOVED.git-id diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_deprecated.h b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_deprecated.h rename to cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.h diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.cpp rename to cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.h b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_extension_manual.h rename to cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_manual.cpp rename to cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_manual.hpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.hpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/lua_cocos2dx_manual.hpp rename to cocos/scripting/lua/bindings/lua_cocos2dx_manual.hpp diff --git a/cocos/scripting/lua/cocos2dx_support/platform/android/CCLuaJavaBridge.cpp b/cocos/scripting/lua/bindings/platform/android/CCLuaJavaBridge.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/android/CCLuaJavaBridge.cpp rename to cocos/scripting/lua/bindings/platform/android/CCLuaJavaBridge.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/platform/android/CCLuaJavaBridge.h b/cocos/scripting/lua/bindings/platform/android/CCLuaJavaBridge.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/android/CCLuaJavaBridge.h rename to cocos/scripting/lua/bindings/platform/android/CCLuaJavaBridge.h diff --git a/cocos/scripting/lua/cocos2dx_support/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp b/cocos/scripting/lua/bindings/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp rename to cocos/scripting/lua/bindings/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp diff --git a/cocos/scripting/lua/cocos2dx_support/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h b/cocos/scripting/lua/bindings/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h rename to cocos/scripting/lua/bindings/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.h diff --git a/cocos/scripting/lua/cocos2dx_support/platform/ios/CCLuaObjcBridge.h b/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/ios/CCLuaObjcBridge.h rename to cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.h diff --git a/cocos/scripting/lua/cocos2dx_support/platform/ios/CCLuaObjcBridge.mm b/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/platform/ios/CCLuaObjcBridge.mm rename to cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm diff --git a/cocos/scripting/lua/cocos2dx_support/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/tolua_fix.c rename to cocos/scripting/lua/bindings/tolua_fix.c diff --git a/cocos/scripting/lua/cocos2dx_support/tolua_fix.h b/cocos/scripting/lua/bindings/tolua_fix.h similarity index 100% rename from cocos/scripting/lua/cocos2dx_support/tolua_fix.h rename to cocos/scripting/lua/bindings/tolua_fix.h diff --git a/cocos/scripting/lua/proj.ios/luabindings-Prefix.pch b/cocos/scripting/lua/proj.ios/luabindings-Prefix.pch deleted file mode 100644 index 175f3ccb23..0000000000 --- a/cocos/scripting/lua/proj.ios/luabindings-Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'luabindings' target in the 'luabindings' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/cocos/scripting/lua/lua/lapi.c b/external/lua/lua/lapi.c similarity index 100% rename from cocos/scripting/lua/lua/lapi.c rename to external/lua/lua/lapi.c diff --git a/cocos/scripting/lua/lua/lapi.h b/external/lua/lua/lapi.h similarity index 100% rename from cocos/scripting/lua/lua/lapi.h rename to external/lua/lua/lapi.h diff --git a/cocos/scripting/lua/lua/lauxlib.c b/external/lua/lua/lauxlib.c similarity index 100% rename from cocos/scripting/lua/lua/lauxlib.c rename to external/lua/lua/lauxlib.c diff --git a/cocos/scripting/lua/lua/lauxlib.h b/external/lua/lua/lauxlib.h similarity index 100% rename from cocos/scripting/lua/lua/lauxlib.h rename to external/lua/lua/lauxlib.h diff --git a/cocos/scripting/lua/lua/lbaselib.c b/external/lua/lua/lbaselib.c similarity index 100% rename from cocos/scripting/lua/lua/lbaselib.c rename to external/lua/lua/lbaselib.c diff --git a/cocos/scripting/lua/lua/lcode.c b/external/lua/lua/lcode.c similarity index 100% rename from cocos/scripting/lua/lua/lcode.c rename to external/lua/lua/lcode.c diff --git a/cocos/scripting/lua/lua/lcode.h b/external/lua/lua/lcode.h similarity index 100% rename from cocos/scripting/lua/lua/lcode.h rename to external/lua/lua/lcode.h diff --git a/cocos/scripting/lua/lua/ldblib.c b/external/lua/lua/ldblib.c similarity index 100% rename from cocos/scripting/lua/lua/ldblib.c rename to external/lua/lua/ldblib.c diff --git a/cocos/scripting/lua/lua/ldebug.c b/external/lua/lua/ldebug.c similarity index 100% rename from cocos/scripting/lua/lua/ldebug.c rename to external/lua/lua/ldebug.c diff --git a/cocos/scripting/lua/lua/ldebug.h b/external/lua/lua/ldebug.h similarity index 100% rename from cocos/scripting/lua/lua/ldebug.h rename to external/lua/lua/ldebug.h diff --git a/cocos/scripting/lua/lua/ldo.c b/external/lua/lua/ldo.c similarity index 100% rename from cocos/scripting/lua/lua/ldo.c rename to external/lua/lua/ldo.c diff --git a/cocos/scripting/lua/lua/ldo.h b/external/lua/lua/ldo.h similarity index 100% rename from cocos/scripting/lua/lua/ldo.h rename to external/lua/lua/ldo.h diff --git a/cocos/scripting/lua/lua/ldump.c b/external/lua/lua/ldump.c similarity index 100% rename from cocos/scripting/lua/lua/ldump.c rename to external/lua/lua/ldump.c diff --git a/cocos/scripting/lua/lua/lfunc.c b/external/lua/lua/lfunc.c similarity index 100% rename from cocos/scripting/lua/lua/lfunc.c rename to external/lua/lua/lfunc.c diff --git a/cocos/scripting/lua/lua/lfunc.h b/external/lua/lua/lfunc.h similarity index 100% rename from cocos/scripting/lua/lua/lfunc.h rename to external/lua/lua/lfunc.h diff --git a/cocos/scripting/lua/lua/lgc.c b/external/lua/lua/lgc.c similarity index 100% rename from cocos/scripting/lua/lua/lgc.c rename to external/lua/lua/lgc.c diff --git a/cocos/scripting/lua/lua/lgc.h b/external/lua/lua/lgc.h similarity index 100% rename from cocos/scripting/lua/lua/lgc.h rename to external/lua/lua/lgc.h diff --git a/cocos/scripting/lua/lua/linit.c b/external/lua/lua/linit.c similarity index 100% rename from cocos/scripting/lua/lua/linit.c rename to external/lua/lua/linit.c diff --git a/cocos/scripting/lua/lua/liolib.c b/external/lua/lua/liolib.c similarity index 100% rename from cocos/scripting/lua/lua/liolib.c rename to external/lua/lua/liolib.c diff --git a/cocos/scripting/lua/lua/llex.c b/external/lua/lua/llex.c similarity index 100% rename from cocos/scripting/lua/lua/llex.c rename to external/lua/lua/llex.c diff --git a/cocos/scripting/lua/lua/llex.h b/external/lua/lua/llex.h similarity index 100% rename from cocos/scripting/lua/lua/llex.h rename to external/lua/lua/llex.h diff --git a/cocos/scripting/lua/lua/llimits.h b/external/lua/lua/llimits.h similarity index 100% rename from cocos/scripting/lua/lua/llimits.h rename to external/lua/lua/llimits.h diff --git a/cocos/scripting/lua/lua/lmathlib.c b/external/lua/lua/lmathlib.c similarity index 100% rename from cocos/scripting/lua/lua/lmathlib.c rename to external/lua/lua/lmathlib.c diff --git a/cocos/scripting/lua/lua/lmem.c b/external/lua/lua/lmem.c similarity index 100% rename from cocos/scripting/lua/lua/lmem.c rename to external/lua/lua/lmem.c diff --git a/cocos/scripting/lua/lua/lmem.h b/external/lua/lua/lmem.h similarity index 100% rename from cocos/scripting/lua/lua/lmem.h rename to external/lua/lua/lmem.h diff --git a/cocos/scripting/lua/lua/loadlib.c b/external/lua/lua/loadlib.c similarity index 100% rename from cocos/scripting/lua/lua/loadlib.c rename to external/lua/lua/loadlib.c diff --git a/cocos/scripting/lua/lua/lobject.c b/external/lua/lua/lobject.c similarity index 100% rename from cocos/scripting/lua/lua/lobject.c rename to external/lua/lua/lobject.c diff --git a/cocos/scripting/lua/lua/lobject.h b/external/lua/lua/lobject.h similarity index 100% rename from cocos/scripting/lua/lua/lobject.h rename to external/lua/lua/lobject.h diff --git a/cocos/scripting/lua/lua/lopcodes.c b/external/lua/lua/lopcodes.c similarity index 100% rename from cocos/scripting/lua/lua/lopcodes.c rename to external/lua/lua/lopcodes.c diff --git a/cocos/scripting/lua/lua/lopcodes.h b/external/lua/lua/lopcodes.h similarity index 100% rename from cocos/scripting/lua/lua/lopcodes.h rename to external/lua/lua/lopcodes.h diff --git a/cocos/scripting/lua/lua/loslib.c b/external/lua/lua/loslib.c similarity index 100% rename from cocos/scripting/lua/lua/loslib.c rename to external/lua/lua/loslib.c diff --git a/cocos/scripting/lua/lua/lparser.c b/external/lua/lua/lparser.c similarity index 100% rename from cocos/scripting/lua/lua/lparser.c rename to external/lua/lua/lparser.c diff --git a/cocos/scripting/lua/lua/lparser.h b/external/lua/lua/lparser.h similarity index 100% rename from cocos/scripting/lua/lua/lparser.h rename to external/lua/lua/lparser.h diff --git a/cocos/scripting/lua/lua/lstate.c b/external/lua/lua/lstate.c similarity index 100% rename from cocos/scripting/lua/lua/lstate.c rename to external/lua/lua/lstate.c diff --git a/cocos/scripting/lua/lua/lstate.h b/external/lua/lua/lstate.h similarity index 100% rename from cocos/scripting/lua/lua/lstate.h rename to external/lua/lua/lstate.h diff --git a/cocos/scripting/lua/lua/lstring.c b/external/lua/lua/lstring.c similarity index 100% rename from cocos/scripting/lua/lua/lstring.c rename to external/lua/lua/lstring.c diff --git a/cocos/scripting/lua/lua/lstring.h b/external/lua/lua/lstring.h similarity index 100% rename from cocos/scripting/lua/lua/lstring.h rename to external/lua/lua/lstring.h diff --git a/cocos/scripting/lua/lua/lstrlib.c b/external/lua/lua/lstrlib.c similarity index 100% rename from cocos/scripting/lua/lua/lstrlib.c rename to external/lua/lua/lstrlib.c diff --git a/cocos/scripting/lua/lua/ltable.c b/external/lua/lua/ltable.c similarity index 100% rename from cocos/scripting/lua/lua/ltable.c rename to external/lua/lua/ltable.c diff --git a/cocos/scripting/lua/lua/ltable.h b/external/lua/lua/ltable.h similarity index 100% rename from cocos/scripting/lua/lua/ltable.h rename to external/lua/lua/ltable.h diff --git a/cocos/scripting/lua/lua/ltablib.c b/external/lua/lua/ltablib.c similarity index 100% rename from cocos/scripting/lua/lua/ltablib.c rename to external/lua/lua/ltablib.c diff --git a/cocos/scripting/lua/lua/ltm.c b/external/lua/lua/ltm.c similarity index 100% rename from cocos/scripting/lua/lua/ltm.c rename to external/lua/lua/ltm.c diff --git a/cocos/scripting/lua/lua/ltm.h b/external/lua/lua/ltm.h similarity index 100% rename from cocos/scripting/lua/lua/ltm.h rename to external/lua/lua/ltm.h diff --git a/cocos/scripting/lua/lua/lua.c b/external/lua/lua/lua.c similarity index 100% rename from cocos/scripting/lua/lua/lua.c rename to external/lua/lua/lua.c diff --git a/cocos/scripting/lua/lua/lua.h b/external/lua/lua/lua.h similarity index 100% rename from cocos/scripting/lua/lua/lua.h rename to external/lua/lua/lua.h diff --git a/cocos/scripting/lua/lua/luaconf.h b/external/lua/lua/luaconf.h similarity index 100% rename from cocos/scripting/lua/lua/luaconf.h rename to external/lua/lua/luaconf.h diff --git a/cocos/scripting/lua/lua/lualib.h b/external/lua/lua/lualib.h similarity index 100% rename from cocos/scripting/lua/lua/lualib.h rename to external/lua/lua/lualib.h diff --git a/cocos/scripting/lua/lua/lundump.c b/external/lua/lua/lundump.c similarity index 100% rename from cocos/scripting/lua/lua/lundump.c rename to external/lua/lua/lundump.c diff --git a/cocos/scripting/lua/lua/lundump.h b/external/lua/lua/lundump.h similarity index 100% rename from cocos/scripting/lua/lua/lundump.h rename to external/lua/lua/lundump.h diff --git a/cocos/scripting/lua/lua/lvm.c b/external/lua/lua/lvm.c similarity index 100% rename from cocos/scripting/lua/lua/lvm.c rename to external/lua/lua/lvm.c diff --git a/cocos/scripting/lua/lua/lvm.h b/external/lua/lua/lvm.h similarity index 100% rename from cocos/scripting/lua/lua/lvm.h rename to external/lua/lua/lvm.h diff --git a/cocos/scripting/lua/lua/lzio.c b/external/lua/lua/lzio.c similarity index 100% rename from cocos/scripting/lua/lua/lzio.c rename to external/lua/lua/lzio.c diff --git a/cocos/scripting/lua/lua/lzio.h b/external/lua/lua/lzio.h similarity index 100% rename from cocos/scripting/lua/lua/lzio.h rename to external/lua/lua/lzio.h diff --git a/cocos/scripting/lua/lua/print.c b/external/lua/lua/print.c similarity index 100% rename from cocos/scripting/lua/lua/print.c rename to external/lua/lua/print.c diff --git a/cocos/scripting/lua/luajit/Android.mk b/external/lua/luajit/Android.mk similarity index 100% rename from cocos/scripting/lua/luajit/Android.mk rename to external/lua/luajit/Android.mk diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/COPYRIGHT b/external/lua/luajit/LuaJIT-2.0.1/COPYRIGHT similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/COPYRIGHT rename to external/lua/luajit/LuaJIT-2.0.1/COPYRIGHT diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/Makefile b/external/lua/luajit/LuaJIT-2.0.1/Makefile similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/Makefile rename to external/lua/luajit/LuaJIT-2.0.1/Makefile diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/README b/external/lua/luajit/LuaJIT-2.0.1/README similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/README rename to external/lua/luajit/LuaJIT-2.0.1/README diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css b/external/lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css rename to external/lua/luajit/LuaJIT-2.0.1/doc/bluequad-print.css diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/bluequad.css b/external/lua/luajit/LuaJIT-2.0.1/doc/bluequad.css similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/bluequad.css rename to external/lua/luajit/LuaJIT-2.0.1/doc/bluequad.css diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/changes.html b/external/lua/luajit/LuaJIT-2.0.1/doc/changes.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/changes.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/changes.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/contact.html b/external/lua/luajit/LuaJIT-2.0.1/doc/contact.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/contact.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/contact.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_c_api.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_api.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_semantics.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_ffi_tutorial.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html b/external/lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/ext_jit.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/extensions.html b/external/lua/luajit/LuaJIT-2.0.1/doc/extensions.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/extensions.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/extensions.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/faq.html b/external/lua/luajit/LuaJIT-2.0.1/doc/faq.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/faq.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/faq.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/install.html b/external/lua/luajit/LuaJIT-2.0.1/doc/install.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/install.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/install.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/luajit.html b/external/lua/luajit/LuaJIT-2.0.1/doc/luajit.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/luajit.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/luajit.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/running.html b/external/lua/luajit/LuaJIT-2.0.1/doc/running.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/running.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/running.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/status.html b/external/lua/luajit/LuaJIT-2.0.1/doc/status.html similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/doc/status.html rename to external/lua/luajit/LuaJIT-2.0.1/doc/status.html diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_arm.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_ppc.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_proto.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x64.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_x86.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua b/external/lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua rename to external/lua/luajit/LuaJIT-2.0.1/dynasm/dynasm.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/etc/luajit.1 b/external/lua/luajit/LuaJIT-2.0.1/etc/luajit.1 similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/etc/luajit.1 rename to external/lua/luajit/LuaJIT-2.0.1/etc/luajit.1 diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/etc/luajit.pc b/external/lua/luajit/LuaJIT-2.0.1/etc/luajit.pc similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/etc/luajit.pc rename to external/lua/luajit/LuaJIT-2.0.1/etc/luajit.pc diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/Makefile b/external/lua/luajit/LuaJIT-2.0.1/src/Makefile similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/Makefile rename to external/lua/luajit/LuaJIT-2.0.1/src/Makefile diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/Makefile.dep b/external/lua/luajit/LuaJIT-2.0.1/src/Makefile.dep similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/Makefile.dep rename to external/lua/luajit/LuaJIT-2.0.1/src/Makefile.dep diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/README b/external/lua/luajit/LuaJIT-2.0.1/src/host/README similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/README rename to external/lua/luajit/LuaJIT-2.0.1/src/host/README diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_asm.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_fold.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_lib.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c b/external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c rename to external/lua/luajit/LuaJIT-2.0.1/src/host/buildvm_peobj.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua b/external/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/host/minilua.c.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/bc.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/bcsave.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_arm.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mips.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_mipsel.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_ppc.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x64.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dis_x86.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/dump.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/v.lua b/external/lua/luajit/LuaJIT-2.0.1/src/jit/v.lua similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/jit/v.lua rename to external/lua/luajit/LuaJIT-2.0.1/src/jit/v.lua diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lauxlib.h b/external/lua/luajit/LuaJIT-2.0.1/src/lauxlib.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lauxlib.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lauxlib.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_aux.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_aux.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_aux.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_aux.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_base.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_base.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_base.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_base.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_bit.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_bit.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_bit.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_bit.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_debug.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_debug.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_debug.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_debug.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_ffi.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_init.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_init.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_init.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_init.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_io.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_io.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_io.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_io.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_jit.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_jit.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_jit.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_jit.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_math.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_math.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_math.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_math.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_os.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_os.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_os.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_os.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_package.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_package.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_package.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_package.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_string.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_string.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_string.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_string.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_table.c b/external/lua/luajit/LuaJIT-2.0.1/src/lib_table.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lib_table.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lib_table.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj.supp b/external/lua/luajit/LuaJIT-2.0.1/src/lj.supp similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj.supp rename to external/lua/luajit/LuaJIT-2.0.1/src/lj.supp diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_alloc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_api.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_api.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_api.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_api.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_arch.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_arch.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_arch.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_arch.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_arm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_mips.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_ppc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_asm_x86.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bc.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_bc.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bc.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_bc.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_bc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_bc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_bcdump.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_bcread.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_bcwrite.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_carith.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_carith.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_carith.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_carith.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_carith.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_carith.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_carith.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_carith.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ccall.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ccallback.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cconv.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cdata.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_char.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_char.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_char.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_char.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_char.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_char.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_char.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_char.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_clib.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_clib.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_clib.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_clib.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_clib.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_clib.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_clib.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_clib.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_cparse.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_crecord.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ctype.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_debug.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_debug.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_debug.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_debug.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_debug.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_debug.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_debug.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_debug.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_def.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_def.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_def.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_def.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_dispatch.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_arm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_mips.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_ppc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_emit_x86.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_err.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_err.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_err.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_err.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_err.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_err.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_err.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_err.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_errmsg.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ff.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ff.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ff.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ff.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ffrecord.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_frame.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_frame.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_frame.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_frame.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_func.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_func.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_func.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_func.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_func.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_func.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_func.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_func.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gc.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_gc.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gc.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_gc.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_gc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_gc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_gdbjit.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ir.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ir.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ir.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ir.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ir.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ir.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ir.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ir.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_ircall.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_iropt.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_jit.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_jit.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_jit.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_jit.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lex.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_lex.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lex.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_lex.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lex.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_lex.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lex.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_lex.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lib.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_lib.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lib.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_lib.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lib.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_lib.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_lib.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_lib.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_load.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_load.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_load.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_load.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_mcode.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_meta.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_meta.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_meta.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_meta.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_meta.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_meta.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_meta.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_meta.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_obj.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_obj.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_obj.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_obj.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_obj.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_obj.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_obj.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_obj.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_dce.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_fold.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_loop.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_mem.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_narrow.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_sink.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_opt_split.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_parse.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_parse.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_parse.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_parse.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_parse.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_parse.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_parse.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_parse.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_record.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_record.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_record.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_record.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_record.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_record.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_record.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_record.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_snap.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_snap.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_snap.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_snap.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_snap.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_snap.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_snap.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_snap.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_state.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_state.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_state.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_state.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_state.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_state.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_state.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_state.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_str.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_str.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_str.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_str.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_str.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_str.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_str.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_str.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_strscan.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_tab.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_tab.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_tab.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_tab.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_tab.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_tab.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_tab.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_tab.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_target.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_target.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_target_arm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_target_mips.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_target_ppc.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_target_x86.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_trace.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_trace.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_trace.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_trace.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_trace.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_trace.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_trace.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_trace.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_traceerr.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_udata.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_udata.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_udata.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_udata.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_udata.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_udata.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_udata.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_udata.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vm.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_vm.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vm.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_vm.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h b/external/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_vmevent.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c b/external/lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c rename to external/lua/luajit/LuaJIT-2.0.1/src/lj_vmmath.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/ljamalg.c b/external/lua/luajit/LuaJIT-2.0.1/src/ljamalg.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/ljamalg.c rename to external/lua/luajit/LuaJIT-2.0.1/src/ljamalg.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lua.h b/external/lua/luajit/LuaJIT-2.0.1/src/lua.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lua.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lua.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lua.hpp b/external/lua/luajit/LuaJIT-2.0.1/src/lua.hpp similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lua.hpp rename to external/lua/luajit/LuaJIT-2.0.1/src/lua.hpp diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luaconf.h b/external/lua/luajit/LuaJIT-2.0.1/src/luaconf.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luaconf.h rename to external/lua/luajit/LuaJIT-2.0.1/src/luaconf.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luajit.c b/external/lua/luajit/LuaJIT-2.0.1/src/luajit.c similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luajit.c rename to external/lua/luajit/LuaJIT-2.0.1/src/luajit.c diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luajit.h b/external/lua/luajit/LuaJIT-2.0.1/src/luajit.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/luajit.h rename to external/lua/luajit/LuaJIT-2.0.1/src/luajit.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lualib.h b/external/lua/luajit/LuaJIT-2.0.1/src/lualib.h similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/lualib.h rename to external/lua/luajit/LuaJIT-2.0.1/src/lualib.h diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat b/external/lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat rename to external/lua/luajit/LuaJIT-2.0.1/src/msvcbuild.bat diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/vm_arm.dasc.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/vm_mips.dasc.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/vm_ppc.dasc.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/vm_ppcspe.dasc.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id b/external/lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id rename to external/lua/luajit/LuaJIT-2.0.1/src/vm_x86.dasc.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat b/external/lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat rename to external/lua/luajit/LuaJIT-2.0.1/src/xedkbuild.bat diff --git a/cocos/scripting/lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch b/external/lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch similarity index 100% rename from cocos/scripting/lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch rename to external/lua/luajit/LuaJIT-2.0.1/v2.0.1_hotfix1.patch diff --git a/cocos/scripting/lua/luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id b/external/lua/luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id rename to external/lua/luajit/android/armeabi-v7a/libluajit.a.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id b/external/lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id rename to external/lua/luajit/android/armeabi/libluajit.a.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/android/x86/libluajit.a.REMOVED.git-id b/external/lua/luajit/android/x86/libluajit.a.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/android/x86/libluajit.a.REMOVED.git-id rename to external/lua/luajit/android/x86/libluajit.a.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/build_android.sh b/external/lua/luajit/build_android.sh similarity index 100% rename from cocos/scripting/lua/luajit/build_android.sh rename to external/lua/luajit/build_android.sh diff --git a/cocos/scripting/lua/luajit/build_ios.sh b/external/lua/luajit/build_ios.sh similarity index 100% rename from cocos/scripting/lua/luajit/build_ios.sh rename to external/lua/luajit/build_ios.sh diff --git a/cocos/scripting/lua/luajit/build_mac.sh b/external/lua/luajit/build_mac.sh similarity index 100% rename from cocos/scripting/lua/luajit/build_mac.sh rename to external/lua/luajit/build_mac.sh diff --git a/cocos/scripting/lua/luajit/include/lauxlib.h b/external/lua/luajit/include/lauxlib.h similarity index 100% rename from cocos/scripting/lua/luajit/include/lauxlib.h rename to external/lua/luajit/include/lauxlib.h diff --git a/cocos/scripting/lua/luajit/include/lua.h b/external/lua/luajit/include/lua.h similarity index 100% rename from cocos/scripting/lua/luajit/include/lua.h rename to external/lua/luajit/include/lua.h diff --git a/cocos/scripting/lua/luajit/include/luaconf.h b/external/lua/luajit/include/luaconf.h similarity index 100% rename from cocos/scripting/lua/luajit/include/luaconf.h rename to external/lua/luajit/include/luaconf.h diff --git a/cocos/scripting/lua/luajit/include/lualib.h b/external/lua/luajit/include/lualib.h similarity index 100% rename from cocos/scripting/lua/luajit/include/lualib.h rename to external/lua/luajit/include/lualib.h diff --git a/cocos/scripting/lua/luajit/ios/libluajit.a.REMOVED.git-id b/external/lua/luajit/ios/libluajit.a.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/ios/libluajit.a.REMOVED.git-id rename to external/lua/luajit/ios/libluajit.a.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/mac/libluajit.a.REMOVED.git-id b/external/lua/luajit/mac/libluajit.a.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/mac/libluajit.a.REMOVED.git-id rename to external/lua/luajit/mac/libluajit.a.REMOVED.git-id diff --git a/cocos/scripting/lua/luajit/win32/lua51.dll.REMOVED.git-id b/external/lua/luajit/win32/lua51.dll.REMOVED.git-id similarity index 100% rename from cocos/scripting/lua/luajit/win32/lua51.dll.REMOVED.git-id rename to external/lua/luajit/win32/lua51.dll.REMOVED.git-id diff --git a/cocos/scripting/lua/tolua/tolua++.h b/external/lua/tolua/tolua++.h similarity index 100% rename from cocos/scripting/lua/tolua/tolua++.h rename to external/lua/tolua/tolua++.h diff --git a/cocos/scripting/lua/tolua/tolua_event.c b/external/lua/tolua/tolua_event.c similarity index 100% rename from cocos/scripting/lua/tolua/tolua_event.c rename to external/lua/tolua/tolua_event.c diff --git a/cocos/scripting/lua/tolua/tolua_event.h b/external/lua/tolua/tolua_event.h similarity index 100% rename from cocos/scripting/lua/tolua/tolua_event.h rename to external/lua/tolua/tolua_event.h diff --git a/cocos/scripting/lua/tolua/tolua_is.c b/external/lua/tolua/tolua_is.c similarity index 100% rename from cocos/scripting/lua/tolua/tolua_is.c rename to external/lua/tolua/tolua_is.c diff --git a/cocos/scripting/lua/tolua/tolua_map.c b/external/lua/tolua/tolua_map.c similarity index 100% rename from cocos/scripting/lua/tolua/tolua_map.c rename to external/lua/tolua/tolua_map.c diff --git a/cocos/scripting/lua/tolua/tolua_push.c b/external/lua/tolua/tolua_push.c similarity index 100% rename from cocos/scripting/lua/tolua/tolua_push.c rename to external/lua/tolua/tolua_push.c diff --git a/cocos/scripting/lua/tolua/tolua_to.c b/external/lua/tolua/tolua_to.c similarity index 100% rename from cocos/scripting/lua/tolua/tolua_to.c rename to external/lua/tolua/tolua_to.c From 8f7a489a4d43131b575b4727388303f0736d129a Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 16 Oct 2013 16:48:39 +0800 Subject: [PATCH 154/557] issue #2905:make cocostudio and gui flat --- cocos/2d/Android.mk | 310 +++++++++--------- .../cocosbuilder/CCBAnimationManager.h | 2 +- cocos/editor-support/cocostudio/Android.mk | 72 ++-- .../cocostudio/{action => }/CCActionFrame.cpp | 0 .../cocostudio/{action => }/CCActionFrame.h | 0 .../{action => }/CCActionFrameEasing.cpp | 4 +- .../{action => }/CCActionFrameEasing.h | 2 +- .../{action => }/CCActionManagerEx.cpp | 4 +- .../{action => }/CCActionManagerEx.h | 4 +- .../cocostudio/{action => }/CCActionNode.cpp | 10 +- .../cocostudio/{action => }/CCActionNode.h | 4 +- .../{action => }/CCActionObject.cpp | 4 +- .../cocostudio/{action => }/CCActionObject.h | 2 +- .../cocostudio/{armature => }/CCArmature.cpp | 12 +- .../cocostudio/{armature => }/CCArmature.h | 12 +- .../animation => }/CCArmatureAnimation.cpp | 12 +- .../animation => }/CCArmatureAnimation.h | 2 +- .../utils => }/CCArmatureDataManager.cpp | 8 +- .../utils => }/CCArmatureDataManager.h | 4 +- .../{armature/utils => }/CCArmatureDefine.cpp | 2 +- .../{armature/utils => }/CCArmatureDefine.h | 0 .../{armature/display => }/CCBatchNode.cpp | 6 +- .../{armature/display => }/CCBatchNode.h | 2 +- .../cocostudio/{armature => }/CCBone.cpp | 12 +- .../cocostudio/{armature => }/CCBone.h | 10 +- .../physics => }/CCColliderDetector.cpp | 6 +- .../physics => }/CCColliderDetector.h | 4 +- .../{components => }/CCComAttribute.cpp | 2 +- .../{components => }/CCComAttribute.h | 2 +- .../{components => }/CCComAudio.cpp | 2 +- .../cocostudio/{components => }/CCComAudio.h | 0 .../{components => }/CCComController.cpp | 2 +- .../{components => }/CCComController.h | 2 +- .../{components => }/CCComRender.cpp | 2 +- .../cocostudio/{components => }/CCComRender.h | 0 .../utils => }/CCDataReaderHelper.cpp | 12 +- .../{armature/utils => }/CCDataReaderHelper.h | 8 +- .../{armature/datas => }/CCDatas.cpp | 6 +- .../cocostudio/{armature/datas => }/CCDatas.h | 4 +- .../display => }/CCDecorativeDisplay.cpp | 2 +- .../display => }/CCDecorativeDisplay.h | 8 +- .../display => }/CCDisplayFactory.cpp | 14 +- .../{armature/display => }/CCDisplayFactory.h | 4 +- .../display => }/CCDisplayManager.cpp | 10 +- .../{armature/display => }/CCDisplayManager.h | 6 +- .../{components => }/CCInputDelegate.cpp | 2 +- .../{components => }/CCInputDelegate.h | 0 .../animation => }/CCProcessBase.cpp | 4 +- .../{armature/animation => }/CCProcessBase.h | 4 +- .../cocostudio/{reader => }/CCSGUIReader.cpp | 8 +- .../cocostudio/{reader => }/CCSGUIReader.h | 4 +- .../{reader => }/CCSSceneReader.cpp | 5 +- .../cocostudio/{reader => }/CCSSceneReader.h | 2 +- .../{armature/display => }/CCSkin.cpp | 8 +- .../{armature/display => }/CCSkin.h | 4 +- .../utils => }/CCSpriteFrameCacheHelper.cpp | 2 +- .../utils => }/CCSpriteFrameCacheHelper.h | 2 +- .../{armature/utils => }/CCTransformHelp.cpp | 4 +- .../{armature/utils => }/CCTransformHelp.h | 4 +- .../{armature/animation => }/CCTween.cpp | 14 +- .../{armature/animation => }/CCTween.h | 4 +- .../{armature/utils => }/CCTweenFunction.cpp | 4 +- .../{armature/utils => }/CCTweenFunction.h | 2 +- .../{armature/utils => }/CCUtilMath.cpp | 2 +- .../{armature/utils => }/CCUtilMath.h | 2 +- .../{json => }/CSContentJsonDictionary.cpp | 2 +- .../{json => }/CSContentJsonDictionary.h | 0 cocos/editor-support/cocostudio/CocoStudio.h | 66 ++-- .../{json => }/DictionaryHelper.cpp | 2 +- .../cocostudio/{json => }/DictionaryHelper.h | 2 +- .../editor-support/cocostudio/json/.DS_Store | Bin 6148 -> 0 bytes cocos/gui/Android.mk | 47 ++- cocos/gui/{system => }/CocosGUI.cpp | 2 +- cocos/gui/{system => }/CocosGUI.h | 37 +-- cocos/gui/{layouts => }/Layout.cpp | 6 +- cocos/gui/{layouts => }/Layout.h | 2 +- cocos/gui/{layouts => }/LayoutParameter.cpp | 4 +- cocos/gui/{layouts => }/LayoutParameter.h | 2 +- cocos/gui/{widgets => }/UIButton.cpp | 2 +- cocos/gui/{widgets => }/UIButton.h | 2 +- cocos/gui/{widgets => }/UICheckBox.cpp | 2 +- cocos/gui/{widgets => }/UICheckBox.h | 2 +- .../scroll-widget => }/UIDragPanel.cpp | 4 +- .../{widgets/scroll-widget => }/UIDragPanel.h | 4 +- cocos/gui/{system => }/UIHelper.cpp | 7 +- cocos/gui/{system => }/UIHelper.h | 4 +- cocos/gui/{widgets => }/UIImageView.cpp | 2 +- cocos/gui/{widgets => }/UIImageView.h | 2 +- cocos/gui/{system => }/UIInputManager.cpp | 4 +- cocos/gui/{system => }/UIInputManager.h | 2 +- cocos/gui/{widgets => }/UILabel.cpp | 2 +- cocos/gui/{widgets => }/UILabel.h | 2 +- cocos/gui/{widgets => }/UILabelAtlas.cpp | 2 +- cocos/gui/{widgets => }/UILabelAtlas.h | 2 +- cocos/gui/{widgets => }/UILabelBMFont.cpp | 2 +- cocos/gui/{widgets => }/UILabelBMFont.h | 2 +- cocos/gui/{system => }/UILayer.cpp | 4 +- cocos/gui/{system => }/UILayer.h | 4 +- cocos/gui/{layouts => }/UILayoutDefine.cpp | 2 +- cocos/gui/{layouts => }/UILayoutDefine.h | 0 .../scroll-widget => }/UIListView.cpp | 2 +- .../{widgets/scroll-widget => }/UIListView.h | 2 +- cocos/gui/{widgets => }/UILoadingBar.cpp | 2 +- cocos/gui/{widgets => }/UILoadingBar.h | 2 +- .../scroll-widget => }/UIPageView.cpp | 2 +- .../{widgets/scroll-widget => }/UIPageView.h | 4 +- cocos/gui/{base-classes => }/UIRootWidget.cpp | 2 +- cocos/gui/{base-classes => }/UIRootWidget.h | 2 +- .../scroll-widget => }/UIScrollInterface.h | 2 +- .../scroll-widget => }/UIScrollView.cpp | 4 +- .../scroll-widget => }/UIScrollView.h | 4 +- cocos/gui/{widgets => }/UISlider.cpp | 2 +- cocos/gui/{widgets => }/UISlider.h | 2 +- cocos/gui/{widgets => }/UITextField.cpp | 2 +- cocos/gui/{widgets => }/UITextField.h | 2 +- cocos/gui/{base-classes => }/UIWidget.cpp | 8 +- cocos/gui/{base-classes => }/UIWidget.h | 4 +- cocos/network/Android.mk | 5 +- cocos/network/HttpClient.h | 6 +- cocos/network/HttpResponse.h | 2 +- extensions/Android.mk | 5 +- extensions/GUI/CCEditBox/CCEditBox.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImpl.h | 2 +- .../GUI/CCEditBox/CCEditBoxImplAndroid.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImplIOS.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImplMac.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImplTizen.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImplWin.h | 2 +- extensions/GUI/CCScrollView/CCScrollView.h | 2 +- extensions/GUI/CCScrollView/CCSorting.h | 2 +- extensions/assets-manager/AssetsManager.h | 2 +- extensions/physics-nodes/CCPhysicsDebugNode.h | 2 +- extensions/physics-nodes/CCPhysicsSprite.h | 2 +- samples/Cpp/TestCpp/Android.mk | 264 +++++++-------- samples/Cpp/TestCpp/Classes/AppDelegate.cpp | 2 +- .../TestCpp/Classes/Box2DTest/Box2dTest.cpp | 2 +- .../Classes/ChipmunkTest/ChipmunkTest.h | 2 +- .../CocosDenshionTest/CocosDenshionTest.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.h | 2 +- .../ComponentsTestScene.h | 2 +- .../EnemyController.h | 2 +- .../PlayerController.h | 2 +- .../ProjectileController.h | 2 +- .../SceneController.h | 2 +- .../CocoStudioGUITest/CocosGUIScene.h | 4 +- .../UINodeContainerTest.cpp | 2 +- .../CocoStudioGUITest/UIScene.cpp | 2 +- .../CocoStudioGUITest/UIScene.h | 4 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 4 +- .../CocoStudioSceneTest/SceneEditorTest.h | 2 +- .../AnimationsTest/AnimationsTestLayer.h | 2 +- .../ButtonTest/ButtonTestLayer.h | 2 +- .../HelloCocosBuilderLayer.h | 2 +- .../LabelTest/LabelTestLayer.h | 2 +- .../CocosBuilderTest/MenuTest/MenuTestLayer.h | 2 +- .../ParticleSystemTestLayer.h | 2 +- .../ScrollViewTest/ScrollViewTestLayer.h | 2 +- .../SpriteTest/SpriteTestLayer.h | 2 +- .../TestHeader/TestHeaderLayer.h | 2 +- .../TimelineCallbackTestLayer.h | 2 +- .../CCControlColourPickerTest.h | 2 +- .../ControlExtensionTest/CCControlScene.h | 2 +- .../CCControlSceneManager.h | 2 +- .../ExtensionsTest/EditBoxTest/EditBoxTest.h | 2 +- .../NetworkTest/HttpClientTest.h | 4 +- .../ExtensionsTest/NetworkTest/SocketIOTest.h | 4 +- .../NetworkTest/WebSocketTest.h | 4 +- .../Scale9SpriteTest/Scale9SpriteTest.cpp | 2 +- .../TableViewTest/CustomTableViewCell.h | 2 +- .../TableViewTest/TableViewTestScene.h | 2 +- .../Classes/SchedulerTest/SchedulerTest.h | 2 +- .../TestCpp/Classes/ShaderTest/ShaderTest.h | 2 +- .../TestCpp/Classes/ShaderTest/ShaderTest2.h | 2 +- samples/Cpp/TestCpp/Classes/testBasic.cpp | 2 +- .../Cpp/TestCpp/proj.android/jni/Android.mk | 2 +- samples/Lua/HelloLua/Classes/AppDelegate.cpp | 2 +- .../Lua/HelloLua/proj.android/build_native.sh | 4 +- .../Lua/HelloLua/proj.android/jni/Android.mk | 11 +- 178 files changed, 682 insertions(+), 691 deletions(-) rename cocos/editor-support/cocostudio/{action => }/CCActionFrame.cpp (100%) rename cocos/editor-support/cocostudio/{action => }/CCActionFrame.h (100%) rename cocos/editor-support/cocostudio/{action => }/CCActionFrameEasing.cpp (98%) rename cocos/editor-support/cocostudio/{action => }/CCActionFrameEasing.h (97%) rename cocos/editor-support/cocostudio/{action => }/CCActionManagerEx.cpp (97%) rename cocos/editor-support/cocostudio/{action => }/CCActionManagerEx.h (96%) rename cocos/editor-support/cocostudio/{action => }/CCActionNode.cpp (98%) rename cocos/editor-support/cocostudio/{action => }/CCActionNode.h (98%) rename cocos/editor-support/cocostudio/{action => }/CCActionObject.cpp (98%) rename cocos/editor-support/cocostudio/{action => }/CCActionObject.h (98%) rename cocos/editor-support/cocostudio/{armature => }/CCArmature.cpp (98%) rename cocos/editor-support/cocostudio/{armature => }/CCArmature.h (96%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCArmatureAnimation.cpp (97%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCArmatureAnimation.h (99%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCArmatureDataManager.cpp (97%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCArmatureDataManager.h (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCArmatureDefine.cpp (96%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCArmatureDefine.h (100%) rename cocos/editor-support/cocostudio/{armature/display => }/CCBatchNode.cpp (95%) rename cocos/editor-support/cocostudio/{armature/display => }/CCBatchNode.h (96%) rename cocos/editor-support/cocostudio/{armature => }/CCBone.cpp (97%) rename cocos/editor-support/cocostudio/{armature => }/CCBone.h (96%) rename cocos/editor-support/cocostudio/{armature/physics => }/CCColliderDetector.cpp (98%) rename cocos/editor-support/cocostudio/{armature/physics => }/CCColliderDetector.h (96%) rename cocos/editor-support/cocostudio/{components => }/CCComAttribute.cpp (99%) rename cocos/editor-support/cocostudio/{components => }/CCComAttribute.h (97%) rename cocos/editor-support/cocostudio/{components => }/CCComAudio.cpp (99%) rename cocos/editor-support/cocostudio/{components => }/CCComAudio.h (100%) rename cocos/editor-support/cocostudio/{components => }/CCComController.cpp (97%) rename cocos/editor-support/cocostudio/{components => }/CCComController.h (97%) rename cocos/editor-support/cocostudio/{components => }/CCComRender.cpp (98%) rename cocos/editor-support/cocostudio/{components => }/CCComRender.h (100%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCDataReaderHelper.cpp (99%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCDataReaderHelper.h (96%) rename cocos/editor-support/cocostudio/{armature/datas => }/CCDatas.cpp (98%) rename cocos/editor-support/cocostudio/{armature/datas => }/CCDatas.h (99%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDecorativeDisplay.cpp (97%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDecorativeDisplay.h (91%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDisplayFactory.cpp (96%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDisplayFactory.h (96%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDisplayManager.cpp (97%) rename cocos/editor-support/cocostudio/{armature/display => }/CCDisplayManager.h (96%) rename cocos/editor-support/cocostudio/{components => }/CCInputDelegate.cpp (99%) rename cocos/editor-support/cocostudio/{components => }/CCInputDelegate.h (100%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCProcessBase.cpp (98%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCProcessBase.h (98%) rename cocos/editor-support/cocostudio/{reader => }/CCSGUIReader.cpp (99%) rename cocos/editor-support/cocostudio/{reader => }/CCSGUIReader.h (97%) rename cocos/editor-support/cocostudio/{reader => }/CCSSceneReader.cpp (99%) rename cocos/editor-support/cocostudio/{reader => }/CCSSceneReader.h (97%) rename cocos/editor-support/cocostudio/{armature/display => }/CCSkin.cpp (96%) rename cocos/editor-support/cocostudio/{armature/display => }/CCSkin.h (95%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCSpriteFrameCacheHelper.cpp (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCSpriteFrameCacheHelper.h (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCTransformHelp.cpp (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCTransformHelp.h (96%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCTween.cpp (97%) rename cocos/editor-support/cocostudio/{armature/animation => }/CCTween.h (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCTweenFunction.cpp (99%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCTweenFunction.h (99%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCUtilMath.cpp (98%) rename cocos/editor-support/cocostudio/{armature/utils => }/CCUtilMath.h (98%) rename cocos/editor-support/cocostudio/{json => }/CSContentJsonDictionary.cpp (99%) rename cocos/editor-support/cocostudio/{json => }/CSContentJsonDictionary.h (100%) rename cocos/editor-support/cocostudio/{json => }/DictionaryHelper.cpp (99%) rename cocos/editor-support/cocostudio/{json => }/DictionaryHelper.h (98%) delete mode 100644 cocos/editor-support/cocostudio/json/.DS_Store rename cocos/gui/{system => }/CocosGUI.cpp (98%) rename cocos/gui/{system => }/CocosGUI.h (67%) rename cocos/gui/{layouts => }/Layout.cpp (99%) rename cocos/gui/{layouts => }/Layout.h (99%) rename cocos/gui/{layouts => }/LayoutParameter.cpp (98%) rename cocos/gui/{layouts => }/LayoutParameter.h (99%) rename cocos/gui/{widgets => }/UIButton.cpp (99%) rename cocos/gui/{widgets => }/UIButton.h (99%) rename cocos/gui/{widgets => }/UICheckBox.cpp (99%) rename cocos/gui/{widgets => }/UICheckBox.h (99%) rename cocos/gui/{widgets/scroll-widget => }/UIDragPanel.cpp (99%) rename cocos/gui/{widgets/scroll-widget => }/UIDragPanel.h (99%) rename cocos/gui/{system => }/UIHelper.cpp (98%) rename cocos/gui/{system => }/UIHelper.h (97%) rename cocos/gui/{widgets => }/UIImageView.cpp (99%) rename cocos/gui/{widgets => }/UIImageView.h (99%) rename cocos/gui/{system => }/UIInputManager.cpp (99%) rename cocos/gui/{system => }/UIInputManager.h (99%) rename cocos/gui/{widgets => }/UILabel.cpp (99%) rename cocos/gui/{widgets => }/UILabel.h (99%) rename cocos/gui/{widgets => }/UILabelAtlas.cpp (99%) rename cocos/gui/{widgets => }/UILabelAtlas.h (98%) rename cocos/gui/{widgets => }/UILabelBMFont.cpp (99%) rename cocos/gui/{widgets => }/UILabelBMFont.h (98%) rename cocos/gui/{system => }/UILayer.cpp (98%) rename cocos/gui/{system => }/UILayer.h (98%) rename cocos/gui/{layouts => }/UILayoutDefine.cpp (98%) rename cocos/gui/{layouts => }/UILayoutDefine.h (100%) rename cocos/gui/{widgets/scroll-widget => }/UIListView.cpp (99%) rename cocos/gui/{widgets/scroll-widget => }/UIListView.h (99%) rename cocos/gui/{widgets => }/UILoadingBar.cpp (99%) rename cocos/gui/{widgets => }/UILoadingBar.h (99%) rename cocos/gui/{widgets/scroll-widget => }/UIPageView.cpp (99%) rename cocos/gui/{widgets/scroll-widget => }/UIPageView.h (98%) rename cocos/gui/{base-classes => }/UIRootWidget.cpp (98%) rename cocos/gui/{base-classes => }/UIRootWidget.h (98%) rename cocos/gui/{widgets/scroll-widget => }/UIScrollInterface.h (98%) rename cocos/gui/{widgets/scroll-widget => }/UIScrollView.cpp (99%) rename cocos/gui/{widgets/scroll-widget => }/UIScrollView.h (99%) rename cocos/gui/{widgets => }/UISlider.cpp (99%) rename cocos/gui/{widgets => }/UISlider.h (99%) rename cocos/gui/{widgets => }/UITextField.cpp (99%) rename cocos/gui/{widgets => }/UITextField.h (99%) rename cocos/gui/{base-classes => }/UIWidget.cpp (99%) rename cocos/gui/{base-classes => }/UIWidget.h (99%) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 74c8b0313f..20017089fe 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -7,165 +7,164 @@ LOCAL_MODULE := cocos2dx_static LOCAL_MODULE_FILENAME := libcocos2d LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/base64.cpp \ -$(LOCAL_PATH)/CCAction.cpp \ -$(LOCAL_PATH)/CCActionCamera.cpp \ -$(LOCAL_PATH)/CCActionCatmullRom.cpp \ -$(LOCAL_PATH)/CCActionEase.cpp \ -$(LOCAL_PATH)/CCActionGrid.cpp \ -$(LOCAL_PATH)/CCActionGrid3D.cpp \ -$(LOCAL_PATH)/CCActionInstant.cpp \ -$(LOCAL_PATH)/CCActionInterval.cpp \ -$(LOCAL_PATH)/CCActionManager.cpp \ -$(LOCAL_PATH)/CCActionPageTurn3D.cpp \ -$(LOCAL_PATH)/CCActionProgressTimer.cpp \ -$(LOCAL_PATH)/CCActionTiledGrid.cpp \ -$(LOCAL_PATH)/CCActionTween.cpp \ -$(LOCAL_PATH)/CCAnimation.cpp \ -$(LOCAL_PATH)/CCAnimationCache.cpp \ -$(LOCAL_PATH)/CCAtlasNode.cpp \ -$(LOCAL_PATH)/CCCamera.cpp \ -$(LOCAL_PATH)/ccCArray.cpp \ -$(LOCAL_PATH)/CCClippingNode.cpp \ -$(LOCAL_PATH)/CCComponent.cpp \ -$(LOCAL_PATH)/CCComponentContainer.cpp \ -$(LOCAL_PATH)/CCConfiguration.cpp \ -$(LOCAL_PATH)/CCDeprecated.cpp \ -$(LOCAL_PATH)/CCDirector.cpp \ -$(LOCAL_PATH)/CCDrawingPrimitives.cpp \ -$(LOCAL_PATH)/CCDrawNode.cpp \ -$(LOCAL_PATH)/CCEvent.cpp \ -$(LOCAL_PATH)/CCEventAcceleration.cpp \ -$(LOCAL_PATH)/CCEventCustom.cpp \ -$(LOCAL_PATH)/CCEventDispatcher.cpp \ -$(LOCAL_PATH)/CCEventKeyboard.cpp \ -$(LOCAL_PATH)/CCEventListener.cpp \ -$(LOCAL_PATH)/CCEventListenerAcceleration.cpp \ -$(LOCAL_PATH)/CCEventListenerCustom.cpp \ -$(LOCAL_PATH)/CCEventListenerKeyboard.cpp \ -$(LOCAL_PATH)/CCEventListenerTouch.cpp \ -$(LOCAL_PATH)/CCEventTouch.cpp \ -$(LOCAL_PATH)/CCFont.cpp \ -$(LOCAL_PATH)/CCFontAtlas.cpp \ -$(LOCAL_PATH)/CCFontAtlasCache.cpp \ -$(LOCAL_PATH)/CCFontAtlasFactory.cpp \ -$(LOCAL_PATH)/CCFontDefinition.cpp \ -$(LOCAL_PATH)/CCFontFNT.cpp \ -$(LOCAL_PATH)/CCFontFreeType.cpp \ -$(LOCAL_PATH)/ccFPSImages.c \ -$(LOCAL_PATH)/CCGLBufferedNode.cpp \ -$(LOCAL_PATH)/CCGLProgram.cpp \ -$(LOCAL_PATH)/ccGLStateCache.cpp \ -$(LOCAL_PATH)/CCGrabber.cpp \ -$(LOCAL_PATH)/CCGrid.cpp \ -$(LOCAL_PATH)/CCIMEDispatcher.cpp \ -$(LOCAL_PATH)/CCLabel.cpp \ -$(LOCAL_PATH)/CCLabelAtlas.cpp \ -$(LOCAL_PATH)/CCLabelBMFont.cpp \ -$(LOCAL_PATH)/CCLabelTextFormatter.cpp \ -$(LOCAL_PATH)/CCLabelTTF.cpp \ -$(LOCAL_PATH)/CCLayer.cpp \ -$(LOCAL_PATH)/CCMenu.cpp \ -$(LOCAL_PATH)/CCMenuItem.cpp \ -$(LOCAL_PATH)/CCMotionStreak.cpp \ -$(LOCAL_PATH)/CCNode.cpp \ -$(LOCAL_PATH)/CCNotificationCenter.cpp \ -$(LOCAL_PATH)/CCParallaxNode.cpp \ -$(LOCAL_PATH)/CCParticleBatchNode.cpp \ -$(LOCAL_PATH)/CCParticleExamples.cpp \ -$(LOCAL_PATH)/CCParticleSystem.cpp \ -$(LOCAL_PATH)/CCParticleSystemQuad.cpp \ -$(LOCAL_PATH)/CCProfiling.cpp \ -$(LOCAL_PATH)/CCProgressTimer.cpp \ -$(LOCAL_PATH)/CCRenderTexture.cpp \ -$(LOCAL_PATH)/CCScene.cpp \ -$(LOCAL_PATH)/CCScheduler.cpp \ -$(LOCAL_PATH)/CCScriptSupport.cpp \ -$(LOCAL_PATH)/CCShaderCache.cpp \ -$(LOCAL_PATH)/ccShaders.cpp \ -$(LOCAL_PATH)/CCSprite.cpp \ -$(LOCAL_PATH)/CCSpriteBatchNode.cpp \ -$(LOCAL_PATH)/CCSpriteFrame.cpp \ -$(LOCAL_PATH)/CCSpriteFrameCache.cpp \ -$(LOCAL_PATH)/CCTextFieldTTF.cpp \ -$(LOCAL_PATH)/CCTextImage.cpp \ -$(LOCAL_PATH)/CCTexture2D.cpp \ -$(LOCAL_PATH)/CCTextureAtlas.cpp \ -$(LOCAL_PATH)/CCTextureCache.cpp \ -$(LOCAL_PATH)/CCTileMapAtlas.cpp \ -$(LOCAL_PATH)/CCTMXLayer.cpp \ -$(LOCAL_PATH)/CCTMXObjectGroup.cpp \ -$(LOCAL_PATH)/CCTMXTiledMap.cpp \ -$(LOCAL_PATH)/CCTMXXMLParser.cpp \ -$(LOCAL_PATH)/CCTouch.cpp \ -$(LOCAL_PATH)/CCTransition.cpp \ -$(LOCAL_PATH)/CCTransitionPageTurn.cpp \ -$(LOCAL_PATH)/CCTransitionProgress.cpp \ -$(LOCAL_PATH)/ccTypes.cpp \ -$(LOCAL_PATH)/CCUserDefault.cpp \ -$(LOCAL_PATH)/CCUserDefaultAndroid.cpp \ -$(LOCAL_PATH)/ccUTF8.cpp \ -$(LOCAL_PATH)/ccUtils.cpp \ -$(LOCAL_PATH)/CCVertex.cpp \ -$(LOCAL_PATH)/cocos2d.cpp \ -$(LOCAL_PATH)/TGAlib.cpp \ -$(LOCAL_PATH)/TransformUtils.cpp \ -$(LOCAL_PATH)/ZipUtils.cpp \ -$(LOCAL_PATH)/platform/CCEGLViewProtocol.cpp \ -$(LOCAL_PATH)/platform/CCFileUtils.cpp \ -$(LOCAL_PATH)/platform/CCSAXParser.cpp \ -$(LOCAL_PATH)/platform/CCThread.cpp \ -$(LOCAL_PATH)/../base/atitc.cpp \ -$(LOCAL_PATH)/../base/CCAffineTransform.cpp \ -$(LOCAL_PATH)/../base/CCArray.cpp \ -$(LOCAL_PATH)/../base/CCAutoreleasePool.cpp \ -$(LOCAL_PATH)/../base/CCData.cpp \ -$(LOCAL_PATH)/../base/CCDataVisitor.cpp \ -$(LOCAL_PATH)/../base/CCDictionary.cpp \ -$(LOCAL_PATH)/../base/CCGeometry.cpp \ -$(LOCAL_PATH)/../base/CCNS.cpp \ -$(LOCAL_PATH)/../base/CCObject.cpp \ -$(LOCAL_PATH)/../base/CCSet.cpp \ -$(LOCAL_PATH)/../base/CCString.cpp \ -$(LOCAL_PATH)/../base/etc1.cpp \ -$(LOCAL_PATH)/../base/s3tc.cpp \ -$(LOCAL_PATH)/../math/kazmath/src/aabb.c \ -$(LOCAL_PATH)/../math/kazmath/src/mat3.c \ -$(LOCAL_PATH)/../math/kazmath/src/mat4.c \ -$(LOCAL_PATH)/../math/kazmath/src/neon_matrix_impl.c \ -$(LOCAL_PATH)/../math/kazmath/src/plane.c \ -$(LOCAL_PATH)/../math/kazmath/src/quaternion.c \ -$(LOCAL_PATH)/../math/kazmath/src/ray2.c \ -$(LOCAL_PATH)/../math/kazmath/src/utility.c \ -$(LOCAL_PATH)/../math/kazmath/src/vec2.c \ -$(LOCAL_PATH)/../math/kazmath/src/vec3.c \ -$(LOCAL_PATH)/../math/kazmath/src/vec4.c \ -$(LOCAL_PATH)/../math/kazmath/src/GL/mat4stack.c \ -$(LOCAL_PATH)/../math/kazmath/src/GL/matrix.c \ -$(LOCAL_PATH)/../physics/CCPhysicsBody.cpp \ -$(LOCAL_PATH)/../physics/CCPhysicsContact.cpp \ -$(LOCAL_PATH)/../physics/CCPhysicsJoint.cpp \ -$(LOCAL_PATH)/../physics/CCPhysicsShape.cpp \ -$(LOCAL_PATH)/../physics/CCPhysicsWorld.cpp \ -$(LOCAL_PATH)/../physics/box2d/CCPhysicsBodyInfo.cpp \ -$(LOCAL_PATH)/../physics/box2d/CCPhysicsContactInfo.cpp \ -$(LOCAL_PATH)/../physics/box2d/CCPhysicsJointInfo.cpp \ -$(LOCAL_PATH)/../physics/box2d/CCPhysicsShapeInfo.cpp \ -$(LOCAL_PATH)/../physics/box2d/CCPhysicsWorldInfo.cpp \ -$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsContactInfo.cpp \ -$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsJointInfo.cpp \ -$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -$(LOCAL_PATH)/../physics/chipmunk/CCPhysicsWorldInfo.cpp \ -$(LOCAL_PATH)/../../external/tinyxml2/tinyxml2.cpp \ -$(LOCAL_PATH)/../../external/unzip/ioapi.cpp \ -$(LOCAL_PATH)/../../external/unzip/unzip.cpp +base64.cpp \ +CCAction.cpp \ +CCActionCamera.cpp \ +CCActionCatmullRom.cpp \ +CCActionEase.cpp \ +CCActionGrid.cpp \ +CCActionGrid3D.cpp \ +CCActionInstant.cpp \ +CCActionInterval.cpp \ +CCActionManager.cpp \ +CCActionPageTurn3D.cpp \ +CCActionProgressTimer.cpp \ +CCActionTiledGrid.cpp \ +CCActionTween.cpp \ +CCAnimation.cpp \ +CCAnimationCache.cpp \ +CCAtlasNode.cpp \ +CCCamera.cpp \ +ccCArray.cpp \ +CCClippingNode.cpp \ +CCComponent.cpp \ +CCComponentContainer.cpp \ +CCConfiguration.cpp \ +CCDeprecated.cpp \ +CCDirector.cpp \ +CCDrawingPrimitives.cpp \ +CCDrawNode.cpp \ +CCEvent.cpp \ +CCEventAcceleration.cpp \ +CCEventCustom.cpp \ +CCEventDispatcher.cpp \ +CCEventKeyboard.cpp \ +CCEventListener.cpp \ +CCEventListenerAcceleration.cpp \ +CCEventListenerCustom.cpp \ +CCEventListenerKeyboard.cpp \ +CCEventListenerTouch.cpp \ +CCEventTouch.cpp \ +CCFont.cpp \ +CCFontAtlas.cpp \ +CCFontAtlasCache.cpp \ +CCFontAtlasFactory.cpp \ +CCFontDefinition.cpp \ +CCFontFNT.cpp \ +CCFontFreeType.cpp \ +ccFPSImages.c \ +CCGLBufferedNode.cpp \ +CCGLProgram.cpp \ +ccGLStateCache.cpp \ +CCGrabber.cpp \ +CCGrid.cpp \ +CCIMEDispatcher.cpp \ +CCLabel.cpp \ +CCLabelAtlas.cpp \ +CCLabelBMFont.cpp \ +CCLabelTextFormatter.cpp \ +CCLabelTTF.cpp \ +CCLayer.cpp \ +CCMenu.cpp \ +CCMenuItem.cpp \ +CCMotionStreak.cpp \ +CCNode.cpp \ +CCNotificationCenter.cpp \ +CCParallaxNode.cpp \ +CCParticleBatchNode.cpp \ +CCParticleExamples.cpp \ +CCParticleSystem.cpp \ +CCParticleSystemQuad.cpp \ +CCProfiling.cpp \ +CCProgressTimer.cpp \ +CCRenderTexture.cpp \ +CCScene.cpp \ +CCScheduler.cpp \ +CCScriptSupport.cpp \ +CCShaderCache.cpp \ +ccShaders.cpp \ +CCSprite.cpp \ +CCSpriteBatchNode.cpp \ +CCSpriteFrame.cpp \ +CCSpriteFrameCache.cpp \ +CCTextFieldTTF.cpp \ +CCTextImage.cpp \ +CCTexture2D.cpp \ +CCTextureAtlas.cpp \ +CCTextureCache.cpp \ +CCTileMapAtlas.cpp \ +CCTMXLayer.cpp \ +CCTMXObjectGroup.cpp \ +CCTMXTiledMap.cpp \ +CCTMXXMLParser.cpp \ +CCTouch.cpp \ +CCTransition.cpp \ +CCTransitionPageTurn.cpp \ +CCTransitionProgress.cpp \ +ccTypes.cpp \ +CCUserDefault.cpp \ +CCUserDefaultAndroid.cpp \ +ccUTF8.cpp \ +ccUtils.cpp \ +CCVertex.cpp \ +cocos2d.cpp \ +TGAlib.cpp \ +TransformUtils.cpp \ +ZipUtils.cpp \ +platform/CCEGLViewProtocol.cpp \ +platform/CCFileUtils.cpp \ +platform/CCSAXParser.cpp \ +platform/CCThread.cpp \ +../base/atitc.cpp \ +../base/CCAffineTransform.cpp \ +../base/CCArray.cpp \ +../base/CCAutoreleasePool.cpp \ +../base/CCData.cpp \ +../base/CCDataVisitor.cpp \ +../base/CCDictionary.cpp \ +../base/CCGeometry.cpp \ +../base/CCNS.cpp \ +../base/CCObject.cpp \ +../base/CCSet.cpp \ +../base/CCString.cpp \ +../base/etc1.cpp \ +../base/s3tc.cpp \ +../math/kazmath/src/aabb.c \ +../math/kazmath/src/mat3.c \ +../math/kazmath/src/mat4.c \ +../math/kazmath/src/neon_matrix_impl.c \ +../math/kazmath/src/plane.c \ +../math/kazmath/src/quaternion.c \ +../math/kazmath/src/ray2.c \ +../math/kazmath/src/utility.c \ +../math/kazmath/src/vec2.c \ +../math/kazmath/src/vec3.c \ +../math/kazmath/src/vec4.c \ +../math/kazmath/src/GL/mat4stack.c \ +../math/kazmath/src/GL/matrix.c \ +../physics/CCPhysicsBody.cpp \ +../physics/CCPhysicsContact.cpp \ +../physics/CCPhysicsJoint.cpp \ +../physics/CCPhysicsShape.cpp \ +../physics/CCPhysicsWorld.cpp \ +../physics/box2d/CCPhysicsBodyInfo.cpp \ +../physics/box2d/CCPhysicsContactInfo.cpp \ +../physics/box2d/CCPhysicsJointInfo.cpp \ +../physics/box2d/CCPhysicsShapeInfo.cpp \ +../physics/box2d/CCPhysicsWorldInfo.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo.cpp \ +../physics/chipmunk/CCPhysicsContactInfo.cpp \ +../physics/chipmunk/CCPhysicsJointInfo.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../../external/tinyxml2/tinyxml2.cpp \ +../../external/unzip/ioapi.cpp \ +../../external/unzip/unzip.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ - $(LOCAL_PATH)/include \ $(LOCAL_PATH)/../math/kazmath/include \ - $(LOCAL_PATH)/platform/android \ + platform/android \ $(LOCAL_PATH)/../physics \ $(LOCAL_PATH)/../base \ $(LOCAL_PATH)/../../external/tinyxml2 \ @@ -173,7 +172,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk LOCAL_C_INCLUDES := $(LOCAL_PATH) \ - $(LOCAL_PATH)/include \ $(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/platform/android \ $(LOCAL_PATH)/../physics \ diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h index 83d962ffef..e9755bbfb1 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h @@ -2,7 +2,7 @@ #define __CCB_CCBANIMATION_MANAGER_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" #include "CCBSequence.h" #include "CCBValue.h" #include "CCBSequenceProperty.h" diff --git a/cocos/editor-support/cocostudio/Android.mk b/cocos/editor-support/cocostudio/Android.mk index 15b18c83d7..b7dfa3838c 100644 --- a/cocos/editor-support/cocostudio/Android.mk +++ b/cocos/editor-support/cocostudio/Android.mk @@ -5,50 +5,50 @@ LOCAL_MODULE := cocostudio_static LOCAL_MODULE_FILENAME := libcocostudio -LOCAL_SRC_FILES := action/CCActionFrame.cpp \ -action/CCActionFrameEasing.cpp \ -action/CCActionManagerEx.cpp \ -action/CCActionNode.cpp \ -action/CCActionObject.cpp \ -armature/CCArmature.cpp \ -armature/CCBone.cpp \ -armature/animation/CCArmatureAnimation.cpp \ -armature/animation/CCProcessBase.cpp \ -armature/animation/CCTween.cpp \ -armature/datas/CCDatas.cpp \ -armature/display/CCBatchNode.cpp \ -armature/display/CCDecorativeDisplay.cpp \ -armature/display/CCDisplayFactory.cpp \ -armature/display/CCDisplayManager.cpp \ -armature/display/CCSkin.cpp \ -armature/physics/CCColliderDetector.cpp \ -armature/utils/CCArmatureDataManager.cpp \ -armature/utils/CCArmatureDefine.cpp \ -armature/utils/CCDataReaderHelper.cpp \ -armature/utils/CCSpriteFrameCacheHelper.cpp \ -armature/utils/CCTransformHelp.cpp \ -armature/utils/CCTweenFunction.cpp \ -armature/utils/CCUtilMath.cpp \ -components/CCComAttribute.cpp \ -components/CCComAudio.cpp \ -components/CCComController.cpp \ -components/CCComRender.cpp \ -components/CCInputDelegate.cpp \ -json/CSContentJsonDictionary.cpp \ -json/DictionaryHelper.cpp \ -reader/CCSGUIReader.cpp \ -reader/CCSSceneReader.cpp \ +LOCAL_SRC_FILES := CCActionFrame.cpp \ +CCActionFrameEasing.cpp \ +CCActionManagerEx.cpp \ +CCActionNode.cpp \ +CCActionObject.cpp \ +CCArmature.cpp \ +CCBone.cpp \ +CCArmatureAnimation.cpp \ +CCProcessBase.cpp \ +CCTween.cpp \ +CCDatas.cpp \ +CCBatchNode.cpp \ +CCDecorativeDisplay.cpp \ +CCDisplayFactory.cpp \ +CCDisplayManager.cpp \ +CCSkin.cpp \ +CCColliderDetector.cpp \ +CCArmatureDataManager.cpp \ +CCArmatureDefine.cpp \ +CCDataReaderHelper.cpp \ +CCSpriteFrameCacheHelper.cpp \ +CCTransformHelp.cpp \ +CCTweenFunction.cpp \ +CCUtilMath.cpp \ +CCComAttribute.cpp \ +CCComAudio.cpp \ +CCComController.cpp \ +CCComRender.cpp \ +CCInputDelegate.cpp \ +CSContentJsonDictionary.cpp \ +DictionaryHelper.cpp \ +CCSGUIReader.cpp \ +CCSSceneReader.cpp \ ../../../external/json/json_reader.cpp \ ../../../external/json/json_value.cpp \ ../../../external/json/json_writer.cpp -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ $(LOCAL_PATH)/../../../external/json LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ $(LOCAL_PATH)/../../../external/json \ -$(LOCAL_PATH) \ -$(LOCAL_PATH)/../../gui \ +$(LOCAL_PATH)/.. \ +$(LOCAL_PATH)/../.. \ $(LOCAL_PATH)/../../../external LOCAL_CFLAGS += -Wno-psabi -fexceptions diff --git a/cocos/editor-support/cocostudio/action/CCActionFrame.cpp b/cocos/editor-support/cocostudio/CCActionFrame.cpp similarity index 100% rename from cocos/editor-support/cocostudio/action/CCActionFrame.cpp rename to cocos/editor-support/cocostudio/CCActionFrame.cpp diff --git a/cocos/editor-support/cocostudio/action/CCActionFrame.h b/cocos/editor-support/cocostudio/CCActionFrame.h similarity index 100% rename from cocos/editor-support/cocostudio/action/CCActionFrame.h rename to cocos/editor-support/cocostudio/CCActionFrame.h diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp b/cocos/editor-support/cocostudio/CCActionFrameEasing.cpp similarity index 98% rename from cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp rename to cocos/editor-support/cocostudio/CCActionFrameEasing.cpp index 74c7467c71..7694b6e53c 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.cpp +++ b/cocos/editor-support/cocostudio/CCActionFrameEasing.cpp @@ -23,8 +23,8 @@ ****************************************************************************/ #include -#include "CCActionFrameEasing.h" -#include "cocostudio/json/DictionaryHelper.h" +#include "cocostudio/CCActionFrameEasing.h" +#include "cocostudio/DictionaryHelper.h" namespace cocostudio { #ifndef M_PI_X_2 diff --git a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h b/cocos/editor-support/cocostudio/CCActionFrameEasing.h similarity index 97% rename from cocos/editor-support/cocostudio/action/CCActionFrameEasing.h rename to cocos/editor-support/cocostudio/CCActionFrameEasing.h index 74ba932d4c..8e3fa2c1f4 100644 --- a/cocos/editor-support/cocostudio/action/CCActionFrameEasing.h +++ b/cocos/editor-support/cocostudio/CCActionFrameEasing.h @@ -26,7 +26,7 @@ #define __ActionFrameEasing_H__ #include "cocos2d.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp similarity index 97% rename from cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp rename to cocos/editor-support/cocostudio/CCActionManagerEx.cpp index b863c1f9a2..68c02fed95 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCActionManagerEx.h" -#include "cocostudio/json/DictionaryHelper.h" +#include "cocostudio/CCActionManagerEx.h" +#include "cocostudio/DictionaryHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h b/cocos/editor-support/cocostudio/CCActionManagerEx.h similarity index 96% rename from cocos/editor-support/cocostudio/action/CCActionManagerEx.h rename to cocos/editor-support/cocostudio/CCActionManagerEx.h index 8776fce030..09d62b10b6 100644 --- a/cocos/editor-support/cocostudio/action/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.h @@ -26,8 +26,8 @@ #define __ActionMANAGER_H__ #include "cocos2d.h" -#include "CCActionObject.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CCActionObject.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp similarity index 98% rename from cocos/editor-support/cocostudio/action/CCActionNode.cpp rename to cocos/editor-support/cocostudio/CCActionNode.cpp index 1390d64ed6..fceca8816c 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -22,11 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCActionNode.h" -#include "CCActionFrameEasing.h" -#include "base-classes/UIWidget.h" -#include "system/UIHelper.h" -#include "cocostudio/json/DictionaryHelper.h" +#include "cocostudio/CCActionNode.h" +#include "cocostudio/CCActionFrameEasing.h" +#include "cocostudio/DictionaryHelper.h" +#include "gui/UIWidget.h" +#include "gui/UIHelper.h" using namespace cocos2d; using namespace gui; diff --git a/cocos/editor-support/cocostudio/action/CCActionNode.h b/cocos/editor-support/cocostudio/CCActionNode.h similarity index 98% rename from cocos/editor-support/cocostudio/action/CCActionNode.h rename to cocos/editor-support/cocostudio/CCActionNode.h index 67a424bda8..6f38a1a647 100644 --- a/cocos/editor-support/cocostudio/action/CCActionNode.h +++ b/cocos/editor-support/cocostudio/CCActionNode.h @@ -26,8 +26,8 @@ #define __ActionNODE_H__ #include "cocos2d.h" -#include "CCActionFrame.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CCActionFrame.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.cpp b/cocos/editor-support/cocostudio/CCActionObject.cpp similarity index 98% rename from cocos/editor-support/cocostudio/action/CCActionObject.cpp rename to cocos/editor-support/cocostudio/CCActionObject.cpp index e218dca888..2dd60c66f2 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/CCActionObject.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCActionObject.h" -#include "cocostudio/json/DictionaryHelper.h" +#include "cocostudio/CCActionObject.h" +#include "cocostudio/DictionaryHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/action/CCActionObject.h b/cocos/editor-support/cocostudio/CCActionObject.h similarity index 98% rename from cocos/editor-support/cocostudio/action/CCActionObject.h rename to cocos/editor-support/cocostudio/CCActionObject.h index 7137f57355..cc748eaaa8 100644 --- a/cocos/editor-support/cocostudio/action/CCActionObject.h +++ b/cocos/editor-support/cocostudio/CCActionObject.h @@ -27,7 +27,7 @@ #include "cocos2d.h" #include "CCActionNode.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/CCArmature.cpp rename to cocos/editor-support/cocostudio/CCArmature.cpp index 7d4777d3f3..5885cbbd25 100644 --- a/cocos/editor-support/cocostudio/armature/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -22,12 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCArmature.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCArmatureDefine.h" -#include "utils/CCDataReaderHelper.h" -#include "datas/CCDatas.h" -#include "display/CCSkin.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDataReaderHelper.h" +#include "cocostudio/CCDatas.h" +#include "cocostudio/CCSkin.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" diff --git a/cocos/editor-support/cocostudio/armature/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/CCArmature.h rename to cocos/editor-support/cocostudio/CCArmature.h index bc0843c540..3e8c521011 100644 --- a/cocos/editor-support/cocostudio/armature/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -25,12 +25,12 @@ THE SOFTWARE. #ifndef __CCARMATURE_H__ #define __CCARMATURE_H__ -#include "utils/CCArmatureDefine.h" -#include "CCBone.h" -#include "display/CCBatchNode.h" -#include "animation/CCArmatureAnimation.h" -#include "utils/CCSpriteFrameCacheHelper.h" -#include "utils/CCArmatureDataManager.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCBatchNode.h" +#include "cocostudio/CCArmatureAnimation.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCArmatureDataManager.h" class b2Body; struct cpBody; diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp rename to cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 5490b4f4ee..a026fc33c9 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -22,12 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCArmatureAnimation.h" -#include "cocostudio/armature/CCArmature.h" -#include "cocostudio/armature/CCBone.h" -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/utils/CCUtilMath.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureAnimation.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCDatas.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h similarity index 99% rename from cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h rename to cocos/editor-support/cocostudio/CCArmatureAnimation.h index b9ac3d4200..5fa819f285 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -26,7 +26,7 @@ THE SOFTWARE. #ifndef __CCANIMATION_H__ #define __CCANIMATION_H__ -#include "CCProcessBase.h" +#include "cocostudio/CCProcessBase.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp rename to cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 2d507f6b69..113ff33202 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -23,10 +23,10 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCArmatureDataManager.h" -#include "CCTransformHelp.h" -#include "CCDataReaderHelper.h" -#include "CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCDataReaderHelper.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/CCArmatureDataManager.h similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h rename to cocos/editor-support/cocostudio/CCArmatureDataManager.h index 016156bec0..1bd426784d 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCARMATUREDATAMANAGER_H__ #define __CCARMATUREDATAMANAGER_H__ -#include "CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp similarity index 96% rename from cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp rename to cocos/editor-support/cocostudio/CCArmatureDefine.cpp index 7ed21c9a3c..3672943778 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCArmatureDefine.h" +#include "cocostudio/CCArmatureDefine.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h similarity index 100% rename from cocos/editor-support/cocostudio/armature/utils/CCArmatureDefine.h rename to cocos/editor-support/cocostudio/CCArmatureDefine.h diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp similarity index 95% rename from cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp rename to cocos/editor-support/cocostudio/CCBatchNode.cpp index ba273731b1..0c6f7598ae 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -22,9 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCBatchNode.h" -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/CCBatchNode.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCArmature.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/display/CCBatchNode.h rename to cocos/editor-support/cocostudio/CCBatchNode.h index 7e0c52bc29..df33e44e0b 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCBATCHNODE_H__ #define __CCBATCHNODE_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" +#include "cocostudio/CCArmatureDefine.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/CCBone.cpp rename to cocos/editor-support/cocostudio/CCBone.cpp index 52dea85860..abd0cb85a5 100644 --- a/cocos/editor-support/cocostudio/armature/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -22,12 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCBone.h" -#include "CCArmature.h" -#include "utils/CCUtilMath.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCTransformHelp.h" -#include "display/CCDisplayManager.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCDisplayManager.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/CCBone.h rename to cocos/editor-support/cocostudio/CCBone.h index 85edc0f5b1..1163738515 100644 --- a/cocos/editor-support/cocostudio/armature/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -25,11 +25,11 @@ THE SOFTWARE. #ifndef __CCBONE_H__ #define __CCBONE_H__ -#include "utils/CCArmatureDefine.h" -#include "datas/CCDatas.h" -#include "animation/CCTween.h" -#include "display/CCDecorativeDisplay.h" -#include "display/CCDisplayManager.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" +#include "cocostudio/CCTween.h" +#include "cocostudio/CCDecorativeDisplay.h" +#include "cocostudio/CCDisplayManager.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp rename to cocos/editor-support/cocostudio/CCColliderDetector.cpp index f7e0c1c500..0839a30d7a 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -22,9 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCColliderDetector.h" -#include "cocostudio/armature/CCBone.h" -#include "cocostudio/armature/utils/CCTransformHelp.h" +#include "cocostudio/CCColliderDetector.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCTransformHelp.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" diff --git a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h rename to cocos/editor-support/cocostudio/CCColliderDetector.h index 5febb92aef..4f6fbeebfe 100644 --- a/cocos/editor-support/cocostudio/armature/physics/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCCOLLIDERDETECTOR_H__ #define __CCCOLLIDERDETECTOR_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" #ifndef PT_RATIO #define PT_RATIO 32 diff --git a/cocos/editor-support/cocostudio/components/CCComAttribute.cpp b/cocos/editor-support/cocostudio/CCComAttribute.cpp similarity index 99% rename from cocos/editor-support/cocostudio/components/CCComAttribute.cpp rename to cocos/editor-support/cocostudio/CCComAttribute.cpp index 5f73dfeacc..f3e57eddbc 100644 --- a/cocos/editor-support/cocostudio/components/CCComAttribute.cpp +++ b/cocos/editor-support/cocostudio/CCComAttribute.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCComAttribute.h" +#include "cocostudio/CCComAttribute.h" using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComAttribute.h b/cocos/editor-support/cocostudio/CCComAttribute.h similarity index 97% rename from cocos/editor-support/cocostudio/components/CCComAttribute.h rename to cocos/editor-support/cocostudio/CCComAttribute.h index 959e8ac1b8..53c7c2c885 100644 --- a/cocos/editor-support/cocostudio/components/CCComAttribute.h +++ b/cocos/editor-support/cocostudio/CCComAttribute.h @@ -27,7 +27,7 @@ THE SOFTWARE. #include "cocos2d.h" #include -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComAudio.cpp b/cocos/editor-support/cocostudio/CCComAudio.cpp similarity index 99% rename from cocos/editor-support/cocostudio/components/CCComAudio.cpp rename to cocos/editor-support/cocostudio/CCComAudio.cpp index 29fcc308f4..76ac167ba7 100644 --- a/cocos/editor-support/cocostudio/components/CCComAudio.cpp +++ b/cocos/editor-support/cocostudio/CCComAudio.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCComAudio.h" +#include "cocostudio/CCComAudio.h" #include "SimpleAudioEngine.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComAudio.h b/cocos/editor-support/cocostudio/CCComAudio.h similarity index 100% rename from cocos/editor-support/cocostudio/components/CCComAudio.h rename to cocos/editor-support/cocostudio/CCComAudio.h diff --git a/cocos/editor-support/cocostudio/components/CCComController.cpp b/cocos/editor-support/cocostudio/CCComController.cpp similarity index 97% rename from cocos/editor-support/cocostudio/components/CCComController.cpp rename to cocos/editor-support/cocostudio/CCComController.cpp index 8bc321a1de..bf57a8724a 100644 --- a/cocos/editor-support/cocostudio/components/CCComController.cpp +++ b/cocos/editor-support/cocostudio/CCComController.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCComController.h" +#include "cocostudio/CCComController.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComController.h b/cocos/editor-support/cocostudio/CCComController.h similarity index 97% rename from cocos/editor-support/cocostudio/components/CCComController.h rename to cocos/editor-support/cocostudio/CCComController.h index 8fcb1c8879..00da3fa74f 100644 --- a/cocos/editor-support/cocostudio/components/CCComController.h +++ b/cocos/editor-support/cocostudio/CCComController.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CC_EXTENTIONS_CCCOMCONTROLLER_H__ #include "cocos2d.h" -#include "CCInputDelegate.h" +#include "cocostudio/CCInputDelegate.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComRender.cpp b/cocos/editor-support/cocostudio/CCComRender.cpp similarity index 98% rename from cocos/editor-support/cocostudio/components/CCComRender.cpp rename to cocos/editor-support/cocostudio/CCComRender.cpp index bfd19a48ab..95465444ea 100644 --- a/cocos/editor-support/cocostudio/components/CCComRender.cpp +++ b/cocos/editor-support/cocostudio/CCComRender.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCComRender.h" +#include "cocostudio/CCComRender.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCComRender.h b/cocos/editor-support/cocostudio/CCComRender.h similarity index 100% rename from cocos/editor-support/cocostudio/components/CCComRender.h rename to cocos/editor-support/cocostudio/CCComRender.h diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp similarity index 99% rename from cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp rename to cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index d1dc3e0655..4749f5eaf9 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ #include "tinyxml2.h" -#include "CCDataReaderHelper.h" -#include "CCArmatureDataManager.h" -#include "CCTransformHelp.h" -#include "CCUtilMath.h" -#include "CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCDataReaderHelper.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h rename to cocos/editor-support/cocostudio/CCDataReaderHelper.h index be8b4c9297..d5c8a0d6f5 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -25,10 +25,10 @@ THE SOFTWARE. #ifndef __CCDATAREADERHELPER_H__ #define __CCDATAREADERHELPER_H__ -#include "CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" -#include "cocostudio/armature/CCArmature.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CSContentJsonDictionary.h" #include #include diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp b/cocos/editor-support/cocostudio/CCDatas.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp rename to cocos/editor-support/cocostudio/CCDatas.cpp index 6d2468cb58..35d6461efc 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.cpp +++ b/cocos/editor-support/cocostudio/CCDatas.cpp @@ -22,9 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCDatas.h" -#include "cocostudio/armature/utils/CCUtilMath.h" -#include "cocostudio/armature/utils/CCTransformHelp.h" +#include "cocostudio/CCDatas.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCTransformHelp.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h similarity index 99% rename from cocos/editor-support/cocostudio/armature/datas/CCDatas.h rename to cocos/editor-support/cocostudio/CCDatas.h index 2725750c84..26128020cf 100644 --- a/cocos/editor-support/cocostudio/armature/datas/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCARMATURE_DATAS_H__ #define __CCARMATURE_DATAS_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/utils/CCTweenFunction.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCTweenFunction.h" #define CC_CREATE_NO_PARAM_NO_INIT(varType)\ diff --git a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp rename to cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp index 0213219ddb..e595ecbe0c 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.cpp +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCDecorativeDisplay.h" +#include "cocostudio/CCDecorativeDisplay.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h similarity index 91% rename from cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h rename to cocos/editor-support/cocostudio/CCDecorativeDisplay.h index f65f143163..7196d0e9ec 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h @@ -25,13 +25,13 @@ THE SOFTWARE. #ifndef __CCDECORATIVEDISPLAY_H__ #define __CCDECORATIVEDISPLAY_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "CCDisplayFactory.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDisplayFactory.h" +#include "cocostudio/CCDatas.h" #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT -#include "../physics/CCColliderDetector.h" +#include "cocostudio/CCColliderDetector.h" #endif namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp similarity index 96% rename from cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp rename to cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 56e5f8c427..034f115481 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -22,13 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCDisplayFactory.h" -#include "cocostudio/armature/CCBone.h" -#include "cocostudio/armature/CCArmature.h" -#include "cocostudio/armature/display/CCSkin.h" -#include "cocostudio/armature/utils/CCSpriteFrameCacheHelper.h" -#include "cocostudio/armature/utils/CCArmatureDataManager.h" -#include "cocostudio/armature/utils/CCTransformHelp.h" +#include "cocostudio/CCDisplayFactory.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCSkin.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCTransformHelp.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h b/cocos/editor-support/cocostudio/CCDisplayFactory.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h rename to cocos/editor-support/cocostudio/CCDisplayFactory.h index f8f6009ffb..3ef0725ff0 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCDISPLAYFACTORY_H__ #define __CCDISPLAYFACTORY_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp rename to cocos/editor-support/cocostudio/CCDisplayManager.cpp index 29ae581cbb..b7d337e3a9 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -22,11 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCDisplayManager.h" -#include "cocostudio/armature/CCBone.h" -#include "cocostudio/armature/CCArmature.h" -#include "cocostudio/armature/utils/CCUtilMath.h" -#include "cocostudio/armature/display/CCSkin.h" +#include "cocostudio/CCDisplayManager.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCSkin.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h rename to cocos/editor-support/cocostudio/CCDisplayManager.h index fd51ca759b..9953d77995 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -25,9 +25,9 @@ THE SOFTWARE. #ifndef __CCDISPLAYMANAGER_H__ #define __CCDISPLAYMANAGER_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/display/CCDecorativeDisplay.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDecorativeDisplay.h" +#include "cocostudio/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp similarity index 99% rename from cocos/editor-support/cocostudio/components/CCInputDelegate.cpp rename to cocos/editor-support/cocostudio/CCInputDelegate.cpp index 65664400c7..9f4fd46a8d 100644 --- a/cocos/editor-support/cocostudio/components/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCInputDelegate.h" +#include "cocostudio/CCInputDelegate.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/components/CCInputDelegate.h b/cocos/editor-support/cocostudio/CCInputDelegate.h similarity index 100% rename from cocos/editor-support/cocostudio/components/CCInputDelegate.h rename to cocos/editor-support/cocostudio/CCInputDelegate.h diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp rename to cocos/editor-support/cocostudio/CCProcessBase.cpp index e235c1cb1e..c3e1bfbc20 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -22,8 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCProcessBase.h" -#include "cocostudio/armature/utils/CCUtilMath.h" +#include "cocostudio/CCProcessBase.h" +#include "cocostudio/CCUtilMath.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h similarity index 98% rename from cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h rename to cocos/editor-support/cocostudio/CCProcessBase.h index 3d247e51a4..9f80fb2ea7 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -26,8 +26,8 @@ THE SOFTWARE. #ifndef __CCPROCESSBASE_H__ #define __CCPROCESSBASE_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp similarity index 99% rename from cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp rename to cocos/editor-support/cocostudio/CCSGUIReader.cpp index ad0eb9ef8d..77cb5d56de 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -21,10 +21,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#include "system/CocosGUI.h" -#include "cocostudio/json/DictionaryHelper.h" -#include "cocostudio/action/CCActionManagerEx.h" +#include "cocostudio/CCSGUIReader.h" +#include "gui/CocosGUI.h" +#include "cocostudio/DictionaryHelper.h" +#include "cocostudio/CCActionManagerEx.h" #include #include diff --git a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h similarity index 97% rename from cocos/editor-support/cocostudio/reader/CCSGUIReader.h rename to cocos/editor-support/cocostudio/CCSGUIReader.h index 0041997bcd..d39c349ee0 100755 --- a/cocos/editor-support/cocostudio/reader/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/CCSGUIReader.h @@ -25,8 +25,8 @@ #ifndef __CCSGUIREADER_H__ #define __CCSGUIREADER_H__ -#include "base-classes/UIWidget.h" -#include "cocostudio/json/CSContentJsonDictionary.h" +#include "gui/UIWidget.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp similarity index 99% rename from cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp rename to cocos/editor-support/cocostudio/CCSSceneReader.cpp index a32572d791..3d8bc7fd8c 100644 --- a/cocos/editor-support/cocostudio/reader/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -22,9 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCSSceneReader.h" -#include "CocoStudio.h" -#include "system/CocosGUI.h" +#include "cocostudio/CocoStudio.h" +#include "gui/CocosGUI.h" using namespace cocos2d; using namespace gui; diff --git a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h similarity index 97% rename from cocos/editor-support/cocostudio/reader/CCSSceneReader.h rename to cocos/editor-support/cocostudio/CCSSceneReader.h index a042edfbf2..f548a2573f 100644 --- a/cocos/editor-support/cocostudio/reader/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -26,7 +26,7 @@ #define __CCSSCENEREADER_H__ #include "cocos2d.h" - #include "cocostudio/json/CSContentJsonDictionary.h" + #include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp similarity index 96% rename from cocos/editor-support/cocostudio/armature/display/CCSkin.cpp rename to cocos/editor-support/cocostudio/CCSkin.cpp index ecc83c7ff6..afd6f5fc51 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -22,10 +22,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCSkin.h" -#include "cocostudio/armature/utils/CCTransformHelp.h" -#include "cocostudio/armature/utils/CCSpriteFrameCacheHelper.h" -#include "cocostudio/armature/CCArmature.h" +#include "cocostudio/CCSkin.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCArmature.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/display/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h similarity index 95% rename from cocos/editor-support/cocostudio/armature/display/CCSkin.h rename to cocos/editor-support/cocostudio/CCSkin.h index 1915ff550b..3494c48436 100644 --- a/cocos/editor-support/cocostudio/armature/display/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCSKIN_H__ #define __CCSKIN_H__ -#include "cocostudio/armature/utils/CCArmatureDefine.h" -#include "cocostudio/armature/CCBone.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCBone.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp rename to cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index d17dab4fa2..d783c4ba4e 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h rename to cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 6e1a4fe094..150fe96aaa 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -24,7 +24,7 @@ THE SOFTWARE. #ifndef __CCSPRITEFRAMECACHEHELPER_H__ #define __CCSPRITEFRAMECACHEHELPER_H__ -#include "CCArmatureDefine.h" +#include "cocostudio/CCArmatureDefine.h" #include using namespace std; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp b/cocos/editor-support/cocostudio/CCTransformHelp.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp rename to cocos/editor-support/cocostudio/CCTransformHelp.cpp index 133dbba1d2..a836055c16 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.cpp +++ b/cocos/editor-support/cocostudio/CCTransformHelp.cpp @@ -22,8 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCTransformHelp.h" -#include "CCUtilMath.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCUtilMath.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h b/cocos/editor-support/cocostudio/CCTransformHelp.h similarity index 96% rename from cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h rename to cocos/editor-support/cocostudio/CCTransformHelp.h index 195d5a1468..ae1bcbf813 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTransformHelp.h +++ b/cocos/editor-support/cocostudio/CCTransformHelp.h @@ -25,8 +25,8 @@ THE SOFTWARE. #ifndef __CCTRANSFORMHELP_H__ #define __CCTRANSFORMHELP_H__ -#include "CCArmatureDefine.h" -#include "cocostudio/armature/datas/CCDatas.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDatas.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp similarity index 97% rename from cocos/editor-support/cocostudio/armature/animation/CCTween.cpp rename to cocos/editor-support/cocostudio/CCTween.cpp index c9ba8cbe6e..8fec95b2a0 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -23,13 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCTween.h" -#include "CCArmatureAnimation.h" -#include "cocostudio/armature/CCBone.h" -#include "cocostudio/armature/CCArmature.h" -#include "cocostudio/armature/utils/CCUtilMath.h" -#include "cocostudio/armature/utils/CCTweenFunction.h" -#include "cocostudio/armature/utils/CCTransformHelp.h" +#include "cocostudio/CCTween.h" +#include "cocostudio/CCArmatureAnimation.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCTweenFunction.h" +#include "cocostudio/CCTransformHelp.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/animation/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h similarity index 98% rename from cocos/editor-support/cocostudio/armature/animation/CCTween.h rename to cocos/editor-support/cocostudio/CCTween.h index f78e7ef927..80b6c6d7e9 100644 --- a/cocos/editor-support/cocostudio/armature/animation/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -26,8 +26,8 @@ THE SOFTWARE. #ifndef __CCTWEEN_H__ #define __CCTWEEN_H__ -#include "CCProcessBase.h" -#include "cocostudio/armature/utils/CCTweenFunction.h" +#include "cocostudio/CCProcessBase.h" +#include "cocostudio/CCTweenFunction.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp b/cocos/editor-support/cocostudio/CCTweenFunction.cpp similarity index 99% rename from cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp rename to cocos/editor-support/cocostudio/CCTweenFunction.cpp index 21b20e6f1a..37b523fc79 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.cpp +++ b/cocos/editor-support/cocostudio/CCTweenFunction.cpp @@ -22,8 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCTweenFunction.h" -#include "CCUtilMath.h" +#include "cocostudio/CCTweenFunction.h" +#include "cocostudio/CCUtilMath.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h b/cocos/editor-support/cocostudio/CCTweenFunction.h similarity index 99% rename from cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h rename to cocos/editor-support/cocostudio/CCTweenFunction.h index 0951bf1eea..255d19d58e 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCTweenFunction.h +++ b/cocos/editor-support/cocostudio/CCTweenFunction.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCTWEENFUNCTION_H__ -#include "CCArmatureDefine.h" +#include "cocostudio/CCArmatureDefine.h" #include namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp b/cocos/editor-support/cocostudio/CCUtilMath.cpp similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp rename to cocos/editor-support/cocostudio/CCUtilMath.cpp index c696e2a6fe..0714958857 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.cpp +++ b/cocos/editor-support/cocostudio/CCUtilMath.cpp @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCUtilMath.h" +#include "cocostudio/CCUtilMath.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h b/cocos/editor-support/cocostudio/CCUtilMath.h similarity index 98% rename from cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h rename to cocos/editor-support/cocostudio/CCUtilMath.h index b767cdcc58..20541a8c80 100644 --- a/cocos/editor-support/cocostudio/armature/utils/CCUtilMath.h +++ b/cocos/editor-support/cocostudio/CCUtilMath.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCUTILMATH_H__ #define __CCUTILMATH_H__ -#include "CCArmatureDefine.h" +#include "cocostudio/CCArmatureDefine.h" #include namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.cpp b/cocos/editor-support/cocostudio/CSContentJsonDictionary.cpp similarity index 99% rename from cocos/editor-support/cocostudio/json/CSContentJsonDictionary.cpp rename to cocos/editor-support/cocostudio/CSContentJsonDictionary.cpp index 287d742a1c..2f88410582 100644 --- a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.cpp +++ b/cocos/editor-support/cocostudio/CSContentJsonDictionary.cpp @@ -25,7 +25,7 @@ */ #include -#include "CSContentJsonDictionary.h" +#include "cocostudio/CSContentJsonDictionary.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h b/cocos/editor-support/cocostudio/CSContentJsonDictionary.h similarity index 100% rename from cocos/editor-support/cocostudio/json/CSContentJsonDictionary.h rename to cocos/editor-support/cocostudio/CSContentJsonDictionary.h diff --git a/cocos/editor-support/cocostudio/CocoStudio.h b/cocos/editor-support/cocostudio/CocoStudio.h index be6d9d807b..03c06775a6 100644 --- a/cocos/editor-support/cocostudio/CocoStudio.h +++ b/cocos/editor-support/cocostudio/CocoStudio.h @@ -25,38 +25,38 @@ #ifndef __EDITOR_SUPPORT_COCOSTUDIO_H__ #define __EDITOR_SUPPORT_COCOSTUDIO_H__ -#include "action/CCActionFrame.h" -#include "action/CCActionFrameEasing.h" -#include "action/CCActionManagerEx.h" -#include "action/CCActionNode.h" -#include "action/CCActionObject.h" -#include "armature/CCArmature.h" -#include "armature/CCBone.h" -#include "armature/animation/CCArmatureAnimation.h" -#include "armature/animation/CCProcessBase.h" -#include "armature/animation/CCTween.h" -#include "armature/datas/CCDatas.h" -#include "armature/display/CCBatchNode.h" -#include "armature/display/CCDecorativeDisplay.h" -#include "armature/display/CCDisplayFactory.h" -#include "armature/display/CCDisplayManager.h" -#include "armature/display/CCSkin.h" -#include "armature/physics/CCColliderDetector.h" -#include "armature/utils/CCArmatureDataManager.h" -#include "armature/utils/CCArmatureDefine.h" -#include "armature/utils/CCDataReaderHelper.h" -#include "armature/utils/CCSpriteFrameCacheHelper.h" -#include "armature/utils/CCTransformHelp.h" -#include "armature/utils/CCTweenFunction.h" -#include "armature/utils/CCUtilMath.h" -#include "components/CCComAttribute.h" -#include "components/CCComAudio.h" -#include "components/CCComController.h" -#include "components/CCComRender.h" -#include "components/CCInputDelegate.h" -#include "json/CSContentJsonDictionary.h" -#include "json/DictionaryHelper.h" -#include "reader/CCSGUIReader.h" -#include "reader/CCSSceneReader.h" +#include "cocostudio/CCActionFrame.h" +#include "cocostudio/CCActionFrameEasing.h" +#include "cocostudio/CCActionManagerEx.h" +#include "cocostudio/CCActionNode.h" +#include "cocostudio/CCActionObject.h" +#include "cocostudio/CCArmature.h" +#include "cocostudio/CCBone.h" +#include "cocostudio/CCArmatureAnimation.h" +#include "cocostudio/CCProcessBase.h" +#include "cocostudio/CCTween.h" +#include "cocostudio/CCDatas.h" +#include "cocostudio/CCBatchNode.h" +#include "cocostudio/CCDecorativeDisplay.h" +#include "cocostudio/CCDisplayFactory.h" +#include "cocostudio/CCDisplayManager.h" +#include "cocostudio/CCSkin.h" +#include "cocostudio/CCColliderDetector.h" +#include "cocostudio/CCArmatureDataManager.h" +#include "cocostudio/CCArmatureDefine.h" +#include "cocostudio/CCDataReaderHelper.h" +#include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "cocostudio/CCTransformHelp.h" +#include "cocostudio/CCTweenFunction.h" +#include "cocostudio/CCUtilMath.h" +#include "cocostudio/CCComAttribute.h" +#include "cocostudio/CCComAudio.h" +#include "cocostudio/CCComController.h" +#include "cocostudio/CCComRender.h" +#include "cocostudio/CCInputDelegate.h" +#include "cocostudio/CSContentJsonDictionary.h" +#include "cocostudio/DictionaryHelper.h" +#include "cocostudio/CCSGUIReader.h" +#include "cocostudio/CCSSceneReader.h" #endif diff --git a/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp b/cocos/editor-support/cocostudio/DictionaryHelper.cpp similarity index 99% rename from cocos/editor-support/cocostudio/json/DictionaryHelper.cpp rename to cocos/editor-support/cocostudio/DictionaryHelper.cpp index ab72de178e..48466eeb3e 100644 --- a/cocos/editor-support/cocostudio/json/DictionaryHelper.cpp +++ b/cocos/editor-support/cocostudio/DictionaryHelper.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "DictionaryHelper.h" +#include "cocostudio/DictionaryHelper.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/json/DictionaryHelper.h b/cocos/editor-support/cocostudio/DictionaryHelper.h similarity index 98% rename from cocos/editor-support/cocostudio/json/DictionaryHelper.h rename to cocos/editor-support/cocostudio/DictionaryHelper.h index e3f34e54ed..33aa5802ed 100644 --- a/cocos/editor-support/cocostudio/json/DictionaryHelper.h +++ b/cocos/editor-support/cocostudio/DictionaryHelper.h @@ -26,7 +26,7 @@ #define __DICTIONARYHELPER_H__ #include "cocos2d.h" -#include "CSContentJsonDictionary.h" +#include "cocostudio/CSContentJsonDictionary.h" #define DICTOOL DictionaryHelper::shareHelper() diff --git a/cocos/editor-support/cocostudio/json/.DS_Store b/cocos/editor-support/cocostudio/json/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplMac.h b/extensions/GUI/CCEditBox/CCEditBoxImplMac.h index 069aa13273..481472dba3 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplMac.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImplMac.h @@ -33,7 +33,7 @@ #import #import -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" #include "CCEditBoxImpl.h" @interface CCCustomNSTextField : NSTextField diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h b/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h index 84e1ae11f1..8395ecce71 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h @@ -31,7 +31,7 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN) -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" #include "CCEditBoxImpl.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplWin.h b/extensions/GUI/CCEditBox/CCEditBoxImplWin.h index 75d29c342e..2b379efe83 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplWin.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImplWin.h @@ -30,7 +30,7 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" #include "CCEditBoxImpl.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index cb03d57c08..5b002887ee 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -27,7 +27,7 @@ #define __CCSCROLLVIEW_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h index eca6fafc4a..7c182b193c 100644 --- a/extensions/GUI/CCScrollView/CCSorting.h +++ b/extensions/GUI/CCScrollView/CCSorting.h @@ -27,7 +27,7 @@ #define __CCSORTING_H__ #include "CCArray.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 7c1781b9b9..23e1a27774 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -30,7 +30,7 @@ #include #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/physics-nodes/CCPhysicsDebugNode.h b/extensions/physics-nodes/CCPhysicsDebugNode.h index 9f793c0a4f..fe4d167bff 100644 --- a/extensions/physics-nodes/CCPhysicsDebugNode.h +++ b/extensions/physics-nodes/CCPhysicsDebugNode.h @@ -24,7 +24,7 @@ #define __PHYSICSNODES_DEBUGNODE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" #if CC_ENABLE_CHIPMUNK_INTEGRATION diff --git a/extensions/physics-nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h index c21dd185da..1252af5919 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.h +++ b/extensions/physics-nodes/CCPhysicsSprite.h @@ -23,7 +23,7 @@ #define __PHYSICSNODES_CCPHYSICSSPRITE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" struct cpBody; class b2Body; diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 9ed6038242..bd0a8e37e6 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -7,137 +7,137 @@ LOCAL_MODULE := cocos_testcpp_common LOCAL_MODULE_FILENAME := libtestcppcommon LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/Classes/AppDelegate.cpp \ -$(LOCAL_PATH)/Classes/BaseTest.cpp \ -$(LOCAL_PATH)/Classes/controller.cpp \ -$(LOCAL_PATH)/Classes/testBasic.cpp \ -$(LOCAL_PATH)/Classes/VisibleRect.cpp \ -$(LOCAL_PATH)/Classes/AccelerometerTest/AccelerometerTest.cpp \ -$(LOCAL_PATH)/Classes/ActionManagerTest/ActionManagerTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsEaseTest/ActionsEaseTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsProgressTest/ActionsProgressTest.cpp \ -$(LOCAL_PATH)/Classes/ActionsTest/ActionsTest.cpp \ -$(LOCAL_PATH)/Classes/Box2DTest/Box2dTest.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/Box2dView.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/GLES-Render.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/Test.cpp \ -$(LOCAL_PATH)/Classes/Box2DTestBed/TestEntries.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-1159.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-1174.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-350.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-422.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-624.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-886.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-899.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-914.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/BugsTest.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-458/Bug-458.cpp \ -$(LOCAL_PATH)/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ -$(LOCAL_PATH)/Classes/ChipmunkTest/ChipmunkTest.cpp \ -$(LOCAL_PATH)/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ -$(LOCAL_PATH)/Classes/ClippingNodeTest/ClippingNodeTest.cpp \ -$(LOCAL_PATH)/Classes/CocosDenshionTest/CocosDenshionTest.cpp \ -$(LOCAL_PATH)/Classes/ConfigurationTest/ConfigurationTest.cpp \ -$(LOCAL_PATH)/Classes/CurlTest/CurlTest.cpp \ -$(LOCAL_PATH)/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ -$(LOCAL_PATH)/Classes/DataVisitorTest/DataVisitorTest.cpp \ -$(LOCAL_PATH)/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ -$(LOCAL_PATH)/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ -$(LOCAL_PATH)/Classes/EffectsTest/EffectsTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ExtensionsTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ -$(LOCAL_PATH)/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ -$(LOCAL_PATH)/Classes/FileUtilsTest/FileUtilsTest.cpp \ -$(LOCAL_PATH)/Classes/FontTest/FontTest.cpp \ -$(LOCAL_PATH)/Classes/IntervalTest/IntervalTest.cpp \ -$(LOCAL_PATH)/Classes/KeyboardTest/KeyboardTest.cpp \ -$(LOCAL_PATH)/Classes/KeypadTest/KeypadTest.cpp \ -$(LOCAL_PATH)/Classes/LabelTest/LabelTest.cpp \ -$(LOCAL_PATH)/Classes/LabelTest/LabelTestNew.cpp \ -$(LOCAL_PATH)/Classes/LayerTest/LayerTest.cpp \ -$(LOCAL_PATH)/Classes/MenuTest/MenuTest.cpp \ -$(LOCAL_PATH)/Classes/MotionStreakTest/MotionStreakTest.cpp \ -$(LOCAL_PATH)/Classes/MutiTouchTest/MutiTouchTest.cpp \ -$(LOCAL_PATH)/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ -$(LOCAL_PATH)/Classes/NodeTest/NodeTest.cpp \ -$(LOCAL_PATH)/Classes/ParallaxTest/ParallaxTest.cpp \ -$(LOCAL_PATH)/Classes/ParticleTest/ParticleTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceAllocTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceParticleTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceSpriteTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTextureTest.cpp \ -$(LOCAL_PATH)/Classes/PerformanceTest/PerformanceTouchesTest.cpp \ -$(LOCAL_PATH)/Classes/PhysicsTest/PhysicsTest.cpp \ -$(LOCAL_PATH)/Classes/RenderTextureTest/RenderTextureTest.cpp \ -$(LOCAL_PATH)/Classes/RotateWorldTest/RotateWorldTest.cpp \ -$(LOCAL_PATH)/Classes/SceneTest/SceneTest.cpp \ -$(LOCAL_PATH)/Classes/SchedulerTest/SchedulerTest.cpp \ -$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest.cpp \ -$(LOCAL_PATH)/Classes/ShaderTest/ShaderTest2.cpp \ -$(LOCAL_PATH)/Classes/SpineTest/SpineTest.cpp \ -$(LOCAL_PATH)/Classes/SpriteTest/SpriteTest.cpp \ -$(LOCAL_PATH)/Classes/TextInputTest/TextInputTest.cpp \ -$(LOCAL_PATH)/Classes/Texture2dTest/Texture2dTest.cpp \ -$(LOCAL_PATH)/Classes/TextureCacheTest/TextureCacheTest.cpp \ -$(LOCAL_PATH)/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ -$(LOCAL_PATH)/Classes/TileMapTest/TileMapTest.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/Ball.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/Paddle.cpp \ -$(LOCAL_PATH)/Classes/TouchesTest/TouchesTest.cpp \ -$(LOCAL_PATH)/Classes/TransitionsTest/TransitionsTest.cpp \ -$(LOCAL_PATH)/Classes/UserDefaultTest/UserDefaultTest.cpp \ -$(LOCAL_PATH)/Classes/ZwoptexTest/ZwoptexTest.cpp +Classes/AppDelegate.cpp \ +Classes/BaseTest.cpp \ +Classes/controller.cpp \ +Classes/testBasic.cpp \ +Classes/VisibleRect.cpp \ +Classes/AccelerometerTest/AccelerometerTest.cpp \ +Classes/ActionManagerTest/ActionManagerTest.cpp \ +Classes/ActionsEaseTest/ActionsEaseTest.cpp \ +Classes/ActionsProgressTest/ActionsProgressTest.cpp \ +Classes/ActionsTest/ActionsTest.cpp \ +Classes/Box2DTest/Box2dTest.cpp \ +Classes/Box2DTestBed/Box2dView.cpp \ +Classes/Box2DTestBed/GLES-Render.cpp \ +Classes/Box2DTestBed/Test.cpp \ +Classes/Box2DTestBed/TestEntries.cpp \ +Classes/BugsTest/Bug-1159.cpp \ +Classes/BugsTest/Bug-1174.cpp \ +Classes/BugsTest/Bug-350.cpp \ +Classes/BugsTest/Bug-422.cpp \ +Classes/BugsTest/Bug-624.cpp \ +Classes/BugsTest/Bug-886.cpp \ +Classes/BugsTest/Bug-899.cpp \ +Classes/BugsTest/Bug-914.cpp \ +Classes/BugsTest/BugsTest.cpp \ +Classes/BugsTest/Bug-458/Bug-458.cpp \ +Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp \ +Classes/ChipmunkTest/ChipmunkTest.cpp \ +Classes/ClickAndMoveTest/ClickAndMoveTest.cpp \ +Classes/ClippingNodeTest/ClippingNodeTest.cpp \ +Classes/CocosDenshionTest/CocosDenshionTest.cpp \ +Classes/ConfigurationTest/ConfigurationTest.cpp \ +Classes/CurlTest/CurlTest.cpp \ +Classes/CurrentLanguageTest/CurrentLanguageTest.cpp \ +Classes/DataVisitorTest/DataVisitorTest.cpp \ +Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp \ +Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp \ +Classes/EffectsTest/EffectsTest.cpp \ +Classes/ExtensionsTest/ExtensionsTest.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \ +Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp \ +Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp \ +Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp \ +Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp \ +Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp \ +Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp \ +Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ +Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ +Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp \ +Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp \ +Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp \ +Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp \ +Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ +Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ +Classes/FileUtilsTest/FileUtilsTest.cpp \ +Classes/FontTest/FontTest.cpp \ +Classes/IntervalTest/IntervalTest.cpp \ +Classes/KeyboardTest/KeyboardTest.cpp \ +Classes/KeypadTest/KeypadTest.cpp \ +Classes/LabelTest/LabelTest.cpp \ +Classes/LabelTest/LabelTestNew.cpp \ +Classes/LayerTest/LayerTest.cpp \ +Classes/MenuTest/MenuTest.cpp \ +Classes/MotionStreakTest/MotionStreakTest.cpp \ +Classes/MutiTouchTest/MutiTouchTest.cpp \ +Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ +Classes/NodeTest/NodeTest.cpp \ +Classes/ParallaxTest/ParallaxTest.cpp \ +Classes/ParticleTest/ParticleTest.cpp \ +Classes/PerformanceTest/PerformanceAllocTest.cpp \ +Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp \ +Classes/PerformanceTest/PerformanceParticleTest.cpp \ +Classes/PerformanceTest/PerformanceSpriteTest.cpp \ +Classes/PerformanceTest/PerformanceTest.cpp \ +Classes/PerformanceTest/PerformanceTextureTest.cpp \ +Classes/PerformanceTest/PerformanceTouchesTest.cpp \ +Classes/PhysicsTest/PhysicsTest.cpp \ +Classes/RenderTextureTest/RenderTextureTest.cpp \ +Classes/RotateWorldTest/RotateWorldTest.cpp \ +Classes/SceneTest/SceneTest.cpp \ +Classes/SchedulerTest/SchedulerTest.cpp \ +Classes/ShaderTest/ShaderTest.cpp \ +Classes/ShaderTest/ShaderTest2.cpp \ +Classes/SpineTest/SpineTest.cpp \ +Classes/SpriteTest/SpriteTest.cpp \ +Classes/TextInputTest/TextInputTest.cpp \ +Classes/Texture2dTest/Texture2dTest.cpp \ +Classes/TextureCacheTest/TextureCacheTest.cpp \ +Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ +Classes/TileMapTest/TileMapTest.cpp \ +Classes/TouchesTest/Ball.cpp \ +Classes/TouchesTest/Paddle.cpp \ +Classes/TouchesTest/TouchesTest.cpp \ +Classes/TransitionsTest/TransitionsTest.cpp \ +Classes/UserDefaultTest/UserDefaultTest.cpp \ +Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes @@ -153,7 +153,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static LOCAL_WHOLE_STATIC_LIBRARIES += network_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/Classes include $(BUILD_STATIC_LIBRARY) diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp index 515a63c9be..ddd7936152 100644 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp +++ b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp @@ -4,7 +4,7 @@ #include "controller.h" #include "SimpleAudioEngine.h" #include "cocostudio/CocoStudio.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC; using namespace CocosDenshion; diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index 8061e522f9..ca75a9efe3 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -1,6 +1,6 @@ #include "Box2dTest.h" #include "../testResource.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC_EXT; #define PTM_RATIO 32 diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h index 06fa3eb55a..33ae31cee7 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h @@ -7,7 +7,7 @@ #include "cocos2d.h" #include "chipmunk.h" #include "../testBasic.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp index f4ff8718a3..207a26a2ab 100644 --- a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp @@ -1,7 +1,7 @@ #include "CocosDenshionTest.h" #include "cocos2d.h" #include "SimpleAudioEngine.h" -#include "GUI/CCControlExtension/CCControlSlider.h" +#include "extensions/GUI/CCControlExtension/CCControlSlider.h" // android effect only support ogg #if (CC_TARGET_PLATFORM == CC_PLATFOR_ANDROID) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index f6001395c3..625fdddf88 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -2,7 +2,7 @@ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../../VisibleRect.h" #include "../../testBasic.h" #include "cocostudio/CocoStudio.h" diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h index edb704b8b1..152764c4bc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h @@ -2,7 +2,7 @@ #define __COMPONENTSTESTSCENE_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" void runComponentsTestLayerTest(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h index 31e3fc5f2d..0025fd6309 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h @@ -2,7 +2,7 @@ #define __CC_ENEMYCONTROLLER_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h index 9ce5b3b424..671bdf7833 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h @@ -2,7 +2,7 @@ #define __CC_PLAYERCONTROLLER_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h index de3c855c86..7ae6b71ab1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h @@ -2,7 +2,7 @@ #define __CC_PROJECTILECONTROLLER_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" class ProjectileController : public cocostudio::ComController diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h index f35b663126..4d6efe0c89 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h @@ -2,7 +2,7 @@ #define __CC_SceneController_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" class SceneController : public cocostudio::ComController diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h index 7e2ab4fd00..5bf2c93be1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h @@ -26,9 +26,9 @@ #define __TestCpp__CocosGUIScene__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../../testBasic.h" -#include "system/CocosGUI.h" +#include "gui/CocosGUI.h" using namespace cocos2d; using namespace cocos2d::extension; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp index e4bd80560f..4ac36f958d 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp @@ -1,7 +1,7 @@ #include "UINodeContainerTest.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" const char* font_UINodeContainerTest = #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index 3f3cf16873..a57787dfb1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -1,5 +1,5 @@ -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "UIScene.h" #include "UISceneManager.h" #include "../ExtensionsTest.h" diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h index 582964d66a..bf10ffa76b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h @@ -26,8 +26,8 @@ #define __TestCpp__UIScene__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "system/CocosGUI.h" +#include "extensions/cocos-ext.h" +#include "gui/CocosGUI.h" USING_NS_CC; USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index dbc04df6ef..0ce946c5a6 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -1,9 +1,9 @@ -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../ExtensionsTest.h" #include "SceneEditorTest.h" #include "cocostudio/CocoStudio.h" -#include "system/CocosGUI.h" +#include "gui/CocosGUI.h" using namespace cocos2d; using namespace cocostudio; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h index 186ce364f3..58494ee696 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h @@ -2,7 +2,7 @@ #define __SCENEEDITORTESTSCENE_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" void runSceneEditorTestLayer(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h index 2fbbd0f427..2ad6658306 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h @@ -2,7 +2,7 @@ #define _ANIMATIONSTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" class AnimationsTestLayer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h index 706ec6b2f7..1fa38a7e0c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h @@ -2,7 +2,7 @@ #define _BUTTONTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" class ButtonTestLayer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h index d6ab2071c4..15a19b5519 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h @@ -2,7 +2,7 @@ #define _HELLOCOCOSBUILDERLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" /* diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h index e92245029f..3cee0e0d46 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h @@ -2,7 +2,7 @@ #define _LABELTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class LabelTestLayer : public cocos2d::Layer { public: diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h index 11c12da610..36c256cf94 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h @@ -2,7 +2,7 @@ #define _MENUTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" class MenuTestLayer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h index 1f41f6e3fd..cf06eb3e87 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h @@ -2,7 +2,7 @@ #define _PARTICLESYSTEMTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class ParticleSystemTestLayer : public cocos2d::Layer { public: diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h index d2d5433fd4..e16039b3ca 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h @@ -2,7 +2,7 @@ #define _SCROLLVIEWTESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class ScrollViewTestLayer : public cocos2d::Layer { public: diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h index ef053be4d9..488a5c4da9 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h @@ -2,7 +2,7 @@ #define _SPRITETESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class SpriteTestLayer : public cocos2d::Layer { public: diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h index f36dea647e..6adde2aeda 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h @@ -2,7 +2,7 @@ #define _TESTHEADERLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" class TestHeaderLayer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h index 87cf80d7b6..f3d47ca84c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h @@ -2,7 +2,7 @@ #define _TIMELINE_TESTLAYER_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" class TimelineCallbackTestLayer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h index 1419606d23..7c5c6839a4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h @@ -24,7 +24,7 @@ */ #include "../CCControlScene.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h index 0d90639cfa..3ca532d095 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h @@ -27,7 +27,7 @@ #define __CCCONTROLSCENE_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h index b144555e3f..3eb912624a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h @@ -26,7 +26,7 @@ #define __CCCONTROLSCENEMANAGER_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h index 7d9e383bd7..640e359775 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h @@ -10,7 +10,7 @@ #define __TestCpp__CCEditBoxTest__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class EditBoxTest : public cocos2d::Layer, public cocos2d::extension::EditBoxDelegate { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h index ab432491dc..9f7d1d3fa3 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h @@ -2,8 +2,8 @@ #define __HTTP_CLIENT_H__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "HttpClient.h" +#include "extensions/cocos-ext.h" +#include "network/HttpClient.h" class HttpClientTest : public cocos2d::Layer { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h index 596738749c..56695bb6a4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h @@ -9,8 +9,8 @@ #define __TestCpp__SocketIOTest__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "SocketIO.h" +#include "extensions/cocos-ext.h" +#include "network/SocketIO.h" class SocketIOTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h index 7ca1080e40..fcec4ec724 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h @@ -10,8 +10,8 @@ #define __TestCpp__WebSocketTest__ #include "cocos2d.h" -#include "cocos-ext.h" -#include "WebSocket.h" +#include "extensions/cocos-ext.h" +#include "network/WebSocket.h" class WebSocketTestLayer : public cocos2d::Layer diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp index c5674a1443..ee0bfe043b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp @@ -28,7 +28,7 @@ #include "Scale9SpriteTest.h" #include "testResource.h" #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h index 16a8c74f25..2ee951ca73 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h @@ -2,7 +2,7 @@ #define __CUSTOMTABELVIEWCELL_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" class CustomTableViewCell : public cocos2d::extension::TableViewCell { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h index 7becc72781..a505195359 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -2,7 +2,7 @@ #define __TABLEVIEWTESTSCENE_H__ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" void runTableViewTest(); diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h index 383c3ee1ac..3e5ba3c9ac 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h @@ -2,7 +2,7 @@ #define _SCHEDULER_TEST_H_ #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../testBasic.h" #include "../BaseTest.h" diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h index 707793a1c5..33876c724a 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h @@ -2,7 +2,7 @@ #define _SHADER_TEST_H_ #include "../testBasic.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../BaseTest.h" USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h index 797b7a13ca..95ddbc592d 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h @@ -1,7 +1,7 @@ #ifndef _SHADER_TEST2_H_ #define _SHADER_TEST2_H_ #include "../testBasic.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "../BaseTest.h" USING_NS_CC_EXT; diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index b35170021f..4f7614f701 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -1,6 +1,6 @@ #include "testBasic.h" #include "controller.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" TestScene::TestScene(bool bPortrait) diff --git a/samples/Cpp/TestCpp/proj.android/jni/Android.mk b/samples/Cpp/TestCpp/proj.android/jni/Android.mk index c3190eef74..7867f3f1fb 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Android.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Android.mk @@ -8,7 +8,7 @@ LOCAL_MODULE_FILENAME := libtestcpp LOCAL_SRC_FILES := testcpp/main.cpp -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes +LOCAL_C_INCLUDES := ../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_testcpp_common diff --git a/samples/Lua/HelloLua/Classes/AppDelegate.cpp b/samples/Lua/HelloLua/Classes/AppDelegate.cpp index 1e2cef387a..d693936216 100644 --- a/samples/Lua/HelloLua/Classes/AppDelegate.cpp +++ b/samples/Lua/HelloLua/Classes/AppDelegate.cpp @@ -1,7 +1,7 @@ #include "cocos2d.h" #include "AppDelegate.h" #include "SimpleAudioEngine.h" -#include "script_support/CCScriptSupport.h" +#include "CCScriptSupport.h" #include "CCLuaEngine.h" USING_NS_CC; diff --git a/samples/Lua/HelloLua/proj.android/build_native.sh b/samples/Lua/HelloLua/proj.android/build_native.sh index 7a7144497f..47bf4396ad 100755 --- a/samples/Lua/HelloLua/proj.android/build_native.sh +++ b/samples/Lua/HelloLua/proj.android/build_native.sh @@ -108,9 +108,9 @@ done if [[ "$buildexternalsfromsource" ]]; then echo "Building external dependencies from source" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}" else echo "Using prebuilt externals" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}" fi diff --git a/samples/Lua/HelloLua/proj.android/jni/Android.mk b/samples/Lua/HelloLua/proj.android/jni/Android.mk index e4aa117413..09d83731fb 100644 --- a/samples/Lua/HelloLua/proj.android/jni/Android.mk +++ b/samples/Lua/HelloLua/proj.android/jni/Android.mk @@ -11,16 +11,9 @@ LOCAL_SRC_FILES := hellolua/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_lua_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_lua_static + include $(BUILD_SHARED_LIBRARY) -$(call import-module,cocos2dx) -$(call import-module,audio/android) $(call import-module,scripting/lua/proj.android) -$(call import-module,extensions) -$(call import-module,cocos2dx/platform/android) From 225738ecc5c43b6dca7552f3030f21313b59ea73 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 17:19:02 +0800 Subject: [PATCH 155/557] issue #2905: [iOS Mac] HelloLua and TestLua work now. --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/scripting/lua/bindings/CCBProxy.h | 3 +++ cocos/scripting/lua/bindings/CCLuaEngine.cpp | 4 ++-- cocos/scripting/lua/bindings/CCLuaEngine.h | 10 +++++----- cocos/scripting/lua/bindings/CCLuaStack.h | 2 +- cocos/scripting/lua/bindings/CCLuaValue.h | 2 +- cocos/scripting/lua/bindings/LuaOpengl.h | 3 ++- cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h | 4 ++-- cocos/scripting/lua/bindings/Lua_web_socket.cpp | 1 - cocos/scripting/lua/bindings/Lua_web_socket.h | 2 +- .../lua/bindings/lua_cocos2dx_extension_manual.cpp | 10 ++++++---- samples/Lua/HelloLua/Classes/AppDelegate.cpp | 2 +- 13 files changed, 26 insertions(+), 21 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 0e61b0c9e8..53dda14b9b 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c574341d56f31ced16553735ba34a697d1bbac02 \ No newline at end of file +97bf8ff69bab6a8a85dc80aca3938ca96cbfe2e5 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index cc5cbe86bf..ffe5f7bf0a 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -a4c6fec549057de458346127f489e6e6bea2f0d1 \ No newline at end of file +d25068403b84374432b0ddaec0ab9c1e3a38c4ec \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/CCBProxy.h b/cocos/scripting/lua/bindings/CCBProxy.h index 9759e87f1f..082bf09db1 100644 --- a/cocos/scripting/lua/bindings/CCBProxy.h +++ b/cocos/scripting/lua/bindings/CCBProxy.h @@ -5,9 +5,12 @@ #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" #include "cocos-ext.h" +#include "cocosbuilder/CocosBuilder.h" USING_NS_CC; USING_NS_CC_EXT; +using namespace cocosbuilder; + class CCBProxy : public Layer{ public: diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp index 21ded3f9b9..558b68acb1 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.cpp +++ b/cocos/scripting/lua/bindings/CCLuaEngine.cpp @@ -24,10 +24,10 @@ #include "CCLuaEngine.h" #include "cocos2d.h" -#include "cocoa/CCArray.h" +#include "CCArray.h" #include "CCScheduler.h" #include "LuaScriptHandlerMgr.h" -#include "GUI/CCControlExtension/CCControl.h" +#include "extensions/GUI/CCControlExtension/CCControl.h" #include "LuaOpengl.h" #include "lua_cocos2dx_extension_manual.h" diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.h b/cocos/scripting/lua/bindings/CCLuaEngine.h index 7df7f1fe02..0a1442aaaa 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.h +++ b/cocos/scripting/lua/bindings/CCLuaEngine.h @@ -30,11 +30,11 @@ extern "C" { } #include "ccTypes.h" -#include "cocoa/CCObject.h" -#include "event_dispatcher/CCTouch.h" -#include "cocoa/CCSet.h" -#include "base_nodes/CCNode.h" -#include "script_support/CCScriptSupport.h" +#include "CCObject.h" +#include "CCTouch.h" +#include "CCSet.h" +#include "CCNode.h" +#include "CCScriptSupport.h" #include "CCLuaStack.h" #include "CCLuaValue.h" diff --git a/cocos/scripting/lua/bindings/CCLuaStack.h b/cocos/scripting/lua/bindings/CCLuaStack.h index e6bb7077c9..dc066ac745 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.h +++ b/cocos/scripting/lua/bindings/CCLuaStack.h @@ -30,7 +30,7 @@ extern "C" { } #include "ccTypes.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "CCLuaValue.h" NS_CC_BEGIN diff --git a/cocos/scripting/lua/bindings/CCLuaValue.h b/cocos/scripting/lua/bindings/CCLuaValue.h index b25a498519..08cdc2544f 100644 --- a/cocos/scripting/lua/bindings/CCLuaValue.h +++ b/cocos/scripting/lua/bindings/CCLuaValue.h @@ -34,7 +34,7 @@ extern "C" { } #include "ccTypes.h" -#include "cocoa/CCObject.h" +#include "CCObject.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY using std::memset; diff --git a/cocos/scripting/lua/bindings/LuaOpengl.h b/cocos/scripting/lua/bindings/LuaOpengl.h index c72e000e83..d0e755a3a8 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.h +++ b/cocos/scripting/lua/bindings/LuaOpengl.h @@ -9,7 +9,8 @@ extern "C" { } #endif -#include "base_nodes/CCNode.h" +#include "CCNode.h" + class GLNode:public cocos2d::Node { virtual void draw(); diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h index efc1110c45..44ea6fa103 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h @@ -7,9 +7,9 @@ extern "C" { } -#include "cocoa/CCObject.h" +#include "CCObject.h" #include "ccMacros.h" -#include "actions/CCActionInstant.h" +#include "CCActionInstant.h" #include #include diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.cpp b/cocos/scripting/lua/bindings/Lua_web_socket.cpp index 27cb3ede7b..736c081344 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.cpp +++ b/cocos/scripting/lua/bindings/Lua_web_socket.cpp @@ -19,7 +19,6 @@ extern "C" { #include "LuaScriptHandlerMgr.h" using namespace cocos2d; -using namespace cocos2d::extension; static int SendBinaryMessageToLua(int nHandler,const unsigned char* pTable,int nLength) diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.h b/cocos/scripting/lua/bindings/Lua_web_socket.h index b51b84b1da..3754262deb 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.h +++ b/cocos/scripting/lua/bindings/Lua_web_socket.h @@ -12,7 +12,7 @@ extern "C" { #endif #include "network/WebSocket.h" -class LuaWebSocket: public cocos2d::extension::WebSocket,public cocos2d::extension::WebSocket::Delegate +class LuaWebSocket: public network::WebSocket,public network::WebSocket::Delegate { public: virtual ~LuaWebSocket(); diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index 0df1b74a13..0e4582b126 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -13,9 +13,11 @@ extern "C" { #include "CCLuaValue.h" #include "cocos-ext.h" #include "CCBProxy.h" +#include "cocostudio/CocoStudio.h" USING_NS_CC; USING_NS_CC_EXT; +using namespace cocostudio; class LuaScrollViewDelegate:public Object, public ScrollViewDelegate { @@ -1334,14 +1336,14 @@ static int lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData(lua_State* L) return 0; int argc = 0; - armature::Bone* self = nullptr; + cocostudio::Bone* self = nullptr; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; #endif - self = static_cast(tolua_tousertype(L,1,0)); + self = static_cast(tolua_tousertype(L,1,0)); #if COCOS2D_DEBUG >= 1 if (nullptr == self) { @@ -1379,14 +1381,14 @@ static int lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData(lua_State* L) return 0; int argc = 0; - armature::Bone* self = nullptr; + cocostudio::Bone* self = nullptr; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; #endif - self = static_cast(tolua_tousertype(L,1,0)); + self = static_cast(tolua_tousertype(L,1,0)); #if COCOS2D_DEBUG >= 1 if (nullptr == self) { diff --git a/samples/Lua/HelloLua/Classes/AppDelegate.cpp b/samples/Lua/HelloLua/Classes/AppDelegate.cpp index 1e2cef387a..d693936216 100644 --- a/samples/Lua/HelloLua/Classes/AppDelegate.cpp +++ b/samples/Lua/HelloLua/Classes/AppDelegate.cpp @@ -1,7 +1,7 @@ #include "cocos2d.h" #include "AppDelegate.h" #include "SimpleAudioEngine.h" -#include "script_support/CCScriptSupport.h" +#include "CCScriptSupport.h" #include "CCLuaEngine.h" USING_NS_CC; From b5233fc18df081bf20211a573b219cc9af7db682 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 17:27:30 +0800 Subject: [PATCH 156/557] issue #2905: [iOS Mac] Updating project configurations. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 53dda14b9b..944c4d9bef 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -97bf8ff69bab6a8a85dc80aca3938ca96cbfe2e5 \ No newline at end of file +81e5f8f3e9c025447f9dd4da9fba085d46f661d9 \ No newline at end of file From afe2b8e0c18c6b7e29dd563b6a14ec481bb07168 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 17:37:34 +0800 Subject: [PATCH 157/557] Update auto-generated submodule manually. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index ba1165bab0..73aebd082a 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit ba1165bab00a7ba34de057b28f272f31f50a303a +Subproject commit 73aebd082ae63561cc1ca769f28e302820da7e39 From 5ffe904a1b7be914b155366db7a70efbb7a1546a Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 16 Oct 2013 22:54:55 +0800 Subject: [PATCH 158/557] issue #2905: [iOS Mac] Updating template. --- .../HelloCpp.xcodeproj/project.pbxproj | 500 +++++++------ .../HelloJavascript.xcodeproj/project.pbxproj | 666 ++++++++++-------- 2 files changed, 608 insertions(+), 558 deletions(-) diff --git a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj index 3f7b3750a3..fdf23b3796 100644 --- a/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj +++ b/template/multi-platform-cpp/proj.ios_mac/HelloCpp.xcodeproj/project.pbxproj @@ -7,12 +7,16 @@ objects = { /* Begin PBXBuildFile section */ - 1ACB3244164770DE00914215 /* libcurl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ACB3243164770DE00914215 /* libcurl.a */; }; - 1AF4C2F417865DCB00122817 /* libbox2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2E317865D9500122817 /* libbox2d iOS.a */; }; - 1AF4C2F517865DCB00122817 /* libchipmunk iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2E117865D9500122817 /* libchipmunk iOS.a */; }; - 1AF4C2F617865DCB00122817 /* libcocos2dx iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2DD17865D9500122817 /* libcocos2dx iOS.a */; }; - 1AF4C2F717865DCB00122817 /* libcocos2dx-extensions iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2DF17865D9500122817 /* libcocos2dx-extensions iOS.a */; }; - 1AF4C2F817865DCB00122817 /* libCocosDenshion iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2E517865D9500122817 /* libCocosDenshion iOS.a */; }; + 1AC6FB1F180E996B004C840B /* libbox2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FAFF180E9839004C840B /* libbox2d Mac.a */; }; + 1AC6FB20180E996B004C840B /* libchipmunk Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FAFD180E9839004C840B /* libchipmunk Mac.a */; }; + 1AC6FB21180E996B004C840B /* libcocos2dx Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FAF9180E9839004C840B /* libcocos2dx Mac.a */; }; + 1AC6FB22180E996B004C840B /* libcocos2dx-extensions Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FAFB180E9839004C840B /* libcocos2dx-extensions Mac.a */; }; + 1AC6FB23180E996B004C840B /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB01180E9839004C840B /* libCocosDenshion Mac.a */; }; + 1AC6FB2E180E99EB004C840B /* libbox2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB0D180E9839004C840B /* libbox2d iOS.a */; }; + 1AC6FB2F180E99EB004C840B /* libchipmunk iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB0B180E9839004C840B /* libchipmunk iOS.a */; }; + 1AC6FB30180E99EB004C840B /* libcocos2dx iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB07180E9839004C840B /* libcocos2dx iOS.a */; }; + 1AC6FB31180E99EB004C840B /* libcocos2dx-extensions iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB09180E9839004C840B /* libcocos2dx-extensions iOS.a */; }; + 1AC6FB32180E99EB004C840B /* libCocosDenshion iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB0F180E9839004C840B /* libCocosDenshion iOS.a */; }; 1AFAF8B716D35DE700DB1158 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AFAF8B316D35DE700DB1158 /* AppDelegate.cpp */; }; 1AFAF8B816D35DE700DB1158 /* HelloWorldScene.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AFAF8B516D35DE700DB1158 /* HelloWorldScene.cpp */; }; 1AFAF8BC16D35E4900DB1158 /* CloseNormal.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AFAF8B916D35E4900DB1158 /* CloseNormal.png */; }; @@ -27,11 +31,6 @@ 503AE10217EB989F00D1A890 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503AE0FF17EB989F00D1A890 /* RootViewController.mm */; }; 503AE10517EB98FF00D1A890 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503AE10317EB98FF00D1A890 /* main.cpp */; }; 503AE11217EB99EE00D1A890 /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 503AE11117EB99EE00D1A890 /* libcurl.dylib */; }; - 503AE11317EB9C0700D1A890 /* libbox2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2D517865D9500122817 /* libbox2d Mac.a */; }; - 503AE11417EB9C0700D1A890 /* libchipmunk Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2D317865D9500122817 /* libchipmunk Mac.a */; }; - 503AE11517EB9C0700D1A890 /* libcocos2dx Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2CF17865D9500122817 /* libcocos2dx Mac.a */; }; - 503AE11617EB9C0700D1A890 /* libcocos2dx-extensions Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2D117865D9500122817 /* libcocos2dx-extensions Mac.a */; }; - 503AE11717EB9C0700D1A890 /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C2D717865D9500122817 /* libCocosDenshion Mac.a */; }; 503AE11B17EB9C5A00D1A890 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 503AE11A17EB9C5A00D1A890 /* IOKit.framework */; }; 5087E75317EB910900C73F5D /* CloseNormal.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AFAF8B916D35E4900DB1158 /* CloseNormal.png */; }; 5087E75417EB910900C73F5D /* CloseSelected.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AFAF8BA16D35E4900DB1158 /* CloseSelected.png */; }; @@ -73,179 +72,179 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 1AF4C2CE17865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FAF8180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1551A33F158F2AB200E66CFE; remoteInfo = "cocos2dx Mac"; }; - 1AF4C2D017865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FAFA180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2FD617814595006731B9; remoteInfo = "cocos2dx-extensions Mac"; }; - 1AF4C2D217865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FAFC180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2CB81780BD04006731B9; remoteInfo = "chipmunk Mac"; }; - 1AF4C2D417865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FAFE180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2D9B1780BDF7006731B9; remoteInfo = "box2d Mac"; }; - 1AF4C2D617865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB00180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2ED617814268006731B9; remoteInfo = "CocosDenshion Mac"; }; - 1AF4C2D817865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB02180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F31FD1781479B006731B9; remoteInfo = "jsbindings Mac"; }; - 1AF4C2DA17865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB04180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1A6FB53017854BC300CDF010; remoteInfo = "luabindings Mac"; }; - 1AF4C2DC17865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB06180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4D641783777C0073F6A7; remoteInfo = "cocos2dx iOS"; }; - 1AF4C2DE17865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB08180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4EFC1783867C0073F6A7; remoteInfo = "cocos2dx-extensions iOS"; }; - 1AF4C2E017865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB0A180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4F3B178387670073F6A7; remoteInfo = "chipmunk iOS"; }; - 1AF4C2E217865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB0C180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4F9E1783876B0073F6A7; remoteInfo = "box2d iOS"; }; - 1AF4C2E417865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB0E180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4FB4178387730073F6A7; remoteInfo = "CocosDenshion iOS"; }; - 1AF4C2E617865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB10180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A5030178387750073F6A7; remoteInfo = "jsbindings iOS"; }; - 1AF4C2E817865D9500122817 /* PBXContainerItemProxy */ = { + 1AC6FB12180E9839004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1A119791178526AA00D62A44; remoteInfo = "luabindings iOS"; }; - 1AF4C2EA17865DB400122817 /* PBXContainerItemProxy */ = { + 1AC6FB15180E9959004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4C241783777C0073F6A7; - remoteInfo = "cocos2dx iOS"; - }; - 1AF4C2EC17865DB400122817 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4E111783867C0073F6A7; - remoteInfo = "cocos2dx-extensions iOS"; - }; - 1AF4C2EE17865DB400122817 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4EFD178387670073F6A7; - remoteInfo = "chipmunk iOS"; - }; - 1AF4C2F017865DB400122817 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4F3C1783876B0073F6A7; - remoteInfo = "box2d iOS"; - }; - 1AF4C2F217865DB400122817 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4F9F178387730073F6A7; - remoteInfo = "CocosDenshion iOS"; - }; - 503AE10717EB99BC00D1A890 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 1; remoteGlobalIDString = 1551A33E158F2AB200E66CFE; remoteInfo = "cocos2dx Mac"; }; - 503AE10917EB99BC00D1A890 /* PBXContainerItemProxy */ = { + 1AC6FB17180E9959004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 1; remoteGlobalIDString = A03F2FC117814595006731B9; remoteInfo = "cocos2dx-extensions Mac"; }; - 503AE10B17EB99BC00D1A890 /* PBXContainerItemProxy */ = { + 1AC6FB19180E9959004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 1; remoteGlobalIDString = A03F2B781780BD04006731B9; remoteInfo = "chipmunk Mac"; }; - 503AE10D17EB99BC00D1A890 /* PBXContainerItemProxy */ = { + 1AC6FB1B180E9959004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A03F2D5D1780BDF7006731B9; - remoteInfo = "box2d Mac"; - }; - 503AE10F17EB99BC00D1A890 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; proxyType = 1; remoteGlobalIDString = A03F2E9817814268006731B9; remoteInfo = "CocosDenshion Mac"; }; + 1AC6FB1D180E9963004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F2D5D1780BDF7006731B9; + remoteInfo = "box2d Mac"; + }; + 1AC6FB24180E99E1004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4C241783777C0073F6A7; + remoteInfo = "cocos2dx iOS"; + }; + 1AC6FB26180E99E1004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4E111783867C0073F6A7; + remoteInfo = "cocos2dx-extensions iOS"; + }; + 1AC6FB28180E99E1004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4EFD178387670073F6A7; + remoteInfo = "chipmunk iOS"; + }; + 1AC6FB2A180E99E1004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4F3C1783876B0073F6A7; + remoteInfo = "box2d iOS"; + }; + 1AC6FB2C180E99E1004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4F9F178387730073F6A7; + remoteInfo = "CocosDenshion iOS"; + }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = ../../../build/cocos2d_libs.xcodeproj; sourceTree = ""; }; 1ACB3243164770DE00914215 /* libcurl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcurl.a; path = ../../cocos2dx/platform/third_party/ios/libraries/libcurl.a; sourceTree = ""; }; - 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = ../../../cocos2d_libs.xcodeproj; sourceTree = ""; }; 1AFAF8B316D35DE700DB1158 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AppDelegate.cpp; path = ../Classes/AppDelegate.cpp; sourceTree = ""; }; 1AFAF8B416D35DE700DB1158 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ../Classes/AppDelegate.h; sourceTree = ""; }; 1AFAF8B516D35DE700DB1158 /* HelloWorldScene.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = HelloWorldScene.cpp; path = ../Classes/HelloWorldScene.cpp; sourceTree = ""; }; @@ -303,13 +302,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 1AC6FB2E180E99EB004C840B /* libbox2d iOS.a in Frameworks */, + 1AC6FB2F180E99EB004C840B /* libchipmunk iOS.a in Frameworks */, + 1AC6FB30180E99EB004C840B /* libcocos2dx iOS.a in Frameworks */, + 1AC6FB31180E99EB004C840B /* libcocos2dx-extensions iOS.a in Frameworks */, + 1AC6FB32180E99EB004C840B /* libCocosDenshion iOS.a in Frameworks */, D6B0611B1803AB670077942B /* CoreMotion.framework in Frameworks */, - 1AF4C2F417865DCB00122817 /* libbox2d iOS.a in Frameworks */, - 1AF4C2F517865DCB00122817 /* libchipmunk iOS.a in Frameworks */, - 1AF4C2F617865DCB00122817 /* libcocos2dx iOS.a in Frameworks */, - 1AF4C2F717865DCB00122817 /* libcocos2dx-extensions iOS.a in Frameworks */, - 1AF4C2F817865DCB00122817 /* libCocosDenshion iOS.a in Frameworks */, - 1ACB3244164770DE00914215 /* libcurl.a in Frameworks */, 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, @@ -326,11 +324,11 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 503AE11317EB9C0700D1A890 /* libbox2d Mac.a in Frameworks */, - 503AE11417EB9C0700D1A890 /* libchipmunk Mac.a in Frameworks */, - 503AE11517EB9C0700D1A890 /* libcocos2dx Mac.a in Frameworks */, - 503AE11617EB9C0700D1A890 /* libcocos2dx-extensions Mac.a in Frameworks */, - 503AE11717EB9C0700D1A890 /* libCocosDenshion Mac.a in Frameworks */, + 1AC6FB1F180E996B004C840B /* libbox2d Mac.a in Frameworks */, + 1AC6FB20180E996B004C840B /* libchipmunk Mac.a in Frameworks */, + 1AC6FB21180E996B004C840B /* libcocos2dx Mac.a in Frameworks */, + 1AC6FB22180E996B004C840B /* libcocos2dx-extensions Mac.a in Frameworks */, + 1AC6FB23180E996B004C840B /* libCocosDenshion Mac.a in Frameworks */, 503AE11217EB99EE00D1A890 /* libcurl.dylib in Frameworks */, 5087E76717EB910900C73F5D /* libz.dylib in Frameworks */, 503AE11B17EB9C5A00D1A890 /* IOKit.framework in Frameworks */, @@ -384,23 +382,23 @@ name = Products; sourceTree = ""; }; - 1AF4C2BC17865D9500122817 /* Products */ = { + 1AC6FAE6180E9839004C840B /* Products */ = { isa = PBXGroup; children = ( - 1AF4C2CF17865D9500122817 /* libcocos2dx Mac.a */, - 1AF4C2D117865D9500122817 /* libcocos2dx-extensions Mac.a */, - 1AF4C2D317865D9500122817 /* libchipmunk Mac.a */, - 1AF4C2D517865D9500122817 /* libbox2d Mac.a */, - 1AF4C2D717865D9500122817 /* libCocosDenshion Mac.a */, - 1AF4C2D917865D9500122817 /* libjsbindings Mac.a */, - 1AF4C2DB17865D9500122817 /* libluabindings Mac.a */, - 1AF4C2DD17865D9500122817 /* libcocos2dx iOS.a */, - 1AF4C2DF17865D9500122817 /* libcocos2dx-extensions iOS.a */, - 1AF4C2E117865D9500122817 /* libchipmunk iOS.a */, - 1AF4C2E317865D9500122817 /* libbox2d iOS.a */, - 1AF4C2E517865D9500122817 /* libCocosDenshion iOS.a */, - 1AF4C2E717865D9500122817 /* libjsbindings iOS.a */, - 1AF4C2E917865D9500122817 /* libluabindings iOS.a */, + 1AC6FAF9180E9839004C840B /* libcocos2dx Mac.a */, + 1AC6FAFB180E9839004C840B /* libcocos2dx-extensions Mac.a */, + 1AC6FAFD180E9839004C840B /* libchipmunk Mac.a */, + 1AC6FAFF180E9839004C840B /* libbox2d Mac.a */, + 1AC6FB01180E9839004C840B /* libCocosDenshion Mac.a */, + 1AC6FB03180E9839004C840B /* libjsbindings Mac.a */, + 1AC6FB05180E9839004C840B /* libluabindings Mac.a */, + 1AC6FB07180E9839004C840B /* libcocos2dx iOS.a */, + 1AC6FB09180E9839004C840B /* libcocos2dx-extensions iOS.a */, + 1AC6FB0B180E9839004C840B /* libchipmunk iOS.a */, + 1AC6FB0D180E9839004C840B /* libbox2d iOS.a */, + 1AC6FB0F180E9839004C840B /* libCocosDenshion iOS.a */, + 1AC6FB11180E9839004C840B /* libjsbindings iOS.a */, + 1AC6FB13180E9839004C840B /* libluabindings iOS.a */, ); name = Products; sourceTree = ""; @@ -408,7 +406,7 @@ 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { isa = PBXGroup; children = ( - 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */, + 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */, 15AA9C4015B7EC450033D6C2 /* Classes */, 29B97323FDCFA39411CA2CEA /* Frameworks */, 080E96DDFE201D6D7F000001 /* ios */, @@ -511,11 +509,11 @@ buildRules = ( ); dependencies = ( - 1AF4C2EB17865DB400122817 /* PBXTargetDependency */, - 1AF4C2ED17865DB400122817 /* PBXTargetDependency */, - 1AF4C2EF17865DB400122817 /* PBXTargetDependency */, - 1AF4C2F117865DB400122817 /* PBXTargetDependency */, - 1AF4C2F317865DB400122817 /* PBXTargetDependency */, + 1AC6FB25180E99E1004C840B /* PBXTargetDependency */, + 1AC6FB27180E99E1004C840B /* PBXTargetDependency */, + 1AC6FB29180E99E1004C840B /* PBXTargetDependency */, + 1AC6FB2B180E99E1004C840B /* PBXTargetDependency */, + 1AC6FB2D180E99E1004C840B /* PBXTargetDependency */, ); name = "HelloCpp iOS"; productName = iphone; @@ -533,11 +531,11 @@ buildRules = ( ); dependencies = ( - 503AE10817EB99BC00D1A890 /* PBXTargetDependency */, - 503AE10A17EB99BC00D1A890 /* PBXTargetDependency */, - 503AE10C17EB99BC00D1A890 /* PBXTargetDependency */, - 503AE10E17EB99BC00D1A890 /* PBXTargetDependency */, - 503AE11017EB99BC00D1A890 /* PBXTargetDependency */, + 1AC6FB1E180E9963004C840B /* PBXTargetDependency */, + 1AC6FB16180E9959004C840B /* PBXTargetDependency */, + 1AC6FB18180E9959004C840B /* PBXTargetDependency */, + 1AC6FB1A180E9959004C840B /* PBXTargetDependency */, + 1AC6FB1C180E9959004C840B /* PBXTargetDependency */, ); name = "HelloCpp Mac"; productName = iphone; @@ -571,8 +569,8 @@ projectDirPath = ""; projectReferences = ( { - ProductGroup = 1AF4C2BC17865D9500122817 /* Products */; - ProjectRef = 1AF4C2BB17865D9500122817 /* cocos2d_libs.xcodeproj */; + ProductGroup = 1AC6FAE6180E9839004C840B /* Products */; + ProjectRef = 1AC6FAE5180E9839004C840B /* cocos2d_libs.xcodeproj */; }, ); projectRoot = ""; @@ -584,102 +582,102 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ - 1AF4C2CF17865D9500122817 /* libcocos2dx Mac.a */ = { + 1AC6FAF9180E9839004C840B /* libcocos2dx Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx Mac.a"; - remoteRef = 1AF4C2CE17865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FAF8180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2D117865D9500122817 /* libcocos2dx-extensions Mac.a */ = { + 1AC6FAFB180E9839004C840B /* libcocos2dx-extensions Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx-extensions Mac.a"; - remoteRef = 1AF4C2D017865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FAFA180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2D317865D9500122817 /* libchipmunk Mac.a */ = { + 1AC6FAFD180E9839004C840B /* libchipmunk Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libchipmunk Mac.a"; - remoteRef = 1AF4C2D217865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FAFC180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2D517865D9500122817 /* libbox2d Mac.a */ = { + 1AC6FAFF180E9839004C840B /* libbox2d Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libbox2d Mac.a"; - remoteRef = 1AF4C2D417865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FAFE180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2D717865D9500122817 /* libCocosDenshion Mac.a */ = { + 1AC6FB01180E9839004C840B /* libCocosDenshion Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libCocosDenshion Mac.a"; - remoteRef = 1AF4C2D617865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB00180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2D917865D9500122817 /* libjsbindings Mac.a */ = { + 1AC6FB03180E9839004C840B /* libjsbindings Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libjsbindings Mac.a"; - remoteRef = 1AF4C2D817865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB02180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2DB17865D9500122817 /* libluabindings Mac.a */ = { + 1AC6FB05180E9839004C840B /* libluabindings Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libluabindings Mac.a"; - remoteRef = 1AF4C2DA17865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB04180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2DD17865D9500122817 /* libcocos2dx iOS.a */ = { + 1AC6FB07180E9839004C840B /* libcocos2dx iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx iOS.a"; - remoteRef = 1AF4C2DC17865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB06180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2DF17865D9500122817 /* libcocos2dx-extensions iOS.a */ = { + 1AC6FB09180E9839004C840B /* libcocos2dx-extensions iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx-extensions iOS.a"; - remoteRef = 1AF4C2DE17865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB08180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2E117865D9500122817 /* libchipmunk iOS.a */ = { + 1AC6FB0B180E9839004C840B /* libchipmunk iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libchipmunk iOS.a"; - remoteRef = 1AF4C2E017865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB0A180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2E317865D9500122817 /* libbox2d iOS.a */ = { + 1AC6FB0D180E9839004C840B /* libbox2d iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libbox2d iOS.a"; - remoteRef = 1AF4C2E217865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB0C180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2E517865D9500122817 /* libCocosDenshion iOS.a */ = { + 1AC6FB0F180E9839004C840B /* libCocosDenshion iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libCocosDenshion iOS.a"; - remoteRef = 1AF4C2E417865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB0E180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2E717865D9500122817 /* libjsbindings iOS.a */ = { + 1AC6FB11180E9839004C840B /* libjsbindings iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libjsbindings iOS.a"; - remoteRef = 1AF4C2E617865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB10180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C2E917865D9500122817 /* libluabindings iOS.a */ = { + 1AC6FB13180E9839004C840B /* libluabindings iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libluabindings iOS.a"; - remoteRef = 1AF4C2E817865D9500122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB12180E9839004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ @@ -750,55 +748,55 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 1AF4C2EB17865DB400122817 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "cocos2dx iOS"; - targetProxy = 1AF4C2EA17865DB400122817 /* PBXContainerItemProxy */; - }; - 1AF4C2ED17865DB400122817 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "cocos2dx-extensions iOS"; - targetProxy = 1AF4C2EC17865DB400122817 /* PBXContainerItemProxy */; - }; - 1AF4C2EF17865DB400122817 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "chipmunk iOS"; - targetProxy = 1AF4C2EE17865DB400122817 /* PBXContainerItemProxy */; - }; - 1AF4C2F117865DB400122817 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "box2d iOS"; - targetProxy = 1AF4C2F017865DB400122817 /* PBXContainerItemProxy */; - }; - 1AF4C2F317865DB400122817 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "CocosDenshion iOS"; - targetProxy = 1AF4C2F217865DB400122817 /* PBXContainerItemProxy */; - }; - 503AE10817EB99BC00D1A890 /* PBXTargetDependency */ = { + 1AC6FB16180E9959004C840B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "cocos2dx Mac"; - targetProxy = 503AE10717EB99BC00D1A890 /* PBXContainerItemProxy */; + targetProxy = 1AC6FB15180E9959004C840B /* PBXContainerItemProxy */; }; - 503AE10A17EB99BC00D1A890 /* PBXTargetDependency */ = { + 1AC6FB18180E9959004C840B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "cocos2dx-extensions Mac"; - targetProxy = 503AE10917EB99BC00D1A890 /* PBXContainerItemProxy */; + targetProxy = 1AC6FB17180E9959004C840B /* PBXContainerItemProxy */; }; - 503AE10C17EB99BC00D1A890 /* PBXTargetDependency */ = { + 1AC6FB1A180E9959004C840B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "chipmunk Mac"; - targetProxy = 503AE10B17EB99BC00D1A890 /* PBXContainerItemProxy */; + targetProxy = 1AC6FB19180E9959004C840B /* PBXContainerItemProxy */; }; - 503AE10E17EB99BC00D1A890 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "box2d Mac"; - targetProxy = 503AE10D17EB99BC00D1A890 /* PBXContainerItemProxy */; - }; - 503AE11017EB99BC00D1A890 /* PBXTargetDependency */ = { + 1AC6FB1C180E9959004C840B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "CocosDenshion Mac"; - targetProxy = 503AE10F17EB99BC00D1A890 /* PBXContainerItemProxy */; + targetProxy = 1AC6FB1B180E9959004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB1E180E9963004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "box2d Mac"; + targetProxy = 1AC6FB1D180E9963004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB25180E99E1004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "cocos2dx iOS"; + targetProxy = 1AC6FB24180E99E1004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB27180E99E1004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "cocos2dx-extensions iOS"; + targetProxy = 1AC6FB26180E99E1004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB29180E99E1004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "chipmunk iOS"; + targetProxy = 1AC6FB28180E99E1004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB2B180E99E1004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "box2d iOS"; + targetProxy = 1AC6FB2A180E99E1004C840B /* PBXContainerItemProxy */; + }; + 1AC6FB2D180E99E1004C840B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "CocosDenshion iOS"; + targetProxy = 1AC6FB2C180E99E1004C840B /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -806,7 +804,7 @@ 1D6058940D05DD3E006BFB54 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COMPRESS_PNG_FILES = NO; GCC_DYNAMIC_NO_PIC = NO; @@ -821,24 +819,13 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../audio/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios/Simulation\"", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/ios", + "$(SRCROOT)/../../../cocos/2d/platform/ios/Simulation", ); INFOPLIST_FILE = ios/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/lib\"", - ); + LIBRARY_SEARCH_PATHS = ""; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; USER_HEADER_SEARCH_PATHS = ""; @@ -848,7 +835,7 @@ 1D6058950D05DD3E006BFB54 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COMPRESS_PNG_FILES = NO; GCC_INLINES_ARE_PRIVATE_EXTERN = NO; @@ -861,24 +848,13 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../audio/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/ios/Simulation\"", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/ios", + "$(SRCROOT)/../../../cocos/2d/platform/ios/Simulation", ); INFOPLIST_FILE = ios/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/lib\"", - ); + LIBRARY_SEARCH_PATHS = ""; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; USER_HEADER_SEARCH_PATHS = ""; @@ -888,7 +864,7 @@ 5087E76D17EB910900C73F5D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; ARCHS = "$(ARCHS_STANDARD_64_BIT)"; CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -904,22 +880,12 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/mac\"", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/mac", + "$(SRCROOT)/../../../external/glfw3/include/mac", ); INFOPLIST_FILE = mac/Info.plist; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/mac/lib\"", - ); + LIBRARY_SEARCH_PATHS = ""; USER_HEADER_SEARCH_PATHS = ""; }; name = Debug; @@ -927,7 +893,7 @@ 5087E76E17EB910900C73F5D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; ARCHS = "$(ARCHS_STANDARD_64_BIT)"; CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -941,22 +907,12 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../../CocosDenshion/include", - "\"$(SRCROOT)/../../../external/chipmunk/include/constraints\"", - "\"$(SRCROOT)/../../../external/chipmunk/include/chipmunk\"", - "\"$(SRCROOT)/../../../extensions\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "\"$(SRCROOT)/../../../external\"", - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/include\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/mac\"", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/mac", + "$(SRCROOT)/../../../external/glfw3/include/mac", ); INFOPLIST_FILE = mac/Info.plist; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/mac/lib\"", - ); + LIBRARY_SEARCH_PATHS = ""; USER_HEADER_SEARCH_PATHS = ""; }; name = Release; @@ -970,6 +926,21 @@ GCC_OPTIMIZATION_LEVEL = 0; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(SRCROOT)/../../..", + "$(SRCROOT)/../../../cocos", + "$(SRCROOT)/../../../cocos/base", + "$(SRCROOT)/../../../cocos/physics", + "$(SRCROOT)/../../../cocos/math/kazmath/include", + "$(SRCROOT)/../../../cocos/2d", + "$(SRCROOT)/../../../cocos/gui", + "$(SRCROOT)/../../../cocos/network", + "$(SRCROOT)/../../../cocos/audio/include", + "$(SRCROOT)/../../../cocos/editor-support", + "$(SRCROOT)/../../../extensions", + "$(SRCROOT)/../../../external", + "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", + ); ONLY_ACTIVE_ARCH = YES; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -983,6 +954,21 @@ CLANG_CXX_LIBRARY = "libc++"; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(SRCROOT)/../../..", + "$(SRCROOT)/../../../cocos", + "$(SRCROOT)/../../../cocos/base", + "$(SRCROOT)/../../../cocos/physics", + "$(SRCROOT)/../../../cocos/math/kazmath/include", + "$(SRCROOT)/../../../cocos/2d", + "$(SRCROOT)/../../../cocos/gui", + "$(SRCROOT)/../../../cocos/network", + "$(SRCROOT)/../../../cocos/audio/include", + "$(SRCROOT)/../../../cocos/editor-support", + "$(SRCROOT)/../../../extensions", + "$(SRCROOT)/../../../external", + "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", + ); OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; diff --git a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index dbc340d66f..82228bc55f 100644 --- a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -7,35 +7,47 @@ objects = { /* Begin PBXBuildFile section */ + 1A6767FA180E9B160076BC67 /* debugger in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767ED180E9B160076BC67 /* debugger */; }; + 1A6767FB180E9B160076BC67 /* debugger in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767ED180E9B160076BC67 /* debugger */; }; + 1A676829180E9C060076BC67 /* libchipmunk Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB4C180E9ACB004C840B /* libchipmunk Mac.a */; }; + 1A67682A180E9C060076BC67 /* libcocos2dx Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB48180E9ACB004C840B /* libcocos2dx Mac.a */; }; + 1A67682B180E9C060076BC67 /* libcocos2dx-extensions Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB4A180E9ACB004C840B /* libcocos2dx-extensions Mac.a */; }; + 1A67682C180E9C060076BC67 /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB50180E9ACB004C840B /* libCocosDenshion Mac.a */; }; + 1A67682D180E9C060076BC67 /* libjsbindings Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB52180E9ACB004C840B /* libjsbindings Mac.a */; }; + 1A676838180E9C1E0076BC67 /* libchipmunk iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB5A180E9ACB004C840B /* libchipmunk iOS.a */; }; + 1A676839180E9C1E0076BC67 /* libcocos2dx iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */; }; + 1A67683A180E9C1E0076BC67 /* libcocos2dx-extensions iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB58180E9ACB004C840B /* libcocos2dx-extensions iOS.a */; }; + 1A67683B180E9C1E0076BC67 /* libCocosDenshion iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB5E180E9ACB004C840B /* libCocosDenshion iOS.a */; }; + 1A67683C180E9C1E0076BC67 /* libjsbindings iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB60180E9ACB004C840B /* libjsbindings iOS.a */; }; + 1A67683E180E9CE90076BC67 /* jsb_chipmunk_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767EE180E9B160076BC67 /* jsb_chipmunk_constants.js */; }; + 1A67683F180E9CE90076BC67 /* jsb_chipmunk.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767EF180E9B160076BC67 /* jsb_chipmunk.js */; }; + 1A676840180E9CE90076BC67 /* jsb_cocos2d_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F0180E9B160076BC67 /* jsb_cocos2d_constants.js */; }; + 1A676841180E9CE90076BC67 /* jsb_cocos2d_extension.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F1180E9B160076BC67 /* jsb_cocos2d_extension.js */; }; + 1A676842180E9CE90076BC67 /* jsb_cocos2d.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F2180E9B160076BC67 /* jsb_cocos2d.js */; }; + 1A676843180E9CE90076BC67 /* jsb_cocosbuilder.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F3180E9B160076BC67 /* jsb_cocosbuilder.js */; }; + 1A676844180E9CE90076BC67 /* jsb_debugger.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F4180E9B160076BC67 /* jsb_debugger.js */; }; + 1A676845180E9CE90076BC67 /* jsb_deprecated.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F5180E9B160076BC67 /* jsb_deprecated.js */; }; + 1A676846180E9CE90076BC67 /* jsb_opengl_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F6180E9B160076BC67 /* jsb_opengl_constants.js */; }; + 1A676847180E9CE90076BC67 /* jsb_opengl.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F7180E9B160076BC67 /* jsb_opengl.js */; }; + 1A676848180E9CE90076BC67 /* jsb_sys.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F8180E9B160076BC67 /* jsb_sys.js */; }; + 1A676849180E9CE90076BC67 /* jsb.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F9180E9B160076BC67 /* jsb.js */; }; + 1A67684A180E9CF10076BC67 /* jsb_chipmunk_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767EE180E9B160076BC67 /* jsb_chipmunk_constants.js */; }; + 1A67684B180E9CF10076BC67 /* jsb_chipmunk.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767EF180E9B160076BC67 /* jsb_chipmunk.js */; }; + 1A67684C180E9CF10076BC67 /* jsb_cocos2d_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F0180E9B160076BC67 /* jsb_cocos2d_constants.js */; }; + 1A67684D180E9CF10076BC67 /* jsb_cocos2d_extension.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F1180E9B160076BC67 /* jsb_cocos2d_extension.js */; }; + 1A67684E180E9CF10076BC67 /* jsb_cocos2d.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F2180E9B160076BC67 /* jsb_cocos2d.js */; }; + 1A67684F180E9CF10076BC67 /* jsb_cocosbuilder.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F3180E9B160076BC67 /* jsb_cocosbuilder.js */; }; + 1A676850180E9CF10076BC67 /* jsb_debugger.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F4180E9B160076BC67 /* jsb_debugger.js */; }; + 1A676851180E9CF10076BC67 /* jsb_deprecated.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F5180E9B160076BC67 /* jsb_deprecated.js */; }; + 1A676852180E9CF10076BC67 /* jsb_opengl_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F6180E9B160076BC67 /* jsb_opengl_constants.js */; }; + 1A676853180E9CF10076BC67 /* jsb_opengl.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F7180E9B160076BC67 /* jsb_opengl.js */; }; + 1A676854180E9CF10076BC67 /* jsb_sys.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F8180E9B160076BC67 /* jsb_sys.js */; }; + 1A676855180E9CF10076BC67 /* jsb.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6767F9180E9B160076BC67 /* jsb.js */; }; 1A82F5FB169AC92500C4B13A /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */; }; - 1A96A4F3174A3432008653A9 /* libcurl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A96A4F2174A3432008653A9 /* libcurl.a */; }; 1AE4B40416D1FECD003C6D1C /* res in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40116D1FECD003C6D1C /* res */; }; 1AE4B40516D1FECD003C6D1C /* src in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40216D1FECD003C6D1C /* src */; }; 1AE4B40616D1FF4C003C6D1C /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40016D1FECD003C6D1C /* main.js */; }; - 1AF4C33317865EC500122817 /* libchipmunk iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C32017865E8F00122817 /* libchipmunk iOS.a */; }; - 1AF4C33417865EC500122817 /* libcocos2dx iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31C17865E8F00122817 /* libcocos2dx iOS.a */; }; - 1AF4C33517865EC500122817 /* libcocos2dx-extensions iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31E17865E8F00122817 /* libcocos2dx-extensions iOS.a */; }; - 1AF4C33617865EC500122817 /* libCocosDenshion iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C32417865E8F00122817 /* libCocosDenshion iOS.a */; }; - 1AF4C33717865EC500122817 /* libjsbindings iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C32617865E8F00122817 /* libjsbindings iOS.a */; }; - 1AF4C35117865F7400122817 /* jsb_chipmunk_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33917865F1600122817 /* jsb_chipmunk_constants.js */; }; - 1AF4C35217865F7400122817 /* jsb_chipmunk.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33A17865F1600122817 /* jsb_chipmunk.js */; }; - 1AF4C35317865F7400122817 /* jsb_cocos2d_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33B17865F1600122817 /* jsb_cocos2d_constants.js */; }; - 1AF4C35417865F7400122817 /* jsb_cocos2d_extension.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33C17865F1600122817 /* jsb_cocos2d_extension.js */; }; - 1AF4C35517865F7400122817 /* jsb_cocos2d.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33D17865F1600122817 /* jsb_cocos2d.js */; }; - 1AF4C35617865F7400122817 /* jsb_cocosbuilder.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33E17865F1600122817 /* jsb_cocosbuilder.js */; }; - 1AF4C35717865F7400122817 /* jsb_debugger.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33F17865F1600122817 /* jsb_debugger.js */; }; - 1AF4C35817865F7400122817 /* jsb_opengl_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34017865F1600122817 /* jsb_opengl_constants.js */; }; - 1AF4C35917865F7400122817 /* jsb_opengl.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34117865F1600122817 /* jsb_opengl.js */; }; - 1AF4C35A17865F7400122817 /* jsb_sys.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34217865F1600122817 /* jsb_sys.js */; }; - 1AF4C35B17865F7400122817 /* jsb.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34317865F1600122817 /* jsb.js */; }; - 1AF4C35C17865F7400122817 /* main.debug.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34417865F1600122817 /* main.debug.js */; }; - 466AF679179FC7EE002EE9BB /* jsb_deprecated.js in Resources */ = {isa = PBXBuildFile; fileRef = 466AF66C179FC7BE002EE9BB /* jsb_deprecated.js */; }; 502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 502380DB17EBB88200990C9B /* libcurl.dylib */; }; - 502380DD17EBB89A00990C9B /* libchipmunk Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31217865E8F00122817 /* libchipmunk Mac.a */; }; - 502380DE17EBB89A00990C9B /* libcocos2dx Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C30E17865E8F00122817 /* libcocos2dx Mac.a */; }; - 502380DF17EBB89A00990C9B /* libcocos2dx-extensions Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31017865E8F00122817 /* libcocos2dx-extensions Mac.a */; }; - 502380E017EBB89A00990C9B /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31617865E8F00122817 /* libCocosDenshion Mac.a */; }; - 502380E117EBB89A00990C9B /* libjsbindings Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AF4C31817865E8F00122817 /* libjsbindings Mac.a */; }; 5091731A17ECDF7A00D62437 /* Icon-29.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731417ECDF7A00D62437 /* Icon-29.png */; }; 5091731B17ECDF7A00D62437 /* Icon-40.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731517ECDF7A00D62437 /* Icon-40.png */; }; 5091731C17ECDF7A00D62437 /* Icon-50.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731617ECDF7A00D62437 /* Icon-50.png */; }; @@ -51,19 +63,6 @@ 509D4A8E17EBB24E00697056 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275491517C094001B78AA /* AVFoundation.framework */; }; 509D4A9017EBB24E00697056 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754D1517C094001B78AA /* Foundation.framework */; }; 509D4A9117EBB24E00697056 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754F1517C094001B78AA /* CoreGraphics.framework */; }; - 509D4A9417EBB24E00697056 /* jsb_deprecated.js in Resources */ = {isa = PBXBuildFile; fileRef = 466AF66C179FC7BE002EE9BB /* jsb_deprecated.js */; }; - 509D4A9517EBB24E00697056 /* jsb_chipmunk_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33917865F1600122817 /* jsb_chipmunk_constants.js */; }; - 509D4A9617EBB24E00697056 /* jsb_chipmunk.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33A17865F1600122817 /* jsb_chipmunk.js */; }; - 509D4A9717EBB24E00697056 /* jsb_cocos2d_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33B17865F1600122817 /* jsb_cocos2d_constants.js */; }; - 509D4A9817EBB24E00697056 /* jsb_cocos2d_extension.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33C17865F1600122817 /* jsb_cocos2d_extension.js */; }; - 509D4A9917EBB24E00697056 /* jsb_cocos2d.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33D17865F1600122817 /* jsb_cocos2d.js */; }; - 509D4A9A17EBB24E00697056 /* jsb_cocosbuilder.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33E17865F1600122817 /* jsb_cocosbuilder.js */; }; - 509D4A9B17EBB24E00697056 /* jsb_debugger.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C33F17865F1600122817 /* jsb_debugger.js */; }; - 509D4A9C17EBB24E00697056 /* jsb_opengl_constants.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34017865F1600122817 /* jsb_opengl_constants.js */; }; - 509D4A9D17EBB24E00697056 /* jsb_opengl.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34117865F1600122817 /* jsb_opengl.js */; }; - 509D4A9E17EBB24E00697056 /* jsb_sys.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34217865F1600122817 /* jsb_sys.js */; }; - 509D4A9F17EBB24E00697056 /* jsb.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34317865F1600122817 /* jsb.js */; }; - 509D4AA017EBB24E00697056 /* main.debug.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AF4C34417865F1600122817 /* main.debug.js */; }; 509D4AA117EBB24E00697056 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40016D1FECD003C6D1C /* main.js */; }; 509D4AA517EBB24E00697056 /* res in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40116D1FECD003C6D1C /* res */; }; 509D4AA617EBB24E00697056 /* src in Resources */ = {isa = PBXBuildFile; fileRef = 1AE4B40216D1FECD003C6D1C /* src */; }; @@ -99,140 +98,196 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 1AF4C30D17865E8F00122817 /* PBXContainerItemProxy */ = { + 1A67681F180E9BF70076BC67 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 1551A33E158F2AB200E66CFE; + remoteInfo = "cocos2dx Mac"; + }; + 1A676821180E9BF70076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F2FC117814595006731B9; + remoteInfo = "cocos2dx-extensions Mac"; + }; + 1A676823180E9BF70076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F2B781780BD04006731B9; + remoteInfo = "chipmunk Mac"; + }; + 1A676825180E9BF70076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F2E9817814268006731B9; + remoteInfo = "CocosDenshion Mac"; + }; + 1A676827180E9BF70076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F31E81781479B006731B9; + remoteInfo = "jsbindings Mac"; + }; + 1A67682E180E9C110076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4C241783777C0073F6A7; + remoteInfo = "cocos2dx iOS"; + }; + 1A676830180E9C110076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4E111783867C0073F6A7; + remoteInfo = "cocos2dx-extensions iOS"; + }; + 1A676832180E9C110076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4EFD178387670073F6A7; + remoteInfo = "chipmunk iOS"; + }; + 1A676834180E9C110076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4F9F178387730073F6A7; + remoteInfo = "CocosDenshion iOS"; + }; + 1A676836180E9C110076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4FB5178387750073F6A7; + remoteInfo = "jsbindings iOS"; + }; + 1AC6FB47180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1551A33F158F2AB200E66CFE; remoteInfo = "cocos2dx Mac"; }; - 1AF4C30F17865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB49180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2FD617814595006731B9; remoteInfo = "cocos2dx-extensions Mac"; }; - 1AF4C31117865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB4B180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2CB81780BD04006731B9; remoteInfo = "chipmunk Mac"; }; - 1AF4C31317865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB4D180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2D9B1780BDF7006731B9; remoteInfo = "box2d Mac"; }; - 1AF4C31517865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB4F180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F2ED617814268006731B9; remoteInfo = "CocosDenshion Mac"; }; - 1AF4C31717865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB51180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A03F31FD1781479B006731B9; remoteInfo = "jsbindings Mac"; }; - 1AF4C31917865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB53180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1A6FB53017854BC300CDF010; remoteInfo = "luabindings Mac"; }; - 1AF4C31B17865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB55180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4D641783777C0073F6A7; remoteInfo = "cocos2dx iOS"; }; - 1AF4C31D17865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB57180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4EFC1783867C0073F6A7; remoteInfo = "cocos2dx-extensions iOS"; }; - 1AF4C31F17865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB59180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4F3B178387670073F6A7; remoteInfo = "chipmunk iOS"; }; - 1AF4C32117865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB5B180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4F9E1783876B0073F6A7; remoteInfo = "box2d iOS"; }; - 1AF4C32317865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB5D180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A4FB4178387730073F6A7; remoteInfo = "CocosDenshion iOS"; }; - 1AF4C32517865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB5F180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = A07A5030178387750073F6A7; remoteInfo = "jsbindings iOS"; }; - 1AF4C32717865E8F00122817 /* PBXContainerItemProxy */ = { + 1AC6FB61180E9ACB004C840B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; proxyType = 2; remoteGlobalIDString = 1A119791178526AA00D62A44; remoteInfo = "luabindings iOS"; }; - 502380EE17EBB8C500990C9B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A03F2E8E178141C1006731B9; - remoteInfo = "build-all-libs Mac"; - }; - 502380F017EBB8FD00990C9B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = A07A4E0B178386390073F6A7; - remoteInfo = "build-all-libs iOS"; - }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 1A6767ED180E9B160076BC67 /* debugger */ = {isa = PBXFileReference; lastKnownFileType = folder; name = debugger; path = ../../../cocos/scripting/javascript/script/debugger; sourceTree = ""; }; + 1A6767EE180E9B160076BC67 /* jsb_chipmunk_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_chipmunk_constants.js; path = ../../../cocos/scripting/javascript/script/jsb_chipmunk_constants.js; sourceTree = ""; }; + 1A6767EF180E9B160076BC67 /* jsb_chipmunk.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_chipmunk.js; path = ../../../cocos/scripting/javascript/script/jsb_chipmunk.js; sourceTree = ""; }; + 1A6767F0180E9B160076BC67 /* jsb_cocos2d_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d_constants.js; path = ../../../cocos/scripting/javascript/script/jsb_cocos2d_constants.js; sourceTree = ""; }; + 1A6767F1180E9B160076BC67 /* jsb_cocos2d_extension.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d_extension.js; path = ../../../cocos/scripting/javascript/script/jsb_cocos2d_extension.js; sourceTree = ""; }; + 1A6767F2180E9B160076BC67 /* jsb_cocos2d.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d.js; path = ../../../cocos/scripting/javascript/script/jsb_cocos2d.js; sourceTree = ""; }; + 1A6767F3180E9B160076BC67 /* jsb_cocosbuilder.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocosbuilder.js; path = ../../../cocos/scripting/javascript/script/jsb_cocosbuilder.js; sourceTree = ""; }; + 1A6767F4180E9B160076BC67 /* jsb_debugger.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_debugger.js; path = ../../../cocos/scripting/javascript/script/jsb_debugger.js; sourceTree = ""; }; + 1A6767F5180E9B160076BC67 /* jsb_deprecated.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_deprecated.js; path = ../../../cocos/scripting/javascript/script/jsb_deprecated.js; sourceTree = ""; }; + 1A6767F6180E9B160076BC67 /* jsb_opengl_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_opengl_constants.js; path = ../../../cocos/scripting/javascript/script/jsb_opengl_constants.js; sourceTree = ""; }; + 1A6767F7180E9B160076BC67 /* jsb_opengl.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_opengl.js; path = ../../../cocos/scripting/javascript/script/jsb_opengl.js; sourceTree = ""; }; + 1A6767F8180E9B160076BC67 /* jsb_sys.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_sys.js; path = ../../../cocos/scripting/javascript/script/jsb_sys.js; sourceTree = ""; }; + 1A6767F9180E9B160076BC67 /* jsb.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb.js; path = ../../../cocos/scripting/javascript/script/jsb.js; sourceTree = ""; }; 1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; 1A96A4F2174A3432008653A9 /* libcurl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcurl.a; path = ../../../cocos2dx/platform/third_party/ios/libraries/libcurl.a; sourceTree = ""; }; + 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = ../../../build/cocos2d_libs.xcodeproj; sourceTree = ""; }; 1AE4B40016D1FECD003C6D1C /* main.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = main.js; path = ../Resources/main.js; sourceTree = ""; }; 1AE4B40116D1FECD003C6D1C /* res */ = {isa = PBXFileReference; lastKnownFileType = folder; name = res; path = ../Resources/res; sourceTree = ""; }; 1AE4B40216D1FECD003C6D1C /* src */ = {isa = PBXFileReference; lastKnownFileType = folder; name = src; path = ../Resources/src; sourceTree = ""; }; - 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = ../../../cocos2d_libs.xcodeproj; sourceTree = ""; }; - 1AF4C33917865F1600122817 /* jsb_chipmunk_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_chipmunk_constants.js; path = ../../../scripting/javascript/bindings/js/jsb_chipmunk_constants.js; sourceTree = ""; }; - 1AF4C33A17865F1600122817 /* jsb_chipmunk.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_chipmunk.js; path = ../../../scripting/javascript/bindings/js/jsb_chipmunk.js; sourceTree = ""; }; - 1AF4C33B17865F1600122817 /* jsb_cocos2d_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d_constants.js; path = ../../../scripting/javascript/bindings/js/jsb_cocos2d_constants.js; sourceTree = ""; }; - 1AF4C33C17865F1600122817 /* jsb_cocos2d_extension.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d_extension.js; path = ../../../scripting/javascript/bindings/js/jsb_cocos2d_extension.js; sourceTree = ""; }; - 1AF4C33D17865F1600122817 /* jsb_cocos2d.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocos2d.js; path = ../../../scripting/javascript/bindings/js/jsb_cocos2d.js; sourceTree = ""; }; - 1AF4C33E17865F1600122817 /* jsb_cocosbuilder.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_cocosbuilder.js; path = ../../../scripting/javascript/bindings/js/jsb_cocosbuilder.js; sourceTree = ""; }; - 1AF4C33F17865F1600122817 /* jsb_debugger.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_debugger.js; path = ../../../scripting/javascript/bindings/js/jsb_debugger.js; sourceTree = ""; }; - 1AF4C34017865F1600122817 /* jsb_opengl_constants.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_opengl_constants.js; path = ../../../scripting/javascript/bindings/js/jsb_opengl_constants.js; sourceTree = ""; }; - 1AF4C34117865F1600122817 /* jsb_opengl.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_opengl.js; path = ../../../scripting/javascript/bindings/js/jsb_opengl.js; sourceTree = ""; }; - 1AF4C34217865F1600122817 /* jsb_sys.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_sys.js; path = ../../../scripting/javascript/bindings/js/jsb_sys.js; sourceTree = ""; }; - 1AF4C34317865F1600122817 /* jsb.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb.js; path = ../../../scripting/javascript/bindings/js/jsb.js; sourceTree = ""; }; - 1AF4C34417865F1600122817 /* main.debug.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = main.debug.js; path = ../../../scripting/javascript/bindings/js/main.debug.js; sourceTree = ""; }; - 466AF66C179FC7BE002EE9BB /* jsb_deprecated.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = jsb_deprecated.js; path = ../../../scripting/javascript/bindings/js/jsb_deprecated.js; sourceTree = ""; }; 502380DB17EBB88200990C9B /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; }; 5091731417ECDF7A00D62437 /* Icon-29.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-29.png"; path = "ios/Icon-29.png"; sourceTree = ""; }; 5091731517ECDF7A00D62437 /* Icon-40.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-40.png"; path = "ios/Icon-40.png"; sourceTree = ""; }; @@ -285,11 +340,11 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 502380DD17EBB89A00990C9B /* libchipmunk Mac.a in Frameworks */, - 502380DE17EBB89A00990C9B /* libcocos2dx Mac.a in Frameworks */, - 502380DF17EBB89A00990C9B /* libcocos2dx-extensions Mac.a in Frameworks */, - 502380E017EBB89A00990C9B /* libCocosDenshion Mac.a in Frameworks */, - 502380E117EBB89A00990C9B /* libjsbindings Mac.a in Frameworks */, + 1A676829180E9C060076BC67 /* libchipmunk Mac.a in Frameworks */, + 1A67682A180E9C060076BC67 /* libcocos2dx Mac.a in Frameworks */, + 1A67682B180E9C060076BC67 /* libcocos2dx-extensions Mac.a in Frameworks */, + 1A67682C180E9C060076BC67 /* libCocosDenshion Mac.a in Frameworks */, + 1A67682D180E9C060076BC67 /* libjsbindings Mac.a in Frameworks */, 502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */, 509D4A8817EBB24E00697056 /* libsqlite3.dylib in Frameworks */, 509D4A8917EBB24E00697056 /* libz.dylib in Frameworks */, @@ -309,12 +364,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 1A676838180E9C1E0076BC67 /* libchipmunk iOS.a in Frameworks */, + 1A676839180E9C1E0076BC67 /* libcocos2dx iOS.a in Frameworks */, + 1A67683A180E9C1E0076BC67 /* libcocos2dx-extensions iOS.a in Frameworks */, + 1A67683B180E9C1E0076BC67 /* libCocosDenshion iOS.a in Frameworks */, + 1A67683C180E9C1E0076BC67 /* libjsbindings iOS.a in Frameworks */, D6B061241803AB9F0077942B /* CoreMotion.framework in Frameworks */, - 1AF4C33317865EC500122817 /* libchipmunk iOS.a in Frameworks */, - 1AF4C33417865EC500122817 /* libcocos2dx iOS.a in Frameworks */, - 1AF4C33517865EC500122817 /* libcocos2dx-extensions iOS.a in Frameworks */, - 1AF4C33617865EC500122817 /* libCocosDenshion iOS.a in Frameworks */, - 1AF4C33717865EC500122817 /* libjsbindings iOS.a in Frameworks */, 1A82F5FB169AC92500C4B13A /* libsqlite3.dylib in Frameworks */, D454520C156E22BD00887EB5 /* libz.dylib in Frameworks */, A92275421517C094001B78AA /* QuartzCore.framework in Frameworks */, @@ -325,7 +380,6 @@ A922754C1517C094001B78AA /* UIKit.framework in Frameworks */, A922754E1517C094001B78AA /* Foundation.framework in Frameworks */, A92275501517C094001B78AA /* CoreGraphics.framework in Frameworks */, - 1A96A4F3174A3432008653A9 /* libcurl.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -342,47 +396,47 @@ name = Resources; sourceTree = ""; }; - 1AF4C2FB17865E8F00122817 /* Products */ = { + 1A6767EC180E9AF00076BC67 /* JS Common */ = { isa = PBXGroup; children = ( - 1AF4C30E17865E8F00122817 /* libcocos2dx Mac.a */, - 1AF4C31017865E8F00122817 /* libcocos2dx-extensions Mac.a */, - 1AF4C31217865E8F00122817 /* libchipmunk Mac.a */, - 1AF4C31417865E8F00122817 /* libbox2d Mac.a */, - 1AF4C31617865E8F00122817 /* libCocosDenshion Mac.a */, - 1AF4C31817865E8F00122817 /* libjsbindings Mac.a */, - 1AF4C31A17865E8F00122817 /* libluabindings Mac.a */, - 1AF4C31C17865E8F00122817 /* libcocos2dx iOS.a */, - 1AF4C31E17865E8F00122817 /* libcocos2dx-extensions iOS.a */, - 1AF4C32017865E8F00122817 /* libchipmunk iOS.a */, - 1AF4C32217865E8F00122817 /* libbox2d iOS.a */, - 1AF4C32417865E8F00122817 /* libCocosDenshion iOS.a */, - 1AF4C32617865E8F00122817 /* libjsbindings iOS.a */, - 1AF4C32817865E8F00122817 /* libluabindings iOS.a */, - ); - name = Products; - sourceTree = ""; - }; - 1AF4C33817865EF900122817 /* JS Common */ = { - isa = PBXGroup; - children = ( - 466AF66C179FC7BE002EE9BB /* jsb_deprecated.js */, - 1AF4C33917865F1600122817 /* jsb_chipmunk_constants.js */, - 1AF4C33A17865F1600122817 /* jsb_chipmunk.js */, - 1AF4C33B17865F1600122817 /* jsb_cocos2d_constants.js */, - 1AF4C33C17865F1600122817 /* jsb_cocos2d_extension.js */, - 1AF4C33D17865F1600122817 /* jsb_cocos2d.js */, - 1AF4C33E17865F1600122817 /* jsb_cocosbuilder.js */, - 1AF4C33F17865F1600122817 /* jsb_debugger.js */, - 1AF4C34017865F1600122817 /* jsb_opengl_constants.js */, - 1AF4C34117865F1600122817 /* jsb_opengl.js */, - 1AF4C34217865F1600122817 /* jsb_sys.js */, - 1AF4C34317865F1600122817 /* jsb.js */, - 1AF4C34417865F1600122817 /* main.debug.js */, + 1A6767ED180E9B160076BC67 /* debugger */, + 1A6767EE180E9B160076BC67 /* jsb_chipmunk_constants.js */, + 1A6767EF180E9B160076BC67 /* jsb_chipmunk.js */, + 1A6767F0180E9B160076BC67 /* jsb_cocos2d_constants.js */, + 1A6767F1180E9B160076BC67 /* jsb_cocos2d_extension.js */, + 1A6767F2180E9B160076BC67 /* jsb_cocos2d.js */, + 1A6767F3180E9B160076BC67 /* jsb_cocosbuilder.js */, + 1A6767F4180E9B160076BC67 /* jsb_debugger.js */, + 1A6767F5180E9B160076BC67 /* jsb_deprecated.js */, + 1A6767F6180E9B160076BC67 /* jsb_opengl_constants.js */, + 1A6767F7180E9B160076BC67 /* jsb_opengl.js */, + 1A6767F8180E9B160076BC67 /* jsb_sys.js */, + 1A6767F9180E9B160076BC67 /* jsb.js */, ); name = "JS Common"; sourceTree = ""; }; + 1AC6FB35180E9ACB004C840B /* Products */ = { + isa = PBXGroup; + children = ( + 1AC6FB48180E9ACB004C840B /* libcocos2dx Mac.a */, + 1AC6FB4A180E9ACB004C840B /* libcocos2dx-extensions Mac.a */, + 1AC6FB4C180E9ACB004C840B /* libchipmunk Mac.a */, + 1AC6FB4E180E9ACB004C840B /* libbox2d Mac.a */, + 1AC6FB50180E9ACB004C840B /* libCocosDenshion Mac.a */, + 1AC6FB52180E9ACB004C840B /* libjsbindings Mac.a */, + 1AC6FB54180E9ACB004C840B /* libluabindings Mac.a */, + 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */, + 1AC6FB58180E9ACB004C840B /* libcocos2dx-extensions iOS.a */, + 1AC6FB5A180E9ACB004C840B /* libchipmunk iOS.a */, + 1AC6FB5C180E9ACB004C840B /* libbox2d iOS.a */, + 1AC6FB5E180E9ACB004C840B /* libCocosDenshion iOS.a */, + 1AC6FB60180E9ACB004C840B /* libjsbindings iOS.a */, + 1AC6FB62180E9ACB004C840B /* libluabindings iOS.a */, + ); + name = Products; + sourceTree = ""; + }; 5091732E17ECDF8A00D62437 /* Icons */ = { isa = PBXGroup; children = ( @@ -417,11 +471,11 @@ A92275321517C094001B78AA = { isa = PBXGroup; children = ( - 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */, - 1AF4C33817865EF900122817 /* JS Common */, + 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */, D4545214156E28EF00887EB5 /* Classes */, A92275401517C094001B78AA /* Frameworks */, D45446CC156DE73F00887EB5 /* ios */, + 1A6767EC180E9AF00076BC67 /* JS Common */, 509D4ACA17EBB2BE00697056 /* mac */, A922753E1517C094001B78AA /* Products */, 15628F5B15F0F5C2000CF24B /* Resources */, @@ -502,7 +556,11 @@ buildRules = ( ); dependencies = ( - 502380EF17EBB8C500990C9B /* PBXTargetDependency */, + 1A676820180E9BF70076BC67 /* PBXTargetDependency */, + 1A676822180E9BF70076BC67 /* PBXTargetDependency */, + 1A676824180E9BF70076BC67 /* PBXTargetDependency */, + 1A676826180E9BF70076BC67 /* PBXTargetDependency */, + 1A676828180E9BF70076BC67 /* PBXTargetDependency */, ); name = "Hello JavaScript Mac"; productName = HelloJavascript; @@ -520,7 +578,11 @@ buildRules = ( ); dependencies = ( - 502380F117EBB8FD00990C9B /* PBXTargetDependency */, + 1A67682F180E9C110076BC67 /* PBXTargetDependency */, + 1A676831180E9C110076BC67 /* PBXTargetDependency */, + 1A676833180E9C110076BC67 /* PBXTargetDependency */, + 1A676835180E9C110076BC67 /* PBXTargetDependency */, + 1A676837180E9C110076BC67 /* PBXTargetDependency */, ); name = "Hello JavaScript iOS"; productName = HelloJavascript; @@ -552,8 +614,8 @@ projectDirPath = ""; projectReferences = ( { - ProductGroup = 1AF4C2FB17865E8F00122817 /* Products */; - ProjectRef = 1AF4C2FA17865E8F00122817 /* cocos2d_libs.xcodeproj */; + ProductGroup = 1AC6FB35180E9ACB004C840B /* Products */; + ProjectRef = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; }, ); projectRoot = ""; @@ -565,102 +627,102 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ - 1AF4C30E17865E8F00122817 /* libcocos2dx Mac.a */ = { + 1AC6FB48180E9ACB004C840B /* libcocos2dx Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx Mac.a"; - remoteRef = 1AF4C30D17865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB47180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31017865E8F00122817 /* libcocos2dx-extensions Mac.a */ = { + 1AC6FB4A180E9ACB004C840B /* libcocos2dx-extensions Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx-extensions Mac.a"; - remoteRef = 1AF4C30F17865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB49180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31217865E8F00122817 /* libchipmunk Mac.a */ = { + 1AC6FB4C180E9ACB004C840B /* libchipmunk Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libchipmunk Mac.a"; - remoteRef = 1AF4C31117865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB4B180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31417865E8F00122817 /* libbox2d Mac.a */ = { + 1AC6FB4E180E9ACB004C840B /* libbox2d Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libbox2d Mac.a"; - remoteRef = 1AF4C31317865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB4D180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31617865E8F00122817 /* libCocosDenshion Mac.a */ = { + 1AC6FB50180E9ACB004C840B /* libCocosDenshion Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libCocosDenshion Mac.a"; - remoteRef = 1AF4C31517865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB4F180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31817865E8F00122817 /* libjsbindings Mac.a */ = { + 1AC6FB52180E9ACB004C840B /* libjsbindings Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libjsbindings Mac.a"; - remoteRef = 1AF4C31717865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB51180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31A17865E8F00122817 /* libluabindings Mac.a */ = { + 1AC6FB54180E9ACB004C840B /* libluabindings Mac.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libluabindings Mac.a"; - remoteRef = 1AF4C31917865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB53180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31C17865E8F00122817 /* libcocos2dx iOS.a */ = { + 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx iOS.a"; - remoteRef = 1AF4C31B17865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB55180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C31E17865E8F00122817 /* libcocos2dx-extensions iOS.a */ = { + 1AC6FB58180E9ACB004C840B /* libcocos2dx-extensions iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libcocos2dx-extensions iOS.a"; - remoteRef = 1AF4C31D17865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB57180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C32017865E8F00122817 /* libchipmunk iOS.a */ = { + 1AC6FB5A180E9ACB004C840B /* libchipmunk iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libchipmunk iOS.a"; - remoteRef = 1AF4C31F17865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB59180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C32217865E8F00122817 /* libbox2d iOS.a */ = { + 1AC6FB5C180E9ACB004C840B /* libbox2d iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libbox2d iOS.a"; - remoteRef = 1AF4C32117865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB5B180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C32417865E8F00122817 /* libCocosDenshion iOS.a */ = { + 1AC6FB5E180E9ACB004C840B /* libCocosDenshion iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libCocosDenshion iOS.a"; - remoteRef = 1AF4C32317865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB5D180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C32617865E8F00122817 /* libjsbindings iOS.a */ = { + 1AC6FB60180E9ACB004C840B /* libjsbindings iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libjsbindings iOS.a"; - remoteRef = 1AF4C32517865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB5F180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 1AF4C32817865E8F00122817 /* libluabindings iOS.a */ = { + 1AC6FB62180E9ACB004C840B /* libluabindings iOS.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libluabindings iOS.a"; - remoteRef = 1AF4C32717865E8F00122817 /* PBXContainerItemProxy */; + remoteRef = 1AC6FB61180E9ACB004C840B /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ @@ -670,23 +732,23 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 509D4A9417EBB24E00697056 /* jsb_deprecated.js in Resources */, - 509D4A9517EBB24E00697056 /* jsb_chipmunk_constants.js in Resources */, - 509D4A9617EBB24E00697056 /* jsb_chipmunk.js in Resources */, - 509D4A9717EBB24E00697056 /* jsb_cocos2d_constants.js in Resources */, - 509D4A9817EBB24E00697056 /* jsb_cocos2d_extension.js in Resources */, - 509D4A9917EBB24E00697056 /* jsb_cocos2d.js in Resources */, - 509D4A9A17EBB24E00697056 /* jsb_cocosbuilder.js in Resources */, - 509D4A9B17EBB24E00697056 /* jsb_debugger.js in Resources */, - 509D4A9C17EBB24E00697056 /* jsb_opengl_constants.js in Resources */, - 509D4A9D17EBB24E00697056 /* jsb_opengl.js in Resources */, - 509D4A9E17EBB24E00697056 /* jsb_sys.js in Resources */, - 509D4A9F17EBB24E00697056 /* jsb.js in Resources */, - 509D4AA017EBB24E00697056 /* main.debug.js in Resources */, + 1A67683E180E9CE90076BC67 /* jsb_chipmunk_constants.js in Resources */, + 1A67683F180E9CE90076BC67 /* jsb_chipmunk.js in Resources */, + 1A676840180E9CE90076BC67 /* jsb_cocos2d_constants.js in Resources */, + 1A676841180E9CE90076BC67 /* jsb_cocos2d_extension.js in Resources */, + 1A676842180E9CE90076BC67 /* jsb_cocos2d.js in Resources */, + 1A676843180E9CE90076BC67 /* jsb_cocosbuilder.js in Resources */, + 1A676844180E9CE90076BC67 /* jsb_debugger.js in Resources */, + 1A676845180E9CE90076BC67 /* jsb_deprecated.js in Resources */, + 1A676846180E9CE90076BC67 /* jsb_opengl_constants.js in Resources */, + 1A676847180E9CE90076BC67 /* jsb_opengl.js in Resources */, + 1A676848180E9CE90076BC67 /* jsb_sys.js in Resources */, + 1A676849180E9CE90076BC67 /* jsb.js in Resources */, 509D4AA117EBB24E00697056 /* main.js in Resources */, 509D4ACF17EBB2BE00697056 /* Icon.icns in Resources */, 509D4AA517EBB24E00697056 /* res in Resources */, 509D4AA617EBB24E00697056 /* src in Resources */, + 1A6767FB180E9B160076BC67 /* debugger in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -694,28 +756,27 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 466AF679179FC7EE002EE9BB /* jsb_deprecated.js in Resources */, - 1AF4C35117865F7400122817 /* jsb_chipmunk_constants.js in Resources */, - 1AF4C35217865F7400122817 /* jsb_chipmunk.js in Resources */, - 1AF4C35317865F7400122817 /* jsb_cocos2d_constants.js in Resources */, + 1A67684A180E9CF10076BC67 /* jsb_chipmunk_constants.js in Resources */, + 1A67684B180E9CF10076BC67 /* jsb_chipmunk.js in Resources */, + 1A67684C180E9CF10076BC67 /* jsb_cocos2d_constants.js in Resources */, + 1A67684D180E9CF10076BC67 /* jsb_cocos2d_extension.js in Resources */, + 1A67684E180E9CF10076BC67 /* jsb_cocos2d.js in Resources */, + 1A67684F180E9CF10076BC67 /* jsb_cocosbuilder.js in Resources */, + 1A676850180E9CF10076BC67 /* jsb_debugger.js in Resources */, + 1A676851180E9CF10076BC67 /* jsb_deprecated.js in Resources */, + 1A676852180E9CF10076BC67 /* jsb_opengl_constants.js in Resources */, + 1A676853180E9CF10076BC67 /* jsb_opengl.js in Resources */, + 1A676854180E9CF10076BC67 /* jsb_sys.js in Resources */, + 1A676855180E9CF10076BC67 /* jsb.js in Resources */, 509D4ABE17EBB2AB00697056 /* Default.png in Resources */, 5091731E17ECDF7A00D62437 /* Icon-80.png in Resources */, 5091731F17ECDF7A00D62437 /* Icon-100.png in Resources */, 509D4AC117EBB2AB00697056 /* Icon-72.png in Resources */, - 1AF4C35417865F7400122817 /* jsb_cocos2d_extension.js in Resources */, - 1AF4C35517865F7400122817 /* jsb_cocos2d.js in Resources */, - 1AF4C35617865F7400122817 /* jsb_cocosbuilder.js in Resources */, 509D4AC017EBB2AB00697056 /* Icon-57.png in Resources */, - 1AF4C35717865F7400122817 /* jsb_debugger.js in Resources */, 5091731A17ECDF7A00D62437 /* Icon-29.png in Resources */, - 1AF4C35817865F7400122817 /* jsb_opengl_constants.js in Resources */, - 1AF4C35917865F7400122817 /* jsb_opengl.js in Resources */, - 1AF4C35A17865F7400122817 /* jsb_sys.js in Resources */, 509D4AC617EBB2AB00697056 /* Icon-152.png in Resources */, 509D4AC517EBB2AB00697056 /* Icon-144.png in Resources */, - 1AF4C35B17865F7400122817 /* jsb.js in Resources */, 509D4AC317EBB2AB00697056 /* Icon-114.png in Resources */, - 1AF4C35C17865F7400122817 /* main.debug.js in Resources */, 509D4ABD17EBB2AB00697056 /* Default-568h@2x.png in Resources */, 1AE4B40616D1FF4C003C6D1C /* main.js in Resources */, 509D4ABF17EBB2AB00697056 /* Default@2x.png in Resources */, @@ -726,6 +787,7 @@ 509D4AC417EBB2AB00697056 /* Icon-120.png in Resources */, 1AE4B40516D1FECD003C6D1C /* src in Resources */, 5091731D17ECDF7A00D62437 /* Icon-58.png in Resources */, + 1A6767FA180E9B160076BC67 /* debugger in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -755,15 +817,55 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 502380EF17EBB8C500990C9B /* PBXTargetDependency */ = { + 1A676820180E9BF70076BC67 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = "build-all-libs Mac"; - targetProxy = 502380EE17EBB8C500990C9B /* PBXContainerItemProxy */; + name = "cocos2dx Mac"; + targetProxy = 1A67681F180E9BF70076BC67 /* PBXContainerItemProxy */; }; - 502380F117EBB8FD00990C9B /* PBXTargetDependency */ = { + 1A676822180E9BF70076BC67 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = "build-all-libs iOS"; - targetProxy = 502380F017EBB8FD00990C9B /* PBXContainerItemProxy */; + name = "cocos2dx-extensions Mac"; + targetProxy = 1A676821180E9BF70076BC67 /* PBXContainerItemProxy */; + }; + 1A676824180E9BF70076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "chipmunk Mac"; + targetProxy = 1A676823180E9BF70076BC67 /* PBXContainerItemProxy */; + }; + 1A676826180E9BF70076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "CocosDenshion Mac"; + targetProxy = 1A676825180E9BF70076BC67 /* PBXContainerItemProxy */; + }; + 1A676828180E9BF70076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "jsbindings Mac"; + targetProxy = 1A676827180E9BF70076BC67 /* PBXContainerItemProxy */; + }; + 1A67682F180E9C110076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "cocos2dx iOS"; + targetProxy = 1A67682E180E9C110076BC67 /* PBXContainerItemProxy */; + }; + 1A676831180E9C110076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "cocos2dx-extensions iOS"; + targetProxy = 1A676830180E9C110076BC67 /* PBXContainerItemProxy */; + }; + 1A676833180E9C110076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "chipmunk iOS"; + targetProxy = 1A676832180E9C110076BC67 /* PBXContainerItemProxy */; + }; + 1A676835180E9C110076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "CocosDenshion iOS"; + targetProxy = 1A676834180E9C110076BC67 /* PBXContainerItemProxy */; + }; + 1A676837180E9C110076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "jsbindings iOS"; + targetProxy = 1A676836180E9C110076BC67 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -771,7 +873,7 @@ 509D4AA817EBB24E00697056 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; ARCHS = "$(ARCHS_STANDARD_64_BIT)"; COMBINE_HIDPI_IMAGES = YES; GCC_DYNAMIC_NO_PIC = NO; @@ -782,29 +884,14 @@ "$(inherited)", ); HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", - "$(SRCROOT)/../../../cocos2dx/include", - "$(SRCROOT)/../../../cocos2dx/platform/mac", - "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", - "$(SRCROOT)/../../../scripting/javascript/spidermonkey-mac/include", - "$(SRCROOT)/../../../scripting/auto-generated/js-bindings", - "$(SRCROOT)/../../../scripting/javascript/bindings", - "$(SRCROOT)/../../../extensions", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/mac", + "$(SRCROOT)/../../../external/spidermonkey/include/mac", + "$(SRCROOT)/../../../external/glfw3/include/mac", ); INFOPLIST_FILE = mac/Info.plist; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-mac/lib\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/mac/lib\"", - ); - OTHER_LDFLAGS = ( - "-lxml2", - "-lz", - "-ljs_static", - ); + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; SDKROOT = macosx; }; name = Debug; @@ -812,7 +899,7 @@ 509D4AA917EBB24E00697056 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; ARCHS = "$(ARCHS_STANDARD_64_BIT)"; COMBINE_HIDPI_IMAGES = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; @@ -822,29 +909,14 @@ "$(inherited)", ); HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../CocosDenshion/include\"", - "$(SRCROOT)/../../../cocos2dx/include", - "$(SRCROOT)/../../../cocos2dx/platform/mac", - "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", - "$(SRCROOT)/../../../scripting/javascript/spidermonkey-mac/include", - "$(SRCROOT)/../../../scripting/auto-generated/js-bindings", - "$(SRCROOT)/../../../scripting/javascript/bindings", - "$(SRCROOT)/../../../extensions", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/mac", + "$(SRCROOT)/../../../external/spidermonkey/include/mac", + "$(SRCROOT)/../../../external/glfw3/include/mac", ); INFOPLIST_FILE = mac/Info.plist; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-mac/lib\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/mac/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/mac/lib\"", - ); - OTHER_LDFLAGS = ( - "-lxml2", - "-lz", - "-ljs_static", - ); + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; SDKROOT = macosx; }; name = Release; @@ -868,10 +940,21 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../cocos2dx", - "$(SRCROOT)/../../cocos2dx/include", - "$(SRCROOT)/../../cocos2dx/platform/ios", - "$(SRCROOT)/../../scripting/javascript/spidermonkey-ios/include1", + "$(SRCROOT)/../../..", + "$(SRCROOT)/../../../cocos", + "$(SRCROOT)/../../../cocos/base", + "$(SRCROOT)/../../../cocos/physics", + "$(SRCROOT)/../../../cocos/math/kazmath/include", + "$(SRCROOT)/../../../cocos/2d", + "$(SRCROOT)/../../../cocos/gui", + "$(SRCROOT)/../../../cocos/network", + "$(SRCROOT)/../../../cocos/audio/include", + "$(SRCROOT)/../../../cocos/editor-support", + "$(SRCROOT)/../../../cocos/scripting/javascript/bindings", + "$(SRCROOT)/../../../cocos/scripting/auto-generated/js-bindings", + "$(SRCROOT)/../../../extensions", + "$(SRCROOT)/../../../external", + "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", ); IPHONEOS_DEPLOYMENT_TARGET = 5.1; ONLY_ACTIVE_ARCH = YES; @@ -894,10 +977,21 @@ GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( - "$(SRCROOT)/../../cocos2dx", - "$(SRCROOT)/../../cocos2dx/include", - "$(SRCROOT)/../../cocos2dx/platform/ios", - "$(SRCROOT)/../../scripting/javascript/spidermonkey-ios/include1", + "$(SRCROOT)/../../..", + "$(SRCROOT)/../../../cocos", + "$(SRCROOT)/../../../cocos/base", + "$(SRCROOT)/../../../cocos/physics", + "$(SRCROOT)/../../../cocos/math/kazmath/include", + "$(SRCROOT)/../../../cocos/2d", + "$(SRCROOT)/../../../cocos/gui", + "$(SRCROOT)/../../../cocos/network", + "$(SRCROOT)/../../../cocos/audio/include", + "$(SRCROOT)/../../../cocos/editor-support", + "$(SRCROOT)/../../../cocos/scripting/javascript/bindings", + "$(SRCROOT)/../../../cocos/scripting/auto-generated/js-bindings", + "$(SRCROOT)/../../../extensions", + "$(SRCROOT)/../../../external", + "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", ); IPHONEOS_DEPLOYMENT_TARGET = 5.1; OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; @@ -909,7 +1003,7 @@ A92277011517C097001B78AA /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COMPRESS_PNG_FILES = NO; GCC_DYNAMIC_NO_PIC = NO; @@ -920,30 +1014,15 @@ "$(inherited)", ); HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../audio/include\"", - "$(SRCROOT)/../../../cocos2dx/include", - "$(SRCROOT)/../../../cocos2dx/platform/ios", - "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", - "$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/include", - "$(SRCROOT)/../../../scripting/auto-generated/js-bindings", - "$(SRCROOT)/../../../scripting/javascript/bindings", - "$(SRCROOT)/../../../extensions", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/ios", + "$(SRCROOT)/../../../cocos/2d/platform/ios/Simulation", + "$(SRCROOT)/../../../external/spidermonkey/include/ios", ); INFOPLIST_FILE = ios/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/lib\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/lib\"", - ); - OTHER_LDFLAGS = ( - "-lxml2", - "-lz", - "-ljs_static", - ); + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -952,7 +1031,7 @@ A92277021517C097001B78AA /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; + ALWAYS_SEARCH_USER_PATHS = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COMPRESS_PNG_FILES = NO; GCC_PRECOMPILE_PREFIX_HEADER = YES; @@ -962,30 +1041,15 @@ "$(inherited)", ); HEADER_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../cocos2dx\"", - "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", - "$(SRCROOT)/../../../cocos2dx/platform/third_party/ios", - "\"$(SRCROOT)/../../../audio/include\"", - "$(SRCROOT)/../../../cocos2dx/include", - "$(SRCROOT)/../../../cocos2dx/platform/ios", - "$(SRCROOT)/../../../external/chipmunk/include/chipmunk", - "$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/include", - "$(SRCROOT)/../../../scripting/auto-generated/js-bindings", - "$(SRCROOT)/../../../scripting/javascript/bindings", - "$(SRCROOT)/../../../extensions", + "$(inherited)", + "$(SRCROOT)/../../../cocos/2d/platform/ios", + "$(SRCROOT)/../../../cocos/2d/platform/ios/Simulation", + "$(SRCROOT)/../../../external/spidermonkey/include/ios", ); INFOPLIST_FILE = ios/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = ( - "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/lib\"", - "\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios/libraries\"", - "\"$(SRCROOT)/../../../external/libwebsockets/ios/lib\"", - ); - OTHER_LDFLAGS = ( - "-lxml2", - "-lz", - "-ljs_static", - ); + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; From 28de91d9650b072c2eecc806d0d2f953c0a1593b Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 16 Oct 2013 11:45:58 -0700 Subject: [PATCH 159/557] more Xcode fixes --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 944c4d9bef..81b945434f 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -81e5f8f3e9c025447f9dd4da9fba085d46f661d9 \ No newline at end of file +7658fe75258895d82e9432317ff63b182547bcdc \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index ffe5f7bf0a..04a9dc0568 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -d25068403b84374432b0ddaec0ab9c1e3a38c4ec \ No newline at end of file +f0ce606901bf2ba3acceae9e9562214dde6a4c69 \ No newline at end of file From 3cbeabc777d2e2d8841fea1959b1d6949c0fb518 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 16 Oct 2013 11:55:14 -0700 Subject: [PATCH 160/557] Icons for test projects --- samples/Cpp/HelloCpp/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../HelloCpp/proj.mac/Icon.icns.REMOVED.git-id | 1 + samples/Cpp/SimpleGame/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + .../TestCpp/proj.mac/Icon.icns.REMOVED.git-id | 2 +- .../Javascript/CocosDragonJS/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + .../Javascript/CrystalCraze/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + .../Javascript/MoonWarriors/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + .../TestJavascript/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + .../WatermelonWithMe/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../proj.mac/Icon.icns.REMOVED.git-id | 1 + samples/Lua/HelloLua/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../HelloLua/proj.mac/Icon.icns.REMOVED.git-id | 1 + samples/Lua/TestLua/proj.mac/Icon.icns | Bin 77152 -> 0 bytes .../TestLua/proj.mac/Icon.icns.REMOVED.git-id | 1 + 19 files changed, 10 insertions(+), 1 deletion(-) delete mode 100644 samples/Cpp/HelloCpp/proj.mac/Icon.icns create mode 100644 samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Cpp/SimpleGame/proj.mac/Icon.icns create mode 100644 samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Javascript/CocosDragonJS/proj.mac/Icon.icns create mode 100644 samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Javascript/CrystalCraze/proj.mac/Icon.icns create mode 100644 samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Javascript/MoonWarriors/proj.mac/Icon.icns create mode 100644 samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Javascript/TestJavascript/proj.mac/Icon.icns create mode 100644 samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns create mode 100644 samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Lua/HelloLua/proj.mac/Icon.icns create mode 100644 samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id delete mode 100644 samples/Lua/TestLua/proj.mac/Icon.icns create mode 100644 samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id diff --git a/samples/Cpp/HelloCpp/proj.mac/Icon.icns b/samples/Cpp/HelloCpp/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id b/samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.mac/Icon.icns b/samples/Cpp/SimpleGame/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id b/samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id b/samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id index 0c90afdb6d..9874ec6979 100644 --- a/samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id +++ b/samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id @@ -1 +1 @@ -2040fc6fe624353ae1d3db50cd3d450f4fda5afc \ No newline at end of file +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns b/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.mac/Icon.icns b/samples/Javascript/CrystalCraze/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.mac/Icon.icns b/samples/Javascript/MoonWarriors/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.mac/Icon.icns b/samples/Javascript/TestJavascript/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns b/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.mac/Icon.icns b/samples/Lua/HelloLua/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id b/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.mac/Icon.icns b/samples/Lua/TestLua/proj.mac/Icon.icns deleted file mode 100644 index 285dee82b3d3f80acf3c0037b6b6ce35df0e9e5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77152 zcmeFZXIxat_Ab0T(TVPcCg&WwF((wvIgtbb0l@$Yf+$9U!rtBFj7Ss^6+xmXS&|aF z0l}Pe9`lUjIL3ZgHO@J6=AQq(U*1pmcR^-g*WPQbTD7Y7s%Jgb0ULvNVx+O_0(MTG zgkcnJ)SEEf@#a<*=Hn~`LW^;F@yiUYEQJKZ+=Qc z@;C=Ct#KBLYV?`;X4u#qA!fFSC$v=LaWrsMs`_?qirQk9g*k`KC#_sfo*6ckVr!*o zZp=~SaF|Yk>zo}H3pfV)h8!M;qew9xD=_6Vb+mO2tr;9eHk(9MpeQIQtLrF7eY@Q^ z*gw=Gx!N@-kqq=bywpD+8SEYKE4bA)B$W>Ib@aj2;qLifao4*CCDMUYOsqAiFMWCN%jT>Ly@S&1;^L0ra@nm@kJ?xIfsBN-+{E3|Q}16qt4&(a zE0u=FhN~T`t-ly|wK93@k*hsXK@kDts@odtvO3};Lz1ubcyISyU*j_;xh`qk@~sDM zbg%O9Se|Ku2@aZLMy?xr`t9vJCPy+o-5q`0S<5H1x7jaSJ$1Rm1aE(jaZ@J8*VowD ztypEb%*Vxf!R$$%1v#ZF?d?{s)HfMtF~)R}I3_)J%QCy=v#d4wn(CHzUVFtcI^W+s zc>Lh$-G}dPJ$?A-@q>5p--l1`J>FjX@zzuPQPjhm_a8pK|NQO}&%9snJbC!&(eUNF z_n+Mg2!9oF@b}wrbGP)um8V-Sd<74j_~qV{N6qIt?-FIQo2MSOuiW+ft*15h%@yJO zr{BMLTAR4!-lIoHYV!1t*VbQ>d!X^%ovh=DV{6(PkOQK&7rwodc!=<=@t&1bpEzcD z;IR+uZWGBd&gsYlW|-mXZTB8TMkFtaV6F9X+~C1lHvQJM$j~^irH&K90~4l9K7M5& zGBP}7?&9^US1+7BVb{5)zOcy1h<%fc$Cz1}t*tC?IFlK^KXikem9CM|%)rRQ<&`_9 zZwUU_irEm-6;R4qAKEDgNKR6pUcO zi4|y=nwmk2Kp?cVG9zc~KJ@A0HnK5DiV>(8n?Rd6TAqa1soPDmPp_InFv~cBhLMrH z$h-G^55C@ge>10SJ;t^W3v_jK zboC6hEjZJkJdZyA{Qi?0Pai%k%1v5i2y2-T7wBqf>*(mSjIsFN$|j$^bLGbM>sRlV zXNba<(6lpH0s{`0$K!JpBeUEw1&oTh7umyqY1ndmjG`(q7YJ~UE{~&%xgK=G z$P9gKcHSJ!kdBd-EHzayLlFS&TtyX%8L@+hX^g{GrL4rp^D&;|YIVN35!@l-Xe;u_ zt8hCIYJ_jurvX;Xa5JWvz>CS$47DoJ)OMeivR)A}M`9GJO8r(10XX${3KmkiERxI|!GV1AP~cRX;c@9hAgK6(j?_53WiF z#8S3ou;)q=lkLQ=2nP4T*{LSbziMC$2QA$sT{e|Jp?*5Pc<~Ro$ZmpJM-d6X7b*Gk5@7| zrI&h!K)hB(^{K{|_H&Z{p>}%Zy$0FmXKe+%rs2LpiCC&tQdW7guBr8G=dfY4?CG~J zf66*K5(Sm{O>Pc$>;35TiNBuFk!!BfRK76 zB&TQPrPT&ad-fD&?Y$>Ao;yME

DIFU*Fwvw&PsdsixNYgCbE#(d^=@ zJ&6K6Ah~Ftfg*`gDEL;`xDF3udR>IR^%=_YK^Ho4eNJ=Gw1X>6TP+ zygb&$dde)f{KfG%PUdrl2ma4r7&R@q;w%_w@9668%P~bN4VxFNLk^I( zNhJ1m_Rh{5v>Y;>FiJq5kxj16xFH`Bb>1o?gN7yu7DIbGJBJl(CmG>Ed{WA1ixsI0 zCd(o)m1S!*wl-HZHMiRnb~-Dac=r2OVl1l3{>|Y!Y&vPmnla-lj#gElZnVekbnTbB zOjPy_T0hTezrW{};0cpwIn3oH9xg{b~m7}?lNm@>u2#zb{P z%>KBzBosCdjv#ya;0|tjC)e=_%96 zWGYMBYRvTIuKs%?A!?Ei9a-YE0=Lsxv2@A2Su<^IY-Y_{xYXHe!(s{&-#&XB{fPbW>7BQy znd0}4?mvAH_lW%X!NVAI@xkp0{28}i-g)*Q_7UarjXU?nk2nvW-Fbdj?eu1zpWc1d!%hk<`2A`ox9#S=+j_b5_Ks5;Sx1>q3~h=`qR90iSO?gZ5*`tIFDhwv!sJWW)RR-!nIICZw*A z?G_f7meg8f3y0g}GdFvFO@C|6{upuE^o!3PJbv^jH@~>3a>|szzR{VRej3eOu{fk? zPQyEt9cN}0WY>%hPCeY3u_55+%w04uXlvoD;!h~QPD#s2tD5dyo13%Jarx?`%F>D$ zr>T=?x*b}4=vUMp6_=QicznfzlZSRLRcC5@z|36*Gk5xej48!m(GB95q_}*4n7M&y z=Bh>I?Um2m1yR;V&)x(BBcq~YQlc~>GFM?t1s>*7unglV(6G6|dX%td*B(9Gzdurp zXIR)}IbzhU1Ew%@Ctln@rp$9TG`)2B`mMVL`}gmQ3Qu)35CtkzGQJ5{q%E+PMPVvS zJ=DZE`mbERLG0Iw+(&5IMXtaU=_dRA!*zK~(i9KjjKOn*gCm#m{kr?2!eX7cn_%WT z?(_Ey3?4sersG_G#kr0i2prLV?WnN0@fz!WcL%w+FLQ#4yJ7(&zN49YKYsh)#_tc= z=YQ;K|I@p&@0GIu+=u^X`gm55Il;RVKz|Hb!GCUI{3!$~s9odZg zyctGgEXxHanuDPRdL^=KFgBk>F^&%kZw<9HXW#t4Pg0+yu-?A0)gOjk2)70`s^EXP_})d;9U zO9ncH6xP5lU!V*yivpcW##n0RX9Ofm3&OGrv{~wa<|#r<0msNn zrdBPe1-GmgC?N%Om&5?{sv{{ISXea)aA>I!@HiOBxZ`z*9!4Tz3~ftcqX08UO;zA8 zKFBZraX!kL0(()KmbtJ28VS%?w`^e^M&>2-Q1oM}D`tw|6dD2ueg@kbp1;SbZVMYN214Pm+Ei5esmWKqomO?WX zGDc=G$QToI|MW@rOG{N%>=ZH?g3Jgcn-XRs=!3{IPe8UZ<>MqRrD^U0jEyb2122S| z)fJUViz(m>wmxz-W-9u5d$zz>C^Y4hV1K-*XTJsX*t+{q+4oO9MJKBdE+K(~So#7O zOB@ss<_Z=T<`x#n`3D6i@Ei|1N?F+{TZ@g2+l0j;{OC!2$;pZXc5HZ(Z2)5=l0S%g zeNbR*!iN2~(uQH#g9%vH%MTOR$iB#ae7{~@SyPqch>!t}QMG_%VuG7SgEr*Sbb*=B zoC7WN&6i}qp4Q{v{UW;%bL9t2l8=2QRW+3dmtx>Ij!6|fXNtp!sW9_WU7xP+eA8U6#2VJVN4`354YW%$P7iwvKu+QJ^j~Q--Lc z?6~s{o}S2gfac|wFFyzw_w$9)6IC^32bWMFKDZVY0*bMTF+7fZL^79;F>VPl zNcN_z`D>Dl_pb4HWo1>>abgTerRiFh2}nl9IH<+{_9!7x)@Q+^)A~>j@m=<^>sJ}{ z7yA(-<9)ePQ4SI+5AT5~g)t4w1friti_LKGx7d;?5SVZ<1|}T*O30``WFMb@iI$Om z{D_t*ed;Q&0PU590V*((TvGrEG2vkW$E)xiz|qrU84ZBa zx9At8A5UseR8>@0mgTL{0y!!cfN)t@6bUGXMuvt2_~G9^WLsLQU>Hq1KhBj@R#sG2o+#X^54}<{7YYp&6pVymj=nx_ zK>X|(@)2&%GzI^V)X#kV_ATM7;+JoqWiL`RF!iE0KfVxOHNM}jI#zk2yu9LQfsZ;B zBl888np8}8j9e69AO=yR?iQIbv`~;FfB5z}@lVB1pZ}0Ong@Sd+?IVN{?z>XYy08y z(z3D>WqGNKAV_J3LOzD6SqcvcMEZo>B;+H)lnoG@5gTUu{HwB$NuM}>{P|IK*K|zL zUiHZ5-#_A?Xn%gYSWCH8ekPk zPmlO13mK*e@UR|@j2R`p`TFhy{u}md{BP>NetEsa@5-ld5AdK{U*G@s+lLSD&K4az zLL8+Y$&YrTM8iU0a!5eY)BQ`7n?zrKC<_T#nE!eZixLP_qyFg}SS!pIaYVZMN*3y9xeP7}d&W1DHidZi@( z_4ikAU*m7E*Ku#u-@g8>>C~UE-o1VG`QgaxH*ep(dH3tn#yoK`?Qj<1ijl-HltNh9 zaa}?#O9TT+7^|8X@nOBTd-VRzO8~K6zIyW-_8l>=)Ly)N^ZGTq^!jJRtG7di1)?Ha zao&NwW^|CoHU()SkT&Wy6c&6F4JrlGEPwz0=`YWpzxd^sH?Mw)f5H6aS<8&wN>siQ4|eu`lXNQN+=s>X(B*Xi{7mlsc; zJ$wG-}k?7%Bu$eXXW$q3bPZ!Cr~l24iA=afn}}$)5UcNT@lzt z7>EpUBUKc}lZ)Ozc?{o=p8s-YUD~r3kJFxDPsLAYkDos7%*+wx^78W1qc-YN#yi-M zF$H5wVU9qggL)^@rx+L-fFLzvF3ixim!ASQ^5D^<=Z_aFrQUn-Am<_V!PCLKOi>Om zJNIC8h0rHyYT>XlFbs6)7}+@c+Z8#Vin_LfKwi1 z-KRge`{de*w5)6*i<6y|DsnXO%kWWvS2J{pqOGN^jmstB`eZIk2RC3D8X76VTn{|| z>@I$XefR#;5>?D7;?~n!cjNBR?%us~`_A3iI|{cS+-^=ico1YB%svo1&j>%d6_$O5 zc`n$dg@bj-Q#5@ZNf|8^8hT8O#Ljwg^UkeXw{JY}oU4rKZM*XL#_fb#dgFD2bhtn7Q$=+NlO#g zB0wOntE8vLgSWb_zP=tC0wVO%E&M9y+LcG$Zj?O(6D`i)xpFP;D*f6uN!#U{SFXie zrCqss@pw`yk;Y5SIJjnd^uhG>b>JvPBo@~sX=#b&-8KNBBxOB)Z8}WN0}n4;y?pt~ z#ryfRt=Dggg|&AsUX8iTymINr%`id#?Tc4pF4HbuzgU%+jHf82CTAqr`KDzgXKn`> zbYqY!0&7Je)<{Z`*Ho!)SN_~M0&BR6_{Jce&vz2gyo`O?L>3kp}R8DcdT zuf$!TUcPWDA(2SpB_>DjNK8peN(+O{JypjN9H60rYl^@HgbrDcN5U~3MIDr)?j5;w zVPyEi(7k-s?0Z8Ou9W5WT^YU*J;FYJWu!`#6w-U+{Dooh2yOVna6@83Od>leF)=A6 zY7r!vd~>;2ktQJ*OX7l5Eeclw64avW(!s%j^MfNnd-^X93=Iu*OV39Sat4MZSEW95 z%&_f-bZ9^{h!0WDw~0=w8=WiQpkwOn8uFIkv<9DPamo(IXl?b-;ejj_p=A3MS2QjIGZ{y^h)u5rbN=) zCzYPd6i3I$Fk@qU)gY+!kW4~-)J$BP0~tE3t{_o6p-0+F^icYn+WLqdqBpunr@Oc7 zd`B2>O5q~K!xy^yx_f%Mr41*$CEd9qB3{gljtMe_w~)2~S*fOmtBd4za<#c&Argxj z=J$1Xi@L~X&vhqvanE(18)&mp7u`BMcVm5jH_^rDZ^*5Zb{!(3;zTS$934EF1&NrY z@Sp(yw=~#%U`FF%z%5VqwV&-EI`Ol~ow|VJ_cv(IX*nw`-+Z9I{cLCF+0Krv)Yk5z zsQpAN&Wa-Nka>_MsF;H^LXD8yrlh5XmM*7VurXTJ*w@R&^R_@9b@= z>1fA0Se@I~=tSkBegBQ9G6@qr?^jkyKT2xh#<;hYKe86)vEw1vmAyw8giI z+M-)IXWEjqhDLj5G}msrp{_n*ukQx zhtEsLnE$mElLsMguxKX*O;Y>|(cyww+SX5+0csTsSBbfUlLR@tqP7FadNmT_` z6~O?BHCS8{8CzV?-aJpY7_S%CaqF9#PaG77hejq8oNQ@4jn~oZ>l*S8G}oVwt>c}p z>!=lbxw$&Jcm?c@2-_bH*l`ZwB zPM?B*ryFb11Kn0GUADq$U07ai(`oz^?ewXVWA&%wPAN6kmnV2kojhUUq$zV(1%!t0 zCHAoP?%nQY4y%to5{~f+6%lxaQ0HkV!NqAwEw!y-7I7^#wfIT;sk)>4-Bzq}!`E=# zoL8-nK2mr3Zp-TDn1 zd^h-P&aNnrKf$diB{q0(@ZIP#XYO41htH@27}9#d*|y!?2)pRd2)raP+`!)&xvhcyH9t~q+_*wK=bV@FDl?OW@! zVg1HUn_cGHOr17!k$X_EzyGGFqOzEyn#W2GZuRpI2==wNF*h+2Oq{cL!Myo%XU+4* zgXvp0Iaz_jwUJkpaAlEPK3h#qT@e-_w-d!jit!_Q#lr+xte1aEnTp1-W;bb!9hX3_7*ULI+oA{ zLWuz9Q&jjW;3S3`2Ubjn;={$F!#YQbV|~|e+T!n^35zHRp%SopwcD~IFe2}$_%OS; zIAzWQ=dail6d1VC-W1XrT>$}`eT+vajXH{@s>XwuUwELX zumCSqEGWtk-LyF<&_NY;^dgLnbntAq?%9=CR6rE63yQKMcI{m&fcXw@Fr1`{>CIiS zc;V7@fm;IBuP`8y$oc|v*jc9vNW7maL@Ep=&^tBi@S!|BpOtqgGi1w_9WLq^B@UyL zD3ry!LicBh@|k%BiD99BdQ=iA7E=L1rpuNuS>mxdV6)FsSh_$i0dPo)0RNX*1sD<| zzr%S%j$(Fh%C_Jg{u5zkz(~>XgJU#?bLjp=Xk_K)#72a`(h6_)cua{oX2pu7E)Yjv z3sqsQH?Ty2RI)$>VhI>oT!jYd9c_65k;Oikl@+&rTj(MNJeq(3#=u-hhz`QlgE?t& zq01mgO~f=vnBsz!E1cGE+PG#mz%(pFgxr{$fzU(&iOUu7L?D;oGgK8}gEu|<;6Xf- zaqwXD&YjzY7%2tg(H8AZ$T*mpc_1q>CK!^{6ikgi*}=il$8Uq{bcipmvAMaKu8M}4 z7@!VABX;7F{>t?W}7395s5O0S#$!%j*H%IF_YcucIw3>hxQ)Tr738SBFDpur}K z5aUq?qO28gOo60iVr6Bj6oaXOXJ&eOInOq>oVv(;3QQ%Yo|);tkg+&$xrm2@0uBjw ztHC0WAB9J!3NU~I#F!x;LCjYCpIwL&MeWZZY#~X;6wCmU9%D+2#sEN3T;{cA(e#Bb zYu7I4!%D0s`Y9i`Oq9!4QRcx=Gw19Rp^_kxV?8QeO;;!s2!)0ai~tB6ihx>RO59>P zj?t9`Rs#5^9E|};tF*>*^(t34m(?zYpqQm+3iuX+TX74LrDc*lX81}<=oO$56cru; zNlW@>b+kOF>4FR^D}9hpC9ld4g{HU^X9mdUS|a(DJg}aO>2CCJTIKBQ;sQH7GNx)Y z3Ra2C$pBWRzyPT5cuI;WqMX7aLPPh2#UxnErE@LDf((R1QOvd<*t0im@BRb6EF4x9 zL&Az=M2o?cSaUbHIjnMYT(v?MRxFmT2``E2SB!OHSiOFS=Af6RzTaN5SDaN+6=(f$9RTvP!oAX1ZWwOtIFfT;)0p_?%lp)`}W=0n-$O-N*-tc zY|TzRv~7Dx$o6gF*khUpf}_khuB?Btnp=$P_or=B(gy0jDEjvx2s63E1Ml zIV;DS4d^zNLMBsaVA;&t6T$ugTebuQZVB3uSS!+o5u%XcElYt>QLqnmS+Hcu(q&U& zSAi)2f+3Q_qzF95&2nLJfsg?5&ej0jpWz#nRpDx(gx+;52!D%dm8Xdf0hhWm}Y3h!(=7Be}RD_6AA!$W_cU~MYL4tyZUeT^YdLF7++K3 zH(6k;r*CQHTG&;NuiHrY>1|r)v2L?>P)Kw9f7{i^JmSSKX2Z2Bl$|D zN&t{Hin5A~$-q-Q#F@{gL9i*#+pxjgXRVLV8V|n^JRvb^lZTg=kB_%ETymW|*L|J$ zdbfqMXU zlmIju#Uu$sk`Y8P4w8)vI9x?2RFN>%`5sah?&?dVkUDIP@!hdvYn(0?xT{qTDm_$z`x+(0uF`CVW9UKW3I=VHSRHP%I+?+ zr`j%c@o-&iJ!8faSEt$52{yPb#d@4B+(rf&e?fohr zi(HglS1-4jK7F3UGU(ilCCg@6+r-RZPKV!ZrcV)Sp)Qg+nh0teg%go1!ssxEtVjnf z3M}JA_RcQO;#Eq{tL9oyn>J&{G;8bWHq)nBPm8f8rcHHoS*Vdk6#%k1nO>>V8DOh#g+5>v3LF;h6xrcD}aWg=fv zFq$&)6Pg;uS&=ozII2tvhJILwXl1I&BEzDqprQeA z$*2)%+)+4@3=K;-d^RK$@H|7ycnmx+ZN{uQ(-J1)lXw%ygJLZu8fql7`2Zat1Ph^U zqYlLlO5{UJ5y6tKVJsvj&?ZhCKYqga*a`IUa417xodZo&Do0iQU(fzEuw+96ZV9k# z*$kRoIYw62w-8#59XEc$1o1e=*s)fYCi)u6kaN+=bgqi33c`DEFaTggG#aS?IP?JH z7H|kfCYuG{K&eHPTOqiDuB57CXo8YvNTiGn^)!{(Xm^BGaWaj`Q&NJg4>m%upChUN zg!@Ki68ab`3nZ$rfuRc$nJgxQ$z;$O3N)0O5hMdNZ(xCD{C&3lOV(PzTkr)h| zPRNB(DDbYqVZ(xxXk-eNN~7TlnshK8Nrk>cdI~<}^HmX-`Cs@c8~Sa??R?8nW$+YJ zVV4rg>x!u8)#T4-_p5@ z=_n}6?Nx%2hoNG!Mu&<4{ROMVP<@C6p(JE1PRGEbWN-m4_W=(@00aQ+w?%S$`M~ei z);8o@VJ$LVrwK!asmx7}Zx4I>rPU3M@r57~nc8mjj6; zu1rNy&KCigGb&0=TT{(S#o)@1KV`>cU;cbG4WlWkakq6E&z z<*3IfiiNzSuC1vH$F)BG{{6SlKYja~M=WWOW++IQLK&$6%2J1}Jyw;56~@z1Td{2>)Jbpi$(jvc6LsTg1_&txyp zBfbp>m4M&=D*N`e3r=Yblt@VuNegh}`v-auBknsPV|`MRnK~N5cFeH+r{sluIt3}EI zqWob02-M#@Zrtu2I3Z<82BZT`CgTh121d?EIRgXI!QKmh%KHB78Xg)blPUrtf4+Ss zOJ(DUuED`G!0#Uz>3S#oZD{yXrIg)&z5`dqm>PIn?_i6RJs`PwvH#C+z2`6V50oRa z{<$n2jEXUr7xsZxNu!h|89IONcPTzlDOHvX_SKp|0*-OU2Q&dgUm|G$ONWOf{R0;z zaD&o-w8sMWMX<1II2XXFxPb;K9onV6{pTgsQstq3dq^E=bQ%?#?AI;@Z`Ml{1_vbF zebW9aDPMBFD<0qzAoVbz3}Jr?1lOa2g0!o*_)F8rQ~)3g~TAuEa)AokZOU5Q+4$q1Zo7xTR&|8BMwMS2Zl~N0Rr$3hSB4O zBjr8!leNi;*qkH1gXL0f5K?=puCBfTq#!Z!K?PgD>1k36$&eHXUNlT;Vv!?^{HMX=c7sMo37zaZl8E#qwtf&9NTT=Rbv9!Fr z=KQNzIuqmA!5N_AFwRnGIY9E&HK^O*KnMo#Ac}MO>;XGtrOLzg9ss`oCy_~Yl*m+4 zb?289J{alR1t(V|N2SIf@kBYm{QvGc3NVN-7+dIiFSs&V${cFn1yk!E{3ibQdu0_> zCACi;?Promygi-6{R2m(HXyMKv05stLFOsccNBBTOu3yX=HR#zR4WJila(Oi=3V<6 z^+_2~pQ?`6y}Ij)AgQ!2sD(PE&bQ4OK41 zIRBk9b)vGO>d3%{GiD^1L=ERfQqs`iA?YNLeDoN|E(I?GBMZU-M32V)XgGkIyI~RS zaE1j#|9@suRaTuSx%g-9IEa4F4g$`6wVWN0E2 z?}QNU>Goz*sQ-;$r3L&da7yXP+ux#@;I|#pfx*6!ki?DRYr!B(-#xddjw|{W1w19I}3S7prmbbrcgLybJ2Tq)I*|@_Boh#J` z*#!kf$oOL=P_jV-3lW1ROFdc|@G~4_eBClwjs6=Gi~PsAV|b-Xd1=@0ZMFa{d9@5k z@=Z7e7bF8Ya^d;;1%+Vyk)z1@KfMpW0q-|7;?0U@&U7}o!qWafu(Py)omEnCqP+CT z;Fl9)m>ADpGO$M#i@(wj;>UvRd3lEl3XuXdyl8Ys1OBh|qq(I%&II~A%Gu)l2WRUu z{-@SY($=1(^_(19Xwavnw*cW6X1kS(}BfV#(ZH-^{=KaZrtIw{S{%FfBnKU7cv9e@!=@m~gE2I3+9Po1t$(gU%Xo8(Nd;9FmR{fp^E9OV@sef%~TfPdH>kuaC4!5q2h%*=yXV0#`&FFbs> z_$V^ItPGq3%i_tC^+nF$bVUDp_crmJ##=e{>)elD-+q0F|Bd=3DrV%J`SQ?|Lcw5< zN9BhPO9ry!;hvEJ^0RV~`+pAa(GsB6$=zR5)gT6tOey-;4=>?l`5XK->CKzy*XnOx z|Jr!!)62JSUjF%D7_Ps5{pLLo!idB4!o&I3K9nMy5>m5GgZ-dH2<}Nu%Q%pkiMjz! zk`Hn*ic;jG%F3E!ez4ZsJpgg|D+=O?#l7OZ{^jLcIL8hrmS4Sj1=snnU%nYAJXBa% zR8W*v{`%PxKrvyF%D=P@WbQBi(sFOb7EPrQ8#Rp2xkQAodvkf-Gl`(SCXU_GWpG=n$_kty}iM7KQ23|%(bJ(j+d5~6*)o=9AEwN{OQvt&qnEFFP_Ff!=8$s;ZKQYw5LyB-mlBV z^HlP43)0J8yxXXVDd_|3U_0192-(PFke`^8oRX53egG*zu_X6X5iCV8+?87mXyi$S z@1Hz+{P6L^r!RnJ_VjuBBMeU0QJ*~OKqNDz?5ytZ=jUM)+!iQc1{K}sL99B6O-M+B zauN6+EQcVK&jGwh8)EeMk!tkb_{lnZ`0&}oMM`ORUp&ZuNPG0)=}>Mak)xcQn|AE+ z=SY?}0v&nOO%57Gl0R5cY?%r(iT@&WjtjZr;3g z{n<}$+N0~Y5^j=j-MtlmlY0AhcX~RJp`4zXl6%?9ETQa>4+S$ThI7IPq-Nj{ktjMQ zHa0#H+yaA$!X$4AW)yNbzaY<79m5=2pIjrZvv1wXkn_|o-M<3-G=*!|Ze71|?OH7S zc55geXwPAIgbq6U>KhU%nQ5m44;gwf?qCH?9D2?b?-_7fO;usr;0*OqXfmY@)u5 zNyBV9hG2)5F3;>EqX5&Q}fKui5~}~{)`7BS1w(;eBmC@*sk3W z2~Xa>csb@0^YX>(H$nxy@;_)7uZ>hCB;hH1D0(KW+?ad-uR3i{!>no`Ng3@2oKTCx zMItdGWuXvCPRUpXGtFR2);1H2WL{UqEp5col!{`p*B3(zv49{He9}*AXgVdqc#Mn4-JTD<0f-|bInM1** z*2C&Nsw6b@ry87y#$$A#N2#!%L5c7U_edp&bQP=={n{^di~H!^u!%i;KqQWhRusqW zuIOIK!Sr$=-5r&`Yj@~gc_&7P1ym$1L_I*|Ded@fNe|IY>1%B56?Nl1(cQXTJ?Dnn zfgo3~NU><7s~2_-UH$bnU6QUG0*8{XA`!FuNY@SnOed~u05qUPcIVFBd-jHg;Sr>L zkvOgdL!Yn!JcNKypv(21Bf4nk&OvT}E~$%iuKTRC)mELjSu|(k>3*V%d9JrEyFzj< zACHO!6imD~``jTRrXA5Sm;w7csWc>H*DksAaNvZ=M>}=_EJDU|_FPS0TW1H}iOGMG z5QDD0uU>mjbEl+i^MSrLpwD%7wjWGxIae69ACHM*M-pN29i3A#4gcn$40#M~581I} z=PqP@7@XeZL*T|NfHm0(KIKSZX_vwqbRJP zvnVnGQQ*SyGgoaf6_-=Pqe8a^L&*@Njygpd>=w_5HNvj|G3y$;np@+~h+3o1Fk9N1 z`tlaUcekFw+prem46C)Jqbxk8`e;SR|H=Gy5k?M>0my09&6Mtiho*r~Ok-CEO``tFpCRcD&uQgkz`v7?#@ z%`Dg-8W9#7!4BWm@Om-EHYvH-4=Nbo?=68_w+3&+cW5B5>^62g z-B#BqZs0c7H=Jo}hMj$DTQh9U@dj4Y>9(}cX1Lxk+TK!~6edmy4~GxV2@Au+i7-}3 z?XN2_CcWr#A1E>eMNmsbnqUB+KYL*S_U*F=>i^H55krn*zHrwvb?Zm$)4xH#K6t=YUcA{1;54c)spxcZ$pWMf%Z`v%kG zlWVj8mcT%8n_LefxP^zUf};wvGTIt)%vLnj)e@()YELy(CHvVgm@{YI68BwMH4Ud= zPhMMFa-=TylyPlsV_jM7YN#~`t;X3p`iF*t^MNY2wes~2sI_NYMw(EdZrbc05CEz` z7sM2b*}Wc`7&axT`Q({U^VsIMDD*fwI;~peuzX{7bv0f^sjjZ7imqf0(&S5K=Y)lx^7P>jym>RR>|cW7kf96O632tFf%A z>d4ytH76j+J{GuaC1`PWCRQ_CS35iSWRzC|r_QvzvNY7$!FBagYp9q_pKfhEZQ@j~ z9Xms|hxi|R6mJN6;Psj&M^)Bu*tiiXf~W`#LZh`aWE)^I=~Gv1*}gT{ujqCR=!%AvJ54$V zbfK#2`i;K6en=Y%jP1dD#)B^Js^VjiwH`ZqQJP0T=#q(4;-FnM^cUF+=) z>xB1^lcW*ojnt7@n4^RWi!yU5{A0^0I^Ay>qG2P7y_Sl>*Wyw zu^6<~38-NU(hCmdlG&X<^#7i|5Um@8!Q~UG4=pNPSa>&i2BaRSI|;!q0%t3i`mCKI@>!5AO8e65wTu zVUzb4=H=kItem{GE%50n4r&-B9_oga`N1J!2l9wqW=?)wNXR-J*g3{RsY%Od!Qut; zT>SjjHbI_iV#&FoNCpJfv#XLyt4E&21sKXF0S-ik;qwl($9vfifG0v3Yp7zc&jm_ueNOG*aL#v!!R=dKqfr+_xtq+$c0Txu~sjE9oTu+z@5SV_BMifkK zV|p4&c9Zas@Cg_crOnAu6=k9lEM0+0qAnrgQenpypR@@+V~VQ4fCeZ`1HXpA41v0_ z*v`?*c~3#GE*!ZLsDmq3G;DuiHTfI`vWiDK9y=y3Uc8b{Ve{1V;OwnXU!4b)2DyI5R3}$Y zdvT5-3R~al(a|x{ z;(gooAvpvYG?t34r7~5Gs%&YX!lGfz4v1qQ@r_!jK;vncm??1BG&oJjV?aF|`l~R} z$=%I8F@+855xi^7V;j%>gpUy-jY>(dJ+>Fwg~J;aUUVqX(HqFqXO#dBr+JFwU`K_E zqjni0-;<~eo{pvI+SJkm8>}o1xr&(00V0|pQufcJF*QsqCx;zA95&g~RGm$O&V%yF ztJk=>Z}rAB$C&{-NM2K22N|3kx|f$s01}5)!#>(BR33XUn@1`4Uh`pbFu=u;INCVw zlaD)@#!@x2aBlk|`#i8}f(2>kP{>E{oavy zyannunWm^VMnCWM*U#TR70t2GRK{#FBO>=jq(s_MIVJ+PXEHb({nTrmAs?I$sudTx zyDhMu>)`1Llx+%i+v$^#-NE4v)N_RKB9ywf*FMgU3aXt};Vv7%>0V9(;9brRiwc7? z9Q!k-j4I}7j-Ajg`}XDg*Q={dbd<5V*^u3aC5RVMl?}&dyho?9-)BrQP(wTrV1>J^ zadvcZUFGa*0fTRwR96G|AOPejS;kxG@)A>bw|%@FAB{FdJDTjSGvP^%!2Nir_nv*p z8-RfgJ9Dn)IIH#_-@g9%^MbR9E{EovwFmf=;`miGC8G&RZ+?9J`r~!#WW%3&wb!{p z>^eHRIA{W4CAb{0XL;=hP=9$%1rGy}cdE+nn*$0c(~6{Ks|J8@hY<&b^}O zDWI23y-~ z|K^91J61PJ{AyFB9PM4FviHyEv^jF4E9{myyXsOf zwsS6Ii|7nDczCpsSb#_WFY#V~N28CvZDbdyS$C~PDn^+mB@fe7BY3}K^V(E&-E^BRIxiO3ZTpHkJ zgqNd2ncTHd%7FqD=+gtQ!kW2A9b$EH$kw2stpQO(U@NQZ;s$EEDm*fC@8SIc zfm?%s%$a$32~AN&9oOgRX{vIWRCrF)ar25L_);S;2NZ>y^Nz_Y81j-=Rn=$(5mhi+ zTI@6JEJ2;4F_>lI5#k@XC2&(}`aeL9@`?s3_JFd<_V$hr^C1_) zW^LKB*&leA8JX6=TvhvBt5IDB+w7F!1ubiDnc8h5Uhzzh61$FR|c$_yJ+D& zXP+6cyE9!9BYm_)?90i|8I{I46aua&bjm#gO6$5uu8p=pZvl z(bup5NV61qqCizJydlu@aFvrYx3;yhPP1aNvDR0Vm)9^c0PIvj&p<^^F-t*GUPemWYOm=Q2tj&X zY<4ExJRMM zB?Ac_g#6k@o7nt-;IHuHKoWD_Bf^Witd zH4RLlxgxcxshNd=yp*(bstk#=bec?xw2X|jjH0QZ{chl#Njc5p37K-DQjt$o6G~xd zkU{=Y=~`iE3UhN~na%J#Mo-Qrt^{#sVq$7)Y^;(cg^^B|5|Ne^moapAm8B;mA&31k z7J9>>94yN7BZq)L2);(zB9wqpfiR;fqE-$<{JcE<-$_t>vQ8XA86T6^@6mF~nAzGu z$)~6Hp1_dssMt6#hV&1VXD5mi#J~h;v=UcMYG7_rY8Gf}Vr*onr=z6_)VUG_wv3Df zxQvq)?h=qe5(?TaJ9Y_6NJ)tBb28FUQ^0d1{4Euepo)g3u7Rvu3 zxCFHLX>cMyOcBm8;^t6Zb)eGK%(BRAhbc@9)jDdb13|98^C2<1C|N) z2AGeike~n`?~d)9+t^rHpt&(T_ojd^Q%Q6P!9qbz%fQUa&bgh34;chJTvb!Y(8S!@ z-pSp2Pe5p7%zkV#tQtBqvj{sCC~&3a`STx)tW7Pz;4Tvs7@AO3i{>RIE-C{4x5S1GBXBk~sLr4052c8fyjD5|Jy1JZ6`>)`C}vo|m_A_nEX zlQuRP!d{SHSbQMkMa-h2laZxqzL@}V(I6NhL?B@+1i4^CMi1%QS<4Y(Bgczkf^9QtRCzl>RLJm zM#Qjmhp-F|jU-4O@$m%Ni5N1Oxmks&RV^R>}#&%n^c6dp%y9h_X;Js_V;$gc*6p|mkU8;Jwm0;xsGsTt`d$;nTDuB}(E zuYGy%Af#<+XKsOma{*^gYGwurjTBRy@g~?<43J?x-4s2XE>4e2SKq)Go+seO9iFz~ zu3{s*if&{B0&&3(@CE-$W8Tmn_fGfZK2F>|Cug?xm=xbWSmTuNW zFjQ#9PJEU`c|TO!4!2#9i}rz}w?8gG1fB|zMggt@Wd}w~NJ>tPkNeOPvJTx0QA5LT z-`Ce(j_O#On46!4O9kBGTiX(|P%bVww_T8gf*c|-uZej2s(f?iyd(8KV@^4t<`p$$*6u!sZ3 zp$AX3ur#;u{RjG0+BF#G=hF1b(#o@?wnfV2CH&&z!a~m?^~$rwmD!cGpV0b>dTnuL z^~EZFe!dk?F?;*Y%ED|fo^>9-^kQXx5gt$1SMRMa&nzzE=N1-P!2UeGC+0YC8}mJQ zmIe5&rN#LLcy+@3vow%&j~s*@~gzC?1<$?8VbAK>tgF7rd!ralRW*0fVi~d`($6hG(8%oE-#?8LEQhV~6Kwm*DVD zqeEU@UYJ{erpw3hj0^ZFBqG3F7l(V-^Vx-kGhlyybqPNUOvh3D7HAv1H0uDDRs!v; z9QkkoynhByxwtStGl!q+03*wj2e$+5EJC229d4{F&!53lEiU4xr{`v8ar1}qEb~h< zSA{lc=S`GUAtxU_g#)1hcTGK+o|&1Qn?HhQS;Wu6BO(uxcBZ8eJ2KJbrOuvL2GL|015R5Qt}1+rinTB6O&~jJpPX7cMwsU4z5CE{ z2)akpZX7op`22hso^Juadcz-4&-(u~Q~ZZ|-bA8vVrJY3%A7L32B zXA(#(SoO~>&L1Mo?arNHI5L>ueHe{!WD{^;)3{mKk8<#$3;5*`7wZ2Od*0+eGP^Y2 zhNpz%yLJ1{ZQNbVDDEE9eOPz!+2akL!69bh*%$CDclSaq_kV*ulQ1}p&%@5g3qwLh z!tFbE2p+r-E<_74J~=TtHI2e>c0Lo&v~tTAZg>B|o_|9B#{V08_I$DmTT?Tv8jLuE z7-Tf}5pd;izC@=G^5uLge$&!}G&slpFYuY=ckmg*lrg?Kw*coGITQK7>K%7e^m2&Q}w>-G2plbsG|)2quPy?*JJ^@c9E2#*cAN=%#0; z0_e&AN91!Vx{5u;)hy309Kh3qCCGULnvJx(K^#bT8>b0G3WOgTesXg5QL7-h{J$rk zb&t+3Pd(B09iLk~0NwrZcwl7c2&Dxu`VhDW`h8Im{WJCe_lO>iK5PqD!T$;Q95A{# ze|-1mF1Y+v5!`YSdQ7oF!k#FW5KwzUn4>tyJ)nE^@X3e|G_v>~lFv*&_=R*fO!cd| zMdI+l-1G?$N?xE}7aaaS2GEuSfjLqm1pCkbjC>};?CyH*iNPdJ;x~@|Jn%OHkOK$r z1MY+t7sVzDO>oftvHMT@_2~aU$Y)0DYryTv9Dh2$P>B}-*CQ?I0@NZ9W&kBezgB=4 z{P)N1q=Vo8$K*4k&n^@J@HT-;v{mAX)cr-m_{8ubR6D>56Ssu6otO>sIsYB&+i%Y! z_B{LoO)f(xzx{?jGd2>@XEFl%?9smfgVVy`XE(Hoi?~bMQOOZ3Fw#QNse5~Pc&yhG zPC@mR&#zv;%6rX^&}Z8LBKq9^Ti46RrpCtK;b+!t*b^%Vfz#cM>)AytFY4P^00@8L z={0<7tO{zF0Dk`P?Bzf3Gs8>N4U+&rf1SJg;w3=QWC(u7)l)arHPk%%@QZ%l2RE%1 zgjqmxoLKsUyTD2G6Ra~qR)p8N3}1=`7S3$`^}p!n?B{e(p8-=%grA=g;pbNXKSR>0 zuA%ZD_}S_D++qc~|HA{DM5sD}DxQlMFW@dw5`*bFZjk=w&}hMq{|bIiStUW8GdI}h zlp4l^wZ#BGBee-KB_jEFn1L*ePf$)kDFVR;v=dap1Y!|kIj#*2p7($WSVAw&#U;2K zCiK!=T}lV|83+HSE|V<5f4G*Go&y051b$6*UC{;s&CNuK(OiVfav5PUPITc;QbQgb zvpbNwJ}nTKtS)jJhcqNqGJbv z0v$eaV8Xd@5sKcBgRb|Fm_jW7BB1drcp#vm?*P4q}L}7ratYM<{l>cBx$qL-~txqI}p%Jm0fwwT0TIP44E8W>9Is?~Aa1l@m1 zKyy5qx>^i;eQ9Y)c|p|%0!@w)J_E1NE5!@IVG|Vw$j75{91z;hp6PSI2;~f1xO^cV zXd#P>{}F+nLkKhl5rNJer+EBmYPh;ErG%xpw5U8^!Mu`yKr_WYUV&SUV#56kC_o@$ zfOAl}5;*6~nLZ~B#^q%1w*1_MnA4D?8AUSVnxQ*pVi zTv`>8f!2Ps1h+`VgjL;86$phnxGp{jn_g!OIaOHC`NK-UKtn4}#6aJh+hCxfmFGVU z^w5*hvGn_tWA`2rdwCKeXy1Y|T*qm1N{sY1{QLrOfk9tF>3)J<2P+M8=>aPk!Su7) zq8L*7?iuLp2@v#vCqU4sv*-Q$_tHl)?ciISZX;Fc?uMVJgg)x<@zfK<7`yKo5@MZj;>_7`j8~ z{CV@iE$IBoePR5@om=U*Dem04n3o9*G$sd^MVp)4jTmUvn{ba=OgMoXAyZFK0gwcU zG{DX?$OwU6pf@=C2;NG0V}pT)54VSJ-bjZ+<(osqR-i{l;oIniV>fTy?k`HuOv_?G zs7UVquFKm=FoKsLzKZcX!DmpngOnJe6oYiRj?>5tVuCPik(ckL4w9qJptn*6Nv>bd z8l=5`>t^kCDlxh}mqxFp4pIa2bmInU44Roim!2JS3}Mi`$KZ{W#ptmMUsng6=!g>` z#PP9XC+%Q#7#sBoy?WzUpU~86FnY!{uB)g~XabRg-e?qh^~HAUkcpc0ce`|lnVervv~}yz-f#;ao_;%AT?Ao z5e^wTax=6YvxPy41a!~U-VFkpo=8CFT)S}o;-$U|h=4wSxjiAHqd7StDGN&*AK$Z} ziDA;Z1h-N}gcw1(2B8cNjf{f7^_UF|Odz03&LaYP2W;2C&j7%KE|rKi=sAD-T7ggJ zMfCApZ|b?tXD@Z2KBGx-iSgLP#DtVYx`c#i1VYmb_dcHkOX&JSD9J)<5~x17MkcV; z?g9XX>7nbe@`1FGK{aE0j$Ha9l4wC-gjV$hnL4G4p#@9AkP!tRTVNw4ngJ$n*& ziV8rP4GfwAVbG~gHdbbqPJS_o`(sk#=nw_{#sl`_!>?z+2ujnGp&B9NIwY&&>UT9X zHHAP?%mxL0?li)kPj;O=+nMKMs-dc;uICU{c>-FUc2S%}81%{XE*AI+0thWG0 zu9Ho1rkeUDIP=Y>h6avFbtg~4E_wXe(G%&%*-jik0WfrsnW6-=sF9Tx7glqRh>ea$ zF!Yh9`&mgbwNHP!57j>rl|K}698eNgmj?X_cjI~hh7Pc(JK53M(b-kEN7DekwQV!d z3Z@2Lz(T{z20D*-q<69b(9njpHa6Fm1t}Ah9%(TdtH|gm+&-GXL(7PTu7VrwBEpR} zlI;kp6e6B3tpuKFKYR$`&_~;kw1t~k*Z_5%Vn;*BDLdG@BOJP&{77qpqaDr(V~SHEg{*ms z0+Y0gZ$v~`_}-?u%pJeXNP-z8=pikVAXcME)l}80Lge_KY;A*WxUIFdy}j7M)ZPZv zZx?r*Cyke<8{n1>fd`MaX0*|?9&Sx@advZY@wCHfk|ViC8K=l7V;mF_9J;4rIvs3P zz};mLUIT1__65Q?K~F`(US-w6$`(y{X!Gc70_?iAwWaw`ON_NGfOT%}CaN+LQu6BN z-oEbcE^)Q(&1o$x&CPA4zOEjgzAgqbJ9&5oM3pqva4L-Q%C4ayA-;8wv2cr1hDUJ$ zIZ^ztsykdUBd`llUwNRS$qa22?F~(7joX^by=+{Z+&!!%Iq47{v6)NKG5}DF4EUyC zQv(puu08?Yx_nzv-!gJ~w%uxQS|}@;1%w9p)ILH)bk*V%ZoYt!&LC=FgrYEXgNAhI z8c(?GvuLQVPp#u@sK+@wx_WvV!f$~niT;CO*YgSRimGf(ucK+m-m^E@j(|hsfb!i+ zxm{5k1WtY55Pz?lhyDy?nA&A{kKSAXAuodj(v5;b@MRe+T;+jK=vb{&Qnx`vSBJZ} zd3!^9X95ikm$%LGz9GRGbp#r^t}H4j)Q%qjNzfHJLF(gB(bZ7bat-tY8rqSZ64SIg zF*`FmKR2ICFb66r7(`g>h87MRNwPdCMmA}KhCW#0@8KO_1_V$Rh8oaK&ET-OG9nJ0 z85ZUauQJ%cp|y3jH0}26@u<413juayWnyL{Ih9TDVLFJGMA03YLSa%?T3|>DICMP_ z&$LxJdwl}j#gL@?i-x8$4~x#MN~xf!sz{Cq_y>m;0)^AU+t>5JbrpE?%?bSDsj1mH zLVg@lc4%V6KnowEnhIDws7g%r+Y_qs4-f4ai-o@~hgdA@a~_`g(|mK6p+B!=Qe4?(yWqk^Fz`cS*92!HKLc)q6*9=W5C@m=|F3ZCD{YM&F($K)v!`<&7(9m0)dmoRF z9tuvrKRX3WHJ3q1F{I#-Im7{EL4hK{hlLdZ@YuO4d4q;d3X3oY$SxJb0X_SmyAnAF zq9i07t{K_I2#C&#)CTn*M@|XfAcs{W0@23CrtZ#RHIT+<@hnKRu@Mk&8k-^H;b&2@ zQW)k5!fXnGnIJ46vRznM7AXa<7W649Mt{spj);>$Kr}fi1qBrij*bm+&m`n}NdzD| zC);NOh=xW~G?f1WqV-J7-E3p)!niP00+K+DVeCerHWa17k%*Ck=K?N+1s3D?K}8bEj)@lTt+bL8`*mRLg!9N2Y@Fz6&Fufa#9Lf zRzXpxOYka!XFm6hxCI1u|HIzwy=D zkF`&&y22bx7^SkrWNczSR+(%wzqtGA`j55s6>n)imQ4^VzffomOIH_5K%ptqM(>P5 zQW=>hWZcoB&rHu|V>OU`PS{s6GIIB8q7Jn2xcJ0`1Z=Sk(Jljrq}1qGIVn2i%=|J{Z&KEU-W*We$&SntL1-&Gd!Xre!&OPY_1suYMh*xxDCg1ffIu?{h*~}V0pFRh zmEOrhM4;8(5dsbE>Jb8M*fETLj`C!>Nh zN6I3$ILSg*bjKzDpkq+AYDiv+1SN}rq|Dx&+`Y1rd~9?eTmk^?fdFVj8~g2K7zUrS zHwSS;%)bN{5CI{Y#*l980e_}r+PVW?qrQWciF8v;9Tt_y1&8>T)f-UIv$FH-+{wei z$^h#J__GB8f93)FnGD032xUO1oe?oj4{7KPISmw~a_kmZz$8=_!0!?n5EKx+x1b2h zg>e)N2r&X6hY{%K>f*hD0k}YcAiwx}L_aeyv9O@6A1-_tMgvbveSJe6Cu?44Htc-v z>Sf#j4M7tiB)#w8hA9cc<=BG?tQqV!fxKW#Eief1=DmB0OXUB>KGOpapbC|dfQ&%> zpI?Ai*0E%`iV>O!Zotp}*4hSoTDG1_u)m9(IFGwb1<3(|eucY1OVGv$`osOPDlBVq ziWXe0Sqy@}%wC_s;#ONhxI=*3Mc4!cfPKb#?)8OwJot}~Z%KC!f}gjNvT@snIqK+W zYnlWj_?gn{+$EGZ#`QB3%peDXOoki?0aA(GnV6i26^Hq3x83UtuSW0$__@JbdN&Wi z&%(9`FC4;pc&GS?`?@>2?{Nz#JDF-GK!l%#oT7e%pUE~mUF?MidP1UoU;uZO9%b}V z_!IT4YU~c2#TMAFckT7^_VDs_^^B`IbG$q;G%D|K&)Mb}XSY-@4R0$ecOOqTA3&eu z_Sl=4ItA^IbT`yc)l$=sv_M_YEjxQI5IZsTAz6j!I4H#@#{5V%c2i=UHk=sb3Z6hd z+j}}Ygrt`@9_c*M(Nvoi=nin^YqqqC!>o`$ljhPu2_pdI2)q%)7>y2(+d0&?!m8#>PK zD^!h@OiD=cMenp@Hgt1!0`%G0$<7)cF>Os$4eXs=oSmFq?R6Bj>|C8~5%>(nwkZnY zipoGf%NqE3z;hVsrpV)vDMva8Os5wF1VV`o=s5(r5d^_oHCXzj7(4WaH5M&LCn&JO z+0!`KJ3!Tqp@N3FJ>LDT}Ho$y@BT1at+%>DP3I*dvUX zG6#`jLp~TlCLjQA)?(>!@#YBi1@hV6-Y&zI+1?t+XMJl28(koub!{!x^E>l|tpcJU$vGC_|bsA;v>&56m;YBb`6jvxUtePST-+Msf-a-3KBm(uL5{)}w(Fbm0w>@ID_2Ekn~3V9_Wo3>BnhrKMA3Nn~Ww zWK(5!Ny{pm`Z)+wLIDS#Z{y)3kYVT`wDcnQ1ErZz)PQ_R1!nt2=ZE^?M>V#3Cvm zP^Uwz4uWQ9XdOXoYQVAsJR9f1k8Toye3k<8SxsBd&_q{GJXexkN>WrrLdVSuq0g{v z3aPbit*G#!9e0G2&_V8BGSG&rHzdnO>{b{y-d_`HMIkcSd4#2HyYy&-_i_pajl&gRB(YxFaPX~2aOi~J# zG{Rmmg@g`6&dMt!1}Lu>kk2?VQedEQ!fGOt%KBDzX4=vO_?bdBsEClYgd{G}1fg^Z zDntlnFT}+puI8mnz%w2MpCrV`K}Udn(V=!q(3lFMo0Mt0fRKm;P6{WXBPj(9lT|de z^^EnEpzjBIg59DW1kYThQRBih8O`cLkvfPq(zMLi+vYUu*nrzzr;i^5)~O1 z9Owr<$K5;}Rk_gvDm<%DF>TuolqV3@z+Y-{bgFj~TF8#ph$mj%YN=9}; zNkw&S15~0A^3q39t2}g4bs_l-ZE@!=T)eO^30I2cOib7x6B!;7=#LCJJK9-Wni?7D zi!i|z1d~EyLP^WYEg&K(4e&D;6Tr{p1o)YjUCzeA$<@o(KPW6JHZeIZ2MpHKH$xsA z!U`kVk15^_2g0VQ=!JtI>~Tga;TB04x8m!4f%dZ4xuRlg9{3+9H- zkkhAe-IRU3=b7O-u@K7xZ6YGWg8bp7KQ0agQ@UDe%1{XbIZb|EPNq#{dB~$U5^-`m zHXZ?CaTy?=we*b5tpTtGNH;PzF(o6fsJyzN1+@i)vjxs_WCwSO=FFMib0PESpg!Vh)KK86^!P>$V*`1%yPU z=<2m6Ff3|+Qfd}*VIzbGl3fTp3UM1ed+yY;FYsE6LaadI{^(ybf`zg$ zHq-;(DFAXUvRhy$Hy6ABiGhZK9EairN1~0INHemsb8+w7B_syavzn%^5wuircK7uU z4v$Gdi&k1y2N8+i`nsBGDvHRH zV!{Ak15nP%nF6m2)ZyCB&C9n7RRW-%-w2KeXF9t9j32rWc{8`D;sA8Uku!PfkUqond0Ne~g|9dB>)v<;;N;AYL11p@SC#`Q_U}ORn5SEZ1b#etuK>S0E zL3~n5W=>vF8JyrK-%iwRz^SOJ4R?eQx_z8%UJtr=`TqL*ynO{}I9y^L7L%BUWhI!5 z-WM4GcgcYPd-wQydwIIUJp_rfbDEP8DmO=U_3*N%pisbj9SGx< zhYNB0;2Ap?OOlwFfyE`}V9DU=5u2ZAfNDJ8IR|AFQA!aqLnz7pE1?c8-B5GDe~Dae z?QKns>qi3D;SIy<@Xy-X`j7Whk;#ckJ#c|TkHNS!2|~V$SPy{m<;1a&@Nn>8H9>rW z$ZBqBTK%;C{64~;qZC7eFc?kP9nlpG_DF%a%QN`7Kkzj_KYCCLo(Kp#HZl*X4N_k0 zApY%_uV23YuYZAwkI%+hHBf$sU>xq(7`%F)um91n?|1V=01ZZ-hvK?~1z1;D+duXN z#=dt#A`%|uA)kQzfD#se_Up&m&(qN21CnagG4FtH|I=STq0f2GZgOa=<2VK9)Sq-d zVX8lWtgn5ogcsawJ4M)${`CA|#y{34;hpa8PyYPmHzxb@>k$T)u78_(IEpzVt4IG% z`)?`_tp4$p|IOg%TQ}bQ_QyZ|@!QP&mp^XwH-q0-Ua$T3$3OmY?bX|Vul?6={@VZJ ztNxF{wZH!V8-M?V!yo_jH~#+ae}6paelz$t{{F__Z{hIAKmLuszw!6SgYGwjf8+0O z{QVXVfBfU$`1>1we>~`ZGx#_D{>I;L;qb>l{*AxC@%P7r?l*&f?{NvyF z`x}3MJm`Ki_&5Ik#@}z@@W(&?jlaL~_s4_oH-mrU?{ED577l;>Or{rV>W*IrM5{^w7B{?qrBt8f3j)qgC0ohtpe)*pQuG#LAL)?dBKr#t-PkJtYF zOu;LU^?cZP-hA&(t42fVK5+Z30kxj9UEB_>Y76Ke+;6>-7O%sJuo6 z&`^YIczXKJI^e}%9O|P;Fb_vS!RT;y?$w7c-`4*3zrK8WyL=~g7ZvJ$`p*{`lVSeF z(YaUu+h4C&9uGD9azlR^RC$iU1o%iQVlb|S@R2Uil81+$CJP#KVz%s!+8-VmF3kg< zF&qE4fdBi$AK9QoNhI;NVFYq2!dTE~Ei5>aI3;MOhS}-kyJs&n)InbmWdvL3yQtY7 zYKa41Fr3f2#kv(n8vO}A3ETfexQ0UO`^I(PA-j;?m+$>%|x}HH=FW{7%`(l`Yg$XO3ShxVM+*p&Ik9 zL(Ec9n{~yvyc_ncP`T$?P06OV>6Hd9eUwBpm;5XyRWtP4>XeB`m%%vO%{Y1OokOc@ zw2b+DI#-_waZ?@(N&VDe{XqBw5DQlEle!R4bAM`(!6Y;>cUVWs0 zkvrD+XftCC#-6`M?I1h5rBOP|8F}Rxz5D{&daKfNFSjeDnMLN$)Hynq3wLTCs#?%s zbt7fm)BAel3N@3BlCsN!%GeVry2@ikQE_i1X(uE`j?u~9TXAp}XVH|C9z%0J+$p{qr2Tpcb|v%eE)m<7e7eN~BBqY} zyixe_?D+hw$3$8j&-q*KlvSkoOZ2?yl3T7b_8)PKvbq*wscy5brjt`js`7nVG3ik2+^SC0!EFQP#qXVQbd;*vQt@I$_aPJ)Hh? ztC-WZb2XTwH}}MxINCZi_m(>?I4NWBfQDz>D)*lNlkjQ)bg@T#9?fm&rLh29Zp}vLr+Zj$+o$$!ajuYwr;PN* z!P~5JorgDPwy%2mROV4|3Huwj%ZNN`y`mfc`mUc5&-KkJ-HoqqwJExqJEc<$gf~TQ ziLH2kp)Fw*!_zkEP=onG5g5#4{%G{-%kZqp5r!+cRK5o|84c%W z?xQ}}V$|;)Et}lt7a7z{rh8w$<9_btSBJSyJY-KT^AI0?J{5FyM{}i~$v34dw$0PA zVi9bC6tW+VRVz*CnW>TljTukmy?l^d(ql~7cI|3fw`fwO-O=0@kJHNm<1H&{vD+ix zjhC3G4t597u*XEc6s6nFj^Vn#N%iqNrI(AF-CEUxt23l(0-wWG-{5L}y1xgl zhP$4uf7+u`m-j;k4f~b*8pI8(gw94gn@OCT#a(5ht=xZpjE242>TV8`z*6awfV}`+ z=#C2-I`W2^*OeWv-CXf(38xc&5f%nzaa%0Y`*O>Kpz4!0hsCD42qPw1Pt z`cl29{~N=Z1N#(`s9EqWUFS|#o-wld#C~k?MC6C_{3`YSR7#A>96Yzx-qKZ&UqYUzUeGb*)i~eV#iwn47AzG{<=|4%_Amipb~mQ$*Po3>dvLa-2|8y?i?) z*zMx$ed^@ghYf{(nBk)~NsB2x&t4DT;d(-a^dgVyHX&&$U*0WpO06FY86FE7YP&p3 z*;(A6HTYtnL#~86Dbvu{%TZHvXujR@dsK{u8vP})1I>I{LRypV?6fwqW|7AnhriRG zjvR11y*qkGb}+M-8Mfrol5m-egnK~i(8{pz-8;qtk6jjMf8wTDigX9n-}E^6@sQ0I zkZv*MJufcmMS1nnMDCW4{3f;USPbvJ@BXUJ_*ML>-8DbE6Q7=o@xRP@zC)7N{PehU zM}s%{tS@)_W4u_d?EEHj0c@6pAFo$+8G~OB9+PN_f+_dnTVJaF_nQw8qTM zY&3rDOm7a3-Vo~0JEUzByf?eM-jh_D#_Boq3#(44$yklC3+kpf5^L)N*}J2dWxnMF z8s5k`GAMx&km(f^&+NS+w7~Bq?sTjEY2|gSK-b>pcRh^Hzqo6Y)ekbuu@>4kmgU#K z^w&&?K5uG3d3>DqW%sj9O&W(IEdx#odwT9$qPKMs*3fcWuK6N-XV{x>O*Nq*eTWyU z_#<1huJ5>Ieol>R~1T)SJU6P?_KhZSvL-I`0(ld(4Hiju2ZGHaX$h&wL>LNOgJ3M z5MWlkAcdPgH^EBRvri>WgM)F1^nO%zY~>-Hme-!HJ(*dm(k;0nAHyC#WhKSN{@m<4 z=l9ITnw^PFhAjQLR+9+F>D&r|nfrTAjY_0`JQr>1x#jTWfdk_q$qGYLZ<(T-P4X^9 zKab7$Qb*&a)_IEK@;jp|DxBZa*9M#Aza>b_w&>U$PFQshxTWpddal&jsI~8d+PbW% zY19`M5*O10>r#y5Me;way$ed1GhHuMhFkc(<3q%U{b)FK6 z6{9WRzv5>T&s#>H;w^mCdHG_3*)>lujpxa`XD6r+HDn2==yUT|2`9`sOzNeMg@&K{ z;`zfU4_lAb#Fu}?HTnCMSA3N;JnwVmOF_u^ zS8F~yeyckzy{Xa20rRoNRIN6w-e;~@7&x0>;} zY?-g|ROvv=m*OKi3`=>KvOA9wJnhNn1cw-C?gUG?8?dg&AH1{2Qjp7g;0@z$&%NC0 z*4KM#1wThb29)p46%X*fYrLs9ws38#%lwvqg4vayrA-18#{_Rs3tX7BHW?bv{%|tr zCc~%dQwHOgha+ciB$ZrsE{?5kpPs0GA+PJ09q8yR{H)dW{(&#$kLtXVoDRq0FAvK- zby(u4Lm_M_MFYjnxsJ*x4(*oPhsrnk8DN_CVkDoH*9M4L^P-~R5pK~0@kT1B0jpO*&;Il8UwGk&VbVCK)1 z&3%gf;rp%X(Q*3t>{r?4g*W5YrVjrID&}-y-j{RdXHI!$`*2sef8!>)pP>h`VyWnD zZtU@*3S$yA)`!>VbTMhYe#qXi&B9z@JgRa!OV^pqGE}ppgpn!MCDluoe7T(Gl~P}y z(iRzyusDiyWG4GhJ+qh1lRd>q?d9edHrD)eT(;$yVfzI;-V@K2X|ZqUMMWwu)OcU? zdGsk9?v!~ddn|W!oYX4s+dPrmoz(5>FHq_IW1590$P~kx-O9-5l~K}RdpoSbYd*v> zzAN8!*XIsl#`yuWmq$$8T3-1LtcLy!tZ#RvxE8RlLriE~_EK%O!F@v}{amJ724r{g zxSqWY!U?d19(FEPkm?~>UVZ!Z8kXw)d5?NhZ5~sUDkWY|W}0DIR{b`$ zc=MrAv&pygm4-&FuB!hChE62x-dc-*t^14$Ydt@|UAFOAt2b22M};Q7s&pu*$TL1o)YoUCey&$@rF(=Go*-`T)<&V|KT_1aAA>KB0SwBz_=aiR9@?c6#-yuk{zY zvBKpKJC&WDllCM<9=uZ!WWQD_TYj9zBah_bnJLRYn=rY=*sw=!mPh$~a+qCwqW25E zN&o0}=KXk=aQ39~D&tn2mA+^Bs!vlb?G-$dbI-9W9Fs8Vdd;Q3LjTlp$vc3%y@|zt z>g4WYG;w<`#fWfqIXrtiBDJHBC9d*1NuUXJ$Z=jBgOjZd>%q(FT@ItlUq1VvrIL*u zs22CW5GL*YvvBUv)4R@o59J^a$vH`;^yPMM~2 z_q8P(-?d9xT-hI-Udh#aaBJgysQ1K1u^E55#c(x*DRTS$=0Y6i^f3c3?{I?;UmCB7 zL`#Pc&E4cqeW5|dcqSwzA@Y9ly698$XpfI`Ps_>Yt&^x)4zBf(=v6)WHrSUM9!&N8 z>1pK~{i)l-I@=x$?RlKf-QCr826|R+Z~xrk_mJn&c+c%zj~&dCT_=5W90LZWb@N4f z>$6NAO()KTd%KZV+E+~vj9Wf^=t|*I(YC*thk?&y6@?%G(sA<_lvY_`@neVehAJOsF!W5Gqw{x8& zdqzf1t*$9A6kY9j^R$WXHIIdzLsSGO$H+*sx`?Tve_ZsF(?SAmCQN*D=O?lhe%ibp z)d(FC8J1cQsZ#f!4Y`pbJFZ$jvh3l%^X<>BxlHx3cPV>5Igut_8?tselBPgmkSBU4 zdw=4CuS!oSu3X!+Jz-~U&;_cCF7)+HoE$fL;@;^C(1gG2<G$qSRpVW8jQv#0B>6f0pl|D2g_GA`wtlZa(V{=sO$@?Y#6TuDga{N@Kdmr8z7eD?%Ov<#VBmR)ByFl0A$<~LBlJl3C z%uhJmHFZS|n8#aPbfllB*`hu-SF5C9rq)jJj9d+eJj9rwk;Yv8?QL>_FC@(_6Npt=TL*Xnr^#hxI**8y& ztvHB&^X~lqjsA;Q2C0ZQuaRT9L21@w#fHmt{#gpCLPgr)Zf-KizcKQz9)2%JF+J#I zKJn$qqhW?0qEr4ssu?Un4s0D?9V$H1+N*BYEscEKrTwJPXf-6+!eM?^NPLy!c5w+O zb)_E~Cn{Y*J7sI@WPEgYv{c01=On?t zFRbbI+>jmnBzv*o^d6?SUw4K2jZPh*?o`>W-yPkjdWNA)i$(FelnR#R!7ciqOr}!2 z-OVo#wC#CV>{{C`K{ob-R964?(`x+#S8vMgIy`zqom)tlg z|02dR>qVVe`kNW0D?6IPcbIOK?pwOF<>=wo8ziA$BCD9E-AF2rVBaqYE;XyX{A6}3 zjISz}O5y3H&k+Uc4Fyr(t~9;7$u?YcnXJMdJI6(8mdkj=gM#*X1F!PcS54va<1VAP zc0-JqfcOS~+(uOxn$Qc$QO6=CJ>(lgZh2oW~6B7?XDIFuHi`R?OLgR+R@j zGSdmqqL{OI%{_e1X;N^XXUvOP-E$J4=OGT( zvJA}ATfEZWW$4}vbM*1e7F*-@2-f8(+*A3=;Q(LABhRiULbS&Ne6Op~ zE&j0Q96xh?W=^JG+&M9ObmZXqdzqQi>{Z|PZ=0RbX(SPLxgMDrbTj>a*Y0cP;k4@g zPZI*o)tr>g`^-w?I&ZX@8ytDHPi^3qVEv;#=OZj}?dB1rr*pm>%u=fvsU6;0ggdg3 zpcUpAVmW?8jaKmPgjcB+rn|`S`Jo>FljQ;zIbOV?*|Q1rc_cxiU)s4+d{M{qaY5?l zb+`RuyI=cPA6Spt!~J4J4*T$WzOHEY6>*cWs&5za-^nwpK3Tlon<*cR#ge*}&K=h6 zdwslz@vWGZl3&OVFU^y#lgY7xx5~!**4PyHzWq5z8?c<;Q)T=_&#ETVkGYBT8Y@ll zCD-hXt(052EgxHE%)$#h;(VJvaf&6W$Q@p$i(`NU)A`TG8ALQm&(HfxA8&T;6Z-az zPe^|GKu^Qn$jp$B(n9nAk`Y(8%P)y@f%n(;w`20j zHeO^}sZPof+&In`!C7YeN4_&vTnjF5lghTqHxjdwiY%Wwb6>WXue4AeBc&6-)uB*{ z_3F&7e^YM$QSG`(fb?sJ(8~hJlB_+ibeGPvR;hd3SZDBE4ZsaN$}L zYjtU{VL6qGf7b&^EGTLGn+)UWo6jQKA%aZR=ueO|c5IJ=wD@!aLc z*On666%S%hK3={0a#9g{fs>)ft^ea%jYfFcnjf>D>Rmwt7ovy6k6D+PcVvW2_#+s+uj^gxX@RyWPE6GcVTkBzAkM21ZskuKsrU z=X*z&7i_O3R+W9?`tA8=$;jiKoP@unOWBo?UDAw!1QgO$RCX^Dti!%hNeqRrg6n7<+SO z-OOb1^&wrZyXS{!tUfBWkcL=j=-um@?%Iv}VDom<$)AVLYJ4KmGQ4B*&EkjUVJVZ+ zQ|B2DOX=(yPnVD4Kc2gZy-;uBbiK9JW6eIP;3zi@71}2~94<_8T2IIemMi_dP9EM_ zdpWP+=Ck9$$3q3K_}y(}d7C!>D8F-edYW76n$tUzZ?iK2S2SqM?BjWi`_C>}nm;4G zOs_xn_DS>gfji#L#lvFa!rt-PBmKK>_6+AJ-Y`03sl(E5npic={W)*8FV#sfxZJ7s z{YxF$0qRBiBKP__-RviwqSxw4G;;Q&^y(3k&I^`CdxEPP$)F-1331P9drkmT- zGWpVqc^qa9G?X@t?4HpauVd|(p*)o+aHj*aRl_Qt@$G)<)7qQqUAVBLud=icO5M)C zac#uQogDj@4Q|Pt|OGJx!Z(nWM67f@G>qxjBHVUS9OL%aDGZqFnrly3pLg z@|Eo_L1A`+8sEMbJY*x&4=Z_Q?*C)9x7h8KZ{nqoKeXhzE}nbfCh5IwG4u4{9sS~k z$9ELW9p1hCl9aE_%bt3JvnXtQ!twHc4Y5GEkD5oc1=zkcG#4fAE>&1Z(i9wY9ewuD4%k#RcAwzR>DxyR{n${-zDx`{;O_Yt?P0>lGmQ&{B`13OykroQ{yYwy1wsIb#Zze?ZC=;koWopzKIupk763;lCAKMwo(Wm z`{pO~Zs_8zNPOq_Qw}z@%Hf;`b7}8>dbNee?e@e8%(a_a4`;0=&R-JWJxS*3zVKY) z9hua~LB}EI*Bm*_=gt)wnC++WTlc;i(4Trsmi^29$@8m5(fZ^cgD0pHL@gGX-#p3J z;mj8uxo>0Zz;gdxi_~lf_KSFg)iX}nJ;zRS7F-{sX%-Tk7YI03c*>35j~DLbohZGRMmJQ(V1^Zt{6PKEiT{|cr* zRG>^&yfd1aO1iX^coB6zS9RJGMd7c5%KPp{%fdP*k5s@lFi;rp5(-3`JbvS`n|JZ( z*gcX#zD!-&!6}VQeEV8a#t1aDJ zK{d+@F1o5e@0T%25$vT&K%w=lRe}<<@mv(LG3-#rRL7RsP}1gonIx2N1D5+0k+N#4 z#15L{S&7>7kaOqV(mJv~$_o8vsjj&T1Y%~Btcr2F4cwiQNwNR{s+HsW*dw^Kk`VnX zs|oD}apr*oy~Y9%lUZZw<-=yX6Ckt|Za}m-jHL{(V z5QFLo3D$^Wy;ifo@~LS2`J~8GejX)5pmn7^C!vhLzJ7<2$c7`;3gmM5YYw4M5OV8y z`wN|l-fay8;AM`Vnd?g=KH+G722&36^Mzw>tb{=k3`bCHmLc%(A|_nCN&!C|=M6V{ z&t@55;jCUS|0-G3)xh7CWg<++7|JDmS3{_|CvLc*b|pr)cX0|rO8x}l3JOg@kulOr zm6-Wqg-Og?D!|6$^gO@hNvJ#qpWx@DVT8v-BvvF|-#q#%w{!-Z3w88cOFz*t$c5Sq z>+c-U!UOj~Icf$vt+BO=RmPv`A`}W+Piu~Qilr>3vlRbb@8g|S%z5>V7SiP$yOd-3 zS_@y~h*+k?jg5TdwLk_HX0h(%#3j7Rx^?z1FXQy{%zffSf*r5%fxe>IP#~>6w%QIK zIxqTlv5>F4Vd0Ify1CDl4DD}n)nCG4YNEtx&_yUjkZ9my3MyKLVARcPuV1*ZjDpL9 zDUCUKenk~#B$C26ZD#U8s~g@lMUGgrq2uw*W#6V9TnGoX8MqsW3i4m)CVVp8=29~=Xgpp(); zykH?nK1pz?7g!bB&OGFOhBJ0`uec4g8I$UY_)Kuke3V6W-+unW_SQci3zAKhLO7cu z2_x%N040Ers97TqdT&DLlAU&~l@%o#+QVX)xl<%?6+l(L0ej1lI&#QCky$Q%RKmqrtZGj%ID6CWiEICn^EA@e+7wE1} z<8)m&6lC?Xv#HNdtwd9&pItATv!SvzD-y0IM*|c#M@5W+-S?PCI6I5Rrb!qYJU8P zm*Pr8`^}GkO>x>4l9D7H5EEVhc7){t7nn0cNpmsLoM_)6!5b!KQnVNddbG%RR4oRM z$rya446fjr`^$fD=QnCw zRGA=dBY?;OK*H*bLKsI{5s|-y1QWsu+TtYrrg)BxKroEma!{ukI@b0(J>xJY$yly9|xM4iz}29RVr5Pssl^ zKyOU}T;;gQD9(S|@koVxis!$m5m)2q@ZXE=*MH&BAMoh&FSl{;w^*;YpwHpaMn8tz z-)@+H4X^$itoGmU4aF}3@inWl=#v13bdm2i=2h(BtYcx;6@0T_Vw8AH9j5<(?2??7 z!EX1@F_c|!)&UBamN#2yDNMuEYiT#301Y<`}psTy% z$^w+F8*8vd>>RUA@w5Q&dC@u;GAH5aDS~xEKK+)W!JZvO>VZi(vaixNdU1U40*2jT z^f@Y{x(E7Ew{M!=Wv!g>+PfIxQoX4x%rD8Q(spQF-(fO-3Jq|*f)lCXaq)94gSloz zxXCDkx}E`0RqHd|r*Td$v0W2UU79N>R8)?79SP`vc!#w-+G$*EQzkj%;OnS-!^_?> zj#$%}B1;APp8c_!u{YUNHZR!)e;LVnM7I?~ z(a0t&_5k$d>9%JGl!3nbXB-;;9SotZ`N>FZ@p8E!_)0NrQ-1v@yC^Q5Fu<#&N1Pj~ z0{oe}E{#*nyKHIi7L3=xcXS~L@XMwq>fp4L%J9wtzpm%l!MYos_SvBTK*fb);IAkt zllS04N*$iJ+WRs-7WF$-Tx(6p`OUbPKyKtccEL^vtSU$FLxYaN^rbqcvh~FR^}qy& z9!Cw3m&qb;)4yH+I~%*V1moc?45k&9-0N@nNeXtwTVBbx_CZx;I{6c&rLaE>f14-~ zPpyJ+s}SBRINzF>BSF~)>r4YdMco8LmMf}3$=aZXNcsO>(7n@<+ko5^dOk~IYQhO4 zS`Qo(2D^F6O+#gUyWq0jNFWHSh4j@Ib9Mq?a5Q)eM2y5J=wA8nI}8@YErstHP(o=l zK2>_>)0l-nvMDl&>76o3-e(-QP-i*5VvvP%VKF`m{)pDWQ~{#7|7?9qww~zd^ZZrr z)1{BbTTphCb<49Re}k?kpb5SUh5Wh<6A2yiA_8j>79~%<43NU_t`SUwGv@s zb=RdNV#cm9pu#aD@4Rz@uMXtTPWJy2^``XQmB`}uVgD3!_B0br9HYOO#)*Z$u!zH# zSR>t!hN-d!_EG)>KwSAJ^6UI63Q|w=TKtq}yv~v*+u$;Ui7Qo5Kf73oH&v`ZNAFB| za<8g6@v|lMgmLyOy`ShaYn>v4apQA*`n5A6$A9TXn$XpSapR^@ix2$m696inJR%Ta zo+@9iERMiE6-a*Zn^7X(Znd>!iJR4uf0E&TT}z0H@*HVJB@<{8{c|mG5Q%a`fEfXG zjMM3PYFO|8#-OIXzszl{*TkFKZ*>tx-BV~p-2gbLBCWmqE0qzqTM zVEa{A5F)p67#w*ae`$zg z+5%?X9dPc;I&j(z>2WUXM528pN0Mz%4_?bSvna0ON!eLVCZn#vw`+|@;7wyjgaM;6 z6tUH@otlOAS4Q9a2X`-J;&HkBNUT-}^=uH-uA_qmU68os=7G=~Kn(+R0y=e)+AxXM z?_9SRIZ$tGFTMQr1%{&sQ`Iq{B;(ZLlpsj|0fDj#W8lo@`AE)G%aAr4N>0JBJaSa- z{-G+`rs=~tJF?2>I5Lh$w?gAKjg?+jJ7ZneBiH$Q%i!s&ONSn_KG=5t9TztoF@$CD z8UEzT{;G~pk*wdC`58;pYUCUv1Mf&K!D+TUTQ>xyGJ4BAWOn6ossShV?fBc@a;+a5 zSO}Nx;&IBA`1}=Cpj!z`ubUrg`LY0_XRD7sjrOqyWDn&%%CI?oXHcaqYX`rvdT)r4 zYL{hbHNb?qxRSprBX|LITHey+vhIPvROkUE4Prv^%`Mt3vDu4mrd9R4?&&@JOuRc) z@p}CBeKktUL`3mJMYRx|KdtnOcS`*!p}75a%8@_MPsSVM#jgw%tpF9H^&F{~F=%PO zM>y2itDCe)z;jEsr*vyo1&n01le}*n-Mt0fcVm&Kn&h{Z*dOX#I@9fg>e$M;^*ZA; zR<%gyZgDbW^x5avx!e!OZ-2g1yI|Qa$Kg93yDi#YY@1e%+NvibJR2QV*g+xxf6;3# zZ^lIvD&Id~E;Lag2n}{6R3Bb%PXkh~(Iy*sP8X{Cf_mVeD*M@>zA5>n&N|U{zmJvx zidK8QgiDIyUup6*8aMZj|5csyzQ9PuGU}HDDgq?LDmXci1WdSaB3Mac`h=jt@<%Hy zM2N7|R6E)fv-lDA|0T<<=r<2pQb{~MB(8{T;k*U;jK`I2Dp<%rS1>+KKpw)KSH?Zb zxKo>iAKjGuVMd2-umpPqT{70K;;)ZMCML;y>($MqhXe8K%sKhS-=_!2!EIEaUQPgy z33)H9UHtS;b(#5~1EFLncl7mRkbJkJA&#Wl5@!ob%R8rq!^HzYrfgX&vJKM5Y2iLA z#0Vd{XCbppb!od$xzgZ5I2Z-N)kL01HC2wqRTBYR)zVNDE(w}l+v$|5QQcqq^9IJb zD7`Pbz_~NJ<*jdtg123uwEsYA1$X8O&vlck7w$}DD8Q+Z)XNAo_Ea4D2-Dol6aR*e z65-|5i82*RW=L9p4|7m&_MkFJEH#-bDipH%)2n*)kqm*oH10vz(R~4AD7x2n(uWG; zCdn*IhaV6q9psWo!>@c>sBK`n#yytqRa2)7!J@y<6reH^)eNYzy!6N&^Bx+Y^B8wd zU@K73#ue~&d3&&+bb(bOubv2i8%`+9Xt+$CC$5GT8K_Wb>FeYH8o;s|^XtO2w@Ail z%HlpKyH=VKqy^a4d16?ClI_@km-Lq?&lrgh3p$;Zr)p!W)Li$xtnCi-yqyIhyVie! zFRAxCR(5!q#g@SWo~O1=LnLPVSal-$xrjbd53#j`|2w#7NA{HM(TT@NWbO2#;Z6;h zM4zv70N}ZXlA|EF@Ui~kOK8b@JavD){!Jb~bsjAsLTY7f7fx3@tN$REyNRxs4Jt7> zWPqLZRp9>D$h5-gjhle%mI7(Jf@7J5*+t^CFwwf-d8JJT@WhiqDu17n`}Jv5^MS`S{k8dmQ=6Iv z*_3KGCYE}6lP(=3dT<5Y9kjXdWde`)EU@;~H&CnBl~-ZSjIK98o9s8Jpji0ON;o3is!E8UJdTr1{*y zuYLjtbE$}dGHk00x9S@?OPRFgbXW{;yBIEXaRA=kr)!~#!^OEpE#G@(6oM@+>)(RB zZbVJ5!X`XT?L`GRh2n!F-)~94|9N!s^uP1wl5jv=S8wd`M$Y!%WS*a)+P_- z{Hmf|feI6#%D2c=)AB{;+7AF%7G@5;D`sbppFvztug`qon!+r+Ax?76r85FpJt+qK zeQet$ar9snnTcDo#pzwVENApJfFJq(QW@h3)2nd_c!)#$c*Em3t_KX3IHHQJ9OOs( zusscq^mE^hus~`-InKQys{t%gJdGRL*=HI>0ci%iQV$hsrN4>6b?N^N3F59sX8%xy83ebj24X)RxY zLn3v9J=!P|G&NbD8V8wp^V}x*$R_(HPeS5Z+3{9aN;W$DteRi?Ifv=#{6vNt2aLUg zeP`w{RQ!%{Pa7Wrj(aI!CA@Kn+(w6Xi;qlJt_gZo!>#ic<5&mN|7#B^N${eXXtT=Z z+-KAQ*_qm&d1v)Uc@ii@?Fg+^vIEy~8tz!AjSBe^ty{p!MQibCz0LqZV)6GTlAkd6 zD~n|Z9xnVlc_?7`waqHGa?}2q2QtZaO}V;NQ;Gxfvev_Rqi5AwBW=*wJ@Gejn-qti zSWMjr+b>=ngL=5UW2@DxM>n@se)3D7wKo_FzD^!%Q~fpTegT=Mfn7ACW_cq#eGm^`=Qgq4MU^7dC|6M3m?8-vRW4+ZdV{8II+}VYchUwf1t>S0JcAa)LlPj%jnIR2iGPFR39{teP1P`GBZ!$K>K~K zf^xrMAH|dk78H@cGe-5b7uW8+FlfmfF?}1d(zS>xL&G6CK|U$;nUU_o%1SRKifTB4 z)60V)CPE0KLVSAfW%4n@e+g6P<1KU@;GT|R!Re91lvswN7YvlYHBl4 z7Y&DZhcs$3J6Q~8{1KS53xmnmn|8gt0rMyf57DO5H-FRDO2kX=sPhpD%_>C(c^ zuEB}F8@Rj;>H1#L=4&qVjRjV8k`!)$3@cp!V{%*T0X`4i*hJqMw#!C)#sENEn`$N? z);KPCyXkout$=wv!z$co;%WSh~*TZJhz!MiCPcrb@>Q5_!>Ji zjc%Tm1rn@|P3{@#+Z}}S0|D0NkLE#ui*5jJ=5!JpF#A6i%5fG}A-eoT-0mao9`(D7 z%Zi@v+k0h}v~5~4Fz#e)6lMeJ1V3*Q^G`G8Wy&=u<(CgFtQsH5{K=GVoX+dKlV75h zXv{!VA{BOzw5NXj`H-&R{r_||&**i85ya6AR?b5qOY#@$pULm3I?bzdyK`$scG0-Ac zfG}m(O-`xsk9ACU417rR8?bSc1bDoxfc%#YcO74@p#jZea;(|csrm>hk@BGF+>N39zW3dY8O0>t zSrz%=4qrootu22s_t}BBeSTCPEBx3>uW3tAi+}f3n_VSa+>9O?0ZB0kJi}F+{sW(@ zR@}yVqm27Uq|P2%rgsK_;nnnX3|DY1T}Iz0|8?L8_$B`fBhHJy|6BaIQ%lfcf$1e( zd;CumYK~D(Am@giQy_k=f9Wk9)CD)?n1cI&)k3cGvC=UFb8IU1wtrRV`#FMShe=aI zXktA}qMGDq%0)3PRH5+rt87cN@D2$^U64(JZSTF{V$dPbO~$l`4aw08&?9)fA{y-g zxn7E7+(?ZoZ=O^0b4fc?cw$lK)@}M|>*OtP!LrQVog93um_1-YMjzpNt*eWkF0Hdb z;ZIi=C{!&cX;2Zuwxw`{W~yCUQ#Y`_;|uCvMnJ!ID1Iz7m^YL(#&Y7YatT~}t(bTj z6&hUf=F?7ZB~5!Hx|fq$MS2nmM&8Yk z{8Brj;7-m|>Oc#&(%DC(!D>H&B867Qt!zq{cV&{-1R|n>>_0qy!tw+BE&JuMIjhHG z3+NLiDI}r%96ZA_^lce1@7z=k>550j z*v8TTn33^ZYi$klt10-FSvjB4c(Fj=>p%eVAM7ZZYDMtf?` zrPCspg;X`X;&%y|YVim`d1duMu@E!O`@j84%C5f($rwjFn%O<5IoN2}u7ixn87D(G z0GDzl$L7oG^j!OrC1LN^a`ptF;)SwK*xGJ@hg-}e_h-?>DBlGe?wt&UIQ;EW78HUSYf(nwkF>If|&XZ=r9naq7<;? zC!p*PcR)A6%EIhA#Mz#3YxM(S4y7*^8c6-;@vtpBXlefdSL7Ob`fxO+(Y>#T#!6@Gno}+Hb z+UxH2Mp~If$TR+w9}bfT?`NsVFyCOhb_pbODckLoZNu0d5miei&{e}}Ung#IBJ*pt zL-%4Mf5$38sP{7&VB#dwpA>^o*N`J2x80tuH_iHv#y#<46g%u-S`!;JXxSaEv$xatR2JNtt@Y=R3A&)Hj)dC4>X3ddV~cnzq!HE~~v zfGCG^!4ifrWTsZ(IN)q3qxx;&k`FIiKcS3y+-)Ssxac79AF2@U7~kxZCRDg8QQ5V{Yzph)1B@n~+^Yx10Y`1J_+r|5b|bd-v=;k5LZQ ztCrWJxOGA9ACeQ$VeY0|$OB0S`)O#5nQ72_Ea@401VweWXnI@3vmAI9YZ8}$Hh#i*LvRT(Ft!@I(pHfYO{U}i25N+|e zNkIFDYorhj%S^*1BP__7a-;as=i#^TE}YL5we(-}hyv`Ib9KOx;_c1EKg^5u4bXAb zciXn_AZbpu{6pKeC*vO#Ok8hM8>6Q%Ps!bcXcl1@1f1@?U{n$u9c)Ag^U2VgIk&Ep zH5FCyL&4khJ`Y0Y_Zjc;rRT-!7d;Qg`H2iA@hyNMJLY@9&>~iJYdlGnr0h5=oIV6# z;9lnD)h0t89j-NM%tCM~Mn!hO1Jj-9v%_nQmoMBg!Z`9)3P=PWGy{-qHI<6hPDAAH zMhAm#D@gIY^)@ZOA3{yoA`Y>kylAxhp|O2}b|z#@vchf`X2+?k~EwOVcJv7bev42qzA{MXf^qH~>LxJ_niGV@j&PIOPJ73z_i zhH+{Vwq^Wo@ed(|*`{||XCae)=*T!Z*jYoBcg7{AB5E}p@b@g9<%X6q`JyvCk4A> z6V3Sx>~XUSO!MWY&Cik4V&Yga7J$bPLMIw^J3PnR6VSwpGh(0=5dq@o_LHZ&2`_tX z$Rm$AK4?SH%(dhA+#y%Q1ZjW5B<8d)DeraV2F9bISUm)p{~|5y9Ke7bl0X_p%3$m> zXijEujU;;@Bd@-4553~mdycLONa7h=E+l7Eh*MK`)FO2F>209z@T@S@2yO~`mBa>@ z$}xFORA~;yFb6Lim$BH1L$?@e3Z#evJnyEPcl@tHvO{Ns1LH(K!t6QWcGrZ%iWYA`HF)6_M~5Tzk} zIhrmR@v+QmdtK2uNW%W$xw0hsqki2Jln9!Ox}ZkclBXQxWlE#?84b1^*mB;;%^6 zG5ZDnHrno)4>J8U=gkI^$iyov>F^j|!DVe*Yx`8<#*N9EA4()BHcF(Byg~SO)J`lCODJy7z(=Cw-8gU&E$Ru{EExkfzF{EzQ0@g|QeC z6hsOF%-Yufh8-bnb6$)#N>PMG=KEuOVTQBQBJsTTC7@2<;aHm9QYZV|%6SvOzF(EW zs0XMd6z3?0PQe&oL+gCmUxyK`a4g`mqVy1;!`@537SRqsjkrANGgIQbhn-m<%!|v& zNmIW=xQ;oCgVD8!jVV1$V{Z^TQ#OvF%?HmN1}REK-)Pe05oOUDX zI6gGc7pWem^z++%o3aSs8{MSWC=R$2Unkk0MBr9OuJ&Bz-QR%dZveB6afo}82vZpA z;(4|;LWxlr@#6T(<{w$j!XOxU8xw0D+LfxUK+ww4P1!}r%tfEwOtBfEk4cXQyHHq z1iRP%qj~C>5Q%rFeg9m>1ZrB6K}`>MPRH^32MUqowOOQJu9DJ77v39Cdju+ z>Kf>0w<{lJ1i%Q$J*VZzEB`05Q-RI6(Q7k#E*$>FQeZ%FL|DO%j&Y4ZS^?pH*ab-Y zm>2hK{r(PUm)L*os+QH5sB&5g>uD`UbOfmLzv-la?|2?Qxi`*}8b8~Xio~);fP}yo zoO;o2YBAVUvitpg@`H#7`>6MYt(u^dOG*#fPdXA+04NO z>Q+=!c>UxwPVZB)>-rBi4zX%s z2DNsLVd$*yPE3oxX2&mKLCqDJOILrmz=V8Y*5$E5KWJ(lni6pG zw(o+Uib#b>3LsS@hHaNM;%~5u`am)L_+Q{Mc{nje<5Z9iQT&pWuruq;8mBc3eve*! z%S&+CxNncUD=i*sDJ>E0Sck8REOqqT8Mj0p&#U}%~Zc1Cn8ob zQV!tF5Sao0eRaJto>(N&Ghz;vrW6*45k*3CsY{Wvu$aUyLxhtALCySX!g1pJVE1M> zd4z!dBR2rPb5uIA5lA42W0!F2L^+*_;Px4POcqPk@C7^2l}HkWQ*mjy;55QJMAIg8 z-0e&Lss+toS0sPrBxB$n0{gFk^QTlh(uh&~uj=VGffSariqkU%-c=BP7OeSA9Ge08 z-OH$Rd6F2&bRk6F#B-}Hes%m{yttEf`M!1&a|}|ShDcT_z5^!hcufgWL;X(aFfSF& z!gAET5X!;&dgGdRhvF}vt#@DU{L}* zo(yFQs{$+h0_rQbvNdP7I2gHyt`F5wiN&O}vU@q+E^f3NK!33Xyku={3*IilkIN#=SQ3O8U=-MdlCxTXHp*O-Zt$ubt77X?uX0KOx?J@t>&qaY_>s zq_~0sytm4$23N=M#5Io|EVRC_jQ}z7BJG)80hBofEo$ZC7)5hoIY8RDS2XJx#zIqU zUZ%ZPUsg}Zg!-^rnVEa%(lgcj-ulYLpY??%T0__UK)EKwSEl z=owh4N%73#euDDZ8=A-bwQW%;$+<;obI0miP|)!f^ZT~aT$-d{GWOOs^`rgR;`r}J z0RKJy4T*Aoi~%hgkTChBfHH3kZ-p^%`-QjvABChbm{%9b;-Geb@E)?57MT>lV%9i? z++7=Hj(UIp5s!uNdkb%)m{V!+d9Zsa!m%j^;>R^(Gh$1H2x$$-C44&Y5*Fnlvgly{ zE=0O*)FHG@AVhElqaFgUr!G{H2S6<)GunBvWUDl3@iJ$a)K{K%U(P+~`c=)T_a zNQ8(X+@{kk7ujq*an_*zy?Llb%jCr~k8p#jbE{IIuL1{6@Q>e|Y#o?1CIc9^Z5=2% z;d%05Qj7?8_6)dAyp^Ue8$wPqa(ej_Y7lb`aSCLhN zLFA;NFq#mu?*$<2A1W#bkVy+_+@TV5%HaZmib272r*%X@0z zg2NGQsgwwR4`QerbE`o59P%+G8Mmo6M@?_@k#9R)Q7BF5O)|zlWxM+&USdW|YH?4Y zLn`!wt=$gnuT6u-EbA32!~y?fu@>p79LW#Y+xcwpv6Zq+Ob9Z_JCo_*v_t|(IJILsho_moZh(% z?(w?uR9O*sd>kLAa!s6UeoKyX23n3mIMfX7IDA~5*V9#0Klg;Qa&K<5@5hS^*)D*> zIr(jyLO3vN^7uA_$bkP%zC?nUYeB`yEmZkfn|`sPxj7E$*RPerwdvofGa!nMbh7p- z$f<|H3ZuWraYC4ZT`*I?vPr&NZ@_KJ2#5~xpj%JY_G?inB>U#`x=|g}4B1dRh-WXy z7C+v=Wz*t*lZXlW|94ar`!Xm|TRtSVz|pt=h8R1^lJTO&@+GVe;@aGXx@=pB^rRbA z5B8-nahgHUCY==Ge!4c$k}0sijDJAP8iFQ-#=REZxSK6vA7(w^$wqpNRs|Sd>CdS? z;~Fv{!Zm*Q=u-VlcZN=i|9-iyHEcXp$EjVO4xdOL9MT!rdOt@yNOG+5j{daQD+{d^ zz;58ceaOJ-k7oC$qd!v@T(+DxbBCScPkBq;3pc4rcJ&uXDGHm-Ts3g=4K|})iL1#V zd9@p*>_~IsSRBi{|8a`+gE^%5+$qTgWWbaE7{|$TWJeebSjM2OHsNReB0oTfT0je> z7YRkn9gf6qq>0MM2_S)`ej~9>>kaEkn{|P$%GRF>12&mR&cSZ&P@9IHf;4V*W869>_SEGY2(UH7BKzqZx&V6(*$Z z4kJQ8J%t|B{~=`c%s7h<@PJG;>&SVMJ|1J7h}^6+eHWNJRkk#DUQ6Ni@1sEsX)-}F zm7pnV;Njy~Vil08Hg3tL0;Sr1xHbp)ZDZUSb(?)wR)9O4sC9#|MrmY+_cyrk5Jl?T#a&*Kl9SZR5f>6^w2`cr)akmT^u|M@-?_Vis!Q?4diy;X%yJlff zmHQl;kf;s@9cA=`GJu;TzTx?1=xe~*1AaH?{?uj-{@sxEDYmFoHk(A@3h{CP$r5g4$ zYP=m$+f?sFstcj!k@e2F>i7JQioyj$xL*AuMIR_A>df2Kh8h`QH}MnN`9W`KjT%?F z)+DF`d2>Z}&gXmJ!2*4I44K?9t2hwV-NbQ?fO82P^g{A&3L6(QY|-^!4bA4+if*GU zKLSrxJ2yzKj&zAbvv_N7kkoglidM8-e>ulVW{Eczu2rAfuT7q?CngLs&BxiP7}d`; z^G(1yem0-VO1eLj79Pg=RX*>#4vL-m3FFh zg5kruUnAGquUvMiDgAF~f}{w3zrrIarYl|}y3h4YSLxrOa0giPK5yOph1|77Q{%t&=N=qNVX{{2T) zZ6{c67d@m0^J%c-fqJZSMPKR zHuaE3auxELZ@kz+#v@In31W~hMDt5YUM~(-%vm;%MpTY;th+jeOpJ`@S2iKiz^C7}Og>=>`H^xP!f&9@)uA|#(pjdH;%QkhtcJPRFCEf!u6J_u9o zjXtZQyMa@4QH4Wh=e%s)rY{v%-e+Bt0H={%bNh`*16w92^r4Il%t?;hYK*BXD3~UC zf#CB4RweS@*Wz{MhE_+oBv~UTf$ZMzNkA1bERrB>k?^PUVt{!SuPEI-Bo!9*94b*c z^k6JJo_#1hOHs&%8BJl>98(bXGI#No+Wc*`z$??om0SKbx6X(wLMEDz<25%Ycy5R- z+FUB8r8`=ULX{-)of7e~+l0O9yGjs1_q+xn5&i(xOjk|63kaPZeNDiSB|Jt( zj*+-lb+_R{6u&UMQ@yetf=+lzbDJ@%I4}4Z=V{tvW6S0mAWby$Xd)lU6>Ui{(vhgd zsxq2G!|3B_j@4jG((O5IWm9k`@T;bNnuwgDC9o@dS`O^=?+71e(0lCny1ea|Su8g^ zd1zAihRE&n`k1dEPIE*rTMpCngwvln2-o(2xLA>z!lM-4x5kpXQ{FMiAZ3vdbF{oU z_dMxd9Dz|FZeeLJn=!t{YWsx}fwa4~oZJ4}YSNSdmtUC~gimleqZfVE!NKrqE-ZX= z1rqOf81&D<-~Ukt#&&|zK(Z)gHNSuKkScRz#4^OId+1j@ef@7UK|=)5N@;rjUzRGD z_}kycZzu?mfWk9#9wK-WwG2p%x@yGBSBJ1xUDPAlS@Js1n_{SE7q_qqQSv~&Z z&;MfgDC#E{s}cSg0qzc&rt}-H*gLm(ncRn;ewV2IfQtju zS82(%r+7ak@)d+o6F%*uz$x*ihVmg#9Ym?iOv^A9gRpn|%2HK(yLr3so1b9VQVwbR z@FmC&rZ-5~5&tN}CP5$~P`Ldew(1KnC`C*Qj8>u@F!uBMRs2c_{})`5Ow&ZVvK0*O zRPqu48QLqsYf@7k*c&mN5OBU|ET$saJ@sn*MK|EB)M`xQ_MU#zuiAzCP;vWFziKb- zLj9-MKT#*@Aii{;sF3ll>UOcnyWw1tDj3Ket1ya&Bjp6S=1|j6&p&@IFB#!3X;VoA zhI3(-yv2Nv);#0abRlUYv)4QA1cLF@Ez;XfsHbGTye%l5$=%xbYRgn{AP{jOG?z*t zCi=NjcxZ((B@h!A3;Qy0MD_9x;zB0$u*SgehV(H{8ByjW;dH3>Z2)_=IQi4A^XL_& zB0`H*$5ZTxwGi-x6=zZIQ#BH-*y%B3%TY_v(YRcpuYj|F$v__!;z5t2G0z!WN@Eu# zJr=~m{~%L>6{mahVSrJDZ%NSh;N78}uHe_>y{|PB6C%5SHQT&fx`yi~rG^?46JNQm zFx1rUB}${#pXE3DBd$?gR}KB4R7tNh$-Jx)-zYalW6t4En*;D^g(+3C`{uq2eJP3zWKe~G{)r! z@iYLa*Lva->>j`d8_l}kfHY*2xd03!TvLdZXDJD>5x$_|$$isrs3t zaotCkK|ZXkmMid;fArveL^*9q3mj$ZIV#vtku^ju`ns^NV&tE%*PiDYaRugMPK04wg39rM>?Qm!c1G}zS~6C1J)sgWpvk_CD$qp~zo5_zM*<|d z4iPoYher_|qB-%rimEyXUspvX%gFJpX7#)8D~n}Hx(>6yG2rd1|0k;zr_=x0X=83y L0000CLjGoE&y@FX diff --git a/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id b/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id new file mode 100644 index 0000000000..9874ec6979 --- /dev/null +++ b/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id @@ -0,0 +1 @@ +3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file From 89448135adbe7f2e308450b8a95e177e1f8de0fe Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 17 Oct 2013 10:57:48 +0800 Subject: [PATCH 161/557] issue #2771: implement some joint definition. --- cocos2dx/physics/CCPhysicsBody.cpp | 38 ++----- cocos2dx/physics/CCPhysicsJoint.cpp | 107 ++++++++++++++---- cocos2dx/physics/CCPhysicsJoint.h | 16 ++- cocos2dx/physics/CCPhysicsShape.cpp | 26 +++++ cocos2dx/physics/CCPhysicsShape.h | 3 +- cocos2dx/physics/CCPhysicsWorld.cpp | 7 +- .../physics/chipmunk/CCPhysicsBodyInfo.cpp | 1 + cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h | 1 + .../physics/chipmunk/CCPhysicsJointInfo.cpp | 42 ++++++- .../physics/chipmunk/CCPhysicsJointInfo.h | 15 ++- .../physics/chipmunk/CCPhysicsShapeInfo.cpp | 38 +++++++ .../physics/chipmunk/CCPhysicsShapeInfo.h | 5 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 11 +- 13 files changed, 237 insertions(+), 73 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.cpp b/cocos2dx/physics/CCPhysicsBody.cpp index 4fd1e45c62..8f1e9e5c1d 100644 --- a/cocos2dx/physics/CCPhysicsBody.cpp +++ b/cocos2dx/physics/CCPhysicsBody.cpp @@ -57,6 +57,7 @@ namespace { static const float MASS_DEFAULT = 1.0; static const float MOMENT_DEFAULT = 200; + static float GROUP_INDEX = 0; } PhysicsBody::PhysicsBody() @@ -226,6 +227,8 @@ bool PhysicsBody::init() CC_BREAK_IF(_info == nullptr); _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); + _info->group = ++GROUP_INDEX; + CC_BREAK_IF(_info->body == nullptr); return true; @@ -306,26 +309,6 @@ void PhysicsBody::addShape(PhysicsShape* shape) { if (shape == nullptr) return; - // already added - if (shape->getBody() == this) - { - return; - } - else if (shape->getBody() != nullptr) - { - shape->getBody()->removeShape(shape); - } - - // reset the body - if (shape->_info->body != _info->body) - { - for (cpShape* subShape : shape->_info->shapes) - { - cpShapeSetBody(subShape, _info->body); - } - shape->_info->body = _info->body; - } - // add shape to body if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) { @@ -567,20 +550,19 @@ void PhysicsBody::removeShape(PhysicsShape* shape) if (it != _shapes.end()) { - if (_world) - { - _world->removeShape(shape); - } - - _shapes.erase(it); - - // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. _area -= shape->getArea(); addMass(-shape->getMass()); addMoment(-shape->getMoment()); + //remove + if (_world) + { + _world->removeShape(shape); + } + _shapes.erase(it); + shape->setBody(nullptr); shape->release(); } } diff --git a/cocos2dx/physics/CCPhysicsJoint.cpp b/cocos2dx/physics/CCPhysicsJoint.cpp index 63b6ac052e..18f63b7101 100644 --- a/cocos2dx/physics/CCPhysicsJoint.cpp +++ b/cocos2dx/physics/CCPhysicsJoint.cpp @@ -37,6 +37,8 @@ #include "Box2D/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsBodyInfo.h" #include "Box2D/CCPhysicsBodyInfo.h" +#include "chipmunk/CCPhysicsShapeInfo.h" +#include "Box2D/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "Box2D/CCPhysicsHelper.h" @@ -47,6 +49,7 @@ PhysicsJoint::PhysicsJoint() , _bodyB(nullptr) , _info(nullptr) , _enable(false) +, _collisionEnable(true) , _tag(0) { @@ -54,6 +57,9 @@ PhysicsJoint::PhysicsJoint() PhysicsJoint::~PhysicsJoint() { + // reset the shapes collision group + setCollisionEnable(true); + CC_SAFE_DELETE(_info); CC_SAFE_RELEASE(_bodyA); @@ -66,7 +72,7 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) { CC_BREAK_IF(a == nullptr || b == nullptr); - CC_BREAK_IF(!(_info = new PhysicsJointInfo())); + CC_BREAK_IF(!(_info = new PhysicsJointInfo(this))); _bodyA = a; _bodyA->retain(); @@ -97,15 +103,15 @@ void PhysicsJoint::setEnable(bool enable) } } -PhysicsJointPin::PhysicsJointPin() -{ - -} - -PhysicsJointPin::~PhysicsJointPin() -{ - -} +//PhysicsJointPin::PhysicsJointPin() +//{ +// +//} +// +//PhysicsJointPin::~PhysicsJointPin() +//{ +// +//} PhysicsJointFixed::PhysicsJointFixed() { @@ -144,6 +150,18 @@ PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const } +void PhysicsJoint::setCollisionEnable(bool enable) +{ + if (_collisionEnable != enable) + { + _collisionEnable = enable; + + for (auto shape : _bodyB->_shapes) + { + shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); + } + } +} PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { @@ -165,8 +183,18 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - _info->joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + // add a pivot joint to fixed two body together + cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); + CC_BREAK_IF(joint); + _info->add(joint); + + // add a gear joint to make two body have the same rotation. + joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); + CC_BREAK_IF(joint); + _info->add(joint); + + setCollisionEnable(false); return true; } while (false); @@ -174,11 +202,11 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) return false; } -PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointPin* joint = new PhysicsJointPin(); - if (joint && joint->init(a, b, anchr1, anchr2)) + if (joint && joint->init(a, b, anchr)) { joint->autorelease(); return joint; @@ -188,13 +216,20 @@ PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const P return nullptr; } -bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr1, const Point& anchr2) +bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) { do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - _info->joint = cpPinJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); + cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + PhysicsHelper::point2cpv(anchr)); + + CC_BREAK_IF(joint); + + _info->add(joint); + + setCollisionEnable(false); return true; } while (false); @@ -221,11 +256,15 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - _info->joint = cpGrooveJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); + CC_BREAK_IF(joint); + + _info->add(joint); + return true; } while (false); @@ -233,11 +272,11 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo } -PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2, float min, float max) +PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointLimit* joint = new PhysicsJointLimit(); - if (joint && joint->init(a, b, anchr1, anchr2, min, max)) + if (joint && joint->init(a, b, anchr1, anchr2)) { return joint; } @@ -246,17 +285,21 @@ PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, con return nullptr; } -bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2, float min, float max) +bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - _info->joint = cpSlideJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), - PhysicsHelper::float2cpfloat(min), - PhysicsHelper::float2cpfloat(max)); + 0, + PhysicsHelper::float2cpfloat(anchr1.getDistance(anchr2))); + + CC_BREAK_IF(joint); + + _info->add(joint); return true; } while (false); @@ -264,6 +307,26 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 return false; } +float PhysicsJointLimit::getMin() +{ + return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); +} + +void PhysicsJointLimit::setMin(float min) +{ + cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); +} + +float PhysicsJointLimit::getMax() +{ + return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); +} + +void PhysicsJointLimit::setMax(float max) +{ + cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos2dx/physics/CCPhysicsJoint.h b/cocos2dx/physics/CCPhysicsJoint.h index 73383c39b6..ebc7ceddc0 100644 --- a/cocos2dx/physics/CCPhysicsJoint.h +++ b/cocos2dx/physics/CCPhysicsJoint.h @@ -53,6 +53,8 @@ public: inline void setTag(int tag) { _tag = tag; } inline bool isEnable() { return _enable; } void setEnable(bool enable); + inline bool isCollisionEnable() { return _collisionEnable; } + void setCollisionEnable(bool enable); protected: bool init(PhysicsBody* a, PhysicsBody* b); @@ -67,6 +69,7 @@ protected: PhysicsBody* _bodyB; PhysicsJointInfo* _info; bool _enable; + bool _collisionEnable; int _tag; friend class PhysicsBody; @@ -127,10 +130,15 @@ protected: class PhysicsJointLimit : public PhysicsJoint { public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2, float min, float max); + PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + + float getMin(); + void setMin(float min); + float getMax(); + void setMax(float max); protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2, float min, float max); + bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); protected: PhysicsJointLimit(); @@ -143,10 +151,10 @@ protected: class PhysicsJointPin : public PhysicsJoint { public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: PhysicsJointPin(); diff --git a/cocos2dx/physics/CCPhysicsShape.cpp b/cocos2dx/physics/CCPhysicsShape.cpp index abc4b4691b..1b5ec5ab0c 100644 --- a/cocos2dx/physics/CCPhysicsShape.cpp +++ b/cocos2dx/physics/CCPhysicsShape.cpp @@ -256,6 +256,32 @@ Point PhysicsShape::getPolyonCenter(Point* points, int count) return PhysicsHelper::cpv2point(center); } +void PhysicsShape::setBody(PhysicsBody *body) +{ + // already added + if (_body == body) + { + return; + } + + if (_body != nullptr) + { + _body->removeShape(this); + } + + if (body == nullptr) + { + _info->setBody(nullptr); + _info->setGroup(CP_NO_GROUP); + _body = nullptr; + }else + { + _info->setBody(body->_info->body); + _info->setGroup(body->_info->group); + _body = body; + } +} + // PhysicsShapeCircle PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) { diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index 30a186aa6b..f02e9e3789 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -108,7 +108,7 @@ protected: */ PhysicsBodyInfo* bodyInfo() const; - inline void setBody(PhysicsBody* body) { _body = body; } + void setBody(PhysicsBody* body); protected: PhysicsShape(); @@ -126,6 +126,7 @@ protected: friend class PhysicsWorld; friend class PhysicsBody; + friend class PhysicsJoint; }; /** A circle shape */ diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 1fda32540f..32f10dea2c 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -125,9 +125,12 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) { _joints.push_back(joint); - if (!cpSpaceContainsConstraint(_info->space, joint->_info->joint)) + for (auto subjoint : joint->_info->joints) { - cpSpaceAddConstraint(_info->space, joint->_info->joint); + if (!cpSpaceContainsConstraint(_info->space, subjoint)) + { + cpSpaceAddConstraint(_info->space, subjoint); + } } } diff --git a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.cpp index 5fd8ceb171..852dad1eeb 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.cpp @@ -28,6 +28,7 @@ NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() : body(nullptr) +, group(CP_NO_GROUP) { } diff --git a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h index 0faef2eb49..a394aa807b 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h @@ -37,6 +37,7 @@ class PhysicsBodyInfo : public Clonable { public: cpBody* body; + cpGroup group; private: PhysicsBodyInfo(); diff --git a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.cpp b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.cpp index aca28aa0fb..7a44587ba5 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.cpp +++ b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.cpp @@ -26,18 +26,54 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN -PhysicsJointInfo::PhysicsJointInfo() -: joint(nullptr) +PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) +: joint(joint) { } PhysicsJointInfo::~PhysicsJointInfo() { - if (joint) + for (cpConstraint* joint : joints) { cpConstraintFree(joint); } } +void PhysicsJointInfo::add(cpConstraint* joint) +{ + if (joint == nullptr) return; + + joints.push_back(joint); + map.insert(std::pair(joint, this)); +} + +void PhysicsJointInfo::remove(cpConstraint* joint) +{ + if (joint == nullptr) return; + + auto it = std::find(joints.begin(), joints.end(), joint); + if (it != joints.end()) + { + joints.erase(it); + + auto mit = map.find(joint); + if (mit != map.end()) map.erase(mit); + + cpConstraintFree(joint); + } +} + +void PhysicsJointInfo::removeAll() +{ + for (cpConstraint* joint : joints) + { + auto mit = map.find(joint); + if (mit != map.end()) map.erase(mit); + cpConstraintFree(joint); + } + + joints.clear(); +} + NS_CC_END #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h index 47b1fc6141..1140b8783e 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h @@ -29,15 +29,26 @@ #define __CCPHYSICS_JOINT_INFO_H__ #include "chipmunk.h" #include "platform/CCPlatformMacros.h" +#include +#include NS_CC_BEGIN +class PhysicsJoint; + class PhysicsJointInfo { public: - cpConstraint* joint; + void add(cpConstraint* shape); + void remove(cpConstraint* shape); + void removeAll(); + +public: + std::vector joints; + PhysicsJoint* joint; + static std::map map; private: - PhysicsJointInfo(); + PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); friend class PhysicsJoint; diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp index 0c048c780b..07e5c2f932 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.cpp @@ -32,6 +32,7 @@ cpBody* PhysicsShapeInfo::shareBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) : shape(shape) +, group(CP_NO_GROUP) { if (shareBody == nullptr) { @@ -52,10 +53,33 @@ PhysicsShapeInfo::~PhysicsShapeInfo() } } +void PhysicsShapeInfo::setGroup(cpGroup group) +{ + this->group = group; + + for (cpShape* shape : shapes) + { + cpShapeSetGroup(shape, group); + } +} + +void PhysicsShapeInfo::setBody(cpBody* body) +{ + if (this->body != body) + { + this->body = body; + for (cpShape* shape : shapes) + { + cpShapeSetBody(shape, body == nullptr ? shareBody : body); + } + } +} + void PhysicsShapeInfo::add(cpShape* shape) { if (shape == nullptr) return; + cpShapeSetGroup(shape, group); shapes.push_back(shape); map.insert(std::pair(shape, this)); } @@ -71,8 +95,22 @@ void PhysicsShapeInfo::remove(cpShape* shape) auto mit = map.find(shape); if (mit != map.end()) map.erase(mit); + + cpShapeFree(shape); } } +void PhysicsShapeInfo::removeAll() +{ + for (cpShape* shape : shapes) + { + auto mit = map.find(shape); + if (mit != map.end()) map.erase(mit); + cpShapeFree(shape); + } + + shapes.clear(); +} + NS_CC_END #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h index 5e9f2a73e3..f84f8613c6 100644 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h @@ -42,12 +42,15 @@ class PhysicsShapeInfo public: void add(cpShape* shape); void remove(cpShape* shape); - void removeall(); + void removeAll(); + void setGroup(cpGroup group); + void setBody(cpBody* body); public: std::vector shapes; PhysicsShape* shape; cpBody* body; + cpGroup group; static std::map map; static cpBody* shareBody; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 5791cee7bc..91c67da54d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -169,16 +169,7 @@ void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); sp->setScale(scale); - auto body = PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale)); - - static int abc = 0; - - if (abc++ > 0) - { - body->setGravityEnable(false); - } - - sp->setPhysicsBody(body); + sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); #endif From 8f9756f0302110ec337e07874b2d7b763cc47c93 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 17 Oct 2013 11:28:57 +0800 Subject: [PATCH 162/557] issue #2905:TestJavascript build ok on Android --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/gui/Android.mk | 2 +- cocos/network/Android.mk | 2 +- .../scripting/javascript/bindings/Android.mk | 34 +++++++++++++++---- .../javascript/bindings/ScriptingCore.cpp | 2 +- .../javascript/bindings/XMLHTTPRequest.cpp | 2 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/js_bindings_chipmunk_manual.cpp | 2 +- .../bindings/js_bindings_system_functions.cpp | 2 +- .../js_bindings_system_registration.cpp | 2 +- .../jsb_cocos2dx_extension_manual.cpp | 2 +- .../javascript/bindings/jsb_websocket.cpp | 2 +- cocos/storage/local-storage/Android.mk | 13 ++++--- .../spidermonkey/prebuilt/android/Android.mk | 4 +-- .../websockets/prebuilt/android/Android.mk | 2 +- samples/Cpp/TestCpp/Android.mk | 4 +-- .../proj.android/build_native.sh | 4 +-- .../proj.android/jni/Android.mk | 14 ++------ 18 files changed, 57 insertions(+), 40 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 81b945434f..e48cb4ba94 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -7658fe75258895d82e9432317ff63b182547bcdc \ No newline at end of file +9fac2ba89faf5e6f3c870c02f5186641e6be1590 \ No newline at end of file diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 197a65f3ad..31edffec85 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := gui_static +LOCAL_MODULE := cocos_gui_static LOCAL_MODULE_FILENAME := libgui diff --git a/cocos/network/Android.mk b/cocos/network/Android.mk index 1e739f3d69..d2f83a52dc 100644 --- a/cocos/network/Android.mk +++ b/cocos/network/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := network_static +LOCAL_MODULE := cocos_network_static LOCAL_MODULE_FILENAME := libnetwork diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 2aca99df10..7482cdef26 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -2,9 +2,9 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := scriptingcore-spidermonkey +LOCAL_MODULE := cocos_jsb_static -LOCAL_MODULE_FILENAME := libscriptingcore-spidermonkey +LOCAL_MODULE_FILENAME := libcocos2dxjsb LOCAL_SRC_FILES := ScriptingCore.cpp \ cocos2d_specifics.cpp \ @@ -34,18 +34,40 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT LOCAL_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../../../CocosDenshion/include \ - $(LOCAL_PATH)/../../auto-generated/js-bindings + $(LOCAL_PATH)/../../auto-generated/js-bindings \ + $(LOCAL_PATH)/../../../../extensions \ + $(LOCAL_PATH)/../../../editor-support/cocostudio LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ - $(LOCAL_PATH)/../../auto-generated/js-bindings + $(LOCAL_PATH)/../../auto-generated/js-bindings -LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static +LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static +LOCAL_WHOLE_STATIC_LIBRARIES += spine_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static +LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_gui_static LOCAL_LDLIBS := -landroid LOCAL_LDLIBS += -llog include $(BUILD_STATIC_LIBRARY) -$(call import-module,scripting/javascript/spidermonkey-android) +$(call import-module,spidermonkey/prebuilt/android) $(call import-module,extensions) +$(call import-module,2d) +$(call import-module,extensions) +$(call import-module,editor-support/cocosbuilder) +$(call import-module,editor-support/spine) +$(call import-module,network) +$(call import-module,chipmunk) +$(call import-module,storage/local-storage) +$(call import-module,editor-support/cocostudio) +$(call import-module,websockets/prebuilt/android) +$(call import-module,gui) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 101005be60..c4603fc8c0 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -16,7 +16,7 @@ #include "ScriptingCore.h" #include "jsdbgapi.h" #include "cocos2d.h" -#include "LocalStorage.h" +#include "local-storage/LocalStorage.h" #include "cocos2d_specifics.hpp" #include "js_bindings_config.h" // for debug socket diff --git a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp index 2230a4a94d..cc7b72c586 100644 --- a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp @@ -67,7 +67,7 @@ void MinXmlHttpRequest::_gotHeader(string header) { // Seems like we have the response Code! Parse it and check for it. char * pch; - std::strcpy(cstr, header.c_str()); + strcpy(cstr, header.c_str()); pch = strtok(cstr," "); while (pch != NULL) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 0204ef566e..b8cda9a498 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -2641da58037c13f92ae771830a1fdf943e4964d2 \ No newline at end of file +bf994ad1fc8ac1044957d83708f7848e99ca59e6 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp index 6233ae2553..14a88c87bb 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "js_bindings_config.h" #ifdef JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp b/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp index 1cb171224b..7d1a819fc8 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp @@ -7,7 +7,7 @@ #include "js_bindings_config.h" //#ifdef JSB_INCLUDE_SYSTEM -#include "LocalStorage.h" +#include "local-storage/LocalStorage.h" #include "jsfriendapi.h" #include "js_bindings_config.h" diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp b/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp index 040a49b410..bf55e188f0 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp @@ -24,7 +24,7 @@ #include "js_bindings_config.h" #include "js_bindings_core.h" -#include "LocalStorage.h" +#include "local-storage/LocalStorage.h" #include "cocos2d.h" // system diff --git a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 7a6d8bfc46..413f941bca 100644 --- a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -6,7 +6,7 @@ // #include "jsb_cocos2dx_extension_manual.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "ScriptingCore.h" #include "cocos2d_specifics.hpp" #include "cocostudio/CocoStudio.h" diff --git a/cocos/scripting/javascript/bindings/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/jsb_websocket.cpp index 49ecf7e57e..b5083ad268 100644 --- a/cocos/scripting/javascript/bindings/jsb_websocket.cpp +++ b/cocos/scripting/javascript/bindings/jsb_websocket.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. #include "jsb_websocket.h" #include "cocos2d.h" -#include "WebSocket.h" +#include "network/WebSocket.h" #include "spidermonkey_specifics.h" #include "ScriptingCore.h" #include "cocos2d_specifics.hpp" diff --git a/cocos/storage/local-storage/Android.mk b/cocos/storage/local-storage/Android.mk index 67db9c191b..ee9d93e36b 100644 --- a/cocos/storage/local-storage/Android.mk +++ b/cocos/storage/local-storage/Android.mk @@ -1,19 +1,24 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := localstorage_static +LOCAL_MODULE := cocos_localstorage_static LOCAL_MODULE_FILENAME := liblocalstorage -LOCAL_SRC_FILES := LocalStorage.cpp -LocalStorageAndroid.cpp \ +LOCAL_SRC_FILES := LocalStorage.cpp \ +LocalStorageAndroid.cpp -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. + LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static + include $(BUILD_STATIC_LIBRARY) + +$(call import-module,2d) diff --git a/external/spidermonkey/prebuilt/android/Android.mk b/external/spidermonkey/prebuilt/android/Android.mk index 7891f4a46e..74f0e9b6a8 100644 --- a/external/spidermonkey/prebuilt/android/Android.mk +++ b/external/spidermonkey/prebuilt/android/Android.mk @@ -3,8 +3,8 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := spidermonkey_static LOCAL_MODULE_FILENAME := js_static -LOCAL_SRC_FILES := ./lib/$(TARGET_ARCH_ABI)/libjs_static.a -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libjs_static.a +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android LOCAL_CPPFLAGS := -D__STDC_LIMIT_MACROS=1 -Wno-invalid-offsetof LOCAL_EXPORT_CPPFLAGS := -D__STDC_LIMIT_MACROS=1 -Wno-invalid-offsetof include $(PREBUILT_STATIC_LIBRARY) diff --git a/external/websockets/prebuilt/android/Android.mk b/external/websockets/prebuilt/android/Android.mk index a5f14e0456..1547fc6140 100644 --- a/external/websockets/prebuilt/android/Android.mk +++ b/external/websockets/prebuilt/android/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := libwebsockets_static +LOCAL_MODULE := websockets_static LOCAL_MODULE_FILENAME := libwebsockets_static LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libwebsockets.a LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index bd0a8e37e6..f54ac22e3b 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -148,9 +148,9 @@ LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static LOCAL_WHOLE_STATIC_LIBRARIES += spine_static -LOCAL_WHOLE_STATIC_LIBRARIES += gui_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_gui_static LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static -LOCAL_WHOLE_STATIC_LIBRARIES += network_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/Classes diff --git a/samples/Javascript/TestJavascript/proj.android/build_native.sh b/samples/Javascript/TestJavascript/proj.android/build_native.sh index b3f633e707..3378f4006a 100755 --- a/samples/Javascript/TestJavascript/proj.android/build_native.sh +++ b/samples/Javascript/TestJavascript/proj.android/build_native.sh @@ -76,7 +76,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR/../../../.." APP_ROOT="$DIR/.." APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../../scripting/javascript/bindings/js" +BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" echo echo "Paths" @@ -110,5 +110,5 @@ echo set -x "$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" \ + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ NDK_LOG=0 V=0 diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk index 5655c291c2..89d17346d0 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk @@ -11,20 +11,10 @@ LOCAL_SRC_FILES := testjavascript/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static -LOCAL_WHOLE_STATIC_LIBRARIES += scriptingcore-spidermonkey -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 include $(BUILD_SHARED_LIBRARY) -$(call import-module,cocos2dx) -$(call import-module,audio/android) -$(call import-module,extensions) -$(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) -$(call import-module,cocos2dx/platform/android) From d72d8e93d2043b4839d25f9ff892cba1b7b20283 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Wed, 16 Oct 2013 22:36:00 -0700 Subject: [PATCH 163/557] Add mouse support to linux --- cocos2dx/platform/linux/CCEGLView.cpp | 35 +++++++++++++++++++++++++ cocos2dx/proj.linux/Makefile | 2 ++ samples/Cpp/TestCpp/proj.linux/Makefile | 1 + 3 files changed, 38 insertions(+) diff --git a/cocos2dx/platform/linux/CCEGLView.cpp b/cocos2dx/platform/linux/CCEGLView.cpp index 384bd05796..51ec0550b2 100644 --- a/cocos2dx/platform/linux/CCEGLView.cpp +++ b/cocos2dx/platform/linux/CCEGLView.cpp @@ -13,6 +13,7 @@ #include "text_input_node/CCIMEDispatcher.h" #include "event_dispatcher/CCEventDispatcher.h" #include "event_dispatcher/CCEventKeyboard.h" +#include "event_dispatcher/CCEventMouse.h" #include NS_CC_BEGIN @@ -159,6 +160,7 @@ public: static void OnGLFWError(int errorID, const char* errorDesc); static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); + static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character); static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); @@ -198,6 +200,21 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in } } } + + if(GLFW_PRESS == action) + { + EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + event.setMouseButton(button); + EventDispatcher::getInstance()->dispatchEvent(&event); + } + else if(GLFW_RELEASE == action) + { + EventMouse event(EventMouse::MouseEventType::MOUSE_UP); + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + event.setMouseButton(button); + EventDispatcher::getInstance()->dispatchEvent(&event); + } } void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) @@ -218,6 +235,23 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } + + EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); + //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + EventDispatcher::getInstance()->dispatchEvent(&event); +} + +void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) +{ + EGLView* eglView = EGLView::getInstance(); + if(nullptr == eglView) return; + + EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); + //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here + event.setScrollData((float)x, -(float)y); + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + EventDispatcher::getInstance()->dispatchEvent(&event); } void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) @@ -282,6 +316,7 @@ bool EGLView::init(const char* viewName, float width, float height, float frameZ glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack); glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack); + glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback); glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback); glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback); glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback); diff --git a/cocos2dx/proj.linux/Makefile b/cocos2dx/proj.linux/Makefile index fa3d1cb659..8f72b33a0d 100644 --- a/cocos2dx/proj.linux/Makefile +++ b/cocos2dx/proj.linux/Makefile @@ -46,6 +46,8 @@ SOURCES = ../actions/CCAction.cpp \ ../event_dispatcher/CCEventListener.cpp \ ../event_dispatcher/CCEventKeyboard.cpp \ ../event_dispatcher/CCEventListenerKeyboard.cpp \ +../event_dispatcher/CCEventMouse.cpp \ +../event_dispatcher/CCEventListenerMouse.cpp \ ../event_dispatcher/CCTouch.cpp \ ../event_dispatcher/CCEventTouch.cpp \ ../event_dispatcher/CCEventListenerTouch.cpp \ diff --git a/samples/Cpp/TestCpp/proj.linux/Makefile b/samples/Cpp/TestCpp/proj.linux/Makefile index b066e6606f..1e0c9492bb 100644 --- a/samples/Cpp/TestCpp/proj.linux/Makefile +++ b/samples/Cpp/TestCpp/proj.linux/Makefile @@ -85,6 +85,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/FontTest/FontTest.cpp \ ../Classes/IntervalTest/IntervalTest.cpp \ ../Classes/KeyboardTest/KeyboardTest.cpp \ + ../Classes/InputTest/MouseTest.cpp \ ../Classes/KeypadTest/KeypadTest.cpp \ ../Classes/LabelTest/LabelTest.cpp \ ../Classes/LabelTest/LabelTestNew.cpp \ From 34fe2ba02c87aa62ce8aecd69bed71c658eb7a2f Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 17 Oct 2013 14:12:43 +0800 Subject: [PATCH 164/557] Added missing icons for some iOS and Mac samples. --- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 04a9dc0568..70bb169acc 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -f0ce606901bf2ba3acceae9e9562214dde6a4c69 \ No newline at end of file +83265c81797ca614f19372a96adf326aeb21b396 \ No newline at end of file From a2de02cc19f79ace82eae549adf5bb9002558186 Mon Sep 17 00:00:00 2001 From: XiaoLongHan Date: Thu, 17 Oct 2013 14:21:55 +0800 Subject: [PATCH 165/557] Change the class name of textfield to compare, so that you can touch anywhere outside of the virtual keyboard. --- cocos/2d/platform/ios/EAGLView.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index 188172e73a..5d305d4bdc 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -378,7 +378,7 @@ static CCEAGLView *view = 0; for(UIView* view in subviews) { - if([view isKindOfClass:NSClassFromString(@"CustomUITextField")]) + if([view isKindOfClass:NSClassFromString(@"CCCustomUITextField")]) { if ([view isFirstResponder]) { From e50f9fc43b47a24f8e51cb859635abac9edb90b8 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 17 Oct 2013 15:04:30 +0800 Subject: [PATCH 166/557] issue #2905: jsbinding samples and lua binding samples build ok on android --- cocos/2d/Android.mk | 4 +- cocos/editor-support/cocosbuilder/Android.mk | 2 +- cocos/editor-support/cocostudio/Android.mk | 2 + .../scripting/javascript/bindings/Android.mk | 2 - cocos/scripting/lua/bindings/Android.mk | 84 +++++++++--------- cocos/scripting/lua/bindings/CCBProxy.h | 2 +- .../lua/bindings/LuaOpengl.cpp.REMOVED.git-id | 2 +- .../lua/bindings/LuaScriptHandlerMgr.cpp | 2 +- external/lua/luajit/.DS_Store | Bin 0 -> 6148 bytes .../luajit/{ => prebuilt/android}/Android.mk | 4 +- .../armeabi-v7a/libluajit.a.REMOVED.git-id | 0 .../armeabi/libluajit.a.REMOVED.git-id | 0 .../android/x86/libluajit.a.REMOVED.git-id | 0 .../ios/libluajit.a.REMOVED.git-id | 0 .../mac/libluajit.a.REMOVED.git-id | 0 .../win32/lua51.dll.REMOVED.git-id | 0 .../luajit/{LuaJIT-2.0.1 => src}/COPYRIGHT | 0 .../lua/luajit/{LuaJIT-2.0.1 => src}/Makefile | 0 .../lua/luajit/{LuaJIT-2.0.1 => src}/README | 0 .../doc/bluequad-print.css | 0 .../{LuaJIT-2.0.1 => src}/doc/bluequad.css | 0 .../{LuaJIT-2.0.1 => src}/doc/changes.html | 0 .../{LuaJIT-2.0.1 => src}/doc/contact.html | 0 .../{LuaJIT-2.0.1 => src}/doc/ext_c_api.html | 0 .../{LuaJIT-2.0.1 => src}/doc/ext_ffi.html | 0 .../doc/ext_ffi_api.html | 0 .../doc/ext_ffi_semantics.html | 0 .../doc/ext_ffi_tutorial.html | 0 .../{LuaJIT-2.0.1 => src}/doc/ext_jit.html | 0 .../{LuaJIT-2.0.1 => src}/doc/extensions.html | 0 .../luajit/{LuaJIT-2.0.1 => src}/doc/faq.html | 0 .../{LuaJIT-2.0.1 => src}/doc/install.html | 0 .../{LuaJIT-2.0.1 => src}/doc/luajit.html | 0 .../{LuaJIT-2.0.1 => src}/doc/running.html | 0 .../{LuaJIT-2.0.1 => src}/doc/status.html | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_arm.h | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_arm.lua | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_mips.h | 0 .../dynasm/dasm_mips.lua | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_ppc.h | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_ppc.lua | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_proto.h | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_x64.lua | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_x86.h | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dasm_x86.lua | 0 .../{LuaJIT-2.0.1 => src}/dynasm/dynasm.lua | 0 .../luajit/{LuaJIT-2.0.1 => src}/etc/luajit.1 | 0 .../{LuaJIT-2.0.1 => src}/etc/luajit.pc | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/Makefile | 0 .../{LuaJIT-2.0.1 => src}/src/Makefile.dep | 0 .../{LuaJIT-2.0.1 => src}/src/host/README | 0 .../{LuaJIT-2.0.1 => src}/src/host/buildvm.c | 0 .../{LuaJIT-2.0.1 => src}/src/host/buildvm.h | 0 .../src/host/buildvm_asm.c | 0 .../src/host/buildvm_fold.c | 0 .../src/host/buildvm_lib.c | 0 .../src/host/buildvm_peobj.c | 0 .../src/host/genminilua.lua | 0 .../src/host/minilua.c.REMOVED.git-id | 0 .../{LuaJIT-2.0.1 => src}/src/jit/bc.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/bcsave.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/dis_arm.lua | 0 .../src/jit/dis_mips.lua | 0 .../src/jit/dis_mipsel.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/dis_ppc.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/dis_x64.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/dis_x86.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/dump.lua | 0 .../{LuaJIT-2.0.1 => src}/src/jit/v.lua | 0 .../{LuaJIT-2.0.1 => src}/src/lauxlib.h | 0 .../{LuaJIT-2.0.1 => src}/src/lib_aux.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_base.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_bit.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_debug.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_ffi.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_init.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lib_io.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_jit.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_math.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lib_os.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_package.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_string.c | 0 .../{LuaJIT-2.0.1 => src}/src/lib_table.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj.supp | 0 .../{LuaJIT-2.0.1 => src}/src/lj_alloc.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_alloc.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_api.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_arch.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_asm.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_asm.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_asm_arm.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_asm_mips.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_asm_ppc.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_asm_x86.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_bc.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_bc.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_bcdump.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_bcread.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_bcwrite.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_carith.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_carith.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ccall.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ccall.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ccallback.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ccallback.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cconv.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cconv.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cdata.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cdata.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_char.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_char.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_clib.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_clib.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cparse.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_cparse.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_crecord.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_crecord.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ctype.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ctype.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_debug.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_debug.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_def.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_dispatch.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_dispatch.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_emit_arm.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_emit_mips.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_emit_ppc.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_emit_x86.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_err.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_err.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_errmsg.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_ff.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ffrecord.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ffrecord.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_frame.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_func.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_func.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_gc.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_gc.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_gdbjit.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_gdbjit.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_ir.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_ir.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_ircall.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_iropt.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_jit.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_lex.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_lex.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_lib.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_lib.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_load.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_mcode.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_mcode.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_meta.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_meta.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_obj.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_obj.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_dce.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_fold.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_loop.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_mem.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_narrow.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_sink.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_opt_split.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_parse.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_parse.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_record.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_record.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_snap.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_snap.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_state.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_state.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_str.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_str.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_strscan.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_strscan.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_tab.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_tab.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_target.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_target_arm.h | 0 .../src/lj_target_mips.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_target_ppc.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_target_x86.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_trace.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_trace.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_traceerr.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_udata.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_udata.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lj_vm.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_vmevent.c | 0 .../{LuaJIT-2.0.1 => src}/src/lj_vmevent.h | 0 .../{LuaJIT-2.0.1 => src}/src/lj_vmmath.c | 0 .../{LuaJIT-2.0.1 => src}/src/ljamalg.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lua.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lua.hpp | 0 .../{LuaJIT-2.0.1 => src}/src/luaconf.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/luajit.c | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/luajit.h | 0 .../luajit/{LuaJIT-2.0.1 => src}/src/lualib.h | 0 .../{LuaJIT-2.0.1 => src}/src/msvcbuild.bat | 0 .../src/vm_arm.dasc.REMOVED.git-id | 0 .../src/vm_mips.dasc.REMOVED.git-id | 0 .../src/vm_ppc.dasc.REMOVED.git-id | 0 .../src/vm_ppcspe.dasc.REMOVED.git-id | 0 .../src/vm_x86.dasc.REMOVED.git-id | 0 .../{LuaJIT-2.0.1 => src}/src/xedkbuild.bat | 0 .../v2.0.1_hotfix1.patch | 0 samples/Cpp/TestCpp/Android.mk | 2 - .../proj.android/build_native.sh | 4 +- .../CocosDragonJS/proj.android/jni/Android.mk | 10 +-- .../CrystalCraze/proj.android/build_native.sh | 4 +- .../CrystalCraze/proj.android/jni/Android.mk | 10 +-- .../MoonWarriors/proj.android/build_native.sh | 4 +- .../MoonWarriors/proj.android/jni/Android.mk | 12 +-- .../proj.android/build_native.sh | 4 +- .../proj.android/jni/Android.mk | 12 +-- .../Lua/HelloLua/proj.android/build_native.sh | 2 +- .../Lua/HelloLua/proj.android/jni/Android.mk | 2 +- .../Lua/TestLua/proj.android/build_native.sh | 6 +- .../Lua/TestLua/proj.android/jni/Android.mk | 15 +--- .../proj.android/build_native.sh | 4 +- .../proj.android/jni/Android.mk | 12 +-- .../proj.android/build_native.sh | 6 +- .../proj.android/jni/Android.mk | 11 +-- 224 files changed, 84 insertions(+), 140 deletions(-) create mode 100644 external/lua/luajit/.DS_Store rename external/lua/luajit/{ => prebuilt/android}/Android.mk (58%) rename external/lua/luajit/{ => prebuilt}/android/armeabi-v7a/libluajit.a.REMOVED.git-id (100%) rename external/lua/luajit/{ => prebuilt}/android/armeabi/libluajit.a.REMOVED.git-id (100%) rename external/lua/luajit/{ => prebuilt}/android/x86/libluajit.a.REMOVED.git-id (100%) rename external/lua/luajit/{ => prebuilt}/ios/libluajit.a.REMOVED.git-id (100%) rename external/lua/luajit/{ => prebuilt}/mac/libluajit.a.REMOVED.git-id (100%) rename external/lua/luajit/{ => prebuilt}/win32/lua51.dll.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/COPYRIGHT (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/Makefile (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/README (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/bluequad-print.css (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/bluequad.css (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/changes.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/contact.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_c_api.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_ffi.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_ffi_api.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_ffi_semantics.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_ffi_tutorial.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/ext_jit.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/extensions.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/faq.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/install.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/luajit.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/running.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/doc/status.html (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_arm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_arm.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_mips.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_mips.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_ppc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_ppc.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_proto.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_x64.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_x86.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dasm_x86.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/dynasm/dynasm.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/etc/luajit.1 (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/etc/luajit.pc (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/Makefile (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/Makefile.dep (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/README (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm_asm.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm_fold.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm_lib.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/buildvm_peobj.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/genminilua.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/host/minilua.c.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/bc.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/bcsave.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_arm.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_mips.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_mipsel.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_ppc.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_x64.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dis_x86.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/dump.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/jit/v.lua (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lauxlib.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_aux.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_base.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_bit.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_debug.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_ffi.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_init.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_io.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_jit.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_math.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_os.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_package.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_string.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lib_table.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj.supp (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_alloc.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_alloc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_api.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_arch.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm_arm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm_mips.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm_ppc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_asm_x86.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_bc.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_bc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_bcdump.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_bcread.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_bcwrite.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_carith.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_carith.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ccall.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ccall.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ccallback.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ccallback.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cconv.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cconv.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cdata.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cdata.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_char.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_char.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_clib.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_clib.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cparse.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_cparse.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_crecord.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_crecord.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ctype.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ctype.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_debug.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_debug.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_def.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_dispatch.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_dispatch.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_emit_arm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_emit_mips.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_emit_ppc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_emit_x86.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_err.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_err.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_errmsg.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ff.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ffrecord.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ffrecord.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_frame.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_func.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_func.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_gc.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_gc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_gdbjit.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_gdbjit.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ir.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ir.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_ircall.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_iropt.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_jit.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_lex.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_lex.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_lib.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_lib.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_load.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_mcode.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_mcode.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_meta.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_meta.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_obj.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_obj.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_dce.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_fold.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_loop.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_mem.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_narrow.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_sink.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_opt_split.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_parse.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_parse.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_record.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_record.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_snap.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_snap.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_state.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_state.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_str.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_str.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_strscan.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_strscan.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_tab.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_tab.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_target.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_target_arm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_target_mips.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_target_ppc.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_target_x86.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_trace.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_trace.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_traceerr.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_udata.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_udata.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_vm.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_vmevent.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_vmevent.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lj_vmmath.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/ljamalg.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lua.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lua.hpp (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/luaconf.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/luajit.c (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/luajit.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/lualib.h (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/msvcbuild.bat (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/vm_arm.dasc.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/vm_mips.dasc.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/vm_ppc.dasc.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/vm_ppcspe.dasc.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/vm_x86.dasc.REMOVED.git-id (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/src/xedkbuild.bat (100%) rename external/lua/luajit/{LuaJIT-2.0.1 => src}/v2.0.1_hotfix1.patch (100%) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 20017089fe..7e60320ddb 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -201,8 +201,10 @@ LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static # define the macro to compile through support/zip_support/ioapi.c -LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API +LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API +LOCAL_CPPFLAGS := -Wno-literal-suffix LOCAL_EXPORT_CFLAGS := -Wno-psabi -DUSE_FILE32API +LOCAL_EXPORT_CPPFLAGS := -Wno-literal-suffix include $(BUILD_STATIC_LIBRARY) diff --git a/cocos/editor-support/cocosbuilder/Android.mk b/cocos/editor-support/cocosbuilder/Android.mk index dd6b2b3b77..4685debd1b 100644 --- a/cocos/editor-support/cocosbuilder/Android.mk +++ b/cocos/editor-support/cocosbuilder/Android.mk @@ -29,7 +29,7 @@ CCScale9SpriteLoader.cpp \ CCScrollViewLoader.cpp \ CCSpriteLoader.cpp -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/ \ +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ $(LOCAL_PATH)/../../.. LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ diff --git a/cocos/editor-support/cocostudio/Android.mk b/cocos/editor-support/cocostudio/Android.mk index b7dfa3838c..380eeba149 100644 --- a/cocos/editor-support/cocostudio/Android.mk +++ b/cocos/editor-support/cocostudio/Android.mk @@ -56,9 +56,11 @@ LOCAL_EXPORT_CFLAGS += -Wno-psabi LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_gui_static include $(BUILD_STATIC_LIBRARY) $(call import-module,2d) $(call import-module,audio/android) +$(call import-module,gui) diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 7482cdef26..27a3b51306 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -52,7 +52,6 @@ LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_localstorage_static LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_gui_static LOCAL_LDLIBS := -landroid LOCAL_LDLIBS += -llog @@ -70,4 +69,3 @@ $(call import-module,chipmunk) $(call import-module,storage/local-storage) $(call import-module,editor-support/cocostudio) $(call import-module,websockets/prebuilt/android) -$(call import-module,gui) diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index 8d1130ba3c..a5293f66a2 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -5,61 +5,59 @@ LOCAL_MODULE := cocos_lua_static LOCAL_MODULE_FILENAME := liblua -LOCAL_SRC_FILES := ../cocos2dx_support/CCLuaBridge.cpp \ - ../cocos2dx_support/CCLuaEngine.cpp \ - ../cocos2dx_support/CCLuaStack.cpp \ - ../cocos2dx_support/CCLuaValue.cpp \ - ../cocos2dx_support/Cocos2dxLuaLoader.cpp \ - ../cocos2dx_support/CCBProxy.cpp \ - ../cocos2dx_support/Lua_web_socket.cpp \ - ../cocos2dx_support/LuaOpengl.cpp \ - ../cocos2dx_support/LuaScriptHandlerMgr.cpp \ - ../cocos2dx_support/LuaBasicConversions.cpp \ +LOCAL_SRC_FILES := CCLuaBridge.cpp \ + CCLuaEngine.cpp \ + CCLuaStack.cpp \ + CCLuaValue.cpp \ + Cocos2dxLuaLoader.cpp \ + CCBProxy.cpp \ + Lua_web_socket.cpp \ + LuaOpengl.cpp \ + LuaScriptHandlerMgr.cpp \ + LuaBasicConversions.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - ../cocos2dx_support/lua_cocos2dx_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_extension_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_deprecated.cpp \ - ../cocos2dx_support/platform/android/CCLuaJavaBridge.cpp \ - ../cocos2dx_support/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp \ - ../tolua/tolua_event.c \ - ../tolua/tolua_is.c \ - ../tolua/tolua_map.c \ - ../tolua/tolua_push.c \ - ../tolua/tolua_to.c \ - ../cocos2dx_support/tolua_fix.c + lua_cocos2dx_manual.cpp \ + lua_cocos2dx_extension_manual.cpp \ + lua_cocos2dx_deprecated.cpp \ + platform/android/CCLuaJavaBridge.cpp \ + platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp \ + ../../../../external/lua/tolua/tolua_event.c \ + ../../../../external/lua/tolua/tolua_is.c \ + ../../../../external/lua/tolua/tolua_map.c \ + ../../../../external/lua/tolua/tolua_push.c \ + ../../../../external/lua/tolua/tolua_to.c \ + tolua_fix.c -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../luajit/include \ - $(LOCAL_PATH)/../tolua \ - $(LOCAL_PATH)/../cocos2dx_support \ - $(LOCAL_PATH)/../../auto-generated/lua-bindings \ - $(LOCAL_PATH)/../cocos2dx_support/platform/android \ - $(LOCAL_PATH)/../cocos2dx_support/platform/android/jni - - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/ \ - $(LOCAL_PATH)/../luajit/include \ - $(LOCAL_PATH)/../tolua \ - $(LOCAL_PATH)/../../../cocos2dx \ - $(LOCAL_PATH)/../../../cocos2dx/include \ - $(LOCAL_PATH)/../../../cocos2dx/platform \ - $(LOCAL_PATH)/../../../cocos2dx/platform/android \ - $(LOCAL_PATH)/../../../cocos2dx/kazmath/include \ - $(LOCAL_PATH)/../../../CocosDenshion/include \ - $(LOCAL_PATH)/../../../extensions \ - $(LOCAL_PATH)/../cocos2dx_support \ +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../../external/lua/tolua \ $(LOCAL_PATH)/../../auto-generated/lua-bindings \ - $(LOCAL_PATH)/../cocos2dx_support/platform/android \ - $(LOCAL_PATH)/../cocos2dx_support/platform/android/jni + $(LOCAL_PATH)/platform/android \ + $(LOCAL_PATH)/platform/android/jni \ + $(LOCAL_PATH)/../../../../extensions \ + $(LOCAL_PATH)/../../../editor-support/cocosbuilder \ + $(LOCAL_PATH)/../../../editor-support/cocostudio + + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) LOCAL_WHOLE_STATIC_LIBRARIES := luajit_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static +LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi include $(BUILD_STATIC_LIBRARY) -$(call import-module,scripting/lua/luajit) +$(call import-module,lua/luajit/prebuilt/android) $(call import-module,extensions) +$(call import-module,2d) +$(call import-module,websockets/prebuilt/android) +$(call import-module,network) +$(call import-module,editor-support/cocostudio) +$(call import-module,editor-support/cocosbuilder) diff --git a/cocos/scripting/lua/bindings/CCBProxy.h b/cocos/scripting/lua/bindings/CCBProxy.h index 082bf09db1..a073db913b 100644 --- a/cocos/scripting/lua/bindings/CCBProxy.h +++ b/cocos/scripting/lua/bindings/CCBProxy.h @@ -4,7 +4,7 @@ #include "cocos2d.h" #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "cocosbuilder/CocosBuilder.h" USING_NS_CC; diff --git a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id index a50fda9d51..bc4c41058d 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id @@ -1 +1 @@ -a57fbb5f0f9564858ced00cf47af905e6a7900c6 \ No newline at end of file +4456a3ba6fbd68175b40e607c6bc19bdfc378ce1 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp index 7b663307a3..ab4d01bd01 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp @@ -10,7 +10,7 @@ extern "C" { #include #include "LuaScriptHandlerMgr.h" #include "cocos2d.h" -#include "cocos-ext.h" +#include "extensions/cocos-ext.h" #include "CCLuaStack.h" #include "CCLuaValue.h" #include "CCLuaEngine.h" diff --git a/external/lua/luajit/.DS_Store b/external/lua/luajit/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 Date: Thu, 17 Oct 2013 15:38:24 +0800 Subject: [PATCH 167/557] Update CHANGELOG --- CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 6163db0772..3b2637b29d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -12,6 +12,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Fixed application will crash when pause and resume. [Mac] [FIX] Removed unused CCLOG() from GL initialization +[iOS] + [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. [Javascript binding] [FIX] Fixed a memory leak in ScriptingCore::runScript() [FIX] sys.localStorage.getItem() does not support non-ascii string. From 222cb93aaf7a05643e439ab16a1bd51814f5fdb6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 17 Oct 2013 15:43:45 +0800 Subject: [PATCH 168/557] Update AUTHORS --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 22a8baf85e..0638129f45 100644 --- a/AUTHORS +++ b/AUTHORS @@ -617,6 +617,9 @@ Developers: jimmystar Fixed a bug that cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. + XiaoLongHan (kpkhxlgy0) + Fixed a bug that outside of keyboard can't be responded to close keyboard when using EditBox。 + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 736a117fae6d14584e50eb3b4a9085c9c1a2042c Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 17 Oct 2013 16:15:51 +0800 Subject: [PATCH 169/557] Changed submodule URL for 'auto-generated'. --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index 7b07af24eb..91585f7b9a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,7 +3,7 @@ url = git://github.com/cocos2d/bindings-generator.git [submodule "cocos/scripting/auto-generated"] path = cocos/scripting/auto-generated - url = git://github.com/folecr/cocos2dx-autogen-bindings.git + url = git://github.com/cocos2d-x/bindings-auto-generated.git [submodule "samples/Javascript/Shared"] path = samples/Javascript/Shared url = git://github.com/cocos2d/cocos2d-js-tests.git From 4d28d0ab8bedad2449f5bddb1b330874c8e743a2 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 17 Oct 2013 17:46:09 +0800 Subject: [PATCH 170/557] issue #2509:make lua android template build ok --- .../proj.android/build_native.sh | 6 +++--- .../proj.android/jni/Android.mk | 15 ++------------- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/template/multi-platform-lua/proj.android/build_native.sh b/template/multi-platform-lua/proj.android/build_native.sh index 6728b60a2e..930a9e5249 100755 --- a/template/multi-platform-lua/proj.android/build_native.sh +++ b/template/multi-platform-lua/proj.android/build_native.sh @@ -80,7 +80,7 @@ fi done # copy common luaScript -for file in "$APP_ROOT"/../../scripting/lua/script/* +for file in "$APP_ROOT"/../../cocos/scripting/lua/script/* do if [ -d "$file" ]; then cp -rf "$file" "$APP_ANDROID_ROOT"/assets @@ -94,9 +94,9 @@ done if [[ "$buildexternalsfromsource" ]]; then echo "Building external dependencies from source" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" else echo "Using prebuilt externals" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" fi \ No newline at end of file diff --git a/template/multi-platform-lua/proj.android/jni/Android.mk b/template/multi-platform-lua/proj.android/jni/Android.mk index af986970fe..a28d2c3d4d 100644 --- a/template/multi-platform-lua/proj.android/jni/Android.mk +++ b/template/multi-platform-lua/proj.android/jni/Android.mk @@ -15,19 +15,8 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_STATIC_LIBRARIES := curl_static_prebuilt -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_lua_static -LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_lua_static include $(BUILD_SHARED_LIBRARY) -$(call import-module,cocos2dx) -$(call import-module,audio/android) -$(call import-module,scripting/lua/proj.android) -$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl) -$(call import-module,extensions) -$(call import-module,external/Box2D) -$(call import-module,cocos2dx/platform/android) +$(call import-module,scripting/lua/bindings) \ No newline at end of file From 9c3cac759ceb8c2814328dce6bdb5ec0dfe67029 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 17 Oct 2013 18:39:37 +0800 Subject: [PATCH 171/557] issue #2905:simple game and assets manager build ok on android --- cocos/scripting/javascript/bindings/Android.mk | 3 ++- samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h | 2 +- .../Cpp/AssetsManagerTest/proj.android/build_native.sh | 4 ++-- .../Cpp/AssetsManagerTest/proj.android/jni/Android.mk | 10 +--------- samples/Cpp/SimpleGame/proj.android/build_native.sh | 2 +- samples/Cpp/SimpleGame/proj.android/jni/Android.mk | 6 ++---- 6 files changed, 9 insertions(+), 18 deletions(-) diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 27a3b51306..5689684060 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -36,7 +36,8 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../../../CocosDenshion/include \ $(LOCAL_PATH)/../../auto-generated/js-bindings \ $(LOCAL_PATH)/../../../../extensions \ - $(LOCAL_PATH)/../../../editor-support/cocostudio + $(LOCAL_PATH)/../../../editor-support/cocostudio \ + $(LOCAL_PATH)/../../../editor-support/cocosbuilder LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ $(LOCAL_PATH)/../../auto-generated/js-bindings diff --git a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h index 7fcf54741d..2a0dae6d7b 100644 --- a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h +++ b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h @@ -11,7 +11,7 @@ #include "CCApplication.h" #include "cocos2d.h" -#include "AssetsManager/AssetsManager.h" +#include "extensions/assets-manager/AssetsManager.h" /** @brief The cocos2d Application. diff --git a/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh b/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh index cfc39f5472..30549e8869 100755 --- a/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh +++ b/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh @@ -68,7 +68,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR/../../../.." APP_ROOT="$DIR/.." APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../../scripting/javascript/bindings/js" +BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" echo "NDK_ROOT = $NDK_ROOT" echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" @@ -119,5 +119,5 @@ if [[ "$buildexternalsfromsource" ]]; then else echo "Using prebuilt externals" "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" fi diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk index 42c47b9f80..78d938432f 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk @@ -11,18 +11,10 @@ LOCAL_SRC_FILES := hellocpp/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static -LOCAL_WHOLE_STATIC_LIBRARIES += scriptingcore-spidermonkey -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) -$(call import-module,cocos2dx) -$(call import-module,audio/android) -$(call import-module,scripting/javascript/spidermonkey-android) $(call import-module,scripting/javascript/bindings) -$(call import-module,cocos2dx/platform/android) diff --git a/samples/Cpp/SimpleGame/proj.android/build_native.sh b/samples/Cpp/SimpleGame/proj.android/build_native.sh index 1383ae1490..8f09b2bb6b 100755 --- a/samples/Cpp/SimpleGame/proj.android/build_native.sh +++ b/samples/Cpp/SimpleGame/proj.android/build_native.sh @@ -104,4 +104,4 @@ fi echo "Building in debug" "$NDK_ROOT"/ndk-build NDK_DEBUG=1 -C "$APP_ANDROID_ROOT" \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk b/samples/Cpp/SimpleGame/proj.android/jni/Android.mk index d0fd9a4eb2..cdc6ac3234 100644 --- a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk +++ b/samples/Cpp/SimpleGame/proj.android/jni/Android.mk @@ -13,11 +13,9 @@ LOCAL_SRC_FILES := hellocpp/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocos2dxandroid_static cocosdenshion_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static include $(BUILD_SHARED_LIBRARY) $(call import-module,audio/android) -$(call import-module,cocos2dx) -$(call import-module,extensions) -$(call import-module,cocos2dx/platform/android) +$(call import-module,2d) From 8c0d7e151c3e9194c257375f814320cc80cf67f6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 18 Oct 2013 10:02:47 +0800 Subject: [PATCH 172/557] Updating the submodule reference of 'auto-generated'. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 73aebd082a..893da8ccfb 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 73aebd082ae63561cc1ca769f28e302820da7e39 +Subproject commit 893da8ccfb4ed7fa754c483a90dc4e5248c36e03 From ca3cbec8582fe6dc0b5068990ca6dc06a5acb64d Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 18 Oct 2013 11:06:17 +0800 Subject: [PATCH 173/557] [Template] Hello JavaScript --> HelloJavascript. It's for replacement. --- .../HelloJavascript.xcodeproj/project.pbxproj | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index 82228bc55f..2a53c9e26c 100644 --- a/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/template/multi-platform-js/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -295,7 +295,7 @@ 5091731717ECDF7A00D62437 /* Icon-58.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-58.png"; path = "ios/Icon-58.png"; sourceTree = ""; }; 5091731817ECDF7A00D62437 /* Icon-80.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-80.png"; path = "ios/Icon-80.png"; sourceTree = ""; }; 5091731917ECDF7A00D62437 /* Icon-100.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-100.png"; path = "ios/Icon-100.png"; sourceTree = ""; }; - 509D4AAA17EBB24E00697056 /* Hello JavaScript Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Hello JavaScript Mac.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 509D4AAA17EBB24E00697056 /* Hello JavaScript Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = "Hello JavaScript Mac.app"; path = "HelloJavaScript Mac.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 509D4AAB17EBB2AB00697056 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppController.h; path = ios/AppController.h; sourceTree = ""; }; 509D4AAC17EBB2AB00697056 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppController.mm; path = ios/AppController.mm; sourceTree = ""; }; 509D4AAD17EBB2AB00697056 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Default-568h@2x.png"; path = "ios/Default-568h@2x.png"; sourceTree = ""; }; @@ -320,7 +320,7 @@ 509D4AE617EBB81800697056 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; 509D4AE817EBB82000697056 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; }; 509D4AEA17EBB82600697056 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; }; - A922753D1517C094001B78AA /* Hello JavaScript iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Hello JavaScript iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + A922753D1517C094001B78AA /* Hello JavaScript iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = "Hello JavaScript iOS.app"; path = "HelloJavaScript iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A92275411517C094001B78AA /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; A92275431517C094001B78AA /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; A92275451517C094001B78AA /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; @@ -545,9 +545,9 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 509D4A7517EBB24E00697056 /* Hello JavaScript Mac */ = { + 509D4A7517EBB24E00697056 /* HelloJavascript Mac */ = { isa = PBXNativeTarget; - buildConfigurationList = 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "Hello JavaScript Mac" */; + buildConfigurationList = 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "HelloJavascript Mac" */; buildPhases = ( 509D4A8017EBB24E00697056 /* Sources */, 509D4A8217EBB24E00697056 /* Frameworks */, @@ -562,14 +562,14 @@ 1A676826180E9BF70076BC67 /* PBXTargetDependency */, 1A676828180E9BF70076BC67 /* PBXTargetDependency */, ); - name = "Hello JavaScript Mac"; + name = "HelloJavascript Mac"; productName = HelloJavascript; productReference = 509D4AAA17EBB24E00697056 /* Hello JavaScript Mac.app */; productType = "com.apple.product-type.application"; }; - A922753C1517C094001B78AA /* Hello JavaScript iOS */ = { + A922753C1517C094001B78AA /* HelloJavascript iOS */ = { isa = PBXNativeTarget; - buildConfigurationList = A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "Hello JavaScript iOS" */; + buildConfigurationList = A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "HelloJavascript iOS" */; buildPhases = ( A92275391517C094001B78AA /* Sources */, A922753A1517C094001B78AA /* Frameworks */, @@ -584,7 +584,7 @@ 1A676835180E9C110076BC67 /* PBXTargetDependency */, 1A676837180E9C110076BC67 /* PBXTargetDependency */, ); - name = "Hello JavaScript iOS"; + name = "HelloJavascript iOS"; productName = HelloJavascript; productReference = A922753D1517C094001B78AA /* Hello JavaScript iOS.app */; productType = "com.apple.product-type.application"; @@ -620,8 +620,8 @@ ); projectRoot = ""; targets = ( - A922753C1517C094001B78AA /* Hello JavaScript iOS */, - 509D4A7517EBB24E00697056 /* Hello JavaScript Mac */, + A922753C1517C094001B78AA /* HelloJavascript iOS */, + 509D4A7517EBB24E00697056 /* HelloJavascript Mac */, ); }; /* End PBXProject section */ @@ -1058,7 +1058,7 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "Hello JavaScript Mac" */ = { + 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "HelloJavascript Mac" */ = { isa = XCConfigurationList; buildConfigurations = ( 509D4AA817EBB24E00697056 /* Debug */, @@ -1076,7 +1076,7 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "Hello JavaScript iOS" */ = { + A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "HelloJavascript iOS" */ = { isa = XCConfigurationList; buildConfigurations = ( A92277011517C097001B78AA /* Debug */, From c8ba071294d55b3361e7d6400a1bef37f78f8855 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 18 Oct 2013 11:13:54 +0800 Subject: [PATCH 174/557] Update AUTHORS --- AUTHORS | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 0638129f45..71cba826b3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -618,7 +618,10 @@ Developers: Fixed a bug that cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. XiaoLongHan (kpkhxlgy0) - Fixed a bug that outside of keyboard can't be responded to close keyboard when using EditBox。 + Fixed a bug that outside of keyboard can't be responded to close keyboard when using EditBox. + + lettas + A fix for multi-platform template. Retired Core Developers: WenSheng Yang From 7d588fbaa32e539aaea87338303ebe687055ad1e Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 18 Oct 2013 11:15:02 +0800 Subject: [PATCH 175/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 3b2637b29d..62169acdf3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,6 +6,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] fixed a memory leak in XMLHTTPRequest.cpp [FIX] removeSpriteFramesFromFile() crashes if file doesn't exist. [FIX] Avoid unnecessary object duplication for Scale9Sprite. + [FIX] create_project.py does not rename/replace template projects completely. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 8f2f524f2d4c131037817b9913208fe3858b7903 Mon Sep 17 00:00:00 2001 From: dualface Date: Fri, 18 Oct 2013 11:30:28 +0800 Subject: [PATCH 176/557] fix tolua_fix, cleanup peertable after object deleted --- cocos/scripting/lua/bindings/tolua_fix.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c index 870db00d75..259a05242e 100644 --- a/cocos/scripting/lua/bindings/tolua_fix.c +++ b/cocos/scripting/lua/bindings/tolua_fix.c @@ -128,7 +128,11 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 3); return -3; } - + + // cleanup peertable + lua_pushvalue(L, TOLUA_NOPEER); + lua_setfenv(L, -2); + ud = (void**)lua_touserdata(L, -1); lua_pop(L, 1); /* stack: mt ubox */ if (ud == NULL) From 88ae56bfe940145145d87f2ab3a0b3dfa5d1384c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 18 Oct 2013 13:52:25 +0800 Subject: [PATCH 177/557] issue #2771: implement PhysicsBody's bit masks. --- cocos2dx/physics/CCPhysicsBody.h | 6 ++-- cocos2dx/physics/CCPhysicsContact.h | 8 +++-- cocos2dx/physics/CCPhysicsShape.h | 14 ++++---- cocos2dx/physics/CCPhysicsWorld.cpp | 52 +++++++++++++++++++++++++---- cocos2dx/physics/CCPhysicsWorld.h | 8 ++--- 5 files changed, 65 insertions(+), 23 deletions(-) diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h index 904d94a1bf..869c7be1da 100644 --- a/cocos2dx/physics/CCPhysicsBody.h +++ b/cocos2dx/physics/CCPhysicsBody.h @@ -149,11 +149,11 @@ public: */ inline Sprite* getOwner() const { return _owner; } - void setCategoryBitmask(int bitmask); + inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } inline int getCategoryBitmask() const { return _categoryBitmask; } - void setContactTestBitmask(int bitmask); + inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } inline int getContactTestBitmask() const { return _contactTestBitmask; } - void setCollisionBitmask(int bitmask); + inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } inline int getCollisionBitmask() const { return _collisionBitmask; } /* diff --git a/cocos2dx/physics/CCPhysicsContact.h b/cocos2dx/physics/CCPhysicsContact.h index 605a6dcf80..df31ae7be3 100644 --- a/cocos2dx/physics/CCPhysicsContact.h +++ b/cocos2dx/physics/CCPhysicsContact.h @@ -47,11 +47,11 @@ public: /* * @brief get contact shape A. */ - inline PhysicsShape* getShapeA() { return _shapeA; } + inline PhysicsShape* getShapeA() const { return _shapeA; } /* * @brief get contact shape B. */ - inline PhysicsShape* getShapeB() { return _shapeB; } + inline PhysicsShape* getShapeB() const { return _shapeB; } /* * @brief get data. */ @@ -65,6 +65,9 @@ private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); + inline bool getNotify() { return _notify; } + inline void setNotify(bool notify) { _notify = notify; } + private: PhysicsContact(); ~PhysicsContact(); @@ -74,6 +77,7 @@ private: PhysicsShape* _shapeB; PhysicsContactInfo* _info; void* _data; + bool _notify; friend class PhysicsWorld; }; diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h index f02e9e3789..fcf70c7c19 100644 --- a/cocos2dx/physics/CCPhysicsShape.h +++ b/cocos2dx/physics/CCPhysicsShape.h @@ -76,17 +76,17 @@ public: }; public: - inline PhysicsBody* getBody(){ return _body; } - inline Type getType() { return _type; } - inline float getArea() { return _area; } - inline float getMoment() { return _moment; } + inline PhysicsBody* getBody() const { return _body; } + inline Type getType() const { return _type; } + inline float getArea() const { return _area; } + inline float getMoment() const { return _moment; } void setMoment(float moment); inline void setTag(int tag) { _tag = tag; } - inline int getTag() { return _tag; } + inline int getTag() const { return _tag; } - inline float getMass() { return _mass; } + inline float getMass() const { return _mass; } void setMass(float mass); - inline float getDensity() { return _material.density; } + inline float getDensity() const { return _material.density; } void setDensity(float density); void setRestitution(float restitution); void setFriction(float friction); diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp index 32f10dea2c..afccdca8d9 100644 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ b/cocos2dx/physics/CCPhysicsWorld.cpp @@ -35,6 +35,7 @@ #include "CCPhysicsShape.h" #include "CCPhysicsContact.h" #include "CCPhysicsJoint.h" +#include "CCPhysicsContact.h" #include "chipmunk/CCPhysicsWorldInfo.h" #include "Box2D/CCPhysicsWorldInfo.h" @@ -361,18 +362,45 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) } } -int PhysicsWorld::collisionBeginCallback(const PhysicsContact& contact) +int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { - if (_listener && _listener->onContactBegin) + bool ret = true; + PhysicsBody* bodyA = contact.getShapeA()->getBody(); + PhysicsBody* bodyB = contact.getShapeB()->getBody(); + + if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0) { - return _listener->onContactBegin(contact); + contact.setNotify(false); } - return true; + if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0) + { + ret = false; + } + + if (contact.getNotify() && _listener && _listener->onContactBegin) + { + // the mask has high priority than _listener->onContactBegin. + // so if the mask test is false, the two bodies won't have collision. + if (ret) + { + ret = _listener->onContactBegin(contact); + }else + { + _listener->onContactBegin(contact); + } + } + + return ret; } -int PhysicsWorld::collisionPreSolveCallback(const PhysicsContact& contact, const PhysicsContactPreSolve& solve) +int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) { + if (!contact.getNotify()) + { + return true; + } + if (_listener && _listener->onContactPreSolve) { return _listener->onContactPreSolve(contact, solve); @@ -381,16 +409,26 @@ int PhysicsWorld::collisionPreSolveCallback(const PhysicsContact& contact, const return true; } -void PhysicsWorld::collisionPostSolveCallback(const PhysicsContact& contact, const PhysicsContactPostSolve& solve) +void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) { + if (!contact.getNotify()) + { + return; + } + if (_listener && _listener->onContactPreSolve) { _listener->onContactPostSolve(contact, solve); } } -void PhysicsWorld::collisionSeparateCallback(const PhysicsContact& contact) +void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return; + } + if (_listener && _listener->onContactEnd) { _listener->onContactEnd(contact); diff --git a/cocos2dx/physics/CCPhysicsWorld.h b/cocos2dx/physics/CCPhysicsWorld.h index d7a30f37cf..a0539ae81d 100644 --- a/cocos2dx/physics/CCPhysicsWorld.h +++ b/cocos2dx/physics/CCPhysicsWorld.h @@ -106,10 +106,10 @@ protected: virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); - virtual int collisionBeginCallback(const PhysicsContact& contact); - virtual int collisionPreSolveCallback(const PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(const PhysicsContact& contact, const PhysicsContactPostSolve& solve); - virtual void collisionSeparateCallback(const PhysicsContact& contact); + virtual int collisionBeginCallback(PhysicsContact& contact); + virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); + virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); + virtual void collisionSeparateCallback(PhysicsContact& contact); #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) static int collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data); From 63c13d8eaa0f34d5e05065c5a3c661f57c197bf9 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 18 Oct 2013 14:18:36 +0800 Subject: [PATCH 178/557] issue #2905:simplify Android.mk dependence --- cocos/editor-support/cocosbuilder/Android.mk | 4 +- cocos/editor-support/cocostudio/Android.mk | 4 +- cocos/gui/Android.mk | 5 +- extensions/Android.mk | 52 +++++------ external/Box2D/Android.mk | 90 ++++++++++---------- external/chipmunk/Android.mk | 58 ++++++------- samples/Cpp/TestCpp/Android.mk | 13 +-- 7 files changed, 106 insertions(+), 120 deletions(-) diff --git a/cocos/editor-support/cocosbuilder/Android.mk b/cocos/editor-support/cocosbuilder/Android.mk index 4685debd1b..f5699a7f60 100644 --- a/cocos/editor-support/cocosbuilder/Android.mk +++ b/cocos/editor-support/cocosbuilder/Android.mk @@ -39,10 +39,8 @@ $(LOCAL_PATH)/../../.. LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_extension_static include $(BUILD_STATIC_LIBRARY) -$(call import-module,2d) $(call import-module,extensions) diff --git a/cocos/editor-support/cocostudio/Android.mk b/cocos/editor-support/cocostudio/Android.mk index 380eeba149..b9b1535fe6 100644 --- a/cocos/editor-support/cocostudio/Android.mk +++ b/cocos/editor-support/cocostudio/Android.mk @@ -43,10 +43,10 @@ CCSSceneReader.cpp \ ../../../external/json/json_writer.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ -$(LOCAL_PATH)/../../../external/json +$(LOCAL_PATH)/../../../external LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ -$(LOCAL_PATH)/../../../external/json \ +$(LOCAL_PATH)/../../../external \ $(LOCAL_PATH)/.. \ $(LOCAL_PATH)/../.. \ $(LOCAL_PATH)/../../../external diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 31edffec85..49f33a17e6 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -39,11 +39,8 @@ LOCAL_EXPORT_CFLAGS += -Wno-psabi LOCAL_WHOLE_STATIC_LIBRARIES := cocostudio_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static include $(BUILD_STATIC_LIBRARY) - -$(call import-module,extensions) $(call import-module,editor-support/cocostudio) -$(call import-module,2d) +$(call import-module,extensions) diff --git a/extensions/Android.mk b/extensions/Android.mk index 8f9bbe4f66..a5f4fd051f 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -6,36 +6,35 @@ LOCAL_MODULE := cocos_extension_static LOCAL_MODULE_FILENAME := libextension LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/assets-manager/AssetsManager.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControl.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlButton.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlColourPicker.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlHuePicker.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlPotentiometer.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSlider.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlStepper.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlSwitch.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCControlUtils.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCInvocation.cpp \ -$(LOCAL_PATH)/GUI/CCControlExtension/CCScale9Sprite.cpp \ -$(LOCAL_PATH)/GUI/CCEditBox/CCEditBox.cpp \ -$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ -$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplNone.cpp \ -$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplTizen.cpp \ -$(LOCAL_PATH)/GUI/CCEditBox/CCEditBoxImplWin.cpp \ -$(LOCAL_PATH)/GUI/CCScrollView/CCScrollView.cpp \ -$(LOCAL_PATH)/GUI/CCScrollView/CCSorting.cpp \ -$(LOCAL_PATH)/GUI/CCScrollView/CCTableView.cpp \ -$(LOCAL_PATH)/GUI/CCScrollView/CCTableViewCell.cpp \ -$(LOCAL_PATH)/physics-nodes/CCPhysicsDebugNode.cpp \ -$(LOCAL_PATH)/physics-nodes/CCPhysicsSprite.cpp +assets-manager/AssetsManager.cpp \ +GUI/CCControlExtension/CCControl.cpp \ +GUI/CCControlExtension/CCControlButton.cpp \ +GUI/CCControlExtension/CCControlColourPicker.cpp \ +GUI/CCControlExtension/CCControlHuePicker.cpp \ +GUI/CCControlExtension/CCControlPotentiometer.cpp \ +GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ +GUI/CCControlExtension/CCControlSlider.cpp \ +GUI/CCControlExtension/CCControlStepper.cpp \ +GUI/CCControlExtension/CCControlSwitch.cpp \ +GUI/CCControlExtension/CCControlUtils.cpp \ +GUI/CCControlExtension/CCInvocation.cpp \ +GUI/CCControlExtension/CCScale9Sprite.cpp \ +GUI/CCEditBox/CCEditBox.cpp \ +GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ +GUI/CCEditBox/CCEditBoxImplNone.cpp \ +GUI/CCEditBox/CCEditBoxImplTizen.cpp \ +GUI/CCEditBox/CCEditBoxImplWin.cpp \ +GUI/CCScrollView/CCScrollView.cpp \ +GUI/CCScrollView/CCSorting.cpp \ +GUI/CCScrollView/CCTableView.cpp \ +GUI/CCScrollView/CCTableViewCell.cpp \ +physics-nodes/CCPhysicsDebugNode.cpp \ +physics-nodes/CCPhysicsSprite.cpp LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static -LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += libwebsockets_static LOCAL_CXXFLAGS += -fexceptions @@ -53,6 +52,7 @@ include $(BUILD_STATIC_LIBRARY) $(call import-module,2d) $(call import-module,audio/android) +$(call import-module,curl/prebuilt/android) $(call import-module,Box2D) -$(call import-module,chipmunk) $(call import-module,websockets/prebuilt/android) + diff --git a/external/Box2D/Android.mk b/external/Box2D/Android.mk index 5172a998e7..c366750c01 100644 --- a/external/Box2D/Android.mk +++ b/external/Box2D/Android.mk @@ -7,51 +7,51 @@ LOCAL_MODULE := box2d_static LOCAL_MODULE_FILENAME := libbox2d LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/Collision/b2BroadPhase.cpp \ -$(LOCAL_PATH)/Collision/b2CollideCircle.cpp \ -$(LOCAL_PATH)/Collision/b2CollideEdge.cpp \ -$(LOCAL_PATH)/Collision/b2CollidePolygon.cpp \ -$(LOCAL_PATH)/Collision/b2Collision.cpp \ -$(LOCAL_PATH)/Collision/b2Distance.cpp \ -$(LOCAL_PATH)/Collision/b2DynamicTree.cpp \ -$(LOCAL_PATH)/Collision/b2TimeOfImpact.cpp \ -$(LOCAL_PATH)/Collision/Shapes/b2ChainShape.cpp \ -$(LOCAL_PATH)/Collision/Shapes/b2CircleShape.cpp \ -$(LOCAL_PATH)/Collision/Shapes/b2EdgeShape.cpp \ -$(LOCAL_PATH)/Collision/Shapes/b2PolygonShape.cpp \ -$(LOCAL_PATH)/Common/b2BlockAllocator.cpp \ -$(LOCAL_PATH)/Common/b2Draw.cpp \ -$(LOCAL_PATH)/Common/b2Math.cpp \ -$(LOCAL_PATH)/Common/b2Settings.cpp \ -$(LOCAL_PATH)/Common/b2StackAllocator.cpp \ -$(LOCAL_PATH)/Common/b2Timer.cpp \ -$(LOCAL_PATH)/Dynamics/b2Body.cpp \ -$(LOCAL_PATH)/Dynamics/b2ContactManager.cpp \ -$(LOCAL_PATH)/Dynamics/b2Fixture.cpp \ -$(LOCAL_PATH)/Dynamics/b2Island.cpp \ -$(LOCAL_PATH)/Dynamics/b2World.cpp \ -$(LOCAL_PATH)/Dynamics/b2WorldCallbacks.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2CircleContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2Contact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2ContactSolver.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -$(LOCAL_PATH)/Dynamics/Contacts/b2PolygonContact.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2DistanceJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2FrictionJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2GearJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2Joint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2MouseJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2PrismaticJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2PulleyJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2RevoluteJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2RopeJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2WeldJoint.cpp \ -$(LOCAL_PATH)/Dynamics/Joints/b2WheelJoint.cpp \ -$(LOCAL_PATH)/Rope/b2Rope.cpp +Collision/b2BroadPhase.cpp \ +Collision/b2CollideCircle.cpp \ +Collision/b2CollideEdge.cpp \ +Collision/b2CollidePolygon.cpp \ +Collision/b2Collision.cpp \ +Collision/b2Distance.cpp \ +Collision/b2DynamicTree.cpp \ +Collision/b2TimeOfImpact.cpp \ +Collision/Shapes/b2ChainShape.cpp \ +Collision/Shapes/b2CircleShape.cpp \ +Collision/Shapes/b2EdgeShape.cpp \ +Collision/Shapes/b2PolygonShape.cpp \ +Common/b2BlockAllocator.cpp \ +Common/b2Draw.cpp \ +Common/b2Math.cpp \ +Common/b2Settings.cpp \ +Common/b2StackAllocator.cpp \ +Common/b2Timer.cpp \ +Dynamics/b2Body.cpp \ +Dynamics/b2ContactManager.cpp \ +Dynamics/b2Fixture.cpp \ +Dynamics/b2Island.cpp \ +Dynamics/b2World.cpp \ +Dynamics/b2WorldCallbacks.cpp \ +Dynamics/Contacts/b2ChainAndCircleContact.cpp \ +Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ +Dynamics/Contacts/b2CircleContact.cpp \ +Dynamics/Contacts/b2Contact.cpp \ +Dynamics/Contacts/b2ContactSolver.cpp \ +Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ +Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ +Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ +Dynamics/Contacts/b2PolygonContact.cpp \ +Dynamics/Joints/b2DistanceJoint.cpp \ +Dynamics/Joints/b2FrictionJoint.cpp \ +Dynamics/Joints/b2GearJoint.cpp \ +Dynamics/Joints/b2Joint.cpp \ +Dynamics/Joints/b2MouseJoint.cpp \ +Dynamics/Joints/b2PrismaticJoint.cpp \ +Dynamics/Joints/b2PulleyJoint.cpp \ +Dynamics/Joints/b2RevoluteJoint.cpp \ +Dynamics/Joints/b2RopeJoint.cpp \ +Dynamics/Joints/b2WeldJoint.cpp \ +Dynamics/Joints/b2WheelJoint.cpp \ +Rope/b2Rope.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. diff --git a/external/chipmunk/Android.mk b/external/chipmunk/Android.mk index e8013df8c3..e8441cd0d7 100644 --- a/external/chipmunk/Android.mk +++ b/external/chipmunk/Android.mk @@ -7,35 +7,35 @@ LOCAL_MODULE := chipmunk_static LOCAL_MODULE_FILENAME := libchipmunk LOCAL_SRC_FILES := \ -$(LOCAL_PATH)/src/chipmunk.c \ -$(LOCAL_PATH)/src/cpArbiter.c \ -$(LOCAL_PATH)/src/cpArray.c \ -$(LOCAL_PATH)/src/cpBB.c \ -$(LOCAL_PATH)/src/cpBBTree.c \ -$(LOCAL_PATH)/src/cpBody.c \ -$(LOCAL_PATH)/src/cpCollision.c \ -$(LOCAL_PATH)/src/cpHashSet.c \ -$(LOCAL_PATH)/src/cpPolyShape.c \ -$(LOCAL_PATH)/src/cpShape.c \ -$(LOCAL_PATH)/src/cpSpace.c \ -$(LOCAL_PATH)/src/cpSpaceComponent.c \ -$(LOCAL_PATH)/src/cpSpaceHash.c \ -$(LOCAL_PATH)/src/cpSpaceQuery.c \ -$(LOCAL_PATH)/src/cpSpaceStep.c \ -$(LOCAL_PATH)/src/cpSpatialIndex.c \ -$(LOCAL_PATH)/src/cpSweep1D.c \ -$(LOCAL_PATH)/src/cpVect.c \ -$(LOCAL_PATH)/src/constraints/cpConstraint.c \ -$(LOCAL_PATH)/src/constraints/cpDampedRotarySpring.c \ -$(LOCAL_PATH)/src/constraints/cpDampedSpring.c \ -$(LOCAL_PATH)/src/constraints/cpGearJoint.c \ -$(LOCAL_PATH)/src/constraints/cpGrooveJoint.c \ -$(LOCAL_PATH)/src/constraints/cpPinJoint.c \ -$(LOCAL_PATH)/src/constraints/cpPivotJoint.c \ -$(LOCAL_PATH)/src/constraints/cpRatchetJoint.c \ -$(LOCAL_PATH)/src/constraints/cpRotaryLimitJoint.c \ -$(LOCAL_PATH)/src/constraints/cpSimpleMotor.c \ -$(LOCAL_PATH)/src/constraints/cpSlideJoint.c +src/chipmunk.c \ +src/cpArbiter.c \ +src/cpArray.c \ +src/cpBB.c \ +src/cpBBTree.c \ +src/cpBody.c \ +src/cpCollision.c \ +src/cpHashSet.c \ +src/cpPolyShape.c \ +src/cpShape.c \ +src/cpSpace.c \ +src/cpSpaceComponent.c \ +src/cpSpaceHash.c \ +src/cpSpaceQuery.c \ +src/cpSpaceStep.c \ +src/cpSpatialIndex.c \ +src/cpSweep1D.c \ +src/cpVect.c \ +src/constraints/cpConstraint.c \ +src/constraints/cpDampedRotarySpring.c \ +src/constraints/cpDampedSpring.c \ +src/constraints/cpGearJoint.c \ +src/constraints/cpGrooveJoint.c \ +src/constraints/cpPinJoint.c \ +src/constraints/cpPivotJoint.c \ +src/constraints/cpRatchetJoint.c \ +src/constraints/cpRotaryLimitJoint.c \ +src/constraints/cpSimpleMotor.c \ +src/constraints/cpSlideJoint.c LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 00c130e372..af16f48433 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -141,28 +141,19 @@ Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static -LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_extension_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static LOCAL_WHOLE_STATIC_LIBRARIES += spine_static LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static + LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/Classes include $(BUILD_STATIC_LIBRARY) -$(call import-module,audio/android) -$(call import-module,Box2D) -$(call import-module,chipmunk) -$(call import-module,2d) $(call import-module,extensions) $(call import-module,editor-support/cocosbuilder) $(call import-module,editor-support/spine) $(call import-module,editor-support/cocostudio) $(call import-module,network) -$(call import-module,curl/prebuilt/android) From 5f65cdc3c0860ab414a177ef0eb3a2d271e446be Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 18 Oct 2013 15:39:09 +0800 Subject: [PATCH 179/557] fix xcode compiling error and simplify android.mk --- .../cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/Android.mk | 7 +------ cocos/2d/platform/android/Android.mk | 2 +- external/png/prebuilt/android/Android.mk | 2 +- external/tiff/prebuilt/android/Android.mk | 2 +- external/webp/prebuilt/android/Android.mk | 2 +- 6 files changed, 6 insertions(+), 11 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index e48cb4ba94..abe193af68 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -9fac2ba89faf5e6f3c870c02f5186641e6be1590 \ No newline at end of file +a791b9789e080d3e7530890cfbaa966fffef5f9e \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 7e60320ddb..ec9f2dbf6e 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -191,12 +191,7 @@ LOCAL_EXPORT_LDLIBS := -lGLESv2 \ -lz \ -landroid -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_libpng_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jpeg_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libxml2_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libtiff_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libwebp_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_freetype2_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_freetype2_static LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static diff --git a/cocos/2d/platform/android/Android.mk b/cocos/2d/platform/android/Android.mk index 2aca5c8ed3..db9bec71b9 100644 --- a/cocos/2d/platform/android/Android.mk +++ b/cocos/2d/platform/android/Android.mk @@ -42,7 +42,7 @@ LOCAL_EXPORT_LDLIBS := -lGLESv1_CM \ -lz \ -landroid -LOCAL_WHOLE_STATIC_LIBRARIES := android_native_app_glue cocos_libpng_static cocos_jpeg_static cocos_libxml2_static cocos_libtiff_static cocos_libwebp_static +LOCAL_WHOLE_STATIC_LIBRARIES := android_native_app_glue cocos_png_static cocos_jpeg_static cocos_tiff_static cocos_webp_static include $(BUILD_STATIC_LIBRARY) diff --git a/external/png/prebuilt/android/Android.mk b/external/png/prebuilt/android/Android.mk index 41a0f91322..457f97c57f 100644 --- a/external/png/prebuilt/android/Android.mk +++ b/external/png/prebuilt/android/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := cocos_libpng_static +LOCAL_MODULE := cocos_png_static LOCAL_MODULE_FILENAME := png LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libpng.a LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android diff --git a/external/tiff/prebuilt/android/Android.mk b/external/tiff/prebuilt/android/Android.mk index 40af980160..417eeda4ad 100644 --- a/external/tiff/prebuilt/android/Android.mk +++ b/external/tiff/prebuilt/android/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := cocos_libtiff_static +LOCAL_MODULE := cocos_tiff_static LOCAL_MODULE_FILENAME := tiff LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libtiff.a LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android diff --git a/external/webp/prebuilt/android/Android.mk b/external/webp/prebuilt/android/Android.mk index e102ac2511..1bd16f8c45 100644 --- a/external/webp/prebuilt/android/Android.mk +++ b/external/webp/prebuilt/android/Android.mk @@ -1,7 +1,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := cocos_libwebp_static +LOCAL_MODULE := cocos_webp_static LOCAL_MODULE_FILENAME := webp LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libwebp.a LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include/android From 6aef4476d95171bbd4ca6c005e1d2259eb6e1f9c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 18 Oct 2013 15:55:47 +0800 Subject: [PATCH 180/557] issue #2771: edit some mistake when merge --- cocos/physics/chipmunk/CCPhysicsHelper.h | 2 +- cocos/physics/chipmunk/CCPhysicsShapeInfo.h | 2 +- samples/Cpp/TestCpp/Classes/controller.cpp | 197 ++++++++++++++++++++ 3 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 samples/Cpp/TestCpp/Classes/controller.cpp diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index 9334d87124..323527cd6a 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -29,7 +29,7 @@ #define __CCPHYSICS_HELPER_H__ #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" #include "cocoa/CCGeometry.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h index f84f8613c6..83be655b02 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h @@ -31,7 +31,7 @@ #include #include #include "chipmunk.h" -#include "platform/CCPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp new file mode 100644 index 0000000000..f78fb2c9af --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -0,0 +1,197 @@ + +// C++ includes +#include +#include +#include + +// test inclues +#include "controller.h" +#include "testResource.h" +#include "tests.h" + + +struct { + const char *test_name; + std::function callback; +} g_aTestNames[] = { + { "Accelerometer", []() { return new AccelerometerTestScene(); } }, + { "ActionManagerTest", [](){return new ActionManagerTestScene(); } }, + { "ActionsEaseTest", [](){return new ActionsEaseTestScene();} }, + { "ActionsProgressTest", [](){return new ProgressActionsTestScene(); } }, + { "ActionsTest", [](){ return new ActionsTestScene(); } }, + { "Box2dTest", []() { return new Box2DTestScene(); } }, + { "Box2dTestBed", []() { return new Box2dTestBedScene(); } }, + { "BugsTest", []() { return new BugsTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + { "ChipmunkTest", []() { return new ChipmunkAccelTouchTestScene(); } }, +#endif + { "ClickAndMoveTest", [](){return new ClickAndMoveTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + { "ClippingNodeTest", []() { return new ClippingNodeTestScene(); } }, +#endif + { "CocosDenshionTest", []() { return new CocosDenshionTestScene(); } }, + { "ConfigurationTest", []() { return new ConfigurationTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) + { "CurlTest", []() { return new CurlTestScene(); } }, +#endif +#endif +#endif +#endif + { "CurrentLanguageTest", []() { return new CurrentLanguageTestScene(); } }, + { "DrawPrimitivesTest", [](){return new DrawPrimitivesTestScene();} }, + { "EventDispatcherTest(NEW)", []() { return new EventDispatcherTestScene(); } }, + { "EffectAdvancedTest", []() { return new EffectAdvanceScene(); } }, + { "EffectsTest", [](){return new EffectTestScene();} }, + { "ExtensionsTest", []() { return new ExtensionsTestScene(); } }, + { "FileUtilsTest", []() { return new FileUtilsTestScene(); } }, + { "FontTest", []() { return new FontTestScene(); } }, + { "IntervalTest", [](){return new IntervalTestScene(); } }, + { "KeyboardTest", []() { return new KeyboardTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) + { "KeypadTest", []() { return new KeypadTestScene(); } }, +#endif + { "LabelTest", [](){return new AtlasTestScene(); } }, + { "LabelTestNew", [](){return new AtlasTestSceneNew(); } }, + { "LayerTest", [](){return new LayerTestScene();} }, + { "MenuTest", [](){return new MenuTestScene();} }, + { "MotionStreakTest", [](){return new MotionStreakTestScene();} }, + { "MutiTouchTest", []() { return new MutiTouchTestScene(); } }, + { "NodeTest", [](){return new CocosNodeTestScene();} }, + { "ParallaxTest", [](){return new ParallaxTestScene(); } }, + { "ParticleTest", [](){return new ParticleTestScene(); } }, + { "PerformanceTest", []() { return new PerformanceTestScene(); } }, + { "PhysicsTest", []() { return new PhysicsTestScene(); } }, + { "RenderTextureTest", [](){return new RenderTextureScene(); } }, + { "RotateWorldTest", [](){return new RotateWorldTestScene(); } }, + { "SceneTest", [](){return new SceneTestScene();} }, + { "SchedulerTest", [](){return new SchedulerTestScene(); } }, + { "ShaderTest", []() { return new ShaderTestScene(); } }, + { "ShaderTestSprite", []() { return new ShaderTestScene2(); } }, + { "SpineTest", []() { return new SpineTestScene(); } }, + { "SpriteTest", [](){return new SpriteTestScene(); } }, + { "TextInputTest", [](){return new TextInputTestScene(); } }, + { "Texture2DTest", [](){return new TextureTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) + { "TextureCacheTest", []() { return new TextureCacheTestScene(); } }, +#endif + { "TexturePackerEncryption", []() { return new TextureAtlasEncryptionTestScene(); } }, + { "TileMapTest", [](){return new TileMapTestScene(); } }, + { "TouchesTest", [](){return new PongScene();} }, + { "TransitionsTest", [](){return new TransitionsTestScene();} }, + { "UserDefaultTest", []() { return new UserDefaultTestScene(); } }, + { "ZwoptexTest", []() { return new ZwoptexTestScene(); } }, +}; + +static int g_testCount = sizeof(g_aTestNames) / sizeof(g_aTestNames[0]); + +#define LINE_SPACE 40 + +static Point s_tCurPos = Point::ZERO; + +TestController::TestController() +: _beginPos(Point::ZERO) +{ + // add close menu + auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, CC_CALLBACK_1(TestController::closeCallback, this) ); + auto menu =Menu::create(closeItem, NULL); + + menu->setPosition( Point::ZERO ); + closeItem->setPosition(Point( VisibleRect::right().x - 30, VisibleRect::top().y - 30)); + + // add menu items for tests + _itemMenu = Menu::create(); + for (int i = 0; i < g_testCount; ++i) + { +// #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE) +// auto label = LabelBMFont::create(g_aTestNames[i].c_str(), "fonts/arial16.fnt"); +// #else + auto label = LabelTTF::create( g_aTestNames[i].test_name, "Arial", 24); +// #endif + auto menuItem = MenuItemLabel::create(label, CC_CALLBACK_1(TestController::menuCallback, this)); + + _itemMenu->addChild(menuItem, i + 10000); + menuItem->setPosition( Point( VisibleRect::center().x, (VisibleRect::top().y - (i + 1) * LINE_SPACE) )); + } + + _itemMenu->setContentSize(Size(VisibleRect::getVisibleRect().size.width, (g_testCount + 1) * (LINE_SPACE))); + _itemMenu->setPosition(s_tCurPos); + addChild(_itemMenu); + + setTouchEnabled(true); + + addChild(menu, 1); + + // Register Touch Event + auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(TestController::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(TestController::onTouchMoved, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); +} + +TestController::~TestController() +{ +} + +void TestController::menuCallback(Object * sender) +{ + + Director::getInstance()->purgeCachedData(); + + // get the userdata, it's the index of the menu item clicked + auto menuItem = static_cast(sender); + int idx = menuItem->getZOrder() - 10000; + + // create the test scene and run it + auto scene = g_aTestNames[idx].callback(); + + if (scene && scene->initTest()) + { + scene->runThisTest(); + scene->release(); + } +} + +void TestController::closeCallback(Object * sender) +{ + Director::getInstance()->end(); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + exit(0); +#endif +} + +bool TestController::onTouchBegan(Touch* touch, Event *event) +{ + _beginPos = touch->getLocation(); + return true; +} + +void TestController::onTouchMoved(Touch* touch, Event *event) +{ + auto touchLocation = touch->getLocation(); + float nMoveY = touchLocation.y - _beginPos.y; + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testCount + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testCount + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); + _beginPos = touchLocation; + s_tCurPos = nextPos; +} From 4ccb13f5d02dba6532822a8fd93b29ef9178e803 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 18 Oct 2013 17:37:04 +0800 Subject: [PATCH 181/557] fix libluajia.a search path bug --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index abe193af68..bb2117f6df 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -a791b9789e080d3e7530890cfbaa966fffef5f9e \ No newline at end of file +af3544581a6508d57d3fe3b1f999cdc091bad543 \ No newline at end of file From 5741a166205a686ed21ea143c6f066f4c0752f19 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 18 Oct 2013 17:47:29 +0800 Subject: [PATCH 182/557] issue #2771: edit some include head file path --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 6 +++--- cocos/physics/chipmunk/CCPhysicsHelper.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 65883d5bcb..72cad042bc 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -43,7 +43,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {1.0f, 1.0f, 1.0f}; /** * A body affect by physics. diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index afccdca8d9..30939dc9fd 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -49,9 +49,9 @@ #include "Box2D/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsHelper.h" -#include "draw_nodes/CCDrawNode.h" -#include "cocoa/CCArray.h" -#include "layers_scenes_transitions_nodes/CCScene.h" +#include "CCDrawNode.h" +#include "CCArray.h" +#include "CCScene.h" #include "CCDirector.h" #include diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index 323527cd6a..337bb1a1df 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -30,7 +30,7 @@ #include "chipmunk.h" #include "CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" +#include "CCGeometry.h" NS_CC_BEGIN From 8fbfff97d933d95600ca54b196372aeee0f4ec0d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 18 Oct 2013 17:56:22 +0800 Subject: [PATCH 183/557] issue #2771: delete some files added by mistake. --- .gitmodules | 2 +- cocos2dx/base_nodes/CCNode.cpp | 1538 ---------------- cocos2dx/base_nodes/CCNode.h | 1575 ----------------- cocos2dx/cocoa/CCGeometry.h | 584 ------ cocos2dx/physics/CCPhysicsBody.h | 292 --- cocos2dx/physics/CCPhysicsContact.h | 147 -- cocos2dx/physics/CCPhysicsJoint.h | 168 -- cocos2dx/physics/CCPhysicsShape.h | 296 ---- cocos2dx/physics/CCPhysicsWorld.cpp | 496 ------ cocos2dx/physics/CCPhysicsWorld.h | 149 -- cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h | 54 - cocos2dx/physics/chipmunk/CCPhysicsHelper.h | 71 - .../physics/chipmunk/CCPhysicsJointInfo.h | 60 - .../physics/chipmunk/CCPhysicsShapeInfo.h | 67 - cocos2dx/sprite_nodes/CCSprite.cpp | 1138 ------------ 15 files changed, 1 insertion(+), 6636 deletions(-) delete mode 100644 cocos2dx/base_nodes/CCNode.cpp delete mode 100644 cocos2dx/base_nodes/CCNode.h delete mode 100644 cocos2dx/cocoa/CCGeometry.h delete mode 100644 cocos2dx/physics/CCPhysicsBody.h delete mode 100644 cocos2dx/physics/CCPhysicsContact.h delete mode 100644 cocos2dx/physics/CCPhysicsJoint.h delete mode 100644 cocos2dx/physics/CCPhysicsShape.h delete mode 100644 cocos2dx/physics/CCPhysicsWorld.cpp delete mode 100644 cocos2dx/physics/CCPhysicsWorld.h delete mode 100644 cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h delete mode 100644 cocos2dx/physics/chipmunk/CCPhysicsHelper.h delete mode 100644 cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h delete mode 100644 cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h delete mode 100644 cocos2dx/sprite_nodes/CCSprite.cpp diff --git a/.gitmodules b/.gitmodules index c4175f6e86..91585f7b9a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,7 +3,7 @@ url = git://github.com/cocos2d/bindings-generator.git [submodule "cocos/scripting/auto-generated"] path = cocos/scripting/auto-generated -url=git://github.com/cocos2d-x/bindings-auto-generated.git + url = git://github.com/cocos2d-x/bindings-auto-generated.git [submodule "samples/Javascript/Shared"] path = samples/Javascript/Shared url = git://github.com/cocos2d/cocos2d-js-tests.git diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp deleted file mode 100644 index 4c3168fde4..0000000000 --- a/cocos2dx/base_nodes/CCNode.cpp +++ /dev/null @@ -1,1538 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2009 Valentin Milea -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCNode.h" - -#include - -#include "cocoa/CCString.h" -#include "support/data_support/ccCArray.h" -#include "support/TransformUtils.h" -#include "CCCamera.h" -#include "effects/CCGrid.h" -#include "CCDirector.h" -#include "CCScheduler.h" -#include "event_dispatcher/CCTouch.h" -#include "actions/CCActionManager.h" -#include "script_support/CCScriptSupport.h" -#include "shaders/CCGLProgram.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEvent.h" -#include "event_dispatcher/CCEventTouch.h" - -#ifdef CC_USE_PHYSICS -#include "physics/CCPhysicsBody.h" -#endif - -// externals -#include "kazmath/GL/matrix.h" -#include "support/component/CCComponent.h" -#include "support/component/CCComponentContainer.h" - - - -#if CC_NODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -NS_CC_BEGIN - -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2) -{ - Object *p1 = static_cast(pp1); - Object *p2 = static_cast(pp2); - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#else -bool nodeComparisonLess(Object* p1, Object* p2) -{ - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#endif - -// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. -static int s_globalOrderOfArrival = 1; -int Node::_globalEventPriorityIndex = 0; - -Node::Node(void) -: _rotationX(0.0f) -, _rotationY(0.0f) -, _scaleX(1.0f) -, _scaleY(1.0f) -, _vertexZ(0.0f) -, _position(Point::ZERO) -, _skewX(0.0f) -, _skewY(0.0f) -, _anchorPointInPoints(Point::ZERO) -, _anchorPoint(Point::ZERO) -, _contentSize(Size::ZERO) -, _additionalTransform(AffineTransform::IDENTITY) -, _transform(AffineTransform::IDENTITY) -, _inverse(AffineTransform::IDENTITY) -, _additionalTransformDirty(false) -, _transformDirty(true) -, _inverseDirty(true) -, _camera(NULL) -// children (lazy allocs) -// lazy alloc -, _grid(NULL) -, _ZOrder(0) -, _children(NULL) -, _parent(NULL) -// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true -, _tag(Node::INVALID_TAG) -// userData is always inited as nil -, _userData(NULL) -, _userObject(NULL) -, _shaderProgram(NULL) -, _orderOfArrival(0) -, _running(false) -, _visible(true) -, _ignoreAnchorPointForPosition(false) -, _reorderChildDirty(false) -, _isTransitionFinished(false) -, _updateScriptHandler(0) -, _componentContainer(NULL) -, _eventPriority(0) -, _oldEventPriority(0) -#ifdef CC_USE_PHYSICS -, _physicsBody(nullptr) -#endif -{ - // set default scheduler and actionManager - Director *director = Director::getInstance(); - _actionManager = director->getActionManager(); - _actionManager->retain(); - _scheduler = director->getScheduler(); - _scheduler->retain(); - - ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); - _scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone; -} - -Node::~Node() -{ - CCLOGINFO( "deallocing Node: %p - tag: %i", this, _tag ); - - if (_updateScriptHandler) - { - ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler); - } - - CC_SAFE_RELEASE(_actionManager); - CC_SAFE_RELEASE(_scheduler); - // attributes - CC_SAFE_RELEASE(_camera); - - CC_SAFE_RELEASE(_grid); - CC_SAFE_RELEASE(_shaderProgram); - CC_SAFE_RELEASE(_userObject); - - if(_children && _children->count() > 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* node = static_cast(child); - if (node) - { - node->_parent = NULL; - } - } - } - - // children - CC_SAFE_RELEASE(_children); - - removeAllComponents(); - - CC_SAFE_DELETE(_componentContainer); - - removeAllEventListeners(); - -#ifdef CC_USE_PHYSICS - CC_SAFE_RELEASE(_physicsBody); -#endif -} - -bool Node::init() -{ - return true; -} - -float Node::getSkewX() const -{ - return _skewX; -} - -void Node::setSkewX(float newSkewX) -{ - _skewX = newSkewX; - _transformDirty = _inverseDirty = true; -} - -float Node::getSkewY() const -{ - return _skewY; -} - -void Node::setSkewY(float newSkewY) -{ - _skewY = newSkewY; - - _transformDirty = _inverseDirty = true; -} - -/// zOrder getter -int Node::getZOrder() const -{ - return _ZOrder; -} - -/// zOrder setter : private method -/// used internally to alter the zOrder variable. DON'T call this method manually -void Node::_setZOrder(int z) -{ - _ZOrder = z; -} - -void Node::setZOrder(int z) -{ - _setZOrder(z); - if (_parent) - { - _parent->reorderChild(this, z); - } -} - -/// vertexZ getter -float Node::getVertexZ() const -{ - return _vertexZ; -} - - -/// vertexZ setter -void Node::setVertexZ(float var) -{ - _vertexZ = var; -} - - -/// rotation getter -float Node::getRotation() const -{ - CCASSERT(_rotationX == _rotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return"); - return _rotationX; -} - -/// rotation setter -void Node::setRotation(float newRotation) -{ - _rotationX = _rotationY = newRotation; - _transformDirty = _inverseDirty = true; - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setRotation(newRotation); - } -#endif -} - -float Node::getRotationX() const -{ - return _rotationX; -} - -void Node::setRotationX(float fRotationX) -{ - _rotationX = fRotationX; - _transformDirty = _inverseDirty = true; -} - -float Node::getRotationY() const -{ - return _rotationY; -} - -void Node::setRotationY(float fRotationY) -{ - _rotationY = fRotationY; - _transformDirty = _inverseDirty = true; -} - -/// scale getter -float Node::getScale(void) const -{ - CCASSERT( _scaleX == _scaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return"); - return _scaleX; -} - -/// scale setter -void Node::setScale(float scale) -{ - _scaleX = _scaleY = scale; - _transformDirty = _inverseDirty = true; -} - -/// scaleX getter -float Node::getScaleX() const -{ - return _scaleX; -} - -/// scale setter -void Node::setScale(float scaleX,float scaleY) -{ - _scaleX = scaleX; - _scaleY = scaleY; - _transformDirty = _inverseDirty = true; -} - -/// scaleX setter -void Node::setScaleX(float newScaleX) -{ - _scaleX = newScaleX; - _transformDirty = _inverseDirty = true; -} - -/// scaleY getter -float Node::getScaleY() const -{ - return _scaleY; -} - -/// scaleY setter -void Node::setScaleY(float newScaleY) -{ - _scaleY = newScaleY; - _transformDirty = _inverseDirty = true; -} - -/// position getter -const Point& Node::getPosition() const -{ - return _position; -} - -/// position setter -void Node::setPosition(const Point& newPosition) -{ - _position = newPosition; - _transformDirty = _inverseDirty = true; - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setPosition(newPosition); - } -#endif -} - -void Node::getPosition(float* x, float* y) const -{ - *x = _position.x; - *y = _position.y; -} - -void Node::setPosition(float x, float y) -{ - setPosition(Point(x, y)); -} - -float Node::getPositionX() const -{ - return _position.x; -} - -float Node::getPositionY() const -{ - return _position.y; -} - -void Node::setPositionX(float x) -{ - setPosition(Point(x, _position.y)); -} - -void Node::setPositionY(float y) -{ - setPosition(Point(_position.x, y)); -} - -unsigned int Node::getChildrenCount() const -{ - return _children ? _children->count() : 0; -} - -/// camera getter: lazy alloc -Camera* Node::getCamera() -{ - if (!_camera) - { - _camera = new Camera(); - } - - return _camera; -} - -/// grid setter -void Node::setGrid(GridBase* pGrid) -{ - CC_SAFE_RETAIN(pGrid); - CC_SAFE_RELEASE(_grid); - _grid = pGrid; -} - - -/// isVisible getter -bool Node::isVisible() const -{ - return _visible; -} - -/// isVisible setter -void Node::setVisible(bool var) -{ - _visible = var; -} - -const Point& Node::getAnchorPointInPoints() const -{ - return _anchorPointInPoints; -} - -/// anchorPoint getter -const Point& Node::getAnchorPoint() const -{ - return _anchorPoint; -} - -void Node::setAnchorPoint(const Point& point) -{ - if( ! point.equals(_anchorPoint)) - { - _anchorPoint = point; - _anchorPointInPoints = Point(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y ); - _transformDirty = _inverseDirty = true; - } -} - -/// contentSize getter -const Size& Node::getContentSize() const -{ - return _contentSize; -} - -void Node::setContentSize(const Size & size) -{ - if ( ! size.equals(_contentSize)) - { - _contentSize = size; - - _anchorPointInPoints = Point(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y ); - _transformDirty = _inverseDirty = true; - } -} - -// isRunning getter -bool Node::isRunning() const -{ - return _running; -} - -/// parent setter -void Node::setParent(Node * var) -{ - _parent = var; -} - -/// isRelativeAnchorPoint getter -bool Node::isIgnoreAnchorPointForPosition() const -{ - return _ignoreAnchorPointForPosition; -} -/// isRelativeAnchorPoint setter -void Node::ignoreAnchorPointForPosition(bool newValue) -{ - if (newValue != _ignoreAnchorPointForPosition) - { - _ignoreAnchorPointForPosition = newValue; - _transformDirty = _inverseDirty = true; - } -} - -/// tag getter -int Node::getTag() const -{ - return _tag; -} - -/// tag setter -void Node::setTag(int var) -{ - _tag = var; -} - -/// userData setter -void Node::setUserData(void *var) -{ - _userData = var; -} - -int Node::getOrderOfArrival() const -{ - return _orderOfArrival; -} - -void Node::setOrderOfArrival(int orderOfArrival) -{ - CCASSERT(orderOfArrival >=0, "Invalid orderOfArrival"); - _orderOfArrival = orderOfArrival; -} - -void Node::setUserObject(Object *pUserObject) -{ - CC_SAFE_RETAIN(pUserObject); - CC_SAFE_RELEASE(_userObject); - _userObject = pUserObject; -} - -void Node::setShaderProgram(GLProgram *pShaderProgram) -{ - CC_SAFE_RETAIN(pShaderProgram); - CC_SAFE_RELEASE(_shaderProgram); - _shaderProgram = pShaderProgram; -} - -Rect Node::getBoundingBox() const -{ - Rect rect = Rect(0, 0, _contentSize.width, _contentSize.height); - return RectApplyAffineTransform(rect, getNodeToParentTransform()); -} - -Node * Node::create(void) -{ - Node * pRet = new Node(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - return pRet; -} - -void Node::cleanup() -{ - // actions - this->stopAllActions(); - this->unscheduleAllSelectors(); - - if ( _scriptType != kScriptTypeNone) - { - int action = kNodeOnCleanup; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } - - // timers - arrayMakeObjectsPerformSelector(_children, cleanup, Node*); -} - - -const char* Node::description() const -{ - return String::createWithFormat("", _tag)->getCString(); -} - -// lazy allocs -void Node::childrenAlloc(void) -{ - _children = Array::createWithCapacity(4); - _children->retain(); -} - -Node* Node::getChildByTag(int aTag) -{ - CCASSERT( aTag != Node::INVALID_TAG, "Invalid tag"); - - if(_children && _children->count() > 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = static_cast(child); - if(pNode && pNode->_tag == aTag) - return pNode; - } - } - return NULL; -} - -/* "add" logic MUST only be on this method -* If a class want's to extend the 'addChild' behavior it only needs -* to override this method -*/ -void Node::addChild(Node *child, int zOrder, int tag) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - CCASSERT( child->_parent == NULL, "child already added. It can't be added again"); - - if( ! _children ) - { - this->childrenAlloc(); - } - - this->insertChild(child, zOrder); - - child->_tag = tag; - - child->setParent(this); - child->setOrderOfArrival(s_globalOrderOfArrival++); - - if( _running ) - { - child->onEnter(); - // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter - if (_isTransitionFinished) { - child->onEnterTransitionDidFinish(); - } - } -} - -void Node::addChild(Node *child, int zOrder) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - this->addChild(child, zOrder, child->_tag); -} - -void Node::addChild(Node *child) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - this->addChild(child, child->_ZOrder, child->_tag); -} - -void Node::removeFromParent() -{ - this->removeFromParentAndCleanup(true); -} - -void Node::removeFromParentAndCleanup(bool cleanup) -{ - if (_parent != NULL) - { - _parent->removeChild(this,cleanup); - } -} - -/* "remove" logic MUST only be on this method -* If a class want's to extend the 'removeChild' behavior it only needs -* to override this method -*/ -void Node::removeChild(Node* child, bool cleanup /* = true */) -{ - // explicit nil handling - if (_children == NULL) - { - return; - } - - int index = _children->getIndexOfObject(child); - if( index != CC_INVALID_INDEX ) - this->detachChild( child, index, cleanup ); -} - -void Node::removeChildByTag(int tag, bool cleanup/* = true */) -{ - CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); - - Node *child = this->getChildByTag(tag); - - if (child == NULL) - { - CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag); - } - else - { - this->removeChild(child, cleanup); - } -} - -void Node::removeAllChildren() -{ - this->removeAllChildrenWithCleanup(true); -} - -void Node::removeAllChildrenWithCleanup(bool cleanup) -{ - // not using detachChild improves speed here - if ( _children && _children->count() > 0 ) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = static_cast(child); - if (pNode) - { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if(_running) - { - pNode->onExitTransitionDidStart(); - pNode->onExit(); - } - - if (cleanup) - { - pNode->cleanup(); - } - // set parent nil at the end - pNode->setParent(NULL); - } - } - - _children->removeAllObjects(); - } - -} - -void Node::detachChild(Node *child, int childIndex, bool doCleanup) -{ - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (_running) - { - child->onExitTransitionDidStart(); - child->onExit(); - } - - // If you don't do cleanup, the child's actions will not get removed and the - // its scheduledSelectors_ dict will not get released! - if (doCleanup) - { - child->cleanup(); - } - - // set parent nil at the end - child->setParent(NULL); - - _children->removeObjectAtIndex(childIndex); -} - - -// helper used by reorderChild & add -void Node::insertChild(Node* child, int z) -{ - _reorderChildDirty = true; - _children->addObject(child); - child->_setZOrder(z); -} - -void Node::reorderChild(Node *child, int zOrder) -{ - CCASSERT( child != NULL, "Child must be non-nil"); - _reorderChildDirty = true; - child->setOrderOfArrival(s_globalOrderOfArrival++); - child->_setZOrder(zOrder); -} - -void Node::sortAllChildren() -{ -#if 0 - if (_reorderChildDirty) - { - int i,j,length = _children->count(); - - // insertion sort - for(i=1; i( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->_ZOrder < tempJ->_ZOrder || ( tempI->_ZOrder == tempJ->_ZOrder && tempI->_orderOfArrival < tempJ->_orderOfArrival ) ) ) - { - _children->fastSetObject( tempJ, j+1 ); - j = j-1; - if(j>=0) - tempJ = static_cast( _children->getObjectAtIndex(j) ); - } - _children->fastSetObject(tempI, j+1); - } - - //don't need to check children recursively, that's done in visit of each child - - _reorderChildDirty = false; - } -#else - if( _reorderChildDirty ) { - std::sort( std::begin(*_children), std::end(*_children), nodeComparisonLess ); - _reorderChildDirty = false; - } -#endif -} - - - void Node::draw() - { - //CCASSERT(0); - // override me - // Only use- this function to draw your stuff. - // DON'T draw your stuff outside this method - } - -void Node::visit() -{ - // quick return if not visible. children won't be drawn. - if (!_visible) - { - return; - } - - kmGLPushMatrix(); - - if (_grid && _grid->isActive()) - { - _grid->beforeDraw(); - } - - this->transform(); - int i = 0; - - if(_children && _children->count() > 0) - { - sortAllChildren(); - // draw children zOrder < 0 - for( ; i < _children->count(); i++ ) - { - auto node = static_cast( _children->getObjectAtIndex(i) ); - - if ( node && node->_ZOrder < 0 ) - node->visit(); - else - break; - } - // self draw - this->draw(); - updateEventPriorityIndex(); - - for( ; i < _children->count(); i++ ) - { - auto node = static_cast( _children->getObjectAtIndex(i) ); - if (node) - node->visit(); - } - } - else - { - this->draw(); - updateEventPriorityIndex(); - } - - // reset for next frame - _orderOfArrival = 0; - - if (_grid && _grid->isActive()) - { - _grid->afterDraw(this); - } - - kmGLPopMatrix(); -} - -void Node::transformAncestors() -{ - if( _parent != NULL ) - { - _parent->transformAncestors(); - _parent->transform(); - } -} - -#ifdef CC_USE_PHYSICS -void Node::updatePhysicsTransform() -{ - if (_physicsBody && _physicsBody->isEnable() && !_physicsBody->isResting()) - { - _position = _physicsBody->getPosition(); - _rotationX = _rotationY = _physicsBody->getRotation(); - _transformDirty = _inverseDirty = true; - } -} -#endif - - -void Node::transform() -{ -#ifdef CC_USE_PHYSICS - updatePhysicsTransform(); -#endif - - kmMat4 transfrom4x4; - - // Convert 3x3 into 4x4 matrix - CGAffineToGL(this->getNodeToParentTransform(), transfrom4x4.mat); - - // Update Z vertex manually - transfrom4x4.mat[14] = _vertexZ; - - kmGLMultMatrix( &transfrom4x4 ); - - - // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if ( _camera != NULL && !(_grid != NULL && _grid->isActive()) ) - { - bool translate = (_anchorPointInPoints.x != 0.0f || _anchorPointInPoints.y != 0.0f); - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(_anchorPointInPoints.y), 0 ); - - _camera->locate(); - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(-_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(-_anchorPointInPoints.y), 0 ); - } - -} - - -void Node::onEnter() -{ - _isTransitionFinished = false; - - arrayMakeObjectsPerformSelector(_children, onEnter, Node*); - - this->resumeSchedulerAndActions(); - - _running = true; - - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnEnter; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onEnterTransitionDidFinish() -{ - _isTransitionFinished = true; - - arrayMakeObjectsPerformSelector(_children, onEnterTransitionDidFinish, Node*); - - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnEnterTransitionDidFinish; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onExitTransitionDidStart() -{ - arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*); - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnExitTransitionDidStart; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onExit() -{ - this->pauseSchedulerAndActions(); - - _running = false; - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnExit; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } - - arrayMakeObjectsPerformSelector(_children, onExit, Node*); - - removeAllEventListeners(); -} - -void Node::setActionManager(ActionManager* actionManager) -{ - if( actionManager != _actionManager ) { - this->stopAllActions(); - CC_SAFE_RETAIN(actionManager); - CC_SAFE_RELEASE(_actionManager); - _actionManager = actionManager; - } -} - -Action * Node::runAction(Action* action) -{ - CCASSERT( action != NULL, "Argument must be non-nil"); - _actionManager->addAction(action, this, !_running); - return action; -} - -void Node::stopAllActions() -{ - _actionManager->removeAllActionsFromTarget(this); -} - -void Node::stopAction(Action* action) -{ - _actionManager->removeAction(action); -} - -void Node::stopActionByTag(int tag) -{ - CCASSERT( tag != Action::INVALID_TAG, "Invalid tag"); - _actionManager->removeActionByTag(tag, this); -} - -Action * Node::getActionByTag(int tag) -{ - CCASSERT( tag != Action::INVALID_TAG, "Invalid tag"); - return _actionManager->getActionByTag(tag, this); -} - -unsigned int Node::getNumberOfRunningActions() const -{ - return _actionManager->getNumberOfRunningActionsInTarget(this); -} - -// Node - Callbacks - -void Node::setScheduler(Scheduler* scheduler) -{ - if( scheduler != _scheduler ) { - this->unscheduleAllSelectors(); - CC_SAFE_RETAIN(scheduler); - CC_SAFE_RELEASE(_scheduler); - _scheduler = scheduler; - } -} - -bool Node::isScheduled(SEL_SCHEDULE selector) -{ - return _scheduler->isScheduledForTarget(selector, this); -} - -void Node::scheduleUpdate() -{ - scheduleUpdateWithPriority(0); -} - -void Node::scheduleUpdateWithPriority(int priority) -{ - _scheduler->scheduleUpdateForTarget(this, priority, !_running); -} - -void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) -{ - unscheduleUpdate(); - _updateScriptHandler = nHandler; - _scheduler->scheduleUpdateForTarget(this, priority, !_running); -} - -void Node::unscheduleUpdate() -{ - _scheduler->unscheduleUpdateForTarget(this); - if (_updateScriptHandler) - { - ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler); - _updateScriptHandler = 0; - } -} - -void Node::schedule(SEL_SCHEDULE selector) -{ - this->schedule(selector, 0.0f, kRepeatForever, 0.0f); -} - -void Node::schedule(SEL_SCHEDULE selector, float interval) -{ - this->schedule(selector, interval, kRepeatForever, 0.0f); -} - -void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) -{ - CCASSERT( selector, "Argument must be non-nil"); - CCASSERT( interval >=0, "Argument must be positive"); - - _scheduler->scheduleSelector(selector, this, interval , repeat, delay, !_running); -} - -void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) -{ - this->schedule(selector, 0.0f, 0, delay); -} - -void Node::unschedule(SEL_SCHEDULE selector) -{ - // explicit nil handling - if (selector == 0) - return; - - _scheduler->unscheduleSelector(selector, this); -} - -void Node::unscheduleAllSelectors() -{ - _scheduler->unscheduleAllForTarget(this); -} - -void Node::resumeSchedulerAndActions() -{ - _scheduler->resumeTarget(this); - _actionManager->resumeTarget(this); -} - -void Node::pauseSchedulerAndActions() -{ - _scheduler->pauseTarget(this); - _actionManager->pauseTarget(this); -} - -// override me -void Node::update(float fDelta) -{ - if (0 != _updateScriptHandler) - { - //only lua use - SchedulerScriptData data(_updateScriptHandler,fDelta); - ScriptEvent event(kScheduleEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } - - if (_componentContainer && !_componentContainer->isEmpty()) - { - _componentContainer->visit(fDelta); - } -} - -const AffineTransform& Node::getNodeToParentTransform() const -{ - if (_transformDirty) - { - - // Translate values - float x = _position.x; - float y = _position.y; - - if (_ignoreAnchorPointForPosition) - { - x += _anchorPointInPoints.x; - y += _anchorPointInPoints.y; - } - - // Rotation values - // Change rotation code to handle X and Y - // If we skew with the exact same value for both x and y then we're simply just rotating - float cx = 1, sx = 0, cy = 1, sy = 0; - if (_rotationX || _rotationY) - { - float radiansX = -CC_DEGREES_TO_RADIANS(_rotationX); - float radiansY = -CC_DEGREES_TO_RADIANS(_rotationY); - cx = cosf(radiansX); - sx = sinf(radiansX); - cy = cosf(radiansY); - sy = sinf(radiansY); - } - - bool needsSkewMatrix = ( _skewX || _skewY ); - - - // optimization: - // inline anchor point calculation if skew is not needed - // Adjusted transform calculation for rotational skew - if (! needsSkewMatrix && !_anchorPointInPoints.equals(Point::ZERO)) - { - x += cy * -_anchorPointInPoints.x * _scaleX + -sx * -_anchorPointInPoints.y * _scaleY; - y += sy * -_anchorPointInPoints.x * _scaleX + cx * -_anchorPointInPoints.y * _scaleY; - } - - - // Build Transform Matrix - // Adjusted transform calculation for rotational skew - _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); - - // XXX: Try to inline skew - // If skew is needed, apply skew and then anchor point - if (needsSkewMatrix) - { - AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); - _transform = AffineTransformConcat(skewMatrix, _transform); - - // adjust anchor point - if (!_anchorPointInPoints.equals(Point::ZERO)) - { - _transform = AffineTransformTranslate(_transform, -_anchorPointInPoints.x, -_anchorPointInPoints.y); - } - } - - if (_additionalTransformDirty) - { - _transform = AffineTransformConcat(_transform, _additionalTransform); - _additionalTransformDirty = false; - } - - _transformDirty = false; - } - - return _transform; -} - -void Node::setAdditionalTransform(const AffineTransform& additionalTransform) -{ - _additionalTransform = additionalTransform; - _transformDirty = true; - _additionalTransformDirty = true; -} - -const AffineTransform& Node::getParentToNodeTransform() const -{ - if ( _inverseDirty ) { - _inverse = AffineTransformInvert(this->getNodeToParentTransform()); - _inverseDirty = false; - } - - return _inverse; -} - -AffineTransform Node::getNodeToWorldTransform() const -{ - AffineTransform t = this->getNodeToParentTransform(); - - for (Node *p = _parent; p != NULL; p = p->getParent()) - t = AffineTransformConcat(t, p->getNodeToParentTransform()); - - return t; -} - -AffineTransform Node::getWorldToNodeTransform() const -{ - return AffineTransformInvert(this->getNodeToWorldTransform()); -} - -Point Node::convertToNodeSpace(const Point& worldPoint) const -{ - Point ret = PointApplyAffineTransform(worldPoint, getWorldToNodeTransform()); - return ret; -} - -Point Node::convertToWorldSpace(const Point& nodePoint) const -{ - Point ret = PointApplyAffineTransform(nodePoint, getNodeToWorldTransform()); - return ret; -} - -Point Node::convertToNodeSpaceAR(const Point& worldPoint) const -{ - Point nodePoint = convertToNodeSpace(worldPoint); - return nodePoint - _anchorPointInPoints; -} - -Point Node::convertToWorldSpaceAR(const Point& nodePoint) const -{ - Point pt = nodePoint + _anchorPointInPoints; - return convertToWorldSpace(pt); -} - -Point Node::convertToWindowSpace(const Point& nodePoint) const -{ - Point worldPoint = this->convertToWorldSpace(nodePoint); - return Director::getInstance()->convertToUI(worldPoint); -} - -// convenience methods which take a Touch instead of Point -Point Node::convertTouchToNodeSpace(Touch *touch) const -{ - Point point = touch->getLocation(); - return this->convertToNodeSpace(point); -} -Point Node::convertTouchToNodeSpaceAR(Touch *touch) const -{ - Point point = touch->getLocation(); - return this->convertToNodeSpaceAR(point); -} - -void Node::updateTransform() -{ - // Recursively iterate over children - arrayMakeObjectsPerformSelector(_children, updateTransform, Node*); -} - -Component* Node::getComponent(const char *pName) -{ - if( _componentContainer ) - return _componentContainer->get(pName); - return nullptr; -} - -bool Node::addComponent(Component *pComponent) -{ - // lazy alloc - if( !_componentContainer ) - _componentContainer = new ComponentContainer(this); - return _componentContainer->add(pComponent); -} - -bool Node::removeComponent(const char *pName) -{ - if( _componentContainer ) - return _componentContainer->remove(pName); - return false; -} - -void Node::removeAllComponents() -{ - if( _componentContainer ) - _componentContainer->removeAll(); -} - -void Node::resetEventPriorityIndex() -{ - _globalEventPriorityIndex = 0; -} - -void Node::associateEventListener(EventListener* listener) -{ - _eventlisteners.insert(listener); -} - -void Node::dissociateEventListener(EventListener* listener) -{ - _eventlisteners.erase(listener); -} - -void Node::removeAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - auto eventListenersCopy = _eventlisteners; - - for (auto& listener : eventListenersCopy) - { - dispatcher->removeEventListener(listener); - } -} - -void Node::setDirtyForAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - for (auto& listener : _eventlisteners) - { - dispatcher->setDirtyForEventType(listener->_type, true); - } -} - -#ifdef CC_USE_PHYSICS -void Node::setPhysicsBody(PhysicsBody* body) -{ - if (_physicsBody != nullptr) - { - _physicsBody->release(); - } - - _physicsBody = body; - _physicsBody->retain(); - _physicsBody->setPosition(getPosition()); - _physicsBody->setRotation(getRotation()); -} - -PhysicsBody* Node::getPhysicsBody() const -{ - return _physicsBody; -} -#endif //CC_USE_PHYSICS - -// NodeRGBA -NodeRGBA::NodeRGBA() -: _displayedOpacity(255) -, _realOpacity(255) -, _displayedColor(Color3B::WHITE) -, _realColor(Color3B::WHITE) -, _cascadeColorEnabled(false) -, _cascadeOpacityEnabled(false) -{} - -NodeRGBA::~NodeRGBA() {} - -bool NodeRGBA::init() -{ - if (Node::init()) - { - _displayedOpacity = _realOpacity = 255; - _displayedColor = _realColor = Color3B::WHITE; - _cascadeOpacityEnabled = _cascadeColorEnabled = false; - return true; - } - return false; -} - -GLubyte NodeRGBA::getOpacity(void) const -{ - return _realOpacity; -} - -GLubyte NodeRGBA::getDisplayedOpacity(void) const -{ - return _displayedOpacity; -} - -void NodeRGBA::setOpacity(GLubyte opacity) -{ - _displayedOpacity = _realOpacity = opacity; - - if (_cascadeOpacityEnabled) - { - GLubyte parentOpacity = 255; - RGBAProtocol* pParent = dynamic_cast(_parent); - if (pParent && pParent->isCascadeOpacityEnabled()) - { - parentOpacity = pParent->getDisplayedOpacity(); - } - this->updateDisplayedOpacity(parentOpacity); - } -} - -void NodeRGBA::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _displayedOpacity = _realOpacity * parentOpacity/255.0; - - if (_cascadeOpacityEnabled) - { - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - RGBAProtocol* item = dynamic_cast(pObj); - if (item) - { - item->updateDisplayedOpacity(_displayedOpacity); - } - } - } -} - -bool NodeRGBA::isCascadeOpacityEnabled(void) const -{ - return _cascadeOpacityEnabled; -} - -void NodeRGBA::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) -{ - _cascadeOpacityEnabled = cascadeOpacityEnabled; -} - -const Color3B& NodeRGBA::getColor(void) const -{ - return _realColor; -} - -const Color3B& NodeRGBA::getDisplayedColor() const -{ - return _displayedColor; -} - -void NodeRGBA::setColor(const Color3B& color) -{ - _displayedColor = _realColor = color; - - if (_cascadeColorEnabled) - { - Color3B parentColor = Color3B::WHITE; - RGBAProtocol *parent = dynamic_cast(_parent); - if (parent && parent->isCascadeColorEnabled()) - { - parentColor = parent->getDisplayedColor(); - } - - updateDisplayedColor(parentColor); - } -} - -void NodeRGBA::updateDisplayedColor(const Color3B& parentColor) -{ - _displayedColor.r = _realColor.r * parentColor.r/255.0; - _displayedColor.g = _realColor.g * parentColor.g/255.0; - _displayedColor.b = _realColor.b * parentColor.b/255.0; - - if (_cascadeColorEnabled) - { - Object *obj = NULL; - CCARRAY_FOREACH(_children, obj) - { - RGBAProtocol *item = dynamic_cast(obj); - if (item) - { - item->updateDisplayedColor(_displayedColor); - } - } - } -} - -bool NodeRGBA::isCascadeColorEnabled(void) const -{ - return _cascadeColorEnabled; -} - -void NodeRGBA::setCascadeColorEnabled(bool cascadeColorEnabled) -{ - _cascadeColorEnabled = cascadeColorEnabled; -} - -NS_CC_END diff --git a/cocos2dx/base_nodes/CCNode.h b/cocos2dx/base_nodes/CCNode.h deleted file mode 100644 index 575e4b5cfb..0000000000 --- a/cocos2dx/base_nodes/CCNode.h +++ /dev/null @@ -1,1575 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2009 Valentin Milea - Copyright (c) 2011 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __PLATFORM_CCNODE_H__ -#define __PLATFORM_CCNODE_H__ - -#include "ccMacros.h" -#include "cocoa/CCAffineTransform.h" -#include "cocoa/CCArray.h" -#include "CCGL.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "kazmath/kazmath.h" -#include "script_support/CCScriptSupport.h" -#include "CCProtocols.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "physics/CCPhysicsSetting.h" - -#include - -NS_CC_BEGIN - -class Camera; -class GridBase; -class Point; -class Touch; -class Action; -class RGBAProtocol; -class LabelProtocol; -class Scheduler; -class ActionManager; -class Component; -class Dictionary; -class ComponentContainer; -class EventDispatcher; -#ifdef CC_USE_PHYSICS -class PhysicsBody; -#endif - -/** - * @addtogroup base_nodes - * @{ - */ - -enum { - kNodeOnEnter, - kNodeOnExit, - kNodeOnEnterTransitionDidFinish, - kNodeOnExitTransitionDidStart, - kNodeOnCleanup -}; - -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2); -#else -bool nodeComparisonLess(Object* p1, Object* p2); -#endif - -class EventListener; - -/** @brief Node is the main element. Anything that gets drawn or contains things that get drawn is a Node. - The most popular Nodes are: Scene, Layer, Sprite, Menu. - - The main features of a Node are: - - They can contain other Node nodes (addChild, getChildByTag, removeChild, etc) - - They can schedule periodic callback (schedule, unschedule, etc) - - They can execute actions (runAction, stopAction, etc) - - Some Node nodes provide extra functionality for them or their children. - - Subclassing a Node usually means (one/all) of: - - overriding init to initialize resources and schedule callbacks - - create callbacks to handle the advancement of time - - overriding draw to render the node - - Features of Node: - - position - - scale (x, y) - - rotation (in degrees, clockwise) - - Camera (an interface to gluLookAt ) - - GridBase (to do mesh transformations) - - anchor point - - size - - visible - - z-order - - openGL z position - - Default values: - - rotation: 0 - - position: (x=0,y=0) - - scale: (x=1,y=1) - - contentSize: (x=0,y=0) - - anchorPoint: (x=0,y=0) - - Limitations: - - A Node is a "void" object. It doesn't have a texture - - Order in transformations with grid disabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be scaled (scale) - -# The node will be moved according to the camera values (camera) - - Order in transformations with grid enabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be scaled (scale) - -# The grid will capture the screen - -# The node will be moved according to the camera values (camera) - -# The grid will render the captured screen - - Camera: - - Each node has a camera. By default it points to the center of the Node. - */ - -class CC_DLL Node : public Object -{ -public: - /// Default tag used for all the nodes - static const int INVALID_TAG = -1; - - /// @{ - /// @name Constructor, Destructor and Initializers - - /** - * Allocates and initializes a node. - * @return A initialized node which is marked as "autorelease". - */ - static Node * create(void); - - /** - * Default constructor - * @js ctor - */ - Node(void); - - /** - * Default destructor - * @js NA - * @lua NA - */ - virtual ~Node(void); - - /** - * Initializes the instance of Node - * @return Whether the initialization was successful. - */ - virtual bool init(); - - /** - * Gets the description string. It makes debugging easier. - * @return A string terminated with '\0' - * @js NA - * @lua NA - */ - const char* description(void) const; - - /// @} end of initializers - - - - /// @{ - /// @name Setters & Getters for Graphic Peroperties - - /** - * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. - * - * The Z order of node is relative to its "brothers": children of the same parent. - * It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d. - * The larger number it is, the later this node will be drawn in each message loop. - * Please refer to setVertexZ(float) for the difference. - * - * @param zOrder Z order of this node. - */ - virtual void setZOrder(int zOrder); - /** - * Sets the z order which stands for the drawing order - * - * This is an internal method. Don't call it outside the framework. - * The difference between setZOrder(int) and _setOrder(int) is: - * - _setZOrder(int) is a pure setter for _ZOrder memeber variable - * - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array. - */ - virtual void _setZOrder(int z); - /** - * Gets the Z order of this node. - * - * @see setZOrder(int) - * - * @return The Z order. - */ - virtual int getZOrder() const; - - /** - * Sets the real OpenGL Z vertex. - * - * Differences between openGL Z vertex and cocos2d Z order: - * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - * - OpenGL Z might require to set 2D projection - * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0 - * - * @warning Use it at your own risk since it might break the cocos2d parent-children z order - * - * @param vertexZ OpenGL Z vertex of this node. - */ - virtual void setVertexZ(float vertexZ); - /** - * Gets OpenGL Z vertex of this node. - * - * @see setVertexZ(float) - * - * @return OpenGL Z vertex of this node - */ - virtual float getVertexZ() const; - - - /** - * Changes the scale factor on X axis of this node - * - * The deafult value is 1.0 if you haven't changed it before - * - * @param scaleX The scale factor on X axis. - */ - virtual void setScaleX(float scaleX); - /** - * Returns the scale factor on X axis of this node - * - * @see setScaleX(float) - * - * @return The scale factor on X axis. - */ - virtual float getScaleX() const; - - - /** - * Changes the scale factor on Y axis of this node - * - * The Default value is 1.0 if you haven't changed it before. - * - * @param scaleY The scale factor on Y axis. - */ - virtual void setScaleY(float scaleY); - /** - * Returns the scale factor on Y axis of this node - * - * @see setScaleY(float) - * - * @return The scale factor on Y axis. - */ - virtual float getScaleY() const; - - - /** - * Changes both X and Y scale factor of the node. - * - * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. - * - * @param scale The scale factor for both X and Y axis. - */ - virtual void setScale(float scale); - /** - * Gets the scale factor of the node, when X and Y have the same scale factor. - * - * @warning Assert when _scaleX != _scaleY. - * @see setScale(float) - * - * @return The scale factor of the node. - */ - virtual float getScale() const; - - /** - * Changes both X and Y scale factor of the node. - * - * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. - * - * @param scaleX The scale factor on X axis. - * @param scaleY The scale factor on Y axis. - */ - virtual void setScale(float scaleX,float scaleY); - - /** - * Changes the position (x,y) of the node in OpenGL coordinates - * - * Usually we use Point(x,y) to compose Point object. - * The original point (0,0) is at the left-bottom corner of screen. - * For example, this codesnip sets the node in the center of screen. - * @code - * Size size = Director::getInstance()->getWinSize(); - * node->setPosition( Point(size.width/2, size.height/2) ) - * @endcode - * - * @param position The position (x,y) of the node in OpenGL coordinates - */ - virtual void setPosition(const Point &position); - /** - * Gets the position (x,y) of the node in OpenGL coordinates - * - * @see setPosition(const Point&) - * - * @return The position (x,y) of the node in OpenGL coordinates - * @code - * In js and lua return value is table which contains x,y - * @endcode - */ - virtual const Point& getPosition() const; - /** - * Sets position in a more efficient way. - * - * Passing two numbers (x,y) is much efficient than passing Point object. - * This method is binded to lua and javascript. - * Passing a number is 10 times faster than passing a object from lua to c++ - * - * @code - * // sample code in lua - * local pos = node::getPosition() -- returns Point object from C++ - * node:setPosition(x, y) -- pass x, y coordinate to C++ - * @endcode - * - * @param x X coordinate for position - * @param y Y coordinate for position - */ - virtual void setPosition(float x, float y); - /** - * Gets position in a more efficient way, returns two number instead of a Point object - * - * @see setPosition(float, float) - * @code - * In js,out value not return - * @endcode - */ - virtual void getPosition(float* x, float* y) const; - /** - * Gets/Sets x or y coordinate individually for position. - * These methods are used in Lua and Javascript Bindings - */ - virtual void setPositionX(float x); - virtual float getPositionX(void) const; - virtual void setPositionY(float y); - virtual float getPositionY(void) const; - - - /** - * Changes the X skew angle of the node in degrees. - * - * This angle describes the shear distortion in the X direction. - * Thus, it is the angle between the Y axis and the left edge of the shape - * The default skewX angle is 0. Positive values distort the node in a CW direction. - * - * @param fSkewX The X skew angle of the node in degrees. - */ - virtual void setSkewX(float fSkewX); - /** - * Returns the X skew angle of the node in degrees. - * - * @see setSkewX(float) - * - * @return The X skew angle of the node in degrees. - */ - virtual float getSkewX() const; - - - /** - * Changes the Y skew angle of the node in degrees. - * - * This angle describes the shear distortion in the Y direction. - * Thus, it is the angle between the X axis and the bottom edge of the shape - * The default skewY angle is 0. Positive values distort the node in a CCW direction. - * - * @param fSkewY The Y skew angle of the node in degrees. - */ - virtual void setSkewY(float fSkewY); - /** - * Returns the Y skew angle of the node in degrees. - * - * @see setSkewY(float) - * - * @return The Y skew angle of the node in degrees. - */ - virtual float getSkewY() const; - - - /** - * Sets the anchor point in percent. - * - * anchorPoint is the point around which all transformations and positioning manipulations take place. - * It's like a pin in the node where it is "attached" to its parent. - * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. - * But you can use values higher than (1,1) and lower than (0,0) too. - * The default anchorPoint is (0.5,0.5), so it starts in the center of the node. - * - * @param anchorPoint The anchor point of node. - */ - virtual void setAnchorPoint(const Point& anchorPoint); - /** - * Returns the anchor point in percent. - * - * @see setAnchorPoint(const Point&) - * - * @return The anchor point of node. - */ - virtual const Point& getAnchorPoint() const; - /** - * Returns the anchorPoint in absolute pixels. - * - * @warning You can only read it. If you wish to modify it, use anchorPoint instead. - * @see getAnchorPoint() - * - * @return The anchor point in absolute pixels. - */ - virtual const Point& getAnchorPointInPoints() const; - - - /** - * Sets the untransformed size of the node. - * - * The contentSize remains the same no matter the node is scaled or rotated. - * All nodes has a size. Layer and Scene has the same size of the screen. - * - * @param contentSize The untransformed size of the node. - */ - virtual void setContentSize(const Size& contentSize); - /** - * Returns the untransformed size of the node. - * - * @see setContentSize(const Size&) - * - * @return The untransformed size of the node. - */ - virtual const Size& getContentSize() const; - - - /** - * Sets whether the node is visible - * - * The default value is true, a node is default to visible - * - * @param visible true if the node is visible, false if the node is hidden. - */ - virtual void setVisible(bool visible); - /** - * Determines if the node is visible - * - * @see setVisible(bool) - * - * @return true if the node is visible, false if the node is hidden. - */ - virtual bool isVisible() const; - - - /** - * Sets the rotation (angle) of the node in degrees. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotation The rotation of the node in degrees. - */ - virtual void setRotation(float rotation); - /** - * Returns the rotation of the node in degrees. - * - * @see setRotation(float) - * - * @return The rotation of the node in degrees. - */ - virtual float getRotation() const; - - - /** - * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotationX The X rotation in degrees which performs a horizontal rotational skew. - */ - virtual void setRotationX(float rotationX); - /** - * Gets the X rotation (angle) of the node in degrees which performs a horizontal rotation skew. - * - * @see setRotationX(float) - * - * @return The X rotation in degrees. - */ - virtual float getRotationX() const; - - - /** - * Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotationY The Y rotation in degrees. - */ - virtual void setRotationY(float rotationY); - /** - * Gets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. - * - * @see setRotationY(float) - * - * @return The Y rotation in degrees. - */ - virtual float getRotationY() const; - - - /** - * Sets the arrival order when this node has a same ZOrder with other children. - * - * A node which called addChild subsequently will take a larger arrival order, - * If two children have the same Z order, the child with larger arrival order will be drawn later. - * - * @warning This method is used internally for zOrder sorting, don't change this manually - * - * @param orderOfArrival The arrival order. - */ - virtual void setOrderOfArrival(int orderOfArrival); - /** - * Returns the arrival order, indecates which children is added previously. - * - * @see setOrderOfArrival(unsigned int) - * - * @return The arrival order. - */ - virtual int getOrderOfArrival() const; - - - /** @deprecated No longer needed - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void setGLServerState(int serverState) { /* ignore */ }; - /** @deprecated No longer needed - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE int getGLServerState() const { return 0; } - - /** - * Sets whether the anchor point will be (0,0) when you position this node. - * - * This is an internal method, only used by Layer and Scene. Don't call it outside framework. - * The default value is false, while in Layer and Scene are true - * - * @param ignore true if anchor point will be (0,0) when you position this node - * @todo This method shoud be renamed as setIgnoreAnchorPointForPosition(bool) or something with "set" - */ - virtual void ignoreAnchorPointForPosition(bool ignore); - /** - * Gets whether the anchor point will be (0,0) when you position this node. - * - * @see ignoreAnchorPointForPosition(bool) - * - * @return true if the anchor point will be (0,0) when you position this node. - */ - virtual bool isIgnoreAnchorPointForPosition() const; - - /// @} end of Setters & Getters for Graphic Peroperties - - - /// @{ - /// @name Children and Parent - - /** - * Adds a child to the container with z-order as 0. - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - */ - virtual void addChild(Node * child); - /** - * Adds a child to the container with a z-order - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - */ - virtual void addChild(Node * child, int zOrder); - /** - * Adds a child to the container with z order and tag - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - * @param tag A interger to identify the node easily. Please refer to setTag(int) - */ - virtual void addChild(Node* child, int zOrder, int tag); - /** - * Gets a child from the container with its tag - * - * @param tag An identifier to find the child node. - * - * @return a Node object whose tag equals to the input parameter - */ - Node * getChildByTag(int tag); - /** - * Return an array of children - * - * Composing a "tree" structure is a very important feature of Node - * Here's a sample code of traversing children array: - * @code - * Node* node = NULL; - * CCARRAY_FOREACH(parent->getChildren(), node) - * { - * node->setPosition(0,0); - * } - * @endcode - * This sample code traverses all children nodes, and set their position to (0,0) - * - * @return An array of children - */ - virtual Array* getChildren() { return _children; } - virtual const Array *getChildren() const { return _children; } - - /** - * Get the amount of children. - * - * @return The amount of children. - */ - unsigned int getChildrenCount() const; - - /** - * Sets the parent node - * - * @param parent A pointer to the parnet node - */ - virtual void setParent(Node* parent); - /** - * Returns a pointer to the parent node - * - * @see setParent(Node*) - * - * @returns A pointer to the parnet node - */ - virtual Node* getParent() { return _parent; } - virtual const Node* getParent() const { return _parent; } - - - ////// REMOVES ////// - - /** - * Removes this node itself from its parent node with a cleanup. - * If the node orphan, then nothing happens. - * @see removeFromParentAndCleanup(bool) - */ - virtual void removeFromParent(); - /** - * Removes this node itself from its parent node. - * If the node orphan, then nothing happens. - * @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. - * @js removeFromParent - * @lua removeFromParent - */ - virtual void removeFromParentAndCleanup(bool cleanup); - - /** - * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. - * - * @param child The child node which will be removed. - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChild(Node* child, bool cleanup = true); - - /** - * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter - * - * @param tag An interger number that identifies a child node - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChildByTag(int tag, bool cleanup = true); - /** - * Removes all children from the container with a cleanup. - * - * @see removeAllChildrenWithCleanup(bool) - */ - virtual void removeAllChildren(); - /** - * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. - * - * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. - * @js removeAllChildren - * @lua removeAllChildren - */ - virtual void removeAllChildrenWithCleanup(bool cleanup); - - /** - * Reorders a child according to a new z value. - * - * @param child An already added child node. It MUST be already added. - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - */ - virtual void reorderChild(Node * child, int zOrder); - - /** - * Sorts the children array once before drawing, instead of every time when a child is added or reordered. - * This appraoch can improves the performance massively. - * @note Don't call this manually unless a child added needs to be removed in the same frame - */ - virtual void sortAllChildren(); - - /// @} end of Children and Parent - - - - /// @{ - /// @name Grid object for effects - - /** - * Returns a grid object that is used when applying effects - * - * @return A Grid object that is used when applying effects - * @js NA - */ - virtual GridBase* getGrid() { return _grid; } - /** - * @js NA - */ - virtual const GridBase* getGrid() const { return _grid; } - - /** - * Changes a grid object that is used when applying effects - * - * @param grid A Grid object that is used when applying effects - */ - virtual void setGrid(GridBase *grid); - - /// @} end of Grid - - - /// @{ - /// @name Tag & User data - - /** - * Returns a tag that is used to identify the node easily. - * - * You can set tags to node then identify them easily. - * @code - * #define TAG_PLAYER 1 - * #define TAG_MONSTER 2 - * #define TAG_BOSS 3 - * // set tags - * node1->setTag(TAG_PLAYER); - * node2->setTag(TAG_MONSTER); - * node3->setTag(TAG_BOSS); - * parent->addChild(node1); - * parent->addChild(node2); - * parent->addChild(node3); - * // identify by tags - * Node* node = NULL; - * CCARRAY_FOREACH(parent->getChildren(), node) - * { - * switch(node->getTag()) - * { - * case TAG_PLAYER: - * break; - * case TAG_MONSTER: - * break; - * case TAG_BOSS: - * break; - * } - * } - * @endcode - * - * @return A interger that identifies the node. - */ - virtual int getTag() const; - /** - * Changes the tag that is used to identify the node easily. - * - * Please refer to getTag for the sample code. - * - * @param tag A interger that indentifies the node. - */ - virtual void setTag(int tag); - - /** - * Returns a custom user data pointer - * - * You can set everything in UserData pointer, a data block, a structure or an object. - * - * @return A custom user data pointer - * @js NA - * @lua NA - */ - virtual void* getUserData() { return _userData; } - /** - * @js NA - * @lua NA - */ - virtual const void* getUserData() const { return _userData; } - - /** - * Sets a custom user data pointer - * - * You can set everything in UserData pointer, a data block, a structure or an object, etc. - * @warning Don't forget to release the memroy manually, - * especially before you change this data pointer, and before this node is autoreleased. - * - * @param userData A custom user data pointer - * @js NA - * @lua NA - */ - virtual void setUserData(void *userData); - - /** - * Returns a user assigned Object - * - * Similar to userData, but instead of holding a void* it holds an object - * - * @return A user assigned Object - * @js NA - * @lua NA - */ - virtual Object* getUserObject() { return _userObject; } - /** - * @js NA - * @lua NA - */ - virtual const Object* getUserObject() const { return _userObject; } - - /** - * Returns a user assigned Object - * - * Similar to UserData, but instead of holding a void* it holds an object. - * The UserObject will be retained once in this method, - * and the previous UserObject (if existed) will be relese. - * The UserObject will be released in Node's destructure. - * - * @param userObject A user assigned Object - */ - virtual void setUserObject(Object *userObject); - - /// @} end of Tag & User Data - - - /// @{ - /// @name Shader Program - /** - * Return the shader program currently used for this node - * - * @return The shader program currelty used for this node - */ - virtual GLProgram* getShaderProgram() { return _shaderProgram; } - virtual const GLProgram* getShaderProgram() const { return _shaderProgram; } - - /** - * Sets the shader program for this node - * - * Since v2.0, each rendering node must set its shader program. - * It should be set in initialize phase. - * @code - * node->setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - * @endcode - * - * @param shaderProgram The shader program which fetchs from ShaderCache. - */ - virtual void setShaderProgram(GLProgram *shaderProgram); - /// @} end of Shader Program - - - /** - * Returns a camera object that lets you move the node using a gluLookAt - * - * @code - * Camera* camera = node->getCamera(); - * camera->setEye(0, 0, 415/2); - * camera->setCenter(0, 0, 0); - * @endcode - * - * @return A Camera object that lets you move the node using a gluLookAt - */ - virtual Camera* getCamera(); - - /** - * Returns whether or not the node accepts event callbacks. - * - * Running means the node accept event callbacks like onEnter(), onExit(), update() - * - * @return Whether or not the node is running. - */ - virtual bool isRunning() const; - - /** - * Schedules for lua script. - * @js NA - */ - void scheduleUpdateWithPriorityLua(int handler, int priority); - - /// @} end Script Bindings - - - /// @{ - /// @name Event Callbacks - - /** - * Event callback that is invoked every time when Node enters the 'stage'. - * If the Node enters the 'stage' with a transition, this event is called when the transition starts. - * During onEnter you can't access a "sister/brother" node. - * If you override onEnter, you shall call its parent's one, e.g., Node::onEnter(). - * @js NA - * @lua NA - */ - virtual void onEnter(); - - /** Event callback that is invoked when the Node enters in the 'stage'. - * If the Node enters the 'stage' with a transition, this event is called when the transition finishes. - * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish() - * @js NA - * @lua NA - */ - virtual void onEnterTransitionDidFinish(); - - /** - * Event callback that is invoked every time the Node leaves the 'stage'. - * If the Node leaves the 'stage' with a transition, this event is called when the transition finishes. - * During onExit you can't access a sibling node. - * If you override onExit, you shall call its parent's one, e.g., Node::onExit(). - * @js NA - * @lua NA - */ - virtual void onExit(); - - /** - * Event callback that is called every time the Node leaves the 'stage'. - * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts. - * @js NA - * @lua NA - */ - virtual void onExitTransitionDidStart(); - - /// @} end of event callbacks. - - - /** - * Stops all running actions and schedulers - */ - virtual void cleanup(); - - /** - * Override this method to draw your own node. - * The following GL states will be enabled by default: - * - glEnableClientState(GL_VERTEX_ARRAY); - * - glEnableClientState(GL_COLOR_ARRAY); - * - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - * - glEnable(GL_TEXTURE_2D); - * AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE - * But if you enable any other GL state, you should disable it after drawing your node. - */ - virtual void draw(); - - /** - * Visits this node's children and draw them recursively. - */ - virtual void visit(); - - - /** - * Returns a "local" axis aligned bounding box of the node. - * The returned box is relative only to its parent. - * - * @note This method returns a temporaty variable, so it can't returns const Rect& - * @todo Rename to getBoundingBox() in the future versions. - * - * @return A "local" axis aligned boudning box of the node. - */ - virtual Rect getBoundingBox() const; - - /** @deprecated Use getBoundingBox instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual Rect boundingBox() const { return getBoundingBox(); } - - /// @{ - /// @name Actions - - /** - * Sets the ActionManager object that is used by all actions. - * - * @warning If you set a new ActionManager, then previously created actions will be removed. - * - * @param actionManager A ActionManager object that is used by all actions. - */ - virtual void setActionManager(ActionManager* actionManager); - /** - * Gets the ActionManager object that is used by all actions. - * @see setActionManager(ActionManager*) - * @return A ActionManager object. - */ - virtual ActionManager* getActionManager() { return _actionManager; } - virtual const ActionManager* getActionManager() const { return _actionManager; } - - /** - * Executes an action, and returns the action that is executed. - * - * This node becomes the action's target. Refer to Action::getTarget() - * @warning Actions don't retain their target. - * - * @return An Action pointer - */ - Action* runAction(Action* action); - - /** - * Stops and removes all actions from the running action list . - */ - void stopAllActions(); - - /** - * Stops and removes an action from the running action list. - * - * @param action The action object to be removed. - */ - void stopAction(Action* action); - - /** - * Removes an action from the running action list by its tag. - * - * @param tag A tag that indicates the action to be removed. - */ - void stopActionByTag(int tag); - - /** - * Gets an action from the running action list by its tag. - * - * @see setTag(int), getTag(). - * - * @return The action object with the given tag. - */ - Action* getActionByTag(int tag); - - /** - * Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). - * - * Composable actions are counted as 1 action. Example: - * If you are running 1 Sequence of 7 actions, it will return 1. - * If you are running 7 Sequences of 2 actions, it will return 7. - * @todo Rename to getNumberOfRunningActions() - * - * @return The number of actions that are running plus the ones that are schedule to run - */ - unsigned int getNumberOfRunningActions() const; - - /** @deprecated Use getNumberOfRunningActions() instead */ - CC_DEPRECATED_ATTRIBUTE unsigned int numberOfRunningActions() const { return getNumberOfRunningActions(); }; - - /// @} end of Actions - - - /// @{ - /// @name Scheduler and Timer - - /** - * Sets a Scheduler object that is used to schedule all "updates" and timers. - * - * @warning If you set a new Scheduler, then previously created timers/update are going to be removed. - * @param scheduler A Shdeduler object that is used to schedule all "update" and timers. - */ - virtual void setScheduler(Scheduler* scheduler); - /** - * Gets a Sheduler object. - * - * @see setScheduler(Scheduler*) - * @return A Scheduler object. - */ - virtual Scheduler* getScheduler() { return _scheduler; } - virtual const Scheduler* getScheduler() const { return _scheduler; } - - - /** - * Checks whether a selector is scheduled. - * - * @param selector A function selector - * @return Whether the funcion selector is scheduled. - * @js NA - * @lua NA - */ - bool isScheduled(SEL_SCHEDULE selector); - - /** - * Schedules the "update" method. - * - * It will use the order number 0. This method will be called every frame. - * Scheduled methods with a lower order value will be called before the ones that have a higher order value. - * Only one "update" method could be scheduled per node. - * @js NA - * @lua NA - */ - void scheduleUpdate(void); - - /** - * Schedules the "update" method with a custom priority. - * - * This selector will be called every frame. - * Scheduled methods with a lower priority will be called before the ones that have a higher value. - * Only one "update" selector could be scheduled per node (You can't have 2 'update' selectors). - * @js NA - * @lua NA - */ - void scheduleUpdateWithPriority(int priority); - - /* - * Unschedules the "update" method. - * @see scheduleUpdate(); - */ - void unscheduleUpdate(void); - - /** - * Schedules a custom selector. - * - * If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. - * @code - * // firstly, implement a schedule function - * void MyNode::TickMe(float dt); - * // wrap this function into a selector via schedule_selector marco. - * this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0); - * @endcode - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. - * @param repeat The selector will be excuted (repeat + 1) times, you can use kRepeatForever for tick infinitely. - * @param delay The amount of time that the first tick will wait before execution. - * @lua NA - */ - void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay); - - /** - * Schedules a custom selector with an interval time in seconds. - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param interval Callback interval time in seconds. 0 means tick every frame, - * @lua NA - */ - void schedule(SEL_SCHEDULE selector, float interval); - - /** - * Schedules a selector that runs only once, with a delay of 0 or larger - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param delay The amount of time that the first tick will wait before execution. - * @lua NA - */ - void scheduleOnce(SEL_SCHEDULE selector, float delay); - - /** - * Schedules a custom selector, the scheduled selector will be ticked every frame - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector A function wrapped as a selector - * @lua NA - */ - void schedule(SEL_SCHEDULE selector); - - /** - * Unschedules a custom selector. - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector A function wrapped as a selector - * @lua NA - */ - void unschedule(SEL_SCHEDULE selector); - - /** - * Unschedule all scheduled selectors: custom selectors, and the 'update' selector. - * Actions are not affected by this method. - * @lua NA - */ - void unscheduleAllSelectors(void); - - /** - * Resumes all scheduled selectors and actions. - * This method is called internally by onEnter - */ - void resumeSchedulerAndActions(void); - /** - * Pauses all scheduled selectors and actions. - * This method is called internally by onExit - */ - void pauseSchedulerAndActions(void); - - /* - * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" - */ - virtual void update(float delta); - - /// @} end of Scheduler and Timer - - /// @{ - /// @name Transformations - - /** - * Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. - */ - void transform(); - /** - * Performs OpenGL view-matrix transformation of it's ancestors. - * Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) - * It's necessary to transform the ancestors again. - */ - void transformAncestors(); - /** - * Calls children's updateTransform() method recursively. - * - * This method is moved from Sprite, so it's no longer specific to Sprite. - * As the result, you apply SpriteBatchNode's optimization on your customed Node. - * e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before. - */ - virtual void updateTransform(); - - /** - * Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates. - * The matrix is in Pixels. - */ - virtual const AffineTransform& getNodeToParentTransform() const; - - /** @deprecated use getNodeToParentTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToParentTransform() const { return getNodeToParentTransform(); } - - /** - * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. - * The matrix is in Pixels. - */ - virtual const AffineTransform& getParentToNodeTransform() const; - - /** @deprecated Use getParentToNodeTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform parentToNodeTransform() const { return getParentToNodeTransform(); } - - /** - * Returns the world affine transform matrix. The matrix is in Pixels. - */ - virtual AffineTransform getNodeToWorldTransform() const; - - /** @deprecated Use getNodeToWorldTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToWorldTransform() const { return getNodeToWorldTransform(); } - - /** - * Returns the inverse world affine transform matrix. The matrix is in Pixels. - */ - virtual AffineTransform getWorldToNodeTransform() const; - - /** @deprecated Use worldToNodeTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform worldToNodeTransform() const { return getWorldToNodeTransform(); } - - /// @} end of Transformations - - - /// @{ - /// @name Coordinate Converters - - /** - * Converts a Point to node (local) space coordinates. The result is in Points. - */ - Point convertToNodeSpace(const Point& worldPoint) const; - - /** - * Converts a Point to world space coordinates. The result is in Points. - */ - Point convertToWorldSpace(const Point& nodePoint) const; - - /** - * Converts a Point to node (local) space coordinates. The result is in Points. - * treating the returned/received node point as anchor relative. - */ - Point convertToNodeSpaceAR(const Point& worldPoint) const; - - /** - * Converts a local Point to world space coordinates.The result is in Points. - * treating the returned/received node point as anchor relative. - */ - Point convertToWorldSpaceAR(const Point& nodePoint) const; - - /** - * convenience methods which take a Touch instead of Point - */ - Point convertTouchToNodeSpace(Touch * touch) const; - - /** - * converts a Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative). - */ - Point convertTouchToNodeSpaceAR(Touch * touch) const; - - /** - * Sets the additional transform. - * - * @note The additional transform will be concatenated at the end of getNodeToParentTransform. - * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't). - * @code - // create a batchNode - SpriteBatchNode* batch= SpriteBatchNode::create("Icon-114.png"); - this->addChild(batch); - - // create two sprites, spriteA will be added to batchNode, they are using different textures. - Sprite* spriteA = Sprite::createWithTexture(batch->getTexture()); - Sprite* spriteB = Sprite::create("Icon-72.png"); - - batch->addChild(spriteA); - - // We can't make spriteB as spriteA's child since they use different textures. So just add it to layer. - // But we want to simulate `parent-child` relationship for these two node. - this->addChild(spriteB); - - //position - spriteA->setPosition(Point(200, 200)); - - // Gets the spriteA's transform. - AffineTransform t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - - //scale - spriteA->setScale(2); - - // Gets the spriteA's transform. - t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - - //rotation - spriteA->setRotation(20); - - // Gets the spriteA's transform. - t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - * @endcode - */ - void setAdditionalTransform(const AffineTransform& additionalTransform); - - /// @} end of Coordinate Converters - - /// @{ - /// @name component functions - /** - * gets a component by its name - */ - Component* getComponent(const char *pName); - - /** - * adds a component - */ - virtual bool addComponent(Component *pComponent); - - /** - * removes a component by its name - */ - virtual bool removeComponent(const char *pName); - - /** - * removes all components - */ - virtual void removeAllComponents(); - /// @} end of component functions - - -#ifdef CC_USE_PHYSICS - /** - * set the PhysicsBody that let the sprite effect with physics - */ - void setPhysicsBody(PhysicsBody* body); - - /** - * get the PhysicsBody the sprite have - */ - PhysicsBody* getPhysicsBody() const; - - /** - * update rotation and position from physics body - */ - virtual void updatePhysicsTransform(); -#endif - - -private: - friend class Director; - friend class EventDispatcher; - - int getEventPriority() const { return _eventPriority; }; - - void associateEventListener(EventListener* listener); - void dissociateEventListener(EventListener* listener); - - static void resetEventPriorityIndex(); - std::set _eventlisteners; - -protected: - - /// Upates event priority for this node. - inline void updateEventPriorityIndex() { - _oldEventPriority = _eventPriority; - _eventPriority = ++_globalEventPriorityIndex; - if (_oldEventPriority != _eventPriority) - { - setDirtyForAllEventListeners(); - } - }; - - /// Removes all event listeners that associated with this node. - void removeAllEventListeners(); - - /// Sets dirty for event listener. - void setDirtyForAllEventListeners(); - - /// lazy allocs - void childrenAlloc(void); - - /// helper that reorder a child - void insertChild(Node* child, int z); - - /// Removes a child, call child->onExit(), do cleanup, remove it from children array. - void detachChild(Node *child, int index, bool doCleanup); - - /// Convert cocos2d coordinates to UI windows coordinate. - Point convertToWindowSpace(const Point& nodePoint) const; - - - float _rotationX; ///< rotation angle on x-axis - float _rotationY; ///< rotation angle on y-axis - - float _scaleX; ///< scaling factor on x-axis - float _scaleY; ///< scaling factor on y-axis - - float _vertexZ; ///< OpenGL real Z vertex - - Point _position; ///< position of the node - - float _skewX; ///< skew angle on x-axis - float _skewY; ///< skew angle on y-axis - - Point _anchorPointInPoints; ///< anchor point in points - Point _anchorPoint; ///< anchor point normalized (NOT in points) - - Size _contentSize; ///< untransformed size of the node - - // "cache" variables are allowed to be mutable - mutable AffineTransform _additionalTransform; ///< transform - mutable AffineTransform _transform; ///< transform - mutable AffineTransform _inverse; ///< inverse transform - mutable bool _additionalTransformDirty; ///< The flag to check whether the additional transform is dirty - mutable bool _transformDirty; ///< transform dirty flag - mutable bool _inverseDirty; ///< inverse transform dirty flag - - Camera *_camera; ///< a camera - - GridBase *_grid; ///< a grid - - int _ZOrder; ///< z-order value that affects the draw order - - Array *_children; ///< array of children nodes - Node *_parent; ///< weak reference to parent node - - int _tag; ///< a tag. Can be any number you assigned just to identify this node - - void *_userData; ///< A user assingned void pointer, Can be point to any cpp object - Object *_userObject; ///< A user assigned Object - - GLProgram *_shaderProgram; ///< OpenGL shader - - int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder - - Scheduler *_scheduler; ///< scheduler used to schedule timers and updates - - ActionManager *_actionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions - - bool _running; ///< is running - - bool _visible; ///< is this node visible - - bool _ignoreAnchorPointForPosition; ///< true if the Anchor Point will be (0,0) when you position the Node, false otherwise. - ///< Used by Layer and Scene. - - bool _reorderChildDirty; ///< children order dirty flag - bool _isTransitionFinished; ///< flag to indicate whether the transition was finished - - int _scriptHandler; ///< script handler for onEnter() & onExit(), used in Javascript binding and Lua binding. - int _updateScriptHandler; ///< script handler for update() callback per frame, which is invoked from lua & javascript. - ccScriptType _scriptType; ///< type of script binding, lua or javascript - - ComponentContainer *_componentContainer; ///< Dictionary of components - - int _eventPriority; ///< The scene graph based priority of event listener. - int _oldEventPriority; ///< The old scene graph based priority of event listener. - static int _globalEventPriorityIndex; ///< The index of global event priority. - -#ifdef CC_USE_PHYSICS - PhysicsBody* _physicsBody; ///< the physicsBody the node have -#endif -}; - -//#pragma mark - NodeRGBA - -/** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol. - - All features from Node are valid, plus the following new features: - - opacity - - RGB colors - - Opacity/Color propagates into children that conform to the RGBAProtocol if cascadeOpacity/cascadeColor is enabled. - @since v2.1 - */ -class CC_DLL NodeRGBA : public Node, public RGBAProtocol -{ -public: - /** - * @js ctor - */ - NodeRGBA(); - /** - * @js NA - * @lua NA - */ - virtual ~NodeRGBA(); - - virtual bool init(); - - // overrides - virtual GLubyte getOpacity() const override; - virtual GLubyte getDisplayedOpacity() const override; - virtual void setOpacity(GLubyte opacity) override; - virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; - virtual bool isCascadeOpacityEnabled() const override; - virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override; - - virtual const Color3B& getColor(void) const override; - virtual const Color3B& getDisplayedColor() const override; - virtual void setColor(const Color3B& color) override; - virtual void updateDisplayedColor(const Color3B& parentColor) override; - virtual bool isCascadeColorEnabled() const override; - virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override; - - virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);}; - virtual bool isOpacityModifyRGB() const override { return false; }; - -protected: - GLubyte _displayedOpacity; - GLubyte _realOpacity; - Color3B _displayedColor; - Color3B _realColor; - bool _cascadeColorEnabled; - bool _cascadeOpacityEnabled; -}; - -// end of base_node group -/// @} - -NS_CC_END - -#endif // __PLATFORM_CCNODE_H__ diff --git a/cocos2dx/cocoa/CCGeometry.h b/cocos2dx/cocoa/CCGeometry.h deleted file mode 100644 index 94bbf3fb10..0000000000 --- a/cocos2dx/cocoa/CCGeometry.h +++ /dev/null @@ -1,584 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCGEMETRY_H__ -#define __CCGEMETRY_H__ - -#include -#include - -#include "platform/CCPlatformMacros.h" -#include "CCObject.h" -#include "ccMacros.h" - -NS_CC_BEGIN - -/** Clamp a value between from and to. - @since v0.99.1 - */ -inline float clampf(float value, float min_inclusive, float max_inclusive) -{ - if (min_inclusive > max_inclusive) { - CC_SWAP(min_inclusive, max_inclusive, float); - } - return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive; -} - -/** - * @addtogroup data_structures - * @{ - */ - -// for Point assignement operator and copy constructor -class CC_DLL Size; - -class CC_DLL Point -{ -public: - float x; - float y; - -public: - /** - * @js NA - */ - Point(); - /** - * @js NA - */ - Point(float x, float y); - /** - * @js NA - * @lua NA - */ - Point(const Point& other); - /** - * @js NA - * @lua NA - */ - explicit Point(const Size& size); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Point& other); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Size& size); - /** - * @js NA - * @lua NA - */ - Point operator+(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point& operator+=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator-(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point& operator-=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator-() const; - /** - * @js NA - * @lua NA - */ - bool operator==(const Point& right); - /** - * @js NA - * @lua NA - */ - bool operator!=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Point operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setPoint(float x, float y); - /** - * @js NA - */ - bool equals(const Point& target) const; - - /** @returns if points have fuzzy equality which means equal with some degree of variance. - @since v2.1.4 - * @js NA - * @lua NA - */ - bool fuzzyEquals(const Point& target, float variance) const; - - /** Calculates distance between point an origin - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLength() const { - return sqrtf(x*x + y*y); - }; - - /** Calculates the square length of a Point (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLengthSq() const { - return dot(*this); //x*x + y*y; - }; - - /** Calculates the square distance between two points (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistanceSq(const Point& other) const { - return (*this - other).getLengthSq(); - }; - - /** Calculates the distance between two points - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistance(const Point& other) const { - return (*this - other).getLength(); - }; - - /** @returns the angle in radians between this vector and the x axis - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getAngle() const { - return atan2f(y, x); - }; - - /** @returns the angle in radians between two vector directions - @since v2.1.4 - * @js NA - * @lua NA - */ - float getAngle(const Point& other) const; - - /** Calculates dot product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float dot(const Point& other) const { - return x*other.x + y*other.y; - }; - - /** Calculates cross product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float cross(const Point& other) const { - return x*other.y - y*other.x; - }; - - /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getPerp() const { - return Point(-y, x); - }; - - /** Calculates midpoint between two points. - @return Point - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getMidpoint(const Point& other) const - { - return Point((x + other.x) / 2.0f, (y + other.y) / 2.0f); - } - - /** Clamp a point between from and to. - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getClampPoint(const Point& min_inclusive, const Point& max_inclusive) const - { - return Point(clampf(x,min_inclusive.x,max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y)); - } - - /** Run a math operation function on each point component - * absf, fllorf, ceilf, roundf - * any function that has the signature: float func(float); - * For example: let's try to take the floor of x,y - * p.compOp(floorf); - @since v3.0 - * @js NA - * @lua NA - */ - inline Point compOp(std::function function) const - { - return Point(function(x), function(y)); - } - - /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getRPerp() const { - return Point(y, -x); - }; - - /** Calculates the projection of this over other. - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point project(const Point& other) const { - return other * (dot(other)/other.dot(other)); - }; - - /** Complex multiplication of two points ("rotates" two points). - @return Point vector with an angle of this.getAngle() + other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point rotate(const Point& other) const { - return Point(x*other.x - y*other.y, x*other.y + y*other.x); - }; - - /** Unrotates two points. - @return Point vector with an angle of this.getAngle() - other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point unrotate(const Point& other) const { - return Point(x*other.x + y*other.y, y*other.x - x*other.y); - }; - - /** Returns point multiplied to a length of 1. - * If the point is 0, it returns (1, 0) - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point normalize() const { - float length = getLength(); - if(length == 0.) return Point(1.f, 0); - return *this / getLength(); - }; - - /** Linear Interpolation between two points a and b - @returns - alpha == 0 ? a - alpha == 1 ? b - otherwise a value between a..b - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point lerp(const Point& other, float alpha) const { - return *this * (1.f - alpha) + other * alpha; - }; - - /** Rotates a point counter clockwise by the angle around a pivot - @param pivot is the pivot, naturally - @param angle is the angle of rotation ccw in radians - @returns the rotated point - @since v2.1.4 - * @js NA - * @lua NA - */ - Point rotateByAngle(const Point& pivot, float angle) const; - - /** - * @js NA - * @lua NA - */ - static inline Point forAngle(const float a) - { - return Point(cosf(a), sinf(a)); - } - - /** A general line-line intersection test - @param A the startpoint for the first line L1 = (A - B) - @param B the endpoint for the first line L1 = (A - B) - @param C the startpoint for the second line L2 = (C - D) - @param D the endpoint for the second line L2 = (C - D) - @param S the range for a hitpoint in L1 (p = A + S*(B - A)) - @param T the range for a hitpoint in L2 (p = C + T*(D - C)) - @returns whether these two lines interects. - - Note that to truly test intersection for segments we have to make - sure that S & T lie within [0..1] and for rays, make sure S & T > 0 - the hit point is C + T * (D - C); - the hit point also is A + S * (B - A); - @since 3.0 - * @js NA - * @lua NA - */ - static bool isLineIntersect(const Point& A, const Point& B, - const Point& C, const Point& D, - float *S = nullptr, float *T = nullptr); - - /** - returns true if Line A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineOverlap(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Line A-B parallel with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineParallel(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Segment A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentOverlap(const Point& A, const Point& B, - const Point& C, const Point& D, - Point* S = nullptr, Point* E = nullptr); - - /** - returns true if Segment A-B intersects with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D); - - /** - returns the intersection point of line A-B, C-D - @since v3.0 - * @js NA - * @lua NA - */ - static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); - - static const Point ZERO; - -private: - // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part - static bool isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E); - - // cross procuct of 2 vector. A->B X C->D - static float crossProduct2Vector(const Point& A, const Point& B, const Point& C, const Point& D) { return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y); } -}; - -class CC_DLL Size -{ -public: - float width; - float height; - -public: - /** - * @js NA - */ - Size(); - /** - * @js NA - */ - Size(float width, float height); - /** - * @js NA - * @lua NA - */ - Size(const Size& other); - /** - * @js NA - * @lua NA - */ - explicit Size(const Point& point); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Size& other); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Point& point); - /** - * @js NA - * @lua NA - */ - Size operator+(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator-(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Size operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setSize(float width, float height); - /** - * @js NA - */ - bool equals(const Size& target) const; - - static const Size ZERO; -}; - -class CC_DLL Rect -{ -public: - Point origin; - Size size; - -public: - /** - * @js NA - */ - Rect(); - /** - * @js NA - */ - Rect(float x, float y, float width, float height); - /** - * @js NA - * @lua NA - */ - Rect(const Rect& other); - /** - * @js NA - * @lua NA - */ - Rect& operator= (const Rect& other); - /** - * @js NA - * @lua NA - */ - void setRect(float x, float y, float width, float height); - /** - * @js NA - */ - float getMinX() const; /// return the leftmost x-value of current rect - /** - * @js NA - */ - float getMidX() const; /// return the midpoint x-value of current rect - /** - * @js NA - */ - float getMaxX() const; /// return the rightmost x-value of current rect - /** - * @js NA - */ - float getMinY() const; /// return the bottommost y-value of current rect - /** - * @js NA - */ - float getMidY() const; /// return the midpoint y-value of current rect - /** - * @js NA - */ - float getMaxY() const; /// return the topmost y-value of current rect - /** - * @js NA - */ - bool equals(const Rect& rect) const; - /** - * @js NA - */ - bool containsPoint(const Point& point) const; - /** - * @js NA - */ - bool intersectsRect(const Rect& rect) const; - /** - * @js NA - * @lua NA - */ - Rect unionWithRect(const Rect & rect) const; - - static const Rect ZERO; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CCGEMETRY_H__ diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h deleted file mode 100644 index 869c7be1da..0000000000 --- a/cocos2dx/physics/CCPhysicsBody.h +++ /dev/null @@ -1,292 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_BODY_H__ -#define __CCPHYSICS_BODY_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -#include "CCPhysicsShape.h" - -#include - -NS_CC_BEGIN -class Sprite; -class PhysicsWorld; -class PhysicsJoint; - -class PhysicsBodyInfo; - - -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; - -/** - * A body affect by physics. - * it can attach one or more shapes. - */ -class PhysicsBody : public Object//, public Clonable -{ -public: - static PhysicsBody* create(); - /** - * @brief Create a body contains a circle shape. - */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - /** - * @brief Create a body contains a box shape. - */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - /** - * @brief Create a body contains a polygon shape. - * points is an array of Point structs defining a convex hull with a clockwise winding. - */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - - /** - * @brief Create a body contains a EdgeSegment shape. - */ - static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgeBox shape. - */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgePolygon shape. - */ - static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgeChain shape. - */ - static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - - virtual void addShape(PhysicsShape* shape); - - /** - * @brief Applies a immediate force to body. - */ - virtual void applyForce(Point force); - /** - * @brief Applies a immediate force to body. - */ - virtual void applyForce(Point force, Point offset); - /** - * @brief Applies a continuous force to body. - */ - virtual void applyImpulse(Point impulse); - /** - * @brief Applies a continuous force to body. - */ - virtual void applyImpulse(Point impulse, Point offset); - /** - * @brief Applies a torque force to body. - */ - virtual void applyTorque(float torque); - - virtual void setVelocity(Point velocity); - virtual Point getVelocity(); - virtual void setAngularVelocity(float velocity); - virtual float getAngularVelocity(); - virtual void setVelocityLimit(float limit); - virtual float getVelocityLimit(); - virtual void setAngularVelocityLimit(float limit); - virtual float getAngularVelocityLimit(); - - /* - * @brief get the body shapes. - */ - inline std::vector& getShapes() { return _shapes; } - /* - * @brief get the first body shapes. - */ - inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } - PhysicsShape* getShapeByTag(int tag); - /* - * @brief remove a shape from body - */ - void removeShape(PhysicsShape* shape); - void removeShapeByTag(int tag); - /* - * @brief remove all shapes - */ - void removeAllShapes(); - - /* - * @brief get the world body added to. - */ - inline PhysicsWorld* getWorld() const { return _world; } - /* - * @brief get all joints the body have - */ - inline const std::vector* getJoints() const { return &_joints; } - - /* - * @brief get the sprite the body set to. - */ - inline Sprite* getOwner() const { return _owner; } - - inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } - inline int getCategoryBitmask() const { return _categoryBitmask; } - inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } - inline int getContactTestBitmask() const { return _contactTestBitmask; } - inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } - inline int getCollisionBitmask() const { return _collisionBitmask; } - - /* - * @brief get the body position. - */ - Point getPosition() const; - /* - * @brief get the body rotation. - */ - float getRotation() const; - - /* - * @brief test the body is dynamic or not. - * a dynamic body will effect with gravity. - */ - inline bool isDynamic() { return _dynamic; } - /* - * @brief set dynamic to body. - * a dynamic body will effect with gravity. - */ - void setDynamic(bool dynamic); - - /* - * @brief set the body mass. - * @note if you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead. - */ - void setMass(float mass); - /* - * @brief get the body mass. - */ - inline float getMass() { return _mass; } - /* - * @brief add mass to body. - * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. - * if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY. - * if mass == -PHYSICS_INFINITY, _mass will not change. - * if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0) - * other wise, mass = mass + _mass; - */ - void addMass(float mass); - - /* - * @brief set the body moment of inertia. - * @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead. - */ - void setMoment(float moment); - /* - * @brief get the body moment of inertia. - */ - inline float getMoment(float moment) { return _moment; } - /* - * @brief add moment of inertia to body. - * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. - * if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY. - * if moment == -PHYSICS_INFINITY, _moment will not change. - * if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0) - * other wise, moment = moment + _moment; - */ - void addMoment(float moment); - /* - * @brief set angular damping. - */ - //void setAngularDamping(float angularDamping); - /* - * @brief get angular damping. - */ - inline float getLinearDamping() { return _linearDamping; } - inline void setLinearDamping(float damping) { _linearDamping = damping; } - inline float getAngularDamping() { return _angularDamping; } - inline void setAngularDamping(float damping) { _angularDamping = damping; } - - //virtual Clonable* clone() const override; - - bool isResting(); - inline bool isEnable() { return _enable; } - void setEnable(bool enable); - - inline bool isRotationEnable() { return _rotationEnable; } - void setRotationEnable(bool enable); - - inline bool isGravityEnable() { return _gravityEnable; } - void setGravityEnable(bool enable); - - - inline int getTag() { return _tag; } - inline void setTag(int tag) { _tag = tag; } - - -protected: - - bool init(); - - virtual void setPosition(Point position); - virtual void setRotation(float rotation); - - virtual void update(float delta) override; - -protected: - PhysicsBody(); - virtual ~PhysicsBody(); - -protected: - Sprite* _owner; - std::vector _joints; - std::vector _shapes; - PhysicsWorld* _world; - PhysicsBodyInfo* _info; - bool _dynamic; - bool _enable; - bool _rotationEnable; - bool _gravityEnable; - bool _massDefault; - bool _momentDefault; - float _mass; - float _area; - float _density; - float _moment; - float _linearDamping; - float _angularDamping; - int _tag; - - int _categoryBitmask; - int _contactTestBitmask; - int _collisionBitmask; - - friend class PhysicsWorld; - friend class PhysicsShape; - friend class PhysicsJoint; - friend class Node; -}; - -NS_CC_END - -#endif // __CCPHYSICS_BODY_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsContact.h b/cocos2dx/physics/CCPhysicsContact.h deleted file mode 100644 index df31ae7be3..0000000000 --- a/cocos2dx/physics/CCPhysicsContact.h +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_CONTACT_H__ -#define __CCPHYSICS_CONTACT_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsShape; -class PhysicsWorld; - -class PhysicsContactInfo; - -/** - * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. - */ -class PhysicsContact -{ -public: - /* - * @brief get contact shape A. - */ - inline PhysicsShape* getShapeA() const { return _shapeA; } - /* - * @brief get contact shape B. - */ - inline PhysicsShape* getShapeB() const { return _shapeB; } - /* - * @brief get data. - */ - inline void* getData() { return _data; } - /* - * @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact end. - */ - inline void setData(void* data) { _data = data; } - -private: - static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); - bool init(PhysicsShape* a, PhysicsShape* b); - - inline bool getNotify() { return _notify; } - inline void setNotify(bool notify) { _notify = notify; } - -private: - PhysicsContact(); - ~PhysicsContact(); - -private: - PhysicsShape* _shapeA; - PhysicsShape* _shapeB; - PhysicsContactInfo* _info; - void* _data; - bool _notify; - - friend class PhysicsWorld; -}; - -/* - * @brief presolve value generated when onContactPreSolve called. - */ -class PhysicsContactPreSolve -{ -private: - PhysicsContactPreSolve(); - ~PhysicsContactPreSolve(); - - static PhysicsContactPreSolve* create(); - bool init(); - - friend class PhysicsWorld; -}; - -/* - * @brief postsolve value generated when onContactPostSolve called. - */ -class PhysicsContactPostSolve -{ -private: - PhysicsContactPostSolve(); - ~PhysicsContactPostSolve(); - - static PhysicsContactPostSolve* create(); - bool init(); - - friend class PhysicsWorld; -}; - -/* - * @brief contact listener. - */ -class PhysicsContactListener -{ -public: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); - -public: - /* - * @brief it will called at two shapes start to contact, and only call it once. - */ - std::function onContactBegin; - /* - * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. - */ - std::function onContactPreSolve; - /* - * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info - */ - std::function onContactPostSolve; - /* - * @brief it will called at two shapes separated, and only call it once. - * onContactBegin and onContactEnd will called in pairs. - */ - std::function onContactEnd; -}; - -NS_CC_END -#endif //__CCPHYSICS_CONTACT_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsJoint.h b/cocos2dx/physics/CCPhysicsJoint.h deleted file mode 100644 index ebc7ceddc0..0000000000 --- a/cocos2dx/physics/CCPhysicsJoint.h +++ /dev/null @@ -1,168 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_JOINT_H__ -#define __CCPHYSICS_JOINT_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsBody; -class PhysicsJointInfo; -class PhysicsBodyInfo; - -/* - * @brief An PhysicsJoint object connects two physics bodies together. - */ -class PhysicsJoint : public Object -{ -protected: - PhysicsJoint(); - virtual ~PhysicsJoint() = 0; - -public: - PhysicsBody* getBodyA() { return _bodyA; } - PhysicsBody* getBodyB() { return _bodyB; } - inline int getTag() { return _tag; } - inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() { return _enable; } - void setEnable(bool enable); - inline bool isCollisionEnable() { return _collisionEnable; } - void setCollisionEnable(bool enable); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b); - - /** - * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. - */ - PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; - -protected: - PhysicsBody* _bodyA; - PhysicsBody* _bodyB; - PhysicsJointInfo* _info; - bool _enable; - bool _collisionEnable; - int _tag; - - friend class PhysicsBody; - friend class PhysicsWorld; -}; - -/* - * @brief A fixed joint fuses the two bodies together at a reference point. Fixed joints are useful for creating complex shapes that can be broken apart later. - */ -class PhysicsJointFixed : public PhysicsJoint -{ -public: - PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - PhysicsJointFixed(); - virtual ~PhysicsJointFixed(); -}; - -/* - * @brief A sliding joint allows the two bodies to slide along a chosen axis. - */ -class PhysicsJointSliding : public PhysicsJoint -{ -public: - PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); - -protected: - PhysicsJointSliding(); - virtual ~PhysicsJointSliding(); -}; - -/* - * @brief A spring joint connects the two bodies with a spring whose length is the initial distance between the two bodies. - */ -class PhysicsJointSpring : public PhysicsJoint -{ -public: - PhysicsJointSpring* create(); - -protected: - bool init(); - -protected: - PhysicsJointSpring(); - virtual ~PhysicsJointSpring(); -}; - -/* - * @brief A limit joint imposes a maximum distance between the two bodies, as if they were connected by a rope. - */ -class PhysicsJointLimit : public PhysicsJoint -{ -public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - - float getMin(); - void setMin(float min); - float getMax(); - void setMax(float max); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - -protected: - PhysicsJointLimit(); - virtual ~PhysicsJointLimit(); -}; - -/* - * @brief A pin joint allows the two bodies to independently rotate around the anchor point as if pinned together. - */ -class PhysicsJointPin : public PhysicsJoint -{ -public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - PhysicsJointPin(); - virtual ~PhysicsJointPin(); -}; - -NS_CC_END - -#endif // __CCPHYSICS_JOINT_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h deleted file mode 100644 index fcf70c7c19..0000000000 --- a/cocos2dx/physics/CCPhysicsShape.h +++ /dev/null @@ -1,296 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_SHAPE_H__ -#define __CCPHYSICS_SHAPE_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsShapeInfo; -class PhysicsBody; -class PhysicsBodyInfo; - - -typedef struct PhysicsMaterial -{ - float density; - float restitution; - float friction; - - PhysicsMaterial() - : density(0.0f) - , restitution(0.0f) - , friction(0.0f){} - - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction){} -}PhysicsMaterial; - -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; - -/** - * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. - */ -class PhysicsShape : public Object -{ -public: - enum class Type - { - UNKNOWN, - CIRCLE, - BOX, - POLYGEN, - EDGESEGMENT, - EDGEBOX, - EDGEPOLYGEN, - EDGECHAIN, - }; - -public: - inline PhysicsBody* getBody() const { return _body; } - inline Type getType() const { return _type; } - inline float getArea() const { return _area; } - inline float getMoment() const { return _moment; } - void setMoment(float moment); - inline void setTag(int tag) { _tag = tag; } - inline int getTag() const { return _tag; } - - inline float getMass() const { return _mass; } - void setMass(float mass); - inline float getDensity() const { return _material.density; } - void setDensity(float density); - void setRestitution(float restitution); - void setFriction(float friction); - void setMaterial(PhysicsMaterial material); - - virtual float calculateDefaultMoment() { return 0; } - virtual float calculateDefaultArea() { return 0; } - virtual Point getOffset() { return Point::ZERO; } - virtual Point getCenter() { return getOffset(); } - - static Point* recenterPoints(Point* points, int count, Point center); - static Point getPolyonCenter(Point* points, int count); - -protected: - bool init(Type type); - - /** - * @brief PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. - */ - PhysicsBodyInfo* bodyInfo() const; - - void setBody(PhysicsBody* body); - -protected: - PhysicsShape(); - virtual ~PhysicsShape() = 0; - -protected: - PhysicsBody* _body; - PhysicsShapeInfo* _info; - Type _type; - float _area; - float _mass; - float _moment; - PhysicsMaterial _material; - int _tag; - - friend class PhysicsWorld; - friend class PhysicsBody; - friend class PhysicsJoint; -}; - -/** A circle shape */ -class PhysicsShapeCircle : public PhysicsShape -{ -public: - static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(float radius); - static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - float getRadius(); - Point getOffset(); -protected: - bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapeCircle(); - ~PhysicsShapeCircle(); -}; - -/** A box shape */ -class PhysicsShapeBox : public PhysicsShape -{ -public: - static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Size size); - static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - Point* getPoints(Point* points); - Size getSize(); - Point getOffset() override { return _offset; } - -protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapeBox(); - virtual ~PhysicsShapeBox(); - -protected: - Point _offset; -}; - -/** A polygon shape */ -class PhysicsShapePolygon : public PhysicsShape -{ -public: - static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Point* points, int count); - static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - Point* getPoints(Point* points); - int getPointsCount(); - Point getCenter() override; -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapePolygon(); - virtual ~PhysicsShapePolygon(); - -protected: - Point _center; -}; - -/** A segment shape */ -class PhysicsShapeEdgeSegment : public PhysicsShape -{ -public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - - Point getPointA(); - Point getPointB(); - Point getCenter() override; - -protected: - bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgeSegment(); - virtual ~PhysicsShapeEdgeSegment(); - -protected: - Point _center; - - friend class PhysicsBody; -}; - -/** An edge box shape */ -class PhysicsShapeEdgeBox : public PhysicsShape -{ -public: - static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); - Point getOffset() override { return _offset; } - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); - -protected: - PhysicsShapeEdgeBox(); - virtual ~PhysicsShapeEdgeBox(); - -protected: - Point _offset; - - friend class PhysicsBody; -}; - -/** An edge polygon shape */ -class PhysicsShapeEdgePolygon : public PhysicsShape -{ -public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgePolygon(); - virtual ~PhysicsShapeEdgePolygon(); - - friend class PhysicsBody; - -protected: - Point _center; -}; - -/** a chain shape */ -class PhysicsShapeEdgeChain : public PhysicsShape -{ -public: - static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgeChain(); - virtual ~PhysicsShapeEdgeChain(); - -protected: - Point _center; - - friend class PhysicsBody; -}; - -NS_CC_END -#endif // __CCPHYSICS_FIXTURE_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp deleted file mode 100644 index afccdca8d9..0000000000 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ /dev/null @@ -1,496 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsWorld.h" -#ifdef CC_USE_PHYSICS - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#include "chipmunk.h" -#elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) -#include "Box2D.h" -#endif - -#include "CCPhysicsBody.h" -#include "CCPhysicsShape.h" -#include "CCPhysicsContact.h" -#include "CCPhysicsJoint.h" -#include "CCPhysicsContact.h" - -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "Box2D/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "Box2D/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsContactInfo.h" -#include "Box2D/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "Box2D/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsHelper.h" - -#include "draw_nodes/CCDrawNode.h" -#include "cocoa/CCArray.h" -#include "layers_scenes_transitions_nodes/CCScene.h" -#include "CCDirector.h" - -#include - -NS_CC_BEGIN - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -const float PHYSICS_INFINITY = INFINITY; - -int PhysicsWorld::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - - CP_ARBITER_GET_SHAPES(arb, a, b); - - auto ita = PhysicsShapeInfo::map.find(a); - auto itb = PhysicsShapeInfo::map.find(b); - CC_ASSERT(ita != PhysicsShapeInfo::map.end() && itb != PhysicsShapeInfo::map.end()); - - PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); - arb->data = contact; - - return world->collisionBeginCallback(*static_cast(arb->data)); -} - -int PhysicsWorld::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - return world->collisionPreSolveCallback(*static_cast(arb->data), - PhysicsContactPreSolve()); -} - -void PhysicsWorld::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - world->collisionPostSolveCallback(*static_cast(arb->data), - PhysicsContactPostSolve()); -} - -void PhysicsWorld::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - PhysicsContact* contact = static_cast(arb->data); - - world->collisionSeparateCallback(*contact); - - delete contact; -} - -bool PhysicsWorld::init() -{ - _info = new PhysicsWorldInfo(); - - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); - - cpSpaceSetDefaultCollisionHandler(_info->space, - PhysicsWorld::collisionBeginCallbackFunc, - PhysicsWorld::collisionPreSolveCallbackFunc, - PhysicsWorld::collisionPostSolveCallbackFunc, - PhysicsWorld::collisionSeparateCallbackFunc, - this); - - return true; -} - -void PhysicsWorld::addJoint(PhysicsJoint* joint) -{ - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it == _joints.end()) - { - _joints.push_back(joint); - - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceAddConstraint(_info->space, subjoint); - } - } - } - -} - -void PhysicsWorld::removeJoint(PhysicsJoint* joint) -{ - -} - -void PhysicsWorld::removeAllJoints() -{ - -} - -void PhysicsWorld::addShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - continue; - } - - if (cpBodyIsStatic(shape->getBody()->_info->body)) - { - cpSpaceAddStaticShape(_info->space, cps); - }else - { - cpSpaceAddShape(_info->space, cps); - } - } -} - -void PhysicsWorld::addBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - if (body->isEnable()) - { - //is gravity enable - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - - // add body to space - if (body->isDynamic()) - { - cpSpaceAddBody(_info->space, body->_info->body); - } - - // add shapes to space - for (auto shape : body->getShapes()) - { - addShape(shape); - } - } - - if (_bodys == nullptr) - { - _bodys = Array::create(body, NULL); - _bodys->retain(); - }else - { - _bodys->addObject(body); - } -} - -void PhysicsWorld::removeBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - if (body->getWorld() == this) - { - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - } - - // remove shaps - for (auto shape : body->getShapes()) - { - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } - } - - // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } - - if (_bodys != nullptr) - { - _bodys->removeObject(body); - } -} - -void PhysicsWorld::removeBodyByTag(int tag) -{ - for (Object* obj : *_bodys) - { - PhysicsBody* body = dynamic_cast(obj); - if (body->getTag() == tag) - { - removeBody(body); - return; - } - } -} - -void PhysicsWorld::removeShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } -} - -void PhysicsWorld::update(float delta) -{ - for (auto body : *_bodys) - { - body->update(delta); - } - - cpSpaceStep(_info->space, delta); - - if (_drawNode) - { - _drawNode->removeFromParent(); - _drawNode = nullptr; - } - - if (_debugDraw) - { - debugDraw(); - } -} - -void PhysicsWorld::debugDraw() -{ - if (_debugDraw && _bodys != nullptr) - { - _drawNode= DrawNode::create(); - - for (Object* obj : *_bodys) - { - PhysicsBody* body = dynamic_cast(obj); - - std::vector shapes = body->getShapes(); - - for (auto shape : shapes) - { - drawWithShape(_drawNode, shape); - } - } - - if (_scene) - { - _scene->addChild(_drawNode); - } - } -} - -void PhysicsWorld::setScene(Scene *scene) -{ - _scene = scene; -} - -void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) -{ - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) - { - cpShape *shape = *it; - - switch ((*it)->klass_private->type) - { - case CP_CIRCLE_SHAPE: - { - float radius = PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(shape)); - Point centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(shape))) - + PhysicsHelper::cpv2point(cpCircleShapeGetOffset(shape)); - - Point seg[4] = {}; - seg[0] = Point(centre.x - radius, centre.y - radius); - seg[1] = Point(centre.x - radius, centre.y + radius); - seg[2] = Point(centre.x + radius, centre.y + radius); - seg[3] = Point(centre.x + radius, centre.y - radius); - node->drawPolygon(seg, 4, Color4F(), 1, Color4F(1, 0, 0, 1)); - break; - } - case CP_SEGMENT_SHAPE: - { - cpSegmentShape *seg = (cpSegmentShape *)shape; - node->drawSegment(PhysicsHelper::cpv2point(seg->ta), - PhysicsHelper::cpv2point(seg->tb), - PhysicsHelper::cpfloat2float(seg->r==0 ? 1 : seg->r), Color4F(1, 0, 0, 1)); - break; - } - case CP_POLY_SHAPE: - { - cpPolyShape* poly = (cpPolyShape*)shape; - int num = poly->numVerts; - Point* seg = new Point[num]; - - PhysicsHelper::cpvs2points(poly->tVerts, seg, num); - - node->drawPolygon(seg, num, Color4F(1.0f, 0.0f, 0.0f, 0.3f), 1.0f, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - - delete[] seg; - break; - } - default: - break; - } - } -} - -int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) -{ - bool ret = true; - PhysicsBody* bodyA = contact.getShapeA()->getBody(); - PhysicsBody* bodyB = contact.getShapeB()->getBody(); - - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0) - { - contact.setNotify(false); - } - - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0) - { - ret = false; - } - - if (contact.getNotify() && _listener && _listener->onContactBegin) - { - // the mask has high priority than _listener->onContactBegin. - // so if the mask test is false, the two bodies won't have collision. - if (ret) - { - ret = _listener->onContactBegin(contact); - }else - { - _listener->onContactBegin(contact); - } - } - - return ret; -} - -int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) -{ - if (!contact.getNotify()) - { - return true; - } - - if (_listener && _listener->onContactPreSolve) - { - return _listener->onContactPreSolve(contact, solve); - } - - return true; -} - -void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) -{ - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactPreSolve) - { - _listener->onContactPostSolve(contact, solve); - } -} - -void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) -{ - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactEnd) - { - _listener->onContactEnd(contact); - } -} - -void PhysicsWorld::setGravity(Point gravity) -{ - if (_bodys != nullptr) - { - for (auto child : *_bodys) - { - PhysicsBody* body = dynamic_cast(child); - - // reset gravity for body - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - body->applyForce(gravity); - } - } - } - - _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); -} - -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#endif - -PhysicsWorld* PhysicsWorld::create() -{ - PhysicsWorld * world = new PhysicsWorld(); - if(world && world->init()) - { - return world; - } - - CC_SAFE_DELETE(world); - return nullptr; -} - -PhysicsWorld::PhysicsWorld() -: _gravity(Point(0.0f, -98.0f)) -, _speed(1.0f) -, _info(nullptr) -, _listener(nullptr) -, _bodys(nullptr) -, _scene(nullptr) -, _debugDraw(false) -, _drawNode(nullptr) -{ - -} - -PhysicsWorld::~PhysicsWorld() -{ - CC_SAFE_DELETE(_info); - CC_SAFE_RELEASE(_bodys); -} - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsWorld.h b/cocos2dx/physics/CCPhysicsWorld.h deleted file mode 100644 index a0539ae81d..0000000000 --- a/cocos2dx/physics/CCPhysicsWorld.h +++ /dev/null @@ -1,149 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_WORLD_H__ -#define __CCPHYSICS_WORLD_H__ - -#include - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -typedef struct cpArbiter cpArbiter; -typedef struct cpSpace cpSpace; -#endif - -NS_CC_BEGIN - -class PhysicsBody; -class PhysicsJoint; -class PhysicsWorldInfo; -class PhysicsShape; -class PhysicsContact; -class PhysicsContactPreSolve; -class PhysicsContactPostSolve; -class PhysicsContactListener; -class Array; - -class Sprite; -class Scene; -class DrawNode; - -/** - * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. - */ -class PhysicsWorld -{ -public: - /** Adds a joint to the physics world.*/ - void addJoint(PhysicsJoint* joint); - /** Removes a joint from the physics world.*/ - void removeJoint(PhysicsJoint* joint); - /** Remove all joints from the physics world.*/ - void removeAllJoints(); - - Array* getBodysAlongRay(Point start, Point end) const; - Array* getBodysAtPoint(Point point) const; - Array* getBodysInRect(Rect rect) const; - Array* getAllBody() const; - - /** Register a listener to receive contact callbacks*/ - inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } - /** Unregister a listener. */ - inline void unregisterContactListener() { _listener = nullptr; } - - /** get the gravity value */ - inline Point getGravity() { return _gravity; } - /** set the gravity value */ - void setGravity(Point gravity); - - /** test the debug draw is enabled */ - inline bool isDebugDraw() { return _debugDraw; } - /** set the debug draw */ - inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } - - virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); - -protected: - static PhysicsWorld* create(); - bool init(); - - void setScene(Scene* scene); - - virtual void addBody(PhysicsBody* body); - virtual void addShape(PhysicsShape* shape); - virtual void removeShape(PhysicsShape* shape); - virtual void update(float delta); - - virtual void debugDraw(); - virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); - - - virtual int collisionBeginCallback(PhysicsContact& contact); - virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); - virtual void collisionSeparateCallback(PhysicsContact& contact); - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - static int collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data); - static int collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); -#endif - -protected: - Point _gravity; - float _speed; - PhysicsWorldInfo* _info; - PhysicsContactListener* _listener; - - - Array* _bodys; - std::list _joints; - Scene* _scene; - - bool _debugDraw; - DrawNode* _drawNode; - -protected: - PhysicsWorld(); - virtual ~PhysicsWorld(); - - friend class Sprite; - friend class Scene; - friend class PhysicsBody; - friend class PhysicsShape; -}; - -NS_CC_END - -#endif // __CCPHYSICS_WORLD_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h deleted file mode 100644 index a394aa807b..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCObject.h" - -NS_CC_BEGIN - -class PhysicsBodyInfo : public Clonable -{ -public: - cpBody* body; - cpGroup group; - -private: - PhysicsBodyInfo(); - ~PhysicsBodyInfo(); - - Clonable* clone() const override; - - friend class PhysicsBody; -}; - -NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h deleted file mode 100644 index 9334d87124..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsHelper -{ -public: - static Point cpv2point(const cpVect& vec) { return Point(vec.x, vec.y); } - static cpVect point2cpv(const Point& point) { return cpv(point.x, point.y); } - static Size cpv2size(const cpVect& vec) { return Size(vec.x, vec.y); } - static cpVect size2cpv(const Size& size) { return cpv(size.width, size.height); } - static float cpfloat2float(cpFloat f) { return f; } - static cpFloat float2cpfloat(float f) { return f; } - - static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) - { - for (int i = 0; i < count; ++i) - { - points[i] = cpv2point(cpvs[i]); - } - - return points; - } - - static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) - { - for (int i = 0; i < count; ++i) - { - cpvs[i] = point2cpv(points[i]); - } - - return cpvs; - } -}; - -NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h deleted file mode 100644 index 1140b8783e..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include -#include -NS_CC_BEGIN - -class PhysicsJoint; - -class PhysicsJointInfo -{ -public: - void add(cpConstraint* shape); - void remove(cpConstraint* shape); - void removeAll(); - -public: - std::vector joints; - PhysicsJoint* joint; - static std::map map; - -private: - PhysicsJointInfo(PhysicsJoint* joint); - ~PhysicsJointInfo(); - - friend class PhysicsJoint; -}; - -NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h deleted file mode 100644 index f84f8613c6..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - -#include -#include -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" - -NS_CC_BEGIN - -class PhysicsShape; - -class PhysicsShapeInfo -{ -public: - void add(cpShape* shape); - void remove(cpShape* shape); - void removeAll(); - void setGroup(cpGroup group); - void setBody(cpBody* body); - -public: - std::vector shapes; - PhysicsShape* shape; - cpBody* body; - cpGroup group; - static std::map map; - static cpBody* shareBody; - -private: - PhysicsShapeInfo(PhysicsShape* shape); - ~PhysicsShapeInfo(); - - friend class PhysicsShape; -}; - -NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/sprite_nodes/CCSprite.cpp b/cocos2dx/sprite_nodes/CCSprite.cpp deleted file mode 100644 index f9bb30df89..0000000000 --- a/cocos2dx/sprite_nodes/CCSprite.cpp +++ /dev/null @@ -1,1138 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCSpriteBatchNode.h" -#include -#include -#include "CCAnimation.h" -#include "CCAnimationCache.h" -#include "ccConfig.h" -#include "CCSprite.h" -#include "CCSpriteFrame.h" -#include "CCSpriteFrameCache.h" -#include "textures/CCTextureCache.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "CCDirector.h" -#include "cocoa/CCGeometry.h" -#include "textures/CCTexture2D.h" -#include "cocoa/CCAffineTransform.h" -#include "support/TransformUtils.h" -#include "support/CCProfiling.h" -// external -#include "kazmath/GL/matrix.h" - - -using namespace std; - -NS_CC_BEGIN - -#if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -Sprite* Sprite::createWithTexture(Texture2D *texture) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithTexture(texture)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithTexture(texture, rect)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::create(const char *filename) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithFile(filename)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::create(const char *filename, const Rect& rect) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithFile(filename, rect)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) -{ - Sprite *sprite = new Sprite(); - if (spriteFrame && sprite && sprite->initWithSpriteFrame(spriteFrame)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) -{ - SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); - -#if COCOS2D_DEBUG > 0 - char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); - CCASSERT(frame != NULL, msg); -#endif - - return createWithSpriteFrame(frame); -} - -Sprite* Sprite::create() -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->init()) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -bool Sprite::init(void) -{ - return initWithTexture(NULL, Rect::ZERO); -} - -// designated initializer -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - if (NodeRGBA::init()) - { - _batchNode = NULL; - - _recursiveDirty = false; - setDirty(false); - - _opacityModifyRGB = true; - - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - - _flippedX = _flippedY = false; - - // default transform anchor: center - setAnchorPoint(Point(0.5f, 0.5f)); - - // zwoptex default values - _offsetPosition = Point::ZERO; - - _hasChildren = false; - - // clean the Quad - memset(&_quad, 0, sizeof(_quad)); - - // Atlas: Color - _quad.bl.colors = Color4B::WHITE; - _quad.br.colors = Color4B::WHITE; - _quad.tl.colors = Color4B::WHITE; - _quad.tr.colors = Color4B::WHITE; - - // shader program - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - - // update texture (calls updateBlendFunc) - setTexture(texture); - setTextureRect(rect, rotated, rect.size); - - // by default use "Self Render". - // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - setBatchNode(NULL); - - return true; - } - else - { - return false; - } -} - -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect) -{ - return initWithTexture(texture, rect, false); -} - -bool Sprite::initWithTexture(Texture2D *texture) -{ - CCASSERT(texture != NULL, "Invalid texture for sprite"); - - Rect rect = Rect::ZERO; - rect.size = texture->getContentSize(); - - return initWithTexture(texture, rect); -} - -bool Sprite::initWithFile(const char *filename) -{ - CCASSERT(filename != NULL, "Invalid filename for sprite"); - - Texture2D *texture = TextureCache::getInstance()->addImage(filename); - if (texture) - { - Rect rect = Rect::ZERO; - rect.size = texture->getContentSize(); - return initWithTexture(texture, rect); - } - - // don't release here. - // when load texture failed, it's better to get a "transparent" sprite then a crashed program - // this->release(); - return false; -} - -bool Sprite::initWithFile(const char *filename, const Rect& rect) -{ - CCASSERT(filename != NULL, ""); - - Texture2D *texture = TextureCache::getInstance()->addImage(filename); - if (texture) - { - return initWithTexture(texture, rect); - } - - // don't release here. - // when load texture failed, it's better to get a "transparent" sprite then a crashed program - // this->release(); - return false; -} - -bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) -{ - CCASSERT(spriteFrame != NULL, ""); - - bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect()); - setDisplayFrame(spriteFrame); - - return bRet; -} - -bool Sprite::initWithSpriteFrameName(const char *spriteFrameName) -{ - CCASSERT(spriteFrameName != NULL, ""); - - SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); - return initWithSpriteFrame(frame); -} - -// XXX: deprecated -/* -Sprite* Sprite::initWithCGImage(CGImageRef pImage) -{ - // todo - // because it is deprecated, so we do not implement it - - return NULL; -} -*/ - -/* -Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) -{ - CCASSERT(pImage != NULL); - - // XXX: possible bug. See issue #349. New API should be added - Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey); - - const Size& size = texture->getContentSize(); - Rect rect = Rect(0 ,0, size.width, size.height); - - return initWithTexture(texture, rect); -} -*/ - -Sprite::Sprite(void) -: _shouldBeHidden(false) -, _texture(nullptr) -{ -} - -Sprite::~Sprite(void) -{ - CC_SAFE_RELEASE(_texture); -} - -void Sprite::setTextureRect(const Rect& rect) -{ - setTextureRect(rect, false, rect.size); -} - - -void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) -{ - _rectRotated = rotated; - - setContentSize(untrimmedSize); - setVertexRect(rect); - setTextureCoords(rect); - - Point relativeOffset = _unflippedOffsetPositionFromCenter; - - // issue #732 - if (_flippedX) - { - relativeOffset.x = -relativeOffset.x; - } - if (_flippedY) - { - relativeOffset.y = -relativeOffset.y; - } - - _offsetPosition.x = relativeOffset.x + (_contentSize.width - _rect.size.width) / 2; - _offsetPosition.y = relativeOffset.y + (_contentSize.height - _rect.size.height) / 2; - - // rendering using batch node - if (_batchNode) - { - // update dirty_, don't update recursiveDirty_ - setDirty(true); - } - else - { - // self rendering - - // Atlas: Vertex - float x1 = 0 + _offsetPosition.x; - float y1 = 0 + _offsetPosition.y; - float x2 = x1 + _rect.size.width; - float y2 = y1 + _rect.size.height; - - // Don't update Z. - _quad.bl.vertices = Vertex3F(x1, y1, 0); - _quad.br.vertices = Vertex3F(x2, y1, 0); - _quad.tl.vertices = Vertex3F(x1, y2, 0); - _quad.tr.vertices = Vertex3F(x2, y2, 0); - } -} - -// override this method to generate "double scale" sprites -void Sprite::setVertexRect(const Rect& rect) -{ - _rect = rect; -} - -void Sprite::setTextureCoords(Rect rect) -{ - rect = CC_RECT_POINTS_TO_PIXELS(rect); - - Texture2D *tex = _batchNode ? _textureAtlas->getTexture() : _texture; - if (! tex) - { - return; - } - - float atlasWidth = (float)tex->getPixelsWide(); - float atlasHeight = (float)tex->getPixelsHigh(); - - float left, right, top, bottom; - - if (_rectRotated) - { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left+(rect.size.height*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top+(rect.size.width*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = (rect.origin.x+rect.size.height) / atlasWidth; - top = rect.origin.y/atlasHeight; - bottom = (rect.origin.y+rect.size.width) / atlasHeight; -#endif // CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if (_flippedX) - { - CC_SWAP(top, bottom, float); - } - - if (_flippedY) - { - CC_SWAP(left, right, float); - } - - _quad.bl.texCoords.u = left; - _quad.bl.texCoords.v = top; - _quad.br.texCoords.u = left; - _quad.br.texCoords.v = bottom; - _quad.tl.texCoords.u = right; - _quad.tl.texCoords.v = top; - _quad.tr.texCoords.u = right; - _quad.tr.texCoords.v = bottom; - } - else - { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left + (rect.size.width*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top + (rect.size.height*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = (rect.origin.x + rect.size.width) / atlasWidth; - top = rect.origin.y/atlasHeight; - bottom = (rect.origin.y + rect.size.height) / atlasHeight; -#endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if(_flippedX) - { - CC_SWAP(left,right,float); - } - - if(_flippedY) - { - CC_SWAP(top,bottom,float); - } - - _quad.bl.texCoords.u = left; - _quad.bl.texCoords.v = bottom; - _quad.br.texCoords.u = right; - _quad.br.texCoords.v = bottom; - _quad.tl.texCoords.u = left; - _quad.tl.texCoords.v = top; - _quad.tr.texCoords.u = right; - _quad.tr.texCoords.v = top; - } -} - -void Sprite::updateTransform(void) -{ - CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode"); - -#ifdef CC_USE_PHYSICS - updatePhysicsTransform(); - setDirty(true); -#endif - - // recalculate matrix only if it is dirty - if( isDirty() ) { - - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if( !_visible || ( _parent && _parent != _batchNode && static_cast(_parent)->_shouldBeHidden) ) - { - _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0); - _shouldBeHidden = true; - } - else - { - _shouldBeHidden = false; - - if( ! _parent || _parent == _batchNode ) - { - _transformToBatch = getNodeToParentTransform(); - } - else - { - CCASSERT( dynamic_cast(_parent), "Logic error in Sprite. Parent must be a Sprite"); - _transformToBatch = AffineTransformConcat( getNodeToParentTransform() , static_cast(_parent)->_transformToBatch ); - } - - // - // calculate the Quad based on the Affine Matrix - // - - Size size = _rect.size; - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - float x = _transformToBatch.tx; - float y = _transformToBatch.ty; - - float cr = _transformToBatch.a; - float sr = _transformToBatch.b; - float cr2 = _transformToBatch.d; - float sr2 = -_transformToBatch.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); - } - - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS - if (_textureAtlas) - { - _textureAtlas->updateQuad(&_quad, _atlasIndex); - } - - _recursiveDirty = false; - setDirty(false); - } - - // MARMALADE CHANGED - // recursively iterate over children -/* if( _hasChildren ) - { - // MARMALADE: CHANGED TO USE Node* - // NOTE THAT WE HAVE ALSO DEFINED virtual Node::updateTransform() - arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*); - }*/ - Node::updateTransform(); - -#if CC_SPRITE_DEBUG_DRAW - // draw bounding box - Point vertices[4] = { - Point( _quad.bl.vertices.x, _quad.bl.vertices.y ), - Point( _quad.br.vertices.x, _quad.br.vertices.y ), - Point( _quad.tr.vertices.x, _quad.tr.vertices.y ), - Point( _quad.tl.vertices.x, _quad.tl.vertices.y ), - }; - ccDrawPoly(vertices, 4, true); -#endif // CC_SPRITE_DEBUG_DRAW -} - -// draw - -void Sprite::draw(void) -{ - CC_PROFILER_START_CATEGORY(kProfilerCategorySprite, "CCSprite - draw"); - - CCASSERT(!_batchNode, "If Sprite is being rendered by SpriteBatchNode, Sprite#draw SHOULD NOT be called"); - - CC_NODE_DRAW_SETUP(); - - GL::blendFunc( _blendFunc.src, _blendFunc.dst ); - - GL::bindTexture2D( _texture->getName() ); - GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); - -#define kQuadSize sizeof(_quad.bl) -#ifdef EMSCRIPTEN - long offset = 0; - setGLBufferData(&_quad, 4 * kQuadSize, 0); -#else - long offset = (long)&_quad; -#endif // EMSCRIPTEN - - // vertex - int diff = offsetof( V3F_C4B_T2F, vertices); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); - - // texCoods - diff = offsetof( V3F_C4B_T2F, texCoords); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); - - // color - diff = offsetof( V3F_C4B_T2F, colors); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); - - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - CHECK_GL_ERROR_DEBUG(); - - -#if CC_SPRITE_DEBUG_DRAW == 1 - // draw bounding box - Point vertices[4]={ - Point(_quad.tl.vertices.x,_quad.tl.vertices.y), - Point(_quad.bl.vertices.x,_quad.bl.vertices.y), - Point(_quad.br.vertices.x,_quad.br.vertices.y), - Point(_quad.tr.vertices.x,_quad.tr.vertices.y), - }; - ccDrawPoly(vertices, 4, true); -#elif CC_SPRITE_DEBUG_DRAW == 2 - // draw texture box - Size s = this->getTextureRect().size; - Point offsetPix = this->getOffsetPosition(); - Point vertices[4] = { - Point(offsetPix.x,offsetPix.y), Point(offsetPix.x+s.width,offsetPix.y), - Point(offsetPix.x+s.width,offsetPix.y+s.height), Point(offsetPix.x,offsetPix.y+s.height) - }; - ccDrawPoly(vertices, 4, true); -#endif // CC_SPRITE_DEBUG_DRAW - - CC_INCREMENT_GL_DRAWS(1); - - CC_PROFILER_STOP_CATEGORY(kProfilerCategorySprite, "CCSprite - draw"); -} - -// Node overrides - -void Sprite::addChild(Node* child) -{ - Node::addChild(child); -} - -void Sprite::addChild(Node *child, int zOrder) -{ - Node::addChild(child, zOrder); -} - -void Sprite::addChild(Node *child, int zOrder, int tag) -{ - CCASSERT(child != NULL, "Argument must be non-NULL"); - - if (_batchNode) - { - Sprite* childSprite = dynamic_cast(child); - CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode"); - CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), ""); - //put it in descendants array of batch node - _batchNode->appendChild(childSprite); - - if (!_reorderChildDirty) - { - setReorderChildDirtyRecursively(); - } - } - //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check - Node::addChild(child, zOrder, tag); - _hasChildren = true; -} - -void Sprite::reorderChild(Node *child, int zOrder) -{ - CCASSERT(child != NULL, ""); - CCASSERT(_children->containsObject(child), ""); - - if (zOrder == child->getZOrder()) - { - return; - } - - if( _batchNode && ! _reorderChildDirty) - { - setReorderChildDirtyRecursively(); - _batchNode->reorderBatch(true); - } - - Node::reorderChild(child, zOrder); -} - -void Sprite::removeChild(Node *child, bool cleanup) -{ - if (_batchNode) - { - _batchNode->removeSpriteFromAtlas((Sprite*)(child)); - } - - Node::removeChild(child, cleanup); - -} - -void Sprite::removeAllChildrenWithCleanup(bool cleanup) -{ - if (_batchNode) - { - Object* object = NULL; - CCARRAY_FOREACH(_children, object) - { - Sprite* child = dynamic_cast(object); - if (child) - { - _batchNode->removeSpriteFromAtlas(child); - } - } - } - - Node::removeAllChildrenWithCleanup(cleanup); - - _hasChildren = false; -} - -void Sprite::sortAllChildren() -{ - if (_reorderChildDirty) - { -#if 0 - int i = 0, j = 0, length = _children->count(); - - // insertion sort - for(i=1; i( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() || - ( tempI->getZOrder() == tempJ->getZOrder() && - tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) ) - { - _children->fastSetObject( tempJ, j+1 ); - j = j-1; - if(j>=0) - tempJ = static_cast( _children->getObjectAtIndex(j) ); - } - _children->fastSetObject(tempI, j+1); - } -#else - std::sort(std::begin(*_children), std::end(*_children), nodeComparisonLess); -#endif - - if ( _batchNode) - { - arrayMakeObjectsPerformSelector(_children, sortAllChildren, Sprite*); - } - - _reorderChildDirty = false; - } -} - -// -// Node property overloads -// used only when parent is SpriteBatchNode -// - -void Sprite::setReorderChildDirtyRecursively(void) -{ - //only set parents flag the first time - if ( ! _reorderChildDirty ) - { - _reorderChildDirty = true; - Node* node = static_cast(_parent); - while (node && node != _batchNode) - { - static_cast(node)->setReorderChildDirtyRecursively(); - node=node->getParent(); - } - } -} - - -void Sprite::setDirtyRecursively(bool bValue) -{ - _recursiveDirty = bValue; - setDirty(bValue); - // recursively set dirty - if (_hasChildren) - { - Object* object = NULL; - CCARRAY_FOREACH(_children, object) - { - Sprite* child = dynamic_cast(object); - if (child) - { - child->setDirtyRecursively(true); - } - } - } -} - -// XXX HACK: optimization -#define SET_DIRTY_RECURSIVELY() { \ - if (_batchNode && ! _recursiveDirty) { \ - _recursiveDirty = true; \ - setDirty(true); \ - if ( _hasChildren) \ - setDirtyRecursively(true); \ - } \ - } - -void Sprite::setPosition(const Point& pos) -{ - Node::setPosition(pos); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotation(float rotation) -{ - Node::setRotation(rotation); - - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotationX(float fRotationX) -{ - Node::setRotationX(fRotationX); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotationY(float fRotationY) -{ - Node::setRotationY(fRotationY); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setSkewX(float sx) -{ - Node::setSkewX(sx); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setSkewY(float sy) -{ - Node::setSkewY(sy); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScaleX(float scaleX) -{ - Node::setScaleX(scaleX); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScaleY(float scaleY) -{ - Node::setScaleY(scaleY); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScale(float fScale) -{ - Node::setScale(fScale); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setVertexZ(float fVertexZ) -{ - Node::setVertexZ(fVertexZ); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setAnchorPoint(const Point& anchor) -{ - Node::setAnchorPoint(anchor); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::ignoreAnchorPointForPosition(bool value) -{ - CCASSERT(! _batchNode, "ignoreAnchorPointForPosition is invalid in Sprite"); - Node::ignoreAnchorPointForPosition(value); -} - -void Sprite::setVisible(bool bVisible) -{ - Node::setVisible(bVisible); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setFlippedX(bool flippedX) -{ - if (_flippedX != flippedX) - { - _flippedX = flippedX; - setTextureRect(_rect, _rectRotated, _contentSize); - } -} - -bool Sprite::isFlippedX(void) const -{ - return _flippedX; -} - -void Sprite::setFlippedY(bool flippedY) -{ - if (_flippedY != flippedY) - { - _flippedY = flippedY; - setTextureRect(_rect, _rectRotated, _contentSize); - } -} - -bool Sprite::isFlippedY(void) const -{ - return _flippedY; -} - -// -// RGBA protocol -// - -void Sprite::updateColor(void) -{ - Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); - - // special opacity for premultiplied textures - if (_opacityModifyRGB) - { - color4.r *= _displayedOpacity/255.0f; - color4.g *= _displayedOpacity/255.0f; - color4.b *= _displayedOpacity/255.0f; - } - - _quad.bl.colors = color4; - _quad.br.colors = color4; - _quad.tl.colors = color4; - _quad.tr.colors = color4; - - // renders using batch node - if (_batchNode) - { - if (_atlasIndex != INDEX_NOT_INITIALIZED) - { - _textureAtlas->updateQuad(&_quad, _atlasIndex); - } - else - { - // no need to set it recursively - // update dirty_, don't update recursiveDirty_ - setDirty(true); - } - } - - // self render - // do nothing -} - -void Sprite::setOpacity(GLubyte opacity) -{ - NodeRGBA::setOpacity(opacity); - - updateColor(); -} - -void Sprite::setColor(const Color3B& color3) -{ - NodeRGBA::setColor(color3); - - updateColor(); -} - -void Sprite::setOpacityModifyRGB(bool modify) -{ - if (_opacityModifyRGB != modify) - { - _opacityModifyRGB = modify; - updateColor(); - } -} - -bool Sprite::isOpacityModifyRGB(void) const -{ - return _opacityModifyRGB; -} - -void Sprite::updateDisplayedColor(const Color3B& parentColor) -{ - NodeRGBA::updateDisplayedColor(parentColor); - - updateColor(); -} - -void Sprite::updateDisplayedOpacity(GLubyte opacity) -{ - NodeRGBA::updateDisplayedOpacity(opacity); - - updateColor(); -} - -// Frames - -void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) -{ - _unflippedOffsetPositionFromCenter = pNewFrame->getOffset(); - - Texture2D *pNewTexture = pNewFrame->getTexture(); - // update texture before updating texture rect - if (pNewTexture != _texture) - { - setTexture(pNewTexture); - } - - // update rect - _rectRotated = pNewFrame->isRotated(); - setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); -} - -void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int frameIndex) -{ - CCASSERT(animationName, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); - - Animation *a = AnimationCache::getInstance()->getAnimation(animationName); - - CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - - AnimationFrame* frame = static_cast( a->getFrames()->getObjectAtIndex(frameIndex) ); - - CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); - - setDisplayFrame(frame->getSpriteFrame()); -} - -bool Sprite::isFrameDisplayed(SpriteFrame *frame) const -{ - Rect r = frame->getRect(); - - return (r.equals(_rect) && - frame->getTexture()->getName() == _texture->getName() && - frame->getOffset().equals(_unflippedOffsetPositionFromCenter)); -} - -SpriteFrame* Sprite::getDisplayFrame() -{ - return SpriteFrame::createWithTexture(_texture, - CC_RECT_POINTS_TO_PIXELS(_rect), - _rectRotated, - CC_POINT_POINTS_TO_PIXELS(_unflippedOffsetPositionFromCenter), - CC_SIZE_POINTS_TO_PIXELS(_contentSize)); -} - -SpriteBatchNode* Sprite::getBatchNode() -{ - return _batchNode; -} - -void Sprite::setBatchNode(SpriteBatchNode *spriteBatchNode) -{ - _batchNode = spriteBatchNode; // weak reference - - // self render - if( ! _batchNode ) { - _atlasIndex = INDEX_NOT_INITIALIZED; - setTextureAtlas(NULL); - _recursiveDirty = false; - setDirty(false); - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - float x2 = x1 + _rect.size.width; - float y2 = y1 + _rect.size.height; - _quad.bl.vertices = Vertex3F( x1, y1, 0 ); - _quad.br.vertices = Vertex3F( x2, y1, 0 ); - _quad.tl.vertices = Vertex3F( x1, y2, 0 ); - _quad.tr.vertices = Vertex3F( x2, y2, 0 ); - - } else { - - // using batch - _transformToBatch = AffineTransformIdentity; - setTextureAtlas(_batchNode->getTextureAtlas()); // weak ref - } -} - -// Texture protocol - -void Sprite::updateBlendFunc(void) -{ - CCASSERT(! _batchNode, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode"); - - // it is possible to have an untextured sprite - if (! _texture || ! _texture->hasPremultipliedAlpha()) - { - _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; - setOpacityModifyRGB(false); - } - else - { - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - setOpacityModifyRGB(true); - } -} - -/* - * This array is the data of a white image with 2 by 2 dimension. - * It's used for creating a default texture when sprite's texture is set to NULL. - * Supposing codes as follows: - * - * auto sp = new Sprite(); - * sp->init(); // Texture was set to NULL, in order to make opacity and color to work correctly, we need to create a 2x2 white texture. - * - * The test is in "TestCpp/SpriteTest/Sprite without texture". - */ -static unsigned char cc_2x2_white_image[] = { - // RGBA8888 - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF -}; - -#define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" - -void Sprite::setTexture(Texture2D *texture) -{ - // If batchnode, then texture id should be the same - CCASSERT(! _batchNode || texture->getName() == _batchNode->getTexture()->getName(), "CCSprite: Batched sprites should use the same texture as the batchnode"); - // accept texture==nil as argument - CCASSERT( !texture || dynamic_cast(texture), "setTexture expects a Texture2D. Invalid argument"); - - if (NULL == texture) - { - // Gets the texture by key firstly. - texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); - - // If texture wasn't in cache, create it from RAW data. - if (NULL == texture) - { - Image* image = new Image(); - bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); - CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); - - texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); - CC_SAFE_RELEASE(image); - } - } - - if (!_batchNode && _texture != texture) - { - CC_SAFE_RETAIN(texture); - CC_SAFE_RELEASE(_texture); - _texture = texture; - updateBlendFunc(); - } -} - -Texture2D* Sprite::getTexture(void) const -{ - return _texture; -} - -NS_CC_END From 0cffe5121965fa77bab543e27e44d1456c6090cd Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 18 Oct 2013 18:08:05 +0800 Subject: [PATCH 184/557] fix libluajia.a search path bug --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index bb2117f6df..18265b616b 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -af3544581a6508d57d3fe3b1f999cdc091bad543 \ No newline at end of file +1c487d29bdc2d80516e86e2ee93b1664e9f7df2f \ No newline at end of file From 54ac8f3537bdbbf9c421c94e6bcad50e8a4a770d Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Sat, 19 Oct 2013 16:44:14 +0800 Subject: [PATCH 185/557] Add cc.RESOLUTION_POLICY to jsb_cocos2d.js,so it can use setDesignResolutionSize in cc.EGLView --- .../javascript/script/jsb_cocos2d.js | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index 80ddb0a066..6ed7e19cba 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -4,6 +4,30 @@ var cc = cc || {}; +cc.RESOLUTION_POLICY = { + // The entire application is visible in the specified area without trying to preserve the original aspect ratio. + // Distortion can occur, and the application may appear stretched or compressed. +EXACTFIT:0, + // The entire application fills the specified area, without distortion but possibly with some cropping, + // while maintaining the original aspect ratio of the application. +NOBORDER:1, + // The entire application is visible in the specified area without distortion while maintaining the original + // aspect ratio of the application. Borders can appear on two sides of the application. +SHOW_ALL:2, + // The application takes the height of the design resolution size and modifies the width of the internal + // canvas so that it fits the aspect ratio of the device + // no distortion will occur however you must make sure your application works on different + // aspect ratios +HEIGHT:3, + // The application takes the width of the design resolution size and modifies the height of the internal + // canvas so that it fits the aspect ratio of the device + // no distortion will occur however you must make sure your application works on different + // aspect ratios +WIDTH:4, + +UNKNOWN:5 +}; + cc.LANGUAGE_ENGLISH = 0; cc.LANGUAGE_CHINESE = 1; cc.LANGUAGE_FRENCH = 2; From 464d1598d23a6bf667ca8e3d1d18d128e9d8d93a Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Sat, 19 Oct 2013 16:48:57 +0800 Subject: [PATCH 186/557] fixed bug of CCBReader that can not autoplaySequence --- cocos/editor-support/cocosbuilder/CCBReader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index d2f57ecf88..938c595f46 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -273,7 +273,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & Dictionary* animationManagers = Dictionary::create(); Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); - if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1 && !_jsControlled) + if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) { // Auto play animations _actionManager->runAnimationsForSequenceIdTweenDuration(_actionManager->getAutoPlaySequenceId(), 0); From f11dba586a17cfd46ea183c081ec7bba7796d7ee Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 21 Oct 2013 22:09:21 +0800 Subject: [PATCH 187/557] issue #2905:modification vs-project for folder structure change --- build/cocos2d-win32.vc2012.sln | 151 +- cocos/2d/cocos2d.vcxproj | 19 +- cocos/audio/proj.win32/CocosDenshion.vcxproj | 10 +- .../javascript/bindings/XMLHTTPRequest.cpp | 847 --------- .../javascript/bindings/XMLHTTPRequest.h | 112 -- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../javascript/bindings/cocos2d_specifics.hpp | 19 - .../bindings/js_bindings_ccbreader.cpp | 324 ---- .../bindings/js_bindings_ccbreader.h | 60 - ...s_chipmunk_auto_classes.cpp.REMOVED.git-id | 1 - .../js_bindings_chipmunk_auto_classes.h | 66 - ...dings_chipmunk_auto_classes_registration.h | 29 - ...ings_chipmunk_functions.cpp.REMOVED.git-id | 1 - .../bindings/js_bindings_chipmunk_functions.h | 292 --- ...bindings_chipmunk_functions_registration.h | 285 --- .../bindings/js_bindings_chipmunk_manual.cpp | 1624 ----------------- .../bindings/js_bindings_chipmunk_manual.h | 103 -- .../js_bindings_chipmunk_registration.cpp | 67 - .../js_bindings_chipmunk_registration.h | 31 - .../javascript/bindings/js_bindings_core.cpp | 2 +- .../bindings/js_bindings_system_functions.cpp | 75 - .../bindings/js_bindings_system_functions.h | 23 - ...s_bindings_system_functions_registration.h | 15 - .../js_bindings_system_registration.cpp | 62 - .../js_bindings_system_registration.h | 31 - .../jsb_cocos2dx_extension_manual.cpp | 1015 ----------- .../bindings/jsb_cocos2dx_extension_manual.h | 16 - .../javascript/bindings/jsb_websocket.cpp | 382 ---- .../javascript/bindings/jsb_websocket.h | 34 - .../bindings/proj.win32/libJSBinding.vcxproj | 53 +- .../proj.win32/libJSBinding.vcxproj.filters | 127 +- cocos/scripting/lua/bindings/liblua.vcxproj | 88 +- .../lua/bindings/liblua.vcxproj.filters | 226 +-- extensions/proj.win32/libExtensions.vcxproj | 248 +-- .../proj.win32/libExtensions.vcxproj.filters | 847 +-------- .../AssetsManagerTest/Classes/AppDelegate.cpp | 1 + .../proj.android/build_native.cmd | 7 +- .../proj.win32/AssetsManagerTest.vcxproj | 43 +- .../HelloCpp/proj.android/build_native.cmd | 5 +- .../Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj | 11 +- .../SimpleGame/proj.android/build_native.cmd | 5 +- .../Cpp/TestCpp/proj.android/build_native.cmd | 12 +- .../Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 32 +- .../CocosDragonJS/Classes/AppDelegate.cpp | 10 +- .../proj.android/build_native.cmd | 7 +- .../proj.win32/CocosDragonJS.vcxproj | 56 +- .../CrystalCraze/Classes/AppDelegate.cpp | 10 +- .../proj.android/build_native.cmd | 7 +- .../proj.win32/CrystalCraze.vcxproj | 62 +- .../MoonWarriors/Classes/AppDelegate.cpp | 10 +- .../proj.android/build_native.cmd | 9 +- .../proj.win32/MoonWarriors.vcxproj | 69 +- .../TestJavascript/Classes/AppDelegate.cpp | 21 +- .../proj.android/build_native.cmd | 6 +- .../proj.win32/TestJavascript.vcxproj | 79 +- .../WatermelonWithMe/Classes/AppDelegate.cpp | 10 +- .../proj.android/build_native.cmd | 7 +- .../proj.win32/WatermelonWithMe.vcxproj | 65 +- .../HelloLua/proj.android/build_native.cmd | 7 +- .../Lua/HelloLua/proj.win32/HelloLua.vcxproj | 47 +- .../Lua/TestLua/proj.android/build_native.cmd | 14 +- .../TestLua/proj.win32/TestLua.win32.vcxproj | 54 +- .../proj.android/build_native.cmd | 5 +- .../proj.win32/HelloCpp.sln | 37 +- .../proj.win32/HelloCpp.vcxproj | 32 +- .../multi-platform-js/Classes/AppDelegate.cpp | 17 +- .../proj.android/build_native.cmd | 6 +- .../proj.win32/HelloJavascript.sln | 47 +- .../proj.win32/HelloJavascript.vcxproj | 54 +- .../proj.android/build_native.cmd | 7 +- .../proj.win32/HelloLua.sln | 51 +- .../proj.win32/HelloLua.vcxproj | 47 +- tools/tojs/cocos2dx_extension.ini | 22 +- tools/tojs/genbindings.sh | 6 + 74 files changed, 1056 insertions(+), 7228 deletions(-) delete mode 100644 cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp delete mode 100644 cocos/scripting/javascript/bindings/XMLHTTPRequest.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_ccbreader.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes_registration.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.cpp.REMOVED.git-id delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions_registration.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.cpp delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_system_functions.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_system_functions_registration.h delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp delete mode 100644 cocos/scripting/javascript/bindings/js_bindings_system_registration.h delete mode 100644 cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp delete mode 100644 cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.h delete mode 100644 cocos/scripting/javascript/bindings/jsb_websocket.cpp delete mode 100644 cocos/scripting/javascript/bindings/jsb_websocket.h diff --git a/build/cocos2d-win32.vc2012.sln b/build/cocos2d-win32.vc2012.sln index d8c443ec6d..c1f930fa51 100644 --- a/build/cocos2d-win32.vc2012.sln +++ b/build/cocos2d-win32.vc2012.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "audio", "..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" EndProject @@ -15,6 +15,54 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensi EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosStudio", "..\cocos\editor-support\cocostudio\proj.win32\libCocosStudio.vcxproj", "{B57CF53F-2E49-4031-9822-047CC0E6BDE2}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libGUI", "..\cocos\gui\proj.win32\libGUI.vcxproj", "{7E06E92C-537A-442B-9E4A-4761C84F8A1A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\cocos\network\proj.win32\libNetwork.vcxproj", "{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetsManagerTest", "..\samples\Cpp\AssetsManagerTest\proj.win32\AssetsManagerTest.vcxproj", "{6D37505F-A890-441D-BD3F-A61E2C0469CE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\samples\Javascript\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CocosDragonJS", "..\samples\Javascript\CocosDragonJS\proj.win32\CocosDragonJS.vcxproj", "{68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrystalCraze", "..\samples\Javascript\CrystalCraze\proj.win32\CrystalCraze.vcxproj", "{9A17D9A4-4B11-4E32-94F6-895FF4909EC5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "..\samples\Javascript\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WatermelonWithMe", "..\samples\Javascript\WatermelonWithMe\proj.win32\WatermelonWithMe.vcxproj", "{BE092D9E-95AE-4F86-84CE-F4519E4F3F15}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "..\samples\Lua\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\samples\Lua\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimpleGame", "..\samples\Cpp\SimpleGame\proj.win32\SimpleGame.vcxproj", "{E0E282F4-8487-452C-BFAB-CB960EB4D22F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForBuilder", "..\cocos\scripting\javascript\bindings\cocosbuilder\libJSBindingForBuilder.vcxproj", "{F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForStudio", "..\cocos\scripting\javascript\bindings\cocostudio\libJSBindingForStudio.vcxproj", "{79D34511-E54E-410A-8BBA-EF175AD6C695}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForNetwork", "..\cocos\scripting\javascript\bindings\network\libJSBindingForNetwork.vcxproj", "{3BEC13F5-E227-4D80-BC77-1C857F83BCFC}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForExtension", "..\cocos\scripting\javascript\bindings\extension\libJSBindingForExtension.vcxproj", "{625F7391-9A91-48A1-8CFC-79508C822637}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libJSBinding", "libJSBinding", "{10F98A57-B9A1-47DA-9FBA-12D328E72ED1}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForChipmunk", "..\cocos\scripting\javascript\bindings\chipmunk\libJSBindingForChipmunk.vcxproj", "{21070E58-EEC6-4E16-8B4F-6D083DF55790}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForLocalStorage", "..\cocos\scripting\javascript\bindings\localstorage\libJSBindingForLocalStorage.vcxproj", "{68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -49,10 +97,111 @@ Global {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.Build.0 = Debug|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.ActiveCfg = Release|Win32 {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.Build.0 = Release|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.ActiveCfg = Debug|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.Build.0 = Debug|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.ActiveCfg = Release|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.Build.0 = Release|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.Build.0 = Debug|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.ActiveCfg = Release|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.Build.0 = Release|Win32 + {7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Debug|Win32.ActiveCfg = Debug|Win32 + {7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Debug|Win32.Build.0 = Debug|Win32 + {7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Release|Win32.ActiveCfg = Release|Win32 + {7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Release|Win32.Build.0 = Release|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.ActiveCfg = Debug|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.Build.0 = Debug|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.ActiveCfg = Release|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.Build.0 = Release|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Debug|Win32.ActiveCfg = Debug|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Debug|Win32.Build.0 = Debug|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.ActiveCfg = Release|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.Build.0 = Release|Win32 + {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Debug|Win32.ActiveCfg = Debug|Win32 + {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Debug|Win32.Build.0 = Debug|Win32 + {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Release|Win32.ActiveCfg = Release|Win32 + {6D37505F-A890-441D-BD3F-A61E2C0469CE}.Release|Win32.Build.0 = Release|Win32 + {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|Win32.ActiveCfg = Debug|Win32 + {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|Win32.Build.0 = Debug|Win32 + {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.ActiveCfg = Release|Win32 + {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.Build.0 = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.ActiveCfg = Debug|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.Build.0 = Debug|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.ActiveCfg = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.Build.0 = Release|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.ActiveCfg = Debug|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.Build.0 = Debug|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.ActiveCfg = Release|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.Build.0 = Release|Win32 + {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Debug|Win32.ActiveCfg = Debug|Win32 + {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Debug|Win32.Build.0 = Debug|Win32 + {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Release|Win32.ActiveCfg = Release|Win32 + {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}.Release|Win32.Build.0 = Release|Win32 + {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Debug|Win32.ActiveCfg = Debug|Win32 + {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Debug|Win32.Build.0 = Debug|Win32 + {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Release|Win32.ActiveCfg = Release|Win32 + {9A17D9A4-4B11-4E32-94F6-895FF4909EC5}.Release|Win32.Build.0 = Release|Win32 + {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.ActiveCfg = Debug|Win32 + {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.Build.0 = Debug|Win32 + {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.ActiveCfg = Release|Win32 + {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.Build.0 = Release|Win32 + {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Debug|Win32.ActiveCfg = Debug|Win32 + {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Debug|Win32.Build.0 = Debug|Win32 + {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Release|Win32.ActiveCfg = Release|Win32 + {BE092D9E-95AE-4F86-84CE-F4519E4F3F15}.Release|Win32.Build.0 = Release|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.ActiveCfg = Debug|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.Build.0 = Debug|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.ActiveCfg = Release|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.Build.0 = Release|Win32 + {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.ActiveCfg = Debug|Win32 + {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.Build.0 = Debug|Win32 + {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.ActiveCfg = Release|Win32 + {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.Build.0 = Release|Win32 + {E0E282F4-8487-452C-BFAB-CB960EB4D22F}.Debug|Win32.ActiveCfg = Debug|Win32 + {E0E282F4-8487-452C-BFAB-CB960EB4D22F}.Debug|Win32.Build.0 = Debug|Win32 + {E0E282F4-8487-452C-BFAB-CB960EB4D22F}.Release|Win32.ActiveCfg = Release|Win32 + {E0E282F4-8487-452C-BFAB-CB960EB4D22F}.Release|Win32.Build.0 = Release|Win32 + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}.Debug|Win32.ActiveCfg = Debug|Win32 + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}.Debug|Win32.Build.0 = Debug|Win32 + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}.Release|Win32.ActiveCfg = Release|Win32 + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}.Release|Win32.Build.0 = Release|Win32 + {79D34511-E54E-410A-8BBA-EF175AD6C695}.Debug|Win32.ActiveCfg = Debug|Win32 + {79D34511-E54E-410A-8BBA-EF175AD6C695}.Debug|Win32.Build.0 = Debug|Win32 + {79D34511-E54E-410A-8BBA-EF175AD6C695}.Release|Win32.ActiveCfg = Release|Win32 + {79D34511-E54E-410A-8BBA-EF175AD6C695}.Release|Win32.Build.0 = Release|Win32 + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC}.Debug|Win32.ActiveCfg = Debug|Win32 + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC}.Debug|Win32.Build.0 = Debug|Win32 + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC}.Release|Win32.ActiveCfg = Release|Win32 + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC}.Release|Win32.Build.0 = Release|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Debug|Win32.ActiveCfg = Debug|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Debug|Win32.Build.0 = Debug|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Release|Win32.ActiveCfg = Release|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Release|Win32.Build.0 = Release|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Debug|Win32.ActiveCfg = Debug|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Debug|Win32.Build.0 = Debug|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Release|Win32.ActiveCfg = Release|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Release|Win32.Build.0 = Release|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Debug|Win32.ActiveCfg = Debug|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Debug|Win32.Build.0 = Debug|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Release|Win32.ActiveCfg = Release|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {39379840-825A-45A0-B363-C09FFEF864BD} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {625F7391-9A91-48A1-8CFC-79508C822637} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {79D34511-E54E-410A-8BBA-EF175AD6C695} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {21070E58-EEC6-4E16-8B4F-6D083DF55790} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE} = {10F98A57-B9A1-47DA-9FBA-12D328E72ED1} + EndGlobalSection GlobalSection(DPCodeReviewSolutionGUID) = preSolution DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} EndGlobalSection diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 0c421489f9..a7f030bb9f 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -36,9 +36,13 @@ + + + + @@ -69,7 +73,7 @@ Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir);$(ProjectDir)..\physics;$(ProjectDir)..\..\external\glfw3\include\win32;$(ProjectDir)..\base;$(ProjectDir)..\..\external\unzip;$(ProjectDir)..\..\external\tinyxml2;$(ProjectDir)platform\win32;$(ProjectDir)..\..\external\win32-specific\icon\include;$(ProjectDir)..\..\external\win32-specific\zlib\include;$(ProjectDir)..\..\external\png\include\win32;$(ProjectDir)..\..\external\jpeg\include\win32;$(ProjectDir)..\..\external\tiff\include\win32;$(ProjectDir)..\..\external\webp\include\win32;$(ProjectDir)..\..\external\freetype2\include\win32;$(ProjectDir)..\..\external\win32-specific\gles\include\OGLES;$(ProjectDir)..\math\kazmath\include;$(ProjectDir)platform\third_party\common\etc;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -116,7 +120,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir)..;$(ProjectDir)..\platform\win32;$(ProjectDir)..\platform\third_party\win32\iconv;$(ProjectDir)..\platform\third_party\win32\zlib;$(ProjectDir)..\platform\third_party\win32\libpng;$(ProjectDir)..\platform\third_party\win32\libjpeg;$(ProjectDir)..\platform\third_party\win32\libtiff;$(ProjectDir)..\platform\third_party\win32\libwebp;$(ProjectDir)..\platform\third_party\win32\libfreetype2;$(ProjectDir)..\platform\third_party\win32\OGLES;..\include;$(ProjectDir)..\kazmath\include;$(ProjectDir)..\platform\third_party\common\etc;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL @@ -128,7 +132,16 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\external*\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\freetype2\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\glfw3\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\curl\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\jpeg\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\png\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\tiff\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\webp\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\zlib\prebuilt\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\icon\prebuilt\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(OutDir)" diff --git a/cocos/audio/proj.win32/CocosDenshion.vcxproj b/cocos/audio/proj.win32/CocosDenshion.vcxproj index b59c65d98c..ecde64b8c3 100644 --- a/cocos/audio/proj.win32/CocosDenshion.vcxproj +++ b/cocos/audio/proj.win32/CocosDenshion.vcxproj @@ -11,7 +11,7 @@ - audio + libAudio {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} CocosDenshion.win32 Win32Proj @@ -36,9 +36,13 @@ + + + + @@ -65,7 +69,7 @@ Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(ProjectDir)..\..\physics;$(ProjectDir)..\..\base;$(ProjectDir)..\..\2d;$(ProjectDir)..\..\2d\platform\win32;$(ProjectDir)..\..\math\kazmath\include;$(ProjectDir)..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\external\win32-specific\gles\include\OGLES;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -89,7 +93,7 @@ - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;"$(ProjectDir)..\..\cocos2dx";"$(ProjectDir)..\..\cocos2dx\include";"$(ProjectDir)..\..\cocos2dx\kazmath\include";"$(ProjectDir)..\..\cocos2dx\platform\win32";"$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES";%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL diff --git a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp deleted file mode 100644 index cc7b72c586..0000000000 --- a/cocos/scripting/javascript/bindings/XMLHTTPRequest.cpp +++ /dev/null @@ -1,847 +0,0 @@ -// -// XMLHTTPRequest.cpp -// XMLHttpRequest -// -// Created by Zynga 2013 -// -// Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp -// Copyright (c) 2012 Rolando Abarca. All rights reserved. -// -// 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 "XMLHTTPRequest.h" -#include - -using namespace std; - -//#pragma mark - MinXmlHttpRequest - -/** - * @brief Implementation for header retrieving. - * @param header - */ -void MinXmlHttpRequest::_gotHeader(string header) -{ - // Get Header and Set StatusText - // Split String into Tokens - char * cstr = new char [header.length()+1]; - - // check for colon. - unsigned found_header_field = header.find_first_of(":"); - - if (found_header_field != std::string::npos) - { - // Found a header field. - string http_field; - string http_value; - - http_field = header.substr(0,found_header_field); - http_value = header.substr(found_header_field+1, header.length()); - - // Get rid of all \n - if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') { - http_value.erase(http_value.size() - 1); - } - - _httpHeader[http_field] = http_value; - - } - else - { - // Seems like we have the response Code! Parse it and check for it. - char * pch; - strcpy(cstr, header.c_str()); - - pch = strtok(cstr," "); - while (pch != NULL) - { - - stringstream ss; - string val; - - ss << pch; - val = ss.str(); - unsigned found_http = val.find("HTTP"); - - // Check for HTTP Header to set statusText - if (found_http != std::string::npos) { - - stringstream mystream; - - // Get Response Status - pch = strtok (NULL, " "); - mystream << pch; - - pch = strtok (NULL, " "); - mystream << " " << pch; - - _statusText = mystream.str(); - - } - - pch = strtok (NULL, " "); - } - } - - CC_SAFE_DELETE_ARRAY(cstr); -} - -/** - * @brief Set Request header for next call. - * @param field Name of the Header to be set. - * @param value Value of the Headerfield - */ -void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) -{ - stringstream header_s; - stringstream value_s; - string header; - - map::iterator iter = _requestHeader.find(field); - - // Concatenate values when header exists. - if (iter != _requestHeader.end()) - { - value_s << iter->second << "," << value; - } - else - { - value_s << value; - } - - _requestHeader[field] = value_s.str(); -} - -/** - * @brief If headers has been set, pass them to curl. - * - */ -void MinXmlHttpRequest::_setHttpRequestHeader() -{ - std::vector header; - - for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it) - { - const char* first = it->first.c_str(); - const char* second = it->second.c_str(); - size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); - char* test = (char*) malloc(len); - memset(test, 0,len); - - strcpy(test, first); - strcpy(test + strlen(first) , ": "); - strcpy(test + strlen(first) + 2, second); - - header.push_back(test); - - free(test); - - } - - if (!header.empty()) - { - _httpRequest->setHeaders(header); - } - -} - -/** - * @brief Callback for HTTPRequest. Handles the response and invokes Callback. - * @param sender Object which initialized callback - * @param respone Response object - */ -void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response) -{ - if (0 != strlen(response->getHttpRequest()->getTag())) - { - CCLOG("%s completed", response->getHttpRequest()->getTag()); - } - - int statusCode = response->getResponseCode(); - char statusString[64] = {}; - sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); - - if (!response->isSucceed()) - { - CCLOG("response failed"); - CCLOG("error buffer: %s", response->getErrorBuffer()); - return; - } - - // set header - std::vector *headers = response->getResponseHeader(); - - char* concatHeader = (char*) malloc(headers->size() + 1); - std::string header(headers->begin(), headers->end()); - strcpy(concatHeader, header.c_str()); - - std::istringstream stream(concatHeader); - std::string line; - while(std::getline(stream, line)) { - _gotHeader(line); - } - - /** get the response data **/ - std::vector *buffer = response->getResponseData(); - char* concatenated = (char*) malloc(buffer->size() + 1); - std::string s2(buffer->begin(), buffer->end()); - - strcpy(concatenated, s2.c_str()); - - if (statusCode == 200) - { - //Succeeded - _status = 200; - _readyState = DONE; - _data << concatenated; - _dataSize = buffer->size(); - } - else - { - _status = 0; - } - // Free Memory. - free((void*) concatHeader); - free((void*) concatenated); - - js_proxy_t * p; - void* ptr = (void*)this; - p = jsb_get_native_proxy(ptr); - - if(p) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - - if (_onreadystateCallback) - { - //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx); - jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback); - jsval out; - JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out); - } - - } - -} -/** - * @brief Send out request and fire callback when done. - * @param cx Javascript context - */ -void MinXmlHttpRequest::_sendRequest(JSContext *cx) -{ - _httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse)); - network::HttpClient::getInstance()->send(_httpRequest); - _httpRequest->release(); -} - -/** - * @brief Constructor initializes cchttprequest and stuff - * - */ -MinXmlHttpRequest::MinXmlHttpRequest() : _onreadystateCallback(NULL), _isNetwork(true) -{ - _httpHeader.clear(); - _requestHeader.clear(); - _withCredentialsValue = true; - _cx = ScriptingCore::getInstance()->getGlobalContext(); - _httpRequest = new network::HttpRequest(); -} - -/** - * @brief Destructor cleans up _httpRequest and stuff - * - */ -MinXmlHttpRequest::~MinXmlHttpRequest() -{ - _httpHeader.clear(); - _requestHeader.clear(); - - if (_onreadystateCallback != NULL) - { - JS_RemoveObjectRoot(_cx, &_onreadystateCallback); - } - - if (_httpRequest) - { - // We don't need to release _httpRequest here since it will be released in the http callback. -// _httpRequest->release(); - } - -} - -/** - * @brief Initialize Object and needed properties. - * - */ -JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest); - -/** - * @brief Implementation for the Javascript Constructor - * - */ -JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest) -{ - MinXmlHttpRequest* req = new MinXmlHttpRequest(); - req->autorelease(); - - js_proxy_t *p; - jsval out; - - JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent); - - if (obj) { - JS_SetPrivate(obj, req); - out = OBJECT_TO_JSVAL(obj); - } - - JS_SET_RVAL(cx, vp, out); - p =jsb_new_proxy(req, obj); - - JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest"); - return JS_TRUE; -} - -/** - * @brief get Callback function for Javascript - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) -{ - if (_onreadystateCallback) - { - JSString *tmpstr = JS_NewStringCopyZ(cx, "1"); - jsval tmpval = STRING_TO_JSVAL(tmpstr); - JS_SetProperty(cx, _onreadystateCallback, "readyState", &tmpval); - - jsval out = OBJECT_TO_JSVAL(_onreadystateCallback); - vp.set(out); - - } - else - { - vp.set(JSVAL_NULL); - } - return JS_TRUE; -} - -/** - * @brief Set Callback function coming from Javascript - * - * - */ -JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) -{ - jsval callback = vp.get(); - if (callback != JSVAL_NULL) - { - _onreadystateCallback = JSVAL_TO_OBJECT(callback); - JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback"); - } - return JS_TRUE; -} - -/** - * @brief upload getter - TODO - * - * Placeholder for further implementations!! - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) -{ - vp.set(JSVAL_NULL); - return JS_TRUE; -} - -/** - * @brief upload setter - TODO - * - * Placeholder for further implementations - */ -JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) -{ - vp.set(JSVAL_NULL); - return JS_TRUE; -} - -/** - * @brief timeout getter - TODO - * - * Placeholder for further implementations - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout) -{ - vp.set(INT_TO_JSVAL(_timeout)); - return JS_TRUE; -} - -/** - * @brief timeout setter - TODO - * - * Placeholder for further implementations - */ -JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout) -{ - jsval timeout_ms = vp.get(); - - _timeout = JSVAL_TO_INT(timeout_ms); - //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout); - return JS_TRUE; - -} - -/** - * @brief get response type for actual XHR - * - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) -{ - JSString* str = JS_NewStringCopyN(cx, "", 0); - vp.set(STRING_TO_JSVAL(str)); - return JS_TRUE; -} - -/** - * @brief responseXML getter - TODO - * - * Placeholder for further implementation. - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML) -{ - vp.set(JSVAL_NULL); - return JS_TRUE; -} - -/** - * @brief set response type for actual XHR - * - * - */ -JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) -{ - jsval type = vp.get(); - if (type.isString()) { - JSString* str = type.toString(); - JSBool equal; - - JS_StringEqualsAscii(cx, str, "text", &equal); - if (equal) - { - _responseType = ResponseType::STRING; - return JS_TRUE; - } - - JS_StringEqualsAscii(cx, str, "arraybuffer", &equal); - if (equal) - { - _responseType = ResponseType::ARRAY_BUFFER; - return JS_TRUE; - } - - JS_StringEqualsAscii(cx, str, "json", &equal); - if (equal) - { - _responseType = ResponseType::JSON; - return JS_TRUE; - } - // ignore the rest of the response types for now - return JS_TRUE; - } - JS_ReportError(cx, "Invalid response type"); - return JS_FALSE; -} - -/** - * @brief get readyState for actual XHR - * - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) -{ - vp.set(INT_TO_JSVAL(_readyState)); - return JS_TRUE; -} - -/** - * @brief get status for actual XHR - * - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status) -{ - vp.set(INT_TO_JSVAL(_status)); - return JS_TRUE; -} - -/** - * @brief get statusText for actual XHR - * - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) -{ - jsval strVal = std_string_to_jsval(cx, _statusText); - - if (strVal != JSVAL_NULL) - { - vp.set(strVal); - return JS_TRUE; - } - else - { - JS_ReportError(cx, "Error trying to create JSString from data"); - return JS_FALSE; - } -} - -/** - * @brief get value of withCredentials property. - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials) -{ - vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue)); - return JS_TRUE; -} - -/** - * withCredentials - set value of withCredentials property. - * - */ -JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) -{ - jsval credential = vp.get(); - if (credential != JSVAL_NULL) - { - _withCredentialsValue = JSVAL_TO_BOOLEAN(credential); - } - - return JS_TRUE; -} - -/** - * @brief get (raw) responseText - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) -{ - jsval strVal = std_string_to_jsval(cx, _data.str()); - - if (strVal != JSVAL_NULL) - { - vp.set(strVal); - //JS_ReportError(cx, "Result: %s", data.str().c_str()); - return JS_TRUE; - } else { - JS_ReportError(cx, "Error trying to create JSString from data"); - return JS_FALSE; - } -} - -/** - * @brief get response of latest XHR - * - */ -JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) -{ - - if (_responseType == ResponseType::JSON) - { - jsval outVal; - - jsval strVal = std_string_to_jsval(cx, _data.str()); - if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) - { - vp.set(outVal); - return JS_TRUE; - } - } - else if (_responseType == ResponseType::ARRAY_BUFFER) - { - JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize); - uint8_t* tmpData = JS_GetArrayBufferData(tmp); - _data.read((char*)tmpData, _dataSize); - jsval outVal = OBJECT_TO_JSVAL(tmp); - - vp.set(outVal); - return JS_TRUE; - } - // by default, return text - return _js_get_responseText(cx, id, vp); -} - -/** - * @brief initialize new xhr. - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) -{ - if (argc >= 2) - { - jsval* argv = JS_ARGV(cx, vp); - const char* method; - const char* urlstr; - JSBool async = true; - JSString* jsMethod = JS_ValueToString(cx, argv[0]); - JSString* jsURL = JS_ValueToString(cx, argv[1]); - - if (argc > 2) { - JS_ValueToBoolean(cx, argv[2], &async); - } - - JSStringWrapper w1(jsMethod); - JSStringWrapper w2(jsURL); - method = w1; - urlstr = w2; - - _url = urlstr; - _meth = method; - _readyState = 1; - _isAsync = async; - - if (_url.length() > 5 && _url.compare(_url.length() - 5, 5, ".json") == 0) - { - _responseType = ResponseType::JSON; - } - - if (_meth.compare("post") == 0 || _meth.compare("POST") == 0) - { - _httpRequest->setRequestType(network::HttpRequest::Type::POST); - } - else - { - _httpRequest->setRequestType(network::HttpRequest::Type::GET); - } - - _httpRequest->setUrl(_url.c_str()); - - _isNetwork = true; - _readyState = OPENED; - - return JS_TRUE; - } - - JS_ReportError(cx, "invalid call: %s", __FUNCTION__); - return JS_FALSE; - -} - -/** - * @brief send xhr - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) -{ - JSString *str = NULL; - std::string data; - - // Clean up header map. New request, new headers! - _httpHeader.clear(); - - if (argc == 1) - { - if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) - { - return JS_FALSE; - } - JSStringWrapper strWrap(str); - data = strWrap.get(); - } - - - if (data.length() > 0 && (_meth.compare("post") == 0 || _meth.compare("POST") == 0)) - { - _httpRequest->setRequestData(data.c_str(), data.length()); - } - - _setHttpRequestHeader(); - _sendRequest(cx); - - return JS_TRUE; -} - -/** - * @brief abort function Placeholder! - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort) -{ - return JS_TRUE; -} - -/** - * @brief Get all response headers as a string - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders) -{ - stringstream responseheaders; - string responseheader; - - for (auto it = _httpHeader.begin(); it != _httpHeader.end(); ++it) - { - responseheaders << it->first << ": " << it->second << "\n"; - } - - responseheader = responseheaders.str(); - - jsval strVal = std_string_to_jsval(cx, responseheader); - if (strVal != JSVAL_NULL) - { - JS_SET_RVAL(cx, vp, strVal); - return JS_TRUE; - } - else - { - JS_ReportError(cx, "Error trying to create JSString from data"); - return JS_FALSE; - } - - return JS_TRUE; -} - -/** - * @brief Get all response headers as a string - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) -{ - JSString *header_value; - - if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) { - return JS_FALSE; - }; - - std::string data; - JSStringWrapper strWrap(header_value); - data = strWrap.get(); - - stringstream streamdata; - - streamdata << data; - - string value = streamdata.str(); - - auto iter = _httpHeader.find(value); - if (iter != _httpHeader.end()) - { - jsval js_ret_val = std_string_to_jsval(cx, iter->second); - JS_SET_RVAL(cx, vp, js_ret_val); - return JS_TRUE; - } - else { - JS_SET_RVAL(cx, vp, JSVAL_NULL); - return JS_TRUE; - } -} - -/** - * @brief Set the given Fields to request Header. - * - * - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) -{ - if (argc >= 2) - { - jsval* argv = JS_ARGV(cx, vp); - const char* field; - const char* value; - - JSString* jsField = JS_ValueToString(cx, argv[0]); - JSString* jsValue = JS_ValueToString(cx, argv[1]); - - JSStringWrapper w1(jsField); - JSStringWrapper w2(jsValue); - field = w1; - value = w2; - - // Populate the request_header map. - _setRequestHeader(field, value); - - return JS_TRUE; - } - - return JS_FALSE; - -} - -/** - * @brief overrideMimeType function - TODO! - * - * Just a placeholder for further implementations. - */ -JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType) -{ - return JS_TRUE; -} - -/** - * @brief destructor for Javascript - * - */ -static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) -{ - CCLOG("basic_object_finalize %p ...", obj); -} - -/** - * @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods. - * @param cx Global Spidermonkey JS Context. - * @param global Global Spidermonkey Javascript object. - */ -void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global) -{ - JSClass js_class = { - "XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub, - JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, - JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS - }; - - MinXmlHttpRequest::js_class = js_class; - static JSPropertySpec props[] = { - JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange), - JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType), - JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML), - JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response), - {0, 0, 0, 0, 0} - }; - - static JSFunctionSpec funcs[] = { - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader), - JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType), - JS_FS_END - }; - - MinXmlHttpRequest::js_parent = NULL; - MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL); - -} - diff --git a/cocos/scripting/javascript/bindings/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/XMLHTTPRequest.h deleted file mode 100644 index 861e0a2536..0000000000 --- a/cocos/scripting/javascript/bindings/XMLHTTPRequest.h +++ /dev/null @@ -1,112 +0,0 @@ -// -// XMLHTTPRequest.h -// XMLHttpRequest -// -// Created by Zynga 2013 -// -// Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.h -// Copyright (c) 2012 Rolando Abarca. All rights reserved. -// -// 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 __FAKE_XMLHTTPREQUEST_H__ -#define __FAKE_XMLHTTPREQUEST_H__ - -#include "network/HttpClient.h" -#include "js_bindings_config.h" -#include "ScriptingCore.h" -#include "jstypes.h" -#include "jsapi.h" -#include "jsfriendapi.h" -#include "jsb_helper.h" - -class MinXmlHttpRequest : public cocos2d::Object -{ -public: - enum class ResponseType - { - STRING, - ARRAY_BUFFER, - BLOB, - DOCUMENT, - JSON - }; - - // Ready States (http://www.w3.org/TR/XMLHttpRequest/#interface-xmlhttprequest) - static const unsigned short UNSENT = 0; - static const unsigned short OPENED = 1; - static const unsigned short HEADERS_RECEIVED = 2; - static const unsigned short LOADING = 3; - static const unsigned short DONE = 4; - - MinXmlHttpRequest(); - ~MinXmlHttpRequest(); - - JS_BINDED_CLASS_GLUE(MinXmlHttpRequest); - JS_BINDED_CONSTRUCTOR(MinXmlHttpRequest); - JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, onreadystatechange); - JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, responseType); - JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, withCredentials); - JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, upload); - JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, timeout); - JS_BINDED_PROP_GET(MinXmlHttpRequest, readyState); - JS_BINDED_PROP_GET(MinXmlHttpRequest, status); - JS_BINDED_PROP_GET(MinXmlHttpRequest, statusText); - JS_BINDED_PROP_GET(MinXmlHttpRequest, responseText); - JS_BINDED_PROP_GET(MinXmlHttpRequest, response); - JS_BINDED_PROP_GET(MinXmlHttpRequest, responseXML); - JS_BINDED_FUNC(MinXmlHttpRequest, open); - JS_BINDED_FUNC(MinXmlHttpRequest, send); - JS_BINDED_FUNC(MinXmlHttpRequest, abort); - JS_BINDED_FUNC(MinXmlHttpRequest, getAllResponseHeaders); - JS_BINDED_FUNC(MinXmlHttpRequest, getResponseHeader); - JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader); - JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType); - - void handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response); - - -private: - void _gotHeader(std::string header); - void _setRequestHeader(const char* field, const char* value); - void _setHttpRequestHeader(); - void _sendRequest(JSContext *cx); - - std::string _url; - JSContext* _cx; - std::string _meth; - std::string _type; - std::stringstream _data; - size_t _dataSize; - JSObject* _onreadystateCallback; - int _readyState; - int _status; - std::string _statusText; - ResponseType _responseType; - unsigned _timeout; - bool _isAsync; - network::HttpRequest* _httpRequest; - bool _isNetwork; - bool _withCredentialsValue; - std::map _httpHeader; - std::map _requestHeader; -}; - -#endif diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index b8cda9a498..082d55b8bd 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -bf994ad1fc8ac1044957d83708f7848e99ca59e6 \ No newline at end of file +33fef8c7bc7006ad55c27fd0ed9c9dd2c8064079 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index 1072cc8064..2981a726a8 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -101,25 +101,6 @@ protected: jsval _extraData; }; - -class JSCCBAnimationWrapper: public JSCallbackWrapper { -public: - JSCCBAnimationWrapper() {} - virtual ~JSCCBAnimationWrapper() {} - - void animationCompleteCallback() { - - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - jsval retval = JSVAL_NULL; - - if(!JSVAL_IS_VOID(_jsCallback) && !JSVAL_IS_VOID(_jsThisObj)) { - JS_CallFunctionValue(cx, JSVAL_TO_OBJECT(_jsThisObj), _jsCallback, 0, NULL, &retval); - } - } - -}; - - class JSCallFuncWrapper: public JSCallbackWrapper { public: JSCallFuncWrapper() {} diff --git a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp deleted file mode 100644 index 733ac47b45..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.cpp +++ /dev/null @@ -1,324 +0,0 @@ -// -// js_bindings_ccbreader.cpp -// watermelon -// -// Created by Rohan Kuruvilla on 14/08/2012. -// -// - -#include "js_bindings_ccbreader.h" -#include "ScriptingCore.h" -#include "js_bindings_config.h" - -USING_NS_CC; -USING_NS_CC_EXT; -using namespace cocosbuilder; - -static void removeSelector(std::string &str) { - size_t found; - found = str.find(":"); - while (found!=std::string::npos){ - str.replace(found, found+1, ""); - found = str.find(":"); - } -} - -SEL_MenuHandler CCBScriptCallbackProxy::onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, - const char * pSelectorName) { - this->callBackProp = pSelectorName; - removeSelector(this->callBackProp); - return menu_selector(CCBScriptCallbackProxy::menuItemCallback); -} - -Control::Handler CCBScriptCallbackProxy::onResolveCCBCCControlSelector(Object * pTarget, - const char * pSelectorName) { - - this->callBackProp = pSelectorName; - removeSelector(this->callBackProp); - return cccontrol_selector(CCBScriptCallbackProxy::controlCallback); -} - -bool CCBScriptCallbackProxy::onAssignCCBMemberVariable(Object * pTarget, - const char * pMemberVariableName, - Node * pNode) { - return true; -} - -void CCBScriptCallbackProxy::onNodeLoaded(Node * pNode, - NodeLoader * pNodeLoader) {} - -CCBSelectorResolver * CCBScriptCallbackProxy::createNew() { - CCBScriptCallbackProxy * ret = new CCBScriptCallbackProxy(); - ret->setJSOwner(this->owner); - return dynamic_cast(ret); -} - -void CCBScriptCallbackProxy::menuItemCallback(Object *pSender) { - ScriptingCore::getInstance()->executeFunctionWithOwner(owner, callBackProp.c_str() ); -} - -void CCBScriptCallbackProxy::controlCallback(Object *pSender, Control::EventType event) { - ScriptingCore::getInstance()->executeFunctionWithOwner(owner, callBackProp.c_str() ); -} - -void CCBScriptCallbackProxy::setCallbackProperty(const char *prop) { - callBackProp = prop; -} - -void CCBScriptCallbackProxy::setJSOwner(jsval ownr) { - owner = ownr; -} - -jsval CCBScriptCallbackProxy::getJSOwner() { - return owner; -} - -JSBool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, uint32_t argc, jsval *vp) -{ - if (argc >= 1) { - jsval *argv = JS_ARGV(cx, vp); - - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocosbuilder::CCBAnimationManager *node = (cocosbuilder::CCBAnimationManager *)(proxy ? proxy->ptr : NULL); - - JSCCBAnimationWrapper *tmpCobj = new JSCCBAnimationWrapper(); - tmpCobj->autorelease(); - - tmpCobj->setJSCallbackThis(argv[0]); - if(argc >= 2) { - tmpCobj->setJSCallbackFunc(argv[1]); - } - - node->setAnimationCompletedCallback(tmpCobj, callfunc_selector(JSCCBAnimationWrapper::animationCompleteCallback)); - - JS_SetReservedSlot(proxy->obj, 0, argv[0]); - JS_SetReservedSlot(proxy->obj, 1, argv[1]); - return JS_TRUE; - } - return JS_FALSE; -} - -JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; - JSObject *obj; - cocosbuilder::CCBReader* cobj; - obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, cobj) - - if (argc == 2) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - cocos2d::Object* arg1; - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); - proxy = jsb_get_js_proxy(tmpObj); - arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg1) - } while (0); - - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - if (argc == 1) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - if (argc == 3) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - cocos2d::Object* arg1; - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); - proxy = jsb_get_js_proxy(tmpObj); - arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg1) - } while (0); - cocos2d::Size arg2; - ok &= jsval_to_ccsize(cx, argv[2], &arg2); - - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1, arg2); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - return JS_FALSE; -} - -JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; - JSObject *obj; - cocosbuilder::CCBReader* cobj; - obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, cobj) - - if (argc == 2) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - cocos2d::Object* arg1; - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); - proxy = jsb_get_js_proxy(tmpObj); - arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg1) - } while (0); - - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - if (argc == 1) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - if (argc == 3) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - cocos2d::Object* arg1; - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); - proxy = jsb_get_js_proxy(tmpObj); - arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg1) - } while (0); - cocos2d::Size arg2; - ok &= jsval_to_ccsize(cx, argv[2], &arg2); - - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1, arg2); - jsval jsret; do { - if (ret) { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - - return JS_FALSE; -} - - -JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) -{ - - NodeLoaderLibrary * ccNodeLoaderLibrary = NodeLoaderLibrary::getInstance(); - - ccNodeLoaderLibrary->registerNodeLoader("", JSLayerLoader::loader()); - - CCBReader * ret = new CCBReader(ccNodeLoaderLibrary); - ret->autorelease(); - - jsval jsret; - if (ret) { - js_proxy_t *proxy = jsb_get_native_proxy(ret); - if (proxy) { - jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { - // create a new js obj of that class - proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } - } else { - jsret = JSVAL_NULL; - } - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - -} - -extern JSObject* jsb_CCBReader_prototype; -extern JSObject* jsb_CCBAnimationManager_prototype; - -void register_CCBuilderReader(JSContext *cx, JSObject *obj) { - jsval nsval; - JSObject *ns; - JS_GetProperty(cx, obj, "cc", &nsval); - if (nsval == JSVAL_VOID) { - ns = JS_NewObject(cx, NULL, NULL, NULL); - nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); - } else { - JS_ValueToObject(cx, nsval, &ns); - } - obj = ns; - - JSObject *tmpObj = JSVAL_TO_OBJECT(anonEvaluate(cx, obj, "(function () { return cc._Reader; })()")); - JS_DefineFunction(cx, tmpObj, "create", js_CocosBuilder_create, 2, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, tmpObj, "loadScene", js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile, 2, JSPROP_READONLY | JSPROP_PERMANENT); - - JS_DefineFunction(cx, jsb_CCBReader_prototype, "load", js_cocos2dx_CCBReader_readNodeGraphFromFile, 2, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_CCBAnimationManager_prototype, "setCompletedAnimationCallback", js_cocos2dx_CCBAnimationManager_animationCompleteCallback, 2, JSPROP_READONLY | JSPROP_PERMANENT); -} diff --git a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h b/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h deleted file mode 100644 index 8bcdabd044..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_ccbreader.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// js_bindings_ccbreader.h -// watermelon -// -// Created by Rohan Kuruvilla on 14/08/2012. -// -// -#ifndef __JS_BINDINGS_CCBREADER_H__ -#define __JS_BINDINGS_CCBREADER_H__ - -#include "jsapi.h" -#include "cocos2d_specifics.hpp" -#include "cocosbuilder/CocosBuilder.h" - -class CCBScriptCallbackProxy: public cocos2d::Layer -, public cocosbuilder::CCBSelectorResolver -, public cocosbuilder::CCBMemberVariableAssigner { - - std::string callBackProp; - jsval owner; - -public: - - - CCBScriptCallbackProxy () {} - virtual ~CCBScriptCallbackProxy() {} - - CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(CCBScriptCallbackProxy, create); - virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, - const char * pSelectorName); - - virtual cocos2d::extension::Control::Handler onResolveCCBCCControlSelector(cocos2d::Object * pTarget, - const char * pSelectorName); - virtual bool onAssignCCBMemberVariable(cocos2d::Object * pTarget, const char * pMemberVariableName, - cocos2d::Node * pNode); - virtual void onNodeLoaded(cocos2d::Node * pNode, - cocosbuilder::NodeLoader * pNodeLoader); - - virtual CCBSelectorResolver * createNew(); - void menuItemCallback(Object *pSender); - void controlCallback(Object *pSender, cocos2d::extension::Control::EventType event); - void setCallbackProperty(const char *prop); - void setJSOwner(jsval ownr); - jsval getJSOwner(); -}; - - -class JSLayerLoader : public cocosbuilder::LayerLoader { -public: - CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(JSLayerLoader, loader); - -protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCBScriptCallbackProxy); -}; - -void register_CCBuilderReader(JSContext *cx, JSObject *global); -JSBool js_CocosBuilder_Run(JSContext *cx, uint32_t argc, jsval *vp); - -#endif /* __JS_BINDINGS_CCBREADER_H__ */ - diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id deleted file mode 100644 index c8c345c32c..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -6558be4f421be9227dc4fabf1b682d479825bd18 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.h deleted file mode 100644 index 42c8840236..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 -* Script version: v0.3 -*/ -#include "js_bindings_config.h" -#ifdef JSB_INCLUDE_CHIPMUNK - -#include "js_bindings_chipmunk_manual.h" -extern JSObject *JSB_cpConstraint_object; -extern JSClass *JSB_cpConstraint_class; -void JSB_cpConstraint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpGrooveJoint_object; -extern JSClass *JSB_cpGrooveJoint_class; -void JSB_cpGrooveJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpSimpleMotor_object; -extern JSClass *JSB_cpSimpleMotor_class; -void JSB_cpSimpleMotor_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpPivotJoint_object; -extern JSClass *JSB_cpPivotJoint_class; -void JSB_cpPivotJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpPinJoint_object; -extern JSClass *JSB_cpPinJoint_class; -void JSB_cpPinJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpSlideJoint_object; -extern JSClass *JSB_cpSlideJoint_class; -void JSB_cpSlideJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpGearJoint_object; -extern JSClass *JSB_cpGearJoint_class; -void JSB_cpGearJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpDampedRotarySpring_object; -extern JSClass *JSB_cpDampedRotarySpring_class; -void JSB_cpDampedRotarySpring_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpDampedSpring_object; -extern JSClass *JSB_cpDampedSpring_class; -void JSB_cpDampedSpring_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpRatchetJoint_object; -extern JSClass *JSB_cpRatchetJoint_class; -void JSB_cpRatchetJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpRotaryLimitJoint_object; -extern JSClass *JSB_cpRotaryLimitJoint_class; -void JSB_cpRotaryLimitJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpArbiter_object; -extern JSClass *JSB_cpArbiter_class; -void JSB_cpArbiter_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpSpace_object; -extern JSClass *JSB_cpSpace_class; -void JSB_cpSpace_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpBody_object; -extern JSClass *JSB_cpBody_class; -void JSB_cpBody_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpShape_object; -extern JSClass *JSB_cpShape_class; -void JSB_cpShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpCircleShape_object; -extern JSClass *JSB_cpCircleShape_class; -void JSB_cpCircleShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpSegmentShape_object; -extern JSClass *JSB_cpSegmentShape_class; -void JSB_cpSegmentShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); -extern JSObject *JSB_cpPolyShape_object; -extern JSClass *JSB_cpPolyShape_class; -void JSB_cpPolyShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); - - -#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes_registration.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes_registration.h deleted file mode 100644 index da26c49bb3..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_auto_classes_registration.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 -* Script version: v0.3 -*/ -#include "js_bindings_config.h" -#ifdef JSB_INCLUDE_CHIPMUNK - -JSB_cpConstraint_createClass(_cx, chipmunk, "Constraint"); -JSB_cpGrooveJoint_createClass(_cx, chipmunk, "GrooveJoint"); -JSB_cpSimpleMotor_createClass(_cx, chipmunk, "SimpleMotor"); -JSB_cpPivotJoint_createClass(_cx, chipmunk, "PivotJoint"); -JSB_cpPinJoint_createClass(_cx, chipmunk, "PinJoint"); -JSB_cpSlideJoint_createClass(_cx, chipmunk, "SlideJoint"); -JSB_cpGearJoint_createClass(_cx, chipmunk, "GearJoint"); -JSB_cpDampedRotarySpring_createClass(_cx, chipmunk, "DampedRotarySpring"); -JSB_cpDampedSpring_createClass(_cx, chipmunk, "DampedSpring"); -JSB_cpRatchetJoint_createClass(_cx, chipmunk, "RatchetJoint"); -JSB_cpRotaryLimitJoint_createClass(_cx, chipmunk, "RotaryLimitJoint"); -JSB_cpArbiter_createClass(_cx, chipmunk, "Arbiter"); -JSB_cpSpace_createClass(_cx, chipmunk, "Space"); -JSB_cpBody_createClass(_cx, chipmunk, "Body"); -JSB_cpShape_createClass(_cx, chipmunk, "Shape"); -JSB_cpCircleShape_createClass(_cx, chipmunk, "CircleShape"); -JSB_cpSegmentShape_createClass(_cx, chipmunk, "SegmentShape"); -JSB_cpPolyShape_createClass(_cx, chipmunk, "PolyShape"); - - -#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.cpp.REMOVED.git-id deleted file mode 100644 index 5cf2a4495d..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.cpp.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -1c5eb9cd58c82de77374cdfa5c9ff647cc8b2f02 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.h deleted file mode 100644 index accf523d5e..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 -* Script version: v0.3 -*/ -#include "js_bindings_config.h" -#ifdef JSB_INCLUDE_CHIPMUNK -#include "js_bindings_chipmunk_manual.h" - -#ifdef __cplusplus -extern "C" { -#endif -JSBool JSB_cpArbiterGetCount(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetDepth(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetNormal(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterIgnore(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterIsFirstContact(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalImpulseWithFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalKE(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpAreaForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpAreaForSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBArea(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBClampVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBContainsBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBContainsVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBExpand(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBIntersects(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBIntersectsSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBMerge(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBMergedArea(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBNewForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBSegmentQuery(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBWrapVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyActivate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyActivateStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyApplyForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyApplyImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetMass(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetMoment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetPos(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetRot(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetTorque(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelAtLocalPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelAtWorldPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyInit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyInitStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsRogue(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsSleeping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyKineticEnergy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyLocal2World(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyNewStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyResetForces(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetMass(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetMoment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetPos(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetTorque(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySleep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySleepWithGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyUpdatePosition(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyUpdateVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyWorld2Local(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBoxShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBoxShapeNew2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeGetOffset(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintActivateBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetRestLength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetRestLength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointGetRatio(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointSetRatio(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpInitChipmunk(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForBox(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForBox2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetDist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetDist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointNew2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPolyShapeGetNumVerts(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPolyShapeGetVert(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetRatchet(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetRatchet(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpResetShapeIdCounter(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetNormal(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeSetNeighbors(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeCacheBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetLayers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSensor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapePointQuery(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetLayers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetSensor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeUpdate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorGetRate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorSetRate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceActivateShapesTouchingShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCurrentTimeStep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetGravity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetIterations(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetStaticBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceInit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceIsLocked(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpacePointQueryFirst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexShapesForBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetGravity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetIterations(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceStep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceUseSpatialHash(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfabs(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfclamp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfclamp01(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpflerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpflerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfmax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfmin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvadd(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvclamp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvcross(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdistsq(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdot(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpveql(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvforangle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlengthsq(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvmult(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnear(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvneg(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnormalize(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnormalize_safe(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvperp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvproject(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvrotate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvrperp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvslerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvslerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvsub(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvtoangle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvunrotate(JSContext *cx, uint32_t argc, jsval *vp); - -#ifdef __cplusplus -} -#endif - - -#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions_registration.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions_registration.h deleted file mode 100644 index 2d84087c28..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_functions_registration.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-10-18 -* Script version: v0.3 -*/ -#include "js_bindings_config.h" -#ifdef JSB_INCLUDE_CHIPMUNK - -#include "js_bindings_chipmunk_manual.h" -JS_DefineFunction(_cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - - -#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp deleted file mode 100644 index 14a88c87bb..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.cpp +++ /dev/null @@ -1,1624 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 "extensions/cocos-ext.h" -#include "js_bindings_config.h" -#ifdef JSB_INCLUDE_CHIPMUNK - -#include "jsapi.h" -#include "jsfriendapi.h" - -#include "js_bindings_chipmunk_manual.h" -#include "js_manual_conversions.h" - -USING_NS_CC_EXT; -// Function declarations -void static freeSpaceChildren(cpSpace *space); - -template -static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { - TypeTest t; - T* cobj = new T(); - cobj->autorelease(); - js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - assert(p); - JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto); - js_proxy_t *pp = jsb_new_proxy(cobj, _tmp); - JS_AddObjectRoot(cx, &pp->obj); - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(_tmp)); - - return JS_TRUE; -} - -#pragma mark - convertions - -/* - * PhysicsSprite - */ -#pragma mark - PhysicsSprite - -JSClass* JSPROXY_CCPhysicsSprite_class = NULL; -JSObject* JSPROXY_CCPhysicsSprite_object = NULL; -// Constructor - -// Destructor -void JSPROXY_CCPhysicsSprite_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("jsbindings: finalizing JS object %p (PhysicsSprite)", obj); -} - -// Arguments: -// Ret value: cpBody* (N/A) -JSBool JSPROXY_CCPhysicsSprite_getCPBody(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - cpBody* ret_val; - - ret_val = real->getCPBody(); - jsval ret_jsval = c_class_to_jsval( cx, ret_val, JSB_cpBody_object, JSB_cpBody_class, "cpBody" ); - JS_SET_RVAL(cx, vp, ret_jsval); - - return JS_TRUE; -} - -// Arguments: -// Ret value: BOOL (b) -JSBool JSPROXY_CCPhysicsSprite_ignoreBodyRotation(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - - bool ret_val; - - ret_val = real->isIgnoreBodyRotation(); - JS_SET_RVAL(cx, vp, BOOLEAN_TO_JSVAL(ret_val)); - return JS_TRUE; -} - -// Arguments: cpBody* -// Ret value: void (None) -JSBool JSPROXY_CCPhysicsSprite_setCPBody_(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - - cpBody* arg0; - - ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - if( ! ok ) return JS_FALSE; - - real->setCPBody((cpBody*)arg0); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: BOOL -// Ret value: void (None) -JSBool JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - JSBool arg0; - - ok &= JS_ValueToBoolean( cx, *argvp++, &arg0 ); - if( ! ok ) return JS_FALSE; - - real->setIgnoreBodyRotation((bool)arg0); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -/* - * PhysicsDebugNode - */ -//#pragma mark - PhysicsDebugNode - -JSClass* JSB_CCPhysicsDebugNode_class = NULL; -JSObject* JSB_CCPhysicsDebugNode_object = NULL; -extern JSObject *js_cocos2dx_CCDrawNode_prototype; - -// Constructor - -// Destructor -void JSB_CCPhysicsDebugNode_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("jsbindings: finalizing JS object %p (PhysicsDebugNode)", obj); -} - -// Arguments: cpSpace* -// Ret value: PhysicsDebugNode* (o) -JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpSpace* arg0; - - ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - PhysicsDebugNode* ret = PhysicsDebugNode::create(arg0); - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCDebugNode"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - - return JS_TRUE; -} - -// Arguments: cpSpace* -// Ret value: void (None) -JSBool JSB_CCPhysicsDebugNode_setSpace_(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(jsthis); - PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpSpace* arg0; - - ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - real->setSpace(arg0); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: -// Ret value: cpSpace* (N/A) -JSBool JSB_CCPhysicsDebugNode_space(JSContext *cx, uint32_t argc, jsval *vp) { - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(jsthis); - PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, real) - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); - cpSpace* ret_val; - - ret_val = real->getSpace(); - - jsval ret_jsval = opaque_to_jsval( cx, ret_val ); - JS_SET_RVAL(cx, vp, ret_jsval); - - return JS_TRUE; -} - -void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, const char* name ) -{ - JSB_CCPhysicsDebugNode_class = (JSClass *)calloc(1, sizeof(JSClass)); - JSB_CCPhysicsDebugNode_class->name = name; - JSB_CCPhysicsDebugNode_class->addProperty = JS_PropertyStub; - JSB_CCPhysicsDebugNode_class->delProperty = JS_DeletePropertyStub; - JSB_CCPhysicsDebugNode_class->getProperty = JS_PropertyStub; - JSB_CCPhysicsDebugNode_class->setProperty = JS_StrictPropertyStub; - JSB_CCPhysicsDebugNode_class->enumerate = JS_EnumerateStub; - JSB_CCPhysicsDebugNode_class->resolve = JS_ResolveStub; - JSB_CCPhysicsDebugNode_class->convert = JS_ConvertStub; - JSB_CCPhysicsDebugNode_class->finalize = JSB_CCPhysicsDebugNode_finalize; - JSB_CCPhysicsDebugNode_class->flags = 0; - - static JSPropertySpec properties[] = { - {0, 0, 0, 0, 0} - }; - static JSFunctionSpec funcs[] = { - JS_FN("_setSpace", JSB_CCPhysicsDebugNode_setSpace_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("getSpace", JSB_CCPhysicsDebugNode_space, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - static JSFunctionSpec st_funcs[] = { - JS_FN("_create", JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - - TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - - JSB_CCPhysicsDebugNode_object = JS_InitClass(cx, globalObj, typeClass->proto, JSB_CCPhysicsDebugNode_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); - - TypeTest t; - js_type_class_t *p; - typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { - p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; - p->jsclass = JSB_CCPhysicsDebugNode_class; - p->proto = JSB_CCPhysicsDebugNode_object; - p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); - } -} - -// Arguments: NSString*, CGRect -// Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32_t argc, jsval *vp) { - - jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; - if (argc == 2) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - cocos2d::Rect arg1; - ok &= jsval_to_ccrect(cx, argv[1], &arg1); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - PhysicsSprite* ret = PhysicsSprite::create(arg0, arg1); - - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - if (argc == 1) { - const char* arg0; - std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - PhysicsSprite* ret = PhysicsSprite::create(arg0); - - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - return JS_FALSE; - -} - -// Arguments: SpriteFrame* -// Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint32_t argc, jsval *vp) { - jsval *argv = JS_ARGV(cx, vp); - cocos2d::SpriteFrame* arg0; - if (argc >= 1) { - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]); - proxy = jsb_get_js_proxy(tmpObj); - arg0 = (cocos2d::SpriteFrame*)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg0) - } while (0); - } - PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrame(arg0); - - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; -} - -// Arguments: NSString* -// Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, uint32_t argc, jsval *vp) { - jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; - const char* arg0; - std::string arg0_tmp; - if (argc >= 1) { - ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - } - PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); - - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; -} - -void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) -{ - JSPROXY_CCPhysicsSprite_class = (JSClass *)calloc(1, sizeof(JSClass)); - JSPROXY_CCPhysicsSprite_class->name = "PhysicsSprite"; - JSPROXY_CCPhysicsSprite_class->addProperty = JS_PropertyStub; - JSPROXY_CCPhysicsSprite_class->delProperty = JS_DeletePropertyStub; - JSPROXY_CCPhysicsSprite_class->getProperty = JS_PropertyStub; - JSPROXY_CCPhysicsSprite_class->setProperty = JS_StrictPropertyStub; - JSPROXY_CCPhysicsSprite_class->enumerate = JS_EnumerateStub; - JSPROXY_CCPhysicsSprite_class->resolve = JS_ResolveStub; - JSPROXY_CCPhysicsSprite_class->convert = JS_ConvertStub; - JSPROXY_CCPhysicsSprite_class->finalize = JSPROXY_CCPhysicsSprite_finalize; - JSPROXY_CCPhysicsSprite_class->flags = 0; - - static JSPropertySpec properties[] = { - {0, 0, 0, 0, 0} - }; - static JSFunctionSpec funcs[] = { - JS_FN("getCPBody", JSPROXY_CCPhysicsSprite_getCPBody, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("getIgnoreBodyRotation", JSPROXY_CCPhysicsSprite_ignoreBodyRotation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("_setCPBody", JSPROXY_CCPhysicsSprite_setCPBody_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("setIgnoreBodyRotation", JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - static JSFunctionSpec st_funcs[] = { - JS_FN("create", JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("createWithSpriteFrame", JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("createWithSpriteFrameName", JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - - TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - - JSPROXY_CCPhysicsSprite_object = JS_InitClass(cx, globalObj, typeClass->proto, JSPROXY_CCPhysicsSprite_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); - - TypeTest t; - js_type_class_t *p; - typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { - p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; - p->jsclass = JSPROXY_CCPhysicsSprite_class; - p->proto = JSPROXY_CCPhysicsSprite_object; - p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); - } -} - - -void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { - jsval nsval; - JSObject *ns; - JS_GetProperty(cx, obj, "cc", &nsval); - if (nsval == JSVAL_VOID) { - ns = JS_NewObject(cx, NULL, NULL, NULL); - nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); - } else { - JS_ValueToObject(cx, nsval, &ns); - } - obj = ns; - JSPROXY_CCPhysicsSprite_createClass(cx, obj); -} - -void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj) { - jsval nsval; - JSObject *ns; - JS_GetProperty(cx, obj, "cc", &nsval); - if (nsval == JSVAL_VOID) { - ns = JS_NewObject(cx, NULL, NULL, NULL); - nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); - } else { - JS_ValueToObject(cx, nsval, &ns); - } - obj = ns; - JSB_CCPhysicsDebugNode_createClass(cx, obj, "PhysicsDebugNode"); -} - -JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) -{ - JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); - JSB_PRECONDITION( ok, "Error converting value to object"); - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - jsval vall, valb, valr, valt; - ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "l", &vall); - ok &= JS_GetProperty(cx, jsobj, "b", &valb); - ok &= JS_GetProperty(cx, jsobj, "r", &valr); - ok &= JS_GetProperty(cx, jsobj, "t", &valt); - JSB_PRECONDITION( ok, "Error obtaining point properties"); - - double l, b, r, t; - ok &= JS_ValueToNumber(cx, vall, &l); - ok &= JS_ValueToNumber(cx, valb, &b); - ok &= JS_ValueToNumber(cx, valr, &r); - ok &= JS_ValueToNumber(cx, valt, &t); - JSB_PRECONDITION( ok, "Error converting value to numbers"); - - ret->l = l; - ret->b = b; - ret->r = r; - ret->t = t; - - return JS_TRUE; -} - -jsval cpBB_to_jsval(JSContext *cx, cpBB bb ) -{ - JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - if (!object) - return JSVAL_VOID; - - if (!JS_DefineProperty(cx, object, "l", DOUBLE_TO_JSVAL(bb.l), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "b", DOUBLE_TO_JSVAL(bb.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "r", DOUBLE_TO_JSVAL(bb.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "t", DOUBLE_TO_JSVAL(bb.t), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JSVAL_VOID; - - return OBJECT_TO_JSVAL(object); -} - -// In order to be compatible with Chipmunk-JS API, -// this function expect to receive an array of numbers, and not an array of vects -// OK: [1,2, 3,4, 5,6] <- expected -// BAD: [{x:1, y:2}, {x:3,y:4}, {x:5, y:6}] <- not expected -JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts) -{ - // Parsing sequence - JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); - JSB_PRECONDITION( ok, "Error converting value to object"); - - JSB_PRECONDITION( jsobj && JS_IsArrayObject( cx, jsobj), "Object must be an array"); - - uint32_t len; - JS_GetArrayLength(cx, jsobj, &len); - - JSB_PRECONDITION( len%2==0, "Array lenght should be even"); - - cpVect *array = (cpVect*)malloc( sizeof(cpVect) * len/2); - - for( uint32_t i=0; i< len;i++ ) { - jsval valarg; - JS_GetElement(cx, jsobj, i, &valarg); - - double value; - ok = JS_ValueToNumber(cx, valarg, &value); - JSB_PRECONDITION( ok, "Error converting value to nsobject"); - - if(i%2==0) - array[i/2].x = value; - else - array[i/2].y = value; - } - - *numVerts = len/2; - *verts = array; - - return JS_TRUE; -} - -#pragma mark - Collision Handler - -struct collision_handler { - cpCollisionType typeA; - cpCollisionType typeB; - - JSObject *begin; - JSObject *pre; - JSObject *post; - JSObject *separate; - JSObject *jsthis; - JSContext *cx; - - // "owner" of the collision handler - // Needed when the space goes out of scope, it will remove all the allocated collision handlers for him. - cpSpace *space; - - unsigned long hash_key; - - unsigned int is_oo; // Objected oriented API ? - UT_hash_handle hh; -}; - -// hash -struct collision_handler* collision_handler_hash = NULL; - -// helper pair -static unsigned long pair_ints( unsigned long A, unsigned long B ) -{ - // order is not important - unsigned long k1 = MIN(A, B ); - unsigned long k2 = MAX(A, B ); - - return (k1 + k2) * (k1 + k2 + 1) /2 + k2; -} - -static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) -{ - struct collision_handler *handler = (struct collision_handler*) data; - - jsval args[2]; - if( handler->is_oo ) { - args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); - args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); - } else { - args[0] = opaque_to_jsval( handler->cx, arb); - args[1] = opaque_to_jsval( handler->cx, space ); - } - - jsval rval; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); - JSB_PRECONDITION2(ok, handler->cx, cpFalse, "Error calling collision callback: begin"); - - if( JSVAL_IS_BOOLEAN(rval) ) { - JSBool ret = JSVAL_TO_BOOLEAN(rval); - return (cpBool)ret; - } - return cpTrue; -} - -static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) -{ - struct collision_handler *handler = (struct collision_handler*) data; - - jsval args[2]; - if( handler->is_oo ) { - args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); - args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); - } else { - args[0] = opaque_to_jsval( handler->cx, arb); - args[1] = opaque_to_jsval( handler->cx, space ); - } - - jsval rval; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); - JSB_PRECONDITION2(ok, handler->cx, JS_FALSE, "Error calling collision callback: pre"); - - if( JSVAL_IS_BOOLEAN(rval) ) { - JSBool ret = JSVAL_TO_BOOLEAN(rval); - return (cpBool)ret; - } - return cpTrue; -} - -static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) -{ - struct collision_handler *handler = (struct collision_handler*) data; - - jsval args[2]; - - if( handler->is_oo ) { - args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); - args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); - } else { - args[0] = opaque_to_jsval( handler->cx, arb); - args[1] = opaque_to_jsval( handler->cx, space ); - } - - jsval ignore; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); - JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Post"); -} - -static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) -{ - struct collision_handler *handler = (struct collision_handler*) data; - - jsval args[2]; - if( handler->is_oo ) { - args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); - args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); - } else { - args[0] = opaque_to_jsval( handler->cx, arb); - args[1] = opaque_to_jsval( handler->cx, space ); - } - - jsval ignore; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); - JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Separate");} - -#pragma mark - cpSpace - -#pragma mark constructor / destructor - -void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *jsthis) -{ - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - if( proxy ) { - CCLOGINFO("jsbindings: finalizing JS object %p (cpSpace), handle: %p", jsthis, proxy->handle); - - // space - cpSpace *space = (cpSpace*) proxy->handle; - - - // Remove collision handlers, since the user might have forgotten to manually remove them - struct collision_handler *current, *tmp; - HASH_ITER(hh, collision_handler_hash, current, tmp) { - if( current->space == space ) { - - JSContext *cx = current->cx; - - // unroot it - if( current->begin ) { - JS_RemoveObjectRoot(cx, ¤t->begin); - } - if( current->pre ) - JS_RemoveObjectRoot(cx, ¤t->pre); - if( current->post ) - JS_RemoveObjectRoot(cx, ¤t->post); - if( current->separate ) - JS_RemoveObjectRoot(cx, ¤t->separate); - - HASH_DEL(collision_handler_hash,current); /* delete; users advances to next */ - free(current); /* optional- if you want to free */ - } - } - - // Free Space Children - freeSpaceChildren(space); - - jsb_del_jsobject_for_proxy(space); - if(proxy->flags == JSB_C_FLAG_CALL_FREE) - cpSpaceFree(space); - jsb_del_c_proxy_for_jsobject(jsthis); - } -} - - -#pragma mark addCollisionHandler - -static -JSBool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space, unsigned int is_oo) -{ - struct collision_handler *handler = (struct collision_handler*) malloc( sizeof(*handler) ); - - JSB_PRECONDITION(handler, "Error allocating memory"); - - JSBool ok = JS_TRUE; - - // args - ok &= jsval_to_int(cx, *argvp++, (int32_t*) &handler->typeA ); - ok &= jsval_to_int(cx, *argvp++, (int32_t*) &handler->typeB ); - - // this is no longer passed, so "this" is going to be "this". -// ok &= JS_ValueToObject(cx, *argvp++, &handler->jsthis ); - handler->jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - - handler->begin = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; - argvp++; - handler->pre = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; - argvp++; - handler->post = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; - argvp++; - handler->separate = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; - argvp++; - - JSB_PRECONDITION(ok, "Error parsing arguments"); - - // Object Oriented API ? - handler->is_oo = is_oo; - - // owner of the collision handler - handler->space = space; - - // Root it - if( handler->begin ) - JS_AddNamedObjectRoot(cx, &handler->begin, "begin collision_handler"); - if( handler->pre ) - JS_AddNamedObjectRoot(cx, &handler->pre, "pre collision_handler"); - if( handler->post ) - JS_AddNamedObjectRoot(cx, &handler->post, "post collision_handler"); - if( handler->separate ) - JS_AddNamedObjectRoot(cx, &handler->separate, "separate collision_handler"); - - handler->cx = cx; - - cpSpaceAddCollisionHandler(space, handler->typeA, handler->typeB, - !handler->begin ? NULL : &myCollisionBegin, - !handler->pre ? NULL : &myCollisionPre, - !handler->post ? NULL : &myCollisionPost, - !handler->separate ? NULL : &myCollisionSeparate, - handler ); - - - // - // Already added ? If so, remove it. - // Then add new entry - // - struct collision_handler *hashElement = NULL; - unsigned long paired_key = pair_ints(handler->typeA, handler->typeB ); - HASH_FIND_INT(collision_handler_hash, &paired_key, hashElement); - if( hashElement ) { - HASH_DEL( collision_handler_hash, hashElement ); - free( hashElement ); - } - - handler->hash_key = paired_key; - HASH_ADD_INT( collision_handler_hash, hash_key, handler ); - - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==7, cx, JS_FALSE, "Invalid number of arguments"); - - - jsval *argvp = JS_ARGV(cx,vp); - - // args - cpSpace *space; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); - JSB_PRECONDITION(ok, "Error parsing arguments"); - - return __jsb_cpSpace_addCollisionHandler(cx, vp, argvp, space, 0); -} - -// method -JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==6, cx, JS_FALSE, "Invalid number of arguments"); - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - return __jsb_cpSpace_addCollisionHandler(cx, vp, JS_ARGV(cx,vp), (cpSpace*)handle, 1); -} - -#pragma mark removeCollisionHandler - -static -JSBool __jsb_cpSpace_removeCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space) -{ - JSBool ok = JS_TRUE; - - cpCollisionType typeA; - cpCollisionType typeB; - ok &= jsval_to_int(cx, *argvp++, (int32_t*) &typeA ); - ok &= jsval_to_int(cx, *argvp++, (int32_t*) &typeB ); - - JSB_PRECONDITION(ok, "Error parsing arguments"); - - cpSpaceRemoveCollisionHandler(space, typeA, typeB ); - - // Remove it - struct collision_handler *hashElement = NULL; - unsigned long key = pair_ints(typeA, typeB ); - HASH_FIND_INT(collision_handler_hash, &key, hashElement); - if( hashElement ) { - - // unroot it - if( hashElement->begin ) - JS_RemoveObjectRoot(cx, &hashElement->begin); - if( hashElement->pre ) - JS_RemoveObjectRoot(cx, &hashElement->pre); - if( hashElement->post ) - JS_RemoveObjectRoot(cx, &hashElement->post); - if( hashElement->separate ) - JS_RemoveObjectRoot(cx, &hashElement->separate); - - HASH_DEL( collision_handler_hash, hashElement ); - free( hashElement ); - } - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Free function -JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - - cpSpace* space; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); - - JSB_PRECONDITION(ok, "Error parsing arguments"); - - return __jsb_cpSpace_removeCollisionHandler(cx, vp, argvp, space); -} - -// method -JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - return __jsb_cpSpace_removeCollisionHandler(cx, vp, JS_ARGV(cx,vp), (cpSpace*)handle); -} - -#pragma mark Add functios. Root JSObjects - -// Arguments: cpBody* -// Ret value: cpBody* -JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpBody* arg1; - - jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceAddBody((cpSpace*)arg0 , (cpBody*)arg1 ); - - // Root it: - JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpBody"); - - // addBody returns the same object that was added, so return it without conversions - JS_SET_RVAL(cx, vp, retval); - - return JS_TRUE; -} - -// Arguments: cpConstraint* -// Ret value: cpConstraint* -JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpConstraint* arg1; - - jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceAddConstraint((cpSpace*)arg0 , (cpConstraint*)arg1 ); - - // Root it: - JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpConstraint"); - - // addConstraint returns the same object that was added, so return it without conversions - JS_SET_RVAL(cx, vp, retval); - - return JS_TRUE; -} - -// Arguments: cpShape* -// Ret value: cpShape* -JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpShape* arg1; - - jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceAddShape((cpSpace*)arg0 , (cpShape*)arg1 ); - - // Root it: - JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpShape"); - - // addShape returns the same object that was added, so return it without conversions - JS_SET_RVAL(cx, vp, retval); - - return JS_TRUE; -} - -// Arguments: cpShape* -// Ret value: cpShape* -JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpShape* arg1; - - jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceAddStaticShape((cpSpace*)arg0 , (cpShape*)arg1 ); - - // Root it: - JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpShape (static)"); - - // addStaticShape returns the same object that was added, so return it without conversions - JS_SET_RVAL(cx, vp, retval); - - return JS_TRUE; -} - -#pragma mark Remove functios. Untoot JSObjects - -// Arguments: cpBody* -// Ret value: void -JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpBody* arg1; - - struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceRemoveBody((cpSpace*)arg0 , (cpBody*)arg1 ); - JS_RemoveObjectRoot(cx, &retproxy->jsobj); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: cpConstraint* -// Ret value: void -JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpConstraint* arg1; - - struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceRemoveConstraint((cpSpace*)arg0 , (cpConstraint*)arg1 ); - JS_RemoveObjectRoot(cx, &retproxy->jsobj); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: cpShape* -// Ret value: void -JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpShape* arg1; - - struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceRemoveShape((cpSpace*)arg0 , (cpShape*)arg1 ); - JS_RemoveObjectRoot(cx, &retproxy->jsobj); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: cpShape* -// Ret value: void -JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); - cpSpace* arg0 = (cpSpace*) proxy->handle; - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpShape* arg1; - - struct jsb_c_proxy_s *retproxy; - ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpSpaceRemoveStaticShape((cpSpace*)arg0 , (cpShape*)arg1 ); - JS_RemoveObjectRoot(cx, &retproxy->jsobj); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} -#pragma mark - Arbiter - -#pragma mark getBodies -static -JSBool __jsb_cpArbiter_getBodies(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) -{ - cpBody *bodyA; - cpBody *bodyB; - cpArbiterGetBodies(arbiter, &bodyA, &bodyB); - - jsval valA, valB; - if( is_oo ) { - valA = c_class_to_jsval(cx, bodyA, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); - valB = c_class_to_jsval(cx, bodyB, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); - } else { - valA = opaque_to_jsval(cx, bodyA); - valB = opaque_to_jsval(cx, bodyB); - } - - JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); - JS_SetElement(cx, jsobj, 0, &valA); - JS_SetElement(cx, jsobj, 1, &valB); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - - return JS_TRUE; -} - -// Free function -JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - - cpArbiter* arbiter; - if( ! jsval_to_opaque( cx, *argvp++, (void**)&arbiter ) ) - return JS_FALSE; - - return __jsb_cpArbiter_getBodies(cx, vp, argvp, arbiter, 0); -} - -// Method -JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); - - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - JSB_PRECONDITION( proxy, "Invalid private object"); - void *handle = proxy->handle; - - return __jsb_cpArbiter_getBodies(cx, vp, JS_ARGV(cx,vp), (cpArbiter*)handle, 1); -} - -#pragma mark getShapes -static -JSBool __jsb_cpArbiter_getShapes(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) -{ - cpShape *shapeA; - cpShape *shapeB; - cpArbiterGetShapes(arbiter, &shapeA, &shapeB); - - jsval valA, valB; - if( is_oo ) { - valA = c_class_to_jsval(cx, shapeA, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); - valB = c_class_to_jsval(cx, shapeB, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); - } else { - valA = opaque_to_jsval(cx, shapeA); - valB = opaque_to_jsval(cx, shapeB); - } - - JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); - JS_SetElement(cx, jsobj, 0, &valA); - JS_SetElement(cx, jsobj, 1, &valB); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - - return JS_TRUE; -} - -// function -JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - - cpArbiter* arbiter; - if( ! jsval_to_opaque( cx, *argvp++, (void**) &arbiter ) ) - return JS_FALSE; - - return __jsb_cpArbiter_getShapes(cx, vp, argvp, arbiter, 0); -} - -// method -JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - return __jsb_cpArbiter_getShapes(cx, vp, JS_ARGV(cx,vp), (cpArbiter*)handle, 1); -} - -#pragma mark - Body - -#pragma mark constructor - -// Manually added to identify static vs dynamic bodies -JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); - JSObject *jsobj = JS_NewObject(cx, JSB_cpBody_class, JSB_cpBody_object, NULL); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - double m; double i; - - ok &= JS_ValueToNumber( cx, *argvp++, &m ); - ok &= JS_ValueToNumber( cx, *argvp++, &i ); - JSB_PRECONDITION(ok, "Error processing arguments"); - - cpBody *ret_body = NULL; - if( m == INFINITY && i == INFINITY) { - ret_body = cpBodyNewStatic(); - - // XXX: Hack. IT WILL LEAK "rogue" objects., But at least it prevents a crash. - // The thing is that "rogue" bodies needs to be freed after the its shape, and I am not sure - // how to do it in a "js" way. - jsb_set_c_proxy_for_jsobject(jsobj, ret_body, JSB_C_FLAG_DO_NOT_CALL_FREE); - } else { - ret_body = cpBodyNew((cpFloat)m , (cpFloat)i ); - jsb_set_c_proxy_for_jsobject(jsobj, ret_body, JSB_C_FLAG_CALL_FREE); - } - - jsb_set_jsobject_for_proxy(jsobj, ret_body); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; -} - -#pragma mark getUserData - -static -JSBool __jsb_cpBody_getUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) -{ - JSObject *data = (JSObject*) cpBodyGetUserData(body); - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(data)); - - return JS_TRUE; -} - -// free function -JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - cpBody *body; - if( ! jsval_to_opaque( cx, *argvp++, (void**) &body ) ) - return JS_FALSE; - - return __jsb_cpBody_getUserData(cx, vp, argvp, body); -} - -// method -JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - return __jsb_cpBody_getUserData(cx, vp, JS_ARGV(cx,vp), (cpBody*)handle); -} - - -#pragma mark setUserData - -static -JSBool __jsb_cpBody_setUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) -{ - JSObject *jsobj; - - JSBool ok = JS_ValueToObject(cx, *argvp++, &jsobj); - - JSB_PRECONDITION(ok, "Error parsing arguments"); - - cpBodySetUserData(body, jsobj); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - - return JS_TRUE; -} - -// free function -JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - cpBody *body; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**) &body ); - JSB_PRECONDITION(ok, "Error parsing arguments"); - return __jsb_cpBody_setUserData(cx, vp, argvp, body); -} - -// method -JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - return __jsb_cpBody_setUserData(cx, vp, JS_ARGV(cx,vp), (cpBody*)handle); -} - -#pragma mark - Poly related - -// cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts); -JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpVect *verts; - int numVerts; - - ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing array"); - - cpFloat area = cpAreaForPoly(numVerts, verts); - - free(verts); - - JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(area)); - return JS_TRUE; -} - -// cpFloat cpMomentForPoly(cpFloat m, int numVerts, const cpVect *verts, cpVect offset); -JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpVect *verts; cpVect offset; - int numVerts; - double m; - - ok &= JS_ValueToNumber(cx, *argvp++, &m); - ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - ok &= jsval_to_cpVect( cx, *argvp++, (cpVect*) &offset ); - - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); - - cpFloat moment = cpMomentForPoly((cpFloat)m, numVerts, verts, offset); - - free(verts); - - JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(moment)); - return JS_TRUE; -} - -// cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts); -JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpVect *verts; - int numVerts; - - ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); - - cpVect centroid = cpCentroidForPoly(numVerts, verts); - - free(verts); - - JS_SET_RVAL(cx, vp, cpVect_to_jsval(cx, (cpVect)centroid)); - return JS_TRUE; -} - -// void cpRecenterPoly(const int numVerts, cpVect *verts); -JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp) -{ - CCASSERT(false, "NOT IMPLEMENTED"); - return JS_FALSE; -} - -#pragma mark - Object Oriented Chipmunk - -/* - * Chipmunk Base Object - */ - -JSClass* JSB_cpBase_class = NULL; -JSObject* JSB_cpBase_object = NULL; -// Constructor -JSBool JSB_cpBase_constructor(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2( argc==1, cx, JS_FALSE, "Invalid arguments. Expecting 1"); - - JSObject *jsobj = JS_NewObject(cx, JSB_cpBase_class, JSB_cpBase_object, NULL); - - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - - void *handle = NULL; - - ok = jsval_to_opaque(cx, *argvp++, &handle); - - JSB_PRECONDITION(ok, "Error converting arguments for JSB_cpBase_constructor"); - - jsb_set_c_proxy_for_jsobject(jsobj, handle, JSB_C_FLAG_DO_NOT_CALL_FREE); - jsb_set_jsobject_for_proxy(jsobj, handle); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; -} - -// Destructor -void JSB_cpBase_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("jsbindings: finalizing JS object %p (cpBase)", obj); - - // should not delete the handle since it was manually added -} - -JSBool JSB_cpBase_getHandle(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); - - struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); - void *handle = proxy->handle; - - jsval ret_val = opaque_to_jsval(cx, handle); - JS_SET_RVAL(cx, vp, ret_val); - return JS_TRUE; -} - -JSBool JSB_cpBase_setHandle(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); - JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); - - jsval *argvp = JS_ARGV(cx,vp); - - void *handle; - JSBool ok = jsval_to_opaque(cx, *argvp++, &handle); - JSB_PRECONDITION( ok, "Invalid parsing arguments"); - - jsb_set_c_proxy_for_jsobject(jsthis, handle, JSB_C_FLAG_DO_NOT_CALL_FREE); - jsb_set_jsobject_for_proxy(jsthis, handle); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - - -void JSB_cpBase_createClass(JSContext *cx, JSObject* globalObj, const char* name ) -{ - JSB_cpBase_class = (JSClass *)calloc(1, sizeof(JSClass)); - JSB_cpBase_class->name = name; - JSB_cpBase_class->addProperty = JS_PropertyStub; - JSB_cpBase_class->delProperty = JS_DeletePropertyStub; - JSB_cpBase_class->getProperty = JS_PropertyStub; - JSB_cpBase_class->setProperty = JS_StrictPropertyStub; - JSB_cpBase_class->enumerate = JS_EnumerateStub; - JSB_cpBase_class->resolve = JS_ResolveStub; - JSB_cpBase_class->convert = JS_ConvertStub; - JSB_cpBase_class->finalize = JSB_cpBase_finalize; - JSB_cpBase_class->flags = JSCLASS_HAS_PRIVATE; - - static JSPropertySpec properties[] = { - {0, 0, 0, 0, 0} - }; - static JSFunctionSpec funcs[] = { - JS_FN("getHandle", JSB_cpBase_getHandle, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("setHandle", JSB_cpBase_setHandle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - static JSFunctionSpec st_funcs[] = { - JS_FS_END - }; - - JSB_cpBase_object = JS_InitClass(cx, globalObj, NULL, JSB_cpBase_class, JSB_cpBase_constructor,0,properties,funcs,NULL,st_funcs); - JSBool found; - JS_SetPropertyAttributes(cx, globalObj, name, JSPROP_ENUMERATE | JSPROP_READONLY, &found); -} - -// Manual "methods" -// Constructor -JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); - JSObject *jsobj = JS_NewObject(cx, JSB_cpPolyShape_class, JSB_cpPolyShape_object, NULL); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - cpBody* body; cpVect *verts; cpVect offset; - int numVerts; - - ok &= jsval_to_c_class( cx, *argvp++, (void**)&body, NULL ); - ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - ok &= jsval_to_cpVect( cx, *argvp++, (cpVect*) &offset ); - JSB_PRECONDITION(ok, "Error processing arguments"); - cpShape *shape = cpPolyShapeNew(body, numVerts, verts, offset); - - jsb_set_c_proxy_for_jsobject(jsobj, shape, JSB_C_FLAG_DO_NOT_CALL_FREE); - jsb_set_jsobject_for_proxy(jsobj, shape); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - - free(verts); - - return JS_TRUE; -} - - -#pragma mark Space Free functions -// -// When the space is removed, it should all remove its children. But not "free" them. -// "free" will be performed by the JS Garbage Collector -// -// Functions copied & pasted from ChipmunkDemo.c -// https://github.com/slembcke/Chipmunk-Physics/blob/master/Demo/ChipmunkDemo.c#L89 -// - -static void unroot_jsobject_from_handle(void *handle) -{ - JSObject *jsobj = jsb_get_jsobject_for_proxy(handle); - struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsobj); - - // HACK context from global - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &proxy->jsobj); - -} -static void shapeFreeWrap(cpSpace *space, cpShape *shape, void *unused){ - cpSpaceRemoveShape(space, shape); - unroot_jsobject_from_handle(shape); -// cpShapeFree(shape); -} - -static void postShapeFree(cpShape *shape, cpSpace *space){ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)shapeFreeWrap, shape, NULL); -} - -static void constraintFreeWrap(cpSpace *space, cpConstraint *constraint, void *unused){ - cpSpaceRemoveConstraint(space, constraint); - unroot_jsobject_from_handle(constraint); -// cpConstraintFree(constraint); -} - -static void postConstraintFree(cpConstraint *constraint, cpSpace *space){ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)constraintFreeWrap, constraint, NULL); -} - -static void bodyFreeWrap(cpSpace *space, cpBody *body, void *unused){ - cpSpaceRemoveBody(space, body); - unroot_jsobject_from_handle(body); -// cpBodyFree(body); -} - -static void postBodyFree(cpBody *body, cpSpace *space){ - cpSpaceAddPostStepCallback(space, (cpPostStepFunc)bodyFreeWrap, body, NULL); -} - -// Safe and future proof way to remove and free all objects that have been added to the space. -void static freeSpaceChildren(cpSpace *space) -{ - // Must remove these BEFORE freeing the body or you will access dangling pointers. - cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)postShapeFree, space); - cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)postConstraintFree, space); - - cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)postBodyFree, space); -} - -#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.h deleted file mode 100644 index c6b40ca757..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_manual.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 __js_bindings_chipmunk_manual -#define __js_bindings_chipmunk_manual - -#include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" -#include "js_manual_conversions.h" -#include "ScriptingCore.h" -#ifdef JSB_INCLUDE_CHIPMUNK - -#include "chipmunk.h" -#include "jsapi.h" - -#include "js_bindings_chipmunk_auto_classes.h" - -// Free Functions -JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); - -JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp); - -JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp); - -// poly related -JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp); - -// "Methods" from the OO API -JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); - -// manually wrapped for rooting/unrooting purposes -JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp); - - -JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp); - -JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp); - - -// convertions - -jsval cpBB_to_jsval(JSContext *cx, cpBB bb ); -JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ); -JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts); - -// requires cocos2d -#define cpVect_to_jsval CGPoint_to_jsval -#define jsval_to_cpVect jsval_to_CGPoint - - -// Object Oriented Chipmunk -void JSB_cpBase_createClass(JSContext* cx, JSObject* globalObj, const char * name ); -extern JSObject* JSB_cpBase_object; -extern JSClass* JSB_cpBase_class; -extern void register_CCPhysicsSprite(JSContext *cx, JSObject *obj); -extern void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj); - -// Manual constructor / destructors -JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp); -void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *obj); - -#endif // JSB_INCLUDE_CHIPMUNK - -#endif // __js_bindings_chipmunk_manual diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.cpp b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.cpp deleted file mode 100644 index a96434eace..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 JSB_INCLUDE_CHIPMUNK -#define JSB_INCLUDE_CHIPMUNK -#endif - -#include "js_bindings_config.h" -#include "ScriptingCore.h" - - -// chipmunk -#include "js_bindings_chipmunk_auto_classes.h" -#include "js_bindings_chipmunk_functions.h" -#include "js_bindings_chipmunk_manual.h" - - -void jsb_register_chipmunk(JSContext *_cx, JSObject *object) -{ - // - // Chipmunk - // - JSObject *chipmunk = JS_NewObject(_cx, NULL, NULL, NULL); - jsval chipmunkVal = OBJECT_TO_JSVAL(chipmunk); - JS_SetProperty(_cx, object, "cp", &chipmunkVal); - - JSB_cpBase_createClass(_cx, chipmunk, "Base"); // manual base class registration -#include "js_bindings_chipmunk_auto_classes_registration.h" -#include "js_bindings_chipmunk_functions_registration.h" - - // manual - JS_DefineFunction(_cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - - JS_DefineFunction(_cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - register_CCPhysicsSprite(_cx, object); - register_CCPhysicsDebugNode(_cx, object); -} - diff --git a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.h b/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.h deleted file mode 100644 index 90bc320b87..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_chipmunk_registration.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 __JSB_CHIPMUNK_REGISTRATION -#define __JSB_CHIPMUNK_REGISTRATION - -void jsb_register_chipmunk( JSContext *globalC, JSObject *globalO); - -#endif // __JSB_CHIPMUNK_REGISTRATION diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index 295184cbb8..fbb6e808fb 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -26,7 +26,7 @@ // cocos2d + chipmunk registration files -#include "js_bindings_chipmunk_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" //#pragma mark - Hash diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp b/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp deleted file mode 100644 index 7d1a819fc8..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_system_functions.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 -* Script version: v0.5 -*/ -#include "cocos2d.h" -#include "js_bindings_config.h" -//#ifdef JSB_INCLUDE_SYSTEM - -#include "local-storage/LocalStorage.h" - -#include "jsfriendapi.h" -#include "js_bindings_config.h" -#include "js_bindings_core.h" -#include "js_manual_conversions.h" -#include "js_bindings_system_functions.h" -#include "ScriptingCore.h" - -USING_NS_CC; - -// Arguments: char* -// Ret value: const char* -JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; - - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - const char* ret_val; - - ret_val = localStorageGetItem((char*)arg0 ); - - jsval ret_jsval = c_string_to_jsval(cx, ret_val ? ret_val : ""); - JS_SET_RVAL(cx, vp, ret_jsval ); - - return JS_TRUE; -} - -// Arguments: char* -// Ret value: void -JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; - - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - localStorageRemoveItem((char*)arg0 ); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - -// Arguments: char*, char* -// Ret value: void -JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; const char* arg1; - - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - - localStorageSetItem((char*)arg0 , (char*)arg1 ); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; -} - - -//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_functions.h b/cocos/scripting/javascript/bindings/js_bindings_system_functions.h deleted file mode 100644 index 26d4a97c99..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_system_functions.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 -* Script version: v0.5 -*/ -#include "js_bindings_config.h" -//#ifdef JSB_INCLUDE_SYSTEM - -//#include "LocalStorage.h" - -#ifdef __cplusplus -extern "C" { -#endif -JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp); - -#ifdef __cplusplus -} -#endif - - -//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_functions_registration.h b/cocos/scripting/javascript/bindings/js_bindings_system_functions_registration.h deleted file mode 100644 index 5bce81d241..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_system_functions_registration.h +++ /dev/null @@ -1,15 +0,0 @@ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 -* Script version: v0.5 -*/ -#include "js_bindings_config.h" -//#ifdef JSB_INCLUDE_SYSTEM - -//#include "LocalStorage.h" -JS_DefineFunction(_cx, system, "getItem", JSB_localStorageGetItem, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, system, "removeItem", JSB_localStorageRemoveItem, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, system, "setItem", JSB_localStorageSetItem, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - - -//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp b/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp deleted file mode 100644 index bf55e188f0..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_system_registration.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 "js_bindings_config.h" -#include "js_bindings_core.h" -#include "local-storage/LocalStorage.h" -#include "cocos2d.h" - -// system -#include "js_bindings_system_functions.h" - - -void jsb_register_system( JSContext *_cx, JSObject *object) -{ - // - // sys - // - JSObject *sys = JS_NewObject(_cx, NULL, NULL, NULL); - jsval systemVal = OBJECT_TO_JSVAL(sys); - JS_SetProperty(_cx, object, "sys", &systemVal); - - - // sys.localStorage - JSObject *ls = JS_NewObject(_cx, NULL, NULL, NULL); - jsval lsVal = OBJECT_TO_JSVAL(ls); - JS_SetProperty(_cx, sys, "localStorage", &lsVal); - - // sys.localStorage functions - JSObject *system = ls; -#include "js_bindings_system_functions_registration.h" - - - // Init DB with full path - //NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; - //NSString *fullpath = [path stringByAppendingPathComponent:@"jsb.sqlite"]; - std::string strFilePath = cocos2d::FileUtils::getInstance()->getWritablePath(); - strFilePath += "/jsb.sqlite"; - localStorageInit(strFilePath.c_str()); - -} - diff --git a/cocos/scripting/javascript/bindings/js_bindings_system_registration.h b/cocos/scripting/javascript/bindings/js_bindings_system_registration.h deleted file mode 100644 index 1afb1b1081..0000000000 --- a/cocos/scripting/javascript/bindings/js_bindings_system_registration.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * JS Bindings: https://github.com/zynga/jsbindings - * - * Copyright (c) 2012 Zynga Inc. - * - * 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 __JSB_SYSTEM_REGISTRATION -#define __JSB_SYSTEM_REGISTRATION - -void jsb_register_system( JSContext *globalC, JSObject *globalO); - -#endif // __JSB_CHIPMUNK_REGISTRATION diff --git a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp deleted file mode 100644 index 413f941bca..0000000000 --- a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ /dev/null @@ -1,1015 +0,0 @@ -// -// jsb_cocos2d_extension_manual.cpp -// -// Created by James Chen on 3/11/13. -// -// - -#include "jsb_cocos2dx_extension_manual.h" -#include "extensions/cocos-ext.h" -#include "ScriptingCore.h" -#include "cocos2d_specifics.hpp" -#include "cocostudio/CocoStudio.h" - -USING_NS_CC; -USING_NS_CC_EXT; - - -class JSB_ScrollViewDelegate -: public Object -, public ScrollViewDelegate -{ -public: - JSB_ScrollViewDelegate() - : _JSDelegate(NULL) - , _needUnroot(false) - {} - - virtual ~JSB_ScrollViewDelegate() - { - if (_needUnroot) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &_JSDelegate); - } - } - - virtual void scrollViewDidScroll(ScrollView* view) - { - js_proxy_t * p = jsb_get_native_proxy(view); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "scrollViewDidScroll", 1, &arg, NULL); - } - - virtual void scrollViewDidZoom(ScrollView* view) - { - js_proxy_t * p = jsb_get_native_proxy(view); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "scrollViewDidZoom", 1, &arg, NULL); - } - - void setJSDelegate(JSObject* pJSDelegate) - { - _JSDelegate = pJSDelegate; - - // Check whether the js delegate is a pure js object. - js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); - if (!p) - { - _needUnroot = true; - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); - } - } -private: - JSObject* _JSDelegate; - bool _needUnroot; -}; - -static JSBool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::ScrollView* cobj = (cocos2d::extension::ScrollView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 1) - { - // save the delegate - JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); - JSB_ScrollViewDelegate* nativeDelegate = new JSB_ScrollViewDelegate(); - nativeDelegate->setJSDelegate(jsDelegate); - - cobj->setUserObject(nativeDelegate); - cobj->setDelegate(nativeDelegate); - - nativeDelegate->release(); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; - } - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; -} - - -#define KEY_TABLEVIEW_DATA_SOURCE "TableViewDataSource" -#define KEY_TABLEVIEW_DELEGATE "TableViewDelegate" - -class JSB_TableViewDelegate -: public Object -, public TableViewDelegate -{ -public: - JSB_TableViewDelegate() - : _JSDelegate(NULL) - , _needUnroot(false) - {} - - virtual ~JSB_TableViewDelegate() - { - if (_needUnroot) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &_JSDelegate); - } - } - - virtual void scrollViewDidScroll(ScrollView* view) - { - callJSDelegate(view, "scrollViewDidScroll"); - } - - virtual void scrollViewDidZoom(ScrollView* view) - { - callJSDelegate(view, "scrollViewDidZoom"); - } - - virtual void tableCellTouched(TableView* table, TableViewCell* cell) - { - callJSDelegate(table, cell, "tableCellTouched"); - } - - virtual void tableCellHighlight(TableView* table, TableViewCell* cell) - { - callJSDelegate(table, cell, "tableCellHighlight"); - } - - virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) - { - callJSDelegate(table, cell, "tableCellUnhighlight"); - } - - virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) - { - callJSDelegate(table, cell, "tableCellWillRecycle"); - } - - void setJSDelegate(JSObject* pJSDelegate) - { - _JSDelegate = pJSDelegate; - - // Check whether the js delegate is a pure js object. - js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); - if (!p) - { - _needUnroot = true; - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); - } - } - - -private: - void callJSDelegate(ScrollView* view, std::string jsFunctionName) - { - js_proxy_t * p = jsb_get_native_proxy(view); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), jsFunctionName.c_str(), 1, &arg, NULL); - } - - void callJSDelegate(TableView* table, TableViewCell* cell, std::string jsFunctionName) - { - js_proxy_t * p = jsb_get_native_proxy(table); - if (!p) return; - - js_proxy_t * pCellProxy = jsb_get_native_proxy(cell); - if (!pCellProxy) return; - - jsval args[2]; - args[0] = OBJECT_TO_JSVAL(p->obj); - args[1] = OBJECT_TO_JSVAL(pCellProxy->obj); - - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), jsFunctionName.c_str(), 2, args, NULL); - } - - JSObject* _JSDelegate; - bool _needUnroot; -}; - -static JSBool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 1) - { - // save the delegate - JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); - JSB_TableViewDelegate* nativeDelegate = new JSB_TableViewDelegate(); - nativeDelegate->setJSDelegate(jsDelegate); - - Dictionary* userDict = static_cast(cobj->getUserObject()); - if (NULL == userDict) - { - userDict = new Dictionary(); - cobj->setUserObject(userDict); - userDict->release(); - } - - userDict->setObject(nativeDelegate, KEY_TABLEVIEW_DELEGATE); - - cobj->setDelegate(nativeDelegate); - - nativeDelegate->release(); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; - } - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; -} - -class JSB_TableViewDataSource -: public Object -, public TableViewDataSource -{ -public: - JSB_TableViewDataSource() - : _JSTableViewDataSource(NULL) - , _needUnroot(false) - {} - - virtual ~JSB_TableViewDataSource() - { - if (_needUnroot) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &_JSTableViewDataSource); - } - } - - virtual Size tableCellSizeForIndex(TableView *table, unsigned int idx) - { - jsval ret; - bool ok = callJSDelegate(table, idx, "tableCellSizeForIndex", ret); - if (!ok) - { - ok = callJSDelegate(table, "cellSizeForTable", ret); - } - if (ok) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - Size size; - JSBool isSucceed = jsval_to_ccsize(cx, ret, &size); - if (isSucceed) return size; - } - return Size::ZERO; - - } - - virtual TableViewCell* tableCellAtIndex(TableView *table, unsigned int idx) - { - jsval ret; - bool ok = callJSDelegate(table, idx, "tableCellAtIndex", ret); - if (ok) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - cocos2d::extension::TableViewCell* arg0; - do { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(ret); - proxy = jsb_get_js_proxy(tmpObj); - arg0 = (cocos2d::extension::TableViewCell*)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( arg0, cx, NULL, "Invalid Native Object"); - } while (0); - return arg0; - } - return NULL; - } - - virtual unsigned int numberOfCellsInTableView(TableView *table) - { - jsval ret; - bool ok = callJSDelegate(table, "numberOfCellsInTableView", ret); - if (ok) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - uint32_t count = 0; - JSBool isSucceed = jsval_to_uint32(cx, ret, &count); - if (isSucceed) return count; - } - return 0; - } - - - void setTableViewDataSource(JSObject* pJSSource) - { - _JSTableViewDataSource = pJSSource; - - // Check whether the js delegate is a pure js object. - js_proxy_t* p = jsb_get_js_proxy(_JSTableViewDataSource); - if (!p) - { - _needUnroot = true; - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_JSTableViewDataSource, "TableViewDataSource"); - } - } - -private: - bool callJSDelegate(TableView* table, std::string jsFunctionName, jsval& retVal) - { - js_proxy_t * p = jsb_get_native_proxy(table); - if (!p) return false; - - JSBool hasAction; - jsval temp_retval; - jsval dataVal = OBJECT_TO_JSVAL(p->obj); - - 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)) - { - return false; - } - if(temp_retval == JSVAL_VOID) - { - return false; - } - - JSAutoCompartment ac(cx, obj); - JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), - 1, &dataVal, &retVal); - return true; - } - return false; - } - - bool callJSDelegate(TableView* table, int idx, std::string jsFunctionName, jsval& retVal) - { - js_proxy_t * p = jsb_get_native_proxy(table); - if (!p) return false; - - - JSBool hasAction; - jsval temp_retval; - jsval dataVal[2]; - dataVal[0] = OBJECT_TO_JSVAL(p->obj); - dataVal[1] = INT_TO_JSVAL(idx); - - 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)) - { - return false; - } - - if(temp_retval == JSVAL_VOID) - { - return false; - } - - JSAutoCompartment ac(cx, obj); - JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), - 2, dataVal, &retVal); - return true; - } - return false; - } - -private: - JSObject* _JSTableViewDataSource; - bool _needUnroot; -}; - -static JSBool js_cocos2dx_CCTableView_setDataSource(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - if (argc == 1) - { - JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); - pNativeSource->setTableViewDataSource(JSVAL_TO_OBJECT(argv[0])); - - Dictionary* userDict = static_cast(cobj->getUserObject()); - if (NULL == userDict) - { - userDict = new Dictionary(); - cobj->setUserObject(userDict); - userDict->release(); - } - - userDict->setObject(pNativeSource, KEY_TABLEVIEW_DATA_SOURCE); - - cobj->setDataSource(pNativeSource); - - pNativeSource->release(); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; - } - - JS_ReportError(cx, "wrong number of arguments"); - return JS_FALSE; -} - -static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; - if (argc == 3 || argc == 2) - { - - JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); - pNativeSource->setTableViewDataSource(JSVAL_TO_OBJECT(argv[0])); - - cocos2d::Size arg1; - ok &= jsval_to_ccsize(cx, argv[1], &arg1); - cocos2d::extension::TableView* ret = NULL; - ret = new TableView(); - ret->autorelease(); - - ret->setDataSource(pNativeSource); - - jsval jsret; - do { - if (ret) - { - js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); - jsret = OBJECT_TO_JSVAL(proxy->obj); - } - else - { - jsret = JSVAL_NULL; - } - } while (0); - - if (argc == 2) - { - ret->initWithViewSize(arg1); - } - else - { - cocos2d::Node* arg2; - do - { - js_proxy_t *proxy; - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[2]); - proxy = jsb_get_js_proxy(tmpObj); - arg2 = (cocos2d::Node*)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( arg2, cx, JS_FALSE, "Invalid Native Object"); - } while (0); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - ret->initWithViewSize(arg1, arg2); - } - ret->reloadData(); - - Dictionary* userDict = new Dictionary(); - userDict->setObject(pNativeSource, KEY_TABLEVIEW_DATA_SOURCE); - ret->setUserObject(userDict); - userDict->release(); - - pNativeSource->release(); - - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; - } - - JS_ReportError(cx, "wrong number of arguments"); - return JS_FALSE; -} - -class JSB_EditBoxDelegate -: public Object -, public EditBoxDelegate -{ -public: - JSB_EditBoxDelegate() - : _JSDelegate(NULL) - , _needUnroot(false) - {} - - virtual ~JSB_EditBoxDelegate() - { - if (_needUnroot) - { - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &_JSDelegate); - } - } - - virtual void editBoxEditingDidBegin(EditBox* editBox) - { - js_proxy_t * p = jsb_get_native_proxy(editBox); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxEditingDidBegin", 1, &arg, NULL); - } - - virtual void editBoxEditingDidEnd(EditBox* editBox) - { - js_proxy_t * p = jsb_get_native_proxy(editBox); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxEditingDidEnd", 1, &arg, NULL); - } - - virtual void editBoxTextChanged(EditBox* editBox, const std::string& text) - { - js_proxy_t * p = jsb_get_native_proxy(editBox); - if (!p) return; - - jsval dataVal[2]; - dataVal[0] = OBJECT_TO_JSVAL(p->obj); - std::string arg1 = text; - dataVal[1] = std_string_to_jsval(ScriptingCore::getInstance()->getGlobalContext(), arg1); - - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxTextChanged", 2, dataVal, NULL); - } - - virtual void editBoxReturn(EditBox* editBox) - { - js_proxy_t * p = jsb_get_native_proxy(editBox); - if (!p) return; - - jsval arg = OBJECT_TO_JSVAL(p->obj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxReturn", 1, &arg, NULL); - } - - void setJSDelegate(JSObject* pJSDelegate) - { - _JSDelegate = pJSDelegate; - - // Check whether the js delegate is a pure js object. - js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); - if (!p) - { - _needUnroot = true; - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); - } - } -private: - JSObject* _JSDelegate; - bool _needUnroot; -}; - -static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::extension::EditBox* cobj = (cocos2d::extension::EditBox *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 1) - { - // save the delegate - JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); - JSB_EditBoxDelegate* nativeDelegate = new JSB_EditBoxDelegate(); - nativeDelegate->setJSDelegate(jsDelegate); - - cobj->setUserObject(nativeDelegate); - cobj->setDelegate(nativeDelegate); - - nativeDelegate->release(); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; - } - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; -} - - - -class JSB_ControlButtonTarget : public Object -{ -public: - JSB_ControlButtonTarget() - : _jsFunc(nullptr), - _type(Control::EventType::TOUCH_DOWN), - _jsTarget(nullptr), - _needUnroot(false) - {} - - 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) - { - log("Failed to get proxy for control button"); - return; - } - - jsval dataVal[2]; - dataVal[0] = OBJECT_TO_JSVAL(p->obj); - int arg1 = (int)event; - dataVal[1] = INT_TO_JSVAL(arg1); - jsval jsRet; - - ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc), 2, dataVal, &jsRet); - } - - void setJSTarget(JSObject* pJSTarget) - { - _jsTarget = pJSTarget; - - 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) - { - _jsFunc = jsFunc; - - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - 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; - 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 = 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* 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 - JSB_ControlButtonTarget* nativeDelegate = new JSB_ControlButtonTarget(); - - nativeDelegate->setJSTarget(jsDelegate); - nativeDelegate->setJSAction(jsFunc); - nativeDelegate->setEventType(arg2); - - Array* nativeDelegateArray = static_cast(cobj->getUserObject()); - if (nullptr == nativeDelegateArray) - { - nativeDelegateArray = new Array(); - nativeDelegateArray->init(); - 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; - } - 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 = 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]); - JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); - - 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); - return JS_FALSE; -} - -class JSArmatureWrapper: public JSCallbackWrapper { -public: - JSArmatureWrapper(); - virtual ~JSArmatureWrapper(); - - virtual void setJSCallbackThis(jsval thisObj); - - void movementCallbackFunc(cocostudio::Armature * pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId); - void frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); - void addArmatureFileInfoAsyncCallbackFunc(float percent); - -private: - bool m_bNeedUnroot; -}; - -JSArmatureWrapper::JSArmatureWrapper() - : m_bNeedUnroot(false) -{ - -} - -JSArmatureWrapper::~JSArmatureWrapper() -{ - if (m_bNeedUnroot) - { - JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_RemoveObjectRoot(cx, &thisObj); - } -} - -void JSArmatureWrapper::setJSCallbackThis(jsval _jsThisObj) -{ - JSCallbackWrapper::setJSCallbackThis(_jsThisObj); - - JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); - js_proxy *p = jsb_get_js_proxy(thisObj); - if (!p) - { - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddObjectRoot(cx, &thisObj); - m_bNeedUnroot = true; - } -} - -void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId) -{ - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); - js_proxy_t *proxy = js_get_or_create_proxy(cx, pArmature); - jsval retval; - if (_jsCallback != JSVAL_VOID) - { - int movementEventType = (int)pMovementEventType; - jsval movementVal = INT_TO_JSVAL(movementEventType); - - jsval idVal = c_string_to_jsval(cx, pMovementId); - - jsval valArr[3]; - valArr[0] = OBJECT_TO_JSVAL(proxy->obj); - valArr[1] = movementVal; - valArr[2] = idVal; - - JS_AddValueRoot(cx, valArr); - JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); - JS_RemoveValueRoot(cx, valArr); - } -} - -void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) -{ - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); - jsval retval; - if (_jsCallback != JSVAL_VOID) - { - jsval percentVal = DOUBLE_TO_JSVAL(percent); - - JS_AddValueRoot(cx, &percentVal); - JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); - JS_RemoveValueRoot(cx, &percentVal); - } -} - - -void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) -{ - JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); - js_proxy_t *proxy = js_get_or_create_proxy(cx, pBone); - jsval retval; - if (_jsCallback != JSVAL_VOID) - { - jsval nameVal = c_string_to_jsval(cx, frameEventName); - jsval originIndexVal = INT_TO_JSVAL(originFrameIndex); - jsval currentIndexVal = INT_TO_JSVAL(currentFrameIndex); - - jsval valArr[4]; - valArr[0] = OBJECT_TO_JSVAL(proxy->obj); - valArr[1] = nameVal; - valArr[2] = originIndexVal; - valArr[3] = currentIndexVal; - - JS_AddValueRoot(cx, valArr); - JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); - JS_RemoveValueRoot(cx, valArr); - } -} - -static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 2) { - jsval *argv = JS_ARGV(cx, vp); - - JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); - tmpObj->autorelease(); - - tmpObj->setJSCallbackFunc(argv[0]); - tmpObj->setJSCallbackThis(argv[1]); - - cobj->setMovementEventCallFunc(tmpObj, movementEvent_selector(JSArmatureWrapper::movementCallbackFunc)); - - return JS_TRUE; - } - JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; -} - -static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 2) { - jsval *argv = JS_ARGV(cx, vp); - - JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); - tmpObj->autorelease(); - - tmpObj->setJSCallbackFunc(argv[0]); - tmpObj->setJSCallbackThis(argv[1]); - - cobj->setFrameEventCallFunc(tmpObj, frameEvent_selector(JSArmatureWrapper::frameCallbackFunc)); - - return JS_TRUE; - } - JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; -} - -static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint32_t argc, jsval *vp) -{ - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (argc == 3) { - jsval *argv = JS_ARGV(cx, vp); - - JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); - tmpObj->autorelease(); - - tmpObj->setJSCallbackFunc(argv[2]); - tmpObj->setJSCallbackThis(argv[1]); - - std::string ret; - jsval_to_std_string(cx, argv[0], &ret); - - cobj->addArmatureFileInfoAsync(ret.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); - - return JS_TRUE; - } - - if(argc == 5){ - jsval *argv = JS_ARGV(cx, vp); - - JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); - tmpObj->autorelease(); - - tmpObj->setJSCallbackFunc(argv[4]); - tmpObj->setJSCallbackThis(argv[3]); - - std::string imagePath; - jsval_to_std_string(cx ,argv[0] , &imagePath); - - std::string plistPath; - jsval_to_std_string(cx ,argv[1] , &plistPath); - - std::string configFilePath; - jsval_to_std_string(cx ,argv[2] , &configFilePath); - - cobj->addArmatureFileInfoAsync(imagePath.c_str(), plistPath.c_str(), configFilePath.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); - - return JS_TRUE; - } - JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; -} - -extern JSObject* jsb_ScrollView_prototype; -extern JSObject* jsb_TableView_prototype; -extern JSObject* jsb_EditBox_prototype; -extern JSObject* jsb_ArmatureAnimation_prototype; -extern JSObject* jsb_ArmatureDataManager_prototype; -extern JSObject* jsb_Control_prototype; - -void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) -{ - JS_DefineFunction(cx, jsb_ScrollView_prototype, "setDelegate", js_cocos2dx_CCScrollView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_TableView_prototype, "setDelegate", js_cocos2dx_CCTableView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_TableView_prototype, "setDataSource", js_cocos2dx_CCTableView_setDataSource, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_EditBox_prototype, "setDelegate", js_cocos2dx_CCEditBox_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); - - JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setMovementEventCallFunc", js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); - - JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setFrameEventCallFunc", js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); - - JS_DefineFunction(cx, jsb_ArmatureDataManager_prototype, "addArmatureFileInfoAsync", jsb_Animation_addArmatureFileInfoAsyncCallFunc, 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); -} \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.h b/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.h deleted file mode 100644 index e8822b1370..0000000000 --- a/cocos/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// jsb_cocos2d_extension_manual.h -// -// Created by James Chen on 3/11/13. -// -// - -#ifndef __jsb_cocos2dx_extension_manual__ -#define __jsb_cocos2dx_extension_manual__ - -#include "jsapi.h" -#include "jsfriendapi.h" - -void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global); - -#endif /* defined(__jsb_cocos2dx_extension_manual__) */ diff --git a/cocos/scripting/javascript/bindings/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/jsb_websocket.cpp deleted file mode 100644 index b5083ad268..0000000000 --- a/cocos/scripting/javascript/bindings/jsb_websocket.cpp +++ /dev/null @@ -1,382 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org -Copyright (c) 2013 James Chen - -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 "jsb_websocket.h" -#include "cocos2d.h" -#include "network/WebSocket.h" -#include "spidermonkey_specifics.h" -#include "ScriptingCore.h" -#include "cocos2d_specifics.hpp" - -using namespace network; - -/* - [Constructor(in DOMString url, in optional DOMString protocols)] - [Constructor(in DOMString url, in optional DOMString[] protocols)] - interface WebSocket { - readonly attribute DOMString url; - - // ready state - const unsigned short CONNECTING = 0; - const unsigned short OPEN = 1; - const unsigned short CLOSING = 2; - const unsigned short CLOSED = 3; - readonly attribute unsigned short readyState; - readonly attribute unsigned long bufferedAmount; - - // networking - attribute Function onopen; - attribute Function onmessage; - attribute Function onerror; - attribute Function onclose; - readonly attribute DOMString protocol; - void send(in DOMString data); - void close(); - }; - WebSocket implements EventTarget; - */ - -class JSB_WebSocketDelegate : public WebSocket::Delegate -{ -public: - - virtual void onOpen(WebSocket* ws) - { - js_proxy_t * p = jsb_get_native_proxy(ws); - if (!p) return; - - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "open"); - JS_SetProperty(cx, jsobj, "type", &vp); - - jsval args = OBJECT_TO_JSVAL(jsobj); - - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onopen", 1, &args); - } - - virtual void onMessage(WebSocket* ws, const WebSocket::Data& data) - { - js_proxy_t * p = jsb_get_native_proxy(ws); - if (!p) return; - - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "message"); - JS_SetProperty(cx, jsobj, "type", &vp); - - jsval args = OBJECT_TO_JSVAL(jsobj); - - if (data.isBinary) - {// data is binary - JSObject* buffer = JS_NewArrayBuffer(cx, data.len); - uint8_t* bufdata = JS_GetArrayBufferData(buffer); - memcpy((void*)bufdata, (void*)data.bytes, data.len); - jsval dataVal = OBJECT_TO_JSVAL(buffer); - JS_SetProperty(cx, jsobj, "data", &dataVal); - } - else - {// data is string - jsval dataVal = c_string_to_jsval(cx, data.bytes); - JS_SetProperty(cx, jsobj, "data", &dataVal); - } - - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onmessage", 1, &args); - } - - virtual void onClose(WebSocket* ws) - { - js_proxy_t * p = jsb_get_native_proxy(ws); - if (!p) return; - - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "close"); - JS_SetProperty(cx, jsobj, "type", &vp); - - jsval args = OBJECT_TO_JSVAL(jsobj); - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onclose", 1, &args); - - js_proxy_t* jsproxy = jsb_get_js_proxy(p->obj); - JS_RemoveObjectRoot(cx, &jsproxy->obj); - jsb_remove_proxy(p, jsproxy); - CC_SAFE_DELETE(ws); - } - - virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error) - { - js_proxy_t * p = jsb_get_native_proxy(ws); - if (!p) return; - - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "error"); - JS_SetProperty(cx, jsobj, "type", &vp); - - jsval args = OBJECT_TO_JSVAL(jsobj); - - ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onerror", 1, &args); - } - - void setJSDelegate(JSObject* pJSDelegate) - { - _JSDelegate = pJSDelegate; - } -private: - JSObject* _JSDelegate; -}; - -JSClass *js_cocos2dx_websocket_class; -JSObject *js_cocos2dx_websocket_prototype; - -void js_cocos2dx_WebSocket_finalize(JSFreeOp *fop, JSObject *obj) { - CCLOG("jsbindings: finalizing JS object %p (WebSocket)", obj); -} - -JSBool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if(argc == 1){ - do - { - if (JSVAL_IS_STRING(argv[0])) - { - std::string data; - jsval_to_std_string(cx, argv[0], &data); - cobj->send(data); - break; - } - - if (argv[0].isObject()) - { - uint8_t *bufdata = NULL; - uint32_t len = 0; - - JSObject* jsobj = JSVAL_TO_OBJECT(argv[0]); - if (JS_IsArrayBufferObject(jsobj)) - { - bufdata = JS_GetArrayBufferData(jsobj); - len = JS_GetArrayBufferByteLength(jsobj); - } - else if (JS_IsArrayBufferViewObject(jsobj)) - { - bufdata = (uint8_t*)JS_GetArrayBufferViewData(jsobj); - len = JS_GetArrayBufferViewByteLength(jsobj); - } - - if (bufdata && len > 0) - { - cobj->send(bufdata, len); - break; - } - } - - JS_ReportError(cx, "data type to be sent is unsupported."); - - } while (0); - - JS_SET_RVAL(cx, vp, JSVAL_VOID); - - return JS_TRUE; - } - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_TRUE; -} - -JSBool js_cocos2dx_extension_WebSocket_close(JSContext *cx, uint32_t argc, jsval *vp){ - JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if(argc == 0){ - cobj->close(); - JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; - } - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; -} - -JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, jsval *vp) -{ - jsval *argv = JS_ARGV(cx, vp); - - if (argc == 1 || argc == 2) - { - - std::string url; - - do { - JSBool ok = jsval_to_std_string(cx, argv[0], &url); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); - } while (0); - - JSObject *obj = JS_NewObject(cx, js_cocos2dx_websocket_class, js_cocos2dx_websocket_prototype, NULL); - - - WebSocket* cobj = new WebSocket(); - JSB_WebSocketDelegate* delegate = new JSB_WebSocketDelegate(); - delegate->setJSDelegate(obj); - - if (argc == 2) - { - std::vector protocols; - - if (JSVAL_IS_STRING(argv[1])) - { - std::string protocol; - do { - JSBool ok = jsval_to_std_string(cx, argv[1], &protocol); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); - } while (0); - protocols.push_back(protocol); - } - else if (argv[1].isObject()) - { - JSBool ok = JS_TRUE; - JSObject* arg2 = JSVAL_TO_OBJECT(argv[1]); - JSB_PRECONDITION(JS_IsArrayObject( cx, arg2 ), "Object must be an array"); - - uint32_t len = 0; - JS_GetArrayLength(cx, arg2, &len); - - for( uint32_t i=0; i< len;i++ ) - { - jsval valarg; - JS_GetElement(cx, arg2, i, &valarg); - std::string protocol; - do { - ok = jsval_to_std_string(cx, valarg, &protocol); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); - } while (0); - - protocols.push_back(protocol); - } - } - cobj->init(*delegate, url, &protocols); - } - else - { - cobj->init(*delegate, url); - } - - - JS_DefineProperty(cx, obj, "URL", argv[0] - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - - //protocol not support yet (always return "") - JS_DefineProperty(cx, obj, "protocol", c_string_to_jsval(cx, "") - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - - // link the native object with the javascript object - js_proxy_t *p = jsb_new_proxy(cobj, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "WebSocket"); - - JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); - return JS_TRUE; - } - - JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; -} - -static JSBool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JSHandleObject obj, JSHandleId id, JSMutableHandleValue vp) -{ - JSObject* jsobj = obj.get(); - js_proxy_t *proxy = jsb_get_js_proxy(jsobj); - WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - - if (cobj) { - vp.set(INT_TO_JSVAL((int)cobj->getReadyState())); - return JS_TRUE; - } else { - JS_ReportError(cx, "Error: WebSocket instance is invalid."); - return JS_FALSE; - } -} - -void register_jsb_websocket(JSContext *cx, JSObject *global) { - - js_cocos2dx_websocket_class = (JSClass *)calloc(1, sizeof(JSClass)); - js_cocos2dx_websocket_class->name = "WebSocket"; - js_cocos2dx_websocket_class->addProperty = JS_PropertyStub; - js_cocos2dx_websocket_class->delProperty = JS_DeletePropertyStub; - js_cocos2dx_websocket_class->getProperty = JS_PropertyStub; - js_cocos2dx_websocket_class->setProperty = JS_StrictPropertyStub; - js_cocos2dx_websocket_class->enumerate = JS_EnumerateStub; - js_cocos2dx_websocket_class->resolve = JS_ResolveStub; - js_cocos2dx_websocket_class->convert = JS_ConvertStub; - js_cocos2dx_websocket_class->finalize = js_cocos2dx_WebSocket_finalize; - js_cocos2dx_websocket_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); - - static JSPropertySpec properties[] = { - {"readyState", 0, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_SHARED, JSOP_WRAPPER(js_cocos2dx_extension_WebSocket_get_readyState), NULL}, - {0, 0, 0, 0, 0} - }; - - static JSFunctionSpec funcs[] = { - JS_FN("send",js_cocos2dx_extension_WebSocket_send, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("close",js_cocos2dx_extension_WebSocket_close, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FS_END - }; - - static JSFunctionSpec st_funcs[] = { - JS_FS_END - }; - - js_cocos2dx_websocket_prototype = JS_InitClass( - cx, global, - NULL, - js_cocos2dx_websocket_class, - js_cocos2dx_extension_WebSocket_constructor, 0, // constructor - properties, - funcs, - NULL, // no static properties - st_funcs); - - JSObject* jsclassObj = JSVAL_TO_OBJECT(anonEvaluate(cx, global, "(function () { return WebSocket; })()")); - - JS_DefineProperty(cx, jsclassObj, "CONNECTING", INT_TO_JSVAL((int)WebSocket::State::CONNECTING) - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - JS_DefineProperty(cx, jsclassObj, "OPEN", INT_TO_JSVAL((int)WebSocket::State::OPEN) - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - JS_DefineProperty(cx, jsclassObj, "CLOSING", INT_TO_JSVAL((int)WebSocket::State::CLOSING) - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - JS_DefineProperty(cx, jsclassObj, "CLOSED", INT_TO_JSVAL((int)WebSocket::State::CLOSED) - , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); - - // make the class enumerable in the registered namespace - JSBool found; - JS_SetPropertyAttributes(cx, global, "WebSocket", JSPROP_ENUMERATE | JSPROP_READONLY, &found); -} - - diff --git a/cocos/scripting/javascript/bindings/jsb_websocket.h b/cocos/scripting/javascript/bindings/jsb_websocket.h deleted file mode 100644 index cde0f40b2e..0000000000 --- a/cocos/scripting/javascript/bindings/jsb_websocket.h +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org -Copyright (c) 2013 James Chen - -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 __jsb_websocket__ -#define __jsb_websocket__ - -#include "jsapi.h" -#include "jsfriendapi.h" - -void register_jsb_websocket(JSContext* cx, JSObject* global); - -#endif /* defined(__jsb_websocket__) */ diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj index df73497bd8..11085f336c 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj @@ -12,68 +12,41 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + {39379840-825A-45A0-B363-C09FFEF864BD} @@ -102,9 +75,11 @@ + + @@ -126,7 +101,7 @@ Level3 Disabled WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;$(ProjectDir)..;$(ProjectDir)..\..\spidermonkey-win32\include;$(ProjectDir)..\..\..\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\extensions\LocalStorage;$(ProjectDir)..\..\..\..\extensions\network;%(AdditionalIncludeDirectories) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true false @@ -137,7 +112,7 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" @@ -149,7 +124,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(O true true WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;$(ProjectDir)..;$(ProjectDir)..\..\spidermonkey-win32\include;$(ProjectDir)..\..\..\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\extensions\LocalStorage;$(ProjectDir)..\..\..\..\extensions\network;%(AdditionalIncludeDirectories) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true @@ -161,7 +136,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(O if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters index 4fdf5413d2..1d1e1d400a 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters @@ -20,21 +20,6 @@ manual - - manual - - - manual - - - manual - - - manual - - - manual - manual @@ -44,15 +29,6 @@ manual - - manual - - - manual - - - manual - manual @@ -65,18 +41,9 @@ manual - - manual - - - manual - generated - - generated - @@ -85,27 +52,6 @@ manual - - manual - - - manual - - - manual - - - manual - - - manual - - - manual - - - manual - manual @@ -121,18 +67,6 @@ manual - - manual - - - manual - - - manual - - - manual - manual @@ -145,55 +79,40 @@ manual - - manual - - - manual - manual generated - - generated - - - js - - - js - - - js - - - js - - - js - - - js - - - js - - - js - - - js - generated - - generated + + js + + + js + + + js + + + js + + + js + + + js + + + js + + + js \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj b/cocos/scripting/lua/bindings/liblua.vcxproj index 84026e44fd..ed1ef534ed 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj +++ b/cocos/scripting/lua/bindings/liblua.vcxproj @@ -35,9 +35,11 @@ + + @@ -62,7 +64,7 @@ Disabled - $(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\audio\include;$(ProjectDir)..\..\..\extensions;$(ProjectDir)..\..\..\extensions\network;$(ProjectDir)..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\tolua;$(ProjectDir)..\luajit\include;$(ProjectDir)..\..\auto-generated\lua-bindings;$(ProjectDir)..\cocos2dx_support;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(ProjectDir);$(ProjectDir)..\..\..;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot)extensions\network;$(EngineRoot)external;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\luajit\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;_DEBUG;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -87,14 +89,14 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\luajit\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$(OutDir)" MaxSpeed true - $(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\audio\include;$(ProjectDir)..\..\..\extensions;$(ProjectDir)..\..\..\extensions\network;$(ProjectDir)..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\tolua;$(ProjectDir)..\luajit\include;$(ProjectDir)..\..\auto-generated\lua-bindings;$(ProjectDir)..\cocos2dx_support;%(AdditionalIncludeDirectories) + $(ProjectDir);$(ProjectDir)..\..\..;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot)extensions\network;$(EngineRoot)external;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\luajit\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;LIBLUA_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -118,55 +120,55 @@ xcopy /Y /Q "$(ProjectDir)..\luajit\win32\*.*" "$(OutDir)" if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\luajit\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$(OutDir)" + + + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj.filters b/cocos/scripting/lua/bindings/liblua.vcxproj.filters index a65b18d1ac..56f49872c4 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj.filters +++ b/cocos/scripting/lua/bindings/liblua.vcxproj.filters @@ -18,135 +18,135 @@ - - tolua - - - tolua - - - tolua - - - tolua - - - tolua - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - cocos2dx_support\generated cocos2dx_support\generated - + + tolua + + + tolua + + + tolua + + + tolua + + + tolua + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + cocos2dx_support - - tolua - - - tolua - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - luajit\include - - - luajit\include - - - luajit\include - - - luajit\include - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - - - cocos2dx_support - cocos2dx_support\generated cocos2dx_support\generated - + + luajit\include + + + luajit\include + + + luajit\include + + + luajit\include + + + tolua + + + tolua + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + + cocos2dx_support + + cocos2dx_support diff --git a/extensions/proj.win32/libExtensions.vcxproj b/extensions/proj.win32/libExtensions.vcxproj index 25597c43e3..7a3615643f 100644 --- a/extensions/proj.win32/libExtensions.vcxproj +++ b/extensions/proj.win32/libExtensions.vcxproj @@ -35,9 +35,11 @@ + + @@ -62,7 +64,7 @@ Disabled - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\external\sqlite3\include;$(ProjectDir)..\..\external;$(ProjectDir)..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\cocos2dx;$(ProjectDir)..\..\cocos2dx\include;$(ProjectDir)..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\zlib;$(ProjectDir)..\..\audio\include;..\;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)external;$(EngineRoot)external\unzip;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\win32-specific\zlib\include;..\;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -79,7 +81,7 @@ MaxSpeed true - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(ProjectDir)..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\external\sqlite3\include;$(ProjectDir)..\..\external;$(ProjectDir)..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\cocos2dx;$(ProjectDir)..\..\cocos2dx\include;$(ProjectDir)..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\zlib;$(ProjectDir)..\..\audio\include;..\;%(AdditionalIncludeDirectories) + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)external;$(EngineRoot)external\unzip;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\win32-specific\zlib\include;..\;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;NDEBUG;_LIB;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -92,89 +94,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -193,130 +113,12 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -339,44 +141,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - diff --git a/extensions/proj.win32/libExtensions.vcxproj.filters b/extensions/proj.win32/libExtensions.vcxproj.filters index 766af1001f..d43ac6197c 100644 --- a/extensions/proj.win32/libExtensions.vcxproj.filters +++ b/extensions/proj.win32/libExtensions.vcxproj.filters @@ -1,9 +1,6 @@  - - {d37545ef-285b-4315-9fca-40da6fc2a6c9} - {202b519b-b5e0-499f-b3b8-ed5da144b248} @@ -16,83 +13,17 @@ {d5806151-7ae1-4fef-af5a-2fa1d1c7377b} - - {4da8061d-80f3-45fd-aa7e-2c0a96701b79} - {5d186e3d-0aaf-4904-a5d8-e5cb0f35f4cc} {49487dbe-5758-436a-b014-8e2edc6b33ae} - - {ff4b5934-99d4-4ea7-9f50-a774192d9ca9} - - - {2a7741ff-87a5-41c8-8e51-d7a1cf0c8e4d} - - - {87250d95-2afd-45e7-bc9d-760478c4e709} - - - {5258a1e1-5d50-4fee-9216-da08d2ec19de} - - - {cf3469d5-421b-4990-a9be-4cd95129fb73} - - - {f48d1291-33fe-49a1-8f9f-4d203e782d4a} - - - {043f8489-822e-43c8-8d9d-5d171a701663} - - - {b8c65820-b5c9-4bd6-83c8-180fdc6100fb} - - - {fa9a165e-cc7c-45e9-ae4f-cae3c2f16e6a} - - - {5e5b3d7d-62a7-493e-a130-ed72ee7c65f2} - - - {d797adcd-2e59-4486-944e-b3e7f3a954b8} - - - {a824cea6-86d7-4230-8738-513a869a1882} - - - {d305abea-33cc-4ae8-b78d-b5fb59927e59} - - - {9af947f9-84cd-4051-953e-67291da6528c} - - - {9713ac75-d9ba-494a-8dcf-03e30f8ee2b2} - - - {2d6f3e38-bb46-4bec-9ec1-73d90cefb3ba} - - - {7556b22b-b7ca-4f3b-938d-0f9c8047892c} - - - {f66c34f1-f75a-4f06-9788-c48972bc0ff2} - - - {1c44450b-d06e-4638-9f0c-1ff62e67ec84} - - - {bec3cdd7-e05b-42d3-97b1-86e26a528a2d} - GUI\CCScrollView - - network - GUI\CCScrollView @@ -138,15 +69,6 @@ GUI\CCControlExtension - - physics_nodes - - - physics_nodes - - - LocalStorage - GUI\CCEditBox @@ -156,390 +78,14 @@ GUI\CCEditBox - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - network - - - network - - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\datas - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\physics - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature - - - CocoStudio\Armature - - - CocoStudio\Armature\utils - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\Reader - AssetsManager - - CCBReader + + physics_nodes - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Reader - - - CocoStudio\Reader - - - CocoStudio\Json - - - CocoStudio\Json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json + + physics_nodes @@ -548,15 +94,6 @@ - - network - - - network - - - network - GUI\CCScrollView @@ -605,15 +142,6 @@ GUI\CCControlExtension - - physics_nodes - - - physics_nodes - - - LocalStorage - GUI\CCEditBox @@ -626,373 +154,14 @@ GUI\CCEditBox - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - spine - - - network - - - network - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\animation - - - CocoStudio\Armature\datas - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\display - - - CocoStudio\Armature\physics - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature\utils - - - CocoStudio\Armature - - - CocoStudio\Armature - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets\ScrollWidget - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\UIWidgets - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\BaseClasses - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\Layouts - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - - - CocoStudio\GUI\System - AssetsManager - - CCBReader + + physics_nodes - - CCBReader + + physics_nodes - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CCBReader - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Action - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Components - - - CocoStudio\Reader - - - CocoStudio\Reader - - - CocoStudio\Json - - - CocoStudio\Json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - - - CocoStudio\Json\lib_json - \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp index 8dadda36ac..31808c17b0 100644 --- a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp +++ b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp @@ -45,6 +45,7 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_cocos2dx_js_extensions); + sc->start(); auto scene = Scene::create(); diff --git a/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd b/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd index 253059b2f8..d397bbc901 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd +++ b/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd @@ -54,7 +54,7 @@ exit /b 1 set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -63,7 +63,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -76,7 +76,6 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets @@ -84,5 +83,5 @@ xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj index 9fdc714c49..b46bf264ae 100644 --- a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj +++ b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) + mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\li if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\AssetsManagerTestRes" rd /s /q "$(OutDir)\AssetsManagerTestRes" mkdir "$(OutDir)\AssetsManagerTestRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y @@ -131,7 +133,7 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Yres_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -151,20 +153,21 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) + mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\AssetsManagerTestRes" rd /s /q "$(OutDir)\AssetsManagerTestRes" mkdir "$(OutDir)\AssetsManagerTestRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y Copy js and resource files. @@ -185,13 +188,27 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Cpp/HelloCpp/proj.android/build_native.cmd b/samples/Cpp/HelloCpp/proj.android/build_native.cmd index 041749c380..f18ac5f170 100644 --- a/samples/Cpp/HelloCpp/proj.android/build_native.cmd +++ b/samples/Cpp/HelloCpp/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%\external;%COCOS2DX_ROOT%\cocos :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,10 +75,9 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj index 233a21ce9c..6da099a164 100644 --- a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj +++ b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj @@ -37,9 +37,11 @@ + + @@ -66,7 +68,7 @@ Disabled - $(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\base;$(ProjectDir)..\..\..\..\cocos\physics;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;..\Classes;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + ..\Classes;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) true EnableFastChecks @@ -94,7 +96,7 @@ MaxSpeed true - $(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\2d\include;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;..\Classes;%(AdditionalIncludeDirectories) + ..\Classes;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -135,9 +137,8 @@ {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Cpp/SimpleGame/proj.android/build_native.cmd b/samples/Cpp/SimpleGame/proj.android/build_native.cmd index cb8929af5b..437e55298f 100644 --- a/samples/Cpp/SimpleGame/proj.android/build_native.cmd +++ b/samples/Cpp/SimpleGame/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,10 +75,9 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.android/build_native.cmd b/samples/Cpp/TestCpp/proj.android/build_native.cmd index 44e95cafe7..d8eaaea7c7 100644 --- a/samples/Cpp/TestCpp/proj.android/build_native.cmd +++ b/samples/Cpp/TestCpp/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\external;%COCOS2DX_ROOT%\cocos :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,10 +75,16 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +rem remove test_image_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_image_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba8888.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgb888.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_a8.pvr.gz + +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index d9227050c3..1dd1fe3146 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -37,10 +37,12 @@ + + @@ -67,7 +69,7 @@ Disabled - $(ProjectDir)..\..\..\..\cocos\physics;$(ProjectDir)..\..\..\..\cocos\base;$(ProjectDir)..\..\..\..\cocos\2d;$(ProjectDir)..\..\..\..\cocos\math\kazmath\include;$(ProjectDir)..\..\..\..\cocos\2d\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\external\win32-specific\gles\include\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\glfw3\include\win32;$(ProjectDir)..\..\..\..\external\websockets\win32\include;$(ProjectDir)..\..\..\..\cocos\audio\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\cocos\network;..\Classes;..;%(AdditionalIncludeDirectories) + ..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL @@ -84,7 +86,7 @@ true Windows MachineX86 - libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) @@ -92,7 +94,7 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -100,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O MaxSpeed true - $(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\pthread;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\audio\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\extensions\network;..\Classes;..;%(AdditionalIncludeDirectories) + ..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -112,7 +114,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O true - libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) $(OutDir)$(ProjectName).exe $(OutDir);%(AdditionalLibraryDirectories) true @@ -127,7 +129,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -467,6 +469,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {b7c2a162-dec9-4418-972e-240ab3cbfcae} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + {21b2c324-891f-48ea-ad1a-5ae13de12e28} false diff --git a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp index 3276d5deda..f14e6df017 100644 --- a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp +++ b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp @@ -8,11 +8,12 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "extension/jsb_cocos2dx_extension_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_ccbreader.h" -#include "js_bindings_system_registration.h" -#include "js_bindings_chipmunk_registration.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "localstorage/js_bindings_system_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" #include "jsb_opengl_registration.h" USING_NS_CC; @@ -124,6 +125,7 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_all_cocos2dx_extension); sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); diff --git a/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd b/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd index 349e2aa5d7..76a9a7138f 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd +++ b/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd @@ -57,7 +57,7 @@ set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\CocosDragonJS\Published files Android" -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -66,7 +66,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -79,7 +79,6 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets @@ -87,5 +86,5 @@ xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause diff --git a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj index e67d8d64eb..8483cb7237 100644 --- a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj +++ b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\li if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\CocosDragonJSRes" rd /s /q "$(OutDir)\CocosDragonJSRes" mkdir "$(OutDir)\CocosDragonJSRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$(OutDir)\CocosDragonJSRes\" /e /Y @@ -131,7 +133,7 @@ xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$ testjs_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_JAVASCRIPT=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -151,20 +153,21 @@ xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\CocosDragonJSRes" rd /s /q "$(OutDir)\CocosDragonJSRes" mkdir "$(OutDir)\CocosDragonJSRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$(OutDir)\CocosDragonJSRes\" /e /Y Copy js and resource files. @@ -185,13 +188,38 @@ xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp index 27520db220..63f1c31aed 100644 --- a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp +++ b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp @@ -5,11 +5,12 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "extension/jsb_cocos2dx_extension_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_ccbreader.h" -#include "js_bindings_system_registration.h" -#include "js_bindings_chipmunk_registration.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "localstorage/js_bindings_system_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" #include "jsb_opengl_registration.h" USING_NS_CC; @@ -106,6 +107,7 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(jsb_register_chipmunk); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); diff --git a/samples/Javascript/CrystalCraze/proj.android/build_native.cmd b/samples/Javascript/CrystalCraze/proj.android/build_native.cmd index 6c248549ae..22f5ad4442 100644 --- a/samples/Javascript/CrystalCraze/proj.android/build_native.cmd +++ b/samples/Javascript/CrystalCraze/proj.android/build_native.cmd @@ -57,7 +57,7 @@ set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\CrystalCraze\Published-Android" -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -66,7 +66,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -79,7 +79,6 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets @@ -87,5 +86,5 @@ xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause diff --git a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj index e2a144bff1..6194bc0354 100644 --- a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj +++ b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\li if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\CrystalCrazeRes" rd /s /q "$(OutDir)\CrystalCrazeRes" mkdir "$(OutDir)\CrystalCrazeRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir)\CrystalCrazeRes\" /e /Y @@ -131,7 +133,7 @@ xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir testjs_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_JAVASCRIPT=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -151,20 +153,21 @@ xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\CrystalCrazeRes" rd /s /q "$(OutDir)\CrystalCrazeRes" mkdir "$(OutDir)\CrystalCrazeRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir)\CrystalCrazeRes\" /e /Y Copy js and resource files. @@ -185,13 +188,44 @@ xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp index 7e7a33a156..c1406c1586 100644 --- a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp +++ b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp @@ -5,11 +5,12 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "extension/jsb_cocos2dx_extension_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_ccbreader.h" -#include "js_bindings_system_registration.h" -#include "js_bindings_chipmunk_registration.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "localstorage/js_bindings_system_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" #include "jsb_opengl_registration.h" USING_NS_CC; @@ -48,6 +49,7 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(jsb_register_chipmunk); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); diff --git a/samples/Javascript/MoonWarriors/proj.android/build_native.cmd b/samples/Javascript/MoonWarriors/proj.android/build_native.cmd index d2dbb3a7e8..e2c1c82c7e 100644 --- a/samples/Javascript/MoonWarriors/proj.android/build_native.cmd +++ b/samples/Javascript/MoonWarriors/proj.android/build_native.cmd @@ -57,7 +57,7 @@ set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\MoonWarriors\res" -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -66,7 +66,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -79,13 +79,12 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets rem copy MoonWarriors js -xcopy /e /q /r /y %RESROUCE_ROOT%\..\src\* %APP_ANDROID_ROOT%\assets +xcopy /e /q /r /y %RESROUCE_ROOT%\..\src %APP_ANDROID_ROOT%\assets rem copy MoonWarriors-native.js xcopy /e /q /r /y %RESROUCE_ROOT%\..\* %APP_ANDROID_ROOT%\assets @@ -93,5 +92,5 @@ xcopy /e /q /r /y %RESROUCE_ROOT%\..\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause diff --git a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj index 1b8d85f756..08efa5fdba 100644 --- a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj +++ b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj @@ -34,19 +34,21 @@ - + + - + + <_ProjectFileVersion>10.0.40219.1 - $(ProjectDir)..\..\..\..\$(Configuration).win32\ + $(SolutionDir)$(Configuration).win32\ $(Configuration).win32\ false - $(ProjectDir)..\..\..\..\$(Configuration).win32\ + $(SolutionDir)$(Configuration).win32\ $(Configuration).win32\ false AllRules.ruleset @@ -77,7 +79,7 @@ Disabled - .;..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + .;..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\li if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\MoonWarriorsRes" rd /s /q "$(OutDir)\MoonWarriorsRes" mkdir "$(OutDir)\MoonWarriorsRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\" /e /Y Copy js and resource files. @@ -129,7 +131,7 @@ xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\ testjs_p.c - .;..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + .;..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -149,20 +151,21 @@ xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\MoonWarriorsRes" rd /s /q "$(OutDir)\MoonWarriorsRes" mkdir "$(OutDir)\MoonWarriorsRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\" /e /Y Copy js and resource files. @@ -183,13 +186,47 @@ xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp index 51ebd8d85f..2a26806916 100644 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp +++ b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp @@ -5,14 +5,18 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "jsb_cocos2dx_studio_auto.hpp" +#include "extension/jsb_cocos2dx_extension_manual.h" +#include "cocostudio/jsb_cocos2dx_studio_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_chipmunk_registration.h" -#include "js_bindings_system_registration.h" +#include "cocosbuilder/cocosbuilder_specifics.hpp" +#include "chipmunk/js_bindings_chipmunk_registration.h" +#include "localstorage/js_bindings_system_registration.h" #include "jsb_opengl_registration.h" -#include "XMLHTTPRequest.h" -#include "jsb_websocket.h" -#include "js_bindings_ccbreader.h" +#include "network/XMLHTTPRequest.h" +#include "network/jsb_websocket.h" +#include "cocosbuilder/js_bindings_ccbreader.h" USING_NS_CC; USING_NS_CC_EXT; @@ -54,7 +58,12 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(MinXmlHttpRequest::_js_register); sc->addRegisterCallback(register_jsb_websocket); + + sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); + + sc->addRegisterCallback(register_all_cocos2dx_studio); + sc->addRegisterCallback(register_all_cocos2dx_studio_manual); sc->start(); diff --git a/samples/Javascript/TestJavascript/proj.android/build_native.cmd b/samples/Javascript/TestJavascript/proj.android/build_native.cmd index 19ee06dd56..a0a5ec0785 100644 --- a/samples/Javascript/TestJavascript/proj.android/build_native.cmd +++ b/samples/Javascript/TestJavascript/proj.android/build_native.cmd @@ -56,7 +56,7 @@ exit /b 1 set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -65,7 +65,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -86,5 +86,5 @@ xcopy /e /q /r /y %APP_ROOT%\..\Shared\tests\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj b/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj index 6af44de033..1af52eccb0 100644 --- a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj +++ b/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,12 +98,12 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -111,7 +113,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\TestJavascriptRes" rd /s /q "$(OutDir)\TestJavascriptRes" mkdir "$(OutDir)\TestJavascriptRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y @@ -132,7 +134,7 @@ xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Ytestjs_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -152,21 +154,22 @@ xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\TestJavascriptRes" rd /s /q "$(OutDir)\TestJavascriptRes" mkdir "$(OutDir)\TestJavascriptRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y Copy js and resource files. @@ -187,14 +190,62 @@ xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {b7c2a162-dec9-4418-972e-240ab3cbfcae} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} + + + {79d34511-e54e-410a-8bba-ef175ad6c695} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {3bec13f5-e227-4d80-bc77-1c857f83bcfc} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {929480e7-23c0-4df6-8456-096d71547116} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} + diff --git a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp index 3e9c616b35..663cd87769 100644 --- a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp +++ b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp @@ -5,11 +5,12 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "extension/jsb_cocos2dx_extension_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_chipmunk_registration.h" -#include "js_bindings_ccbreader.h" -#include "js_bindings_system_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "localstorage/js_bindings_system_registration.h" #include "jsb_opengl_registration.h" USING_NS_CC; @@ -46,6 +47,7 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(jsb_register_chipmunk); + sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); diff --git a/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd b/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd index 9594dada6b..a592025ff0 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd +++ b/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd @@ -57,7 +57,7 @@ set COCOS2DX_ROOT=%~dp0..\..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\WatermelonWithMe" -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -66,7 +66,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -79,7 +79,6 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets @@ -87,5 +86,5 @@ xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj index b6b8e34883..48f07febfb 100644 --- a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj +++ b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\li if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\WatermelonWithMeRes" rd /s /q "$(OutDir)\WatermelonWithMeRes" mkdir "$(OutDir)\WatermelonWithMeRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWithMeRes\" /e /Y @@ -131,7 +133,7 @@ xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWi testjs_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -151,20 +153,21 @@ xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWi if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\WatermelonWithMeRes" rd /s /q "$(OutDir)\WatermelonWithMeRes" mkdir "$(OutDir)\WatermelonWithMeRes" -xcopy "$(ProjectDir)..\..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWithMeRes\" /e /Y Copy js and resource files. @@ -185,13 +188,47 @@ xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWi - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Lua/HelloLua/proj.android/build_native.cmd b/samples/Lua/HelloLua/proj.android/build_native.cmd index 7daf57dd23..4116608669 100644 --- a/samples/Lua/HelloLua/proj.android/build_native.cmd +++ b/samples/Lua/HelloLua/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,13 +75,12 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets rem copy common luaScript -xcopy /e /q /r /y %APP_ROOT%\..\..\scripting\lua\script\* %APP_ANDROID_ROOT%\assets +xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj b/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj index f01edcaf43..fb17ddfe2e 100644 --- a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj +++ b/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\auto-generated\lua-bindings;$(ProjectDir)..\..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;$(ProjectDir)..\..\..\..\extensions;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -95,14 +97,14 @@ $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - libcocos2d.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;libExtensions.lib;websockets.lib;libchipmunk.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows MachineX86 - xcopy "$(ProjectDir)..\..\..\..\scripting\lua\script" "$(ProjectDir)..\..\HelloLua\Resources" /e /Y + xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\lua\script" "$(ProjectDir)..\..\HelloLua\Resources" /e /Y @@ -119,7 +121,7 @@ HelloLua_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\auto-generated\lua-bindings;$(ProjectDir)..\..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -138,10 +140,11 @@ $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - libcocos2d.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;libExtensions.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true @@ -153,17 +156,35 @@ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false - + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + {ddc3e27f-004d-4dd4-9dd3-931a013d2159} - false + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Lua/TestLua/proj.android/build_native.cmd b/samples/Lua/TestLua/proj.android/build_native.cmd index 5602f41812..fa1fc0ad75 100644 --- a/samples/Lua/TestLua/proj.android/build_native.cmd +++ b/samples/Lua/TestLua/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,13 +75,19 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets rem copy common luaScript -xcopy /e /q /r /y %APP_ROOT%\..\..\scripting\lua\script\* %APP_ANDROID_ROOT%\assets +xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +rem remove test_image_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_image_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba8888.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgb888.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba4444.pvr.gz +del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_a8.pvr.gz + +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj index 1d7682a2d2..0a4ea9edbd 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj @@ -36,11 +36,13 @@ - + + - + + @@ -64,7 +66,7 @@ - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\auto-generated\lua-bindings;$(ProjectDir)..\..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) Level3 @@ -82,7 +84,7 @@ MachineX86 true $(OutDir);%(AdditionalLibraryDirectories) - libcocos2d.lib;libExtensions.lib;libBox2d.lib;libchipmunk.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) 0x0409 @@ -103,17 +105,17 @@ xcopy "$(ProjectDir)..\..\..\Cpp\TestCpp\Resources" "$(ProjectDir)..\..\TestLua\Resources" /e /Y -xcopy "$(ProjectDir)..\..\..\..\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y +xcopy "$(EngineRoot)cocos\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y copy files from TestCpp to TestLua if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)" - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\..\scripting\auto-generated\lua-bindings;$(ProjectDir)..\..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\..\cocos2dx;$(ProjectDir)..\..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\..\external;$(ProjectDir)..\..\..\..\external\libwebsockets\win32\include;$(ProjectDir)..\..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) Level3 @@ -129,7 +131,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O Windows MachineX86 $(OutDir);%(AdditionalLibraryDirectories) - libcocos2d.lib;libExtensions.lib;libBox2d.lib;libchipmunk.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) true @@ -151,12 +153,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O xcopy "$(ProjectDir)..\..\..\Cpp\TestCpp\Resources" "$(ProjectDir)..\..\TestLua\Resources" /e /Y -xcopy "$(ProjectDir)..\..\..\..\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y copy files from TestCpp to TestLua if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -167,6 +169,38 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O + + + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} + + + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {ddc3e27f-004d-4dd4-9dd3-931a013d2159} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} + + diff --git a/template/multi-platform-cpp/proj.android/build_native.cmd b/template/multi-platform-cpp/proj.android/build_native.cmd index 68a56c815c..5b25ec4817 100644 --- a/template/multi-platform-cpp/proj.android/build_native.cmd +++ b/template/multi-platform-cpp/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,10 +75,9 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/template/multi-platform-cpp/proj.win32/HelloCpp.sln b/template/multi-platform-cpp/proj.win32/HelloCpp.sln index 31c2e25053..774ee12d79 100644 --- a/template/multi-platform-cpp/proj.win32/HelloCpp.sln +++ b/template/multi-platform-cpp/proj.win32/HelloCpp.sln @@ -3,32 +3,17 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "HelloCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosDenshion", "..\..\..\CocosDenshion\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\..\..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\..\..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\..\..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\..\..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -43,22 +28,14 @@ Global {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.ActiveCfg = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.Build.0 = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/template/multi-platform-cpp/proj.win32/HelloCpp.vcxproj b/template/multi-platform-cpp/proj.win32/HelloCpp.vcxproj index 70a728fe8e..f2e35df259 100644 --- a/template/multi-platform-cpp/proj.win32/HelloCpp.vcxproj +++ b/template/multi-platform-cpp/proj.win32/HelloCpp.vcxproj @@ -36,11 +36,13 @@ - + + - + + @@ -67,7 +69,7 @@ Disabled - $(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\external;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\audio\include;$(ProjectDir)..\..\..\extensions;..\Classes;..;%(AdditionalIncludeDirectories) + $(EngineRoot)cocos\audio\include;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;..\Classes;..;%(AdditionalIncludeDirectories) WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -80,7 +82,7 @@ true - libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) + %(AdditionalDependencies) $(OutDir)$(ProjectName).exe $(OutDir);%(AdditionalLibraryDirectories) true @@ -93,14 +95,14 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" MaxSpeed true - $(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\external;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\audio\include;$(ProjectDir)..\..\..\extensions;..\Classes;..;%(AdditionalIncludeDirectories) + $(EngineRoot)cocos\audio\include;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;..\Classes;..;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -112,7 +114,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD true - libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;websockets.lib;%(AdditionalDependencies) $(OutDir)$(ProjectName).exe $(OutDir);%(AdditionalLibraryDirectories) true @@ -127,7 +129,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -141,25 +143,15 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - false - - - {929480e7-23c0-4df6-8456-096d71547116} - false {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - false diff --git a/template/multi-platform-js/Classes/AppDelegate.cpp b/template/multi-platform-js/Classes/AppDelegate.cpp index ec78d9f5ae..4c2fea3abf 100644 --- a/template/multi-platform-js/Classes/AppDelegate.cpp +++ b/template/multi-platform-js/Classes/AppDelegate.cpp @@ -5,14 +5,11 @@ #include "ScriptingCore.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_extension_manual.h" #include "cocos2d_specifics.hpp" -#include "js_bindings_chipmunk_registration.h" -#include "js_bindings_system_registration.h" -#include "js_bindings_ccbreader.h" +#include "extension/jsb_cocos2dx_extension_manual.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" #include "jsb_opengl_registration.h" -#include "XMLHTTPRequest.h" -#include "jsb_websocket.h" +#include "localstorage/js_bindings_system_registration.h" USING_NS_CC; using namespace CocosDenshion; @@ -41,15 +38,11 @@ bool AppDelegate::applicationDidFinishLaunching() ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_all_cocos2dx_extension); - sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(register_cocos2dx_js_extensions); - sc->addRegisterCallback(register_CCBuilderReader); + sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(jsb_register_chipmunk); - sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); - sc->addRegisterCallback(MinXmlHttpRequest::_js_register); - sc->addRegisterCallback(register_jsb_websocket); - + sc->addRegisterCallback(jsb_register_system); sc->start(); ScriptEngineProtocol *engine = ScriptingCore::getInstance(); diff --git a/template/multi-platform-js/proj.android/build_native.cmd b/template/multi-platform-js/proj.android/build_native.cmd index 5934330044..82eb0151a5 100644 --- a/template/multi-platform-js/proj.android/build_native.cmd +++ b/template/multi-platform-js/proj.android/build_native.cmd @@ -56,7 +56,7 @@ exit /b 1 set COCOS2DX_ROOT=%~dp0..\..\.. set APP_ROOT=%~dp0.. set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%APP_ROOT%\..\..\scripting\javascript\bindings\js +set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) :MODULE1 @@ -65,7 +65,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -86,5 +86,5 @@ xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets rem copy bindings/*.js into assets' root xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/template/multi-platform-js/proj.win32/HelloJavascript.sln b/template/multi-platform-js/proj.win32/HelloJavascript.sln index 025d85dd02..5880df4c17 100644 --- a/template/multi-platform-js/proj.win32/HelloJavascript.sln +++ b/template/multi-platform-js/proj.win32/HelloJavascript.sln @@ -10,23 +10,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript", "HelloJav {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\..\..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\..\..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosDenshion", "..\..\..\CocosDenshion\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\..\..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" ProjectSection(ProjectDependencies) = postProject {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\..\..\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\..\..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" ProjectSection(ProjectDependencies) = postProject {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} @@ -34,6 +27,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\..\..\sc {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} EndProjectSection EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForChipmunk", "..\..\..\cocos\scripting\javascript\bindings\chipmunk\libJSBindingForChipmunk.vcxproj", "{21070E58-EEC6-4E16-8B4F-6D083DF55790}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\..\..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForLocalStorage", "..\..\..\cocos\scripting\javascript\bindings\localstorage\libJSBindingForLocalStorage.vcxproj", "{68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForExtension", "..\..\..\cocos\scripting\javascript\bindings\extension\libJSBindingForExtension.vcxproj", "{625F7391-9A91-48A1-8CFC-79508C822637}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\..\..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -52,10 +55,6 @@ Global {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 @@ -64,6 +63,26 @@ Global {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|Win32.Build.0 = Debug|Win32 {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.ActiveCfg = Release|Win32 {39379840-825A-45A0-B363-C09FFEF864BD}.Release|Win32.Build.0 = Release|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Debug|Win32.ActiveCfg = Debug|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Debug|Win32.Build.0 = Debug|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Release|Win32.ActiveCfg = Release|Win32 + {21070E58-EEC6-4E16-8B4F-6D083DF55790}.Release|Win32.Build.0 = Release|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.ActiveCfg = Debug|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.Build.0 = Debug|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.ActiveCfg = Release|Win32 + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.Build.0 = Release|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Debug|Win32.ActiveCfg = Debug|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Debug|Win32.Build.0 = Debug|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Release|Win32.ActiveCfg = Release|Win32 + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE}.Release|Win32.Build.0 = Release|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Debug|Win32.ActiveCfg = Debug|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Debug|Win32.Build.0 = Debug|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Release|Win32.ActiveCfg = Release|Win32 + {625F7391-9A91-48A1-8CFC-79508C822637}.Release|Win32.Build.0 = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj index fb2ad0984c..26bab7731b 100644 --- a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj +++ b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj @@ -34,11 +34,13 @@ - + + - + + @@ -77,7 +79,7 @@ Disabled - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\extensions;$(ProjectDir)..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks @@ -96,11 +98,11 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -110,7 +112,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\HelloJavascriptRes" rd /s /q "$(OutDir)\HelloJavascriptRes" mkdir "$(OutDir)\HelloJavascriptRes" -xcopy "$(ProjectDir)..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\HelloJavascriptRes\" /e /Y +xcopy "$(EngineRoot)cocos\scripting\javascript\script\*.js" "$(OutDir)\HelloJavascriptRes\" /e /Y xcopy "$(ProjectDir)..\Resources" "$(OutDir)\HelloJavascriptRes\" /e /Y @@ -131,7 +133,7 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\HelloJavascriptRes\" /e /Ygame_p.c - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\scripting\javascript\spidermonkey-win32\include;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\extensions;$(ProjectDir)..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\scripting\javascript\bindings;$(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) @@ -151,20 +153,21 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\HelloJavascriptRes\" /e /Y if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\scripting\javascript\spidermonkey-win32\lib\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcocos2d.lib;libExtensions.lib;libCocosDenshion.lib;libchipmunk.lib;libJSBinding.lib;libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 + true if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\HelloJavascriptRes" rd /s /q "$(OutDir)\HelloJavascriptRes" mkdir "$(OutDir)\HelloJavascriptRes" -xcopy "$(ProjectDir)..\..\..\scripting\javascript\bindings\js\*.js" "$(OutDir)\HelloJavascriptRes\" /e /Y +xcopy "$(EngineRoot)cocos\scripting\javascript\script\*.js" "$(OutDir)\HelloJavascriptRes\" /e /Y xcopy "$(ProjectDir)..\Resources" "$(OutDir)\HelloJavascriptRes\" /e /Y Copy js and resource files. @@ -181,13 +184,32 @@ xcopy "$(ProjectDir)..\Resources" "$(OutDir)\HelloJavascriptRes\" /e /Y - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - false + + + {21070e58-eec6-4e16-8b4f-6d083df55790} + + + {625f7391-9a91-48a1-8cfc-79508c822637} + + + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/template/multi-platform-lua/proj.android/build_native.cmd b/template/multi-platform-lua/proj.android/build_native.cmd index e8caf30dd1..0177685738 100644 --- a/template/multi-platform-lua/proj.android/build_native.cmd +++ b/template/multi-platform-lua/proj.android/build_native.cmd @@ -62,7 +62,7 @@ if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) goto :COPY_RES :MODULE2 echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt + set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external :COPY_RES echo NDK_ROOT = %NDK_ROOT% @@ -75,13 +75,12 @@ rem make sure assets is exist if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res rem copy Resources/* into assets' root xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets rem copy common luaScript -xcopy /e /q /r /y %APP_ROOT%\..\..\scripting\lua\script\* %APP_ANDROID_ROOT%\assets +xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 +call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* pause \ No newline at end of file diff --git a/template/multi-platform-lua/proj.win32/HelloLua.sln b/template/multi-platform-lua/proj.win32/HelloLua.sln index ddd4ee62c8..5fdeacb7a4 100644 --- a/template/multi-platform-lua/proj.win32/HelloLua.sln +++ b/template/multi-platform-lua/proj.win32/HelloLua.sln @@ -11,13 +11,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "HelloLua.vcxpro {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosDenshion", "..\..\..\CocosDenshion\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - EndProjectSection -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\..\..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" ProjectSection(ProjectDependencies) = postProject {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} @@ -30,11 +23,17 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\..\..\extern EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\..\..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\..\..\scripting\lua\proj.win32\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" - ProjectSection(ProjectDependencies) = postProject - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\..\..\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\..\..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\..\..\cocos\network\proj.win32\libNetwork.vcxproj", "{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\..\..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosStudio", "..\..\..\cocos\editor-support\cocostudio\proj.win32\libCocosStudio.vcxproj", "{B57CF53F-2E49-4031-9822-047CC0E6BDE2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -46,14 +45,6 @@ Global {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.Build.0 = Debug|Win32 {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.ActiveCfg = Release|Win32 {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.Build.0 = Release|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.ActiveCfg = Debug|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 @@ -66,10 +57,30 @@ Global {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.ActiveCfg = Debug|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32 {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32 {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32 {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.ActiveCfg = Debug|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.Build.0 = Debug|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.ActiveCfg = Release|Win32 + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.Build.0 = Release|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.ActiveCfg = Debug|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.Build.0 = Debug|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.ActiveCfg = Release|Win32 + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.Build.0 = Release|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.Build.0 = Debug|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.ActiveCfg = Release|Win32 + {B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/template/multi-platform-lua/proj.win32/HelloLua.vcxproj b/template/multi-platform-lua/proj.win32/HelloLua.vcxproj index 2007e7db42..b15be7cabb 100644 --- a/template/multi-platform-lua/proj.win32/HelloLua.vcxproj +++ b/template/multi-platform-lua/proj.win32/HelloLua.vcxproj @@ -36,11 +36,13 @@ - + + - + + @@ -64,7 +66,7 @@ - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\scripting\auto-generated\js-bindings;$(ProjectDir)..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\external;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\audio\include;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)external;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\lua;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) Level3 @@ -82,7 +84,7 @@ MachineX86 true $(OutDir);%(AdditionalLibraryDirectories) - libcocos2d.lib;libExtensions.lib;libBox2d.lib;libchipmunk.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) 0x0409 @@ -102,18 +104,18 @@ - xcopy "$(ProjectDir)..\..\..\scripting\lua\script" "$(ProjectDir)..\Resources" /e /Y + xcopy "$(ProjectDir)..\..\..\cocos\scripting\lua\script" "$(ProjectDir)..\Resources" /e /Y if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" - $(ProjectDir)..\Classes;$(ProjectDir)..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\scripting\lua\lua;$(ProjectDir)..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\scripting\lua\src;$(ProjectDir)..\..\..\cocos2dx;$(ProjectDir)..\..\..\cocos2dx\include;$(ProjectDir)..\..\..\cocos2dx\kazmath\include;$(ProjectDir)..\..\..\cocos2dx\platform\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32;$(ProjectDir)..\..\..\cocos2dx\platform\third_party\win32\OGLES;$(ProjectDir)..\..\..\external;$(ProjectDir)..\..\..\external\chipmunk\include\chipmunk;$(ProjectDir)..\..\..\audio\include;$(ProjectDir)..\..\..\scripting\lua\cocos2dx_support;$(ProjectDir)..\..\..\scripting\lua\tolua;$(ProjectDir)..\..\..\scripting\lua\lua;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)external;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\lua;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) Level3 @@ -130,7 +132,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD Windows MachineX86 $(OutDir);%(AdditionalLibraryDirectories) - libcocos2d.lib;libExtensions.lib;libBox2d.lib;libchipmunk.lib;libCocosDenshion.lib;liblua.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) + lua51.lib;websockets.lib;%(AdditionalDependencies) + true 0x0409 @@ -157,7 +160,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -171,6 +174,32 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\libwebsockets\win32\lib\*.*" "$(OutD + + + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} + + + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} + + + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} + + + {b57cf53f-2e49-4031-9822-047cc0e6bde2} + + + {df2638c0-8128-4847-867c-6eafe3dee7b5} + + + {ddc3e27f-004d-4dd4-9dd3-931a013d2159} + + + {21b2c324-891f-48ea-ad1a-5ae13de12e28} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} + + diff --git a/tools/tojs/cocos2dx_extension.ini b/tools/tojs/cocos2dx_extension.ini index 1519b2eb92..a6475253f2 100644 --- a/tools/tojs/cocos2dx_extension.ini +++ b/tools/tojs/cocos2dx_extension.ini @@ -13,7 +13,7 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT @@ -23,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h +headers = %(cocosdir)s/extensions/cocos-ext.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager +classes = AssetsManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -36,9 +36,7 @@ classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getCCBMemberVariableAssigner readFloat getCCBSelectorResolver toLowerCase lastPathComponent deletePathExtension endsWith concat getResolutionScale getAnimatedProperties readBool readInt addOwnerCallbackNode addDocumentCallbackName readCachedString readNodeGraphFromData addDocumentCallbackNode getLoadedSpriteSheet initWithData readFileWithCleanUp getOwner$ readNodeGraphFromFile createSceneWithNodeGraphFromFile getAnimationManagers$ setAnimationManagers], - CCBAnimationManager::[setAnimationCompletedCallback], - ScrollView::[(g|s)etDelegate$], +skip = ScrollView::[(g|s)etDelegate$], .*Delegate::[*], .*Loader.*::[*], *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], @@ -48,15 +46,11 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*], - Armature::[createBone updateBlendType getBody setBody getShapeList .*BlendFunc], - Skin::[getSkinData setSkinData], - ArmatureAnimation::[updateHandler updateFrameData frameEvent] + ControlSwitchSprite::[*] rename_functions = -rename_classes = CCBReader::_Reader, - CCBAnimationManager::BuilderAnimationManager +rename_classes = # for all class names, should we remove something when registering in the target VM? remove_prefix = @@ -65,11 +59,11 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Object ProcessBase +base_classes_to_skip = Object # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = ArmatureDataManager +abstract_classes = # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no diff --git a/tools/tojs/genbindings.sh b/tools/tojs/genbindings.sh index 56b1b4500f..37d07f9d12 100755 --- a/tools/tojs/genbindings.sh +++ b/tools/tojs/genbindings.sh @@ -84,3 +84,9 @@ LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py echo "Generating bindings for cocos2dx_extension..." LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto + +echo "Generating bindings for cocos2dx_builder..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_builder_auto + +echo "Generating bindings for cocos2dx_studio..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_studio_auto \ No newline at end of file From 232f0d598b743c3ed678d1eb8d7a636573fc07e5 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 21 Oct 2013 22:21:11 +0800 Subject: [PATCH 188/557] issues #2905:add new vs project --- .../proj.win32/libCocosBuilder.vcxproj | 142 ++ .../libCocosBuilder.vcxproj.filters | 170 ++ .../proj.win32/libCocosBuilder.vcxproj.user | 4 + .../proj.win32/libCocosStudio.vcxproj | 174 ++ .../proj.win32/libCocosStudio.vcxproj.filters | 290 +++ .../proj.win32/libCocosStudio.vcxproj.user | 4 + .../spine/proj.win32/libSpine.vcxproj | 134 ++ .../spine/proj.win32/libSpine.vcxproj.filters | 146 ++ .../spine/proj.win32/libSpine.vcxproj.user | 4 + cocos/gui/proj.win32/libGUI.vcxproj | 136 ++ cocos/gui/proj.win32/libGUI.vcxproj.filters | 159 ++ cocos/gui/proj.win32/libGUI.vcxproj.user | 4 + cocos/network/proj.win32/libNetwork.vcxproj | 131 ++ .../proj.win32/libNetwork.vcxproj.filters | 45 + .../proj.win32/libNetwork.vcxproj.user | 3 + ...s_chipmunk_auto_classes.cpp.REMOVED.git-id | 1 + .../js_bindings_chipmunk_auto_classes.h | 66 + ...dings_chipmunk_auto_classes_registration.h | 29 + ...ings_chipmunk_functions.cpp.REMOVED.git-id | 1 + .../chipmunk/js_bindings_chipmunk_functions.h | 292 +++ ...bindings_chipmunk_functions_registration.h | 285 +++ .../chipmunk/js_bindings_chipmunk_manual.cpp | 1624 +++++++++++++++++ .../chipmunk/js_bindings_chipmunk_manual.h | 103 ++ .../js_bindings_chipmunk_registration.cpp | 67 + .../js_bindings_chipmunk_registration.h | 31 + .../chipmunk/libJSBindingForChipmunk.vcxproj | 121 ++ .../libJSBindingForChipmunk.vcxproj.filters | 47 + .../libJSBindingForChipmunk.vcxproj.user | 6 + .../cocosbuilder/cocosbuilder_specifics.hpp | 23 + .../cocosbuilder/js_bindings_ccbreader.cpp | 324 ++++ .../cocosbuilder/js_bindings_ccbreader.h | 60 + .../libJSBindingForBuilder.vcxproj | 119 ++ .../libJSBindingForBuilder.vcxproj.filters | 37 + .../libJSBindingForBuilder.vcxproj.user | 6 + .../cocostudio/jsb_cocos2dx_studio_manual.cpp | 229 +++ .../cocostudio/jsb_cocos2dx_studio_manual.h | 16 + .../cocostudio/libJSBindingForStudio.vcxproj | 118 ++ .../libJSBindingForStudio.vcxproj.filters | 34 + .../libJSBindingForStudio.vcxproj.user | 6 + .../jsb_cocos2dx_extension_manual.cpp | 799 ++++++++ .../extension/jsb_cocos2dx_extension_manual.h | 16 + .../libJSBindingForExtension.vcxproj | 118 ++ .../libJSBindingForExtension.vcxproj.filters | 34 + .../libJSBindingForExtension.vcxproj.user | 6 + .../js_bindings_system_functions.cpp | 75 + .../js_bindings_system_functions.h | 23 + ...s_bindings_system_functions_registration.h | 15 + .../js_bindings_system_registration.cpp | 62 + .../js_bindings_system_registration.h | 31 + .../libJSBindingForLocalStorage.vcxproj | 116 ++ ...ibJSBindingForLocalStorage.vcxproj.filters | 32 + .../libJSBindingForLocalStorage.vcxproj.user | 6 + .../bindings/network/XMLHTTPRequest.cpp | 847 +++++++++ .../bindings/network/XMLHTTPRequest.h | 112 ++ .../bindings/network/jsb_websocket.cpp | 382 ++++ .../bindings/network/jsb_websocket.h | 34 + .../network/libJSBindingForNetwork.vcxproj | 115 ++ .../libJSBindingForNetwork.vcxproj.filters | 29 + .../libJSBindingForNetwork.vcxproj.user | 6 + .../proj.win32/libLocalStorage.vcxproj | 93 + .../libLocalStorage.vcxproj.filters | 21 + .../proj.win32/libLocalStorage.vcxproj.user | 4 + 62 files changed, 8167 insertions(+) create mode 100644 cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj create mode 100644 cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.filters create mode 100644 cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.user create mode 100644 cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj create mode 100644 cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.filters create mode 100644 cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.user create mode 100644 cocos/editor-support/spine/proj.win32/libSpine.vcxproj create mode 100644 cocos/editor-support/spine/proj.win32/libSpine.vcxproj.filters create mode 100644 cocos/editor-support/spine/proj.win32/libSpine.vcxproj.user create mode 100644 cocos/gui/proj.win32/libGUI.vcxproj create mode 100644 cocos/gui/proj.win32/libGUI.vcxproj.filters create mode 100644 cocos/gui/proj.win32/libGUI.vcxproj.user create mode 100644 cocos/network/proj.win32/libNetwork.vcxproj create mode 100644 cocos/network/proj.win32/libNetwork.vcxproj.filters create mode 100644 cocos/network/proj.win32/libNetwork.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp create mode 100644 cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.h create mode 100644 cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj create mode 100644 cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp create mode 100644 cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.h create mode 100644 cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj create mode 100644 cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp create mode 100644 cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.h create mode 100644 cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj create mode 100644 cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp create mode 100644 cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h create mode 100644 cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions_registration.h create mode 100644 cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp create mode 100644 cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.h create mode 100644 cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj create mode 100644 cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.user create mode 100644 cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp create mode 100644 cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h create mode 100644 cocos/scripting/javascript/bindings/network/jsb_websocket.cpp create mode 100644 cocos/scripting/javascript/bindings/network/jsb_websocket.h create mode 100644 cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj create mode 100644 cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.filters create mode 100644 cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.user create mode 100644 cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj create mode 100644 cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.filters create mode 100644 cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.user diff --git a/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj new file mode 100644 index 0000000000..2b44d72452 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj @@ -0,0 +1,142 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {811C0DAB-7B96-4BD3-A154-B7572B58E4AB} + libCocosBuilder + + + + StaticLibrary + true + v110_xp + Unicode + + + StaticLibrary + false + v110_xp + true + Unicode + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + + Level3 + Disabled + + + $(EngineRoot);$(EngineRoot)extensions;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + 4267;4251;4244;%(DisableSpecificWarnings) + false + + + true + + + + + Level3 + MaxSpeed + true + true + + + $(EngineRoot);$(EngineRoot)extensions;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.filters b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.filters new file mode 100644 index 0000000000..8dfedcc4bf --- /dev/null +++ b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.filters @@ -0,0 +1,170 @@ + + + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.user b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.user new file mode 100644 index 0000000000..a375ae3527 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj new file mode 100644 index 0000000000..d52ce8d931 --- /dev/null +++ b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj @@ -0,0 +1,174 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {B57CF53F-2E49-4031-9822-047CC0E6BDE2} + libCocosStudio + + + + StaticLibrary + true + v110_xp + Unicode + + + StaticLibrary + false + v110_xp + true + Unicode + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + + Level3 + Disabled + + + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + 4267;4251;4244;%(DisableSpecificWarnings) + false + + + true + + + + + Level3 + MaxSpeed + true + true + true + WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + + + true + true + true + + + + + + \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.filters b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.filters new file mode 100644 index 0000000000..10053f03e2 --- /dev/null +++ b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.filters @@ -0,0 +1,290 @@ + + + + + {d793b86c-0905-4c9b-b6bc-161e351c9eb2} + + + {855f2366-3429-4f77-a080-a41a39c99270} + + + {1a8c6b14-fb28-4485-8417-9b6838fbc4ef} + + + {42f1ce3f-46ab-4a16-a96e-9eb076c873f7} + + + {f8271f80-1663-4425-91c8-7365ec3af017} + + + {48f28446-ffe4-4aa1-a34c-8968c3367ae6} + + + {ad9b4fd1-dc17-4704-9c60-7709eb916f13} + + + {55c682b3-7a48-4fab-ad5a-eb979f3c305e} + + + {c6464479-e0ab-4afc-96fc-1ffc73e40232} + + + {023e3440-1259-4981-ba54-24390d1df447} + + + {e8d09ad5-8816-4724-a10b-04263868ed7c} + + + + + action + + + action + + + action + + + action + + + action + + + components + + + components + + + components + + + components + + + components + + + json + + + json + + + reader + + + reader + + + armature\animation + + + armature\animation + + + armature\animation + + + armature\datas + + + armature\display + + + armature\display + + + armature\display + + + armature\display + + + armature\display + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\physics + + + armature + + + armature + + + json\libjson + + + json\libjson + + + json\libjson + + + + + action + + + action + + + action + + + action + + + action + + + components + + + components + + + components + + + components + + + components + + + json + + + json + + + reader + + + reader + + + armature\animation + + + armature\animation + + + armature\animation + + + armature\datas + + + armature\display + + + armature\display + + + armature\display + + + armature\display + + + armature\display + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\utils + + + armature\physics + + + armature + + + armature + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + + + json\libjson + + + json\libjson + + + json\libjson + + + json\libjson + + + \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.user b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.user new file mode 100644 index 0000000000..a375ae3527 --- /dev/null +++ b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/cocos/editor-support/spine/proj.win32/libSpine.vcxproj b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj new file mode 100644 index 0000000000..b4fc436abf --- /dev/null +++ b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj @@ -0,0 +1,134 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE} + libSpine + + + + StaticLibrary + true + v110_xp + Unicode + + + StaticLibrary + false + v110_xp + true + Unicode + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + + Level3 + Disabled + + + $(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + 4267;4251;4244;%(DisableSpecificWarnings) + false + + + true + + + + + Level3 + MaxSpeed + true + true + + + WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + + + true + true + true + + + + + + \ No newline at end of file diff --git a/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.filters b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.filters new file mode 100644 index 0000000000..d6ed5b1506 --- /dev/null +++ b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.filters @@ -0,0 +1,146 @@ + + + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.user b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.user new file mode 100644 index 0000000000..a375ae3527 --- /dev/null +++ b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/cocos/gui/proj.win32/libGUI.vcxproj b/cocos/gui/proj.win32/libGUI.vcxproj new file mode 100644 index 0000000000..1e483d4b85 --- /dev/null +++ b/cocos/gui/proj.win32/libGUI.vcxproj @@ -0,0 +1,136 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {7E06E92C-537A-442B-9E4A-4761C84F8A1A} + libGUI + + + + StaticLibrary + true + v110_xp + Unicode + + + StaticLibrary + false + v110_xp + true + Unicode + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + + Level3 + Disabled + + + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + 4267;4251;4244;%(DisableSpecificWarnings) + false + + + true + + + + + Level3 + MaxSpeed + true + true + + + WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + + + true + true + true + + + + + + \ No newline at end of file diff --git a/cocos/gui/proj.win32/libGUI.vcxproj.filters b/cocos/gui/proj.win32/libGUI.vcxproj.filters new file mode 100644 index 0000000000..12f0d385ab --- /dev/null +++ b/cocos/gui/proj.win32/libGUI.vcxproj.filters @@ -0,0 +1,159 @@ + + + + + {e31ab7d3-b8b2-467f-9e08-fd5fe168b491} + + + {f9d13563-9e5e-4b35-b0e7-d41f587efa42} + + + {ed8a2ae0-5690-4d0d-829b-7c07164c0597} + + + {5f6e9e52-fbe7-4073-ac71-98632f9e6781} + + + {b59b178a-b7e0-4826-ba07-44c46cd29a10} + + + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + System + + + System + + + System + + + System + + + Layouts + + + Layouts + + + Layouts + + + BaseClasses + + + BaseClasses + + + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets\ScrollWidget + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + UIWidgets + + + System + + + System + + + System + + + System + + + Layouts + + + Layouts + + + Layouts + + + BaseClasses + + + BaseClasses + + + \ No newline at end of file diff --git a/cocos/gui/proj.win32/libGUI.vcxproj.user b/cocos/gui/proj.win32/libGUI.vcxproj.user new file mode 100644 index 0000000000..a375ae3527 --- /dev/null +++ b/cocos/gui/proj.win32/libGUI.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/cocos/network/proj.win32/libNetwork.vcxproj b/cocos/network/proj.win32/libNetwork.vcxproj new file mode 100644 index 0000000000..088538dfed --- /dev/null +++ b/cocos/network/proj.win32/libNetwork.vcxproj @@ -0,0 +1,131 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + libNetwork + {DF2638C0-8128-4847-867C-6EAFE3DEE7B5} + network.win32 + Win32Proj + + + + StaticLibrary + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + NotSet + v100 + v110 + v110_xp + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + false + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + false + AllRules.ruleset + + + AllRules.ruleset + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + + Disabled + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(EngineRoot)cocos;$(EngineRoot)external\websockets\include\win32;$(EngineRoot)external\curl\include\win32;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + false + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + 4251 + true + + + winmm.lib;libcocos2d.lib;%(AdditionalDependencies) + $(OutDir)$(ProjectName).dll + true + Windows + $(TargetDir)$(TargetName).lib + MachineX86 + $(OutDir) + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(EngineRoot)cocos;$(EngineRoot)external\websockets\include\win32;$(EngineRoot)external\curl\include\win32;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + 4251 + true + + + winmm.lib;libcocos2d.lib;%(AdditionalDependencies) + $(OutDir)$(ProjectName).dll + true + Windows + true + true + $(TargetDir)$(TargetName).lib + MachineX86 + $(OutDir) + + + + + + \ No newline at end of file diff --git a/cocos/network/proj.win32/libNetwork.vcxproj.filters b/cocos/network/proj.win32/libNetwork.vcxproj.filters new file mode 100644 index 0000000000..bbfe567f42 --- /dev/null +++ b/cocos/network/proj.win32/libNetwork.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/cocos/network/proj.win32/libNetwork.vcxproj.user b/cocos/network/proj.win32/libNetwork.vcxproj.user new file mode 100644 index 0000000000..ace9a86acb --- /dev/null +++ b/cocos/network/proj.win32/libNetwork.vcxproj.user @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id new file mode 100644 index 0000000000..c8c345c32c --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id @@ -0,0 +1 @@ +6558be4f421be9227dc4fabf1b682d479825bd18 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.h new file mode 100644 index 0000000000..42c8840236 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.h @@ -0,0 +1,66 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 +* Script version: v0.3 +*/ +#include "js_bindings_config.h" +#ifdef JSB_INCLUDE_CHIPMUNK + +#include "js_bindings_chipmunk_manual.h" +extern JSObject *JSB_cpConstraint_object; +extern JSClass *JSB_cpConstraint_class; +void JSB_cpConstraint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpGrooveJoint_object; +extern JSClass *JSB_cpGrooveJoint_class; +void JSB_cpGrooveJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpSimpleMotor_object; +extern JSClass *JSB_cpSimpleMotor_class; +void JSB_cpSimpleMotor_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpPivotJoint_object; +extern JSClass *JSB_cpPivotJoint_class; +void JSB_cpPivotJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpPinJoint_object; +extern JSClass *JSB_cpPinJoint_class; +void JSB_cpPinJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpSlideJoint_object; +extern JSClass *JSB_cpSlideJoint_class; +void JSB_cpSlideJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpGearJoint_object; +extern JSClass *JSB_cpGearJoint_class; +void JSB_cpGearJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpDampedRotarySpring_object; +extern JSClass *JSB_cpDampedRotarySpring_class; +void JSB_cpDampedRotarySpring_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpDampedSpring_object; +extern JSClass *JSB_cpDampedSpring_class; +void JSB_cpDampedSpring_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpRatchetJoint_object; +extern JSClass *JSB_cpRatchetJoint_class; +void JSB_cpRatchetJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpRotaryLimitJoint_object; +extern JSClass *JSB_cpRotaryLimitJoint_class; +void JSB_cpRotaryLimitJoint_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpArbiter_object; +extern JSClass *JSB_cpArbiter_class; +void JSB_cpArbiter_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpSpace_object; +extern JSClass *JSB_cpSpace_class; +void JSB_cpSpace_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpBody_object; +extern JSClass *JSB_cpBody_class; +void JSB_cpBody_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpShape_object; +extern JSClass *JSB_cpShape_class; +void JSB_cpShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpCircleShape_object; +extern JSClass *JSB_cpCircleShape_class; +void JSB_cpCircleShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpSegmentShape_object; +extern JSClass *JSB_cpSegmentShape_class; +void JSB_cpSegmentShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); +extern JSObject *JSB_cpPolyShape_object; +extern JSClass *JSB_cpPolyShape_class; +void JSB_cpPolyShape_createClass(JSContext *cx, JSObject* globalObj, const char* name ); + + +#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h new file mode 100644 index 0000000000..da26c49bb3 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h @@ -0,0 +1,29 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 +* Script version: v0.3 +*/ +#include "js_bindings_config.h" +#ifdef JSB_INCLUDE_CHIPMUNK + +JSB_cpConstraint_createClass(_cx, chipmunk, "Constraint"); +JSB_cpGrooveJoint_createClass(_cx, chipmunk, "GrooveJoint"); +JSB_cpSimpleMotor_createClass(_cx, chipmunk, "SimpleMotor"); +JSB_cpPivotJoint_createClass(_cx, chipmunk, "PivotJoint"); +JSB_cpPinJoint_createClass(_cx, chipmunk, "PinJoint"); +JSB_cpSlideJoint_createClass(_cx, chipmunk, "SlideJoint"); +JSB_cpGearJoint_createClass(_cx, chipmunk, "GearJoint"); +JSB_cpDampedRotarySpring_createClass(_cx, chipmunk, "DampedRotarySpring"); +JSB_cpDampedSpring_createClass(_cx, chipmunk, "DampedSpring"); +JSB_cpRatchetJoint_createClass(_cx, chipmunk, "RatchetJoint"); +JSB_cpRotaryLimitJoint_createClass(_cx, chipmunk, "RotaryLimitJoint"); +JSB_cpArbiter_createClass(_cx, chipmunk, "Arbiter"); +JSB_cpSpace_createClass(_cx, chipmunk, "Space"); +JSB_cpBody_createClass(_cx, chipmunk, "Body"); +JSB_cpShape_createClass(_cx, chipmunk, "Shape"); +JSB_cpCircleShape_createClass(_cx, chipmunk, "CircleShape"); +JSB_cpSegmentShape_createClass(_cx, chipmunk, "SegmentShape"); +JSB_cpPolyShape_createClass(_cx, chipmunk, "PolyShape"); + + +#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id new file mode 100644 index 0000000000..5cf2a4495d --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id @@ -0,0 +1 @@ +1c5eb9cd58c82de77374cdfa5c9ff647cc8b2f02 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h new file mode 100644 index 0000000000..accf523d5e --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h @@ -0,0 +1,292 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-11-07 +* Script version: v0.3 +*/ +#include "js_bindings_config.h" +#ifdef JSB_INCLUDE_CHIPMUNK +#include "js_bindings_chipmunk_manual.h" + +#ifdef __cplusplus +extern "C" { +#endif +JSBool JSB_cpArbiterGetCount(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetDepth(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetFriction(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetNormal(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetPoint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterIgnore(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterIsFirstContact(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterSetFriction(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterTotalImpulse(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterTotalImpulseWithFriction(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterTotalKE(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpAreaForCircle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpAreaForSegment(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBArea(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBClampVect(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBContainsBB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBContainsVect(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBExpand(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBIntersects(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBIntersectsSegment(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBMerge(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBMergedArea(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBNewForCircle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBSegmentQuery(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBBWrapVect(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyActivate(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyActivateStatic(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyApplyForce(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyApplyImpulse(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyDestroy(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyFree(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetAngVel(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetForce(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetMass(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetMoment(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetPos(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetRot(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetTorque(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetVel(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetVelAtLocalPoint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetVelAtWorldPoint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyGetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyInit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyInitStatic(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyIsRogue(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyIsSleeping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyIsStatic(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyKineticEnergy(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyLocal2World(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyNewStatic(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyResetForces(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetAngVel(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetForce(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetMass(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetMoment(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetPos(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetTorque(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetVel(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySleep(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySleepWithGroup(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyUpdatePosition(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyUpdateVelocity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodyWorld2Local(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBoxShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBoxShapeNew2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpCircleShapeGetOffset(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpCircleShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpCircleShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintActivateBodies(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintDestroy(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintFree(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetA(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetImpulse(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintSetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintSetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpConstraintSetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringGetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringSetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedRotarySpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringGetRestLength(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringSetRestLength(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpDampedSpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGearJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGearJointGetRatio(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGearJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGearJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGearJointSetRatio(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointGetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointGetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointSetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpGrooveJointSetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpInitChipmunk(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpMomentForBox(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpMomentForBox2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpMomentForCircle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpMomentForSegment(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointGetDist(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPinJointSetDist(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointNew2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPivotJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPolyShapeGetNumVerts(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpPolyShapeGetVert(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointGetAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointGetRatchet(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointSetAngle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRatchetJointSetRatchet(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpResetShapeIdCounter(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRotaryLimitJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRotaryLimitJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRotaryLimitJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRotaryLimitJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRotaryLimitJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeGetA(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeGetB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeGetNormal(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSegmentShapeSetNeighbors(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeCacheBB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeDestroy(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeFree(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetBB(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetFriction(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetGroup(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetLayers(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetSensor(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapePointQuery(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetFriction(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetGroup(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetLayers(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetSensor(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpShapeUpdate(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSimpleMotorGetRate(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSimpleMotorNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSimpleMotorSetRate(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSlideJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceActivateShapesTouchingShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceAddBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceAddConstraint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceAddShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceAddStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceContainsBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceContainsConstraint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceContainsShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceDestroy(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceFree(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetCurrentTimeStep(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetGravity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetIterations(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceGetStaticBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceInit(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceIsLocked(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceNew(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpacePointQueryFirst(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceReindexShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceReindexShapesForBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceReindexStatic(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceRemoveBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceRemoveConstraint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceRemoveShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceRemoveStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetGravity(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetIterations(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceSetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceStep(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceUseSpatialHash(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpfabs(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpfclamp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpfclamp01(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpflerp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpflerpconst(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpfmax(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpfmin(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvadd(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvclamp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvcross(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvdist(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvdistsq(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvdot(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpveql(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvforangle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvlength(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvlengthsq(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvlerp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvlerpconst(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvmult(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvnear(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvneg(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvnormalize(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvnormalize_safe(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvperp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvproject(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvrotate(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvrperp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvslerp(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvslerpconst(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvsub(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvtoangle(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpvunrotate(JSContext *cx, uint32_t argc, jsval *vp); + +#ifdef __cplusplus +} +#endif + + +#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h new file mode 100644 index 0000000000..2d84087c28 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h @@ -0,0 +1,285 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c chipmunk_jsb.ini" on 2012-10-18 +* Script version: v0.3 +*/ +#include "js_bindings_config.h" +#ifdef JSB_INCLUDE_CHIPMUNK + +#include "js_bindings_chipmunk_manual.h" +JS_DefineFunction(_cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + + +#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp new file mode 100644 index 0000000000..14a88c87bb --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -0,0 +1,1624 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 "extensions/cocos-ext.h" +#include "js_bindings_config.h" +#ifdef JSB_INCLUDE_CHIPMUNK + +#include "jsapi.h" +#include "jsfriendapi.h" + +#include "js_bindings_chipmunk_manual.h" +#include "js_manual_conversions.h" + +USING_NS_CC_EXT; +// Function declarations +void static freeSpaceChildren(cpSpace *space); + +template +static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { + TypeTest t; + T* cobj = new T(); + cobj->autorelease(); + js_type_class_t *p; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, p); + assert(p); + JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto); + js_proxy_t *pp = jsb_new_proxy(cobj, _tmp); + JS_AddObjectRoot(cx, &pp->obj); + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(_tmp)); + + return JS_TRUE; +} + +#pragma mark - convertions + +/* + * PhysicsSprite + */ +#pragma mark - PhysicsSprite + +JSClass* JSPROXY_CCPhysicsSprite_class = NULL; +JSObject* JSPROXY_CCPhysicsSprite_object = NULL; +// Constructor + +// Destructor +void JSPROXY_CCPhysicsSprite_finalize(JSFreeOp *fop, JSObject *obj) +{ + CCLOGINFO("jsbindings: finalizing JS object %p (PhysicsSprite)", obj); +} + +// Arguments: +// Ret value: cpBody* (N/A) +JSBool JSPROXY_CCPhysicsSprite_getCPBody(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + cpBody* ret_val; + + ret_val = real->getCPBody(); + jsval ret_jsval = c_class_to_jsval( cx, ret_val, JSB_cpBody_object, JSB_cpBody_class, "cpBody" ); + JS_SET_RVAL(cx, vp, ret_jsval); + + return JS_TRUE; +} + +// Arguments: +// Ret value: BOOL (b) +JSBool JSPROXY_CCPhysicsSprite_ignoreBodyRotation(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + + bool ret_val; + + ret_val = real->isIgnoreBodyRotation(); + JS_SET_RVAL(cx, vp, BOOLEAN_TO_JSVAL(ret_val)); + return JS_TRUE; +} + +// Arguments: cpBody* +// Ret value: void (None) +JSBool JSPROXY_CCPhysicsSprite_setCPBody_(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + + cpBody* arg0; + + ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); + if( ! ok ) return JS_FALSE; + + real->setCPBody((cpBody*)arg0); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: BOOL +// Ret value: void (None) +JSBool JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + PhysicsSprite* real = (PhysicsSprite *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + JSBool arg0; + + ok &= JS_ValueToBoolean( cx, *argvp++, &arg0 ); + if( ! ok ) return JS_FALSE; + + real->setIgnoreBodyRotation((bool)arg0); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +/* + * PhysicsDebugNode + */ +//#pragma mark - PhysicsDebugNode + +JSClass* JSB_CCPhysicsDebugNode_class = NULL; +JSObject* JSB_CCPhysicsDebugNode_object = NULL; +extern JSObject *js_cocos2dx_CCDrawNode_prototype; + +// Constructor + +// Destructor +void JSB_CCPhysicsDebugNode_finalize(JSFreeOp *fop, JSObject *obj) +{ + CCLOGINFO("jsbindings: finalizing JS object %p (PhysicsDebugNode)", obj); +} + +// Arguments: cpSpace* +// Ret value: PhysicsDebugNode* (o) +JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpSpace* arg0; + + ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + PhysicsDebugNode* ret = PhysicsDebugNode::create(arg0); + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCDebugNode"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + + return JS_TRUE; +} + +// Arguments: cpSpace* +// Ret value: void (None) +JSBool JSB_CCPhysicsDebugNode_setSpace_(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(jsthis); + PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + + JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpSpace* arg0; + + ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + real->setSpace(arg0); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: +// Ret value: cpSpace* (N/A) +JSBool JSB_CCPhysicsDebugNode_space(JSContext *cx, uint32_t argc, jsval *vp) { + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(jsthis); + PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, real) + JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + cpSpace* ret_val; + + ret_val = real->getSpace(); + + jsval ret_jsval = opaque_to_jsval( cx, ret_val ); + JS_SET_RVAL(cx, vp, ret_jsval); + + return JS_TRUE; +} + +void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, const char* name ) +{ + JSB_CCPhysicsDebugNode_class = (JSClass *)calloc(1, sizeof(JSClass)); + JSB_CCPhysicsDebugNode_class->name = name; + JSB_CCPhysicsDebugNode_class->addProperty = JS_PropertyStub; + JSB_CCPhysicsDebugNode_class->delProperty = JS_DeletePropertyStub; + JSB_CCPhysicsDebugNode_class->getProperty = JS_PropertyStub; + JSB_CCPhysicsDebugNode_class->setProperty = JS_StrictPropertyStub; + JSB_CCPhysicsDebugNode_class->enumerate = JS_EnumerateStub; + JSB_CCPhysicsDebugNode_class->resolve = JS_ResolveStub; + JSB_CCPhysicsDebugNode_class->convert = JS_ConvertStub; + JSB_CCPhysicsDebugNode_class->finalize = JSB_CCPhysicsDebugNode_finalize; + JSB_CCPhysicsDebugNode_class->flags = 0; + + static JSPropertySpec properties[] = { + {0, 0, 0, 0, 0} + }; + static JSFunctionSpec funcs[] = { + JS_FN("_setSpace", JSB_CCPhysicsDebugNode_setSpace_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getSpace", JSB_CCPhysicsDebugNode_space, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + static JSFunctionSpec st_funcs[] = { + JS_FN("_create", JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + TypeTest t1; + js_type_class_t *typeClass; + uint32_t typeId = t1.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + + JSB_CCPhysicsDebugNode_object = JS_InitClass(cx, globalObj, typeClass->proto, JSB_CCPhysicsDebugNode_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); + + TypeTest t; + js_type_class_t *p; + typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, p); + if (!p) { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + p->type = typeId; + p->jsclass = JSB_CCPhysicsDebugNode_class; + p->proto = JSB_CCPhysicsDebugNode_object; + p->parentProto = typeClass->proto; + HASH_ADD_INT(_js_global_type_ht, type, p); + } +} + +// Arguments: NSString*, CGRect +// Ret value: PhysicsSprite* (o) +JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32_t argc, jsval *vp) { + + jsval *argv = JS_ARGV(cx, vp); + JSBool ok = JS_TRUE; + if (argc == 2) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + cocos2d::Rect arg1; + ok &= jsval_to_ccrect(cx, argv[1], &arg1); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + PhysicsSprite* ret = PhysicsSprite::create(arg0, arg1); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + if (argc == 1) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + PhysicsSprite* ret = PhysicsSprite::create(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + return JS_FALSE; + +} + +// Arguments: SpriteFrame* +// Ret value: PhysicsSprite* (o) +JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint32_t argc, jsval *vp) { + jsval *argv = JS_ARGV(cx, vp); + cocos2d::SpriteFrame* arg0; + if (argc >= 1) { + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]); + proxy = jsb_get_js_proxy(tmpObj); + arg0 = (cocos2d::SpriteFrame*)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg0) + } while (0); + } + PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrame(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; +} + +// Arguments: NSString* +// Ret value: PhysicsSprite* (o) +JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, uint32_t argc, jsval *vp) { + jsval *argv = JS_ARGV(cx, vp); + JSBool ok = JS_TRUE; + const char* arg0; + std::string arg0_tmp; + if (argc >= 1) { + ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + } + PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass; + uint32_t typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; +} + +void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) +{ + JSPROXY_CCPhysicsSprite_class = (JSClass *)calloc(1, sizeof(JSClass)); + JSPROXY_CCPhysicsSprite_class->name = "PhysicsSprite"; + JSPROXY_CCPhysicsSprite_class->addProperty = JS_PropertyStub; + JSPROXY_CCPhysicsSprite_class->delProperty = JS_DeletePropertyStub; + JSPROXY_CCPhysicsSprite_class->getProperty = JS_PropertyStub; + JSPROXY_CCPhysicsSprite_class->setProperty = JS_StrictPropertyStub; + JSPROXY_CCPhysicsSprite_class->enumerate = JS_EnumerateStub; + JSPROXY_CCPhysicsSprite_class->resolve = JS_ResolveStub; + JSPROXY_CCPhysicsSprite_class->convert = JS_ConvertStub; + JSPROXY_CCPhysicsSprite_class->finalize = JSPROXY_CCPhysicsSprite_finalize; + JSPROXY_CCPhysicsSprite_class->flags = 0; + + static JSPropertySpec properties[] = { + {0, 0, 0, 0, 0} + }; + static JSFunctionSpec funcs[] = { + JS_FN("getCPBody", JSPROXY_CCPhysicsSprite_getCPBody, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getIgnoreBodyRotation", JSPROXY_CCPhysicsSprite_ignoreBodyRotation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("_setCPBody", JSPROXY_CCPhysicsSprite_setCPBody_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setIgnoreBodyRotation", JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + static JSFunctionSpec st_funcs[] = { + JS_FN("create", JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("createWithSpriteFrame", JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("createWithSpriteFrameName", JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + TypeTest t1; + js_type_class_t *typeClass; + uint32_t typeId = t1.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); + assert(typeClass); + + JSPROXY_CCPhysicsSprite_object = JS_InitClass(cx, globalObj, typeClass->proto, JSPROXY_CCPhysicsSprite_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); + + TypeTest t; + js_type_class_t *p; + typeId = t.s_id(); + HASH_FIND_INT(_js_global_type_ht, &typeId, p); + if (!p) { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + p->type = typeId; + p->jsclass = JSPROXY_CCPhysicsSprite_class; + p->proto = JSPROXY_CCPhysicsSprite_object; + p->parentProto = typeClass->proto; + HASH_ADD_INT(_js_global_type_ht, type, p); + } +} + + +void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { + jsval nsval; + JSObject *ns; + JS_GetProperty(cx, obj, "cc", &nsval); + if (nsval == JSVAL_VOID) { + ns = JS_NewObject(cx, NULL, NULL, NULL); + nsval = OBJECT_TO_JSVAL(ns); + JS_SetProperty(cx, obj, "cc", &nsval); + } else { + JS_ValueToObject(cx, nsval, &ns); + } + obj = ns; + JSPROXY_CCPhysicsSprite_createClass(cx, obj); +} + +void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj) { + jsval nsval; + JSObject *ns; + JS_GetProperty(cx, obj, "cc", &nsval); + if (nsval == JSVAL_VOID) { + ns = JS_NewObject(cx, NULL, NULL, NULL); + nsval = OBJECT_TO_JSVAL(ns); + JS_SetProperty(cx, obj, "cc", &nsval); + } else { + JS_ValueToObject(cx, nsval, &ns); + } + obj = ns; + JSB_CCPhysicsDebugNode_createClass(cx, obj, "PhysicsDebugNode"); +} + +JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) +{ + JSObject *jsobj; + JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); + JSB_PRECONDITION( ok, "Error converting value to object"); + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + jsval vall, valb, valr, valt; + ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "l", &vall); + ok &= JS_GetProperty(cx, jsobj, "b", &valb); + ok &= JS_GetProperty(cx, jsobj, "r", &valr); + ok &= JS_GetProperty(cx, jsobj, "t", &valt); + JSB_PRECONDITION( ok, "Error obtaining point properties"); + + double l, b, r, t; + ok &= JS_ValueToNumber(cx, vall, &l); + ok &= JS_ValueToNumber(cx, valb, &b); + ok &= JS_ValueToNumber(cx, valr, &r); + ok &= JS_ValueToNumber(cx, valt, &t); + JSB_PRECONDITION( ok, "Error converting value to numbers"); + + ret->l = l; + ret->b = b; + ret->r = r; + ret->t = t; + + return JS_TRUE; +} + +jsval cpBB_to_jsval(JSContext *cx, cpBB bb ) +{ + JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); + if (!object) + return JSVAL_VOID; + + if (!JS_DefineProperty(cx, object, "l", DOUBLE_TO_JSVAL(bb.l), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "b", DOUBLE_TO_JSVAL(bb.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "r", DOUBLE_TO_JSVAL(bb.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "t", DOUBLE_TO_JSVAL(bb.t), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) + return JSVAL_VOID; + + return OBJECT_TO_JSVAL(object); +} + +// In order to be compatible with Chipmunk-JS API, +// this function expect to receive an array of numbers, and not an array of vects +// OK: [1,2, 3,4, 5,6] <- expected +// BAD: [{x:1, y:2}, {x:3,y:4}, {x:5, y:6}] <- not expected +JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts) +{ + // Parsing sequence + JSObject *jsobj; + JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); + JSB_PRECONDITION( ok, "Error converting value to object"); + + JSB_PRECONDITION( jsobj && JS_IsArrayObject( cx, jsobj), "Object must be an array"); + + uint32_t len; + JS_GetArrayLength(cx, jsobj, &len); + + JSB_PRECONDITION( len%2==0, "Array lenght should be even"); + + cpVect *array = (cpVect*)malloc( sizeof(cpVect) * len/2); + + for( uint32_t i=0; i< len;i++ ) { + jsval valarg; + JS_GetElement(cx, jsobj, i, &valarg); + + double value; + ok = JS_ValueToNumber(cx, valarg, &value); + JSB_PRECONDITION( ok, "Error converting value to nsobject"); + + if(i%2==0) + array[i/2].x = value; + else + array[i/2].y = value; + } + + *numVerts = len/2; + *verts = array; + + return JS_TRUE; +} + +#pragma mark - Collision Handler + +struct collision_handler { + cpCollisionType typeA; + cpCollisionType typeB; + + JSObject *begin; + JSObject *pre; + JSObject *post; + JSObject *separate; + JSObject *jsthis; + JSContext *cx; + + // "owner" of the collision handler + // Needed when the space goes out of scope, it will remove all the allocated collision handlers for him. + cpSpace *space; + + unsigned long hash_key; + + unsigned int is_oo; // Objected oriented API ? + UT_hash_handle hh; +}; + +// hash +struct collision_handler* collision_handler_hash = NULL; + +// helper pair +static unsigned long pair_ints( unsigned long A, unsigned long B ) +{ + // order is not important + unsigned long k1 = MIN(A, B ); + unsigned long k2 = MAX(A, B ); + + return (k1 + k2) * (k1 + k2 + 1) /2 + k2; +} + +static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) +{ + struct collision_handler *handler = (struct collision_handler*) data; + + jsval args[2]; + if( handler->is_oo ) { + args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); + args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); + } else { + args[0] = opaque_to_jsval( handler->cx, arb); + args[1] = opaque_to_jsval( handler->cx, space ); + } + + jsval rval; + JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); + JSB_PRECONDITION2(ok, handler->cx, cpFalse, "Error calling collision callback: begin"); + + if( JSVAL_IS_BOOLEAN(rval) ) { + JSBool ret = JSVAL_TO_BOOLEAN(rval); + return (cpBool)ret; + } + return cpTrue; +} + +static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) +{ + struct collision_handler *handler = (struct collision_handler*) data; + + jsval args[2]; + if( handler->is_oo ) { + args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); + args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); + } else { + args[0] = opaque_to_jsval( handler->cx, arb); + args[1] = opaque_to_jsval( handler->cx, space ); + } + + jsval rval; + JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); + JSB_PRECONDITION2(ok, handler->cx, JS_FALSE, "Error calling collision callback: pre"); + + if( JSVAL_IS_BOOLEAN(rval) ) { + JSBool ret = JSVAL_TO_BOOLEAN(rval); + return (cpBool)ret; + } + return cpTrue; +} + +static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) +{ + struct collision_handler *handler = (struct collision_handler*) data; + + jsval args[2]; + + if( handler->is_oo ) { + args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); + args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); + } else { + args[0] = opaque_to_jsval( handler->cx, arb); + args[1] = opaque_to_jsval( handler->cx, space ); + } + + jsval ignore; + JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); + JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Post"); +} + +static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) +{ + struct collision_handler *handler = (struct collision_handler*) data; + + jsval args[2]; + if( handler->is_oo ) { + args[0] = c_class_to_jsval(handler->cx, arb, JSB_cpArbiter_object, JSB_cpArbiter_class, "cpArbiter"); + args[1] = c_class_to_jsval(handler->cx, space, JSB_cpSpace_object, JSB_cpSpace_class, "cpArbiter"); + } else { + args[0] = opaque_to_jsval( handler->cx, arb); + args[1] = opaque_to_jsval( handler->cx, space ); + } + + jsval ignore; + JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); + JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Separate");} + +#pragma mark - cpSpace + +#pragma mark constructor / destructor + +void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *jsthis) +{ + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + if( proxy ) { + CCLOGINFO("jsbindings: finalizing JS object %p (cpSpace), handle: %p", jsthis, proxy->handle); + + // space + cpSpace *space = (cpSpace*) proxy->handle; + + + // Remove collision handlers, since the user might have forgotten to manually remove them + struct collision_handler *current, *tmp; + HASH_ITER(hh, collision_handler_hash, current, tmp) { + if( current->space == space ) { + + JSContext *cx = current->cx; + + // unroot it + if( current->begin ) { + JS_RemoveObjectRoot(cx, ¤t->begin); + } + if( current->pre ) + JS_RemoveObjectRoot(cx, ¤t->pre); + if( current->post ) + JS_RemoveObjectRoot(cx, ¤t->post); + if( current->separate ) + JS_RemoveObjectRoot(cx, ¤t->separate); + + HASH_DEL(collision_handler_hash,current); /* delete; users advances to next */ + free(current); /* optional- if you want to free */ + } + } + + // Free Space Children + freeSpaceChildren(space); + + jsb_del_jsobject_for_proxy(space); + if(proxy->flags == JSB_C_FLAG_CALL_FREE) + cpSpaceFree(space); + jsb_del_c_proxy_for_jsobject(jsthis); + } +} + + +#pragma mark addCollisionHandler + +static +JSBool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space, unsigned int is_oo) +{ + struct collision_handler *handler = (struct collision_handler*) malloc( sizeof(*handler) ); + + JSB_PRECONDITION(handler, "Error allocating memory"); + + JSBool ok = JS_TRUE; + + // args + ok &= jsval_to_int(cx, *argvp++, (int32_t*) &handler->typeA ); + ok &= jsval_to_int(cx, *argvp++, (int32_t*) &handler->typeB ); + + // this is no longer passed, so "this" is going to be "this". +// ok &= JS_ValueToObject(cx, *argvp++, &handler->jsthis ); + handler->jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + + handler->begin = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; + argvp++; + handler->pre = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; + argvp++; + handler->post = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; + argvp++; + handler->separate = !JSVAL_IS_NULL(*argvp) ? JSVAL_TO_OBJECT(*argvp) : NULL; + argvp++; + + JSB_PRECONDITION(ok, "Error parsing arguments"); + + // Object Oriented API ? + handler->is_oo = is_oo; + + // owner of the collision handler + handler->space = space; + + // Root it + if( handler->begin ) + JS_AddNamedObjectRoot(cx, &handler->begin, "begin collision_handler"); + if( handler->pre ) + JS_AddNamedObjectRoot(cx, &handler->pre, "pre collision_handler"); + if( handler->post ) + JS_AddNamedObjectRoot(cx, &handler->post, "post collision_handler"); + if( handler->separate ) + JS_AddNamedObjectRoot(cx, &handler->separate, "separate collision_handler"); + + handler->cx = cx; + + cpSpaceAddCollisionHandler(space, handler->typeA, handler->typeB, + !handler->begin ? NULL : &myCollisionBegin, + !handler->pre ? NULL : &myCollisionPre, + !handler->post ? NULL : &myCollisionPost, + !handler->separate ? NULL : &myCollisionSeparate, + handler ); + + + // + // Already added ? If so, remove it. + // Then add new entry + // + struct collision_handler *hashElement = NULL; + unsigned long paired_key = pair_ints(handler->typeA, handler->typeB ); + HASH_FIND_INT(collision_handler_hash, &paired_key, hashElement); + if( hashElement ) { + HASH_DEL( collision_handler_hash, hashElement ); + free( hashElement ); + } + + handler->hash_key = paired_key; + HASH_ADD_INT( collision_handler_hash, hash_key, handler ); + + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==7, cx, JS_FALSE, "Invalid number of arguments"); + + + jsval *argvp = JS_ARGV(cx,vp); + + // args + cpSpace *space; + JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); + JSB_PRECONDITION(ok, "Error parsing arguments"); + + return __jsb_cpSpace_addCollisionHandler(cx, vp, argvp, space, 0); +} + +// method +JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==6, cx, JS_FALSE, "Invalid number of arguments"); + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + return __jsb_cpSpace_addCollisionHandler(cx, vp, JS_ARGV(cx,vp), (cpSpace*)handle, 1); +} + +#pragma mark removeCollisionHandler + +static +JSBool __jsb_cpSpace_removeCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space) +{ + JSBool ok = JS_TRUE; + + cpCollisionType typeA; + cpCollisionType typeB; + ok &= jsval_to_int(cx, *argvp++, (int32_t*) &typeA ); + ok &= jsval_to_int(cx, *argvp++, (int32_t*) &typeB ); + + JSB_PRECONDITION(ok, "Error parsing arguments"); + + cpSpaceRemoveCollisionHandler(space, typeA, typeB ); + + // Remove it + struct collision_handler *hashElement = NULL; + unsigned long key = pair_ints(typeA, typeB ); + HASH_FIND_INT(collision_handler_hash, &key, hashElement); + if( hashElement ) { + + // unroot it + if( hashElement->begin ) + JS_RemoveObjectRoot(cx, &hashElement->begin); + if( hashElement->pre ) + JS_RemoveObjectRoot(cx, &hashElement->pre); + if( hashElement->post ) + JS_RemoveObjectRoot(cx, &hashElement->post); + if( hashElement->separate ) + JS_RemoveObjectRoot(cx, &hashElement->separate); + + HASH_DEL( collision_handler_hash, hashElement ); + free( hashElement ); + } + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Free function +JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + + cpSpace* space; + JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); + + JSB_PRECONDITION(ok, "Error parsing arguments"); + + return __jsb_cpSpace_removeCollisionHandler(cx, vp, argvp, space); +} + +// method +JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + return __jsb_cpSpace_removeCollisionHandler(cx, vp, JS_ARGV(cx,vp), (cpSpace*)handle); +} + +#pragma mark Add functios. Root JSObjects + +// Arguments: cpBody* +// Ret value: cpBody* +JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpBody* arg1; + + jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceAddBody((cpSpace*)arg0 , (cpBody*)arg1 ); + + // Root it: + JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpBody"); + + // addBody returns the same object that was added, so return it without conversions + JS_SET_RVAL(cx, vp, retval); + + return JS_TRUE; +} + +// Arguments: cpConstraint* +// Ret value: cpConstraint* +JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpConstraint* arg1; + + jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceAddConstraint((cpSpace*)arg0 , (cpConstraint*)arg1 ); + + // Root it: + JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpConstraint"); + + // addConstraint returns the same object that was added, so return it without conversions + JS_SET_RVAL(cx, vp, retval); + + return JS_TRUE; +} + +// Arguments: cpShape* +// Ret value: cpShape* +JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpShape* arg1; + + jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceAddShape((cpSpace*)arg0 , (cpShape*)arg1 ); + + // Root it: + JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpShape"); + + // addShape returns the same object that was added, so return it without conversions + JS_SET_RVAL(cx, vp, retval); + + return JS_TRUE; +} + +// Arguments: cpShape* +// Ret value: cpShape* +JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpShape* arg1; + + jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceAddStaticShape((cpSpace*)arg0 , (cpShape*)arg1 ); + + // Root it: + JS_AddNamedObjectRoot(cx, &retproxy->jsobj, "cpShape (static)"); + + // addStaticShape returns the same object that was added, so return it without conversions + JS_SET_RVAL(cx, vp, retval); + + return JS_TRUE; +} + +#pragma mark Remove functios. Untoot JSObjects + +// Arguments: cpBody* +// Ret value: void +JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpBody* arg1; + + struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceRemoveBody((cpSpace*)arg0 , (cpBody*)arg1 ); + JS_RemoveObjectRoot(cx, &retproxy->jsobj); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: cpConstraint* +// Ret value: void +JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpConstraint* arg1; + + struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceRemoveConstraint((cpSpace*)arg0 , (cpConstraint*)arg1 ); + JS_RemoveObjectRoot(cx, &retproxy->jsobj); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: cpShape* +// Ret value: void +JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpShape* arg1; + + struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceRemoveShape((cpSpace*)arg0 , (cpShape*)arg1 ); + JS_RemoveObjectRoot(cx, &retproxy->jsobj); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: cpShape* +// Ret value: void +JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); + cpSpace* arg0 = (cpSpace*) proxy->handle; + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpShape* arg1; + + struct jsb_c_proxy_s *retproxy; + ok &= jsval_to_c_class( cx, *argvp++, (void**)&arg1, &retproxy ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpSpaceRemoveStaticShape((cpSpace*)arg0 , (cpShape*)arg1 ); + JS_RemoveObjectRoot(cx, &retproxy->jsobj); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} +#pragma mark - Arbiter + +#pragma mark getBodies +static +JSBool __jsb_cpArbiter_getBodies(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) +{ + cpBody *bodyA; + cpBody *bodyB; + cpArbiterGetBodies(arbiter, &bodyA, &bodyB); + + jsval valA, valB; + if( is_oo ) { + valA = c_class_to_jsval(cx, bodyA, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); + valB = c_class_to_jsval(cx, bodyB, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); + } else { + valA = opaque_to_jsval(cx, bodyA); + valB = opaque_to_jsval(cx, bodyB); + } + + JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); + JS_SetElement(cx, jsobj, 0, &valA); + JS_SetElement(cx, jsobj, 1, &valB); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); + + return JS_TRUE; +} + +// Free function +JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + + cpArbiter* arbiter; + if( ! jsval_to_opaque( cx, *argvp++, (void**)&arbiter ) ) + return JS_FALSE; + + return __jsb_cpArbiter_getBodies(cx, vp, argvp, arbiter, 0); +} + +// Method +JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + JSB_PRECONDITION( proxy, "Invalid private object"); + void *handle = proxy->handle; + + return __jsb_cpArbiter_getBodies(cx, vp, JS_ARGV(cx,vp), (cpArbiter*)handle, 1); +} + +#pragma mark getShapes +static +JSBool __jsb_cpArbiter_getShapes(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) +{ + cpShape *shapeA; + cpShape *shapeB; + cpArbiterGetShapes(arbiter, &shapeA, &shapeB); + + jsval valA, valB; + if( is_oo ) { + valA = c_class_to_jsval(cx, shapeA, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); + valB = c_class_to_jsval(cx, shapeB, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); + } else { + valA = opaque_to_jsval(cx, shapeA); + valB = opaque_to_jsval(cx, shapeB); + } + + JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); + JS_SetElement(cx, jsobj, 0, &valA); + JS_SetElement(cx, jsobj, 1, &valB); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); + + return JS_TRUE; +} + +// function +JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + + cpArbiter* arbiter; + if( ! jsval_to_opaque( cx, *argvp++, (void**) &arbiter ) ) + return JS_FALSE; + + return __jsb_cpArbiter_getShapes(cx, vp, argvp, arbiter, 0); +} + +// method +JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + return __jsb_cpArbiter_getShapes(cx, vp, JS_ARGV(cx,vp), (cpArbiter*)handle, 1); +} + +#pragma mark - Body + +#pragma mark constructor + +// Manually added to identify static vs dynamic bodies +JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + JSObject *jsobj = JS_NewObject(cx, JSB_cpBody_class, JSB_cpBody_object, NULL); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + double m; double i; + + ok &= JS_ValueToNumber( cx, *argvp++, &m ); + ok &= JS_ValueToNumber( cx, *argvp++, &i ); + JSB_PRECONDITION(ok, "Error processing arguments"); + + cpBody *ret_body = NULL; + if( m == INFINITY && i == INFINITY) { + ret_body = cpBodyNewStatic(); + + // XXX: Hack. IT WILL LEAK "rogue" objects., But at least it prevents a crash. + // The thing is that "rogue" bodies needs to be freed after the its shape, and I am not sure + // how to do it in a "js" way. + jsb_set_c_proxy_for_jsobject(jsobj, ret_body, JSB_C_FLAG_DO_NOT_CALL_FREE); + } else { + ret_body = cpBodyNew((cpFloat)m , (cpFloat)i ); + jsb_set_c_proxy_for_jsobject(jsobj, ret_body, JSB_C_FLAG_CALL_FREE); + } + + jsb_set_jsobject_for_proxy(jsobj, ret_body); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); + return JS_TRUE; +} + +#pragma mark getUserData + +static +JSBool __jsb_cpBody_getUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) +{ + JSObject *data = (JSObject*) cpBodyGetUserData(body); + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(data)); + + return JS_TRUE; +} + +// free function +JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + cpBody *body; + if( ! jsval_to_opaque( cx, *argvp++, (void**) &body ) ) + return JS_FALSE; + + return __jsb_cpBody_getUserData(cx, vp, argvp, body); +} + +// method +JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + return __jsb_cpBody_getUserData(cx, vp, JS_ARGV(cx,vp), (cpBody*)handle); +} + + +#pragma mark setUserData + +static +JSBool __jsb_cpBody_setUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) +{ + JSObject *jsobj; + + JSBool ok = JS_ValueToObject(cx, *argvp++, &jsobj); + + JSB_PRECONDITION(ok, "Error parsing arguments"); + + cpBodySetUserData(body, jsobj); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + + return JS_TRUE; +} + +// free function +JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + cpBody *body; + JSBool ok = jsval_to_opaque( cx, *argvp++, (void**) &body ); + JSB_PRECONDITION(ok, "Error parsing arguments"); + return __jsb_cpBody_setUserData(cx, vp, argvp, body); +} + +// method +JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + return __jsb_cpBody_setUserData(cx, vp, JS_ARGV(cx,vp), (cpBody*)handle); +} + +#pragma mark - Poly related + +// cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts); +JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpVect *verts; + int numVerts; + + ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing array"); + + cpFloat area = cpAreaForPoly(numVerts, verts); + + free(verts); + + JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(area)); + return JS_TRUE; +} + +// cpFloat cpMomentForPoly(cpFloat m, int numVerts, const cpVect *verts, cpVect offset); +JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpVect *verts; cpVect offset; + int numVerts; + double m; + + ok &= JS_ValueToNumber(cx, *argvp++, &m); + ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); + ok &= jsval_to_cpVect( cx, *argvp++, (cpVect*) &offset ); + + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); + + cpFloat moment = cpMomentForPoly((cpFloat)m, numVerts, verts, offset); + + free(verts); + + JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(moment)); + return JS_TRUE; +} + +// cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts); +JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpVect *verts; + int numVerts; + + ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); + + cpVect centroid = cpCentroidForPoly(numVerts, verts); + + free(verts); + + JS_SET_RVAL(cx, vp, cpVect_to_jsval(cx, (cpVect)centroid)); + return JS_TRUE; +} + +// void cpRecenterPoly(const int numVerts, cpVect *verts); +JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp) +{ + CCASSERT(false, "NOT IMPLEMENTED"); + return JS_FALSE; +} + +#pragma mark - Object Oriented Chipmunk + +/* + * Chipmunk Base Object + */ + +JSClass* JSB_cpBase_class = NULL; +JSObject* JSB_cpBase_object = NULL; +// Constructor +JSBool JSB_cpBase_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2( argc==1, cx, JS_FALSE, "Invalid arguments. Expecting 1"); + + JSObject *jsobj = JS_NewObject(cx, JSB_cpBase_class, JSB_cpBase_object, NULL); + + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + + void *handle = NULL; + + ok = jsval_to_opaque(cx, *argvp++, &handle); + + JSB_PRECONDITION(ok, "Error converting arguments for JSB_cpBase_constructor"); + + jsb_set_c_proxy_for_jsobject(jsobj, handle, JSB_C_FLAG_DO_NOT_CALL_FREE); + jsb_set_jsobject_for_proxy(jsobj, handle); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); + return JS_TRUE; +} + +// Destructor +void JSB_cpBase_finalize(JSFreeOp *fop, JSObject *obj) +{ + CCLOGINFO("jsbindings: finalizing JS object %p (cpBase)", obj); + + // should not delete the handle since it was manually added +} + +JSBool JSB_cpBase_getHandle(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + + struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); + void *handle = proxy->handle; + + jsval ret_val = opaque_to_jsval(cx, handle); + JS_SET_RVAL(cx, vp, ret_val); + return JS_TRUE; +} + +JSBool JSB_cpBase_setHandle(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); + JSB_PRECONDITION( jsthis, "Invalid jsthis object"); + JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + + jsval *argvp = JS_ARGV(cx,vp); + + void *handle; + JSBool ok = jsval_to_opaque(cx, *argvp++, &handle); + JSB_PRECONDITION( ok, "Invalid parsing arguments"); + + jsb_set_c_proxy_for_jsobject(jsthis, handle, JSB_C_FLAG_DO_NOT_CALL_FREE); + jsb_set_jsobject_for_proxy(jsthis, handle); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + + +void JSB_cpBase_createClass(JSContext *cx, JSObject* globalObj, const char* name ) +{ + JSB_cpBase_class = (JSClass *)calloc(1, sizeof(JSClass)); + JSB_cpBase_class->name = name; + JSB_cpBase_class->addProperty = JS_PropertyStub; + JSB_cpBase_class->delProperty = JS_DeletePropertyStub; + JSB_cpBase_class->getProperty = JS_PropertyStub; + JSB_cpBase_class->setProperty = JS_StrictPropertyStub; + JSB_cpBase_class->enumerate = JS_EnumerateStub; + JSB_cpBase_class->resolve = JS_ResolveStub; + JSB_cpBase_class->convert = JS_ConvertStub; + JSB_cpBase_class->finalize = JSB_cpBase_finalize; + JSB_cpBase_class->flags = JSCLASS_HAS_PRIVATE; + + static JSPropertySpec properties[] = { + {0, 0, 0, 0, 0} + }; + static JSFunctionSpec funcs[] = { + JS_FN("getHandle", JSB_cpBase_getHandle, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setHandle", JSB_cpBase_setHandle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + static JSFunctionSpec st_funcs[] = { + JS_FS_END + }; + + JSB_cpBase_object = JS_InitClass(cx, globalObj, NULL, JSB_cpBase_class, JSB_cpBase_constructor,0,properties,funcs,NULL,st_funcs); + JSBool found; + JS_SetPropertyAttributes(cx, globalObj, name, JSPROP_ENUMERATE | JSPROP_READONLY, &found); +} + +// Manual "methods" +// Constructor +JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + JSObject *jsobj = JS_NewObject(cx, JSB_cpPolyShape_class, JSB_cpPolyShape_object, NULL); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + cpBody* body; cpVect *verts; cpVect offset; + int numVerts; + + ok &= jsval_to_c_class( cx, *argvp++, (void**)&body, NULL ); + ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); + ok &= jsval_to_cpVect( cx, *argvp++, (cpVect*) &offset ); + JSB_PRECONDITION(ok, "Error processing arguments"); + cpShape *shape = cpPolyShapeNew(body, numVerts, verts, offset); + + jsb_set_c_proxy_for_jsobject(jsobj, shape, JSB_C_FLAG_DO_NOT_CALL_FREE); + jsb_set_jsobject_for_proxy(jsobj, shape); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); + + free(verts); + + return JS_TRUE; +} + + +#pragma mark Space Free functions +// +// When the space is removed, it should all remove its children. But not "free" them. +// "free" will be performed by the JS Garbage Collector +// +// Functions copied & pasted from ChipmunkDemo.c +// https://github.com/slembcke/Chipmunk-Physics/blob/master/Demo/ChipmunkDemo.c#L89 +// + +static void unroot_jsobject_from_handle(void *handle) +{ + JSObject *jsobj = jsb_get_jsobject_for_proxy(handle); + struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsobj); + + // HACK context from global + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &proxy->jsobj); + +} +static void shapeFreeWrap(cpSpace *space, cpShape *shape, void *unused){ + cpSpaceRemoveShape(space, shape); + unroot_jsobject_from_handle(shape); +// cpShapeFree(shape); +} + +static void postShapeFree(cpShape *shape, cpSpace *space){ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)shapeFreeWrap, shape, NULL); +} + +static void constraintFreeWrap(cpSpace *space, cpConstraint *constraint, void *unused){ + cpSpaceRemoveConstraint(space, constraint); + unroot_jsobject_from_handle(constraint); +// cpConstraintFree(constraint); +} + +static void postConstraintFree(cpConstraint *constraint, cpSpace *space){ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)constraintFreeWrap, constraint, NULL); +} + +static void bodyFreeWrap(cpSpace *space, cpBody *body, void *unused){ + cpSpaceRemoveBody(space, body); + unroot_jsobject_from_handle(body); +// cpBodyFree(body); +} + +static void postBodyFree(cpBody *body, cpSpace *space){ + cpSpaceAddPostStepCallback(space, (cpPostStepFunc)bodyFreeWrap, body, NULL); +} + +// Safe and future proof way to remove and free all objects that have been added to the space. +void static freeSpaceChildren(cpSpace *space) +{ + // Must remove these BEFORE freeing the body or you will access dangling pointers. + cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)postShapeFree, space); + cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)postConstraintFree, space); + + cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)postBodyFree, space); +} + +#endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h new file mode 100644 index 0000000000..c6b40ca757 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h @@ -0,0 +1,103 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 __js_bindings_chipmunk_manual +#define __js_bindings_chipmunk_manual + +#include "js_bindings_config.h" +#include "cocosjs_manual_conversions.h" +#include "js_manual_conversions.h" +#include "ScriptingCore.h" +#ifdef JSB_INCLUDE_CHIPMUNK + +#include "chipmunk.h" +#include "jsapi.h" + +#include "js_bindings_chipmunk_auto_classes.h" + +// Free Functions +JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); + +JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp); + +JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp); + +// poly related +JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp); + +// "Methods" from the OO API +JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); + +// manually wrapped for rooting/unrooting purposes +JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp); + + +JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp); + +JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp); + + +// convertions + +jsval cpBB_to_jsval(JSContext *cx, cpBB bb ); +JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ); +JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts); + +// requires cocos2d +#define cpVect_to_jsval CGPoint_to_jsval +#define jsval_to_cpVect jsval_to_CGPoint + + +// Object Oriented Chipmunk +void JSB_cpBase_createClass(JSContext* cx, JSObject* globalObj, const char * name ); +extern JSObject* JSB_cpBase_object; +extern JSClass* JSB_cpBase_class; +extern void register_CCPhysicsSprite(JSContext *cx, JSObject *obj); +extern void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj); + +// Manual constructor / destructors +JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp); +void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *obj); + +#endif // JSB_INCLUDE_CHIPMUNK + +#endif // __js_bindings_chipmunk_manual diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp new file mode 100644 index 0000000000..a96434eace --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp @@ -0,0 +1,67 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 JSB_INCLUDE_CHIPMUNK +#define JSB_INCLUDE_CHIPMUNK +#endif + +#include "js_bindings_config.h" +#include "ScriptingCore.h" + + +// chipmunk +#include "js_bindings_chipmunk_auto_classes.h" +#include "js_bindings_chipmunk_functions.h" +#include "js_bindings_chipmunk_manual.h" + + +void jsb_register_chipmunk(JSContext *_cx, JSObject *object) +{ + // + // Chipmunk + // + JSObject *chipmunk = JS_NewObject(_cx, NULL, NULL, NULL); + jsval chipmunkVal = OBJECT_TO_JSVAL(chipmunk); + JS_SetProperty(_cx, object, "cp", &chipmunkVal); + + JSB_cpBase_createClass(_cx, chipmunk, "Base"); // manual base class registration +#include "js_bindings_chipmunk_auto_classes_registration.h" +#include "js_bindings_chipmunk_functions_registration.h" + + // manual + JS_DefineFunction(_cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + + JS_DefineFunction(_cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(_cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + register_CCPhysicsSprite(_cx, object); + register_CCPhysicsDebugNode(_cx, object); +} + diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.h new file mode 100644 index 0000000000..90bc320b87 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.h @@ -0,0 +1,31 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 __JSB_CHIPMUNK_REGISTRATION +#define __JSB_CHIPMUNK_REGISTRATION + +void jsb_register_chipmunk( JSContext *globalC, JSObject *globalO); + +#endif // __JSB_CHIPMUNK_REGISTRATION diff --git a/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj new file mode 100644 index 0000000000..9148f9376f --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj @@ -0,0 +1,121 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + + + {21070E58-EEC6-4E16-8B4F-6D083DF55790} + Win32Proj + libJSBindingForChipmunk + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.filters b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.filters new file mode 100644 index 0000000000..43253970bc --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.filters @@ -0,0 +1,47 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + manual + + + manual + + + manual + + + manual + + + manual + + + manual + + + + + manual + + + manual + + + manual + + + manual + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.user b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp new file mode 100644 index 0000000000..f6b3252c57 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp @@ -0,0 +1,23 @@ +#ifndef __JS_COCOSBUILDER_SPECIFICS_H__ +#define __JS_COCOSBUILDER_SPECIFICS_H__ + +#include "../cocos2d_specifics.hpp" + +class JSCCBAnimationWrapper: public JSCallbackWrapper { +public: + JSCCBAnimationWrapper() {} + virtual ~JSCCBAnimationWrapper() {} + + void animationCompleteCallback() { + + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + jsval retval = JSVAL_NULL; + + if(!JSVAL_IS_VOID(_jsCallback) && !JSVAL_IS_VOID(_jsThisObj)) { + JS_CallFunctionValue(cx, JSVAL_TO_OBJECT(_jsThisObj), _jsCallback, 0, NULL, &retval); + } + } + +}; + +#endif diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp new file mode 100644 index 0000000000..733ac47b45 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp @@ -0,0 +1,324 @@ +// +// js_bindings_ccbreader.cpp +// watermelon +// +// Created by Rohan Kuruvilla on 14/08/2012. +// +// + +#include "js_bindings_ccbreader.h" +#include "ScriptingCore.h" +#include "js_bindings_config.h" + +USING_NS_CC; +USING_NS_CC_EXT; +using namespace cocosbuilder; + +static void removeSelector(std::string &str) { + size_t found; + found = str.find(":"); + while (found!=std::string::npos){ + str.replace(found, found+1, ""); + found = str.find(":"); + } +} + +SEL_MenuHandler CCBScriptCallbackProxy::onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, + const char * pSelectorName) { + this->callBackProp = pSelectorName; + removeSelector(this->callBackProp); + return menu_selector(CCBScriptCallbackProxy::menuItemCallback); +} + +Control::Handler CCBScriptCallbackProxy::onResolveCCBCCControlSelector(Object * pTarget, + const char * pSelectorName) { + + this->callBackProp = pSelectorName; + removeSelector(this->callBackProp); + return cccontrol_selector(CCBScriptCallbackProxy::controlCallback); +} + +bool CCBScriptCallbackProxy::onAssignCCBMemberVariable(Object * pTarget, + const char * pMemberVariableName, + Node * pNode) { + return true; +} + +void CCBScriptCallbackProxy::onNodeLoaded(Node * pNode, + NodeLoader * pNodeLoader) {} + +CCBSelectorResolver * CCBScriptCallbackProxy::createNew() { + CCBScriptCallbackProxy * ret = new CCBScriptCallbackProxy(); + ret->setJSOwner(this->owner); + return dynamic_cast(ret); +} + +void CCBScriptCallbackProxy::menuItemCallback(Object *pSender) { + ScriptingCore::getInstance()->executeFunctionWithOwner(owner, callBackProp.c_str() ); +} + +void CCBScriptCallbackProxy::controlCallback(Object *pSender, Control::EventType event) { + ScriptingCore::getInstance()->executeFunctionWithOwner(owner, callBackProp.c_str() ); +} + +void CCBScriptCallbackProxy::setCallbackProperty(const char *prop) { + callBackProp = prop; +} + +void CCBScriptCallbackProxy::setJSOwner(jsval ownr) { + owner = ownr; +} + +jsval CCBScriptCallbackProxy::getJSOwner() { + return owner; +} + +JSBool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, uint32_t argc, jsval *vp) +{ + if (argc >= 1) { + jsval *argv = JS_ARGV(cx, vp); + + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocosbuilder::CCBAnimationManager *node = (cocosbuilder::CCBAnimationManager *)(proxy ? proxy->ptr : NULL); + + JSCCBAnimationWrapper *tmpCobj = new JSCCBAnimationWrapper(); + tmpCobj->autorelease(); + + tmpCobj->setJSCallbackThis(argv[0]); + if(argc >= 2) { + tmpCobj->setJSCallbackFunc(argv[1]); + } + + node->setAnimationCompletedCallback(tmpCobj, callfunc_selector(JSCCBAnimationWrapper::animationCompleteCallback)); + + JS_SetReservedSlot(proxy->obj, 0, argv[0]); + JS_SetReservedSlot(proxy->obj, 1, argv[1]); + return JS_TRUE; + } + return JS_FALSE; +} + +JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSBool ok = JS_TRUE; + JSObject *obj; + cocosbuilder::CCBReader* cobj; + obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, cobj) + + if (argc == 2) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + cocos2d::Object* arg1; + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); + proxy = jsb_get_js_proxy(tmpObj); + arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg1) + } while (0); + + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + if (argc == 1) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + if (argc == 3) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + cocos2d::Object* arg1; + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); + proxy = jsb_get_js_proxy(tmpObj); + arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg1) + } while (0); + cocos2d::Size arg2; + ok &= jsval_to_ccsize(cx, argv[2], &arg2); + + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1, arg2); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + return JS_FALSE; +} + +JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSBool ok = JS_TRUE; + JSObject *obj; + cocosbuilder::CCBReader* cobj; + obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cobj = (cocosbuilder::CCBReader *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, cobj) + + if (argc == 2) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + cocos2d::Object* arg1; + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); + proxy = jsb_get_js_proxy(tmpObj); + arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg1) + } while (0); + + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + if (argc == 1) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + if (argc == 3) { + const char* arg0; + std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); + cocos2d::Object* arg1; + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]); + proxy = jsb_get_js_proxy(tmpObj); + arg1 = (cocos2d::Object*)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg1) + } while (0); + cocos2d::Size arg2; + ok &= jsval_to_ccsize(cx, argv[2], &arg2); + + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1, arg2); + jsval jsret; do { + if (ret) { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + + return JS_FALSE; +} + + +JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) +{ + + NodeLoaderLibrary * ccNodeLoaderLibrary = NodeLoaderLibrary::getInstance(); + + ccNodeLoaderLibrary->registerNodeLoader("", JSLayerLoader::loader()); + + CCBReader * ret = new CCBReader(ccNodeLoaderLibrary); + ret->autorelease(); + + jsval jsret; + if (ret) { + js_proxy_t *proxy = jsb_get_native_proxy(ret); + if (proxy) { + jsret = OBJECT_TO_JSVAL(proxy->obj); + } else { + // create a new js obj of that class + proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } + } else { + jsret = JSVAL_NULL; + } + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + +} + +extern JSObject* jsb_CCBReader_prototype; +extern JSObject* jsb_CCBAnimationManager_prototype; + +void register_CCBuilderReader(JSContext *cx, JSObject *obj) { + jsval nsval; + JSObject *ns; + JS_GetProperty(cx, obj, "cc", &nsval); + if (nsval == JSVAL_VOID) { + ns = JS_NewObject(cx, NULL, NULL, NULL); + nsval = OBJECT_TO_JSVAL(ns); + JS_SetProperty(cx, obj, "cc", &nsval); + } else { + JS_ValueToObject(cx, nsval, &ns); + } + obj = ns; + + JSObject *tmpObj = JSVAL_TO_OBJECT(anonEvaluate(cx, obj, "(function () { return cc._Reader; })()")); + JS_DefineFunction(cx, tmpObj, "create", js_CocosBuilder_create, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, tmpObj, "loadScene", js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, jsb_CCBReader_prototype, "load", js_cocos2dx_CCBReader_readNodeGraphFromFile, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_CCBAnimationManager_prototype, "setCompletedAnimationCallback", js_cocos2dx_CCBAnimationManager_animationCompleteCallback, 2, JSPROP_READONLY | JSPROP_PERMANENT); +} diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h new file mode 100644 index 0000000000..b1b3b187cc --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h @@ -0,0 +1,60 @@ +// +// js_bindings_ccbreader.h +// watermelon +// +// Created by Rohan Kuruvilla on 14/08/2012. +// +// +#ifndef __JS_BINDINGS_CCBREADER_H__ +#define __JS_BINDINGS_CCBREADER_H__ + +#include "jsapi.h" +#include "cocosbuilder_specifics.hpp" +#include "cocosbuilder/CocosBuilder.h" + +class CCBScriptCallbackProxy: public cocos2d::Layer +, public cocosbuilder::CCBSelectorResolver +, public cocosbuilder::CCBMemberVariableAssigner { + + std::string callBackProp; + jsval owner; + +public: + + + CCBScriptCallbackProxy () {} + virtual ~CCBScriptCallbackProxy() {} + + CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(CCBScriptCallbackProxy, create); + virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::Object * pTarget, + const char * pSelectorName); + + virtual cocos2d::extension::Control::Handler onResolveCCBCCControlSelector(cocos2d::Object * pTarget, + const char * pSelectorName); + virtual bool onAssignCCBMemberVariable(cocos2d::Object * pTarget, const char * pMemberVariableName, + cocos2d::Node * pNode); + virtual void onNodeLoaded(cocos2d::Node * pNode, + cocosbuilder::NodeLoader * pNodeLoader); + + virtual CCBSelectorResolver * createNew(); + void menuItemCallback(Object *pSender); + void controlCallback(Object *pSender, cocos2d::extension::Control::EventType event); + void setCallbackProperty(const char *prop); + void setJSOwner(jsval ownr); + jsval getJSOwner(); +}; + + +class JSLayerLoader : public cocosbuilder::LayerLoader { +public: + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(JSLayerLoader, loader); + +protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCBScriptCallbackProxy); +}; + +void register_CCBuilderReader(JSContext *cx, JSObject *global); +JSBool js_CocosBuilder_Run(JSContext *cx, uint32_t argc, jsval *vp); + +#endif /* __JS_BINDINGS_CCBREADER_H__ */ + diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj new file mode 100644 index 0000000000..d6f2eb8d12 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj @@ -0,0 +1,119 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + + {F9DA0FC1-651B-457B-962E-A4D61CEBF5FD} + Win32Proj + libJSBindingForBuilder + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.filters b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.filters new file mode 100644 index 0000000000..6746ab6be9 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.filters @@ -0,0 +1,37 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + generated + + + manual + + + + + generated + + + manual + + + manual + + + + + generated + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.user b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp new file mode 100644 index 0000000000..34ecbca985 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -0,0 +1,229 @@ +// +// jsb_cocos2dx_studio_manual.h +// +// Created by LinWenhai on 20/10/13. +// +// +#include "jsb_cocos2dx_studio_manual.h" +#include "ScriptingCore.h" +#include "cocos2d_specifics.hpp" +#include "cocostudio/CocoStudio.h" + +class JSArmatureWrapper: public JSCallbackWrapper { +public: + JSArmatureWrapper(); + virtual ~JSArmatureWrapper(); + + virtual void setJSCallbackThis(jsval thisObj); + + void movementCallbackFunc(cocostudio::Armature * pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId); + void frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + void addArmatureFileInfoAsyncCallbackFunc(float percent); + +private: + bool m_bNeedUnroot; +}; + +JSArmatureWrapper::JSArmatureWrapper() + : m_bNeedUnroot(false) +{ + +} + +JSArmatureWrapper::~JSArmatureWrapper() +{ + if (m_bNeedUnroot) + { + JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &thisObj); + } +} + +void JSArmatureWrapper::setJSCallbackThis(jsval _jsThisObj) +{ + JSCallbackWrapper::setJSCallbackThis(_jsThisObj); + + JSObject *thisObj = JSVAL_TO_OBJECT(_jsThisObj); + js_proxy *p = jsb_get_js_proxy(thisObj); + if (!p) + { + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddObjectRoot(cx, &thisObj); + m_bNeedUnroot = true; + } +} + +void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, cocostudio::MovementEventType pMovementEventType, const char *pMovementId) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + js_proxy_t *proxy = js_get_or_create_proxy(cx, pArmature); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + int movementEventType = (int)pMovementEventType; + jsval movementVal = INT_TO_JSVAL(movementEventType); + + jsval idVal = c_string_to_jsval(cx, pMovementId); + + jsval valArr[3]; + valArr[0] = OBJECT_TO_JSVAL(proxy->obj); + valArr[1] = movementVal; + valArr[2] = idVal; + + JS_AddValueRoot(cx, valArr); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); + JS_RemoveValueRoot(cx, valArr); + } +} + +void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + jsval percentVal = DOUBLE_TO_JSVAL(percent); + + JS_AddValueRoot(cx, &percentVal); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); + JS_RemoveValueRoot(cx, &percentVal); + } +} + + +void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) +{ + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); + js_proxy_t *proxy = js_get_or_create_proxy(cx, pBone); + jsval retval; + if (_jsCallback != JSVAL_VOID) + { + jsval nameVal = c_string_to_jsval(cx, frameEventName); + jsval originIndexVal = INT_TO_JSVAL(originFrameIndex); + jsval currentIndexVal = INT_TO_JSVAL(currentFrameIndex); + + jsval valArr[4]; + valArr[0] = OBJECT_TO_JSVAL(proxy->obj); + valArr[1] = nameVal; + valArr[2] = originIndexVal; + valArr[3] = currentIndexVal; + + JS_AddValueRoot(cx, valArr); + JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); + JS_RemoveValueRoot(cx, valArr); + } +} + +static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 2) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[0]); + tmpObj->setJSCallbackThis(argv[1]); + + cobj->setMovementEventCallFunc(tmpObj, movementEvent_selector(JSArmatureWrapper::movementCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + +static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 2) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[0]); + tmpObj->setJSCallbackThis(argv[1]); + + cobj->setFrameEventCallFunc(tmpObj, frameEvent_selector(JSArmatureWrapper::frameCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + +static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 3) { + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[2]); + tmpObj->setJSCallbackThis(argv[1]); + + std::string ret; + jsval_to_std_string(cx, argv[0], &ret); + + cobj->addArmatureFileInfoAsync(ret.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); + + return JS_TRUE; + } + + if(argc == 5){ + jsval *argv = JS_ARGV(cx, vp); + + JSArmatureWrapper *tmpObj = new JSArmatureWrapper(); + tmpObj->autorelease(); + + tmpObj->setJSCallbackFunc(argv[4]); + tmpObj->setJSCallbackThis(argv[3]); + + std::string imagePath; + jsval_to_std_string(cx ,argv[0] , &imagePath); + + std::string plistPath; + jsval_to_std_string(cx ,argv[1] , &plistPath); + + std::string configFilePath; + jsval_to_std_string(cx ,argv[2] , &configFilePath); + + cobj->addArmatureFileInfoAsync(imagePath.c_str(), plistPath.c_str(), configFilePath.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); + + return JS_TRUE; + } + JS_ReportError(cx, "Invalid number of arguments"); + return JS_FALSE; +} + +extern JSObject* jsb_ArmatureAnimation_prototype; +extern JSObject* jsb_ArmatureDataManager_prototype; + +void register_all_cocos2dx_studio_manual(JSContext* cx, JSObject* global) +{ + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setMovementEventCallFunc", js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setFrameEventCallFunc", js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, jsb_ArmatureDataManager_prototype, "addArmatureFileInfoAsync", jsb_Animation_addArmatureFileInfoAsyncCallFunc, 3, JSPROP_READONLY | JSPROP_PERMANENT); +} \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.h b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.h new file mode 100644 index 0000000000..35ebd55755 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.h @@ -0,0 +1,16 @@ +// +// jsb_cocos2dx_studio_manual.h +// +// Created by LinWenhai on 20/10/13. +// +// + +#ifndef __jsb_cocos2dx_studio_manual__ +#define __jsb_cocos2dx_studio_manual__ + +#include "jsapi.h" +#include "jsfriendapi.h" + +void register_all_cocos2dx_studio_manual(JSContext* cx, JSObject* global); + +#endif /* defined(__jsb_cocos2dx_studio_manual__) */ diff --git a/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj new file mode 100644 index 0000000000..2212730521 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj @@ -0,0 +1,118 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + {79D34511-E54E-410A-8BBA-EF175AD6C695} + Win32Proj + libJSBindingForStudio + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.filters b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.filters new file mode 100644 index 0000000000..16be2bb316 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.filters @@ -0,0 +1,34 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + generated + + + manual + + + + + generated + + + manual + + + + + generated + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.user b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp new file mode 100644 index 0000000000..9f2ab82470 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp @@ -0,0 +1,799 @@ +// +// jsb_cocos2d_extension_manual.cpp +// +// Created by James Chen on 3/11/13. +// +// + +#include "jsb_cocos2dx_extension_manual.h" +#include "extensions/cocos-ext.h" +#include "ScriptingCore.h" +#include "cocos2d_specifics.hpp" + +USING_NS_CC; +USING_NS_CC_EXT; + + +class JSB_ScrollViewDelegate +: public Object +, public ScrollViewDelegate +{ +public: + JSB_ScrollViewDelegate() + : _JSDelegate(NULL) + , _needUnroot(false) + {} + + virtual ~JSB_ScrollViewDelegate() + { + if (_needUnroot) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &_JSDelegate); + } + } + + virtual void scrollViewDidScroll(ScrollView* view) + { + js_proxy_t * p = jsb_get_native_proxy(view); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "scrollViewDidScroll", 1, &arg, NULL); + } + + virtual void scrollViewDidZoom(ScrollView* view) + { + js_proxy_t * p = jsb_get_native_proxy(view); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "scrollViewDidZoom", 1, &arg, NULL); + } + + void setJSDelegate(JSObject* pJSDelegate) + { + _JSDelegate = pJSDelegate; + + // Check whether the js delegate is a pure js object. + js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); + if (!p) + { + _needUnroot = true; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); + } + } +private: + JSObject* _JSDelegate; + bool _needUnroot; +}; + +static JSBool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::ScrollView* cobj = (cocos2d::extension::ScrollView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 1) + { + // save the delegate + JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); + JSB_ScrollViewDelegate* nativeDelegate = new JSB_ScrollViewDelegate(); + nativeDelegate->setJSDelegate(jsDelegate); + + cobj->setUserObject(nativeDelegate); + cobj->setDelegate(nativeDelegate); + + nativeDelegate->release(); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; +} + + +#define KEY_TABLEVIEW_DATA_SOURCE "TableViewDataSource" +#define KEY_TABLEVIEW_DELEGATE "TableViewDelegate" + +class JSB_TableViewDelegate +: public Object +, public TableViewDelegate +{ +public: + JSB_TableViewDelegate() + : _JSDelegate(NULL) + , _needUnroot(false) + {} + + virtual ~JSB_TableViewDelegate() + { + if (_needUnroot) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &_JSDelegate); + } + } + + virtual void scrollViewDidScroll(ScrollView* view) + { + callJSDelegate(view, "scrollViewDidScroll"); + } + + virtual void scrollViewDidZoom(ScrollView* view) + { + callJSDelegate(view, "scrollViewDidZoom"); + } + + virtual void tableCellTouched(TableView* table, TableViewCell* cell) + { + callJSDelegate(table, cell, "tableCellTouched"); + } + + virtual void tableCellHighlight(TableView* table, TableViewCell* cell) + { + callJSDelegate(table, cell, "tableCellHighlight"); + } + + virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) + { + callJSDelegate(table, cell, "tableCellUnhighlight"); + } + + virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) + { + callJSDelegate(table, cell, "tableCellWillRecycle"); + } + + void setJSDelegate(JSObject* pJSDelegate) + { + _JSDelegate = pJSDelegate; + + // Check whether the js delegate is a pure js object. + js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); + if (!p) + { + _needUnroot = true; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); + } + } + + +private: + void callJSDelegate(ScrollView* view, std::string jsFunctionName) + { + js_proxy_t * p = jsb_get_native_proxy(view); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), jsFunctionName.c_str(), 1, &arg, NULL); + } + + void callJSDelegate(TableView* table, TableViewCell* cell, std::string jsFunctionName) + { + js_proxy_t * p = jsb_get_native_proxy(table); + if (!p) return; + + js_proxy_t * pCellProxy = jsb_get_native_proxy(cell); + if (!pCellProxy) return; + + jsval args[2]; + args[0] = OBJECT_TO_JSVAL(p->obj); + args[1] = OBJECT_TO_JSVAL(pCellProxy->obj); + + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), jsFunctionName.c_str(), 2, args, NULL); + } + + JSObject* _JSDelegate; + bool _needUnroot; +}; + +static JSBool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 1) + { + // save the delegate + JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); + JSB_TableViewDelegate* nativeDelegate = new JSB_TableViewDelegate(); + nativeDelegate->setJSDelegate(jsDelegate); + + Dictionary* userDict = static_cast(cobj->getUserObject()); + if (NULL == userDict) + { + userDict = new Dictionary(); + cobj->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(nativeDelegate, KEY_TABLEVIEW_DELEGATE); + + cobj->setDelegate(nativeDelegate); + + nativeDelegate->release(); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; +} + +class JSB_TableViewDataSource +: public Object +, public TableViewDataSource +{ +public: + JSB_TableViewDataSource() + : _JSTableViewDataSource(NULL) + , _needUnroot(false) + {} + + virtual ~JSB_TableViewDataSource() + { + if (_needUnroot) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &_JSTableViewDataSource); + } + } + + virtual Size tableCellSizeForIndex(TableView *table, unsigned int idx) + { + jsval ret; + bool ok = callJSDelegate(table, idx, "tableCellSizeForIndex", ret); + if (!ok) + { + ok = callJSDelegate(table, "cellSizeForTable", ret); + } + if (ok) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + Size size; + JSBool isSucceed = jsval_to_ccsize(cx, ret, &size); + if (isSucceed) return size; + } + return Size::ZERO; + + } + + virtual TableViewCell* tableCellAtIndex(TableView *table, unsigned int idx) + { + jsval ret; + bool ok = callJSDelegate(table, idx, "tableCellAtIndex", ret); + if (ok) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + cocos2d::extension::TableViewCell* arg0; + do { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(ret); + proxy = jsb_get_js_proxy(tmpObj); + arg0 = (cocos2d::extension::TableViewCell*)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( arg0, cx, NULL, "Invalid Native Object"); + } while (0); + return arg0; + } + return NULL; + } + + virtual unsigned int numberOfCellsInTableView(TableView *table) + { + jsval ret; + bool ok = callJSDelegate(table, "numberOfCellsInTableView", ret); + if (ok) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + uint32_t count = 0; + JSBool isSucceed = jsval_to_uint32(cx, ret, &count); + if (isSucceed) return count; + } + return 0; + } + + + void setTableViewDataSource(JSObject* pJSSource) + { + _JSTableViewDataSource = pJSSource; + + // Check whether the js delegate is a pure js object. + js_proxy_t* p = jsb_get_js_proxy(_JSTableViewDataSource); + if (!p) + { + _needUnroot = true; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_JSTableViewDataSource, "TableViewDataSource"); + } + } + +private: + bool callJSDelegate(TableView* table, std::string jsFunctionName, jsval& retVal) + { + js_proxy_t * p = jsb_get_native_proxy(table); + if (!p) return false; + + JSBool hasAction; + jsval temp_retval; + jsval dataVal = OBJECT_TO_JSVAL(p->obj); + + 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)) + { + return false; + } + if(temp_retval == JSVAL_VOID) + { + return false; + } + + JSAutoCompartment ac(cx, obj); + JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), + 1, &dataVal, &retVal); + return true; + } + return false; + } + + bool callJSDelegate(TableView* table, int idx, std::string jsFunctionName, jsval& retVal) + { + js_proxy_t * p = jsb_get_native_proxy(table); + if (!p) return false; + + + JSBool hasAction; + jsval temp_retval; + jsval dataVal[2]; + dataVal[0] = OBJECT_TO_JSVAL(p->obj); + dataVal[1] = INT_TO_JSVAL(idx); + + 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)) + { + return false; + } + + if(temp_retval == JSVAL_VOID) + { + return false; + } + + JSAutoCompartment ac(cx, obj); + JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), + 2, dataVal, &retVal); + return true; + } + return false; + } + +private: + JSObject* _JSTableViewDataSource; + bool _needUnroot; +}; + +static JSBool js_cocos2dx_CCTableView_setDataSource(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + if (argc == 1) + { + JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); + pNativeSource->setTableViewDataSource(JSVAL_TO_OBJECT(argv[0])); + + Dictionary* userDict = static_cast(cobj->getUserObject()); + if (NULL == userDict) + { + userDict = new Dictionary(); + cobj->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(pNativeSource, KEY_TABLEVIEW_DATA_SOURCE); + + cobj->setDataSource(pNativeSource); + + pNativeSource->release(); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments"); + return JS_FALSE; +} + +static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSBool ok = JS_TRUE; + if (argc == 3 || argc == 2) + { + + JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); + pNativeSource->setTableViewDataSource(JSVAL_TO_OBJECT(argv[0])); + + cocos2d::Size arg1; + ok &= jsval_to_ccsize(cx, argv[1], &arg1); + cocos2d::extension::TableView* ret = NULL; + ret = new TableView(); + ret->autorelease(); + + ret->setDataSource(pNativeSource); + + jsval jsret; + do { + if (ret) + { + js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); + jsret = OBJECT_TO_JSVAL(proxy->obj); + } + else + { + jsret = JSVAL_NULL; + } + } while (0); + + if (argc == 2) + { + ret->initWithViewSize(arg1); + } + else + { + cocos2d::Node* arg2; + do + { + js_proxy_t *proxy; + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[2]); + proxy = jsb_get_js_proxy(tmpObj); + arg2 = (cocos2d::Node*)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( arg2, cx, JS_FALSE, "Invalid Native Object"); + } while (0); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + ret->initWithViewSize(arg1, arg2); + } + ret->reloadData(); + + Dictionary* userDict = new Dictionary(); + userDict->setObject(pNativeSource, KEY_TABLEVIEW_DATA_SOURCE); + ret->setUserObject(userDict); + userDict->release(); + + pNativeSource->release(); + + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments"); + return JS_FALSE; +} + +class JSB_EditBoxDelegate +: public Object +, public EditBoxDelegate +{ +public: + JSB_EditBoxDelegate() + : _JSDelegate(NULL) + , _needUnroot(false) + {} + + virtual ~JSB_EditBoxDelegate() + { + if (_needUnroot) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_RemoveObjectRoot(cx, &_JSDelegate); + } + } + + virtual void editBoxEditingDidBegin(EditBox* editBox) + { + js_proxy_t * p = jsb_get_native_proxy(editBox); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxEditingDidBegin", 1, &arg, NULL); + } + + virtual void editBoxEditingDidEnd(EditBox* editBox) + { + js_proxy_t * p = jsb_get_native_proxy(editBox); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxEditingDidEnd", 1, &arg, NULL); + } + + virtual void editBoxTextChanged(EditBox* editBox, const std::string& text) + { + js_proxy_t * p = jsb_get_native_proxy(editBox); + if (!p) return; + + jsval dataVal[2]; + dataVal[0] = OBJECT_TO_JSVAL(p->obj); + std::string arg1 = text; + dataVal[1] = std_string_to_jsval(ScriptingCore::getInstance()->getGlobalContext(), arg1); + + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxTextChanged", 2, dataVal, NULL); + } + + virtual void editBoxReturn(EditBox* editBox) + { + js_proxy_t * p = jsb_get_native_proxy(editBox); + if (!p) return; + + jsval arg = OBJECT_TO_JSVAL(p->obj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "editBoxReturn", 1, &arg, NULL); + } + + void setJSDelegate(JSObject* pJSDelegate) + { + _JSDelegate = pJSDelegate; + + // Check whether the js delegate is a pure js object. + js_proxy_t* p = jsb_get_js_proxy(_JSDelegate); + if (!p) + { + _needUnroot = true; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_JSDelegate, "TableViewDelegate"); + } + } +private: + JSObject* _JSDelegate; + bool _needUnroot; +}; + +static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::extension::EditBox* cobj = (cocos2d::extension::EditBox *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 1) + { + // save the delegate + JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); + JSB_EditBoxDelegate* nativeDelegate = new JSB_EditBoxDelegate(); + nativeDelegate->setJSDelegate(jsDelegate); + + cobj->setUserObject(nativeDelegate); + cobj->setDelegate(nativeDelegate); + + nativeDelegate->release(); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; +} + + + +class JSB_ControlButtonTarget : public Object +{ +public: + JSB_ControlButtonTarget() + : _jsFunc(nullptr), + _type(Control::EventType::TOUCH_DOWN), + _jsTarget(nullptr), + _needUnroot(false) + {} + + 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) + { + log("Failed to get proxy for control button"); + return; + } + + jsval dataVal[2]; + dataVal[0] = OBJECT_TO_JSVAL(p->obj); + int arg1 = (int)event; + dataVal[1] = INT_TO_JSVAL(arg1); + jsval jsRet; + + ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc), 2, dataVal, &jsRet); + } + + void setJSTarget(JSObject* pJSTarget) + { + _jsTarget = pJSTarget; + + 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) + { + _jsFunc = jsFunc; + + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + 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; + 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 = 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* 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 + JSB_ControlButtonTarget* nativeDelegate = new JSB_ControlButtonTarget(); + + nativeDelegate->setJSTarget(jsDelegate); + nativeDelegate->setJSAction(jsFunc); + nativeDelegate->setEventType(arg2); + + Array* nativeDelegateArray = static_cast(cobj->getUserObject()); + if (nullptr == nativeDelegateArray) + { + nativeDelegateArray = new Array(); + nativeDelegateArray->init(); + 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; + } + 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 = 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]); + JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); + + 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); + 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) +{ + JS_DefineFunction(cx, jsb_ScrollView_prototype, "setDelegate", js_cocos2dx_CCScrollView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_TableView_prototype, "setDelegate", js_cocos2dx_CCTableView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_TableView_prototype, "setDataSource", js_cocos2dx_CCTableView_setDataSource, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_EditBox_prototype, "setDelegate", js_cocos2dx_CCEditBox_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); + + 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); +} \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.h b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.h new file mode 100644 index 0000000000..e8822b1370 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.h @@ -0,0 +1,16 @@ +// +// jsb_cocos2d_extension_manual.h +// +// Created by James Chen on 3/11/13. +// +// + +#ifndef __jsb_cocos2dx_extension_manual__ +#define __jsb_cocos2dx_extension_manual__ + +#include "jsapi.h" +#include "jsfriendapi.h" + +void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global); + +#endif /* defined(__jsb_cocos2dx_extension_manual__) */ diff --git a/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj new file mode 100644 index 0000000000..b9ea3695d9 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj @@ -0,0 +1,118 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + + + {625F7391-9A91-48A1-8CFC-79508C822637} + Win32Proj + libJSBindingForExtension + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.filters b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.filters new file mode 100644 index 0000000000..805e94fc71 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.filters @@ -0,0 +1,34 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + generated + + + manual + + + + + generated + + + manual + + + + + generated + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.user b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp new file mode 100644 index 0000000000..7d1a819fc8 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp @@ -0,0 +1,75 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 +* Script version: v0.5 +*/ +#include "cocos2d.h" +#include "js_bindings_config.h" +//#ifdef JSB_INCLUDE_SYSTEM + +#include "local-storage/LocalStorage.h" + +#include "jsfriendapi.h" +#include "js_bindings_config.h" +#include "js_bindings_core.h" +#include "js_manual_conversions.h" +#include "js_bindings_system_functions.h" +#include "ScriptingCore.h" + +USING_NS_CC; + +// Arguments: char* +// Ret value: const char* +JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + const char* arg0; + + ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + const char* ret_val; + + ret_val = localStorageGetItem((char*)arg0 ); + + jsval ret_jsval = c_string_to_jsval(cx, ret_val ? ret_val : ""); + JS_SET_RVAL(cx, vp, ret_jsval ); + + return JS_TRUE; +} + +// Arguments: char* +// Ret value: void +JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + const char* arg0; + + ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + localStorageRemoveItem((char*)arg0 ); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + +// Arguments: char*, char* +// Ret value: void +JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + jsval *argvp = JS_ARGV(cx,vp); + JSBool ok = JS_TRUE; + const char* arg0; const char* arg1; + + ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); + ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + + localStorageSetItem((char*)arg0 , (char*)arg1 ); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; +} + + +//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h new file mode 100644 index 0000000000..26d4a97c99 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h @@ -0,0 +1,23 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 +* Script version: v0.5 +*/ +#include "js_bindings_config.h" +//#ifdef JSB_INCLUDE_SYSTEM + +//#include "LocalStorage.h" + +#ifdef __cplusplus +extern "C" { +#endif +JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp); +JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp); + +#ifdef __cplusplus +} +#endif + + +//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions_registration.h b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions_registration.h new file mode 100644 index 0000000000..5774403878 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions_registration.h @@ -0,0 +1,15 @@ +/* +* AUTOGENERATED FILE. DO NOT EDIT IT +* Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 +* Script version: v0.5 +*/ +#include "../js_bindings_config.h" +//#ifdef JSB_INCLUDE_SYSTEM + +//#include "LocalStorage.h" +JS_DefineFunction(_cx, system, "getItem", JSB_localStorageGetItem, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, system, "removeItem", JSB_localStorageRemoveItem, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(_cx, system, "setItem", JSB_localStorageSetItem, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + + +//#endif // JSB_INCLUDE_SYSTEM diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp new file mode 100644 index 0000000000..bf55e188f0 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp @@ -0,0 +1,62 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 "js_bindings_config.h" +#include "js_bindings_core.h" +#include "local-storage/LocalStorage.h" +#include "cocos2d.h" + +// system +#include "js_bindings_system_functions.h" + + +void jsb_register_system( JSContext *_cx, JSObject *object) +{ + // + // sys + // + JSObject *sys = JS_NewObject(_cx, NULL, NULL, NULL); + jsval systemVal = OBJECT_TO_JSVAL(sys); + JS_SetProperty(_cx, object, "sys", &systemVal); + + + // sys.localStorage + JSObject *ls = JS_NewObject(_cx, NULL, NULL, NULL); + jsval lsVal = OBJECT_TO_JSVAL(ls); + JS_SetProperty(_cx, sys, "localStorage", &lsVal); + + // sys.localStorage functions + JSObject *system = ls; +#include "js_bindings_system_functions_registration.h" + + + // Init DB with full path + //NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; + //NSString *fullpath = [path stringByAppendingPathComponent:@"jsb.sqlite"]; + std::string strFilePath = cocos2d::FileUtils::getInstance()->getWritablePath(); + strFilePath += "/jsb.sqlite"; + localStorageInit(strFilePath.c_str()); + +} + diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.h b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.h new file mode 100644 index 0000000000..1afb1b1081 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.h @@ -0,0 +1,31 @@ +/* + * JS Bindings: https://github.com/zynga/jsbindings + * + * Copyright (c) 2012 Zynga Inc. + * + * 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 __JSB_SYSTEM_REGISTRATION +#define __JSB_SYSTEM_REGISTRATION + +void jsb_register_system( JSContext *globalC, JSObject *globalO); + +#endif // __JSB_CHIPMUNK_REGISTRATION diff --git a/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj new file mode 100644 index 0000000000..2f074d6c17 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj @@ -0,0 +1,116 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + + {68F5F371-BD7B-4C30-AE5B-0B08F22E0CDE} + Win32Proj + libJSBindingForLocalStorage + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\spidermonkey\include\win32;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\spidermonkey\include\win32;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.filters b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.filters new file mode 100644 index 0000000000..9fc0ee4734 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.filters @@ -0,0 +1,32 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + manual + + + manual + + + + + manual + + + manual + + + manual + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.user b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp new file mode 100644 index 0000000000..cc7b72c586 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -0,0 +1,847 @@ +// +// XMLHTTPRequest.cpp +// XMLHttpRequest +// +// Created by Zynga 2013 +// +// Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp +// Copyright (c) 2012 Rolando Abarca. All rights reserved. +// +// 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 "XMLHTTPRequest.h" +#include + +using namespace std; + +//#pragma mark - MinXmlHttpRequest + +/** + * @brief Implementation for header retrieving. + * @param header + */ +void MinXmlHttpRequest::_gotHeader(string header) +{ + // Get Header and Set StatusText + // Split String into Tokens + char * cstr = new char [header.length()+1]; + + // check for colon. + unsigned found_header_field = header.find_first_of(":"); + + if (found_header_field != std::string::npos) + { + // Found a header field. + string http_field; + string http_value; + + http_field = header.substr(0,found_header_field); + http_value = header.substr(found_header_field+1, header.length()); + + // Get rid of all \n + if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') { + http_value.erase(http_value.size() - 1); + } + + _httpHeader[http_field] = http_value; + + } + else + { + // Seems like we have the response Code! Parse it and check for it. + char * pch; + strcpy(cstr, header.c_str()); + + pch = strtok(cstr," "); + while (pch != NULL) + { + + stringstream ss; + string val; + + ss << pch; + val = ss.str(); + unsigned found_http = val.find("HTTP"); + + // Check for HTTP Header to set statusText + if (found_http != std::string::npos) { + + stringstream mystream; + + // Get Response Status + pch = strtok (NULL, " "); + mystream << pch; + + pch = strtok (NULL, " "); + mystream << " " << pch; + + _statusText = mystream.str(); + + } + + pch = strtok (NULL, " "); + } + } + + CC_SAFE_DELETE_ARRAY(cstr); +} + +/** + * @brief Set Request header for next call. + * @param field Name of the Header to be set. + * @param value Value of the Headerfield + */ +void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) +{ + stringstream header_s; + stringstream value_s; + string header; + + map::iterator iter = _requestHeader.find(field); + + // Concatenate values when header exists. + if (iter != _requestHeader.end()) + { + value_s << iter->second << "," << value; + } + else + { + value_s << value; + } + + _requestHeader[field] = value_s.str(); +} + +/** + * @brief If headers has been set, pass them to curl. + * + */ +void MinXmlHttpRequest::_setHttpRequestHeader() +{ + std::vector header; + + for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it) + { + const char* first = it->first.c_str(); + const char* second = it->second.c_str(); + size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); + char* test = (char*) malloc(len); + memset(test, 0,len); + + strcpy(test, first); + strcpy(test + strlen(first) , ": "); + strcpy(test + strlen(first) + 2, second); + + header.push_back(test); + + free(test); + + } + + if (!header.empty()) + { + _httpRequest->setHeaders(header); + } + +} + +/** + * @brief Callback for HTTPRequest. Handles the response and invokes Callback. + * @param sender Object which initialized callback + * @param respone Response object + */ +void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response) +{ + if (0 != strlen(response->getHttpRequest()->getTag())) + { + CCLOG("%s completed", response->getHttpRequest()->getTag()); + } + + int statusCode = response->getResponseCode(); + char statusString[64] = {}; + sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); + + if (!response->isSucceed()) + { + CCLOG("response failed"); + CCLOG("error buffer: %s", response->getErrorBuffer()); + return; + } + + // set header + std::vector *headers = response->getResponseHeader(); + + char* concatHeader = (char*) malloc(headers->size() + 1); + std::string header(headers->begin(), headers->end()); + strcpy(concatHeader, header.c_str()); + + std::istringstream stream(concatHeader); + std::string line; + while(std::getline(stream, line)) { + _gotHeader(line); + } + + /** get the response data **/ + std::vector *buffer = response->getResponseData(); + char* concatenated = (char*) malloc(buffer->size() + 1); + std::string s2(buffer->begin(), buffer->end()); + + strcpy(concatenated, s2.c_str()); + + if (statusCode == 200) + { + //Succeeded + _status = 200; + _readyState = DONE; + _data << concatenated; + _dataSize = buffer->size(); + } + else + { + _status = 0; + } + // Free Memory. + free((void*) concatHeader); + free((void*) concatenated); + + js_proxy_t * p; + void* ptr = (void*)this; + p = jsb_get_native_proxy(ptr); + + if(p) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + + if (_onreadystateCallback) + { + //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx); + jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback); + jsval out; + JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out); + } + + } + +} +/** + * @brief Send out request and fire callback when done. + * @param cx Javascript context + */ +void MinXmlHttpRequest::_sendRequest(JSContext *cx) +{ + _httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse)); + network::HttpClient::getInstance()->send(_httpRequest); + _httpRequest->release(); +} + +/** + * @brief Constructor initializes cchttprequest and stuff + * + */ +MinXmlHttpRequest::MinXmlHttpRequest() : _onreadystateCallback(NULL), _isNetwork(true) +{ + _httpHeader.clear(); + _requestHeader.clear(); + _withCredentialsValue = true; + _cx = ScriptingCore::getInstance()->getGlobalContext(); + _httpRequest = new network::HttpRequest(); +} + +/** + * @brief Destructor cleans up _httpRequest and stuff + * + */ +MinXmlHttpRequest::~MinXmlHttpRequest() +{ + _httpHeader.clear(); + _requestHeader.clear(); + + if (_onreadystateCallback != NULL) + { + JS_RemoveObjectRoot(_cx, &_onreadystateCallback); + } + + if (_httpRequest) + { + // We don't need to release _httpRequest here since it will be released in the http callback. +// _httpRequest->release(); + } + +} + +/** + * @brief Initialize Object and needed properties. + * + */ +JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest); + +/** + * @brief Implementation for the Javascript Constructor + * + */ +JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest) +{ + MinXmlHttpRequest* req = new MinXmlHttpRequest(); + req->autorelease(); + + js_proxy_t *p; + jsval out; + + JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent); + + if (obj) { + JS_SetPrivate(obj, req); + out = OBJECT_TO_JSVAL(obj); + } + + JS_SET_RVAL(cx, vp, out); + p =jsb_new_proxy(req, obj); + + JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest"); + return JS_TRUE; +} + +/** + * @brief get Callback function for Javascript + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) +{ + if (_onreadystateCallback) + { + JSString *tmpstr = JS_NewStringCopyZ(cx, "1"); + jsval tmpval = STRING_TO_JSVAL(tmpstr); + JS_SetProperty(cx, _onreadystateCallback, "readyState", &tmpval); + + jsval out = OBJECT_TO_JSVAL(_onreadystateCallback); + vp.set(out); + + } + else + { + vp.set(JSVAL_NULL); + } + return JS_TRUE; +} + +/** + * @brief Set Callback function coming from Javascript + * + * + */ +JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) +{ + jsval callback = vp.get(); + if (callback != JSVAL_NULL) + { + _onreadystateCallback = JSVAL_TO_OBJECT(callback); + JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback"); + } + return JS_TRUE; +} + +/** + * @brief upload getter - TODO + * + * Placeholder for further implementations!! + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) +{ + vp.set(JSVAL_NULL); + return JS_TRUE; +} + +/** + * @brief upload setter - TODO + * + * Placeholder for further implementations + */ +JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) +{ + vp.set(JSVAL_NULL); + return JS_TRUE; +} + +/** + * @brief timeout getter - TODO + * + * Placeholder for further implementations + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout) +{ + vp.set(INT_TO_JSVAL(_timeout)); + return JS_TRUE; +} + +/** + * @brief timeout setter - TODO + * + * Placeholder for further implementations + */ +JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout) +{ + jsval timeout_ms = vp.get(); + + _timeout = JSVAL_TO_INT(timeout_ms); + //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout); + return JS_TRUE; + +} + +/** + * @brief get response type for actual XHR + * + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) +{ + JSString* str = JS_NewStringCopyN(cx, "", 0); + vp.set(STRING_TO_JSVAL(str)); + return JS_TRUE; +} + +/** + * @brief responseXML getter - TODO + * + * Placeholder for further implementation. + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML) +{ + vp.set(JSVAL_NULL); + return JS_TRUE; +} + +/** + * @brief set response type for actual XHR + * + * + */ +JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) +{ + jsval type = vp.get(); + if (type.isString()) { + JSString* str = type.toString(); + JSBool equal; + + JS_StringEqualsAscii(cx, str, "text", &equal); + if (equal) + { + _responseType = ResponseType::STRING; + return JS_TRUE; + } + + JS_StringEqualsAscii(cx, str, "arraybuffer", &equal); + if (equal) + { + _responseType = ResponseType::ARRAY_BUFFER; + return JS_TRUE; + } + + JS_StringEqualsAscii(cx, str, "json", &equal); + if (equal) + { + _responseType = ResponseType::JSON; + return JS_TRUE; + } + // ignore the rest of the response types for now + return JS_TRUE; + } + JS_ReportError(cx, "Invalid response type"); + return JS_FALSE; +} + +/** + * @brief get readyState for actual XHR + * + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) +{ + vp.set(INT_TO_JSVAL(_readyState)); + return JS_TRUE; +} + +/** + * @brief get status for actual XHR + * + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status) +{ + vp.set(INT_TO_JSVAL(_status)); + return JS_TRUE; +} + +/** + * @brief get statusText for actual XHR + * + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) +{ + jsval strVal = std_string_to_jsval(cx, _statusText); + + if (strVal != JSVAL_NULL) + { + vp.set(strVal); + return JS_TRUE; + } + else + { + JS_ReportError(cx, "Error trying to create JSString from data"); + return JS_FALSE; + } +} + +/** + * @brief get value of withCredentials property. + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials) +{ + vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue)); + return JS_TRUE; +} + +/** + * withCredentials - set value of withCredentials property. + * + */ +JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) +{ + jsval credential = vp.get(); + if (credential != JSVAL_NULL) + { + _withCredentialsValue = JSVAL_TO_BOOLEAN(credential); + } + + return JS_TRUE; +} + +/** + * @brief get (raw) responseText + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) +{ + jsval strVal = std_string_to_jsval(cx, _data.str()); + + if (strVal != JSVAL_NULL) + { + vp.set(strVal); + //JS_ReportError(cx, "Result: %s", data.str().c_str()); + return JS_TRUE; + } else { + JS_ReportError(cx, "Error trying to create JSString from data"); + return JS_FALSE; + } +} + +/** + * @brief get response of latest XHR + * + */ +JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) +{ + + if (_responseType == ResponseType::JSON) + { + jsval outVal; + + jsval strVal = std_string_to_jsval(cx, _data.str()); + if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) + { + vp.set(outVal); + return JS_TRUE; + } + } + else if (_responseType == ResponseType::ARRAY_BUFFER) + { + JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize); + uint8_t* tmpData = JS_GetArrayBufferData(tmp); + _data.read((char*)tmpData, _dataSize); + jsval outVal = OBJECT_TO_JSVAL(tmp); + + vp.set(outVal); + return JS_TRUE; + } + // by default, return text + return _js_get_responseText(cx, id, vp); +} + +/** + * @brief initialize new xhr. + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) +{ + if (argc >= 2) + { + jsval* argv = JS_ARGV(cx, vp); + const char* method; + const char* urlstr; + JSBool async = true; + JSString* jsMethod = JS_ValueToString(cx, argv[0]); + JSString* jsURL = JS_ValueToString(cx, argv[1]); + + if (argc > 2) { + JS_ValueToBoolean(cx, argv[2], &async); + } + + JSStringWrapper w1(jsMethod); + JSStringWrapper w2(jsURL); + method = w1; + urlstr = w2; + + _url = urlstr; + _meth = method; + _readyState = 1; + _isAsync = async; + + if (_url.length() > 5 && _url.compare(_url.length() - 5, 5, ".json") == 0) + { + _responseType = ResponseType::JSON; + } + + if (_meth.compare("post") == 0 || _meth.compare("POST") == 0) + { + _httpRequest->setRequestType(network::HttpRequest::Type::POST); + } + else + { + _httpRequest->setRequestType(network::HttpRequest::Type::GET); + } + + _httpRequest->setUrl(_url.c_str()); + + _isNetwork = true; + _readyState = OPENED; + + return JS_TRUE; + } + + JS_ReportError(cx, "invalid call: %s", __FUNCTION__); + return JS_FALSE; + +} + +/** + * @brief send xhr + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) +{ + JSString *str = NULL; + std::string data; + + // Clean up header map. New request, new headers! + _httpHeader.clear(); + + if (argc == 1) + { + if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) + { + return JS_FALSE; + } + JSStringWrapper strWrap(str); + data = strWrap.get(); + } + + + if (data.length() > 0 && (_meth.compare("post") == 0 || _meth.compare("POST") == 0)) + { + _httpRequest->setRequestData(data.c_str(), data.length()); + } + + _setHttpRequestHeader(); + _sendRequest(cx); + + return JS_TRUE; +} + +/** + * @brief abort function Placeholder! + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort) +{ + return JS_TRUE; +} + +/** + * @brief Get all response headers as a string + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders) +{ + stringstream responseheaders; + string responseheader; + + for (auto it = _httpHeader.begin(); it != _httpHeader.end(); ++it) + { + responseheaders << it->first << ": " << it->second << "\n"; + } + + responseheader = responseheaders.str(); + + jsval strVal = std_string_to_jsval(cx, responseheader); + if (strVal != JSVAL_NULL) + { + JS_SET_RVAL(cx, vp, strVal); + return JS_TRUE; + } + else + { + JS_ReportError(cx, "Error trying to create JSString from data"); + return JS_FALSE; + } + + return JS_TRUE; +} + +/** + * @brief Get all response headers as a string + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) +{ + JSString *header_value; + + if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) { + return JS_FALSE; + }; + + std::string data; + JSStringWrapper strWrap(header_value); + data = strWrap.get(); + + stringstream streamdata; + + streamdata << data; + + string value = streamdata.str(); + + auto iter = _httpHeader.find(value); + if (iter != _httpHeader.end()) + { + jsval js_ret_val = std_string_to_jsval(cx, iter->second); + JS_SET_RVAL(cx, vp, js_ret_val); + return JS_TRUE; + } + else { + JS_SET_RVAL(cx, vp, JSVAL_NULL); + return JS_TRUE; + } +} + +/** + * @brief Set the given Fields to request Header. + * + * + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) +{ + if (argc >= 2) + { + jsval* argv = JS_ARGV(cx, vp); + const char* field; + const char* value; + + JSString* jsField = JS_ValueToString(cx, argv[0]); + JSString* jsValue = JS_ValueToString(cx, argv[1]); + + JSStringWrapper w1(jsField); + JSStringWrapper w2(jsValue); + field = w1; + value = w2; + + // Populate the request_header map. + _setRequestHeader(field, value); + + return JS_TRUE; + } + + return JS_FALSE; + +} + +/** + * @brief overrideMimeType function - TODO! + * + * Just a placeholder for further implementations. + */ +JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType) +{ + return JS_TRUE; +} + +/** + * @brief destructor for Javascript + * + */ +static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) +{ + CCLOG("basic_object_finalize %p ...", obj); +} + +/** + * @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods. + * @param cx Global Spidermonkey JS Context. + * @param global Global Spidermonkey Javascript object. + */ +void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global) +{ + JSClass js_class = { + "XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub, + JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, + basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS + }; + + MinXmlHttpRequest::js_class = js_class; + static JSPropertySpec props[] = { + JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange), + JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType), + JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML), + JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response), + {0, 0, 0, 0, 0} + }; + + static JSFunctionSpec funcs[] = { + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader), + JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType), + JS_FS_END + }; + + MinXmlHttpRequest::js_parent = NULL; + MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL); + +} + diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h new file mode 100644 index 0000000000..861e0a2536 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -0,0 +1,112 @@ +// +// XMLHTTPRequest.h +// XMLHttpRequest +// +// Created by Zynga 2013 +// +// Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.h +// Copyright (c) 2012 Rolando Abarca. All rights reserved. +// +// 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 __FAKE_XMLHTTPREQUEST_H__ +#define __FAKE_XMLHTTPREQUEST_H__ + +#include "network/HttpClient.h" +#include "js_bindings_config.h" +#include "ScriptingCore.h" +#include "jstypes.h" +#include "jsapi.h" +#include "jsfriendapi.h" +#include "jsb_helper.h" + +class MinXmlHttpRequest : public cocos2d::Object +{ +public: + enum class ResponseType + { + STRING, + ARRAY_BUFFER, + BLOB, + DOCUMENT, + JSON + }; + + // Ready States (http://www.w3.org/TR/XMLHttpRequest/#interface-xmlhttprequest) + static const unsigned short UNSENT = 0; + static const unsigned short OPENED = 1; + static const unsigned short HEADERS_RECEIVED = 2; + static const unsigned short LOADING = 3; + static const unsigned short DONE = 4; + + MinXmlHttpRequest(); + ~MinXmlHttpRequest(); + + JS_BINDED_CLASS_GLUE(MinXmlHttpRequest); + JS_BINDED_CONSTRUCTOR(MinXmlHttpRequest); + JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, onreadystatechange); + JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, responseType); + JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, withCredentials); + JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, upload); + JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, timeout); + JS_BINDED_PROP_GET(MinXmlHttpRequest, readyState); + JS_BINDED_PROP_GET(MinXmlHttpRequest, status); + JS_BINDED_PROP_GET(MinXmlHttpRequest, statusText); + JS_BINDED_PROP_GET(MinXmlHttpRequest, responseText); + JS_BINDED_PROP_GET(MinXmlHttpRequest, response); + JS_BINDED_PROP_GET(MinXmlHttpRequest, responseXML); + JS_BINDED_FUNC(MinXmlHttpRequest, open); + JS_BINDED_FUNC(MinXmlHttpRequest, send); + JS_BINDED_FUNC(MinXmlHttpRequest, abort); + JS_BINDED_FUNC(MinXmlHttpRequest, getAllResponseHeaders); + JS_BINDED_FUNC(MinXmlHttpRequest, getResponseHeader); + JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader); + JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType); + + void handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response); + + +private: + void _gotHeader(std::string header); + void _setRequestHeader(const char* field, const char* value); + void _setHttpRequestHeader(); + void _sendRequest(JSContext *cx); + + std::string _url; + JSContext* _cx; + std::string _meth; + std::string _type; + std::stringstream _data; + size_t _dataSize; + JSObject* _onreadystateCallback; + int _readyState; + int _status; + std::string _statusText; + ResponseType _responseType; + unsigned _timeout; + bool _isAsync; + network::HttpRequest* _httpRequest; + bool _isNetwork; + bool _withCredentialsValue; + std::map _httpHeader; + std::map _requestHeader; +}; + +#endif diff --git a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp new file mode 100644 index 0000000000..b5083ad268 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp @@ -0,0 +1,382 @@ +/**************************************************************************** +Copyright (c) 2013 cocos2d-x.org +Copyright (c) 2013 James Chen + +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 "jsb_websocket.h" +#include "cocos2d.h" +#include "network/WebSocket.h" +#include "spidermonkey_specifics.h" +#include "ScriptingCore.h" +#include "cocos2d_specifics.hpp" + +using namespace network; + +/* + [Constructor(in DOMString url, in optional DOMString protocols)] + [Constructor(in DOMString url, in optional DOMString[] protocols)] + interface WebSocket { + readonly attribute DOMString url; + + // ready state + const unsigned short CONNECTING = 0; + const unsigned short OPEN = 1; + const unsigned short CLOSING = 2; + const unsigned short CLOSED = 3; + readonly attribute unsigned short readyState; + readonly attribute unsigned long bufferedAmount; + + // networking + attribute Function onopen; + attribute Function onmessage; + attribute Function onerror; + attribute Function onclose; + readonly attribute DOMString protocol; + void send(in DOMString data); + void close(); + }; + WebSocket implements EventTarget; + */ + +class JSB_WebSocketDelegate : public WebSocket::Delegate +{ +public: + + virtual void onOpen(WebSocket* ws) + { + js_proxy_t * p = jsb_get_native_proxy(ws); + if (!p) return; + + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); + jsval vp = c_string_to_jsval(cx, "open"); + JS_SetProperty(cx, jsobj, "type", &vp); + + jsval args = OBJECT_TO_JSVAL(jsobj); + + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onopen", 1, &args); + } + + virtual void onMessage(WebSocket* ws, const WebSocket::Data& data) + { + js_proxy_t * p = jsb_get_native_proxy(ws); + if (!p) return; + + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); + jsval vp = c_string_to_jsval(cx, "message"); + JS_SetProperty(cx, jsobj, "type", &vp); + + jsval args = OBJECT_TO_JSVAL(jsobj); + + if (data.isBinary) + {// data is binary + JSObject* buffer = JS_NewArrayBuffer(cx, data.len); + uint8_t* bufdata = JS_GetArrayBufferData(buffer); + memcpy((void*)bufdata, (void*)data.bytes, data.len); + jsval dataVal = OBJECT_TO_JSVAL(buffer); + JS_SetProperty(cx, jsobj, "data", &dataVal); + } + else + {// data is string + jsval dataVal = c_string_to_jsval(cx, data.bytes); + JS_SetProperty(cx, jsobj, "data", &dataVal); + } + + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onmessage", 1, &args); + } + + virtual void onClose(WebSocket* ws) + { + js_proxy_t * p = jsb_get_native_proxy(ws); + if (!p) return; + + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); + jsval vp = c_string_to_jsval(cx, "close"); + JS_SetProperty(cx, jsobj, "type", &vp); + + jsval args = OBJECT_TO_JSVAL(jsobj); + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onclose", 1, &args); + + js_proxy_t* jsproxy = jsb_get_js_proxy(p->obj); + JS_RemoveObjectRoot(cx, &jsproxy->obj); + jsb_remove_proxy(p, jsproxy); + CC_SAFE_DELETE(ws); + } + + virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error) + { + js_proxy_t * p = jsb_get_native_proxy(ws); + if (!p) return; + + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); + jsval vp = c_string_to_jsval(cx, "error"); + JS_SetProperty(cx, jsobj, "type", &vp); + + jsval args = OBJECT_TO_JSVAL(jsobj); + + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onerror", 1, &args); + } + + void setJSDelegate(JSObject* pJSDelegate) + { + _JSDelegate = pJSDelegate; + } +private: + JSObject* _JSDelegate; +}; + +JSClass *js_cocos2dx_websocket_class; +JSObject *js_cocos2dx_websocket_prototype; + +void js_cocos2dx_WebSocket_finalize(JSFreeOp *fop, JSObject *obj) { + CCLOG("jsbindings: finalizing JS object %p (WebSocket)", obj); +} + +JSBool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if(argc == 1){ + do + { + if (JSVAL_IS_STRING(argv[0])) + { + std::string data; + jsval_to_std_string(cx, argv[0], &data); + cobj->send(data); + break; + } + + if (argv[0].isObject()) + { + uint8_t *bufdata = NULL; + uint32_t len = 0; + + JSObject* jsobj = JSVAL_TO_OBJECT(argv[0]); + if (JS_IsArrayBufferObject(jsobj)) + { + bufdata = JS_GetArrayBufferData(jsobj); + len = JS_GetArrayBufferByteLength(jsobj); + } + else if (JS_IsArrayBufferViewObject(jsobj)) + { + bufdata = (uint8_t*)JS_GetArrayBufferViewData(jsobj); + len = JS_GetArrayBufferViewByteLength(jsobj); + } + + if (bufdata && len > 0) + { + cobj->send(bufdata, len); + break; + } + } + + JS_ReportError(cx, "data type to be sent is unsupported."); + + } while (0); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); + return JS_TRUE; +} + +JSBool js_cocos2dx_extension_WebSocket_close(JSContext *cx, uint32_t argc, jsval *vp){ + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if(argc == 0){ + cobj->close(); + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); + return JS_FALSE; +} + +JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + + if (argc == 1 || argc == 2) + { + + std::string url; + + do { + JSBool ok = jsval_to_std_string(cx, argv[0], &url); + JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + } while (0); + + JSObject *obj = JS_NewObject(cx, js_cocos2dx_websocket_class, js_cocos2dx_websocket_prototype, NULL); + + + WebSocket* cobj = new WebSocket(); + JSB_WebSocketDelegate* delegate = new JSB_WebSocketDelegate(); + delegate->setJSDelegate(obj); + + if (argc == 2) + { + std::vector protocols; + + if (JSVAL_IS_STRING(argv[1])) + { + std::string protocol; + do { + JSBool ok = jsval_to_std_string(cx, argv[1], &protocol); + JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + } while (0); + protocols.push_back(protocol); + } + else if (argv[1].isObject()) + { + JSBool ok = JS_TRUE; + JSObject* arg2 = JSVAL_TO_OBJECT(argv[1]); + JSB_PRECONDITION(JS_IsArrayObject( cx, arg2 ), "Object must be an array"); + + uint32_t len = 0; + JS_GetArrayLength(cx, arg2, &len); + + for( uint32_t i=0; i< len;i++ ) + { + jsval valarg; + JS_GetElement(cx, arg2, i, &valarg); + std::string protocol; + do { + ok = jsval_to_std_string(cx, valarg, &protocol); + JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + } while (0); + + protocols.push_back(protocol); + } + } + cobj->init(*delegate, url, &protocols); + } + else + { + cobj->init(*delegate, url); + } + + + JS_DefineProperty(cx, obj, "URL", argv[0] + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + + //protocol not support yet (always return "") + JS_DefineProperty(cx, obj, "protocol", c_string_to_jsval(cx, "") + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + + // link the native object with the javascript object + js_proxy_t *p = jsb_new_proxy(cobj, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "WebSocket"); + + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); + return JS_FALSE; +} + +static JSBool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JSHandleObject obj, JSHandleId id, JSMutableHandleValue vp) +{ + JSObject* jsobj = obj.get(); + js_proxy_t *proxy = jsb_get_js_proxy(jsobj); + WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (cobj) { + vp.set(INT_TO_JSVAL((int)cobj->getReadyState())); + return JS_TRUE; + } else { + JS_ReportError(cx, "Error: WebSocket instance is invalid."); + return JS_FALSE; + } +} + +void register_jsb_websocket(JSContext *cx, JSObject *global) { + + js_cocos2dx_websocket_class = (JSClass *)calloc(1, sizeof(JSClass)); + js_cocos2dx_websocket_class->name = "WebSocket"; + js_cocos2dx_websocket_class->addProperty = JS_PropertyStub; + js_cocos2dx_websocket_class->delProperty = JS_DeletePropertyStub; + js_cocos2dx_websocket_class->getProperty = JS_PropertyStub; + js_cocos2dx_websocket_class->setProperty = JS_StrictPropertyStub; + js_cocos2dx_websocket_class->enumerate = JS_EnumerateStub; + js_cocos2dx_websocket_class->resolve = JS_ResolveStub; + js_cocos2dx_websocket_class->convert = JS_ConvertStub; + js_cocos2dx_websocket_class->finalize = js_cocos2dx_WebSocket_finalize; + js_cocos2dx_websocket_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); + + static JSPropertySpec properties[] = { + {"readyState", 0, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_SHARED, JSOP_WRAPPER(js_cocos2dx_extension_WebSocket_get_readyState), NULL}, + {0, 0, 0, 0, 0} + }; + + static JSFunctionSpec funcs[] = { + JS_FN("send",js_cocos2dx_extension_WebSocket_send, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("close",js_cocos2dx_extension_WebSocket_close, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + static JSFunctionSpec st_funcs[] = { + JS_FS_END + }; + + js_cocos2dx_websocket_prototype = JS_InitClass( + cx, global, + NULL, + js_cocos2dx_websocket_class, + js_cocos2dx_extension_WebSocket_constructor, 0, // constructor + properties, + funcs, + NULL, // no static properties + st_funcs); + + JSObject* jsclassObj = JSVAL_TO_OBJECT(anonEvaluate(cx, global, "(function () { return WebSocket; })()")); + + JS_DefineProperty(cx, jsclassObj, "CONNECTING", INT_TO_JSVAL((int)WebSocket::State::CONNECTING) + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + JS_DefineProperty(cx, jsclassObj, "OPEN", INT_TO_JSVAL((int)WebSocket::State::OPEN) + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + JS_DefineProperty(cx, jsclassObj, "CLOSING", INT_TO_JSVAL((int)WebSocket::State::CLOSING) + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + JS_DefineProperty(cx, jsclassObj, "CLOSED", INT_TO_JSVAL((int)WebSocket::State::CLOSED) + , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); + + // make the class enumerable in the registered namespace + JSBool found; + JS_SetPropertyAttributes(cx, global, "WebSocket", JSPROP_ENUMERATE | JSPROP_READONLY, &found); +} + + diff --git a/cocos/scripting/javascript/bindings/network/jsb_websocket.h b/cocos/scripting/javascript/bindings/network/jsb_websocket.h new file mode 100644 index 0000000000..cde0f40b2e --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/jsb_websocket.h @@ -0,0 +1,34 @@ +/**************************************************************************** +Copyright (c) 2013 cocos2d-x.org +Copyright (c) 2013 James Chen + +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 __jsb_websocket__ +#define __jsb_websocket__ + +#include "jsapi.h" +#include "jsfriendapi.h" + +void register_jsb_websocket(JSContext* cx, JSObject* global); + +#endif /* defined(__jsb_websocket__) */ diff --git a/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj new file mode 100644 index 0000000000..e4ff3eed4b --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj @@ -0,0 +1,115 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + + + {3BEC13F5-E227-4D80-BC77-1C857F83BCFC} + Win32Proj + libJSBindingForNetwork + + + + StaticLibrary + true + Unicode + v100 + v110 + v110_xp + + + StaticLibrary + false + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + + + $(Configuration).win32\ + + + + + + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\websockets\include\win32;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + false + + + Windows + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\..\external\sqlite3\libraries\win32\*.*" "$(OutDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_LIB;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\websockets\include\win32;%(AdditionalIncludeDirectories) + 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) + true + + + Windows + true + true + true + + + + + + + + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.filters b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.filters new file mode 100644 index 0000000000..3fd3c5a5d1 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.filters @@ -0,0 +1,29 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + manual + + + manual + + + + + manual + + + manual + + + \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.user b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.user new file mode 100644 index 0000000000..3f03091124 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj.user @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj new file mode 100644 index 0000000000..d79eb7ce1c --- /dev/null +++ b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj @@ -0,0 +1,93 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + + + + + + + {632A8F38-D0F0-4D22-86B3-D69F5E6BF63A} + libLocalStorage + + + + StaticLibrary + true + v110_xp + Unicode + + + StaticLibrary + false + v110_xp + true + Unicode + + + + + + + + + + + + + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + + + + Level3 + Disabled + + + $(EngineRoot)external\sqlite3\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + 4267;4251;4244;%(DisableSpecificWarnings) + false + + + true + + + + + Level3 + MaxSpeed + true + true + + + $(EngineRoot)external\sqlite3\include;%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + + + true + true + true + + + + + + \ No newline at end of file diff --git a/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.filters b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.filters new file mode 100644 index 0000000000..b23d606b74 --- /dev/null +++ b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.filters @@ -0,0 +1,21 @@ + + + + + {0310200c-b520-4f77-85f6-46f568b10f4d} + + + {69cfa37c-4b20-409e-ad74-a26314878d8a} + + + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.user b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.user new file mode 100644 index 0000000000..a375ae3527 --- /dev/null +++ b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From e99b80b304348f3a944268d3ff58720a6f82f70d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 21 Oct 2013 23:16:21 +0800 Subject: [PATCH 189/557] issue #2771: implements rayCast and rectQuery --- cocos/physics/CCPhysicsBody.cpp | 8 +- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.h | 13 ++- cocos/physics/CCPhysicsWorld.cpp | 136 +++++++++++++++++++---- cocos/physics/CCPhysicsWorld.h | 42 ++++--- cocos/physics/chipmunk/CCPhysicsHelper.h | 2 + 6 files changed, 155 insertions(+), 48 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 8f1e9e5c1d..22a0010cbe 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -77,6 +77,9 @@ PhysicsBody::PhysicsBody() , _linearDamping(0.0f) , _angularDamping(0.0f) , _tag(0) +, _categoryBitmask(UINT_MAX) +, _collisionBitmask(UINT_MAX) +, _contactTestBitmask(0) { } @@ -109,11 +112,6 @@ PhysicsBody* PhysicsBody::create() return nullptr; } -void update(float delta) -{ - -} - PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 72cad042bc..65d9f7318a 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -276,8 +276,8 @@ protected: int _tag; int _categoryBitmask; - int _contactTestBitmask; int _collisionBitmask; + int _contactTestBitmask; friend class PhysicsWorld; friend class PhysicsShape; diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 3f2ef8659c..9b9e3044c0 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -80,6 +80,7 @@ private: bool _notify; friend class PhysicsWorld; + friend class PhysicsWorldCallback; }; /* @@ -94,7 +95,7 @@ private: static PhysicsContactPreSolve* create(); bool init(); - friend class PhysicsWorld; + friend class PhysicsWorldCallback; }; /* @@ -109,7 +110,7 @@ private: static PhysicsContactPostSolve* create(); bool init(); - friend class PhysicsWorld; + friend class PhysicsWorldCallback; }; /* @@ -125,20 +126,20 @@ public: /* * @brief it will called at two shapes start to contact, and only call it once. */ - std::function onContactBegin; + std::function onContactBegin; /* * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. */ - std::function onContactPreSolve; + std::function onContactPreSolve; /* * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info */ - std::function onContactPostSolve; + std::function onContactPostSolve; /* * @brief it will called at two shapes separated, and only call it once. * onContactBegin and onContactEnd will called in pairs. */ - std::function onContactEnd; + std::function onContactEnd; }; NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 30939dc9fd..6ca256bc67 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -60,12 +60,45 @@ NS_CC_BEGIN #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +namespace +{ + typedef struct RayCastCallbackInfo + { + PhysicsWorld* world; + PhysicsRayCastCallback* callback; + Point p1; + Point p2; + void* data; + }RayCastCallbackInfo; + + typedef struct RectQueryCallbackInfo + { + PhysicsWorld* world; + PhysicsRectQueryCallback* callback; + void* data; + }RectQueryCallbackInfo; +} + +class PhysicsWorldCallback +{ +public: + static int collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world); + static int collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world); + static void collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world); + static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world); + static void rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info); + static void rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info); + +private: + static bool continues; +}; + +bool PhysicsWorldCallback::continues = true; + const float PHYSICS_INFINITY = INFINITY; -int PhysicsWorld::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data) +int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world) { - PhysicsWorld* world = static_cast(data); - CP_ARBITER_GET_SHAPES(arb, a, b); auto ita = PhysicsShapeInfo::map.find(a); @@ -78,23 +111,20 @@ int PhysicsWorld::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *spa return world->collisionBeginCallback(*static_cast(arb->data)); } -int PhysicsWorld::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) +int PhysicsWorldCallback::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - PhysicsWorld* world = static_cast(data); return world->collisionPreSolveCallback(*static_cast(arb->data), PhysicsContactPreSolve()); } -void PhysicsWorld::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) +void PhysicsWorldCallback::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - PhysicsWorld* world = static_cast(data); world->collisionPostSolveCallback(*static_cast(arb->data), PhysicsContactPostSolve()); } -void PhysicsWorld::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) +void PhysicsWorldCallback::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - PhysicsWorld* world = static_cast(data); PhysicsContact* contact = static_cast(arb->data); world->collisionSeparateCallback(*contact); @@ -102,6 +132,40 @@ void PhysicsWorld::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, delete contact; } +void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info) +{ + if (!PhysicsWorldCallback::continues) + { + return; + } + + auto it = PhysicsShapeInfo::map.find(shape); + CC_ASSERT(it != PhysicsShapeInfo::map.end()); + + PhysicsWorldCallback::continues = info->callback->report(*info->world, + *it->second->shape, + Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), + Point(n.x, n.y), + (float)t, + info->data); +} + +void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) +{ + auto it = PhysicsShapeInfo::map.find(shape); + + CC_ASSERT(it != PhysicsShapeInfo::map.end()); + + if (!PhysicsWorldCallback::continues) + { + return; + } + + PhysicsWorldCallback::continues = info->callback->report(*info->world, + *it->second->shape, + info->data); +} + bool PhysicsWorld::init() { _info = new PhysicsWorldInfo(); @@ -109,10 +173,10 @@ bool PhysicsWorld::init() cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); cpSpaceSetDefaultCollisionHandler(_info->space, - PhysicsWorld::collisionBeginCallbackFunc, - PhysicsWorld::collisionPreSolveCallbackFunc, - PhysicsWorld::collisionPostSolveCallbackFunc, - PhysicsWorld::collisionSeparateCallbackFunc, + (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, + (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, + (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, + (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, this); return true; @@ -368,12 +432,14 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) PhysicsBody* bodyA = contact.getShapeA()->getBody(); PhysicsBody* bodyB = contact.getShapeB()->getBody(); - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0) + if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 + || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) { contact.setNotify(false); } - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0) + if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0 + || (bodyB->getCategoryBitmask() & bodyA->getCollisionBitmask()) == 0) { ret = false; } @@ -384,10 +450,10 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) // so if the mask test is false, the two bodies won't have collision. if (ret) { - ret = _listener->onContactBegin(contact); + ret = _listener->onContactBegin(*this, contact); }else { - _listener->onContactBegin(contact); + _listener->onContactBegin(*this, contact); } } @@ -403,7 +469,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const Physi if (_listener && _listener->onContactPreSolve) { - return _listener->onContactPreSolve(contact, solve); + return _listener->onContactPreSolve(*this, contact, solve); } return true; @@ -418,7 +484,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const Phy if (_listener && _listener->onContactPreSolve) { - _listener->onContactPostSolve(contact, solve); + _listener->onContactPostSolve(*this, contact, solve); } } @@ -431,7 +497,7 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) if (_listener && _listener->onContactEnd) { - _listener->onContactEnd(contact); + _listener->onContactEnd(*this, contact); } } @@ -456,6 +522,36 @@ void PhysicsWorld::setGravity(Point gravity) cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); } + +void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) +{ + RayCastCallbackInfo info = {this, &callback, point1, point2, data}; + cpSpaceSegmentQuery(this->_info->space, + PhysicsHelper::point2cpv(point1), + PhysicsHelper::point2cpv(point2), + CP_ALL_LAYERS, + CP_NO_GROUP, + (cpSpaceSegmentQueryFunc)PhysicsWorldCallback::rayCastCallbackFunc, + &info); +} + + +void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) +{ + RectQueryCallbackInfo info = {this, &callback, data}; + cpSpaceBBQuery(this->_info->space, + PhysicsHelper::rect2cpbb(rect), + CP_ALL_LAYERS, + CP_NO_GROUP, + (cpSpaceBBQueryFunc)PhysicsWorldCallback::rectQueryCallbackFunc, + &info); +} + +Array* PhysicsWorld::getAllBody() const +{ + return _bodys; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 3247ab5221..fa6a509dfc 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -33,12 +33,6 @@ #include "CCObject.h" #include "CCGeometry.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -typedef struct cpArbiter cpArbiter; -typedef struct cpSpace cpSpace; -#endif - NS_CC_BEGIN class PhysicsBody; @@ -55,6 +49,29 @@ class Sprite; class Scene; class DrawNode; +class PhysicsWorld; +class PhysicsRayCastCallback +{ +public: + /** + * @brief Called for each fixture found in the query. You control how the ray cast + * proceeds by returning a float: + * return true: continue + * return false: terminate the ray cast + * @param fixture the fixture hit by the ray + * @param point the point of initial intersection + * @param normal the normal vector at the point of intersection + * @return true to continue, false to terminate + */ + std::function report; +}; + +class PhysicsRectQueryCallback +{ +public: + std::function report; +}; + /** * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. */ @@ -68,9 +85,8 @@ public: /** Remove all joints from the physics world.*/ void removeAllJoints(); - Array* getBodysAlongRay(Point start, Point end) const; - Array* getBodysAtPoint(Point point) const; - Array* getBodysInRect(Rect rect) const; + void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); + void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); Array* getAllBody() const; /** Register a listener to receive contact callbacks*/ @@ -111,13 +127,6 @@ protected: virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); virtual void collisionSeparateCallback(PhysicsContact& contact); -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - static int collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data); - static int collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); -#endif - protected: Point _gravity; float _speed; @@ -140,6 +149,7 @@ protected: friend class Scene; friend class PhysicsBody; friend class PhysicsShape; + friend class PhysicsWorldCallback; }; NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index 337bb1a1df..bf6f6d14db 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -43,6 +43,8 @@ public: static cpVect size2cpv(const Size& size) { return cpv(size.width, size.height); } static float cpfloat2float(cpFloat f) { return f; } static cpFloat float2cpfloat(float f) { return f; } + static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); } + static Rect cpbb2rect(const cpBB& bb) { return Rect(bb.l, bb.b, bb.r, bb.t); } static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) { From c6f9f0e4061ef3c0c05b86d19ce2a82cb5b02cd7 Mon Sep 17 00:00:00 2001 From: lite3 Date: Tue, 22 Oct 2013 11:30:53 +0800 Subject: [PATCH 190/557] do not change anchor point of child. --- extensions/GUI/CCScrollView/CCScrollView.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 95b9c48c51..ee6a416310 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -469,8 +469,6 @@ void ScrollView::updateInset() */ void ScrollView::addChild(Node * child, int zOrder, int tag) { - child->ignoreAnchorPointForPosition(false); - child->setAnchorPoint(Point(0.0f, 0.0f)); if (_container != child) { _container->addChild(child, zOrder, tag); } else { From b56a9962a6f4334856bb79792244094255014944 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 22 Oct 2013 15:32:44 +0800 Subject: [PATCH 191/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 62169acdf3..b1708fabda 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,6 +19,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Fixed a memory leak in ScriptingCore::runScript() [FIX] sys.localStorage.getItem() does not support non-ascii string. [FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. + [FIX] CCBReader can't play sequence automatically in JSB. [Lua Binding] [NEW] Added Armature lua binding and added test samples. From 7ef5bd81109facaeadc5cc2d1f639e5b9fedfc7c Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 22 Oct 2013 15:34:32 +0800 Subject: [PATCH 192/557] Update AUTHORS --- AUTHORS | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 71cba826b3..f416e6c39f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -622,7 +622,10 @@ Developers: lettas A fix for multi-platform template. - + + HoGarfield (garfield_ho) + Fixed a bug that CCBReader can't play sequence automatically in JSB. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 55d45081f68833473851617adce8d382ee30ed83 Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Tue, 22 Oct 2013 15:41:43 +0800 Subject: [PATCH 193/557] Fixed name --- cocos/scripting/javascript/script/jsb_cocos2d.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index 6ed7e19cba..684eb386d9 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -7,10 +7,10 @@ var cc = cc || {}; cc.RESOLUTION_POLICY = { // The entire application is visible in the specified area without trying to preserve the original aspect ratio. // Distortion can occur, and the application may appear stretched or compressed. -EXACTFIT:0, +EXACT_FIT:0, // The entire application fills the specified area, without distortion but possibly with some cropping, // while maintaining the original aspect ratio of the application. -NOBORDER:1, +NO_BORDER:1, // The entire application is visible in the specified area without distortion while maintaining the original // aspect ratio of the application. Borders can appear on two sides of the application. SHOW_ALL:2, @@ -18,12 +18,12 @@ SHOW_ALL:2, // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios -HEIGHT:3, +FIXED_HEIGHT:3, // The application takes the width of the design resolution size and modifies the height of the internal // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios -WIDTH:4, +FIXED_WIDTH:4, UNKNOWN:5 }; From 31a2217178825e622d73f9f79e326041b3614ee1 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 22 Oct 2013 15:56:08 +0800 Subject: [PATCH 194/557] issues #2905:add miss file --- cocos/2d/cocos2d_headers.props | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 cocos/2d/cocos2d_headers.props diff --git a/cocos/2d/cocos2d_headers.props b/cocos/2d/cocos2d_headers.props new file mode 100644 index 0000000000..a5d8616d03 --- /dev/null +++ b/cocos/2d/cocos2d_headers.props @@ -0,0 +1,19 @@ + + + + + $(MSBuildThisFileDirectory)..\..\ + + + + + $(EngineRoot)cocos\2d;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES; + + + + + $(EngineRoot) + true + + + \ No newline at end of file From 0002815acb3e276bb9a8d5b0860ec5e6459a640c Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Tue, 22 Oct 2013 15:56:35 +0800 Subject: [PATCH 195/557] Modify the sequenceCompleted method in CCBAnimationManager,So it can set the next sequence in callback --- .../cocosbuilder/CCBAnimationManager.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index 13b039dcac..0ca75e25ce 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -910,6 +910,11 @@ void CCBAnimationManager::sequenceCompleted() _lastCompletedSequenceName = runningSequenceName; } + if (nextSeqId != -1) + { + runAnimationsForSequenceIdTweenDuration(nextSeqId, 0); + } + if (_delegate) { // There may be another runAnimation() call in this delegate method @@ -920,11 +925,6 @@ void CCBAnimationManager::sequenceCompleted() if (_target && _animationCompleteCallbackFunc) { (_target->*_animationCompleteCallbackFunc)(); } - - if (nextSeqId != -1) - { - runAnimationsForSequenceIdTweenDuration(nextSeqId, 0); - } } // Custom actions From be1f17ca0ff8aefb5117eeb14b0c89db35e84d16 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Tue, 22 Oct 2013 16:14:49 +0800 Subject: [PATCH 196/557] issue #3037:Add assetsmananger lua binding and a releated test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCScriptSupport.h | 1 + cocos/scripting/lua/bindings/CCLuaEngine.cpp | 48 +++++ cocos/scripting/lua/bindings/CCLuaEngine.h | 1 + .../lua/bindings/LuaScriptHandlerMgr.h | 4 + .../lua_assetsmanager_test_sample.cpp | 164 ++++++++++++++++++ .../bindings/lua_assetsmanager_test_sample.h | 17 ++ .../lua_cocos2dx_extension_manual.cpp | 120 +++++++++++++ .../bindings/lua_cocos2dx_extension_manual.h | 11 ++ .../scripting/lua/script/Cocos2dConstants.lua | 10 ++ extensions/assets-manager/AssetsManager.h | 6 + samples/Lua/TestLua/Classes/AppDelegate.cpp | 7 + .../AssetsManagerTest/AssetsManagerModule.lua | 43 +++++ .../AssetsManagerTest/AssetsManagerTest.lua | 161 +++++++++++++++++ .../TestLua/Resources/luaScript/mainMenu.lua | 2 + tools/tojs/cocos2dx_extension.ini | 2 +- tools/tolua/cocos2dx_extension.ini | 6 +- 17 files changed, 601 insertions(+), 4 deletions(-) create mode 100644 cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp create mode 100644 cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h create mode 100644 samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua create mode 100644 samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 18265b616b..627e8dbf20 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1c487d29bdc2d80516e86e2ee93b1664e9f7df2f \ No newline at end of file +486af7c751cc94ff5dc25748cdb4bcb183be5dd2 \ No newline at end of file diff --git a/cocos/2d/CCScriptSupport.h b/cocos/2d/CCScriptSupport.h index 0c7f502a8b..f5803f4cb7 100644 --- a/cocos/2d/CCScriptSupport.h +++ b/cocos/2d/CCScriptSupport.h @@ -211,6 +211,7 @@ enum ScriptEventType kControlEvent, kCommonEvent, kTableViewEvent,//Now it's only used in LuaBinding + kAssetsManagerEvent,//Now it's only used in Lua Binding }; struct BasicScriptData diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp index 558b68acb1..dfbf607e84 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.cpp +++ b/cocos/scripting/lua/bindings/CCLuaEngine.cpp @@ -252,6 +252,11 @@ int LuaEngine::sendEvent(ScriptEvent* evt) return handleTableViewEvent(evt->data); } break; + case kAssetsManagerEvent: + { + return handleAssetsManagerEvent(evt->data); + } + break; default: break; } @@ -770,4 +775,47 @@ int LuaEngine::handleTableViewEventReturnArray(void* data,int numResults,Array& return ret; } + +int LuaEngine::handleAssetsManagerEvent(void* data) +{ + if (nullptr == data) + return 0; + + BasicScriptData* eventData = static_cast(data); + if (nullptr == eventData->nativeObject || nullptr == eventData->value) + return 0; + + LuaAssetsManagerEventData* assetsManagerEventData = static_cast(eventData->value); + if (assetsManagerEventData->handlerType < ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS || assetsManagerEventData->handlerType > ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR ) + return 0; + + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)eventData->nativeObject, assetsManagerEventData->handlerType); + + if (0 == handler) + return 0; + + int ret = 0; + switch (assetsManagerEventData->handlerType) + { + case ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS: + case ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR: + { + _stack->pushInt(assetsManagerEventData->value); + ret = _stack->executeFunctionByHandler(handler, 1); + } + break; + + case ScriptHandlerMgr::HandlerType::ASSETSMANAGER_SUCCESS: + { + ret = _stack->executeFunctionByHandler(handler, 0); + } + break; + + default: + break; + } + + return ret; +} + NS_CC_END diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.h b/cocos/scripting/lua/bindings/CCLuaEngine.h index 0a1442aaaa..e739103080 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.h +++ b/cocos/scripting/lua/bindings/CCLuaEngine.h @@ -141,6 +141,7 @@ private: int handlerControlEvent(void* data); int handleTableViewEvent(void* data); int handleTableViewEventReturnArray(void* data,int numResults,Array& resultArray); + int handleAssetsManagerEvent(void* data); void extendWebsocket(lua_State* lua_S); void extendGLNode(lua_State* lua_S); private: diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h index 44ea6fa103..d460804cf2 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h @@ -95,6 +95,10 @@ public: TABLECELL_SIZE_FOR_INDEX, TABLECELL_AT_INDEX, TABLEVIEW_NUMS_OF_CELLS, + + ASSETSMANAGER_PROGRESS, + ASSETSMANAGER_SUCCESS, + ASSETSMANAGER_ERROR, }; typedef int Handler; diff --git a/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp b/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp new file mode 100644 index 0000000000..e3d6377f0b --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp @@ -0,0 +1,164 @@ +#include "lua_assetsmanager_test_sample.h" + +#ifdef __cplusplus +extern "C" { +#endif +#include "tolua_fix.h" +#ifdef __cplusplus +} +#endif + +#include "cocos2d.h" +#include "cocos-ext.h" + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) +#include +#include +#endif + +USING_NS_CC; +USING_NS_CC_EXT; + + +static int lua_cocos2dx_createDownloadDir(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = lua_gettop(L); +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + if (0 == argc) + { + std::string pathToSave = FileUtils::getInstance()->getWritablePath(); + pathToSave += "tmpdir"; + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) + DIR *pDir = NULL; + + pDir = opendir (pathToSave.c_str()); + if (! pDir) + { + mkdir(pathToSave.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); + } +#else + if ((GetFileAttributesA(pathToSave.c_str())) == INVALID_FILE_ATTRIBUTES) + { + CreateDirectoryA(pathToSave.c_str(), 0); + } +#endif + tolua_pushstring(L, pathToSave.c_str()); + CCLOG("the path to save is %s",pathToSave.c_str()); + return 1; + } + + CCLOG("'createDownloadDir' function wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'createDownloadDir'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_deleteDownloadDir(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = lua_gettop(L); + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 1, 0, &tolua_err)) goto tolua_lerror; +#endif + std::string pathToSave = tolua_tostring(L, 1, ""); + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) + std::string command = "rm -r "; + // Path may include space. + command += "\"" + pathToSave + "\""; + system(command.c_str()); +#else + std::string command = "rd /s /q "; + // Path may include space. + command += "\"" + pathToSave + "\""; + system(command.c_str()); +#endif + return 0; + } + + CCLOG("'resetDownloadDir' function wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'resetDownloadDir'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_addSearchPath(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = lua_gettop(L); + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 1, 0, &tolua_err) || + !tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + std::string pathToSave = tolua_tostring(L, 1, ""); + bool before = tolua_toboolean(L, 2, 0); + std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); + if (before) + { + searchPaths.insert(searchPaths.begin(), pathToSave); + } + else + { + searchPaths.push_back(pathToSave); + } + + FileUtils::getInstance()->setSearchPaths(searchPaths); + + return 0; + } + CCLOG("'addSearchPath' function wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'addSearchPath'.",&tolua_err); + return 0; +#endif +} + +int register_assetsmanager_test_sample(lua_State* L) +{ + tolua_open(L); + tolua_module(L, NULL, 0); + tolua_beginmodule(L, NULL); + tolua_function(L, "createDownloadDir", lua_cocos2dx_createDownloadDir); + tolua_function(L, "deleteDownloadDir", lua_cocos2dx_deleteDownloadDir); + tolua_function(L, "addSearchPath", lua_cocos2dx_addSearchPath); + tolua_endmodule(L); + return 0; +} diff --git a/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h b/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h new file mode 100644 index 0000000000..967593de71 --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h @@ -0,0 +1,17 @@ +#ifndef COCOS2DX_COCOS_SCRIPTING_LUA_BINDINGS_LUA_ASSETSMANAGER_TEST_SAMPLE_H +#define COCOS2DX_COCOS_SCRIPTING_LUA_BINDINGS_LUA_ASSETSMANAGER_TEST_SAMPLE_H + +#ifdef __cplusplus +extern "C" { +#endif +#include "tolua++.h" +#ifdef __cplusplus +} +#endif + +/** + * The apis which are bound in this file are temporary for the assetsmanager test sample.After the completion of some systems like fileutils,these apis will be deprecated + */ +TOLUA_API int register_assetsmanager_test_sample(lua_State* tolua_S); + +#endif // #ifndef COCOS2DX_COCOS_SCRIPTING_LUA_BINDINGS_LUA_ASSETSMANAGER_TEST_SAMPLE_H diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index 0e4582b126..e74dbac377 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -1426,6 +1426,125 @@ static void extendBone(lua_State* L) } } +class LuaAssetsManagerDelegateProtocol:public Object, public AssetsManagerDelegateProtocol +{ +public: + virtual ~LuaAssetsManagerDelegateProtocol() + {} + + virtual void onProgress(int percent) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS); + if (0 != handler) + { + LuaAssetsManagerEventData eventData(ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS,percent); + BasicScriptData data((void*)this,&eventData); + ScriptEvent event(kAssetsManagerEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + } + + virtual void onSuccess() + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_SUCCESS); + if (0 != handler) + { + LuaAssetsManagerEventData eventData(ScriptHandlerMgr::HandlerType::ASSETSMANAGER_SUCCESS); + BasicScriptData data((void*)this,&eventData); + ScriptEvent event(kAssetsManagerEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + } + + virtual void onError(AssetsManager::ErrorCode errorCode) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR); + if (0 != handler) + { + LuaAssetsManagerEventData eventData(ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR, (int)errorCode); + BasicScriptData data((void*)this,&eventData); + ScriptEvent event(kAssetsManagerEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + } +}; + +static int lua_cocos2dx_AssetsManager_setDelegate(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + AssetsManager* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"AssetsManager",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (AssetsManager*) tolua_tousertype(L,1,0); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_AssetsManager_setDelegate'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (2 == argc) + { + LuaAssetsManagerDelegateProtocol* delegate = dynamic_cast( self->getDelegate()); + if (nullptr == delegate) + { + delegate = new LuaAssetsManagerDelegateProtocol(); + if (nullptr == delegate) + return 0; + + self->setUserObject(delegate); + self->setDelegate(delegate); + delegate->release(); + } + + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(L, 2, "LUA_FUNCTION", 0, &tolua_err) || + !tolua_isnumber(L, 3, 0, &tolua_err) ) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = toluafix_ref_function(L, 2, 0); + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(L,3,0) + (int)ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS); + + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)delegate, handler, handlerType); + return 0; + } + } + + CCLOG("'setDelegate' function of AssetsManager has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setDelegate'.",&tolua_err); + return 0; +#endif +} + +static void extendAssetsManager(lua_State* L) +{ + lua_pushstring(L, "AssetsManager"); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_istable(L,-1)) + { + tolua_function(L, "setDelegate", lua_cocos2dx_AssetsManager_setDelegate); + } +} + int register_all_cocos2dx_extension_manual(lua_State* tolua_S) { extendScrollView(tolua_S); @@ -1435,5 +1554,6 @@ int register_all_cocos2dx_extension_manual(lua_State* tolua_S) extendCCBAnimationManager(tolua_S); extendTableView(tolua_S); extendBone(tolua_S); + extendAssetsManager(tolua_S); return 0; } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h index dc7dd1d623..2c8b22eddb 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h @@ -26,4 +26,15 @@ struct LuaTableViewEventData } }; +struct LuaAssetsManagerEventData +{ + cocos2d::ScriptHandlerMgr::HandlerType handlerType; + int value; + + LuaAssetsManagerEventData(cocos2d::ScriptHandlerMgr::HandlerType _handleType, int _value = 0):handlerType(_handleType),value(_value) + { + } +}; + + #endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_LUA_COCOS2DX_EXTENSION_MANUAL_H diff --git a/cocos/scripting/lua/script/Cocos2dConstants.lua b/cocos/scripting/lua/script/Cocos2dConstants.lua index 5a8ae27e94..e4dc029c55 100644 --- a/cocos/scripting/lua/script/Cocos2dConstants.lua +++ b/cocos/scripting/lua/script/Cocos2dConstants.lua @@ -272,3 +272,13 @@ cc.WEBSOCKET_STATE_CONNECTING = 0 cc.WEBSOCKET_STATE_OPEN = 1 cc.WEBSOCKET_STATE_CLOSING = 2 cc.WEBSOCKET_STATE_CLOSED = 3 + +cc.ASSETSMANAGER_CREATE_FILE = 0 +cc.ASSETSMANAGER_NETWORK = 1 +cc.ASSETSMANAGER_NO_NEW_VERSION = 2 +cc.ASSETSMANAGER_UNCOMPRESS = 3 + +cc.ASSETSMANAGER_PROTOCOL_PROGRESS = 0 +cc.ASSETSMANAGER_PROTOCOL_SUCCESS = 1 +cc.ASSETSMANAGER_PROTOCOL_ERROR = 2 + diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 23e1a27774..80f0ae5d81 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -141,6 +141,12 @@ public: */ void setDelegate(AssetsManagerDelegateProtocol *delegate); + /** + * @js NA + * @lua NA + */ + AssetsManagerDelegateProtocol* getDelegate() { return _delegate ;} + /** @brief Sets connection time out in seconds */ void setConnectionTimeout(unsigned int timeout); diff --git a/samples/Lua/TestLua/Classes/AppDelegate.cpp b/samples/Lua/TestLua/Classes/AppDelegate.cpp index 6f5f6dedfe..025f938b6b 100644 --- a/samples/Lua/TestLua/Classes/AppDelegate.cpp +++ b/samples/Lua/TestLua/Classes/AppDelegate.cpp @@ -3,6 +3,7 @@ #include "AppDelegate.h" #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" +#include "lua_assetsmanager_test_sample.h" using namespace CocosDenshion; @@ -50,7 +51,13 @@ bool AppDelegate::applicationDidFinishLaunching() LuaEngine* pEngine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(pEngine); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ||CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + LuaStack* stack = pEngine->getLuaStack(); + register_assetsmanager_test_sample(stack->getLuaState()); +#endif + std::vector searchPaths = pFileUtils->getSearchPaths(); + searchPaths.insert(searchPaths.begin(), "Images"); searchPaths.insert(searchPaths.begin(), "cocosbuilderRes"); #if CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua new file mode 100644 index 0000000000..ab9b3874a6 --- /dev/null +++ b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua @@ -0,0 +1,43 @@ +local AssetManagerModule = {} + +function AssetManagerModule.newScene(backfunc) + + local winSize = cc.Director:getInstance():getWinSize() + + local newScene = cc.Scene:create() + local layer = cc.Layer:create() + + local function backToUpdate() + local scene = backfunc() + if scene ~= nil then + cc.Director:getInstance():replaceScene(scene) + end + end + + --Create BackMneu + cc.MenuItemFont:setFontName("Arial") + cc.MenuItemFont:setFontSize(24) + local backMenuItem = cc.MenuItemFont:create("Back") + backMenuItem:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) + backMenuItem:registerScriptTapHandler(backToUpdate) + + local backMenu = cc.Menu:create() + backMenu:setPosition(0, 0) + backMenu:addChild(backMenuItem) + layer:addChild(backMenu,6) + + local helloLabel = cc.LabelTTF:create("Hello World", "Arial", 38) + helloLabel:setPosition(cc.p(winSize.width / 2, winSize.height - 40)) + layer:addChild(helloLabel, 5) + + local sprite = cc.Sprite:create("background.png") + sprite:setAnchorPoint(cc.p(0.5, 0.5)) + sprite:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) + layer:addChild(sprite, 0) + + newScene:addChild(layer) + cc.Director:getInstance():replaceScene(newScene) +end + + +return AssetManagerModule diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua new file mode 100644 index 0000000000..853342a706 --- /dev/null +++ b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua @@ -0,0 +1,161 @@ +local targetPlatform = cc.Application:getInstance():getTargetPlatform() + +local lineSpace = 40 +local itemTagBasic = 1000 +local menuItemNames = +{ + "enter", + "reset", + "update", +} + +local winSize = cc.Director:getInstance():getWinSize() + +local function updateLayer() + + local support = false + if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) + or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) + or (cc.PLATFORM_OS_IPHONE == targetPlatform) then + support = true + end + + if not support then + return nil + end + + local isUpdateItemClicked = false + local assetsManager = nil + local pathToSave = "" + + local layer = cc.Layer:create() + local menu = cc.Menu:create() + menu:setPosition(cc.p(0, 0)) + cc.MenuItemFont:setFontName("Arial") + cc.MenuItemFont:setFontSize(24) + + local progressLable = cc.LabelTTF:create("","Arial",30) + progressLable:setPosition(cc.p(140,50)) + layer:addChild(progressLable) + + pathToSave = createDownloadDir() + + local function onError(errorCode) + if errorCode == cc.ASSETSMANAGER_NO_NEW_VERSION then + progressLable:setString("no new version") + elseif errorCode == cc.ASSETSMANAGER_NETWORK then + progressLable:setString("network error") + end + end + + local function onProgress( percent ) + local progress = string.format("downloading %d%%",percent) + progressLable:setString(progress) + end + + local function onSuccess() + progressLable:setString("downloading ok") + end + + local function getAssetsManager() + if nil == assetsManager then + assetsManager = cc.AssetsManager:new("https://raw.github.com/samuele3hu/AssetsManagerTest/master/package.zip", + "https://raw.github.com/samuele3hu/AssetsManagerTest/master/version", + pathToSave) + assetsManager:retain() + assetsManager:setDelegate(onError, cc.ASSETSMANAGER_PROTOCOL_ERROR ) + assetsManager:setDelegate(onProgress, cc.ASSETSMANAGER_PROTOCOL_PROGRESS) + assetsManager:setDelegate(onSuccess, cc.ASSETSMANAGER_PROTOCOL_SUCCESS ) + assetsManager:setConnectionTimeout(3) + end + + return assetsManager + end + + local function update(sender) + + progressLable:setString("") + + getAssetsManager():update() + + --isUpdateItemClicked = true + + end + + local function reset(sender) + progressLable:setString("") + + deleteDownloadDir(pathToSave) + + getAssetsManager():deleteVersion() + + createDownloadDir() + end + + local function reloadModule( moduleName ) + + package.loaded[moduleName] = nil + + return require(moduleName) + end + + local function enter(sender) + + if not isUpdateItemClicked then + addSearchPath(pathToSave,true) + end + + assetsManagerModule = reloadModule("luaScript/AssetsManagerTest/AssetsManagerModule") + + assetsManagerModule.newScene(AssetsManagerTestMain) + end + + local callbackFuncs = + { + enter, + reset, + update, + } + + local function menuCallback(tag, menuItem) + local scene = nil + local nIdx = menuItem:getZOrder() - itemTagBasic + local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) + if nil ~= ExtensionsTestScene then + cc.Director:getInstance():replaceScene(ExtensionsTestScene) + end + end + + for i = 1, table.getn(menuItemNames) do + local item = cc.MenuItemFont:create(menuItemNames[i]) + item:registerScriptTapHandler(callbackFuncs[i]) + item:setPosition(winSize.width / 2, winSize.height - i * lineSpace) + if not support then + item:setEnabled(false) + end + menu:addChild(item, itemTagBasic + i) + end + + local function onNodeEvent(msgName) + if nil ~= assetsManager then + assetsManager:release() + assetsManager = nil + end + end + + layer:registerScriptHandler(onNodeEvent) + + layer:addChild(menu) + + return layer +end + +------------------------------------- +-- AssetsManager Test +------------------------------------- +function AssetsManagerTestMain() + local scene = cc.Scene:create() + scene:addChild(updateLayer()) + scene:addChild(CreateBackMenuItem()) + return scene +end diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua index 73d79855d6..1a534252e1 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua @@ -13,6 +13,7 @@ require "luaScript/ActionManagerTest/ActionManagerTest" require "luaScript/ActionsEaseTest/ActionsEaseTest" require "luaScript/ActionsProgressTest/ActionsProgressTest" require "luaScript/ActionsTest/ActionsTest" +require "luaScript/AssetsManagerTest/AssetsManagerTest" require "luaScript/BugsTest/BugsTest" require "luaScript/ClickAndMoveTest/ClickAndMoveTest" require "luaScript/CocosDenshionTest/CocosDenshionTest" @@ -58,6 +59,7 @@ local _allTests = { { isSupported = true, name = "ActionsEaseTest" , create_func = EaseActionsTest }, { isSupported = true, name = "ActionsProgressTest" , create_func = ProgressActionsTest }, { isSupported = true, name = "ActionsTest" , create_func = ActionsTest }, + { isSupported = true, name = "AssetsManagerTest" , create_func = AssetsManagerTestMain }, { isSupported = false, name = "Box2dTest" , create_func= Box2dTestMain }, { isSupported = false, name = "Box2dTestBed" , create_func= Box2dTestBedMain }, { isSupported = true, name = "BugsTest" , create_func= BugsTestMain }, diff --git a/tools/tojs/cocos2dx_extension.ini b/tools/tojs/cocos2dx_extension.ini index 1519b2eb92..c91b2545ea 100644 --- a/tools/tojs/cocos2dx_extension.ini +++ b/tools/tojs/cocos2dx_extension.ini @@ -44,7 +44,7 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], EditBox::[(g|s)etDelegate ^keyboard.* touchDownAction getScriptEditBoxHandler registerScriptEditBoxHandler unregisterScriptEditBoxHandler], TableView::[create (g|s)etDataSource$ (g|s)etDelegate], - AssetsManager::[setDelegate], + AssetsManager::[(g|s)etDelegate], AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index 67d87c51d6..dd5aa433aa 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,7 +13,7 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT cxxgenerator_headers = @@ -26,7 +26,7 @@ headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/ # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -43,6 +43,8 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType (g|s)etDelegate .*HSV], EditBox::[(g|s)etDelegate ^keyboard.* touchDownAction getScriptEditBoxHandler registerScriptEditBoxHandler unregisterScriptEditBoxHandler], TableView::[create (g|s)etDataSource$ (g|s)etDelegate], + AssetsManager::[(g|s)etDelegate], + AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], ControlSwitchSprite::[*], From 7a1b6f2972939741b79248b8e605803dbc846f02 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 22 Oct 2013 16:33:41 +0800 Subject: [PATCH 197/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index b1708fabda..7b81c3c5f9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -7,6 +7,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] removeSpriteFramesFromFile() crashes if file doesn't exist. [FIX] Avoid unnecessary object duplication for Scale9Sprite. [FIX] create_project.py does not rename/replace template projects completely. + [FIX] Could not set next animation in CCBAnimationCompleted callback. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From c47d2b7ae287dc61137594c3eaaca2ccccb53182 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 22 Oct 2013 16:34:10 +0800 Subject: [PATCH 198/557] Update AUTHORS --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index f416e6c39f..4dff8c12b5 100644 --- a/AUTHORS +++ b/AUTHORS @@ -625,6 +625,7 @@ Developers: HoGarfield (garfield_ho) Fixed a bug that CCBReader can't play sequence automatically in JSB. + Could not set next animation in CCBAnimationCompleted callback. Retired Core Developers: WenSheng Yang From 24561860f0d3ea47474f7094b7c2d6596c7c18c6 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 22 Oct 2013 18:00:24 +0800 Subject: [PATCH 199/557] issue #2771: add ray cast test --- cocos/physics/CCPhysicsShape.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 58 ++-- cocos/physics/CCPhysicsWorld.h | 14 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 291 +++++++++++++++++- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 32 +- 5 files changed, 349 insertions(+), 48 deletions(-) diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4191c7e6b5..d1b5e0db04 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -97,7 +97,7 @@ public: virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } - static Point* recenterPoints(Point* points, int count, Point center); + static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); static Point getPolyonCenter(Point* points, int count); protected: diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 6ca256bc67..cab183ba7a 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -89,7 +89,7 @@ public: static void rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info); static void rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info); -private: +public: static bool continues; }; @@ -391,12 +391,16 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) Point centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(shape))) + PhysicsHelper::cpv2point(cpCircleShapeGetOffset(shape)); - Point seg[4] = {}; - seg[0] = Point(centre.x - radius, centre.y - radius); - seg[1] = Point(centre.x - radius, centre.y + radius); - seg[2] = Point(centre.x + radius, centre.y + radius); - seg[3] = Point(centre.x + radius, centre.y - radius); - node->drawPolygon(seg, 4, Color4F(), 1, Color4F(1, 0, 0, 1)); + static const int CIRCLE_SEG_NUM = 12; + Point seg[CIRCLE_SEG_NUM] = {}; + + for (int i = 0; i < CIRCLE_SEG_NUM; ++i) + { + float angle = (float)i * M_PI / (float)CIRCLE_SEG_NUM * 2.0f; + Point d(radius * cosf(angle), radius * sinf(angle)); + seg[i] = centre + d; + } + node->drawPolygon(seg, CIRCLE_SEG_NUM, Color4F(1.0f, 0.0f, 0.0f, 0.3f), 1, Color4F(1, 0, 0, 1)); break; } case CP_SEGMENT_SHAPE: @@ -525,26 +529,36 @@ void PhysicsWorld::setGravity(Point gravity) void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) { - RayCastCallbackInfo info = {this, &callback, point1, point2, data}; - cpSpaceSegmentQuery(this->_info->space, - PhysicsHelper::point2cpv(point1), - PhysicsHelper::point2cpv(point2), - CP_ALL_LAYERS, - CP_NO_GROUP, - (cpSpaceSegmentQueryFunc)PhysicsWorldCallback::rayCastCallbackFunc, - &info); + if (callback.report != nullptr) + { + RayCastCallbackInfo info = {this, &callback, point1, point2, data}; + + PhysicsWorldCallback::continues = true; + cpSpaceSegmentQuery(this->_info->space, + PhysicsHelper::point2cpv(point1), + PhysicsHelper::point2cpv(point2), + CP_ALL_LAYERS, + CP_NO_GROUP, + (cpSpaceSegmentQueryFunc)PhysicsWorldCallback::rayCastCallbackFunc, + &info); + } } void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) { - RectQueryCallbackInfo info = {this, &callback, data}; - cpSpaceBBQuery(this->_info->space, - PhysicsHelper::rect2cpbb(rect), - CP_ALL_LAYERS, - CP_NO_GROUP, - (cpSpaceBBQueryFunc)PhysicsWorldCallback::rectQueryCallbackFunc, - &info); + if (callback.report != nullptr) + { + RectQueryCallbackInfo info = {this, &callback, data}; + + PhysicsWorldCallback::continues = true; + cpSpaceBBQuery(this->_info->space, + PhysicsHelper::rect2cpbb(rect), + CP_ALL_LAYERS, + CP_NO_GROUP, + (cpSpaceBBQueryFunc)PhysicsWorldCallback::rectQueryCallbackFunc, + &info); + } } Array* PhysicsWorld::getAllBody() const diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index fa6a509dfc..e61cde2763 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -53,6 +53,10 @@ class PhysicsWorld; class PhysicsRayCastCallback { public: + PhysicsRayCastCallback() + : report(nullptr) + {} + virtual ~PhysicsRayCastCallback(){} /** * @brief Called for each fixture found in the query. You control how the ray cast * proceeds by returning a float: @@ -63,13 +67,19 @@ public: * @param normal the normal vector at the point of intersection * @return true to continue, false to terminate */ - std::function report; + std::function report; }; class PhysicsRectQueryCallback { public: - std::function report; + PhysicsRectQueryCallback() + : report(nullptr) + {} + virtual ~PhysicsRectQueryCallback(){} + +public: + std::function report; }; /** diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 91c67da54d..0c67ddc204 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -9,6 +9,7 @@ namespace CL(PhysicsDemoPyramidStack), CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), + CL(PhysicsDemoRayCast), }; static int sceneIdx=-1; @@ -48,6 +49,8 @@ namespace return layer; } + + static const Color4F STATIC_COLOR = {1.0f, 0.0f, 0.0f, 1.0f}; } @@ -87,6 +90,8 @@ void PhysicsTestScene::toggleDebug() PhysicsDemo::PhysicsDemo() : _scene(nullptr) +, _ball(nullptr) +, _spriteTexture(nullptr) { } @@ -304,22 +309,62 @@ namespace } } -Node* PhysicsDemoLogoSmash::makeBall(float x, float y) +Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial material) { - auto ball = Sprite::createWithTexture(_ball->getTexture()); - ball->setScale(0.1); + Sprite* ball = nullptr; + if (_ball != nullptr) + { + ball = Sprite::createWithTexture(_ball->getTexture()); + }else + { + ball = Sprite::create("Images/ball.png"); + } - auto body = PhysicsBody::createCircle(0.95, PhysicsMaterial(1, 0, 0)); - body->setMass(1.0); - body->setMoment(PHYSICS_INFINITY); + ball->setScale(0.13f * radius); + auto body = PhysicsBody::createCircle(radius, material); ball->setPhysicsBody(body); - ball->setPosition(Point(x, y)); return ball; } +Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial material) +{ + auto box = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowSquare.png") : Sprite::create("Images/CyanSquare.png"); + + box->setScaleX(size.width/100.0f); + box->setScaleY(size.height/100.0f); + + auto body = PhysicsBody::createBox(size); + box->setPhysicsBody(body); + box->setPosition(Point(x, y)); + + return box; +} + +Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial material) +{ + auto triangle = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowTriangle.png") : Sprite::create("Images/CyanTriangle.png"); + + if(size.height == 0) + { + triangle->setScale(size.width/100.0f); + }else + { + triangle->setScaleX(size.width/50.0f); + triangle->setScaleY(size.height/43.5f); + } + + Point vers[] = { Point(0, size.height/2), Point(size.width/2, -size.height/2), Point(-size.width/2, -size.height/2)}; + + auto body = PhysicsBody::createPolygon(vers, 3); + triangle->setPhysicsBody(body); + triangle->setPosition(Point(x, y)); + + return triangle; +} + void PhysicsDemoLogoSmash::onEnter() { PhysicsDemo::onEnter(); @@ -337,19 +382,22 @@ void PhysicsDemoLogoSmash::onEnter() float x_jitter = 0.05*frand(); float y_jitter = 0.05*frand(); - _ball->addChild(makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, - 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2)); + Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, + 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, + 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); + + ball->getPhysicsBody()->setMass(1.0); + ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); + + _ball->addChild(ball); + } } } - auto bullet = Sprite::createWithTexture(_ball->getTexture()); - bullet->setScale(0.5); - - auto body = PhysicsBody::createCircle(8, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); - body->setVelocity(Point(400, 0)); - bullet->setPhysicsBody(body); + auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -393,7 +441,7 @@ void PhysicsDemoPlink::onEnter() { PhysicsDemo::onEnter(); - auto node = Node::create(); + auto node = DrawNode::create(); auto body = PhysicsBody::create(); body->setDynamic(false); node->setPhysicsBody(body); @@ -405,7 +453,11 @@ void PhysicsDemoPlink::onEnter() { for (int j = 0; j < 4; ++j) { - body->addShape(PhysicsShapePolygon::create(tris, 3, PHYSICSSHAPE_MATERIAL_DEFAULT, Point(rect.origin.x + rect.size.width/9*i + (j%2)*40 - 20, rect.origin.y + j*70))); + Point offset(rect.origin.x + rect.size.width/9*i + (j%2)*40 - 20, rect.origin.y + j*70); + body->addShape(PhysicsShapePolygon::create(tris, 3, PHYSICSSHAPE_MATERIAL_DEFAULT, offset)); + + Point drawVec[] = {tris[0] + offset, tris[1] + offset, tris[2] + offset}; + node->drawPolygon(drawVec, 3, STATIC_COLOR, 1, STATIC_COLOR); } } @@ -416,4 +468,209 @@ void PhysicsDemoPlink::onEnter() std::string PhysicsDemoPlink::title() { return "Plink"; +} + +PhysicsDemoRayCast::PhysicsDemoRayCast() +: _angle(0.0f) +, _node(nullptr) +, _mode(0) +{} + +void PhysicsDemoRayCast::onEnter() +{ + PhysicsDemo::onEnter(); + setTouchEnabled(true); + + _scene->getPhysicsWorld()->setGravity(Point::ZERO); + + auto node = DrawNode::create(); + node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + node->drawSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50), 1, STATIC_COLOR); + this->addChild(node); + + MenuItemFont::setFontSize(18); + auto item = MenuItemFont::create("Change Mode(any)", CC_CALLBACK_1(PhysicsDemoRayCast::changeModeCallback, this)); + + auto menu = Menu::create(item, NULL); + this->addChild(menu); + menu->setPosition(Point(VisibleRect::left().x+100, VisibleRect::top().y-10)); + + scheduleUpdate(); +} + +void PhysicsDemoRayCast::changeModeCallback(Object* sender) +{ + _mode = (_mode + 1) % 3; + + switch (_mode) + { + case 0: + ((MenuItemFont*)sender)->setString("Change Mode(any)"); + break; + case 1: + ((MenuItemFont*)sender)->setString("Change Mode(nearest)"); + break; + case 2: + ((MenuItemFont*)sender)->setString("Change Mode(multiple)"); + break; + + default: + break; + } +} + +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data) +{ + *((Point*)data) = point; + return false; +} + +class PhysicsDemoNearestRayCastCallback : public PhysicsRayCastCallback +{ +public: + PhysicsDemoNearestRayCastCallback(); + +private: + float _friction; +}; + +PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() +: _friction(1.0f) +{ + report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + { + if (_friction > fraction) + { + *((Point*)data) = point; + _friction = fraction; + } + + return true; + }; +} + +namespace +{ + static const int MAX_MULTI_RAYCAST_NUM = 5; +} + +class PhysicsDemoMultiRayCastCallback : public PhysicsRayCastCallback +{ +public: + PhysicsDemoMultiRayCastCallback(); + +public: + Point points[MAX_MULTI_RAYCAST_NUM]; + int num; +}; + +PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() +: num(0) +{ + report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + { + if (num < MAX_MULTI_RAYCAST_NUM) + { + points[num++] = point; + } + + return true; + }; +} + +void PhysicsDemoRayCast::update(float delta) +{ + float L = 150.0f; + Point point1 = VisibleRect::center(); + Point d(L * cosf(_angle), L * sinf(_angle)); + Point point2 = point1 + d; + + removeChild(_node); + _node = DrawNode::create(); + switch (_mode) + { + case 0: + { + PhysicsRayCastCallback callback; + Point point3 = point2; + callback.report = anyRay; + + _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _node->drawSegment(point1, point3, 1, STATIC_COLOR); + + if (point2 != point3) + { + _node->drawDot(point3, 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + } + addChild(_node); + + break; + } + case 1: + { + PhysicsDemoNearestRayCastCallback callback; + Point point3 = point2; + + _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _node->drawSegment(point1, point3, 1, STATIC_COLOR); + + if (point2 != point3) + { + _node->drawDot(point3, 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + } + addChild(_node); + + break; + } + case 2: + { + PhysicsDemoMultiRayCastCallback callback; + + _scene->getPhysicsWorld()->rayCast(callback, point1, point2, nullptr); + + _node->drawSegment(point1, point2, 1, STATIC_COLOR); + + for (int i = 0; i < callback.num; ++i) + { + _node->drawDot(callback.points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + } + + addChild(_node); + + break; + } + + default: + break; + } + + _angle += 0.25f * M_PI / 180.0f; +} + +void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Event* event) +{ + //Add a new body/atlas sprite at the touched location + + for( auto &touch: touches) + { + auto location = touch->getLocation(); + + float r = CCRANDOM_0_1(); + + if (r < 1.0f/3.0f) + { + addChild(makeBall(location.x, location.y, 5 + CCRANDOM_0_1()*10)); + }else if(r < 2.0f/3.0f) + { + addChild(makeBox(location.x, location.y, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); + }else + { + addChild(makeTriangle(location.x, location.y, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); + } + } +} + +std::string PhysicsDemoRayCast::title() +{ + return "Ray Cast"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 34f8053b37..65c1c6bad9 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -37,9 +37,13 @@ public: void toggleDebugCallback(Object* sender); void addGrossiniAtPosition(Point p, float scale = 1.0); + Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); + Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); + Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); -private: +protected: Texture2D* _spriteTexture; // weak ref + SpriteBatchNode* _ball; }; class PhysicsDemoClickAdd : public PhysicsDemo @@ -57,11 +61,6 @@ class PhysicsDemoLogoSmash : public PhysicsDemo public: void onEnter() override; std::string title() override; - - Node* makeBall(float x, float y); - -private: - SpriteBatchNode* _ball; }; class PhysicsDemoPyramidStack : public PhysicsDemo @@ -78,4 +77,25 @@ public: std::string title() override; }; +class PhysicsDemoRayCast : public PhysicsDemo +{ +public: + PhysicsDemoRayCast(); +public: + void onEnter() override; + std::string title() override; + void update(float delta) override; + + void onTouchesEnded(const std::vector& touches, Event* event) override; + + void changeModeCallback(Object* sender); + + static bool anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data); + +private: + float _angle; + DrawNode* _node; + int _mode; +}; + #endif From 6a664d480a870c0a46c923fcd15fcdf9a3d0a9ee Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 22 Oct 2013 18:01:56 +0800 Subject: [PATCH 200/557] issue #2905:samples build ok on linux --- build/Makefile | 101 ++++--- build/install-deps-linux.sh | 2 +- cocos/2d/Makefile | 302 +++++++++++---------- cocos/2d/cocos2dx.mk | 45 +-- cocos/2d/platform/linux/CCEGLView.cpp | 2 +- cocos/2d/platform/linux/CCEGLView.h | 2 +- cocos/audio/proj.linux/Makefile | 10 +- cocos/editor-support/cocosbuilder/Makefile | 44 +++ cocos/editor-support/cocostudio/Makefile | 69 +++++ cocos/editor-support/spine/Makefile | 42 +++ cocos/gui/Layout.cpp | 4 +- cocos/gui/Makefile | 44 +++ cocos/network/Makefile | 22 ++ cocos/physics/CCPhysicsBody.cpp | 10 +- cocos/physics/CCPhysicsContact.cpp | 2 +- cocos/physics/CCPhysicsJoint.cpp | 6 +- cocos/physics/CCPhysicsShape.cpp | 6 +- cocos/physics/CCPhysicsWorld.cpp | 10 +- cocos/scripting/lua/bindings/Makefile | 126 +++++---- extensions/proj.linux/Makefile | 166 ++--------- extensions/proj.linux/extensions.prf | 20 -- external/Box2D/proj.linux/Makefile | 2 +- external/chipmunk/proj.linux/Makefile | 2 +- samples/Cpp/HelloCpp/proj.linux/Makefile | 2 +- samples/Cpp/SimpleGame/proj.linux/Makefile | 5 +- samples/Cpp/TestCpp/proj.linux/Makefile | 24 +- samples/Lua/HelloLua/proj.linux/Makefile | 18 +- samples/Lua/TestLua/proj.linux/Makefile | 16 +- 28 files changed, 615 insertions(+), 489 deletions(-) create mode 100644 cocos/editor-support/cocosbuilder/Makefile create mode 100644 cocos/editor-support/cocostudio/Makefile create mode 100644 cocos/editor-support/spine/Makefile create mode 100644 cocos/gui/Makefile create mode 100644 cocos/network/Makefile delete mode 100644 extensions/proj.linux/extensions.prf diff --git a/build/Makefile b/build/Makefile index fbea65f3cd..761855d264 100644 --- a/build/Makefile +++ b/build/Makefile @@ -3,68 +3,89 @@ PLATFORM ?= linux all: chipmunk: - $(MAKE) -C external/chipmunk/proj.$(PLATFORM) + $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) chipmunk-clean: - $(MAKE) -C external/chipmunk/proj.$(PLATFORM) clean + $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) clean box2d: - $(MAKE) -C external/Box2D/proj.$(PLATFORM) + $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) box2d-clean: - $(MAKE) -C external/Box2D/proj.$(PLATFORM) clean + $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) clean -libextensions: chipmunk cocosdenshion box2d - $(MAKE) -C extensions/proj.$(PLATFORM) -libextensions-clean: - $(MAKE) -C extensions/proj.$(PLATFORM) clean +cocos2dx: chipmunk + $(MAKE) -C ../cocos/2d +cocos2dx-clean: + $(MAKE) -C ../cocos/2d clean -libcocos2dx: libextensions - $(MAKE) -C cocos2dx/proj.$(PLATFORM) -libcocos2dx-clean: - $(MAKE) -C cocos2dx/proj.$(PLATFORM) clean +audio: cocos2dx + $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) +audio-clean: + $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) clean -cocosdenshion: libcocos2dx - $(MAKE) -C audio/proj.$(PLATFORM) -cocosdenshion-clean: - $(MAKE) -C audio/proj.$(PLATFORM) clean +gui: + $(MAKE) -C ../cocos/gui +gui-clean: + $(MAKE) -C ../cocos/gui clean -lua: libextensions - $(MAKE) -C scripting/lua/proj.$(PLATFORM) +network: cocos2dx + $(MAKE) -C ../cocos/network +network-clean: + $(MAKE) -C ../cocos/network clean + +cocosbuilder: + $(MAKE) -C ../cocos/editor-support/cocosbuilder +cocosbuilder-clean: + $(MAKE) -C ../cocos/editor-support/cocosbuilder clean + +spine: + $(MAKE) -C ../cocos/editor-support/spine +spine-clean: + $(MAKE) -C ../cocos/editor-support/spine clean + +cocostudio: + $(MAKE) -C ../cocos/editor-support/cocostudio +cocostudio-clean: + $(MAKE) -C ../cocos/editor-support/cocostudio clean + +extensions: chipmunk audio box2d + $(MAKE) -C ../extensions/proj.$(PLATFORM) +extensions-clean: + $(MAKE) -C ../extensions/proj.$(PLATFORM) clean + +lua: extensions cocosbuilder cocostudio + $(MAKE) -C ../cocos/scripting/lua/bindings lua-clean: - $(MAKE) -C scripting/lua/proj.$(PLATFORM) clean + $(MAKE) -C ../cocos/scripting/lua/bindings clean -hellocpp: libcocos2dx - $(MAKE) -C samples/Cpp/HelloCpp/proj.$(PLATFORM) +hellocpp: cocos2dx + $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) hellocpp-clean: - $(MAKE) -C samples/Cpp/HelloCpp/proj.$(PLATFORM) clean + $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) clean -testcpp: libcocos2dx libextensions - $(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM) +testcpp: cocos2dx audio extensions cocostudio gui cocosbuilder spine network + $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) testcpp-clean: - $(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM) clean + $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) clean -simplegame: libcocos2dx - $(MAKE) -C samples/Cpp/SimpleGame/proj.$(PLATFORM) +simplegame: cocos2dx audio + $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) simplegame-clean: - $(MAKE) -C samples/Cpp/SimpleGame/proj.$(PLATFORM) clean + $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) clean -all: chipmunk cocosdenshion libextensions libcocos2dx lua hellocpp testcpp simplegame -clean: libcocos2dx-clean box2d-clean chipmunk-clean cocosdenshion-clean libextensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean +all: chipmunk audio extensions cocos2dx lua hellocpp testcpp simplegame +clean: cocos2dx-clean box2d-clean chipmunk-clean audio-clean extensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean -# Haven't yet got the lua projects working with emscripten -ifneq ($(PLATFORM),emscripten) - -hellolua: libcocos2dx lua - $(MAKE) -C samples/Lua/HelloLua/proj.$(PLATFORM) +hellolua: cocos2dx lua + $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) hellolua-clean: - $(MAKE) -C samples/Lua/HelloLua/proj.$(PLATFORM) clean + $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) clean -testlua: libcocos2dx lua - $(MAKE) -C samples/Lua/TestLua/proj.$(PLATFORM) +testlua: cocos2dx lua + $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) testlua-clean: - $(MAKE) -C samples/Lua/TestLua/proj.$(PLATFORM) clean + $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) clean all: hellolua testlua clean: hellolua-clean testlua-clean -endif .PHONY: all clean diff --git a/build/install-deps-linux.sh b/build/install-deps-linux.sh index f62c78a3e8..687b51926b 100755 --- a/build/install-deps-linux.sh +++ b/build/install-deps-linux.sh @@ -32,5 +32,5 @@ if [ -n "$MISSING" ]; then fi # install glfw -tools/travis-scripts/install_glfw.sh +../tools/travis-scripts/install_glfw.sh diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile index fa3d1cb659..d88604b130 100644 --- a/cocos/2d/Makefile +++ b/cocos/2d/Makefile @@ -1,93 +1,83 @@ TARGET = libcocos2d.so -INCLUDES += \ - -I../platform/third_party/linux/libfreetype2 \ - -I../platform/third_party/common/etc \ - -I../platform/third_party/common/s3tc \ - -I../platform/third_party/common/atitc \ - -I../../extensions \ - -I../../extensions/CCBReader \ - -I../../extensions/GUI/CCControlExtension \ - -I../../extensions/GUI/CCControlExtension \ - -I../../external/chipmunk/include/chipmunk \ - -I../../extensions/network \ - -I../../extensions/Components +INCLUDES = -SOURCES = ../actions/CCAction.cpp \ -../actions/CCActionCamera.cpp \ -../actions/CCActionEase.cpp \ -../actions/CCActionGrid.cpp \ -../actions/CCActionGrid3D.cpp \ -../actions/CCActionInstant.cpp \ -../actions/CCActionInterval.cpp \ -../actions/CCActionManager.cpp \ -../actions/CCActionPageTurn3D.cpp \ -../actions/CCActionProgressTimer.cpp \ -../actions/CCActionTiledGrid.cpp \ -../actions/CCActionCatmullRom.cpp \ -../actions/CCActionTween.cpp \ -../base_nodes/CCAtlasNode.cpp \ -../base_nodes/CCNode.cpp \ -../cocoa/CCAffineTransform.cpp \ -../cocoa/CCAutoreleasePool.cpp \ -../cocoa/CCGeometry.cpp \ -../cocoa/CCNS.cpp \ -../cocoa/CCObject.cpp \ -../cocoa/CCSet.cpp \ -../cocoa/CCArray.cpp \ -../cocoa/CCDictionary.cpp \ -../cocoa/CCString.cpp \ -../cocoa/CCDataVisitor.cpp \ -../cocoa/CCData.cpp \ -../event_dispatcher/CCEventAcceleration.cpp \ -../event_dispatcher/CCEventListenerAcceleration.cpp \ -../event_dispatcher/CCEvent.cpp \ -../event_dispatcher/CCEventDispatcher.cpp \ -../event_dispatcher/CCEventListener.cpp \ -../event_dispatcher/CCEventKeyboard.cpp \ -../event_dispatcher/CCEventListenerKeyboard.cpp \ -../event_dispatcher/CCTouch.cpp \ -../event_dispatcher/CCEventTouch.cpp \ -../event_dispatcher/CCEventListenerTouch.cpp \ -../event_dispatcher/CCEventCustom.cpp \ -../event_dispatcher/CCEventListenerCustom.cpp \ -../draw_nodes/CCDrawingPrimitives.cpp \ -../draw_nodes/CCDrawNode.cpp \ -../effects/CCGrabber.cpp \ -../effects/CCGrid.cpp \ -../label_nodes/CCFont.cpp \ -../label_nodes/CCFontAtlas.cpp \ -../label_nodes/CCFontAtlasCache.cpp \ -../label_nodes/CCFontAtlasFactory.cpp \ -../label_nodes/CCFontDefinition.cpp \ -../label_nodes/CCFontFNT.cpp \ -../label_nodes/CCFontFreeType.cpp \ -../label_nodes/CCLabel.cpp \ -../label_nodes/CCLabelAtlas.cpp \ -../label_nodes/CCLabelBMFont.cpp \ -../label_nodes/CCLabelTTF.cpp \ -../label_nodes/CCLabelTextFormatter.cpp \ -../label_nodes/CCTextImage.cpp \ -../layers_scenes_transitions_nodes/CCLayer.cpp \ -../layers_scenes_transitions_nodes/CCScene.cpp \ -../layers_scenes_transitions_nodes/CCTransition.cpp \ -../layers_scenes_transitions_nodes/CCTransitionPageTurn.cpp \ -../layers_scenes_transitions_nodes/CCTransitionProgress.cpp \ -../menu_nodes/CCMenu.cpp \ -../menu_nodes/CCMenuItem.cpp \ -../misc_nodes/CCMotionStreak.cpp \ -../misc_nodes/CCProgressTimer.cpp \ -../misc_nodes/CCClippingNode.cpp \ -../misc_nodes/CCRenderTexture.cpp \ -../particle_nodes/CCParticleExamples.cpp \ -../particle_nodes/CCParticleSystem.cpp \ -../particle_nodes/CCParticleSystemQuad.cpp \ -../particle_nodes/CCParticleBatchNode.cpp \ -../physics/Box2D/CCPhysicsContactInfo.cpp \ -../physics/Box2D/CCPhysicsJointInfo.cpp \ -../physics/Box2D/CCPhysicsShapeInfo.cpp \ -../physics/Box2D/CCPhysicsBodyInfo.cpp \ -../physics/Box2D/CCPhysicsWorldInfo.cpp \ +SOURCES = \ +CCAction.cpp \ +CCActionCamera.cpp \ +CCActionEase.cpp \ +CCActionGrid.cpp \ +CCActionGrid3D.cpp \ +CCActionInstant.cpp \ +CCActionInterval.cpp \ +CCActionManager.cpp \ +CCActionPageTurn3D.cpp \ +CCActionProgressTimer.cpp \ +CCActionTiledGrid.cpp \ +CCActionCatmullRom.cpp \ +CCActionTween.cpp \ +CCAtlasNode.cpp \ +CCNode.cpp \ +../base/CCAffineTransform.cpp \ +../base/CCAutoreleasePool.cpp \ +../base/CCGeometry.cpp \ +../base/CCNS.cpp \ +../base/CCObject.cpp \ +../base/CCSet.cpp \ +../base/CCArray.cpp \ +../base/CCDictionary.cpp \ +../base/CCString.cpp \ +../base/CCDataVisitor.cpp \ +../base/CCData.cpp \ +CCEventAcceleration.cpp \ +CCEventListenerAcceleration.cpp \ +CCEvent.cpp \ +CCEventDispatcher.cpp \ +CCEventListener.cpp \ +CCEventKeyboard.cpp \ +CCEventListenerKeyboard.cpp \ +CCTouch.cpp \ +CCEventTouch.cpp \ +CCEventListenerTouch.cpp \ +CCEventCustom.cpp \ +CCEventListenerCustom.cpp \ +CCDrawingPrimitives.cpp \ +CCDrawNode.cpp \ +CCGrabber.cpp \ +CCGrid.cpp \ +CCFont.cpp \ +CCFontAtlas.cpp \ +CCFontAtlasCache.cpp \ +CCFontAtlasFactory.cpp \ +CCFontDefinition.cpp \ +CCFontFNT.cpp \ +CCFontFreeType.cpp \ +CCLabel.cpp \ +CCLabelAtlas.cpp \ +CCLabelBMFont.cpp \ +CCLabelTTF.cpp \ +CCLabelTextFormatter.cpp \ +CCTextImage.cpp \ +CCLayer.cpp \ +CCScene.cpp \ +CCTransition.cpp \ +CCTransitionPageTurn.cpp \ +CCTransitionProgress.cpp \ +CCMenu.cpp \ +CCMenuItem.cpp \ +CCMotionStreak.cpp \ +CCProgressTimer.cpp \ +CCClippingNode.cpp \ +CCRenderTexture.cpp \ +CCParticleExamples.cpp \ +CCParticleSystem.cpp \ +CCParticleSystemQuad.cpp \ +CCParticleBatchNode.cpp \ +../physics/box2d/CCPhysicsContactInfo.cpp \ +../physics/box2d/CCPhysicsJointInfo.cpp \ +../physics/box2d/CCPhysicsShapeInfo.cpp \ +../physics/box2d/CCPhysicsBodyInfo.cpp \ +../physics/box2d/CCPhysicsWorldInfo.cpp \ ../physics/chipmunk/CCPhysicsContactInfo.cpp \ ../physics/chipmunk/CCPhysicsJointInfo.cpp \ ../physics/chipmunk/CCPhysicsShapeInfo.cpp \ @@ -109,68 +99,68 @@ SOURCES = ../actions/CCAction.cpp \ ../platform/linux/CCEGLView.cpp \ ../platform/linux/CCImage.cpp \ ../platform/linux/CCDevice.cpp \ -../platform/third_party/common/etc/etc1.cpp \ -../platform/third_party/common/s3tc/s3tc.cpp \ -../platform/third_party/common/atitc/atitc.cpp \ -../script_support/CCScriptSupport.cpp \ -../sprite_nodes/CCAnimation.cpp \ -../sprite_nodes/CCAnimationCache.cpp \ -../sprite_nodes/CCSprite.cpp \ -../sprite_nodes/CCSpriteBatchNode.cpp \ -../sprite_nodes/CCSpriteFrame.cpp \ -../sprite_nodes/CCSpriteFrameCache.cpp \ -../support/ccUTF8.cpp \ -../support/CCProfiling.cpp \ -../support/user_default/CCUserDefault.cpp \ -../support/TransformUtils.cpp \ -../support/base64.cpp \ -../support/ccUtils.cpp \ -../support/CCVertex.cpp \ -../support/CCNotificationCenter.cpp \ -../support/image_support/TGAlib.cpp \ -../support/tinyxml2/tinyxml2.cpp \ -../support/zip_support/ZipUtils.cpp \ -../support/zip_support/ioapi.cpp \ -../support/zip_support/unzip.cpp \ -../support/data_support/ccCArray.cpp \ -../support/component/CCComponent.cpp \ -../support/component/CCComponentContainer.cpp \ -../text_input_node/CCIMEDispatcher.cpp \ -../text_input_node/CCTextFieldTTF.cpp \ -../textures/CCTexture2D.cpp \ -../textures/CCTextureAtlas.cpp \ -../textures/CCTextureCache.cpp \ -../tilemap_parallax_nodes/CCParallaxNode.cpp \ -../tilemap_parallax_nodes/CCTMXLayer.cpp \ -../tilemap_parallax_nodes/CCTMXObjectGroup.cpp \ -../tilemap_parallax_nodes/CCTMXTiledMap.cpp \ -../tilemap_parallax_nodes/CCTMXXMLParser.cpp \ -../tilemap_parallax_nodes/CCTileMapAtlas.cpp \ -../shaders/CCGLProgram.cpp \ -../shaders/ccGLStateCache.cpp \ -../shaders/CCShaderCache.cpp \ -../shaders/ccShaders.cpp \ -../kazmath/src/aabb.c \ -../kazmath/src/plane.c \ -../kazmath/src/vec2.c \ -../kazmath/src/mat3.c \ -../kazmath/src/quaternion.c \ -../kazmath/src/vec3.c \ -../kazmath/src/mat4.c \ -../kazmath/src/ray2.c \ -../kazmath/src/vec4.c \ -../kazmath/src/neon_matrix_impl.c \ -../kazmath/src/utility.c \ -../kazmath/src/GL/mat4stack.c \ -../kazmath/src/GL/matrix.c \ -../CCCamera.cpp \ -../CCConfiguration.cpp \ -../CCDirector.cpp \ -../CCScheduler.cpp \ -../ccFPSImages.c \ -../ccTypes.cpp \ -../cocos2d.cpp \ -../CCDeprecated.cpp +../base/etc1.cpp \ +../base/s3tc.cpp \ +../base/atitc.cpp \ +CCScriptSupport.cpp \ +CCAnimation.cpp \ +CCAnimationCache.cpp \ +CCSprite.cpp \ +CCSpriteBatchNode.cpp \ +CCSpriteFrame.cpp \ +CCSpriteFrameCache.cpp \ +ccUTF8.cpp \ +CCProfiling.cpp \ +CCUserDefault.cpp \ +TransformUtils.cpp \ +base64.cpp \ +ccUtils.cpp \ +CCVertex.cpp \ +CCNotificationCenter.cpp \ +TGAlib.cpp \ +../../external/tinyxml2/tinyxml2.cpp \ +ZipUtils.cpp \ +../../external/unzip/ioapi.cpp \ +../../external/unzip/unzip.cpp \ +ccCArray.cpp \ +CCComponent.cpp \ +CCComponentContainer.cpp \ +CCIMEDispatcher.cpp \ +CCTextFieldTTF.cpp \ +CCTexture2D.cpp \ +CCTextureAtlas.cpp \ +CCTextureCache.cpp \ +CCParallaxNode.cpp \ +CCTMXLayer.cpp \ +CCTMXObjectGroup.cpp \ +CCTMXTiledMap.cpp \ +CCTMXXMLParser.cpp \ +CCTileMapAtlas.cpp \ +CCGLProgram.cpp \ +ccGLStateCache.cpp \ +CCShaderCache.cpp \ +ccShaders.cpp \ +../math/kazmath/src/aabb.c \ +../math/kazmath/src/plane.c \ +../math/kazmath/src/vec2.c \ +../math/kazmath/src/mat3.c \ +../math/kazmath/src/quaternion.c \ +../math/kazmath/src/vec3.c \ +../math/kazmath/src/mat4.c \ +../math/kazmath/src/ray2.c \ +../math/kazmath/src/vec4.c \ +../math/kazmath/src/neon_matrix_impl.c \ +../math/kazmath/src/utility.c \ +../math/kazmath/src/GL/mat4stack.c \ +../math/kazmath/src/GL/matrix.c \ +CCCamera.cpp \ +CCConfiguration.cpp \ +CCDirector.cpp \ +CCScheduler.cpp \ +ccFPSImages.c \ +ccTypes.cpp \ +cocos2d.cpp \ +CCDeprecated.cpp COCOS_ROOT = ../.. @@ -189,10 +179,24 @@ $(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + $(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ +$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + +$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + $(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + + diff --git a/cocos/2d/cocos2dx.mk b/cocos/2d/cocos2dx.mk index 0058e43bac..41ef87b631 100644 --- a/cocos/2d/cocos2dx.mk +++ b/cocos/2d/cocos2dx.mk @@ -45,28 +45,30 @@ THIS_MAKEFILE := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) ifndef COCOS_ROOT COCOS_ROOT := $(realpath $(dir $(THIS_MAKEFILE))/../..) endif -COCOS_SRC = $(COCOS_ROOT)/cocos2dx +COCOS_SRC = $(COCOS_ROOT)/cocos/2d OBJ_DIR ?= obj LIB_DIR = $(COCOS_ROOT)/lib/linux BIN_DIR = bin INCLUDES += \ - -I$(COCOS_SRC) \ - -I$(COCOS_SRC)/cocoa \ - -I$(COCOS_SRC)/include \ - -I$(COCOS_SRC)/kazmath/include \ + -I$(COCOS_SRC)/ \ + -I$(COCOS_SRC)/../math/kazmath/include \ -I$(COCOS_SRC)/platform/linux \ - -I$(COCOS_SRC)/platform/third_party/linux/libjpeg \ - -I$(COCOS_SRC)/platform/third_party/linux/libtiff \ - -I$(COCOS_SRC)/platform/third_party/linux/libwebp + -I$(COCOS_SRC)/../../external/jpeg/include/linux \ + -I$(COCOS_SRC)/../../external/tiff/include/linux \ + -I$(COCOS_SRC)/../../external/webp/include/linux \ + -I$(COCOS_SRC)/../../external/tinyxml2 \ + -I$(COCOS_SRC)/../../external/unzip \ + -I$(COCOS_SRC)/../../external/glfw3/include/linux \ + -I$(COCOS_SRC)/../physics \ + -I$(COCOS_SRC)/../base \ + -I$(COCOS_SRC)/../../external/chipmunk/include/chipmunk \ + -I$(COCOS_SRC)/../../external/freetype2/include/linux \ + -I$(COCOS_SRC)/../.. \ + -I$(COCOS_SRC)/../audio/include LBITS := $(shell getconf LONG_BIT) -ifeq ($(LBITS),64) -INCLUDES += -I$(COCOS_SRC)/platform/third_party/linux/include64 -else -INCLUDES += -I$(COCOS_SRC)/platform/third_party/linux -endif ifeq ($(DEBUG), 1) CCFLAGS += -g3 -O0 @@ -100,22 +102,23 @@ DEPS = $(OBJECTS:.o=.d) CORE_MAKEFILE_LIST := $(MAKEFILE_LIST) -include $(DEPS) +STATICLIBS_DIR = $(COCOS_ROOT)/external ifeq ($(LBITS),64) -STATICLIBS_DIR = $(COCOS_SRC)/platform/third_party/linux/libraries/lib64 +POSTFIX = 64-bit else -STATICLIBS_DIR = $(COCOS_SRC)/platform/third_party/linux/libraries +POSTFIX = 32-bit endif -STATICLIBS = $(STATICLIBS_DIR)/libfreetype.a \ - $(STATICLIBS_DIR)/libjpeg.a \ - $(STATICLIBS_DIR)/libtiff.a \ - $(STATICLIBS_DIR)/libwebp.a +STATICLIBS = $(STATICLIBS_DIR)/freetype2/prebuilt/linux/$(POSTFIX)/libfreetype.a \ + $(STATICLIBS_DIR)/jpeg/prebuilt/linux/$(POSTFIX)/libjpeg.a \ + $(STATICLIBS_DIR)/tiff/prebuilt/linux/$(POSTFIX)/libtiff.a \ + $(STATICLIBS_DIR)/webp/prebuilt/linux/$(POSTFIX)/libwebp.a ifneq ($(OPENAL),1) ifeq ($(LBITS),64) -FMOD_LIBDIR = $(COCOS_ROOT)/audio/third_party/fmod/lib64/api/lib +FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/lib64/api/lib SHAREDLIBS += -lfmodex64 else -FMOD_LIBDIR = $(COCOS_ROOT)/audio/third_party/fmod/api/lib +FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/api/lib SHAREDLIBS += -lfmodex endif endif diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 452d5738a3..561fedcca8 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -10,7 +10,7 @@ #include "ccMacros.h" #include "CCDirector.h" #include "CCTouch.h" -#include "/CCIMEDispatcher.h" +#include "CCIMEDispatcher.h" #include "CCEventDispatcher.h" #include "CCEventKeyboard.h" #include diff --git a/cocos/2d/platform/linux/CCEGLView.h b/cocos/2d/platform/linux/CCEGLView.h index 9d29d9c188..ed4fc18245 100644 --- a/cocos/2d/platform/linux/CCEGLView.h +++ b/cocos/2d/platform/linux/CCEGLView.h @@ -11,7 +11,7 @@ #include "platform/CCCommon.h" #include "CCGeometry.h" #include "platform/CCEGLViewProtocol.h" -#include "platform/third_party/linux/glfw/glfw3.h" +#include "glfw3.h" #include bool initExtensions(); diff --git a/cocos/audio/proj.linux/Makefile b/cocos/audio/proj.linux/Makefile index 82dc89a6d6..e8b18e3972 100644 --- a/cocos/audio/proj.linux/Makefile +++ b/cocos/audio/proj.linux/Makefile @@ -1,6 +1,6 @@ TARGET = libcocosdenshion.so -INCLUDES += -I.. -I../include +INCLUDES = -I.. -I../include ##Using OpenAL ifeq ($(OPENAL),1) @@ -26,15 +26,15 @@ SOURCES = \ ../linux/FmodAudioPlayer.cpp ifeq ($(LBITS),64) -INCLUDES += -I../third_party/fmod/lib64/api/inc +INCLUDES += -I../third-party/fmod/lib64/api/inc else -INCLUDES += -I../third_party/fmod/api/inc +INCLUDES += -I../third-party/fmod/api/inc endif endif -COCOS_ROOT = ../.. -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk +COCOS_ROOT = ../../.. +include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk TARGET := $(LIB_DIR)/$(TARGET) diff --git a/cocos/editor-support/cocosbuilder/Makefile b/cocos/editor-support/cocosbuilder/Makefile new file mode 100644 index 0000000000..688c5d49d5 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/Makefile @@ -0,0 +1,44 @@ +TARGET = libcocosbuilder.a + +INCLUDES = + +SOURCES = CCBFileLoader.cpp \ +CCMenuItemImageLoader.cpp \ +CCBReader.cpp \ +CCMenuItemLoader.cpp \ +CCControlButtonLoader.cpp \ +CCNodeLoader.cpp \ +CCControlLoader.cpp \ +CCNodeLoaderLibrary.cpp \ +CCLabelBMFontLoader.cpp \ +CCParticleSystemQuadLoader.cpp \ +CCLabelTTFLoader.cpp \ +CCScale9SpriteLoader.cpp \ +CCLayerColorLoader.cpp \ +CCScrollViewLoader.cpp \ +CCLayerGradientLoader.cpp \ +CCSpriteLoader.cpp \ +CCLayerLoader.cpp \ +CCBAnimationManager.cpp \ +CCBKeyframe.cpp \ +CCBSequence.cpp \ +CCBSequenceProperty.cpp \ +CCBValue.cpp \ +CCNode+CCBRelativePositioning.cpp + +include ../../2d/cocos2dx.mk + +CXXFLAGS += -Wno-multichar + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) + +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + diff --git a/cocos/editor-support/cocostudio/Makefile b/cocos/editor-support/cocostudio/Makefile new file mode 100644 index 0000000000..810c28372e --- /dev/null +++ b/cocos/editor-support/cocostudio/Makefile @@ -0,0 +1,69 @@ +TARGET = libcocostudio.a + +COCOS_ROOT=../../.. + +INCLUDES = -I../../2d \ +-I../../../external \ +-I.. \ +-I../.. \ + +SOURCES = CCActionFrame.cpp \ +CCActionFrameEasing.cpp \ +CCActionManagerEx.cpp \ +CCActionNode.cpp \ +CCActionObject.cpp \ +CCArmature.cpp \ +CCBone.cpp \ +CCArmatureAnimation.cpp \ +CCProcessBase.cpp \ +CCTween.cpp \ +CCDatas.cpp \ +CCBatchNode.cpp \ +CCDecorativeDisplay.cpp \ +CCDisplayFactory.cpp \ +CCDisplayManager.cpp \ +CCSkin.cpp \ +CCColliderDetector.cpp \ +CCArmatureDataManager.cpp \ +CCArmatureDefine.cpp \ +CCDataReaderHelper.cpp \ +CCSpriteFrameCacheHelper.cpp \ +CCTransformHelp.cpp \ +CCTweenFunction.cpp \ +CCUtilMath.cpp \ +CCComAttribute.cpp \ +CCComAudio.cpp \ +CCComController.cpp \ +CCComRender.cpp \ +CCInputDelegate.cpp \ +CSContentJsonDictionary.cpp \ +DictionaryHelper.cpp \ +CCSGUIReader.cpp \ +CCSSceneReader.cpp \ +../../../external/json/json_reader.cpp \ +../../../external/json/json_value.cpp \ +../../../external/json/json_writer.cpp + +include ../../2d/cocos2dx.mk + +CXXFLAGS += -Wno-multichar + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) + +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + +$(OBJ_DIR)/%.o: ../../../%.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + +$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/editor-support/spine/Makefile b/cocos/editor-support/spine/Makefile new file mode 100644 index 0000000000..88514a824e --- /dev/null +++ b/cocos/editor-support/spine/Makefile @@ -0,0 +1,42 @@ +TARGET = libspine.a + +INCLUDES = -I.. + +SOURCES = Animation.cpp \ +AnimationState.cpp \ +AnimationStateData.cpp \ +Atlas.cpp \ +AtlasAttachmentLoader.cpp \ +Attachment.cpp \ +AttachmentLoader.cpp \ +Bone.cpp \ +BoneData.cpp \ +Json.cpp \ +RegionAttachment.cpp \ +Skeleton.cpp \ +SkeletonData.cpp \ +SkeletonJson.cpp \ +Skin.cpp \ +Slot.cpp \ +SlotData.cpp \ +extension.cpp \ +spine-cocos2dx.cpp \ +CCSkeleton.cpp \ +CCSkeletonAnimation.cpp + +include ../../2d/cocos2dx.mk + +CXXFLAGS += -Wno-multichar + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) + +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + diff --git a/cocos/gui/Layout.cpp b/cocos/gui/Layout.cpp index b7014ac1ed..a9e4f75a30 100644 --- a/cocos/gui/Layout.cpp +++ b/cocos/gui/Layout.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/layout.h" +#include "gui/Layout.h" #include "gui/UILayer.h" #include "gui/UIHelper.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" @@ -782,4 +782,4 @@ bool RectClippingNode::isEnabled() const return _enabled; } -} \ No newline at end of file +} diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile new file mode 100644 index 0000000000..0e8501cc63 --- /dev/null +++ b/cocos/gui/Makefile @@ -0,0 +1,44 @@ +TARGET = libgui.a + +INCLUDES = -I../ \ +-I../editor-support \ +-I../../external + +SOURCES = UIRootWidget.cpp \ +UIWidget.cpp \ +Layout.cpp \ +LayoutParameter.cpp \ +UILayoutDefine.cpp \ +CocosGUI.cpp \ +UIHelper.cpp \ +UIInputManager.cpp \ +UILayer.cpp \ +UIDragPanel.cpp \ +UIListView.cpp \ +UIPageView.cpp \ +UIScrollView.cpp \ +UIButton.cpp \ +UICheckBox.cpp \ +UIImageView.cpp \ +UILabel.cpp \ +UILabelAtlas.cpp \ +UILabelBMFont.cpp \ +UILoadingBar.cpp \ +UISlider.cpp \ +UITextField.cpp + +include ../2d/cocos2dx.mk + +CXXFLAGS += -Wno-multichar + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) + +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/network/Makefile b/cocos/network/Makefile new file mode 100644 index 0000000000..029078722d --- /dev/null +++ b/cocos/network/Makefile @@ -0,0 +1,22 @@ +TARGET = libnetwork.a + +INCLUDES = -I.. + +SOURCES = HttpClient.cpp \ +SocketIO.cpp + +include ../2d/cocos2dx.mk + +CXXFLAGS += -Wno-multichar + +TARGET := $(LIB_DIR)/$(TARGET) + +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) + +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 2dc38bf286..2fb6c4458b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -37,16 +37,16 @@ #include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" +#include "box2d/CCPhysicsBodyInfo.h" #include "chipmunk/CCPhysicsJointInfo.h" -#include "Box2D/CCPhysicsJointInfo.h" +#include "box2d/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsWorldInfo.h" -#include "Box2D/CCPhysicsWorldInfo.h" +#include "box2d/CCPhysicsWorldInfo.h" #include "chipmunk/CCPhysicsShapeInfo.h" -#include "Box2D/CCPhysicsShapeInfo.h" +#include "box2d/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" -#include "Box2D/CCPhysicsHelper.h" +#include "box2d/CCPhysicsHelper.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 928c8c9e59..1ec9667d6f 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -31,7 +31,7 @@ #endif #include "chipmunk/CCPhysicsContactInfo.h" -#include "Box2D/CCPhysicsContactInfo.h" +#include "box2d/CCPhysicsContactInfo.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 63b6ac052e..b2742720e4 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -34,11 +34,11 @@ #include "CCPhysicsBody.h" #include "chipmunk/CCPhysicsJointInfo.h" -#include "Box2D/CCPhysicsJointInfo.h" +#include "box2d/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" +#include "box2d/CCPhysicsBodyInfo.h" #include "chipmunk/CCPhysicsHelper.h" -#include "Box2D/CCPhysicsHelper.h" +#include "box2d/CCPhysicsHelper.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index b373e0710e..15e0a82ca0 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -35,9 +35,9 @@ #include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" +#include "box2d/CCPhysicsBodyInfo.h" #include "chipmunk/CCPhysicsShapeInfo.h" -#include "Box2D/CCPhysicsShapeInfo.h" +#include "box2d/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" NS_CC_BEGIN @@ -518,4 +518,4 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater NS_CC_END -#endif // CC_USE_PHYSICS \ No newline at end of file +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1777a395f0..11859579ac 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -37,15 +37,15 @@ #include "CCPhysicsJoint.h" #include "chipmunk/CCPhysicsWorldInfo.h" -#include "Box2D/CCPhysicsWorldInfo.h" +#include "box2d/CCPhysicsWorldInfo.h" #include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" +#include "box2d/CCPhysicsBodyInfo.h" #include "chipmunk/CCPhysicsShapeInfo.h" -#include "Box2D/CCPhysicsShapeInfo.h" +#include "box2d/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsContactInfo.h" -#include "Box2D/CCPhysicsContactInfo.h" +#include "box2d/CCPhysicsContactInfo.h" #include "chipmunk/CCPhysicsJointInfo.h" -#include "Box2D/CCPhysicsJointInfo.h" +#include "box2d/CCPhysicsJointInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "CCDrawNode.h" diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile index 1aaa6c897e..95145d5fbc 100644 --- a/cocos/scripting/lua/bindings/Makefile +++ b/cocos/scripting/lua/bindings/Makefile @@ -1,64 +1,72 @@ TARGET = liblua.so -INCLUDES += -I.. -I../lua -I../tolua -I../cocos2dx_support -I../../auto-generated/lua-bindings \ - -I../Classes -I../../../audio/include -I../../../extensions -I../../../external/chipmunk/include/chipmunk +INCLUDES += -I../../../../external/lua/tolua \ +-I../../../../external/lua/lua \ +-I../../auto-generated/lua-bindings \ +-I../../../../extensions \ +-I../../../editor-support \ +-I. \ +-I../../../editor-support/cocosbuilder \ +-I../../../editor-support/cocostudio \ +-I../../../../external \ +-I../../../ -SOURCES = ../lua/lapi.c \ - ../lua/lauxlib.c \ - ../lua/lbaselib.c \ - ../lua/lcode.c \ - ../lua/ldblib.c \ - ../lua/ldebug.c \ - ../lua/ldo.c \ - ../lua/ldump.c \ - ../lua/lfunc.c \ - ../lua/lgc.c \ - ../lua/linit.c \ - ../lua/liolib.c \ - ../lua/llex.c \ - ../lua/lmathlib.c \ - ../lua/lmem.c \ - ../lua/loadlib.c \ - ../lua/lobject.c \ - ../lua/lopcodes.c \ - ../lua/loslib.c \ - ../lua/lparser.c \ - ../lua/lstate.c \ - ../lua/lstring.c \ - ../lua/lstrlib.c \ - ../lua/ltable.c \ - ../lua/ltablib.c \ - ../lua/ltm.c \ - ../lua/lundump.c \ - ../lua/lvm.c \ - ../lua/lzio.c \ - ../lua/print.c \ - ../tolua/tolua_event.c \ - ../tolua/tolua_is.c \ - ../tolua/tolua_map.c \ - ../tolua/tolua_push.c \ - ../tolua/tolua_to.c \ - ../cocos2dx_support/tolua_fix.c \ +SOURCES = ../../../../external/lua/lua/lapi.c \ + ../../../../external/lua/lua/lauxlib.c \ + ../../../../external/lua/lua/lbaselib.c \ + ../../../../external/lua/lua/lcode.c \ + ../../../../external/lua/lua/ldblib.c \ + ../../../../external/lua/lua/ldebug.c \ + ../../../../external/lua/lua/ldo.c \ + ../../../../external/lua/lua/ldump.c \ + ../../../../external/lua/lua/lfunc.c \ + ../../../../external/lua/lua/lgc.c \ + ../../../../external/lua/lua/linit.c \ + ../../../../external/lua/lua/liolib.c \ + ../../../../external/lua/lua/llex.c \ + ../../../../external/lua/lua/lmathlib.c \ + ../../../../external/lua/lua/lmem.c \ + ../../../../external/lua/lua/loadlib.c \ + ../../../../external/lua/lua/lobject.c \ + ../../../../external/lua/lua/lopcodes.c \ + ../../../../external/lua/lua/loslib.c \ + ../../../../external/lua/lua/lparser.c \ + ../../../../external/lua/lua/lstate.c \ + ../../../../external/lua/lua/lstring.c \ + ../../../../external/lua/lua/lstrlib.c \ + ../../../../external/lua/lua/ltable.c \ + ../../../../external/lua/lua/ltablib.c \ + ../../../../external/lua/lua/ltm.c \ + ../../../../external/lua/lua/lundump.c \ + ../../../../external/lua/lua/lvm.c \ + ../../../../external/lua/lua/lzio.c \ + ../../../../external/lua/lua/print.c \ + ../../../../external/lua/tolua/tolua_event.c \ + ../../../../external/lua/tolua/tolua_is.c \ + ../../../../external/lua/tolua/tolua_map.c \ + ../../../../external/lua/tolua/tolua_push.c \ + ../../../../external/lua/tolua/tolua_to.c \ + tolua_fix.c \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - ../cocos2dx_support/CCLuaBridge.cpp \ - ../cocos2dx_support/CCLuaEngine.cpp \ - ../cocos2dx_support/CCLuaStack.cpp \ - ../cocos2dx_support/CCLuaValue.cpp \ - ../cocos2dx_support/Cocos2dxLuaLoader.cpp \ - ../cocos2dx_support/CCBProxy.cpp \ - ../cocos2dx_support/LuaOpengl.cpp \ - ../cocos2dx_support/LuaScriptHandlerMgr.cpp \ - ../cocos2dx_support/LuaBasicConversions.cpp \ - ../cocos2dx_support/lua_cocos2dx_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_extension_manual.cpp \ - ../cocos2dx_support/lua_cocos2dx_deprecated.cpp + CCLuaBridge.cpp \ + CCLuaEngine.cpp \ + CCLuaStack.cpp \ + CCLuaValue.cpp \ + Cocos2dxLuaLoader.cpp \ + CCBProxy.cpp \ + LuaOpengl.cpp \ + LuaScriptHandlerMgr.cpp \ + LuaBasicConversions.cpp \ + lua_cocos2dx_manual.cpp \ + lua_cocos2dx_extension_manual.cpp \ + lua_cocos2dx_deprecated.cpp -include ../../../cocos2dx/proj.linux/cocos2dx.mk +include ../../../2d/cocos2dx.mk TARGET := $(LIB_DIR)/$(TARGET) -SHAREDLIBS += -lextension +SHAREDLIBS += -lextension -lcocostudio -lcocosbuilder STATICLIBS += $(LIB_DIR)/libbox2d.a all: $(TARGET) @@ -67,14 +75,18 @@ $(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) +$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + $(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) +$(OBJ_DIR)/%.o: ../../../../%.c $(CORE_MAKEFILE_LIST) + @mkdir -p $(@D) + $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ + +$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/extensions/proj.linux/Makefile b/extensions/proj.linux/Makefile index 6565ee9b94..fe07e988e5 100644 --- a/extensions/proj.linux/Makefile +++ b/extensions/proj.linux/Makefile @@ -1,146 +1,36 @@ TARGET = libextension.a -COCOS_ROOT=../.. +INCLUDES = -I.. -INCLUDES = -I$(COCOS_ROOT)/external \ - -I$(COCOS_ROOT)/external/chipmunk/include/chipmunk \ - -I$(COCOS_ROOT)/audio/include \ - -I.. \ - -I../CCBReader \ - -I../GUI/CCControlExtension \ - -I../GUI/CCEditBox \ - -I../network \ - -I../CocoStudio/Components \ - -I../CocoStudio/Armature +SOURCES = \ +assets-manager/AssetsManager.cpp \ +GUI/CCControlExtension/CCControl.cpp \ +GUI/CCControlExtension/CCControlButton.cpp \ +GUI/CCControlExtension/CCControlColourPicker.cpp \ +GUI/CCControlExtension/CCControlHuePicker.cpp \ +GUI/CCControlExtension/CCControlPotentiometer.cpp \ +GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ +GUI/CCControlExtension/CCControlSlider.cpp \ +GUI/CCControlExtension/CCControlStepper.cpp \ +GUI/CCControlExtension/CCControlSwitch.cpp \ +GUI/CCControlExtension/CCControlUtils.cpp \ +GUI/CCControlExtension/CCInvocation.cpp \ +GUI/CCControlExtension/CCScale9Sprite.cpp \ +GUI/CCEditBox/CCEditBox.cpp \ +GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ +GUI/CCEditBox/CCEditBoxImplNone.cpp \ +GUI/CCEditBox/CCEditBoxImplTizen.cpp \ +GUI/CCEditBox/CCEditBoxImplWin.cpp \ +GUI/CCScrollView/CCScrollView.cpp \ +GUI/CCScrollView/CCSorting.cpp \ +GUI/CCScrollView/CCTableView.cpp \ +GUI/CCScrollView/CCTableViewCell.cpp \ +physics-nodes/CCPhysicsDebugNode.cpp \ +physics-nodes/CCPhysicsSprite.cpp -SOURCES = ../CCBReader/CCBFileLoader.cpp \ -../CCBReader/CCMenuItemImageLoader.cpp \ -../CCBReader/CCBReader.cpp \ -../CCBReader/CCMenuItemLoader.cpp \ -../CCBReader/CCControlButtonLoader.cpp \ -../CCBReader/CCNodeLoader.cpp \ -../CCBReader/CCControlLoader.cpp \ -../CCBReader/CCNodeLoaderLibrary.cpp \ -../CCBReader/CCLabelBMFontLoader.cpp \ -../CCBReader/CCParticleSystemQuadLoader.cpp \ -../CCBReader/CCLabelTTFLoader.cpp \ -../CCBReader/CCScale9SpriteLoader.cpp \ -../CCBReader/CCLayerColorLoader.cpp \ -../CCBReader/CCScrollViewLoader.cpp \ -../CCBReader/CCLayerGradientLoader.cpp \ -../CCBReader/CCSpriteLoader.cpp \ -../CCBReader/CCLayerLoader.cpp \ -../CCBReader/CCBAnimationManager.cpp \ -../CCBReader/CCBKeyframe.cpp \ -../CCBReader/CCBSequence.cpp \ -../CCBReader/CCBSequenceProperty.cpp \ -../CCBReader/CCBValue.cpp \ -../CCBReader/CCNode+CCBRelativePositioning.cpp \ -../GUI/CCScrollView/CCScrollView.cpp \ -../GUI/CCScrollView/CCSorting.cpp \ -../GUI/CCScrollView/CCTableView.cpp \ -../GUI/CCScrollView/CCTableViewCell.cpp \ -../GUI/CCControlExtension/CCControlButton.cpp \ -../GUI/CCControlExtension/CCControlColourPicker.cpp \ -../GUI/CCControlExtension/CCControl.cpp \ -../GUI/CCControlExtension/CCControlHuePicker.cpp \ -../GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -../GUI/CCControlExtension/CCControlSlider.cpp \ -../GUI/CCControlExtension/CCControlSwitch.cpp \ -../GUI/CCControlExtension/CCControlUtils.cpp \ -../GUI/CCControlExtension/CCInvocation.cpp \ -../GUI/CCControlExtension/CCScale9Sprite.cpp \ -../GUI/CCControlExtension/CCControlPotentiometer.cpp \ -../GUI/CCControlExtension/CCControlStepper.cpp \ -../GUI/CCEditBox/CCEditBox.cpp \ -../GUI/CCEditBox/CCEditBoxImplNone.cpp \ -../network/HttpClient.cpp \ -../physics_nodes/CCPhysicsDebugNode.cpp \ -../physics_nodes/CCPhysicsSprite.cpp \ -../CocoStudio/Armature/CCArmature.cpp \ -../CocoStudio/Armature/CCBone.cpp \ -../CocoStudio/Armature/animation/CCArmatureAnimation.cpp \ -../CocoStudio/Armature/animation/CCProcessBase.cpp \ -../CocoStudio/Armature/animation/CCTween.cpp \ -../CocoStudio/Armature/datas/CCDatas.cpp \ -../CocoStudio/Armature/display/CCBatchNode.cpp \ -../CocoStudio/Armature/display/CCDecorativeDisplay.cpp \ -../CocoStudio/Armature/display/CCDisplayFactory.cpp \ -../CocoStudio/Armature/display/CCDisplayManager.cpp \ -../CocoStudio/Armature/display/CCSkin.cpp \ -../CocoStudio/Armature/physics/CCColliderDetector.cpp \ -../CocoStudio/Armature/utils/CCArmatureDefine.cpp \ -../CocoStudio/Armature/utils/CCArmatureDataManager.cpp \ -../CocoStudio/Armature/utils/CCDataReaderHelper.cpp \ -../CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.cpp \ -../CocoStudio/Armature/utils/CCTransformHelp.cpp \ -../CocoStudio/Armature/utils/CCTweenFunction.cpp \ -../CocoStudio/Armature/utils/CCUtilMath.cpp \ -../CocoStudio/Components/CCComAttribute.cpp \ -../CocoStudio/Components/CCComAudio.cpp \ -../CocoStudio/Components/CCComController.cpp \ -../CocoStudio/Components/CCComRender.cpp \ -../CocoStudio/Components/CCInputDelegate.cpp \ -../CocoStudio/GUI/BaseClasses/UIRootWidget.cpp \ -../CocoStudio/GUI/BaseClasses/UIWidget.cpp \ -../CocoStudio/GUI/Layouts/Layout.cpp \ -../CocoStudio/GUI/Layouts/LayoutParameter.cpp \ -../CocoStudio/GUI/Layouts/UILayoutDefine.cpp \ -../CocoStudio/GUI/System/CocosGUI.cpp \ -../CocoStudio/GUI/System/UIHelper.cpp \ -../CocoStudio/GUI/System/UIInputManager.cpp \ -../CocoStudio/GUI/System/UILayer.cpp \ -../CocoStudio/GUI/UIWidgets/UIButton.cpp \ -../CocoStudio/GUI/UIWidgets/UICheckBox.cpp \ -../CocoStudio/GUI/UIWidgets/UIImageView.cpp \ -../CocoStudio/GUI/UIWidgets/UILabel.cpp \ -../CocoStudio/GUI/UIWidgets/UILabelAtlas.cpp \ -../CocoStudio/GUI/UIWidgets/UILabelBMFont.cpp \ -../CocoStudio/GUI/UIWidgets/UILoadingBar.cpp \ -../CocoStudio/GUI/UIWidgets/UISlider.cpp \ -../CocoStudio/GUI/UIWidgets/UITextField.cpp \ -../CocoStudio/GUI/UIWidgets/ScrollWidget/UIDragPanel.cpp \ -../CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.cpp \ -../CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.cpp \ -../CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.cpp \ -../CocoStudio/Json/CSContentJsonDictionary.cpp \ -../CocoStudio/Json/DictionaryHelper.cpp \ -../CocoStudio/Json/lib_json/json_reader.cpp \ -../CocoStudio/Json/lib_json/json_value.cpp \ -../CocoStudio/Json/lib_json/json_writer.cpp \ -../CocoStudio/Reader/CCSGUIReader.cpp \ -../CocoStudio/Reader/CCSSceneReader.cpp \ -../CocoStudio/Action/CCActionFrame.cpp \ -../CocoStudio/Action/CCActionFrameEasing.cpp \ -../CocoStudio/Action/CCActionManagerEx.cpp \ -../CocoStudio/Action/CCActionNode.cpp \ -../CocoStudio/Action/CCActionObject.cpp \ -../spine/Animation.cpp \ -../spine/AnimationState.cpp \ -../spine/AnimationStateData.cpp \ -../spine/Atlas.cpp \ -../spine/AtlasAttachmentLoader.cpp \ -../spine/Attachment.cpp \ -../spine/AttachmentLoader.cpp \ -../spine/Bone.cpp \ -../spine/BoneData.cpp \ -../spine/Json.cpp \ -../spine/RegionAttachment.cpp \ -../spine/Skeleton.cpp \ -../spine/SkeletonData.cpp \ -../spine/SkeletonJson.cpp \ -../spine/Skin.cpp \ -../spine/Slot.cpp \ -../spine/SlotData.cpp \ -../spine/extension.cpp \ -../spine/spine-cocos2dx.cpp \ -../spine/CCSkeleton.cpp \ -../spine/CCSkeletonAnimation.cpp \ -../CCDeprecated-ext.cpp +include ../../cocos/2d/cocos2dx.mk -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk - -CXXFLAGS += -Wno-multichar +CXXFLAGS += -Wno-multichar -Wno-unused-result TARGET := $(LIB_DIR)/$(TARGET) diff --git a/extensions/proj.linux/extensions.prf b/extensions/proj.linux/extensions.prf deleted file mode 100644 index d399b91272..0000000000 --- a/extensions/proj.linux/extensions.prf +++ /dev/null @@ -1,20 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile extensions on demand using Makefile. - build_extension.name = Build extension static library - build_extension.input = $$PWD/Makefile - build_extension.output = $$CC_LIBRARY_DIR/libextension.a - build_extension.target = $$CC_LIBRARY_DIR/libextension.a - build_extension.CONFIG = no_link target_predeps - build_extension.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_extension - QMAKE_EXTRA_TARGETS += build_extension - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libextension.a - LIBS += -Wl,-Bstatic -lextension -Wl,-Bdynamic -} - diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile index e430bc9883..b43814ccef 100644 --- a/external/Box2D/proj.linux/Makefile +++ b/external/Box2D/proj.linux/Makefile @@ -46,7 +46,7 @@ SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ ../Dynamics/b2WorldCallbacks.cpp \ ../Rope/b2Rope.cpp -include ../../../cocos2dx/proj.linux/cocos2dx.mk +include ../../../cocos/2d/cocos2dx.mk INCLUDES = -I../.. diff --git a/external/chipmunk/proj.linux/Makefile b/external/chipmunk/proj.linux/Makefile index b0e5d1f572..a2cb985b7c 100644 --- a/external/chipmunk/proj.linux/Makefile +++ b/external/chipmunk/proj.linux/Makefile @@ -28,7 +28,7 @@ SOURCES = ../src/chipmunk.c \ ../src/constraints/cpSlideJoint.c \ ../src/constraints/cpPinJoint.c \ -include ../../../cocos2dx/proj.linux/cocos2dx.mk +include ../../../cocos/2d/cocos2dx.mk TARGET = $(LIB_DIR)/libchipmunk.a INCLUDES = -I../include/chipmunk diff --git a/samples/Cpp/HelloCpp/proj.linux/Makefile b/samples/Cpp/HelloCpp/proj.linux/Makefile index 178fa06a86..0548290a52 100644 --- a/samples/Cpp/HelloCpp/proj.linux/Makefile +++ b/samples/Cpp/HelloCpp/proj.linux/Makefile @@ -7,7 +7,7 @@ SOURCES = main.cpp \ ../Classes/HelloWorldScene.cpp COCOS_ROOT = ../../../.. -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk +include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk SHAREDLIBS += -lcocos2d COCOS_LIBS = $(LIB_DIR)/libcocos2d.so diff --git a/samples/Cpp/SimpleGame/proj.linux/Makefile b/samples/Cpp/SimpleGame/proj.linux/Makefile index 61485ebb7f..9204555b28 100644 --- a/samples/Cpp/SimpleGame/proj.linux/Makefile +++ b/samples/Cpp/SimpleGame/proj.linux/Makefile @@ -8,11 +8,10 @@ SOURCES = main.cpp \ ../Classes/GameOverScene.cpp COCOS_ROOT = ../../../.. -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk +include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk SHAREDLIBS += -lcocos2d -lcocosdenshion -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so -INCLUDES += -I$(COCOS_ROOT)/audio/include +INCLUDES += -I$(COCOS_ROOT)/cocos/audio/include $(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) diff --git a/samples/Cpp/TestCpp/proj.linux/Makefile b/samples/Cpp/TestCpp/proj.linux/Makefile index 4dda11cafe..ea1051612c 100644 --- a/samples/Cpp/TestCpp/proj.linux/Makefile +++ b/samples/Cpp/TestCpp/proj.linux/Makefile @@ -2,6 +2,11 @@ EXECUTABLE = TestCpp DEFINES += -DCC_KEYBOARD_SUPPORT +INCLUDES = -I../../../../external \ + -I../../../../cocos/editor-support \ + -I../../../../cocos \ + -I../Classes + SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/ActionManagerTest/ActionManagerTest.cpp \ ../Classes/ActionsEaseTest/ActionsEaseTest.cpp \ @@ -135,22 +140,19 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ SHAREDLIBS = -lcocos2d -lcocosdenshion -lcurl -lpng COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so -include ../../../../cocos2dx/proj.linux/cocos2dx.mk - -INCLUDES += -I../ \ - -I../../ \ - -I../Classes \ - -I$(COCOS_ROOT)/audio/include \ - -I$(COCOS_ROOT)/extensions/ \ - -I$(COCOS_ROOT)/external/ \ - -I$(COCOS_ROOT)/external/chipmunk/include/chipmunk +include ../../../../cocos/2d/cocos2dx.mk STATICLIBS += \ - $(STATICLIBS_DIR)/libcurl.a \ + $(STATICLIBS_DIR)/curl/prebuilt/linux/$(POSTFIX)/libcurl.a \ $(LIB_DIR)/libextension.a \ $(LIB_DIR)/libbox2d.a \ - $(LIB_DIR)/libchipmunk.a + $(LIB_DIR)/libchipmunk.a \ + $(LIB_DIR)/libgui.a \ + $(LIB_DIR)/libcocosbuilder.a \ + $(LIB_DIR)/libspine.a \ + $(LIB_DIR)/libcocostudio.a \ + $(LIB_DIR)/libnetwork.a ####### Build rules $(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) diff --git a/samples/Lua/HelloLua/proj.linux/Makefile b/samples/Lua/HelloLua/proj.linux/Makefile index 1ebb038045..6a0ddf230c 100644 --- a/samples/Lua/HelloLua/proj.linux/Makefile +++ b/samples/Lua/HelloLua/proj.linux/Makefile @@ -1,28 +1,22 @@ EXECUTABLE = HelloLua COCOS_ROOT = ../../../.. -INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/audio/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support \ - -I$(COCOS_ROOT)/extensions \ +INCLUDES = -I../Classes \ + -I$(COCOS_ROOT)/audio/include \ + -I$(COCOS_ROOT)/cocos/scripting/lua/bindings \ + -I$(COCOS_ROOT)/external/lua/lua SOURCES = main.cpp ../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -lextension -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk +include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk $(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) - cp -n ../../../../scripting/lua/script/* ../../../../samples/Lua/HelloLua/Resources + cp -n ../../../../cocos/scripting/lua/script/* ../../../../samples/Lua/HelloLua/Resources $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) $(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/samples/Lua/TestLua/proj.linux/Makefile b/samples/Lua/TestLua/proj.linux/Makefile index a23cc6dda4..5151716394 100644 --- a/samples/Lua/TestLua/proj.linux/Makefile +++ b/samples/Lua/TestLua/proj.linux/Makefile @@ -1,22 +1,22 @@ EXECUTABLE = TestLua COCOS_ROOT = ../../../.. -INCLUDES = -I../ -I../Classes -I$(COCOS_ROOT)/audio/include \ - -I$(COCOS_ROOT)/scripting/lua/lua \ - -I$(COCOS_ROOT)/scripting/lua/tolua \ - -I$(COCOS_ROOT)/scripting/lua/cocos2dx_support +INCLUDES = -I../Classes \ + -I$(COCOS_ROOT)/audio/include \ + -I$(COCOS_ROOT)/cocos/scripting/lua/bindings \ + -I$(COCOS_ROOT)/external/lua/lua -SOURCES = main.cpp ../Classes/AppDelegate.cpp +SOURCES = main.cpp \ +../Classes/AppDelegate.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua -COCOS_LIBS = $(LIB_DIR)/libcocos2d.so $(LIB_DIR)/libcocosdenshion.so $(LIB_DIR)/liblua.so -include $(COCOS_ROOT)/cocos2dx/proj.linux/cocos2dx.mk +include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk $(TARGET): $(OBJECTS) $(STATICLIBS) $(COCOS_LIBS) $(CORE_MAKEFILE_LIST) @mkdir -p $(@D) cp -R -n ../../../../samples/Cpp/TestCpp/Resources ../../../../samples/Lua/TestLua - cp -n ../../../../scripting/lua/script/* ../../../../samples/Lua/TestLua/Resources + cp -n ../../../../cocos/scripting/lua/script/* ../../../../samples/Lua/TestLua/Resources $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) $(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) From 3252a8979138bcd7bbada264d733474a6561854f Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 22 Oct 2013 18:11:07 +0800 Subject: [PATCH 201/557] issues #2905:add SimpleGame vs-project --- .../SimpleGame/proj.win32/SimpleGame.vcxproj | 151 ++++++++++++++++++ .../proj.win32/SimpleGame.vcxproj.filters | 41 +++++ .../proj.win32/SimpleGame.vcxproj.user | 11 ++ samples/Cpp/SimpleGame/proj.win32/main.cpp | 20 +++ samples/Cpp/SimpleGame/proj.win32/main.h | 13 ++ 5 files changed, 236 insertions(+) create mode 100644 samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj create mode 100644 samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters create mode 100644 samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user create mode 100644 samples/Cpp/SimpleGame/proj.win32/main.cpp create mode 100644 samples/Cpp/SimpleGame/proj.win32/main.h diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj new file mode 100644 index 0000000000..cb3c74751e --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj @@ -0,0 +1,151 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {E0E282F4-8487-452C-BFAB-CB960EB4D22F} + SimpleGame + Win32Proj + + + + Application + Unicode + true + v100 + v110 + v110_xp + + + Application + Unicode + v100 + v110 + v110_xp + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + true + $(SolutionDir)$(Configuration).win32\ + $(Configuration).win32\ + false + AllRules.ruleset + + + AllRules.ruleset + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + + Disabled + ..\Classes;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + 4267;4251;4244;%(DisableSpecificWarnings) + + + $(OutDir)$(ProjectName).exe + $(OutDir);%(AdditionalLibraryDirectories) + true + Windows + MachineX86 + libcocos2d.lib;libchipmunk.lib;%(AdditionalDependencies) + + + + + + + + + MaxSpeed + true + ..\Classes;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + 4267;4251;4244;%(DisableSpecificWarnings) + + + libcocos2d.lib;%(AdditionalDependencies) + $(OutDir)$(ProjectName).exe + $(OutDir);%(AdditionalLibraryDirectories) + true + Windows + true + true + MachineX86 + + + + + + + + + + + + + + + + + + + + + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} + false + + + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} + + + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} + + + + + + \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters new file mode 100644 index 0000000000..cf39562aaa --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters @@ -0,0 +1,41 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + + + Classes + + + Classes + + + win32 + + + Classes + + + + + Classes + + + Classes + + + win32 + + + Classes + + + \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user new file mode 100644 index 0000000000..32a6296820 --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user @@ -0,0 +1,11 @@ + + + + $(ProjectDir)..\Resources + WindowsLocalDebugger + + + $(ProjectDir)..\Resources + WindowsLocalDebugger + + \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/main.cpp b/samples/Cpp/SimpleGame/proj.win32/main.cpp new file mode 100644 index 0000000000..d819bb02e0 --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.win32/main.cpp @@ -0,0 +1,20 @@ +#include "main.h" +#include "../Classes/AppDelegate.h" +#include "CCEGLView.h" + +USING_NS_CC; + +int APIENTRY _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) +{ + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + + // create the application instance + AppDelegate app; + EGLView eglView; + eglView.init("SimpleGame",900,640); + return Application::getInstance()->run(); +} diff --git a/samples/Cpp/SimpleGame/proj.win32/main.h b/samples/Cpp/SimpleGame/proj.win32/main.h new file mode 100644 index 0000000000..e74708bdf2 --- /dev/null +++ b/samples/Cpp/SimpleGame/proj.win32/main.h @@ -0,0 +1,13 @@ +#ifndef __MAIN_H__ +#define __MAIN_H__ + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +// Windows Header Files: +#include +#include + +// C RunTime Header Files +#include "CCStdC.h" + +#endif // __MAIN_H__ From 51801d9218ee834616ff5f08b6a873ab8e25e78a Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 23 Oct 2013 10:11:08 +0800 Subject: [PATCH 202/557] issue #2771: fix some compile error in android and win32 --- cocos/physics/CCPhysicsJoint.cpp | 18 ++++++------ cocos/physics/CCPhysicsWorld.cpp | 5 ++++ cocos/physics/CCPhysicsWorld.h | 1 + cocos/physics/chipmunk/CCPhysicsJointInfo.cpp | 3 ++ .../Classes/PhysicsTest/PhysicsTest.cpp | 29 +++++++++++++++++++ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 9 +++++- 6 files changed, 55 insertions(+), 10 deletions(-) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 18f63b7101..09b1de36dd 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -103,15 +103,15 @@ void PhysicsJoint::setEnable(bool enable) } } -//PhysicsJointPin::PhysicsJointPin() -//{ -// -//} -// -//PhysicsJointPin::~PhysicsJointPin() -//{ -// -//} +PhysicsJointPin::PhysicsJointPin() +{ + +} + +PhysicsJointPin::~PhysicsJointPin() +{ + +} PhysicsJointFixed::PhysicsJointFixed() { diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index cab183ba7a..ec7514ef6d 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -561,6 +561,11 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } +Array* getShapesAtPoint(Point point) +{ + +} + Array* PhysicsWorld::getAllBody() const { return _bodys; diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index e61cde2763..868889b539 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -97,6 +97,7 @@ public: void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); + Array* getShapesAtPoint(Point point); Array* getAllBody() const; /** Register a listener to receive contact callbacks*/ diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp index 7a44587ba5..b3fc376710 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp @@ -24,8 +24,11 @@ #include "CCPhysicsJointInfo.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#include NS_CC_BEGIN +std::map PhysicsJointInfo::map; + PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) : joint(joint) { diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 0c67ddc204..240d3ee2e8 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -673,4 +673,33 @@ void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Even std::string PhysicsDemoRayCast::title() { return "Ray Cast"; +} + + +void PhysicsDemoJoints::onEnter() +{ + PhysicsDemo::onEnter(); + + setTouchEnabled(true); + + _scene->getPhysicsWorld()->setGravity(Point::ZERO); + + +} + +void PhysicsDemoJoints::onTouchesEnded(const std::vector& touches, Event* event) +{ + //Add a new body/atlas sprite at the touched location + + for( auto &touch: touches) + { + auto location = touch->getLocation(); + + + } +} + +std::string PhysicsDemoJoints::title() +{ + return "Joints"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 65c1c6bad9..9df12624de 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -85,7 +85,6 @@ public: void onEnter() override; std::string title() override; void update(float delta) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; void changeModeCallback(Object* sender); @@ -98,4 +97,12 @@ private: int _mode; }; +class PhysicsDemoJoints : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + void onTouchesEnded(const std::vector& touches, Event* event) override; +}; + #endif From 17422c31235e8cf22e0e9aaca84c325afdbb3fb2 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 23 Oct 2013 11:08:21 +0800 Subject: [PATCH 203/557] issue #2771: fix some compile error in win32 --- cocos/physics/CCPhysicsShape.h | 14 +++++--------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 4 ++-- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index d1b5e0db04..ebbe646466 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -44,15 +44,11 @@ typedef struct PhysicsMaterial float restitution; float friction; - PhysicsMaterial() - : density(0.0f) - , restitution(0.0f) - , friction(0.0f){} - - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction){} + static PhysicsMaterial make(float density, float restitution, float friction) + { + PhysicsMaterial var = {density, restitution, friction}; + return var; + } }PhysicsMaterial; const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 240d3ee2e8..907a0df83a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -384,7 +384,7 @@ void PhysicsDemoLogoSmash::onEnter() Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, - 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); + 0.95f, PhysicsMaterial::make(1.0f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); @@ -396,7 +396,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(400, 0, 10, PhysicsMaterial::make(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); From 969b464b9b4097a6b57aa92182788a825763abcf Mon Sep 17 00:00:00 2001 From: ondesly Date: Wed, 23 Oct 2013 12:29:59 +0400 Subject: [PATCH 205/557] android & ios screen size change support --- cocos/2d/platform/android/CCApplication.cpp | 4 +++ cocos/2d/platform/android/CCApplication.h | 7 +++++ cocos/2d/platform/android/nativeactivity.cpp | 27 +++++++++++++++++++ cocos/2d/platform/ios/CCApplication.h | 7 +++++ cocos/2d/platform/ios/CCApplication.mm | 4 +++ .../proj.ios_mac/ios/RootViewController.mm | 11 +++++++- .../proj.ios_mac/ios/RootViewController.mm | 12 +++++++-- .../proj.ios_mac/ios/RootViewController.mm | 11 +++++++- 8 files changed, 79 insertions(+), 4 deletions(-) diff --git a/cocos/2d/platform/android/CCApplication.cpp b/cocos/2d/platform/android/CCApplication.cpp index 61b3f288cd..07c5814b3e 100644 --- a/cocos/2d/platform/android/CCApplication.cpp +++ b/cocos/2d/platform/android/CCApplication.cpp @@ -128,4 +128,8 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_ANDROID; } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/cocos/2d/platform/android/CCApplication.h b/cocos/2d/platform/android/CCApplication.h index e321266c81..d9b7d00f34 100644 --- a/cocos/2d/platform/android/CCApplication.h +++ b/cocos/2d/platform/android/CCApplication.h @@ -50,6 +50,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index fa4fb434d4..1cc60c406c 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -12,6 +12,7 @@ #include #include +#include #include "CCDirector.h" #include "CCApplication.h" @@ -69,6 +70,9 @@ struct engine { struct saved_state state; }; +static bool isContentRectChanged = false; +static std::chrono::steady_clock::time_point timeRectChanged; + static struct engine engine; static char* editboxText = NULL; @@ -556,6 +560,11 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { } } +static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { + timeRectChanged = std::chrono::steady_clock::now(); + isContentRectChanged = true; +} + /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own @@ -584,6 +593,9 @@ void android_main(struct android_app* state) { engine.state = *(struct saved_state*)state->savedState; } + // Screen size change support + state->activity->callbacks->onContentRectChanged = onContentRectChanged; + // loop waiting for stuff to do. while (1) { @@ -671,5 +683,20 @@ void android_main(struct android_app* state) { } else { LOG_RENDER_DEBUG("android_main : !engine.animating"); } + + // Check if screen size changed + if (isContentRectChanged) { + std::chrono::duration duration( + std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); + + // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime + if (duration.count() > 30) { + isContentRectChanged = false; + + int32_t newWidth = ANativeWindow_getWidth(engine.app->window); + int32_t newHeight = ANativeWindow_getHeight(engine.app->window); + cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); + } + } } } diff --git a/cocos/2d/platform/ios/CCApplication.h b/cocos/2d/platform/ios/CCApplication.h index 86be67bd29..a281a4f554 100644 --- a/cocos/2d/platform/ios/CCApplication.h +++ b/cocos/2d/platform/ios/CCApplication.h @@ -76,6 +76,13 @@ public: */ virtual Platform getTargetPlatform(); + /** + @brief This function will be called when the application screen size is changed. + @param new width + @param new height + */ + virtual void applicationScreenSizeChanged(int newWidth, int newHeight); + protected: static Application * sm_pSharedApplication; }; diff --git a/cocos/2d/platform/ios/CCApplication.mm b/cocos/2d/platform/ios/CCApplication.mm index 8c8d543c2e..c09a0aa8a9 100644 --- a/cocos/2d/platform/ios/CCApplication.mm +++ b/cocos/2d/platform/ios/CCApplication.mm @@ -146,4 +146,8 @@ Application::Platform Application::getTargetPlatform() } } +void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { + +} + NS_CC_END diff --git a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm index 906aeaf082..187b274b91 100644 --- a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm @@ -1,5 +1,6 @@ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -43,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm index a0f626dcd6..187b274b91 100644 --- a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,6 @@ - #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -44,6 +44,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { diff --git a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm index a00da00584..093a9b4c3a 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm @@ -24,7 +24,8 @@ ****************************************************************************/ #import "RootViewController.h" - +#import "cocos2d.h" +#import "EAGLView.h" @implementation RootViewController @@ -68,6 +69,14 @@ return YES; } +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); +} + //fix not hide status on ios7 - (BOOL)prefersStatusBarHidden { From dfd69d262aafacea1c77fbb0d932dd549d4c20f2 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 23 Oct 2013 16:48:51 +0800 Subject: [PATCH 206/557] adjust std:function support 10 parameter --- cocos/2d/cocos2d_headers.props | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/2d/cocos2d_headers.props b/cocos/2d/cocos2d_headers.props index a5d8616d03..020fd07d2f 100644 --- a/cocos/2d/cocos2d_headers.props +++ b/cocos/2d/cocos2d_headers.props @@ -8,6 +8,7 @@ $(EngineRoot)cocos\2d;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES; + _VARIADIC_MAX=10;%(PreprocessorDefinitions) From e81efb24c932275090b45461f2fd4a07279d082d Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 23 Oct 2013 16:49:50 +0800 Subject: [PATCH 207/557] issue #2905: android samples run ok --- .../Cpp/AssetsManagerTest/proj.android/project.properties | 4 ++-- samples/Cpp/HelloCpp/proj.android/project.properties | 5 ++--- samples/Cpp/SimpleGame/proj.android/project.properties | 4 ++-- samples/Cpp/TestCpp/proj.android/project.properties | 4 ++-- .../Javascript/CocosDragonJS/proj.android/project.properties | 4 ++-- .../Javascript/CrystalCraze/proj.android/project.properties | 4 ++-- .../Javascript/MoonWarriors/proj.android/project.properties | 4 ++-- .../TestJavascript/proj.android/project.properties | 4 ++-- .../WatermelonWithMe/proj.android/project.properties | 4 ++-- samples/Lua/HelloLua/proj.android/project.properties | 4 ++-- samples/Lua/TestLua/proj.android/project.properties | 4 ++-- template/multi-platform-cpp/proj.android/project.properties | 4 ++-- template/multi-platform-js/proj.android/project.properties | 2 +- template/multi-platform-lua/proj.android/project.properties | 4 ++-- 14 files changed, 27 insertions(+), 28 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/project.properties b/samples/Cpp/AssetsManagerTest/proj.android/project.properties index 5c08afb38c..f7e62936d0 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/project.properties +++ b/samples/Cpp/AssetsManagerTest/proj.android/project.properties @@ -11,5 +11,5 @@ #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=android-13 -android.library.reference.1=../../../../cocos2dx/platform/android/java +target=android-10 +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Cpp/HelloCpp/proj.android/project.properties b/samples/Cpp/HelloCpp/proj.android/project.properties index 088495876a..0a6dc6664d 100644 --- a/samples/Cpp/HelloCpp/proj.android/project.properties +++ b/samples/Cpp/HelloCpp/proj.android/project.properties @@ -8,7 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java -android.library=false +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Cpp/SimpleGame/proj.android/project.properties b/samples/Cpp/SimpleGame/proj.android/project.properties index 5c08afb38c..f7e62936d0 100644 --- a/samples/Cpp/SimpleGame/proj.android/project.properties +++ b/samples/Cpp/SimpleGame/proj.android/project.properties @@ -11,5 +11,5 @@ #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=android-13 -android.library.reference.1=../../../../cocos2dx/platform/android/java +target=android-10 +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Cpp/TestCpp/proj.android/project.properties b/samples/Cpp/TestCpp/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Cpp/TestCpp/proj.android/project.properties +++ b/samples/Cpp/TestCpp/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/CocosDragonJS/proj.android/project.properties b/samples/Javascript/CocosDragonJS/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/project.properties +++ b/samples/Javascript/CocosDragonJS/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/CrystalCraze/proj.android/project.properties b/samples/Javascript/CrystalCraze/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Javascript/CrystalCraze/proj.android/project.properties +++ b/samples/Javascript/CrystalCraze/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/MoonWarriors/proj.android/project.properties b/samples/Javascript/MoonWarriors/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Javascript/MoonWarriors/proj.android/project.properties +++ b/samples/Javascript/MoonWarriors/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/TestJavascript/proj.android/project.properties b/samples/Javascript/TestJavascript/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Javascript/TestJavascript/proj.android/project.properties +++ b/samples/Javascript/TestJavascript/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/WatermelonWithMe/proj.android/project.properties b/samples/Javascript/WatermelonWithMe/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/project.properties +++ b/samples/Javascript/WatermelonWithMe/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Lua/HelloLua/proj.android/project.properties b/samples/Lua/HelloLua/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Lua/HelloLua/proj.android/project.properties +++ b/samples/Lua/HelloLua/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Lua/TestLua/proj.android/project.properties b/samples/Lua/TestLua/proj.android/project.properties index db4ff43492..0a6dc6664d 100644 --- a/samples/Lua/TestLua/proj.android/project.properties +++ b/samples/Lua/TestLua/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../../cocos2dx/platform/android/java +android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/template/multi-platform-cpp/proj.android/project.properties b/template/multi-platform-cpp/proj.android/project.properties index 6495217b66..16f145cfc9 100644 --- a/template/multi-platform-cpp/proj.android/project.properties +++ b/template/multi-platform-cpp/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../cocos2dx/platform/android/java +android.library.reference.1=../../../cocos/2d/platform/android/java diff --git a/template/multi-platform-js/proj.android/project.properties b/template/multi-platform-js/proj.android/project.properties index 6495217b66..f0d6a80641 100644 --- a/template/multi-platform-js/proj.android/project.properties +++ b/template/multi-platform-js/proj.android/project.properties @@ -10,4 +10,4 @@ # Project target. target=android-13 -android.library.reference.1=../../../cocos2dx/platform/android/java +android.library.reference.1=../../../cocos/2d/platform/android/java diff --git a/template/multi-platform-lua/proj.android/project.properties b/template/multi-platform-lua/proj.android/project.properties index 6495217b66..16f145cfc9 100644 --- a/template/multi-platform-lua/proj.android/project.properties +++ b/template/multi-platform-lua/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-13 +target=android-10 -android.library.reference.1=../../../cocos2dx/platform/android/java +android.library.reference.1=../../../cocos/2d/platform/android/java From 3305dd1de3a1c6f4ece62865e8ea6fbe8353a10b Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 23 Oct 2013 17:05:27 +0800 Subject: [PATCH 208/557] issues #2905:add miss file --- tools/tojs/cocos2dx_builder.ini | 65 +++++++++++++++++++++++++++++++++ tools/tojs/cocos2dx_studio.ini | 65 +++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 tools/tojs/cocos2dx_builder.ini create mode 100644 tools/tojs/cocos2dx_studio.ini diff --git a/tools/tojs/cocos2dx_builder.ini b/tools/tojs/cocos2dx_builder.ini new file mode 100644 index 0000000000..15de5f54d8 --- /dev/null +++ b/tools/tojs/cocos2dx_builder.ini @@ -0,0 +1,65 @@ +[cocos2dx_builder] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_builder + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = cc + +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include +android_flags = -D_SIZE_T_DEFINED_ + +clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include +clang_flags = -nostdinc -x c++ -std=c++11 + +cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + +cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT + +cxxgenerator_headers = + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes = CCBReader.* CCBAnimationManager.* + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getCCBMemberVariableAssigner readFloat getCCBSelectorResolver toLowerCase lastPathComponent deletePathExtension endsWith concat getResolutionScale getAnimatedProperties readBool readInt addOwnerCallbackNode addDocumentCallbackName readCachedString readNodeGraphFromData addDocumentCallbackNode getLoadedSpriteSheet initWithData readFileWithCleanUp getOwner$ readNodeGraphFromFile createSceneWithNodeGraphFromFile getAnimationManagers$ setAnimationManagers], + CCBAnimationManager::[setAnimationCompletedCallback], + .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener] + +rename_functions = + +rename_classes = CCBReader::_Reader, + CCBAnimationManager::BuilderAnimationManager + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Object + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = + +# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. +script_control_cpp = no + diff --git a/tools/tojs/cocos2dx_studio.ini b/tools/tojs/cocos2dx_studio.ini new file mode 100644 index 0000000000..47859dac3f --- /dev/null +++ b/tools/tojs/cocos2dx_studio.ini @@ -0,0 +1,65 @@ +[cocos2dx_studio] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_studio + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = cc + +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include +android_flags = -D_SIZE_T_DEFINED_ + +clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include +clang_flags = -nostdinc -x c++ -std=c++11 + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + +cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT + +cxxgenerator_headers = + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], + Armature::[createBone updateBlendType getBody setBody getShapeList .*BlendFunc], + Skin::[getSkinData setSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent] + +rename_functions = + +rename_classes = + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Object ProcessBase + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = ArmatureDataManager + +# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. +script_control_cpp = no + From 899f720efa299637abbc41a10f33a33419ed4d86 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 23 Oct 2013 17:28:23 +0800 Subject: [PATCH 209/557] issue #2771: implement getShapeAtPoint and getShapesAtPoint --- cocos/physics/CCPhysicsJoint.cpp | 21 ++++++---- cocos/physics/CCPhysicsWorld.cpp | 33 ++++++++++++++- cocos/physics/CCPhysicsWorld.h | 1 + .../Classes/PhysicsTest/PhysicsTest.cpp | 41 +++++++++++++------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 12 +++++- 5 files changed, 85 insertions(+), 23 deletions(-) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 09b1de36dd..6631599f71 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -70,16 +70,21 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) { do { - CC_BREAK_IF(a == nullptr || b == nullptr); - CC_BREAK_IF(!(_info = new PhysicsJointInfo(this))); - _bodyA = a; - _bodyA->retain(); - _bodyA->_joints.push_back(this); - _bodyB = b; - _bodyB->retain(); - _bodyB->_joints.push_back(this); + if (a != nullptr) + { + _bodyA = a; + _bodyA->retain(); + _bodyA->_joints.push_back(this); + } + + if (b != nullptr) + { + _bodyB = b; + _bodyB->retain(); + _bodyB->_joints.push_back(this); + } return true; } while (false); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index ec7514ef6d..44d0fc1f96 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -88,6 +88,7 @@ public: static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world); static void rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info); static void rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info); + static void nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr); public: static bool continues; @@ -166,6 +167,15 @@ void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallba info->data); } +void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) +{ + auto it = PhysicsShapeInfo::map.find(shape); + + CC_ASSERT(it != PhysicsShapeInfo::map.end()); + + arr->addObject(it->second->shape); +} + bool PhysicsWorld::init() { _info = new PhysicsWorldInfo(); @@ -561,9 +571,30 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* getShapesAtPoint(Point point) +Array* PhysicsWorld::getShapesAtPoint(Point point) { + Array* arr = Array::create(); + cpSpaceNearestPointQuery(this->_info->space, + PhysicsHelper::point2cpv(point), + 0, + CP_ALL_LAYERS, + CP_NO_GROUP, + (cpSpaceNearestPointQueryFunc)PhysicsWorldCallback::nearestPointQueryFunc, + arr); + return arr; +} + +PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) +{ + cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, + PhysicsHelper::point2cpv(point), + 0, + CP_ALL_LAYERS, + CP_NO_GROUP, + nullptr); + + return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; } Array* PhysicsWorld::getAllBody() const diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 868889b539..63c841cc93 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -98,6 +98,7 @@ public: void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); Array* getShapesAtPoint(Point point); + PhysicsShape* getShapeAtPoint(Point point); Array* getAllBody() const; /** Register a listener to receive contact callbacks*/ diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 907a0df83a..c92b431716 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -92,6 +92,7 @@ PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _ball(nullptr) , _spriteTexture(nullptr) +, _mouse(nullptr) { } @@ -296,7 +297,8 @@ namespace -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127, -97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8, 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, - 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0}; + 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0 + }; static inline int get_pixel(int x, int y) { @@ -365,6 +367,31 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m return triangle; } +void PhysicsDemo::onTouchesBegan(const std::vector& touches, Event* event) +{ + for( auto &touch: touches) + { + auto location = touch->getLocation(); + Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + + PhysicsShape* shape = nullptr; + for (Object* obj : *arr) + { + + } + } +} + +void PhysicsDemo::onTouchesMoved(const std::vector& touches, Event* event) +{ + +} + +void PhysicsDemo::onTouchesEnded(const std::vector& touches, Event* event) +{ + +} + void PhysicsDemoLogoSmash::onEnter() { PhysicsDemo::onEnter(); @@ -687,18 +714,6 @@ void PhysicsDemoJoints::onEnter() } -void PhysicsDemoJoints::onTouchesEnded(const std::vector& touches, Event* event) -{ - //Add a new body/atlas sprite at the touched location - - for( auto &touch: touches) - { - auto location = touch->getLocation(); - - - } -} - std::string PhysicsDemoJoints::title() { return "Joints"; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 9df12624de..b915e9d664 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -41,9 +41,14 @@ public: Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); + void onTouchesBegan(const std::vector& touches, Event* event) override; + void onTouchesMoved(const std::vector& touches, Event* event) override; + void onTouchesEnded(const std::vector& touches, Event* event) override; + protected: Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; + DrawNode* _mouse; }; class PhysicsDemoClickAdd : public PhysicsDemo @@ -99,10 +104,15 @@ private: class PhysicsDemoJoints : public PhysicsDemo { +public: + PhysicsDemoJoints(); + public: void onEnter() override; std::string title() override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + +private: + PhysicsShape* _touchesShape; }; #endif From d07d054a01991fd3b2d9a2c2c36f3194018febf1 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 23 Oct 2013 17:44:20 +0800 Subject: [PATCH 210/557] issue #2905:ndk-r8e build ok now --- cocos/2d/Android.mk | 4 ---- cocos/editor-support/cocostudio/Android.mk | 3 +-- cocos/gui/Android.mk | 14 +++++++++----- samples/Cpp/TestCpp/Android.mk | 5 +++-- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index ec9f2dbf6e..6a25764f44 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -203,10 +203,6 @@ LOCAL_EXPORT_CPPFLAGS := -Wno-literal-suffix include $(BUILD_STATIC_LIBRARY) -$(call import-module,jpeg/prebuilt/android) -$(call import-module,png/prebuilt/android) -$(call import-module,tiff/prebuilt/android) -$(call import-module,webp/prebuilt/android) $(call import-module,freetype2/prebuilt/android) $(call import-module,chipmunk) $(call import-module,2d/platform/android) diff --git a/cocos/editor-support/cocostudio/Android.mk b/cocos/editor-support/cocostudio/Android.mk index b9b1535fe6..ea352f8485 100644 --- a/cocos/editor-support/cocostudio/Android.mk +++ b/cocos/editor-support/cocostudio/Android.mk @@ -48,8 +48,7 @@ $(LOCAL_PATH)/../../../external LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ $(LOCAL_PATH)/../../../external \ $(LOCAL_PATH)/.. \ -$(LOCAL_PATH)/../.. \ -$(LOCAL_PATH)/../../../external +$(LOCAL_PATH)/../.. LOCAL_CFLAGS += -Wno-psabi -fexceptions LOCAL_EXPORT_CFLAGS += -Wno-psabi diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 49f33a17e6..33171c7c1d 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -29,18 +29,22 @@ UISlider.cpp \ UITextField.cpp -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ +$(LOCAL_PATH)/../editor-support -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \ -$(LOCAL_PATH)/.. +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../2d \ +$(LOCAL_PATH)/../../external \ +$(LOCAL_PATH)/.. \ +$(LOCAL_PATH)/../.. \ +$(LOCAL_PATH)/../editor-support LOCAL_CFLAGS += -Wno-psabi LOCAL_EXPORT_CFLAGS += -Wno-psabi -LOCAL_WHOLE_STATIC_LIBRARIES := cocostudio_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static include $(BUILD_STATIC_LIBRARY) -$(call import-module,editor-support/cocostudio) $(call import-module,extensions) +$(call import-module,2d) diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index af16f48433..c848586fbb 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -141,11 +141,11 @@ Classes/ZwoptexTest/ZwoptexTest.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/Classes -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocosbuilder_static LOCAL_WHOLE_STATIC_LIBRARIES += spine_static LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/Classes @@ -157,3 +157,4 @@ $(call import-module,editor-support/cocosbuilder) $(call import-module,editor-support/spine) $(call import-module,editor-support/cocostudio) $(call import-module,network) +$(call import-module,2d) From a8ddca81bd165d8d06f04f63d22f7d1d17626440 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 23 Oct 2013 18:52:09 +0800 Subject: [PATCH 211/557] issue #2771: fix some compile error in win32 --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsShape.h | 18 ++++++++++++------ .../Classes/PhysicsTest/PhysicsTest.cpp | 10 +++++----- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 6 +++--- 4 files changed, 21 insertions(+), 15 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 65d9f7318a..f1715b0f1a 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -43,7 +43,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {1.0f, 1.0f, 1.0f}; +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(1.0f, 1.0f, 1.0f); /** * A body affect by physics. diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index ebbe646466..6cd5329f6d 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -44,14 +44,20 @@ typedef struct PhysicsMaterial float restitution; float friction; - static PhysicsMaterial make(float density, float restitution, float friction) - { - PhysicsMaterial var = {density, restitution, friction}; - return var; - } + PhysicsMaterial() + : density(0.0f) + , restitution(0.0f) + , friction(0.0f) + {} + + PhysicsMaterial(float density, float restitution, float friction) + : density(density) + , restitution(restitution) + , friction(friction) + {} }PhysicsMaterial; -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; +const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 1.0f, 1.0f); /** * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index c92b431716..f0ceb3553c 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -50,7 +50,7 @@ namespace return layer; } - static const Color4F STATIC_COLOR = {1.0f, 0.0f, 0.0f, 1.0f}; + static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); } @@ -411,7 +411,7 @@ void PhysicsDemoLogoSmash::onEnter() Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, - 0.95f, PhysicsMaterial::make(1.0f, 0.0f, 0.0f)); + 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); @@ -423,7 +423,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(400, 0, 10, PhysicsMaterial::make(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -454,7 +454,7 @@ void PhysicsDemoPyramidStack::onEnter() { for(int j=0; j<=i; j++) { - addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2); + addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); } } } @@ -671,7 +671,7 @@ void PhysicsDemoRayCast::update(float delta) break; } - _angle += 0.25f * M_PI / 180.0f; + _angle += 0.25f * (float)M_PI / 180.0f; } void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Event* event) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index b915e9d664..0c685ef98e 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -37,9 +37,9 @@ public: void toggleDebugCallback(Object* sender); void addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = {1.0f, 1.0f, 1.0f}); + Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); + Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); + Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); void onTouchesBegan(const std::vector& touches, Event* event) override; void onTouchesMoved(const std::vector& touches, Event* event) override; From d7689073e0c91c342ed551614ddef050cf537d7c Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 24 Oct 2013 11:12:21 +0800 Subject: [PATCH 212/557] issue #3049:Add XMLHttpRequest lua binding and corresponding test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- .../lua/bindings/lua_xml_http_request.cpp | 922 ++++++++++++++++++ .../lua/bindings/lua_xml_http_request.h | 94 ++ 3 files changed, 1017 insertions(+), 1 deletion(-) create mode 100644 cocos/scripting/lua/bindings/lua_xml_http_request.cpp create mode 100644 cocos/scripting/lua/bindings/lua_xml_http_request.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 18265b616b..b62768a5e8 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1c487d29bdc2d80516e86e2ee93b1664e9f7df2f \ No newline at end of file +fcdf6af61b7c3ac52b92590b16090335bd26b169 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp new file mode 100644 index 0000000000..eaf2202ba0 --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp @@ -0,0 +1,922 @@ + +#include "lua_xml_http_request.h" + +extern "C" +{ +#include "tolua_fix.h" +} + +#include + +using namespace std; + +LuaMinXmlHttpRequest::LuaMinXmlHttpRequest():_isNetwork(true) +{ + _httpHeader.clear(); + _requestHeader.clear(); + _withCredentialsValue = true; + _httpRequest = new network::HttpRequest(); +} + +LuaMinXmlHttpRequest::~LuaMinXmlHttpRequest() +{ + _httpHeader.clear(); + _requestHeader.clear(); +} + +/** + * @brief Implementation for header retrieving. + * @param header + */ +void LuaMinXmlHttpRequest::_gotHeader(string header) +{ + // Get Header and Set StatusText + // Split String into Tokens + char * cstr = new char [header.length()+1]; + + // check for colon. + unsigned found_header_field = header.find_first_of(":"); + + if (found_header_field != std::string::npos) + { + // Found a header field. + string http_field; + string http_value; + + http_field = header.substr(0,found_header_field); + http_value = header.substr(found_header_field+1, header.length()); + + // Get rid of all \n + if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') { + http_value.erase(http_value.size() - 1); + } + + _httpHeader[http_field] = http_value; + + } + else + { + // Seems like we have the response Code! Parse it and check for it. + char * pch; + strcpy(cstr, header.c_str()); + + pch = strtok(cstr," "); + while (pch != NULL) + { + + stringstream ss; + string val; + + ss << pch; + val = ss.str(); + unsigned found_http = val.find("HTTP"); + + // Check for HTTP Header to set statusText + if (found_http != std::string::npos) { + + stringstream mystream; + + // Get Response Status + pch = strtok (NULL, " "); + mystream << pch; + + pch = strtok (NULL, " "); + mystream << " " << pch; + + _statusText = mystream.str(); + + } + + pch = strtok (NULL, " "); + } + } + + CC_SAFE_DELETE_ARRAY(cstr); +} + +/** + * @brief Set Request header for next call. + * @param field Name of the Header to be set. + * @param value Value of the Headerfield + */ +void LuaMinXmlHttpRequest::setRequestHeader(const char* field, const char* value) +{ + stringstream header_s; + stringstream value_s; + string header; + + map::iterator iter = _requestHeader.find(field); + + // Concatenate values when header exists. + if (iter != _requestHeader.end()) + { + value_s << iter->second << "," << value; + } + else + { + value_s << value; + } + + _requestHeader[field] = value_s.str(); +} + +/** + * @brief If headers has been set, pass them to curl. + * + */ +void LuaMinXmlHttpRequest::_setHttpRequestHeader() +{ + std::vector header; + + for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it) + { + const char* first = it->first.c_str(); + const char* second = it->second.c_str(); + size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); + char* test = (char*) malloc(len); + memset(test, 0,len); + + strcpy(test, first); + strcpy(test + strlen(first) , ": "); + strcpy(test + strlen(first) + 2, second); + + header.push_back(test); + + free(test); + + } + + if (!header.empty()) + { + _httpRequest->setHeaders(header); + } + +} + +/** + * @brief Send out request and fire callback when done. + */ +void LuaMinXmlHttpRequest::_sendRequest() +{ + _httpRequest->setResponseCallback(this, httpresponse_selector(LuaMinXmlHttpRequest::handle_requestResponse)); + network::HttpClient::getInstance()->send(_httpRequest); + _httpRequest->release(); +} + + +/** + * @brief Callback for HTTPRequest. Handles the response and invokes Callback. + * @param sender Object which initialized callback + * @param respone Response object + * @js NA + */ +void LuaMinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response) +{ + if (0 != strlen(response->getHttpRequest()->getTag())) + { + CCLOG("%s completed", response->getHttpRequest()->getTag()); + } + + int statusCode = response->getResponseCode(); + char statusString[64] = {}; + sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); + + if (!response->isSucceed()) + { + CCLOG("response failed"); + CCLOG("error buffer: %s", response->getErrorBuffer()); + return; + } + + // set header + std::vector *headers = response->getResponseHeader(); + + char* concatHeader = (char*) malloc(headers->size() + 1); + std::string header(headers->begin(), headers->end()); + strcpy(concatHeader, header.c_str()); + + std::istringstream stream(concatHeader); + std::string line; + while(std::getline(stream, line)) { + _gotHeader(line); + } + + /** get the response data **/ + std::vector *buffer = response->getResponseData(); + char* concatenated = (char*) malloc(buffer->size() + 1); + std::string s2(buffer->begin(), buffer->end()); + + strcpy(concatenated, s2.c_str()); + + if (statusCode == 200) + { + //Succeeded + _status = 200; + _readyState = DONE; + _data << concatenated; + _dataSize = buffer->size(); + } + else + { + _status = 0; + } + // Free Memory. + free((void*) concatHeader); + free((void*) concatenated); + + // call back lua function --TODO + int handler = 0; +} + +/* function to regType */ +static void lua_reg_xml_http_request(lua_State* L) +{ + tolua_usertype(L, "XMLHttpRequest"); +} + +static int lua_collect_xml_http_request (lua_State* L) +{ + LuaMinXmlHttpRequest* self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); + Mtolua_delete(self); + return 0; +} + +static int lua_cocos2dx_XMLHttpRequest_constructor(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + argc = lua_gettop(L)-1; + if (argc == 0) + { + self = new LuaMinXmlHttpRequest(); + self->autorelease(); + int ID = self? (int)self->_ID : -1; + int* luaID = self? &self->_luaID : NULL; + toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "XMLHttpRequest"); + } + + CCLOG("%s has wrong number of arguments: %d, was expecting %d \n", "XMLHttpRequest",argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_constructor'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_responseType(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_responseType'\n", nullptr); + return 0; + } +#endif + + tolua_pushnumber(L, (lua_Number)self->getResponseType()); + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_responseType'.",&tolua_err); + return 0; +#endif +} + +static int lua_set_XMLHttpRequest_responseType(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_set_XMLHttpRequest_responseType'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + int responseType = (int)tolua_tonumber(L,2,0); + + self->setResponseType((LuaMinXmlHttpRequest::ResponseType)responseType); + + return 0; + } + + CCLOG("'setResponseType' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_set_XMLHttpRequest_responseType'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_withCredentials(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_withCredentials'\n", nullptr); + return 0; + } +#endif + + tolua_pushboolean(L, self->getWithCredentialsValue()); + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_withCredentials'.",&tolua_err); + return 0; +#endif +} + +static int lua_set_XMLHttpRequest_withCredentials(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_set_XMLHttpRequest_withCredentials'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + self->setWithCredentialsValue((bool)tolua_toboolean(L, 2, 0)); + return 0; + } + + CCLOG("'setWithCredentials' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_set_XMLHttpRequest_withCredentials'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_timeout(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_timeout'\n", nullptr); + return 0; + } +#endif + + tolua_pushnumber(L, (lua_Number)self->getTimeout()); + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_timeout'.",&tolua_err); + return 0; +#endif +} + +static int lua_set_XMLHttpRequest_timeout(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_set_XMLHttpRequest_timeout'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + self->setTimeout((unsigned)tolua_tonumber(L, 2, 0)); + return 0; + } + + CCLOG("'setTimeout' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_set_XMLHttpRequest_timeout'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_readyState(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_readyState'\n", nullptr); + return 0; + } +#endif + + lua_pushinteger(L, (lua_Integer)self->getReadyState()); + + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_readyState'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_status(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_status'\n", nullptr); + return 0; + } +#endif + + lua_pushinteger(L, (lua_Integer)self->getStatus()); + + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_status'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_statusText(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_statusText'\n", nullptr); + return 0; + } +#endif + + lua_pushstring(L, self->getStatusText().c_str()); + + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_statusText'.",&tolua_err); + return 0; +#endif +} + +static int lua_get_XMLHttpRequest_response(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_response'\n", nullptr); + return 0; + } +#endif + + if (self->getResponseType() == LuaMinXmlHttpRequest::ResponseType::JSON) + { + //TODO + return 0; + } + else if(self->getResponseType() == LuaMinXmlHttpRequest::ResponseType::ARRAY_BUFFER) + { + //TODO + return 0; + } + else + { + lua_pushstring(L, self->getStatusText().c_str()); + return 1; + } + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_response'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_XMLHttpRequest_open(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_open'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if ( argc >= 2) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 2, 0, &tolua_err) || + !tolua_isstring(L, 3, 0, &tolua_err)) + goto tolua_lerror; +#endif + + std::string method = tolua_tostring(L, 2, ""); + std::string url = tolua_tostring(L, 3, ""); + bool async = true; + if (argc > 2) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 4, 0, &tolua_err) ) + goto tolua_lerror; +#endif + async = tolua_toboolean(L, 4, 0); + } + + self->setUrl(url); + self->setMethod(method); + self->setReadyState(1); + self->setAsync(async); + + if (url.length() > 5 && url.compare(url.length() - 5, 5, ".json") == 0 ) + { + self->setResponseType(LuaMinXmlHttpRequest::ResponseType::JSON); + } + + if (nullptr != self->getHttpRequest()) + { + if (method.compare("post") == 0 || method.compare("POST") == 0) + { + self->getHttpRequest()->setRequestType(network::HttpRequest::Type::POST); + } + else + { + self->getHttpRequest()->setRequestType(network::HttpRequest::Type::GET); + } + + self->getHttpRequest()->setUrl(url.c_str()); + + } + + self->setIsNetWork(true); + self->setReadyState(LuaMinXmlHttpRequest::OPENED); + + return 0; + } + + CCLOG("'open' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_open'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_XMLHttpRequest_send(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + std::string data = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_send'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if ( 1 == argc ) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + data = tolua_tostring(L, 2, ""); + } + + if (data.length() > 0 && + (self->getMethod().compare("post") == 0 || self->getMethod().compare("POST") == 0) && + nullptr != self->getHttpRequest()) + { + self->getHttpRequest()->setRequestData(data.c_str(), data.length()); + } + + self->_setHttpRequestHeader(); + self->_sendRequest(); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_send'.",&tolua_err); + return 0; +#endif +} + +/** + * @brief abort function Placeholder! + */ +static int lua_cocos2dx_XMLHttpRequest_abort(lua_State* L) +{ + return 0; +} + +static int lua_cocos2dx_XMLHttpRequest_setRequestHeader(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + const char* field = ""; + const char* value = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_setRequestHeader'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if ( 2 == argc ) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 2, 0, &tolua_err) || + !tolua_isstring(L, 3, 0, &tolua_err) ) + goto tolua_lerror; +#endif + + field = tolua_tostring(L, 2, ""); + value = tolua_tostring(L, 3, ""); + self->setRequestHeader(field, value); + return 0; + } + + CCLOG("'setRequestHeader' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_setRequestHeader'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + + stringstream responseheaders; + string responseheader = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if ( 0 == argc ) + { + map httpHeader = self->getHttpHeader(); + + for (auto it = httpHeader.begin(); it != httpHeader.end(); ++it) + { + responseheaders << it->first << ": "<< it->second << "\n"; + } + + responseheader = responseheaders.str(); + tolua_pushstring(L, responseheader.c_str()); + return 1; + } + + CCLOG("'getAllResponseHeaders' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_XMLHttpRequest_getResponseHeader(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + + string responseheader = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if ( 1 == argc ) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isstring(L, 2, 0, &tolua_err) ) + goto tolua_lerror; +#endif + responseheader = tolua_tostring(L, 2, ""); + + stringstream streamData; + streamData << responseheader; + + string value = streamData.str(); + + + auto iter = self->getHttpHeader().find(value); + if (iter != self->getHttpHeader().end()) + { + tolua_pushstring(L, (iter->second).c_str()); + return 1; + } + } + + CCLOG("'getResponseHeader' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders'.",&tolua_err); + return 0; +#endif +} + +TOLUA_API int lua_xml_http_request_open(lua_State* L) +{ + tolua_open(L); + lua_reg_xml_http_request(L); + tolua_module(L,NULL,0); + tolua_beginmodule(L,NULL); + tolua_cclass(L,"XMLHttpRequest","XMLHttpRequest","",lua_collect_xml_http_request); + tolua_beginmodule(L,"XMLHttpRequest"); + tolua_variable(L, "responseType", lua_get_XMLHttpRequest_responseType, lua_set_XMLHttpRequest_responseType); + tolua_variable(L, "withCredentials", lua_get_XMLHttpRequest_withCredentials, lua_set_XMLHttpRequest_withCredentials); + tolua_variable(L, "timeout", lua_get_XMLHttpRequest_timeout, lua_set_XMLHttpRequest_timeout); + tolua_variable(L, "readyState", lua_get_XMLHttpRequest_readyState, nullptr); + tolua_variable(L, "status",lua_get_XMLHttpRequest_status,nullptr); + tolua_variable(L, "statusText", lua_get_XMLHttpRequest_statusText, nullptr); + tolua_variable(L, "response", lua_get_XMLHttpRequest_response, nullptr); + tolua_function(L, "new", lua_cocos2dx_XMLHttpRequest_constructor); + tolua_function(L, "open", lua_cocos2dx_XMLHttpRequest_open); + tolua_function(L, "send", lua_cocos2dx_XMLHttpRequest_send); + tolua_function(L, "abort", lua_cocos2dx_XMLHttpRequest_abort); + tolua_function(L, "setRequestHeader", lua_cocos2dx_XMLHttpRequest_setRequestHeader); + tolua_function(L, "getAllResponseHeaders", lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders); + tolua_function(L, "getResponseHeader", lua_cocos2dx_XMLHttpRequest_getResponseHeader); + tolua_endmodule(L); + tolua_endmodule(L); + return 1; +} diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.h b/cocos/scripting/lua/bindings/lua_xml_http_request.h new file mode 100644 index 0000000000..2b5a3a2f17 --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.h @@ -0,0 +1,94 @@ +#ifndef __COCOS_SCRIPTING_LUA_BINDINGS_LUA_XML_HTTP_REQUEST_H__ +#define __COCOS_SCRIPTING_LUA_BINDINGS_LUA_XML_HTTP_REQUEST_H__ + +#ifdef __cplusplus +extern "C" { +#endif +#include "tolua++.h" +#ifdef __cplusplus +} +#endif + + +#include "network/HttpClient.h" + +class LuaMinXmlHttpRequest : public cocos2d::Object +{ +public: + enum class ResponseType + { + STRING, + ARRAY_BUFFER, + BLOB, + DOCUMENT, + JSON + }; + + // Ready States (http://www.w3.org/TR/XMLHttpRequest/#interface-xmlhttprequest) + static const unsigned short UNSENT = 0; + static const unsigned short OPENED = 1; + static const unsigned short HEADERS_RECEIVED = 2; + static const unsigned short LOADING = 3; + static const unsigned short DONE = 4; + + LuaMinXmlHttpRequest(); + ~LuaMinXmlHttpRequest(); + + void handle_requestResponse(network::HttpClient *sender, network::HttpResponse *response); + + inline void setResponseType(ResponseType type) { _responseType = type; } + inline ResponseType getResponseType() {return _responseType; } + + inline void setWithCredentialsValue(bool value) { _withCredentialsValue = value; } + inline bool getWithCredentialsValue() {return _withCredentialsValue; } + + inline void setTimeout(unsigned timeOut) {_timeout = timeOut; } + inline unsigned getTimeout() { return _timeout;} + + inline void setReadyState(int readyState) { _readyState = readyState; } + inline int getReadyState() { return _readyState ;} + + inline network::HttpRequest* getHttpRequest() { return _httpRequest; } + inline int getStatus() { return _status; } + inline std::string getStatusText() { return _statusText ;} + + inline std::string getUrl(){return _url;} + inline void setUrl(std::string url) { _url = url ;} + + inline std::string getMethod(){return _meth;} + inline void setMethod(std::string meth) { _meth = meth ; } + + inline void setAsync(bool isAsync){ _isAsync = isAsync; } + inline void setIsNetWork(bool isNetWork) {_isNetwork = isNetWork; } + + void _setHttpRequestHeader(); + void _sendRequest(); + void setRequestHeader(const char* field, const char* value); + + std::map getHttpHeader() { return _httpHeader ;} +private: + void _gotHeader(std::string header); + + + + std::string _url; + std::string _meth; + std::string _type; + std::stringstream _data; + size_t _dataSize; + int _readyState; + int _status; + std::string _statusText; + ResponseType _responseType; + unsigned _timeout; + bool _isAsync; + network::HttpRequest* _httpRequest; + bool _isNetwork; + bool _withCredentialsValue; + std::map _httpHeader; + std::map _requestHeader; +}; + +TOLUA_API int lua_xml_http_request_open(lua_State* L); + +#endif //#ifndef __COCOS_SCRIPTING_LUA_BINDINGS_LUA_XML_HTTP_REQUEST_H__ From fd993e2fa210ab7c4c2a274518ffc72d6f4b532c Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 24 Oct 2013 17:54:57 +0800 Subject: [PATCH 213/557] issues #2905:split jsbinding module --- .../scripting/javascript/bindings/Android.mk | 43 +++---------------- .../javascript/bindings/chipmunk/Android.mk | 33 ++++++++++++++ .../bindings/cocosbuilder/Android.mk | 29 +++++++++++++ .../javascript/bindings/cocostudio/Android.mk | 30 +++++++++++++ .../javascript/bindings/extension/Android.mk | 30 +++++++++++++ .../bindings/localstorage/Android.mk | 29 +++++++++++++ .../javascript/bindings/network/Android.mk | 30 +++++++++++++ .../proj.android/jni/Android.mk | 13 ++++++ 8 files changed, 200 insertions(+), 37 deletions(-) create mode 100644 cocos/scripting/javascript/bindings/chipmunk/Android.mk create mode 100644 cocos/scripting/javascript/bindings/cocosbuilder/Android.mk create mode 100644 cocos/scripting/javascript/bindings/cocostudio/Android.mk create mode 100644 cocos/scripting/javascript/bindings/extension/Android.mk create mode 100644 cocos/scripting/javascript/bindings/localstorage/Android.mk create mode 100644 cocos/scripting/javascript/bindings/network/Android.mk diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 5689684060..8195fde121 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -8,65 +8,34 @@ LOCAL_MODULE_FILENAME := libcocos2dxjsb LOCAL_SRC_FILES := ScriptingCore.cpp \ cocos2d_specifics.cpp \ - jsb_cocos2dx_extension_manual.cpp \ js_manual_conversions.cpp \ cocosjs_manual_conversions.cpp \ - js_bindings_chipmunk_manual.cpp \ - js_bindings_chipmunk_functions.cpp \ - js_bindings_chipmunk_auto_classes.cpp \ - js_bindings_chipmunk_registration.cpp \ - js_bindings_system_functions.cpp \ - js_bindings_system_registration.cpp \ - js_bindings_ccbreader.cpp \ js_bindings_core.cpp \ js_bindings_opengl.cpp \ jsb_opengl_functions.cpp \ jsb_opengl_manual.cpp \ jsb_opengl_registration.cpp \ - ../../auto-generated/js-bindings/jsb_cocos2dx_auto.cpp \ - ../../auto-generated/js-bindings/jsb_cocos2dx_extension_auto.cpp \ - XMLHTTPRequest.cpp \ - jsb_websocket.cpp + ../../auto-generated/js-bindings/jsb_cocos2dx_auto.cpp LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT LOCAL_C_INCLUDES := $(LOCAL_PATH) \ - $(LOCAL_PATH)/../../../CocosDenshion/include \ + $(LOCAL_PATH)/../../../audio/include \ + $(LOCAL_PATH)/../../../storage \ $(LOCAL_PATH)/../../auto-generated/js-bindings \ - $(LOCAL_PATH)/../../../../extensions \ - $(LOCAL_PATH)/../../../editor-support/cocostudio \ - $(LOCAL_PATH)/../../../editor-support/cocosbuilder + $(LOCAL_PATH)/../../../../extensions LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ - $(LOCAL_PATH)/../../auto-generated/js-bindings + $(LOCAL_PATH)/../../auto-generated/js-bindings \ + $(LOCAL_PATH)/../../../audio/include LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static -LOCAL_WHOLE_STATIC_LIBRARIES += spine_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocos_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static -LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static - -LOCAL_LDLIBS := -landroid -LOCAL_LDLIBS += -llog include $(BUILD_STATIC_LIBRARY) $(call import-module,spidermonkey/prebuilt/android) -$(call import-module,extensions) $(call import-module,2d) -$(call import-module,extensions) -$(call import-module,editor-support/cocosbuilder) -$(call import-module,editor-support/spine) -$(call import-module,network) -$(call import-module,chipmunk) -$(call import-module,storage/local-storage) -$(call import-module,editor-support/cocostudio) -$(call import-module,websockets/prebuilt/android) diff --git a/cocos/scripting/javascript/bindings/chipmunk/Android.mk b/cocos/scripting/javascript/bindings/chipmunk/Android.mk new file mode 100644 index 0000000000..ae7b615b57 --- /dev/null +++ b/cocos/scripting/javascript/bindings/chipmunk/Android.mk @@ -0,0 +1,33 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_chipmunk_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsbchipmunk + +LOCAL_SRC_FILES := js_bindings_chipmunk_manual.cpp \ + js_bindings_chipmunk_functions.cpp \ + js_bindings_chipmunk_auto_classes.cpp \ + js_bindings_chipmunk_registration.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../.. + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,extensions) +$(call import-module,chipmunk) diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/Android.mk b/cocos/scripting/javascript/bindings/cocosbuilder/Android.mk new file mode 100644 index 0000000000..be5e73de8f --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocosbuilder/Android.mk @@ -0,0 +1,29 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_builder_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsbbuilder + +LOCAL_SRC_FILES := js_bindings_ccbreader.cpp \ + ../../../auto-generated/js-bindings/jsb_cocos2dx_builder_auto.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../editor-support/cocosbuilder + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,editor-support/cocosbuilder) diff --git a/cocos/scripting/javascript/bindings/cocostudio/Android.mk b/cocos/scripting/javascript/bindings/cocostudio/Android.mk new file mode 100644 index 0000000000..ca0eb1939f --- /dev/null +++ b/cocos/scripting/javascript/bindings/cocostudio/Android.mk @@ -0,0 +1,30 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_studio_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsbstudio + +LOCAL_SRC_FILES := jsb_cocos2dx_studio_manual.cpp \ + ../../../auto-generated/js-bindings/jsb_cocos2dx_studio_auto.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../../extensions \ + $(LOCAL_PATH)/../../../../editor-support/cocostudio + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,editor-support/cocostudio) diff --git a/cocos/scripting/javascript/bindings/extension/Android.mk b/cocos/scripting/javascript/bindings/extension/Android.mk new file mode 100644 index 0000000000..871a5c1cf5 --- /dev/null +++ b/cocos/scripting/javascript/bindings/extension/Android.mk @@ -0,0 +1,30 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_extension_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsbextension + +LOCAL_SRC_FILES := jsb_cocos2dx_extension_manual.cpp \ + ../../../auto-generated/js-bindings/jsb_cocos2dx_extension_auto.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../../extensions + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../../ + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,extensions) diff --git a/cocos/scripting/javascript/bindings/localstorage/Android.mk b/cocos/scripting/javascript/bindings/localstorage/Android.mk new file mode 100644 index 0000000000..e13104f94c --- /dev/null +++ b/cocos/scripting/javascript/bindings/localstorage/Android.mk @@ -0,0 +1,29 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_localstorage_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsblocalstorage + +LOCAL_SRC_FILES := js_bindings_system_functions.cpp \ + js_bindings_system_registration.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) \ + $(LOCAL_PATH)/../../../../../extensions + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_localstorage_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,storage/local-storage) diff --git a/cocos/scripting/javascript/bindings/network/Android.mk b/cocos/scripting/javascript/bindings/network/Android.mk new file mode 100644 index 0000000000..6f5c59aa96 --- /dev/null +++ b/cocos/scripting/javascript/bindings/network/Android.mk @@ -0,0 +1,30 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := jsb_network_static + +LOCAL_MODULE_FILENAME := libcocos2dxjsbnetwork + +LOCAL_SRC_FILES := XMLHTTPRequest.cpp \ + jsb_websocket.cpp + +LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT + +LOCAL_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) + +LOCAL_WHOLE_STATIC_LIBRARIES := spidermonkey_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static + +include $(BUILD_STATIC_LIBRARY) + +$(call import-module,spidermonkey/prebuilt/android) +$(call import-module,scripting/javascript/bindings) +$(call import-module,network) +$(call import-module,websockets/prebuilt/android) diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk index 89d17346d0..0a9f023dc3 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Android.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Android.mk @@ -12,9 +12,22 @@ LOCAL_SRC_FILES := testjavascript/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_studio_static + LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 include $(BUILD_SHARED_LIBRARY) $(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) +$(call import-module,scripting/javascript/bindings/cocostudio) From 342003f7b244d68b8ae9a5419a8290fb96b95de3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 18:03:15 +0800 Subject: [PATCH 214/557] Update AUTHORS --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 4dff8c12b5..9357213fb6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -627,6 +627,9 @@ Developers: Fixed a bug that CCBReader can't play sequence automatically in JSB. Could not set next animation in CCBAnimationCompleted callback. + lite3 + Fixed a bug that Node's anchor point was changed after being added to ScrollView. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From f2584f973007259760a5135feed1e9267e7d16c0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 18:04:13 +0800 Subject: [PATCH 215/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 7b81c3c5f9..567b572bc1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -8,6 +8,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Avoid unnecessary object duplication for Scale9Sprite. [FIX] create_project.py does not rename/replace template projects completely. [FIX] Could not set next animation in CCBAnimationCompleted callback. + [FIX] The Node's anchor point was changed after being added to ScrollView. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 56ef19714642b4a74b227d1f20b2a034613c19bd Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 24 Oct 2013 18:36:36 +0800 Subject: [PATCH 216/557] update the reference to cocos2d-x repo. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 893da8ccfb..2f3c531665 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 893da8ccfb4ed7fa754c483a90dc4e5248c36e03 +Subproject commit 2f3c5316657e64ec38b8ed3ea6826eb48c46f32c From fdcf0196659fd97de2d58643fbb77b937ab32204 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 25 Oct 2013 10:31:22 +0800 Subject: [PATCH 217/557] issue #2771: implement contact callbacks --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.cpp | 103 ++++++++++++++++++++--------- cocos/physics/CCPhysicsContact.h | 56 +++++++++++++--- cocos/physics/CCPhysicsJoint.cpp | 8 +-- cocos/physics/CCPhysicsSetting.h | 5 ++ cocos/physics/CCPhysicsShape.cpp | 4 +- cocos/physics/CCPhysicsWorld.cpp | 42 +++++++++--- cocos/physics/CCPhysicsWorld.h | 6 +- 8 files changed, 164 insertions(+), 62 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f1715b0f1a..ad3ea332fa 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -142,7 +142,7 @@ public: /* * @brief get all joints the body have */ - inline const std::vector* getJoints() const { return &_joints; } + inline const std::vector& getJoints() const { return _joints; } /* * @brief get the sprite the body set to. diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 1ec9667d6f..71ed2beb01 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -32,6 +32,8 @@ #include "chipmunk/CCPhysicsContactInfo.h" #include "box2d/CCPhysicsContactInfo.h" +#include "chipmunk/CCPhysicsHelper.h" +#include "box2d/CCPhysicsHelper.h" NS_CC_BEGIN @@ -39,7 +41,11 @@ PhysicsContact::PhysicsContact() : _shapeA(nullptr) , _shapeB(nullptr) , _info(nullptr) +, _notify(true) +, _begin(false) , _data(nullptr) +, _contactInfo(nullptr) +, _contactData(nullptr) { } @@ -47,6 +53,7 @@ PhysicsContact::PhysicsContact() PhysicsContact::~PhysicsContact() { CC_SAFE_DELETE(_info); + CC_SAFE_DELETE(_contactData); } PhysicsContact* PhysicsContact::create(PhysicsShape* a, PhysicsShape* b) @@ -78,37 +85,69 @@ bool PhysicsContact::init(PhysicsShape* a, PhysicsShape* b) return false; } -// PhysicsContactPreSolve implementation -PhysicsContactPreSolve::PhysicsContactPreSolve() +void PhysicsContact::generateContactData() { + if (_contactInfo == nullptr) + { + return; + } + cpArbiter* arb = (cpArbiter*)_contactInfo; + _contactData = new PhysicsContactData(); + _contactData->count = cpArbiterGetCount(arb); + for (int i=0; i<_contactData->count; ++i) + { + _contactData->points[i] = PhysicsHelper::cpv2point(cpArbiterGetPoint(arb, i)); + } + + _contactData->normal = _contactData->count > 0 ? PhysicsHelper::cpv2point(cpArbiterGetNormal(arb, 0)) : Point::ZERO; +} + +// PhysicsContactPreSolve implementation +PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo) +: _preContactData(data) +, _contactInfo(contactInfo) +{ +} + +float PhysicsContactPreSolve::getElasticity() +{ + return ((cpArbiter*)_contactInfo)->e; +} + +float PhysicsContactPreSolve::getFriciton() +{ + return ((cpArbiter*)_contactInfo)->u; +} + +Point PhysicsContactPreSolve::getSurfaceVelocity() +{ + return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); +} + +void PhysicsContactPreSolve::setElasticity(float elasticity) +{ + ((cpArbiter*)_contactInfo)->e = elasticity; +} + +void PhysicsContactPreSolve::setFriction(float friction) +{ + ((cpArbiter*)_contactInfo)->u = friction; +} + +void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) +{ + ((cpArbiter*)_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } PhysicsContactPreSolve::~PhysicsContactPreSolve() { - + CC_SAFE_DELETE(_preContactData); } -PhysicsContactPreSolve* PhysicsContactPreSolve::create() -{ - PhysicsContactPreSolve * solve = new PhysicsContactPreSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; -} - -bool PhysicsContactPreSolve::init() -{ - return true; -} - - // PhysicsContactPostSolve implementation -PhysicsContactPostSolve::PhysicsContactPostSolve() +PhysicsContactPostSolve::PhysicsContactPostSolve(void* contactInfo) +: _contactInfo(contactInfo) { } @@ -118,21 +157,19 @@ PhysicsContactPostSolve::~PhysicsContactPostSolve() } -PhysicsContactPostSolve* PhysicsContactPostSolve::create() +float PhysicsContactPostSolve::getElasticity() { - PhysicsContactPostSolve * solve = new PhysicsContactPostSolve(); - if(solve && solve->init()) - { - return solve; - } - - CC_SAFE_DELETE(solve); - return nullptr; + return ((cpArbiter*)_contactInfo)->e; } -bool PhysicsContactPostSolve::init() +float PhysicsContactPostSolve::getFriciton() { - return true; + return ((cpArbiter*)_contactInfo)->u; +} + +Point PhysicsContactPostSolve::getSurfaceVelocity() +{ + return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); } PhysicsContactListener::PhysicsContactListener() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 9b9e3044c0..6c96539c92 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -38,6 +38,18 @@ class PhysicsWorld; class PhysicsContactInfo; + +typedef struct PhysicsContactData +{ + Point points[PHYSICS_CONTACT_POINT_MAX]; + int count; + Point normal; + + PhysicsContactData() + : count(0) + {} +}PhysicsContactData; + /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ @@ -52,6 +64,7 @@ public: * @brief get contact shape B. */ inline PhysicsShape* getShapeB() const { return _shapeB; } + inline const PhysicsContactData* getContactData() const { return _contactData; } /* * @brief get data. */ @@ -68,6 +81,8 @@ private: inline bool getNotify() { return _notify; } inline void setNotify(bool notify) { _notify = notify; } + void generateContactData(); + private: PhysicsContact(); ~PhysicsContact(); @@ -76,8 +91,12 @@ private: PhysicsShape* _shapeA; PhysicsShape* _shapeB; PhysicsContactInfo* _info; - void* _data; bool _notify; + bool _begin; + + void* _data; + void* _contactInfo; + PhysicsContactData* _contactData; friend class PhysicsWorld; friend class PhysicsWorldCallback; @@ -88,14 +107,27 @@ private: */ class PhysicsContactPreSolve { +public: + // getter/setter + float getElasticity(); + float getFriciton(); + Point getSurfaceVelocity(); + void setElasticity(float elasticity); + void setFriction(float friction); + void setSurfaceVelocity(Point surfaceVelocity); + private: - PhysicsContactPreSolve(); + PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo); ~PhysicsContactPreSolve(); - static PhysicsContactPreSolve* create(); - bool init(); +private: + float _elasticity; + float _friction; + Point _surfaceVelocity; + PhysicsContactData* _preContactData; + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* @@ -103,14 +135,20 @@ private: */ class PhysicsContactPostSolve { +public: + // getter + float getElasticity(); + float getFriciton(); + Point getSurfaceVelocity(); + private: - PhysicsContactPostSolve(); + PhysicsContactPostSolve(void* contactInfo); ~PhysicsContactPostSolve(); - static PhysicsContactPostSolve* create(); - bool init(); +private: + void* _contactInfo; - friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 6cca90dd5b..5e475bf367 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -161,10 +161,10 @@ void PhysicsJoint::setCollisionEnable(bool enable) { _collisionEnable = enable; - for (auto shape : _bodyB->_shapes) - { - shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); - } +// for (auto shape : _bodyB->_shapes) +// { +// shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); +// } } } diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index b29b12054d..ee3214bcd7 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -46,6 +46,11 @@ namespace cocos2d { extern const float PHYSICS_INFINITY; + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + static const int PHYSICS_CONTACT_POINT_MAX = 4; +#else +#endif } #endif // __CCPHYSICS_SETTING_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 6ffd7d86aa..77634e9113 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -272,12 +272,12 @@ void PhysicsShape::setBody(PhysicsBody *body) if (body == nullptr) { _info->setBody(nullptr); - _info->setGroup(CP_NO_GROUP); + //_info->setGroup(CP_NO_GROUP); _body = nullptr; }else { _info->setBody(body->_info->body); - _info->setGroup(body->_info->group); + //_info->setGroup(body->_info->group); _body = body; } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 9085805e1d..451c7b82a2 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -60,6 +60,8 @@ NS_CC_BEGIN #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +const float PHYSICS_INFINITY = INFINITY; + namespace { typedef struct RayCastCallbackInfo @@ -96,8 +98,6 @@ public: bool PhysicsWorldCallback::continues = true; -const float PHYSICS_INFINITY = INFINITY; - int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world) { CP_ARBITER_GET_SHAPES(arb, a, b); @@ -108,20 +108,19 @@ int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSp PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); arb->data = contact; + contact->_contactInfo = arb; - return world->collisionBeginCallback(*static_cast(arb->data)); + return world->collisionBeginCallback(*contact); } int PhysicsWorldCallback::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - return world->collisionPreSolveCallback(*static_cast(arb->data), - PhysicsContactPreSolve()); + return world->collisionPreSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) { - world->collisionPostSolveCallback(*static_cast(arb->data), - PhysicsContactPostSolve()); + world->collisionPostSolveCallback(*static_cast(arb->data)); } void PhysicsWorldCallback::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world) @@ -445,7 +444,24 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) bool ret = true; PhysicsBody* bodyA = contact.getShapeA()->getBody(); PhysicsBody* bodyB = contact.getShapeB()->getBody(); + std::vector jointsA = bodyA->getJoints(); + // check the joint is collision enable or not + for (PhysicsJoint* joint : jointsA) + { + if (!joint->isCollisionEnable()) + { + PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; + + if (body == bodyB) + { + contact.setNotify(false); + return false; + } + } + } + + // bitmask check if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) { @@ -460,6 +476,9 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (contact.getNotify() && _listener && _listener->onContactBegin) { + contact._begin = true; + contact.generateContactData(); + // the mask has high priority than _listener->onContactBegin. // so if the mask test is false, the two bodies won't have collision. if (ret) @@ -474,7 +493,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) return ret; } -int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) +int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { @@ -483,13 +502,17 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const Physi if (_listener && _listener->onContactPreSolve) { + PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); + contact._begin = false; + contact.generateContactData(); + return _listener->onContactPreSolve(*this, contact, solve); } return true; } -void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) +void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { @@ -498,6 +521,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const Phy if (_listener && _listener->onContactPreSolve) { + PhysicsContactPostSolve solve(contact._contactInfo); _listener->onContactPostSolve(*this, contact, solve); } } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 63c841cc93..34528d6270 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -40,8 +40,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class PhysicsContactPreSolve; -class PhysicsContactPostSolve; class PhysicsContactListener; class Array; @@ -135,8 +133,8 @@ protected: virtual int collisionBeginCallback(PhysicsContact& contact); - virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); + virtual int collisionPreSolveCallback(PhysicsContact& contact); + virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); protected: From b4eb97058905e1790fdf5313159f53d61aa9a228 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 10:50:03 +0800 Subject: [PATCH 218/557] [JSB] Fixing compilation errors for iOS and Mac projects. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 18265b616b..17e0cee1da 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1c487d29bdc2d80516e86e2ee93b1664e9f7df2f \ No newline at end of file +b695026fc3d856d540590ff09112696f66379c22 \ No newline at end of file From 779e539658687b7ab81a70802a8c65bc6227633e Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 12 Oct 2013 11:25:28 +0800 Subject: [PATCH 219/557] Remove event controller codes from Layer class. HelloCpp works. --- cocos/2d/CCEventDispatcher.cpp | 51 +--- cocos/2d/CCEventListener.cpp | 2 +- cocos/2d/CCEventListener.h | 2 +- cocos/2d/CCEventListenerAcceleration.cpp | 2 +- cocos/2d/CCEventListenerAcceleration.h | 2 +- cocos/2d/CCEventListenerCustom.cpp | 4 +- cocos/2d/CCEventListenerCustom.h | 2 +- cocos/2d/CCEventListenerKeyboard.cpp | 2 +- cocos/2d/CCEventListenerKeyboard.h | 2 +- cocos/2d/CCEventListenerTouch.cpp | 131 +++++--- cocos/2d/CCEventListenerTouch.h | 52 +++- cocos/2d/CCEventTouch.cpp | 3 + cocos/2d/CCEventTouch.h | 5 + cocos/2d/CCLayer.cpp | 365 ----------------------- cocos/2d/CCLayer.h | 76 ----- cocos/2d/CCMenu.cpp | 14 +- cocos/2d/CCMenu.h | 8 +- 17 files changed, 166 insertions(+), 557 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 14be190f68..0e596b788a 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -125,7 +125,7 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list CCASSERT(listener && node, "Invalid parameters."); CCASSERT(!listener->_isRegistered, "The listener has been registered."); - if (!listener->checkAvaiable()) + if (!listener->checkAvailable()) return; auto item = new EventListenerItem(); @@ -147,7 +147,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, CCASSERT(!listener->_isRegistered, "The listener has been registered."); CCASSERT(fixedPriority != 0, "0 priority is forbidden for fixed priority since it's used for scene graph based priority."); - if (!listener->checkAvaiable()) + if (!listener->checkAvailable()) return; auto item = new EventListenerItem(); @@ -294,37 +294,14 @@ void EventDispatcher::dispatchEvent(Event* event, bool forceSortListeners) void EventDispatcher::dispatchTouchEvent(EventTouch* event) { - auto touchListeners = getListenerItemsForType(EventTouch::EVENT_TYPE); - if (touchListeners == nullptr) + auto oneByOnelisteners = getListenerItemsForType(EventTouch::MODE_ONE_BY_ONE); + auto allAtOncelisteners = getListenerItemsForType(EventTouch::MODE_ALL_AT_ONCE); + + // If there aren't any touch listeners, return directly. + if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) return; - std::vector oneByOnelisteners; - oneByOnelisteners.reserve(touchListeners->size()); - - std::vector allInOnelisteners; - allInOnelisteners.reserve(touchListeners->size()); - - EventListenerTouch* touchEventListener = nullptr; - - std::for_each(touchListeners->begin(), touchListeners->end(), [&](EventListenerItem*& item){ - - touchEventListener = static_cast(item->listener); - - if (touchEventListener->_dispatchMode == Touch::DispatchMode::ONE_BY_ONE) - { - oneByOnelisteners.push_back(item); - } - else if (touchEventListener->_dispatchMode == Touch::DispatchMode::ALL_AT_ONCE) - { - allInOnelisteners.push_back(item); - } - else - { - CCASSERT(false, "Not supported touch listener type."); - } - }); - - bool isNeedsMutableSet = (oneByOnelisteners.size() > 0 && allInOnelisteners.size() > 0); + bool isNeedsMutableSet = (oneByOnelisteners && allAtOncelisteners); std::vector orignalTouches = event->getTouches(); std::vector mutableTouches(orignalTouches.size()); @@ -333,7 +310,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // // process the target handlers 1st // - if (oneByOnelisteners.size() > 0) + if (oneByOnelisteners) { auto mutableTouchesIter = mutableTouches.begin(); auto touchesIter = orignalTouches.begin(); @@ -342,7 +319,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) { bool isSwallowed = false; - for (auto& item : oneByOnelisteners) + for (auto& item : *oneByOnelisteners) { // Skip if the listener was removed. if (item->listener == nullptr) @@ -353,7 +330,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) bool isClaimed = false; std::vector::iterator removedIter; - auto touchEventListener = static_cast(item->listener); + auto touchEventListener = static_cast(item->listener); EventTouch::EventCode eventCode = event->getEventCode(); if (eventCode == EventTouch::EventCode::BEGAN) @@ -434,9 +411,9 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // // process standard handlers 2nd // - if (allInOnelisteners.size() > 0 && mutableTouches.size() > 0) + if (allAtOncelisteners && mutableTouches.size() > 0) { - for (auto& item : allInOnelisteners) + for (auto& item : *allAtOncelisteners) { // Skip if the listener was removed. if (item->listener == nullptr) @@ -444,7 +421,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) event->setCurrentTarget(item->node); - auto touchEventListener = static_cast(item->listener); + auto touchEventListener = static_cast(item->listener); switch (event->getEventCode()) { diff --git a/cocos/2d/CCEventListener.cpp b/cocos/2d/CCEventListener.cpp index ce3c787883..451be9a8c8 100644 --- a/cocos/2d/CCEventListener.cpp +++ b/cocos/2d/CCEventListener.cpp @@ -44,7 +44,7 @@ bool EventListener::init(const std::string& t, std::function callb return true; } -bool EventListener::checkAvaiable() +bool EventListener::checkAvailable() { return (_onEvent != nullptr); } diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index 82c47445e0..559cf21739 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -54,7 +54,7 @@ public: virtual ~EventListener(); /** Checks whether the listener is available. */ - virtual bool checkAvaiable() = 0; + virtual bool checkAvailable() = 0; /** Clones the listener, its subclasses have to override this method. */ virtual EventListener* clone() = 0; diff --git a/cocos/2d/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp index e7e1f6055b..d8b01fc4ce 100644 --- a/cocos/2d/CCEventListenerAcceleration.cpp +++ b/cocos/2d/CCEventListenerAcceleration.cpp @@ -84,7 +84,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone() return ret; } -bool EventListenerAcceleration::checkAvaiable() +bool EventListenerAcceleration::checkAvailable() { CCASSERT(onAccelerationEvent, ""); diff --git a/cocos/2d/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h index 1fb9536be7..2905df9486 100644 --- a/cocos/2d/CCEventListenerAcceleration.h +++ b/cocos/2d/CCEventListenerAcceleration.h @@ -38,7 +38,7 @@ public: /// Overrides virtual EventListenerAcceleration* clone() override; - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; private: EventListenerAcceleration(); diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index 7be79b9dcb..abe4153198 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -80,10 +80,10 @@ EventListenerCustom* EventListenerCustom::clone() return ret; } -bool EventListenerCustom::checkAvaiable() +bool EventListenerCustom::checkAvailable() { bool ret = false; - if (EventListener::checkAvaiable() && _onCustomEvent != nullptr) + if (EventListener::checkAvailable() && _onCustomEvent != nullptr) { ret = true; } diff --git a/cocos/2d/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h index 190ed63f95..a823d4a4ba 100644 --- a/cocos/2d/CCEventListenerCustom.h +++ b/cocos/2d/CCEventListenerCustom.h @@ -59,7 +59,7 @@ public: static EventListenerCustom* create(const std::string& eventName, std::function callback); /// Overrides - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; virtual EventListenerCustom* clone() override; protected: diff --git a/cocos/2d/CCEventListenerKeyboard.cpp b/cocos/2d/CCEventListenerKeyboard.cpp index 80709f8cef..a6e3b617ae 100644 --- a/cocos/2d/CCEventListenerKeyboard.cpp +++ b/cocos/2d/CCEventListenerKeyboard.cpp @@ -29,7 +29,7 @@ NS_CC_BEGIN -bool EventListenerKeyboard::checkAvaiable() +bool EventListenerKeyboard::checkAvailable() { CCASSERT(onKeyPressed && onKeyReleased, ""); diff --git a/cocos/2d/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h index f7b4c288d9..dd223da533 100644 --- a/cocos/2d/CCEventListenerKeyboard.h +++ b/cocos/2d/CCEventListenerKeyboard.h @@ -40,7 +40,7 @@ public: /// Overrides virtual EventListenerKeyboard* clone() override; - virtual bool checkAvaiable() override; + virtual bool checkAvailable() override; std::function onKeyPressed; std::function onKeyReleased; diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index ec418c2949..49ec1462c9 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -30,46 +30,39 @@ NS_CC_BEGIN -EventListenerTouch::EventListenerTouch() +EventListenerTouchOneByOne::EventListenerTouchOneByOne() : onTouchBegan(nullptr) , onTouchMoved(nullptr) , onTouchEnded(nullptr) , onTouchCancelled(nullptr) -, onTouchesBegan(nullptr) -, onTouchesMoved(nullptr) -, onTouchesEnded(nullptr) -, onTouchesCancelled(nullptr) , _needSwallow(false) -, _dispatchMode(Touch::DispatchMode::ALL_AT_ONCE) { } -EventListenerTouch::~EventListenerTouch() +EventListenerTouchOneByOne::~EventListenerTouchOneByOne() { - CCLOGINFO("In the destructor of TouchEventListener, %p", this); + CCLOGINFO("In the destructor of EventListenerTouchOneByOne, %p", this); } -bool EventListenerTouch::init(Touch::DispatchMode mode) +bool EventListenerTouchOneByOne::init() { - if (EventListener::init(EventTouch::EVENT_TYPE, nullptr)) + if (EventListener::init(EventTouch::MODE_ONE_BY_ONE, nullptr)) { - _dispatchMode = mode; return true; } return false; } -void EventListenerTouch::setSwallowTouches(bool needSwallow) +void EventListenerTouchOneByOne::setSwallowTouches(bool needSwallow) { - CCASSERT(_dispatchMode == Touch::DispatchMode::ONE_BY_ONE, "Swallow touches only available in OneByOne mode."); _needSwallow = needSwallow; } -EventListenerTouch* EventListenerTouch::create(Touch::DispatchMode mode) +EventListenerTouchOneByOne* EventListenerTouchOneByOne::create() { - auto ret = new EventListenerTouch(); - if (ret && ret->init(mode)) + auto ret = new EventListenerTouchOneByOne(); + if (ret && ret->init()) { ret->autorelease(); } @@ -80,38 +73,22 @@ EventListenerTouch* EventListenerTouch::create(Touch::DispatchMode mode) return ret; } -bool EventListenerTouch::checkAvaiable() +bool EventListenerTouchOneByOne::checkAvailable() { - if (_dispatchMode == Touch::DispatchMode::ALL_AT_ONCE) + if (onTouchBegan == nullptr && onTouchMoved == nullptr + && onTouchEnded == nullptr && onTouchCancelled == nullptr) { - if (onTouchesBegan == nullptr && onTouchesMoved == nullptr - && onTouchesEnded == nullptr && onTouchesCancelled == nullptr) - { - CCASSERT(false, "Invalid TouchEventListener."); - return false; - } - } - else if (_dispatchMode == Touch::DispatchMode::ONE_BY_ONE) - { - if (onTouchBegan == nullptr && onTouchMoved == nullptr - && onTouchEnded == nullptr && onTouchCancelled == nullptr) - { - CCASSERT(false, "Invalid TouchEventListener."); - return false; - } - } - else - { - CCASSERT(false, ""); + CCASSERT(false, "Invalid TouchEventListener."); + return false; } return true; } -EventListenerTouch* EventListenerTouch::clone() +EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone() { - auto ret = new EventListenerTouch(); - if (ret && ret->init(_dispatchMode)) + auto ret = new EventListenerTouchOneByOne(); + if (ret && ret->init()) { ret->autorelease(); @@ -119,13 +96,8 @@ EventListenerTouch* EventListenerTouch::clone() ret->onTouchMoved = onTouchMoved; ret->onTouchEnded = onTouchEnded; ret->onTouchCancelled = onTouchCancelled; - ret->onTouchesBegan = onTouchesBegan; - ret->onTouchesMoved = onTouchesMoved; - ret->onTouchesEnded = onTouchesEnded; - ret->onTouchesCancelled = onTouchesCancelled; ret->_claimedTouches = _claimedTouches; - ret->_dispatchMode = _dispatchMode; ret->_needSwallow = _needSwallow; } else @@ -135,4 +107,73 @@ EventListenerTouch* EventListenerTouch::clone() return ret; } +///////// +EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce() +: onTouchesBegan(nullptr) +, onTouchesMoved(nullptr) +, onTouchesEnded(nullptr) +, onTouchesCancelled(nullptr) +{ +} + +EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce() +{ + CCLOGINFO("In the destructor of EventListenerTouchAllAtOnce, %p", this); +} + +bool EventListenerTouchAllAtOnce::init() +{ + if (EventListener::init(EventTouch::MODE_ALL_AT_ONCE, nullptr)) + { + return true; + } + + return false; +} + +EventListenerTouchAllAtOnce* EventListenerTouchAllAtOnce::create() +{ + auto ret = new EventListenerTouchAllAtOnce(); + if (ret && ret->init()) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +bool EventListenerTouchAllAtOnce::checkAvailable() +{ + if (onTouchesBegan == nullptr && onTouchesMoved == nullptr + && onTouchesEnded == nullptr && onTouchesCancelled == nullptr) + { + CCASSERT(false, "Invalid TouchEventListener."); + return false; + } + + return true; +} + +EventListenerTouchAllAtOnce* EventListenerTouchAllAtOnce::clone() +{ + auto ret = new EventListenerTouchAllAtOnce(); + if (ret && ret->init()) + { + ret->autorelease(); + + ret->onTouchesBegan = onTouchesBegan; + ret->onTouchesMoved = onTouchesMoved; + ret->onTouchesEnded = onTouchesEnded; + ret->onTouchesCancelled = onTouchesCancelled; + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 3002676bda..d34de1b237 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -33,38 +33,58 @@ NS_CC_BEGIN -class EventListenerTouch : public EventListener + +class EventListenerTouchOneByOne : public EventListener { public: - static EventListenerTouch* create(Touch::DispatchMode mode); + static EventListenerTouchOneByOne* create(); + + virtual ~EventListenerTouchOneByOne(); + + void setSwallowTouches(bool needSwallow); /// Overrides - virtual EventListenerTouch* clone() override; - virtual bool checkAvaiable() override; - - virtual ~EventListenerTouch(); - -private: - EventListenerTouch(); - bool init(Touch::DispatchMode mode); - + virtual EventListenerTouchOneByOne* clone() override; + virtual bool checkAvailable() override; + // + public: std::function onTouchBegan; std::function onTouchMoved; std::function onTouchEnded; std::function onTouchCancelled; +private: + EventListenerTouchOneByOne(); + bool init(); + + std::vector _claimedTouches; + bool _needSwallow; + + friend class EventDispatcher; +}; + + +class EventListenerTouchAllAtOnce : public EventListener +{ +public: + static EventListenerTouchAllAtOnce* create(); + virtual ~EventListenerTouchAllAtOnce(); + + /// Overrides + virtual EventListenerTouchAllAtOnce* clone() override; + virtual bool checkAvailable() override; + // +public: std::function&, Event*)> onTouchesBegan; std::function&, Event*)> onTouchesMoved; std::function&, Event*)> onTouchesEnded; std::function&, Event*)> onTouchesCancelled; - void setSwallowTouches(bool needSwallow); - private: - std::vector _claimedTouches; - bool _needSwallow; - Touch::DispatchMode _dispatchMode; + EventListenerTouchAllAtOnce(); + bool init(); +private: friend class EventDispatcher; }; diff --git a/cocos/2d/CCEventTouch.cpp b/cocos/2d/CCEventTouch.cpp index dbb0963775..987d87d0e9 100644 --- a/cocos/2d/CCEventTouch.cpp +++ b/cocos/2d/CCEventTouch.cpp @@ -26,6 +26,9 @@ NS_CC_BEGIN +const char* EventTouch::MODE_ONE_BY_ONE = "TouchEventOneByOne"; +const char* EventTouch::MODE_ALL_AT_ONCE = "TouchEventAllAtOnce"; + const char* EventTouch::EVENT_TYPE = "TouchEvent"; NS_CC_END diff --git a/cocos/2d/CCEventTouch.h b/cocos/2d/CCEventTouch.h index 3d54cecea7..558bfe0593 100644 --- a/cocos/2d/CCEventTouch.h +++ b/cocos/2d/CCEventTouch.h @@ -36,7 +36,12 @@ NS_CC_BEGIN class EventTouch : public Event { public: + static const char* MODE_ONE_BY_ONE; + static const char* MODE_ALL_AT_ONCE; + static const char* EVENT_TYPE; + + static const int MAX_TOUCHES = 5; enum class EventCode diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 19346ea844..717570e6fe 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -48,14 +48,6 @@ NS_CC_BEGIN // Layer Layer::Layer() -: _touchEnabled(false) -, _accelerometerEnabled(false) -, _keyboardEnabled(false) -, _touchMode(Touch::DispatchMode::ALL_AT_ONCE) -, _swallowsTouches(true) -, _touchListener(nullptr) -, _keyboardListener(nullptr) -, _accelerationListener(nullptr) { _ignoreAnchorPointForPosition = true; setAnchorPoint(Point(0.5f, 0.5f)); @@ -74,8 +66,6 @@ bool Layer::init() Director * pDirector; CC_BREAK_IF(!(pDirector = Director::getInstance())); this->setContentSize(pDirector->getWinSize()); - setTouchEnabled(false); - setAccelerometerEnabled(false); // success bRet = true; } while(0); @@ -97,44 +87,6 @@ Layer *Layer::create() } } -/// Touch and Accelerometer related - -void Layer::addTouchListener() -{ - if (_touchListener != nullptr) - return; - - auto dispatcher = EventDispatcher::getInstance(); - - if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE ) - { - // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ALL_AT_ONCE); - - listener->onTouchesBegan = CC_CALLBACK_2(Layer::onTouchesBegan, this); - listener->onTouchesMoved = CC_CALLBACK_2(Layer::onTouchesMoved, this); - listener->onTouchesEnded = CC_CALLBACK_2(Layer::onTouchesEnded, this); - listener->onTouchesCancelled = CC_CALLBACK_2(Layer::onTouchesCancelled, this); - - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - _touchListener = listener; - } - else - { - // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); - listener->setSwallowTouches(_swallowsTouches); - - listener->onTouchBegan = CC_CALLBACK_2(Layer::onTouchBegan, this); - listener->onTouchMoved = CC_CALLBACK_2(Layer::onTouchMoved, this); - listener->onTouchEnded = CC_CALLBACK_2(Layer::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(Layer::onTouchCancelled, this); - - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - _touchListener = listener; - } -} - int Layer::executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch) { if (kScriptTypeNone != _scriptType) @@ -160,323 +112,6 @@ int Layer::executeScriptTouchesHandler(EventTouch::EventCode eventType, const st return 0; } -/// isTouchEnabled getter -bool Layer::isTouchEnabled() const -{ - return _touchEnabled; -} - -/// isTouchEnabled setter -void Layer::setTouchEnabled(bool enabled) -{ - if (_touchEnabled != enabled) - { - _touchEnabled = enabled; - if (_running) - { - if (enabled) - { - this->addTouchListener(); - } - else - { - EventDispatcher::getInstance()->removeEventListener(_touchListener); - _touchListener = nullptr; - } - } - } -} - -void Layer::setTouchMode(Touch::DispatchMode mode) -{ - if(_touchMode != mode) - { - _touchMode = mode; - - if( _touchEnabled) - { - setTouchEnabled(false); - setTouchEnabled(true); - } - } -} - -void Layer::setSwallowsTouches(bool swallowsTouches) -{ - if (_swallowsTouches != swallowsTouches) - { - _swallowsTouches = swallowsTouches; - - if( _touchEnabled) - { - setTouchEnabled(false); - setTouchEnabled(true); - } - } -} - -Touch::DispatchMode Layer::getTouchMode() const -{ - return _touchMode; -} - -bool Layer::isSwallowsTouches() const -{ - return _swallowsTouches; -} - - - -/// isAccelerometerEnabled getter -bool Layer::isAccelerometerEnabled() const -{ - return _accelerometerEnabled; -} -/// isAccelerometerEnabled setter -void Layer::setAccelerometerEnabled(bool enabled) -{ - if (enabled != _accelerometerEnabled) - { - _accelerometerEnabled = enabled; - - Device::setAccelerometerEnabled(enabled); - - if (_running) - { - auto dispatcher = EventDispatcher::getInstance(); - dispatcher->removeEventListener(_accelerationListener); - _accelerationListener = nullptr; - - if (enabled) - { - _accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this); - } - } - } -} - - -void Layer::setAccelerometerInterval(double interval) { - if (_accelerometerEnabled) - { - if (_running) - { - Device::setAccelerometerInterval(interval); - } - } -} - - -void Layer::onAcceleration(Acceleration* pAccelerationValue, Event* event) -{ - CC_UNUSED_PARAM(pAccelerationValue); - - if(kScriptTypeNone != _scriptType) - { - BasicScriptData data(this,(void*)pAccelerationValue); - ScriptEvent event(kAccelerometerEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } -} - -void Layer::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) -{ - CC_UNUSED_PARAM(keyCode); - CC_UNUSED_PARAM(event); -} - -void Layer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) -{ - CC_UNUSED_PARAM(event); - if(kScriptTypeNone != _scriptType) - { - KeypadScriptData data(keyCode, this); - ScriptEvent event(kKeypadEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } -} - -/// isKeyboardEnabled getter -bool Layer::isKeyboardEnabled() const -{ - return _keyboardEnabled; -} -/// isKeyboardEnabled setter -void Layer::setKeyboardEnabled(bool enabled) -{ - if (enabled != _keyboardEnabled) - { - _keyboardEnabled = enabled; - - auto dispatcher = EventDispatcher::getInstance(); - dispatcher->removeEventListener(_keyboardListener); - _keyboardListener = nullptr; - - if (enabled) - { - auto listener = EventListenerKeyboard::create(); - listener->onKeyPressed = CC_CALLBACK_2(Layer::onKeyPressed, this); - listener->onKeyReleased = CC_CALLBACK_2(Layer::onKeyReleased, this); - - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - _keyboardListener = listener; - } - } -} - -/// Callbacks -void Layer::onEnter() -{ - // register 'parent' nodes first - // since events are propagated in reverse order - if (_touchEnabled) - { - this->addTouchListener(); - } - - // then iterate over all the children - Node::onEnter(); - - // add this layer to concern the Accelerometer Sensor - if (_accelerometerEnabled) - { - auto dispatcher = EventDispatcher::getInstance(); - dispatcher->removeEventListener(_accelerationListener); - _accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this); - } -} - -void Layer::onExit() -{ - auto dispatcher = EventDispatcher::getInstance(); - - dispatcher->removeEventListener(_touchListener); - _touchListener = nullptr; - - // remove this layer from the delegates who concern Accelerometer Sensor - dispatcher->removeEventListener(_accelerationListener); - _accelerationListener = nullptr; - - // remove this layer from the delegates who concern the keypad msg - dispatcher->removeEventListener(_keyboardListener); - _keyboardListener = nullptr; - - Node::onExit(); -} - -void Layer::onEnterTransitionDidFinish() -{ - if (_accelerometerEnabled) - { - auto dispatcher = EventDispatcher::getInstance(); - dispatcher->removeEventListener(_accelerationListener); - _accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this); - } - - Node::onEnterTransitionDidFinish(); -} - -bool Layer::onTouchBegan(Touch *pTouch, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - return executeScriptTouchHandler(EventTouch::EventCode::BEGAN, pTouch) == 0 ? false : true; - } - - CC_UNUSED_PARAM(pTouch); - CC_UNUSED_PARAM(pEvent); - CCASSERT(false, "Layer#ccTouchBegan override me"); - return true; -} - -void Layer::onTouchMoved(Touch *pTouch, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchHandler(EventTouch::EventCode::MOVED, pTouch); - return; - } - - CC_UNUSED_PARAM(pTouch); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchEnded(Touch *pTouch, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchHandler(EventTouch::EventCode::ENDED, pTouch); - return; - } - - CC_UNUSED_PARAM(pTouch); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchCancelled(Touch *pTouch, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchHandler(EventTouch::EventCode::CANCELLED, pTouch); - return; - } - - CC_UNUSED_PARAM(pTouch); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchesBegan(const std::vector& pTouches, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchesHandler(EventTouch::EventCode::BEGAN, pTouches); - return; - } - - CC_UNUSED_PARAM(pTouches); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchesMoved(const std::vector& pTouches, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchesHandler(EventTouch::EventCode::MOVED, pTouches); - return; - } - - CC_UNUSED_PARAM(pTouches); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchesEnded(const std::vector& pTouches, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchesHandler(EventTouch::EventCode::ENDED, pTouches); - return; - } - - CC_UNUSED_PARAM(pTouches); - CC_UNUSED_PARAM(pEvent); -} - -void Layer::onTouchesCancelled(const std::vector& pTouches, Event *pEvent) -{ - if (kScriptTypeNone != _scriptType) - { - executeScriptTouchesHandler(EventTouch::EventCode::CANCELLED, pTouches); - return; - } - - CC_UNUSED_PARAM(pTouches); - CC_UNUSED_PARAM(pEvent); -} - - #ifdef CC_USE_PHYSICS void Layer::addChild(Node* child) { diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 0dad16ff21..09effe2fcd 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -46,10 +46,6 @@ NS_CC_BEGIN class TouchScriptHandlerEntry; -class EventListenerTouch; -class EventListenerKeyboard; -class EventListenerAcceleration; - // // Layer // @@ -86,22 +82,9 @@ public: CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - // default implements are used to call script callback if exist - virtual bool onTouchBegan(Touch *touch, Event *event); - virtual void onTouchMoved(Touch *touch, Event *event); - virtual void onTouchEnded(Touch *touch, Event *event); - virtual void onTouchCancelled(Touch *touch, Event *event); - -// // default implements are used to call script callback if exist - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); - virtual void onTouchesCancelled(const std::vector&touches, Event *event); /** @deprecated Please override onAcceleration */ CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(Acceleration* accelerationValue) final {}; - - virtual void onAcceleration(Acceleration* acc, Event* event); /** If isTouchEnabled, this method is called onEnter. Override it to change the way Layer receives touch events. @@ -115,48 +98,13 @@ public: */ CC_DEPRECATED_ATTRIBUTE virtual void registerWithTouchDispatcher() final {}; - /** whether or not it will receive Touch events. - You can enable / disable touch events with this property. - Only the touches of this node will be affected. This "method" is not propagated to it's children. - @since v0.8.1 - */ - virtual bool isTouchEnabled() const; - virtual void setTouchEnabled(bool value); - - virtual void setTouchMode(Touch::DispatchMode mode); - virtual Touch::DispatchMode getTouchMode() const; - - /** swallowsTouches of the touch events. Default is true */ - virtual void setSwallowsTouches(bool swallowsTouches); - virtual bool isSwallowsTouches() const; - - /** whether or not it will receive Accelerometer events - You can enable / disable accelerometer events with this property. - @since v0.8.1 - */ - virtual bool isAccelerometerEnabled() const; - virtual void setAccelerometerEnabled(bool value); - virtual void setAccelerometerInterval(double interval); - - /** whether or not it will receive keyboard or keypad events - You can enable / disable accelerometer events with this property. - it's new in cocos2d-x - */ - - virtual bool isKeyboardEnabled() const; - virtual void setKeyboardEnabled(bool value); /** Please use onKeyPressed instead. */ virtual void keyPressed(int keyCode) final {}; /** Please use onKeyReleased instead. */ virtual void keyReleased(int keyCode) final {}; - - virtual void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event); - virtual void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event); - CC_DEPRECATED_ATTRIBUTE virtual bool isKeypadEnabled() const final { return isKeyboardEnabled(); }; - CC_DEPRECATED_ATTRIBUTE virtual void setKeypadEnabled(bool value) { setKeyboardEnabled(value); }; /** @deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead. */ CC_DEPRECATED_ATTRIBUTE virtual void keyBackClicked() final {}; @@ -164,21 +112,6 @@ public: // // Overrides // - /** - * @js NA - * @lua NA - */ - virtual void onEnter() override; - /** - * @js NA - * @lua NA - */ - virtual void onExit() override; - /** - * @js NA - * @lua NA - */ - virtual void onEnterTransitionDidFinish() override; #ifdef CC_USE_PHYSICS virtual void addChild(Node* child) override; @@ -186,15 +119,6 @@ public: virtual void addChild(Node* child, int zOrder, int tag) override; #endif // CC_USE_PHYSICS -protected: - void addTouchListener(); - - bool _touchEnabled; - bool _accelerometerEnabled; - bool _keyboardEnabled; - EventListenerTouch* _touchListener; - EventListenerKeyboard* _keyboardListener; - EventListenerAcceleration* _accelerationListener; private: Touch::DispatchMode _touchMode; bool _swallowsTouches; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index c0c10e9cdb..fc38405355 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -127,9 +127,6 @@ bool Menu::initWithArray(Array* pArrayOfItems) { if (Layer::init()) { - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - setTouchEnabled(true); - _enabled = true; // menu in the center of the screen Size s = Director::getInstance()->getWinSize(); @@ -188,8 +185,15 @@ void Menu::onEnter() { Layer::onEnter(); - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + auto eventDispatcher = EventDispatcher::getInstance(); + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this); + touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this); + + eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); } void Menu::onExit() diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index bd685786c4..a735d138db 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -119,10 +119,10 @@ public: virtual void addChild(Node * child, int zOrder) override; virtual void addChild(Node * child, int zOrder, int tag) override; - virtual bool onTouchBegan(Touch* touch, Event* event) override; - virtual void onTouchEnded(Touch* touch, Event* event) override; - virtual void onTouchCancelled(Touch* touch, Event* event) override; - virtual void onTouchMoved(Touch* touch, Event* event) override; + virtual bool onTouchBegan(Touch* touch, Event* event); + virtual void onTouchEnded(Touch* touch, Event* event); + virtual void onTouchCancelled(Touch* touch, Event* event); + virtual void onTouchMoved(Touch* touch, Event* event); virtual void onEnter() override; virtual void onExit() override; From cfaef2a01ab78140ce8ea67e24055be0e30cec90 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 12 Oct 2013 14:02:01 +0800 Subject: [PATCH 220/557] Adding onEnterHook, onXXXHook for Node. --- cocos/2d/CCNode.cpp | 25 +++++++++++++++ cocos/2d/CCNode.h | 6 +++- .../cocosbuilder/CCLayerLoader.cpp | 4 +-- .../cocostudio/CCInputDelegate.cpp | 4 +-- cocos/gui/UILayer.cpp | 15 ++++++--- .../GUI/CCControlExtension/CCControl.cpp | 15 +++++---- .../CCControlExtension/CCControlButton.cpp | 1 - .../CCControlColourPicker.cpp | 1 - .../CCControlExtension/CCControlHuePicker.cpp | 1 - .../CCControlPotentiometer.cpp | 2 -- .../CCControlSaturationBrightnessPicker.cpp | 1 - .../CCControlExtension/CCControlSlider.cpp | 1 - .../CCControlExtension/CCControlStepper.cpp | 2 -- .../CCControlExtension/CCControlSwitch.cpp | 1 - extensions/GUI/CCScrollView/CCScrollView.cpp | 32 ++++++++++++------- extensions/GUI/CCScrollView/CCScrollView.h | 5 --- .../AccelerometerTest/AccelerometerTest.cpp | 6 ++-- .../AccelerometerTest/AccelerometerTest.h | 2 +- .../Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h | 2 +- .../Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 17 ++++++++-- .../Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp | 9 +++++- .../Cpp/TestCpp/Classes/BugsTest/Bug-914.h | 4 +-- .../Cpp/TestCpp/Classes/BugsTest/BugsTest.h | 4 +-- .../ClickAndMoveTest/ClickAndMoveTest.cpp | 9 ++++-- .../ClickAndMoveTest/ClickAndMoveTest.h | 4 +-- .../ClippingNodeTest/ClippingNodeTest.cpp | 18 +++++++++-- .../ClippingNodeTest/ClippingNodeTest.h | 2 +- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 4 +-- 28 files changed, 133 insertions(+), 64 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 2145829c34..33f9963526 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -136,6 +136,11 @@ Node::Node(void) , _physicsBody(nullptr) #endif { + onEnterHook = nullptr; + onEnterTransitionDidFinishHook = nullptr; + onExitHook = nullptr; + onExitTransitionDidStartHook = nullptr; + // set default scheduler and actionManager Director *director = Director::getInstance(); _actionManager = director->getActionManager(); @@ -945,6 +950,11 @@ void Node::onEnter() ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } + + if (onEnterHook) + { + onEnterHook(); + } } void Node::onEnterTransitionDidFinish() @@ -960,10 +970,20 @@ void Node::onEnterTransitionDidFinish() ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } + + if (onEnterTransitionDidFinishHook) + { + onEnterTransitionDidFinishHook(); + } } void Node::onExitTransitionDidStart() { + if (onExitTransitionDidStartHook) + { + onExitTransitionDidStartHook(); + } + arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*); if (_scriptType != kScriptTypeNone) { @@ -976,6 +996,11 @@ void Node::onExitTransitionDidStart() void Node::onExit() { + if (onExitHook) + { + onExitHook(); + } + this->pauseSchedulerAndActions(); _running = false; diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index ca0529756b..ca0a8eca96 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -928,6 +928,7 @@ public: * @lua NA */ virtual void onEnter(); + std::function onEnterHook; /** Event callback that is invoked when the Node enters in the 'stage'. * If the Node enters the 'stage' with a transition, this event is called when the transition finishes. @@ -936,6 +937,7 @@ public: * @lua NA */ virtual void onEnterTransitionDidFinish(); + std::function onEnterTransitionDidFinishHook; /** * Event callback that is invoked every time the Node leaves the 'stage'. @@ -946,6 +948,7 @@ public: * @lua NA */ virtual void onExit(); + std::function onExitHook; /** * Event callback that is called every time the Node leaves the 'stage'. @@ -954,7 +957,8 @@ public: * @lua NA */ virtual void onExitTransitionDidStart(); - + std::function onExitTransitionDidStartHook; + /// @} end of event callbacks. diff --git a/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp b/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp index f13cf610f6..ebca5a8839 100644 --- a/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLayerLoader.cpp @@ -14,9 +14,9 @@ namespace cocosbuilder { void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_TOUCH_ENABLED) == 0) { - ((Layer *)pNode)->setTouchEnabled(pCheck); +// FIXME: ((Layer *)pNode)->setTouchEnabled(pCheck); } else if(strcmp(pPropertyName, PROPERTY_ACCELEROMETER_ENABLED) == 0) { - ((Layer *)pNode)->setAccelerometerEnabled(pCheck); +// FIXME: ((Layer *)pNode)->setAccelerometerEnabled(pCheck); } else if(strcmp(pPropertyName, PROPERTY_MOUSE_ENABLED) == 0) { // TODO XXX CCLOG("The property '%s' is not supported!", PROPERTY_MOUSE_ENABLED); diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index 9f4fd46a8d..968645bc4e 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -112,7 +112,7 @@ void InputDelegate::setTouchEnabled(bool enabled) { if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE ) { // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ALL_AT_ONCE); + auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(InputDelegate::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(InputDelegate::onTouchesMoved, this); @@ -123,7 +123,7 @@ void InputDelegate::setTouchEnabled(bool enabled) _touchListener = listener; } else { // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(InputDelegate::onTouchBegan, this); diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index f92d73c9c7..891301bf5b 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -74,15 +74,22 @@ UILayer* UILayer::create(void) void UILayer::onEnter() { - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - setTouchEnabled(true); CCLayer::onEnter(); + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(UILayer::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(UILayer::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(UILayer::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(UILayer::onTouchCancelled, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } void UILayer::onExit() { - setTouchEnabled(false); +// setTouchEnabled(false); CCLayer::onExit(); } @@ -164,4 +171,4 @@ void UILayer::onTouchCancelled(Touch *pTouch, Event *pEvent) _inputManager->onTouchCancelled(pTouch); } -} \ No newline at end of file +} diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index d12859b703..1419edbc36 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -93,17 +93,18 @@ Control::~Control() CC_SAFE_RELEASE(_dispatchTable); } -////Menu - Events -//void Control::registerWithTouchDispatcher() -//{ -// Director::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, getTouchPriority(), true); -//} - void Control::onEnter() { Layer::onEnter(); - this->setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + auto dispatcher = EventDispatcher::getInstance(); + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(Control::onTouchEnded, this); + touchListener->onTouchCancelled = CC_CALLBACK_2(Control::onTouchCancelled, this); + + dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); } void Control::onExit() diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 4f889f7066..5e4e102aba 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -96,7 +96,6 @@ bool ControlButton::initWithLabelAndBackgroundSprite(Node* node, Scale9Sprite* b this->setTitleLabelDispatchTable(Dictionary::create()); this->setBackgroundSpriteDispatchTable(Dictionary::create()); - setTouchEnabled(true); _isPushed = false; _zoomOnTouchDown = true; diff --git a/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp b/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp index 18da7f0abf..082c929bea 100644 --- a/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp +++ b/extensions/GUI/CCControlExtension/CCControlColourPicker.cpp @@ -54,7 +54,6 @@ bool ControlColourPicker::init() { if (Control::init()) { - setTouchEnabled(true); // Cache the sprites SpriteFrameCache::getInstance()->addSpriteFramesWithFile("extensions/CCControlColourPickerSpriteSheet.plist"); diff --git a/extensions/GUI/CCControlExtension/CCControlHuePicker.cpp b/extensions/GUI/CCControlExtension/CCControlHuePicker.cpp index 48230e84ab..6e5600edf0 100644 --- a/extensions/GUI/CCControlExtension/CCControlHuePicker.cpp +++ b/extensions/GUI/CCControlExtension/CCControlHuePicker.cpp @@ -62,7 +62,6 @@ bool ControlHuePicker::initWithTargetAndPos(Node* target, Point pos) { if (Control::init()) { - setTouchEnabled(true); // Add background and slider sprites this->setBackground(ControlUtils::addSpriteToTargetWithPosAndAnchor("huePickerBackground.png", target, pos, Point(0.0f, 0.0f))); this->setSlider(ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, Point(0.5f, 0.5f))); diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp index 3a28593955..ab3fccdb74 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp @@ -76,8 +76,6 @@ bool ControlPotentiometer::initWithTrackSprite_ProgressTimer_ThumbSprite(Sprite* { if (Control::init()) { - setTouchEnabled(true); - setProgressTimer(progressTimer); setThumbSprite(thumbSprite); thumbSprite->setPosition(progressTimer->getPosition()); diff --git a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp index 3252de4c94..4d59fca00d 100644 --- a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp @@ -60,7 +60,6 @@ bool ControlSaturationBrightnessPicker::initWithTargetAndPos(Node* target, Point { if (Control::init()) { - setTouchEnabled(true); // Add background and slider sprites _background=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, Point(0.0f, 0.0f)); _overlay=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, Point(0.0f, 0.0f)); diff --git a/extensions/GUI/CCControlExtension/CCControlSlider.cpp b/extensions/GUI/CCControlExtension/CCControlSlider.cpp index 1ba96962b6..bafd327d69 100644 --- a/extensions/GUI/CCControlExtension/CCControlSlider.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSlider.cpp @@ -84,7 +84,6 @@ ControlSlider* ControlSlider::create(Sprite * backgroundSprite, Sprite* pogressS CCASSERT(thumbSprite, "Thumb sprite must be not nil"); ignoreAnchorPointForPosition(false); - setTouchEnabled(true); this->setBackgroundSprite(backgroundSprite); this->setProgressSprite(progressSprite); diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.cpp b/extensions/GUI/CCControlExtension/CCControlStepper.cpp index 7aee633bda..4c4df49589 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.cpp +++ b/extensions/GUI/CCControlExtension/CCControlStepper.cpp @@ -74,8 +74,6 @@ bool ControlStepper::initWithMinusSpriteAndPlusSprite(Sprite *minusSprite, Sprit CCASSERT(minusSprite, "Minus sprite must be not nil"); CCASSERT(plusSprite, "Plus sprite must be not nil"); - setTouchEnabled(true); - // Set the default values _autorepeat = true; _continuous = true; diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index dcf7fd555e..fe67a3f905 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -346,7 +346,6 @@ bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sp CCASSERT(offSprite, "offSprite must not be nil."); CCASSERT(thumbSprite, "thumbSprite must not be nil."); - setTouchEnabled(true); _on = true; _switchSprite = new ControlSwitchSprite(); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index ee6a416310..e5f4c0503e 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -109,8 +109,16 @@ bool ScrollView::initWithViewSize(Size size, Node *container/* = NULL*/) this->setViewSize(size); - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + this->onEnterHook = [this]() { + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); + + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; _touches.reserve(EventTouch::MAX_TOUCHES); @@ -177,16 +185,16 @@ void ScrollView::resume(Object* sender) _container->resumeSchedulerAndActions(); } -void ScrollView::setTouchEnabled(bool e) -{ - Layer::setTouchEnabled(e); - if (!e) - { - _dragging = false; - _touchMoved = false; - _touches.clear(); - } -} +//void ScrollView::setTouchEnabled(bool e) +//{ +// Layer::setTouchEnabled(e); +// if (!e) +// { +// _dragging = false; +// _touchMoved = false; +// _touches.clear(); +// } +//} void ScrollView::setContentOffset(Point offset, bool animated/* = false*/) { diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 5b002887ee..42b9d78425 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -216,10 +216,6 @@ public: virtual void onTouchCancelled(Touch *touch, Event *event); // Overrides -// virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) override; virtual void setContentSize(const Size & size) override; virtual const Size& getContentSize() const override; /** @@ -230,7 +226,6 @@ public: virtual void addChild(Node * child, int zOrder, int tag) override; virtual void addChild(Node * child, int zOrder) override; virtual void addChild(Node * child) override; - void setTouchEnabled(bool e) override; protected: /** diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index 4f06570737..ada7540cc6 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,8 +32,10 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); - setAccelerometerEnabled(true); - + auto dispatcher = EventDispatcher::getInstance(); + + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto label = LabelTTF::create(title().c_str(), "Arial", 32); addChild(label, 1); diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h index f1524be1ab..7e4cc7edf1 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h @@ -15,7 +15,7 @@ public: AccelerometerTest(void); ~AccelerometerTest(void); - virtual void onAcceleration(Acceleration* acc, Event* event) override; + virtual void onAcceleration(Acceleration* acc, Event* event); virtual std::string title(); virtual void onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h index 9e04493964..480d572f7a 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h @@ -21,7 +21,7 @@ public: void addNewSpriteAtPosition(Point p); void update(float dt); - virtual void onTouchesEnded(const std::vector& touches, Event* event) override; + virtual void onTouchesEnded(const std::vector& touches, Event* event); //CREATE_NODE(Box2DTestLayer); } ; diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index 2f03948186..a86859ebb1 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -19,7 +19,13 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - setAccelerometerEnabled(true); + + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; + schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f); return true; @@ -56,7 +62,14 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - setAccelerometerEnabled(true); + + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; + + schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f); return true; diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp index 64665fd18f..337d9b1006 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp @@ -30,7 +30,14 @@ bool Bug914Layer::init() // Apple recommends to re-assign "self" with the "super" return value if (BugsTestBaseLayer::init()) { - setTouchEnabled(true); + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; + // ask director the the window size auto size = Director::getInstance()->getWinSize(); LayerColor *layer; diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h index af5f8c1bdd..41ee2c25c8 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h @@ -9,8 +9,8 @@ public: static Scene* scene(); virtual bool init(); - virtual void onTouchesMoved(const std::vector& touches, Event * event) override; - virtual void onTouchesBegan(const std::vector& touches, Event * event) override; + virtual void onTouchesMoved(const std::vector& touches, Event * event); + virtual void onTouchesBegan(const std::vector& touches, Event * event); void restart(Object* sender); CREATE_FUNC(Bug914Layer); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h index 8ea7d2bbbd..88de62b0a1 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h @@ -8,8 +8,8 @@ class BugsTestMainLayer : public Layer public: virtual void onEnter(); - virtual void onTouchesBegan(const std::vector& touches, Event *event) override; - virtual void onTouchesMoved(const std::vector&touches, Event *event) override; + virtual void onTouchesBegan(const std::vector& touches, Event *event); + virtual void onTouchesMoved(const std::vector&touches, Event *event); protected: Point _beginPos; diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp index 4215b8810d..5a87658f35 100644 --- a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp @@ -17,8 +17,13 @@ void ClickAndMoveTestScene::runThisTest() MainLayer::MainLayer() { - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this); + listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; auto sprite = Sprite::create(s_pathGrossini); diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h index f223d0b5ee..7cb8f7a3b4 100644 --- a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h +++ b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h @@ -13,8 +13,8 @@ class MainLayer : public Layer { public: MainLayer(); - virtual bool onTouchBegan(Touch* touch, Event *event) override; - virtual void onTouchEnded(Touch* touch, Event *event) override; + virtual bool onTouchBegan(Touch* touch, Event *event); + virtual void onTouchEnded(Touch* touch, Event *event); }; #endif diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 51e9791097..fcde7712ad 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -448,8 +448,13 @@ void HoleDemo::setup() _outerClipper->addChild(holesClipper); this->addChild(_outerClipper); - - this->setTouchEnabled(true); + + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; } void HoleDemo::pokeHoleAtPoint(Point point) @@ -526,7 +531,14 @@ void ScrollViewDemo::setup() _scrolling = false; - this->setTouchEnabled(true); + this->onEnterHook = [this](){ + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + }; } void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h index 11445bf406..0cb0c21d6d 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h @@ -98,7 +98,7 @@ public: virtual std::string title(); virtual std::string subtitle(); void pokeHoleAtPoint(Point point); - virtual void onTouchesBegan(const std::vector& touches, Event *event) override; + virtual void onTouchesBegan(const std::vector& touches, Event *event); private: ClippingNode* _outerClipper; Node* _holes; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 0c685ef98e..7dbb28617b 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -57,8 +57,8 @@ public: void onEnter() override; std::string subtitle() override; - void onTouchesEnded(const std::vector& touches, Event* event) override; - void onAcceleration(Acceleration* acc, Event* event) override; + void onTouchesEnded(const std::vector& touches, Event* event); + void onAcceleration(Acceleration* acc, Event* event); }; class PhysicsDemoLogoSmash : public PhysicsDemo From f7e2c63230d8d3dde81baba0578d8aab199f0fed Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 21 Oct 2013 17:22:42 +0800 Subject: [PATCH 221/557] Refactor event dispatcher. Remove non-node relative member variables. --- cocos/2d/CCDirector.cpp | 2 - cocos/2d/CCEventDispatcher.cpp | 185 +++++++++++++++++++++++++++++---- cocos/2d/CCEventDispatcher.h | 43 +++++++- cocos/2d/CCEventListener.h | 2 +- cocos/2d/CCNode.cpp | 23 +--- cocos/2d/CCNode.h | 21 +--- 6 files changed, 210 insertions(+), 66 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 8d1d8cb5df..9dc388ea11 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -229,8 +229,6 @@ void Director::setGLDefaultValues() // Draw the Scene void Director::drawScene() { - Node::resetEventPriorityIndex(); - // calculate "global" dt calculateDeltaTime(); diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 0e596b788a..57a8d5ffde 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -59,10 +59,156 @@ private: NS_CC_BEGIN static EventDispatcher* g_instance = nullptr; +static int s_eventPriorityIndex = 0; + +void EventDispatcher::visitNode(Node* node) +{ + int i = 0; + int childrenCount = node->_children ? node->_children->count() : 0; + + if(childrenCount > 0) + { + Node* child = nullptr; + // visit children zOrder < 0 + for( ; i < childrenCount; i++ ) + { + child = static_cast( node->_children->getObjectAtIndex(i) ); + + if ( child && child->_ZOrder < 0 ) + visitNode(child); + else + break; + } + + node->_eventPriority = ++s_eventPriorityIndex; + + for( ; i < childrenCount; i++ ) + { + child = static_cast( node->_children->getObjectAtIndex(i) ); + if (child) + visitNode(child); + } + } + else + { + node->_eventPriority = ++s_eventPriorityIndex; + } +} + +EventDispatcher::EventListenerItem::EventListenerItem() +: fixedPriority(0) +, listener(nullptr) +, node(nullptr) +{ + +} EventDispatcher::EventListenerItem::~EventListenerItem() { - CC_SAFE_RELEASE(this->node); +} + +EventDispatcher::EventListenerItemVector::EventListenerItemVector() +: _sceneGraphItems(nullptr) +, _fixedItems(nullptr) +{ +} + +EventDispatcher::EventListenerItemVector::~EventListenerItemVector() +{ + CC_SAFE_DELETE(_sceneGraphItems); + CC_SAFE_DELETE(_fixedItems); +} + +size_t EventDispatcher::EventListenerItemVector::size() const +{ + size_t ret = 0; + if (_sceneGraphItems) + ret += _sceneGraphItems->size(); + if (_fixedItems) + ret += _fixedItems->size(); + + return ret; +} + +bool EventDispatcher::EventListenerItemVector::empty() const +{ + return (_sceneGraphItems == nullptr || _sceneGraphItems->empty()) + && (_fixedItems == nullptr || _fixedItems->empty()); +} + +void EventDispatcher::EventListenerItemVector::iterate(IterateCallback cb, EventDispatcher::EventListenerItemVector::IterateMode mode/* = IterateMode::ALL*/) +{ + auto loop = [&cb](std::vector* items) -> bool { + for (auto iter = items->begin(); iter != items->end(); ++iter) + { + if (cb(iter, items)) + return false; + } + return true; + }; + + switch (mode) + { + case IterateMode::FIXED_PRIORITY_LESS_THAN_0: + loop(_lt0); + break; + case IterateMode::SCENE_GRAPH_PRIORITY: + loop(_eq0); + break; + case IterateMode::FIXED_PRIORITY_GREATER_THAN_0: + loop(_gt0); + break; + case IterateMode::ALL: + { + if (!loop(_lt0)) return; + if (!loop(_eq0)) return; + if (!loop(_gt0)) return; + } + default: + break; + } +} + +void EventDispatcher::EventListenerItemVector::push_back(EventDispatcher::EventListenerItem* item) +{ + if (item->fixedPriority == 0) + { + if (_sceneGraphItems == nullptr) + { + _sceneGraphItems = new std::vector(); + _sceneGraphItems->reserve(100); + } + + _sceneGraphItems->push_back(item); + } + else + { + if (_fixedItems == nullptr) + { + _fixedItems = new std::vector(); + _fixedItems->reserve(100); + } + + _fixedItems->push_back(item); + } +} + +void EventDispatcher::EventListenerItemVector::remove(EventDispatcher::EventListenerItem* item) +{ + if (item->fixedPriority < 0) + { + CCASSERT(_lt0, "vector invaild"); + + } + else if (item->fixedPriority == 0) + { + CCASSERT(_eq0, "vector invaild"); + + } + else + { + CCASSERT(_gt0, "vector invalid"); + } } EventDispatcher::EventDispatcher() @@ -96,13 +242,13 @@ void EventDispatcher::addEventListenerWithItem(EventListenerItem* item) { if (_inDispatch == 0) { - std::vector* listenerList = nullptr; + EventListenerItemVector* listenerList = nullptr; auto iter = _listeners.find(item->listener->_type); if (iter == _listeners.end()) { - listenerList = new std::vector(); - listenerList->reserve(100); + listenerList = new EventListenerItemVector(); +// listenerList->reserve(100); _listeners.insert(std::make_pair(item->listener->_type, listenerList)); } else @@ -110,7 +256,7 @@ void EventDispatcher::addEventListenerWithItem(EventListenerItem* item) listenerList = iter->second; } - listenerList->insert(listenerList->begin(), item); + listenerList->push_back(item); setDirtyForEventType(item->listener->_type, true); } @@ -169,32 +315,35 @@ void EventDispatcher::removeEventListener(EventListener* listener) for (auto iter = _listeners.begin(); iter != _listeners.end();) { - for (auto itemIter = iter->second->begin(); itemIter != iter->second->end(); ++itemIter) - { - if ((*itemIter)->listener == listener) + iter->second->iterate([&](std::vector::iterator itemIt, std::vector* current) -> bool { + + auto item = *itemIt; + if (item->listener == listener) { CC_SAFE_RETAIN(listener); - (*itemIter)->listener->_isRegistered = false; - if ((*itemIter)->node != nullptr) + item->listener->_isRegistered = false; + if (item->node != nullptr) { - (*itemIter)->node->dissociateEventListener(listener); + item->node->dissociateEventListener(listener); } - (*itemIter)->listener->release(); + item->listener->release(); if (_inDispatch == 0) { - delete (*itemIter); - iter->second->erase(itemIter); + current->erase(itemIt); + delete item; } else { - (*itemIter)->listener = nullptr; + item->listener = nullptr; } - + isFound = true; - break; + return false; } - } + + return true; + }); if (iter->second->empty()) { diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 06b6e430c7..04191ea6d8 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -100,23 +100,58 @@ public: */ void dispatchEvent(Event* event, bool forceSortListeners = false); + void sortSceneGraphListeners(const std::string& eventType); + void setDirtyForEventType(const std::string& eventType, bool isDirty); bool isDirtyForEventType(const std::string& eventType); + void visitNode(Node* node); + public: /** Destructor of EventDispatcher */ ~EventDispatcher(); private: + struct EventListenerItem { - int fixedPriority; // The higher the number, the higher the priority - Node* node; // Weak reference. + int fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority. + Node* node; // Weak reference. EventListener* listener; + + EventListenerItem(); ~EventListenerItem(); }; + + class EventListenerItemVector + { + public: + EventListenerItemVector(); + ~EventListenerItemVector(); + size_t size() const; + bool empty() const; + + enum class IterateMode + { + FIXED_PRIORITY_LESS_THAN_0, + SCENE_GRAPH_PRIORITY, + FIXED_PRIORITY_GREATER_THAN_0, + ALL + }; + + typedef std::function::iterator, std::vector*)> IterateCallback; + + void iterate(IterateCallback cb, IterateMode mode = IterateMode::ALL); + void push_back(EventListenerItem* item); + void remove(EventListenerItem* item); + + private: + std::vector* _fixedItems; + std::vector* _sceneGraphItems; + }; + /** Constructor of EventDispatcher */ EventDispatcher(); @@ -127,7 +162,7 @@ private: void dispatchTouchEvent(EventTouch* event); /** Gets event the listener list for the event type. */ - std::vector* getListenerItemsForType(const std::string& eventType); + EventListenerItemVector* getListenerItemsForType(const std::string& eventType); /** Sorts the listeners of specified type by priority */ void sortAllEventListenerItemsForType(const std::string& eventType); @@ -142,7 +177,7 @@ private: /** * Listeners map. */ - std::map*> _listeners; + std::map _listeners; /// Priority dirty flag std::map _priorityDirtyFlagMap; diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index 559cf21739..982531416c 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -39,7 +39,7 @@ class Event; /** * The base class of event listener. * If you need custom listener which with different callback, you need to inherit this class. - * For instance, you could refer to AccelerationEventListener, KeyboardEventListener or TouchEventListener, CustomEventListener. + * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard, EventListenerTouchOneByOne, EventListenerCustom. */ class EventListener : public Object { diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 33f9963526..aad3d3fe6d 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -89,10 +89,10 @@ bool nodeComparisonLess(Object* p1, Object* p2) // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. static int s_globalOrderOfArrival = 1; -int Node::_globalEventPriorityIndex = 0; Node::Node(void) -: _rotationX(0.0f) +: _eventPriority(0) +, _rotationX(0.0f) , _rotationY(0.0f) , _scaleX(1.0f) , _scaleY(1.0f) @@ -130,8 +130,6 @@ Node::Node(void) , _isTransitionFinished(false) , _updateScriptHandler(0) , _componentContainer(NULL) -, _eventPriority(0) -, _oldEventPriority(0) #ifdef CC_USE_PHYSICS , _physicsBody(nullptr) #endif @@ -864,7 +862,6 @@ void Node::visit() } // self draw this->draw(); - updateEventPriorityIndex(); for( ; i < _children->count(); i++ ) { @@ -876,7 +873,6 @@ void Node::visit() else { this->draw(); - updateEventPriorityIndex(); } // reset for next frame @@ -1367,11 +1363,6 @@ void Node::removeAllComponents() _componentContainer->removeAll(); } -void Node::resetEventPriorityIndex() -{ - _globalEventPriorityIndex = 0; -} - void Node::associateEventListener(EventListener* listener) { _eventlisteners.insert(listener); @@ -1394,16 +1385,6 @@ void Node::removeAllEventListeners() } } -void Node::setDirtyForAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - for (auto& listener : _eventlisteners) - { - dispatcher->setDirtyForEventType(listener->_type, true); - } -} - #ifdef CC_USE_PHYSICS void Node::setPhysicsBody(PhysicsBody* body) { diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index ca0a8eca96..b5c42f2301 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1407,32 +1407,17 @@ private: friend class Director; friend class EventDispatcher; - int getEventPriority() const { return _eventPriority; }; - void associateEventListener(EventListener* listener); void dissociateEventListener(EventListener* listener); - static void resetEventPriorityIndex(); std::set _eventlisteners; + int _eventPriority; protected: - /// Upates event priority for this node. - inline void updateEventPriorityIndex() { - _oldEventPriority = _eventPriority; - _eventPriority = ++_globalEventPriorityIndex; - if (_oldEventPriority != _eventPriority) - { - setDirtyForAllEventListeners(); - } - }; - /// Removes all event listeners that associated with this node. void removeAllEventListeners(); - /// Sets dirty for event listener. - void setDirtyForAllEventListeners(); - /// lazy allocs void childrenAlloc(void); @@ -1509,10 +1494,6 @@ protected: ccScriptType _scriptType; ///< type of script binding, lua or javascript ComponentContainer *_componentContainer; ///< Dictionary of components - - int _eventPriority; ///< The scene graph based priority of event listener. - int _oldEventPriority; ///< The old scene graph based priority of event listener. - static int _globalEventPriorityIndex; ///< The index of global event priority. #ifdef CC_USE_PHYSICS PhysicsBody* _physicsBody; ///< the physicsBody the node have From 1f3863e787b97955796e23ad22c718ed142932c3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 11:27:24 +0800 Subject: [PATCH 222/557] Event Dispatcher refactor commit. TestCpp could run. --- cocos/2d/CCEventDispatcher.cpp | 903 +++++++++++------- cocos/2d/CCEventDispatcher.h | 105 +- cocos/2d/CCEventListener.cpp | 1 + cocos/2d/CCEventListener.h | 12 +- cocos/2d/CCMenu.cpp | 2 + cocos/2d/CCNode.cpp | 61 +- cocos/2d/CCNode.h | 18 - cocos/2d/CCParticleBatchNode.cpp | 1 - cocos/2d/CCRenderTexture.cpp | 1 - cocos/2d/CCSpriteBatchNode.cpp | 1 - cocos/2d/platform/CCEGLViewProtocol.cpp | 6 +- .../editor-support/cocostudio/CCArmature.cpp | 1 - .../editor-support/cocostudio/CCBatchNode.cpp | 1 - extensions/GUI/CCScrollView/CCScrollView.cpp | 20 +- .../Classes/ActionsTest/ActionsTest.cpp | 2 +- .../Classes/Box2DTestBed/Box2dView.cpp | 20 +- .../TestCpp/Classes/Box2DTestBed/Box2dView.h | 3 +- .../Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 16 +- .../Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp | 12 +- .../Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp | 2 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 4 +- .../Classes/ChipmunkTest/ChipmunkTest.h | 4 +- .../ClickAndMoveTest/ClickAndMoveTest.cpp | 12 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 24 +- .../CocosDenshionTest/CocosDenshionTest.cpp | 4 +- .../Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp | 2 +- .../Cpp/TestCpp/Classes/CurlTest/CurlTest.h | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 6 +- .../CocoStudioArmatureTest/ArmatureScene.h | 2 +- .../Classes/ExtensionsTest/ExtensionsTest.cpp | 2 +- .../Classes/KeyboardTest/KeyboardTest.cpp | 2 +- .../TestCpp/Classes/KeypadTest/KeypadTest.cpp | 2 +- .../TestCpp/Classes/KeypadTest/KeypadTest.h | 2 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 2 +- .../Classes/LabelTest/LabelTestNew.cpp | 2 +- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 4 +- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 18 +- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.h | 1 + .../MotionStreakTest/MotionStreakTest.cpp | 2 +- .../Classes/MutiTouchTest/MutiTouchTest.cpp | 2 +- .../NewEventDispatcherTest.cpp | 6 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 2 +- .../Classes/ParallaxTest/ParallaxTest.cpp | 2 +- .../Classes/ParticleTest/ParticleTest.cpp | 2 +- .../PerformanceTouchesTest.cpp | 14 +- .../PerformanceTest/PerformanceTouchesTest.h | 16 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 4 +- .../RenderTextureTest/RenderTextureTest.cpp | 6 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/TextInputTest/TextInputTest.cpp | 4 +- .../Classes/TileMapTest/TileMapTest.cpp | 2 +- .../TestCpp/Classes/TouchesTest/Paddle.cpp | 2 +- samples/Cpp/TestCpp/Classes/controller.cpp | 4 +- 53 files changed, 763 insertions(+), 590 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 57a8d5ffde..7933a5edd6 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -31,7 +31,7 @@ #include -#define DUMP_LISTENER_ITEM_PRIORITY_INFO 0 +#define DUMP_LISTENER_ITEM_PRIORITY_INFO 1 namespace { @@ -61,155 +61,156 @@ NS_CC_BEGIN static EventDispatcher* g_instance = nullptr; static int s_eventPriorityIndex = 0; -void EventDispatcher::visitNode(Node* node) +void EventDispatcher::visitTarget(Node* node) { + // Reset priority index + s_eventPriorityIndex = 0; + _nodePriorityMap.clear(); + int i = 0; - int childrenCount = node->_children ? node->_children->count() : 0; + Array* children = node->getChildren(); + int childrenCount = children ? children->count() : 0; if(childrenCount > 0) { + Node* child = nullptr; // visit children zOrder < 0 for( ; i < childrenCount; i++ ) { - child = static_cast( node->_children->getObjectAtIndex(i) ); + child = static_cast( children->getObjectAtIndex(i) ); - if ( child && child->_ZOrder < 0 ) - visitNode(child); + if ( child && child->getZOrder() < 0 ) + visitTarget(child); else break; } - node->_eventPriority = ++s_eventPriorityIndex; + _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); for( ; i < childrenCount; i++ ) { - child = static_cast( node->_children->getObjectAtIndex(i) ); + child = static_cast( children->getObjectAtIndex(i) ); if (child) - visitNode(child); + visitTarget(child); } } else { - node->_eventPriority = ++s_eventPriorityIndex; + _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); } } -EventDispatcher::EventListenerItem::EventListenerItem() -: fixedPriority(0) -, listener(nullptr) -, node(nullptr) +void EventDispatcher::pauseTarget(Node* node) { - + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + l->_paused = true; + } + } } -EventDispatcher::EventListenerItem::~EventListenerItem() +void EventDispatcher::resumeTarget(Node* node) +{ + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + l->_paused = false; + } + } +} + +void EventDispatcher::cleanTarget(Node* node) +{ + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + removeEventListener(l); + } + } +} + +EventDispatcher::EventListenerVector::EventListenerVector() +: _sceneGraphListeners(nullptr) +, _fixedListeners(nullptr) +, _gt0Index(0) { } -EventDispatcher::EventListenerItemVector::EventListenerItemVector() -: _sceneGraphItems(nullptr) -, _fixedItems(nullptr) +EventDispatcher::EventListenerVector::~EventListenerVector() { + CC_SAFE_DELETE(_sceneGraphListeners); + CC_SAFE_DELETE(_fixedListeners); } -EventDispatcher::EventListenerItemVector::~EventListenerItemVector() -{ - CC_SAFE_DELETE(_sceneGraphItems); - CC_SAFE_DELETE(_fixedItems); -} - -size_t EventDispatcher::EventListenerItemVector::size() const +size_t EventDispatcher::EventListenerVector::size() const { size_t ret = 0; - if (_sceneGraphItems) - ret += _sceneGraphItems->size(); - if (_fixedItems) - ret += _fixedItems->size(); + if (_sceneGraphListeners) + ret += _sceneGraphListeners->size(); + if (_fixedListeners) + ret += _fixedListeners->size(); return ret; } -bool EventDispatcher::EventListenerItemVector::empty() const +bool EventDispatcher::EventListenerVector::empty() const { - return (_sceneGraphItems == nullptr || _sceneGraphItems->empty()) - && (_fixedItems == nullptr || _fixedItems->empty()); + return (_sceneGraphListeners == nullptr || _sceneGraphListeners->empty()) + && (_fixedListeners == nullptr || _fixedListeners->empty()); } -void EventDispatcher::EventListenerItemVector::iterate(IterateCallback cb, EventDispatcher::EventListenerItemVector::IterateMode mode/* = IterateMode::ALL*/) +void EventDispatcher::EventListenerVector::push_back(EventListener* listener) { - auto loop = [&cb](std::vector* items) -> bool { - for (auto iter = items->begin(); iter != items->end(); ++iter) + if (listener->_fixedPriority == 0) + { + if (_sceneGraphListeners == nullptr) { - if (cb(iter, items)) - return false; + _sceneGraphListeners = new std::vector(); + _sceneGraphListeners->reserve(100); } - return true; - }; + + _sceneGraphListeners->push_back(listener); + } + else + { + if (_fixedListeners == nullptr) + { + _fixedListeners = new std::vector(); + _fixedListeners->reserve(100); + } + + _fixedListeners->push_back(listener); + } +} + +void EventDispatcher::EventListenerVector::clear() +{ + if (_sceneGraphListeners) + { + _sceneGraphListeners->clear(); + delete _sceneGraphListeners; + _sceneGraphListeners = nullptr; + } - switch (mode) + if (_fixedListeners) { - case IterateMode::FIXED_PRIORITY_LESS_THAN_0: - loop(_lt0); - break; - case IterateMode::SCENE_GRAPH_PRIORITY: - loop(_eq0); - break; - case IterateMode::FIXED_PRIORITY_GREATER_THAN_0: - loop(_gt0); - break; - case IterateMode::ALL: - { - if (!loop(_lt0)) return; - if (!loop(_eq0)) return; - if (!loop(_gt0)) return; - } - default: - break; + _fixedListeners->clear(); + delete _fixedListeners; + _fixedListeners = nullptr; } } -void EventDispatcher::EventListenerItemVector::push_back(EventDispatcher::EventListenerItem* item) -{ - if (item->fixedPriority == 0) - { - if (_sceneGraphItems == nullptr) - { - _sceneGraphItems = new std::vector(); - _sceneGraphItems->reserve(100); - } - - _sceneGraphItems->push_back(item); - } - else - { - if (_fixedItems == nullptr) - { - _fixedItems = new std::vector(); - _fixedItems->reserve(100); - } - - _fixedItems->push_back(item); - } -} - -void EventDispatcher::EventListenerItemVector::remove(EventDispatcher::EventListenerItem* item) -{ - if (item->fixedPriority < 0) - { - CCASSERT(_lt0, "vector invaild"); - - } - else if (item->fixedPriority == 0) - { - CCASSERT(_eq0, "vector invaild"); - - } - else - { - CCASSERT(_gt0, "vector invalid"); - } -} EventDispatcher::EventDispatcher() : _inDispatch(0) @@ -238,31 +239,75 @@ void EventDispatcher::destroyInstance() CC_SAFE_DELETE(g_instance); } -void EventDispatcher::addEventListenerWithItem(EventListenerItem* item) +void EventDispatcher::associateNodeAndEventListener(Node* node, EventListener* listener) +{ + std::vector* listeners = nullptr; + auto found = _nodeListenersMap.find(node); + if (found != _nodeListenersMap.end()) + { + listeners = found->second; + } + else + { + listeners = new std::vector(); + } + + listeners->push_back(listener); + + _nodeListenersMap.insert(std::make_pair(node, listeners)); +} + +void EventDispatcher::dissociateNodeAndEventListener(Node* node, EventListener* listener) +{ + std::vector* listeners = nullptr; + auto found = _nodeListenersMap.find(node); + if (found != _nodeListenersMap.end()) + { + listeners = found->second; + auto iter = std::find(listeners->begin(), listeners->end(), listener); + if (iter != listeners->end()) + { + listeners->erase(iter); + } + + if (listeners->empty()) + { + _nodeListenersMap.erase(found); + } + } +} + +void EventDispatcher::addEventListener(EventListener* listener) { if (_inDispatch == 0) { - EventListenerItemVector* listenerList = nullptr; + EventListenerVector* listenerList = nullptr; - auto iter = _listeners.find(item->listener->_type); + auto iter = _listeners.find(listener->_type); if (iter == _listeners.end()) { - listenerList = new EventListenerItemVector(); -// listenerList->reserve(100); - _listeners.insert(std::make_pair(item->listener->_type, listenerList)); + listenerList = new EventListenerVector(); + _listeners.insert(std::make_pair(listener->_type, listenerList)); } else { listenerList = iter->second; } - listenerList->push_back(item); - - setDirtyForEventType(item->listener->_type, true); + listenerList->push_back(listener); + + if (listener->_fixedPriority == 0) + { + setDirtyForEventType(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + } + else + { + setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); + } } else { - _toAddedListeners.push_back(item); + _toAddedListeners.push_back(listener); } } @@ -274,17 +319,21 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list if (!listener->checkAvailable()) return; - auto item = new EventListenerItem(); - item->node = node; - item->node->retain(); - item->fixedPriority = 0; - item->listener = listener; - item->listener->retain(); - item->listener->_isRegistered = true; + listener->_node = node; +// listener->_node->retain(); + listener->_fixedPriority = 0; - addEventListenerWithItem(item); + listener->retain(); + listener->_isRegistered = true; - node->associateEventListener(listener); + addEventListener(listener); + + associateNodeAndEventListener(node, listener); + + if (node->isRunning()) + { + resumeTarget(node); + } } void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority) @@ -296,14 +345,13 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, if (!listener->checkAvailable()) return; - auto item = new EventListenerItem(); - item->node = nullptr; - item->fixedPriority = fixedPriority; - item->listener = listener; - item->listener->retain(); - item->listener->_isRegistered = true; + listener->_node = nullptr; + listener->_fixedPriority = fixedPriority; + listener->retain(); + listener->_isRegistered = true; + listener->_paused = false; - addEventListenerWithItem(item); + addEventListener(listener); } void EventDispatcher::removeEventListener(EventListener* listener) @@ -313,37 +361,45 @@ void EventDispatcher::removeEventListener(EventListener* listener) bool isFound = false; - for (auto iter = _listeners.begin(); iter != _listeners.end();) - { - iter->second->iterate([&](std::vector::iterator itemIt, std::vector* current) -> bool { + auto removeListenerInVector = [&](std::vector* listeners){ + if (listeners == nullptr) + return; - auto item = *itemIt; - if (item->listener == listener) + for (auto iter = listeners->begin(); iter != listeners->end(); ++iter) + { + auto l = *iter; + if (l == listener) { CC_SAFE_RETAIN(listener); - item->listener->_isRegistered = false; - if (item->node != nullptr) + l->_isRegistered = false; + if (l->_node != nullptr) { - item->node->dissociateEventListener(listener); + dissociateNodeAndEventListener(l->_node, listener); } - item->listener->release(); + l->release(); if (_inDispatch == 0) { - current->erase(itemIt); - delete item; - } - else - { - item->listener = nullptr; + listeners->erase(iter); } isFound = true; - return false; + break; } - - return true; - }); + } + }; + + for (auto iter = _listeners.begin(); iter != _listeners.end();) + { + auto listeners = iter->second; + auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); + auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); + + removeListenerInVector(sceneGraphPriorityListeners); + if (!isFound) + { + removeListenerInVector(fixedPriorityListeners); + } if (iter->second->empty()) { @@ -374,17 +430,18 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) { - for (auto itemIter = iter->second->begin(); itemIter != iter->second->end(); ++itemIter) + auto fixedPriorityListeners = iter->second->getFixedPriorityListeners(); + if (fixedPriorityListeners) { - auto item = *itemIter; - if (item->listener == listener) + auto found = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener); + if (found != fixedPriorityListeners->end()) { - CCASSERT(item->node, "Can't set fixed priority with scene graph based listener."); + CCASSERT(listener->_node, "Can't set fixed priority with scene graph based listener."); - if (item->fixedPriority != fixedPriority) + if (listener->_fixedPriority != fixedPriority) { - item->fixedPriority = fixedPriority; - setDirtyForEventType(listener->_type, true); + listener->_fixedPriority = fixedPriority; + setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); } return; } @@ -392,59 +449,151 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) } } -void EventDispatcher::dispatchEvent(Event* event, bool forceSortListeners) +void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent) +{ + bool shouldStopPropagation = false; + auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); + auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); + + int i = 0; + // priority < 0 + if (fixedPriorityListeners) + { + for (; !fixedPriorityListeners->empty() && i < listeners->getGt0Index(); ++i) + { + auto l = fixedPriorityListeners->at(i); + if (!l->isPaused() && onEvent(l)) + { + shouldStopPropagation = true; + break; + } + } + } + + if (sceneGraphPriorityListeners) + { + if (!shouldStopPropagation) + { + // priority == 0, scene graph priority + for (auto& listener : *sceneGraphPriorityListeners) + { + if (!listener->isPaused() && onEvent(listener)) + { + shouldStopPropagation = true; + break; + } + } + } + } + + if (fixedPriorityListeners) + { + if (!shouldStopPropagation) + { + // priority > 0 + for (; i < fixedPriorityListeners->size(); ++i) + { + auto l = fixedPriorityListeners->at(i); + + if (!l->isPaused() && onEvent(fixedPriorityListeners->at(i))) + { + shouldStopPropagation = true; + break; + } + } + } + } +} + +void EventDispatcher::dispatchEvent(Event* event) { if (!_isEnabled) return; - bool isDirty = false; + updateDirtyFlagForSceneGraph(); + + DirtyFlag dirtyFlag = DirtyFlag::NONE; + auto dirtyIter = _priorityDirtyFlagMap.find(event->_type); if (dirtyIter != _priorityDirtyFlagMap.end()) { - isDirty = dirtyIter->second; + dirtyFlag = dirtyIter->second; } - if (forceSortListeners || isDirty) + if (dirtyFlag != DirtyFlag::NONE) { - sortAllEventListenerItemsForType(event->_type); - // Sets the dirty flag to false - if (isDirty) + if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) { - dirtyIter->second = false; + sortEventListenersOfFixedPriority(event->_type); } + + if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) + { + sortEventListenersOfSceneGraphPriority(event->_type); + } + + dirtyIter->second = DirtyFlag::NONE; } - + DispatchGuard guard(_inDispatch); - - if (event->_type == EventTouch::EVENT_TYPE) - { - dispatchTouchEvent(static_cast(event)); - return; - } auto iter = _listeners.find(event->getType()); if (iter != _listeners.end()) { - auto listenerList = iter->second; - for (auto& item : *listenerList) - { - CCASSERT(item, "listener item is invalid."); - - event->setCurrentTarget(item->node); - item->listener->_onEvent(event); - - if (event->isStopped()) - break; - } + auto listeners = iter->second; + + auto onEvent = [&event](EventListener* listener) -> bool{ + event->setCurrentTarget(listener->_node); + listener->_onEvent(event); + return event->isStopped(); + }; + + dispatchEventToListeners(listeners, onEvent); } - updateListenerItems(); + updateListeners(); } void EventDispatcher::dispatchTouchEvent(EventTouch* event) { - auto oneByOnelisteners = getListenerItemsForType(EventTouch::MODE_ONE_BY_ONE); - auto allAtOncelisteners = getListenerItemsForType(EventTouch::MODE_ALL_AT_ONCE); + if (!_isEnabled) + return; + + updateDirtyFlagForSceneGraph(); + + auto sortTouchListeners = [this](const std::string& type){ + + DirtyFlag dirtyFlag = DirtyFlag::NONE; + auto dirtyIter = _priorityDirtyFlagMap.find(type); + if (dirtyIter != _priorityDirtyFlagMap.end()) + { + dirtyFlag = dirtyIter->second; + } + + if (dirtyFlag != DirtyFlag::NONE) + { + if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) + { + sortEventListenersOfFixedPriority(type); + } + + if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) + { + sortEventListenersOfSceneGraphPriority(type); + } + + dirtyIter->second = DirtyFlag::NONE; + } + + }; + + sortTouchListeners(EventTouch::MODE_ONE_BY_ONE); + sortTouchListeners(EventTouch::MODE_ALL_AT_ONCE); + + DispatchGuard guard(_inDispatch); + + auto oneByOnelisteners = getListeners(EventTouch::MODE_ONE_BY_ONE); + auto allAtOncelisteners = getListeners(EventTouch::MODE_ALL_AT_ONCE); // If there aren't any touch listeners, return directly. if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) @@ -455,7 +604,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) std::vector orignalTouches = event->getTouches(); std::vector mutableTouches(orignalTouches.size()); std::copy(orignalTouches.begin(), orignalTouches.end(), mutableTouches.begin()); - + // // process the target handlers 1st // @@ -468,62 +617,63 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) { bool isSwallowed = false; - for (auto& item : *oneByOnelisteners) - { + auto onTouchEvent = [&](EventListener* l) -> bool { // Return true to break + EventListenerTouchOneByOne* listener = static_cast(l); + // Skip if the listener was removed. - if (item->listener == nullptr) - continue; + if (!listener->_isRegistered) + return false; - event->setCurrentTarget(item->node); + event->setCurrentTarget(listener->_node); bool isClaimed = false; std::vector::iterator removedIter; - auto touchEventListener = static_cast(item->listener); EventTouch::EventCode eventCode = event->getEventCode(); if (eventCode == EventTouch::EventCode::BEGAN) { - if (touchEventListener->onTouchBegan) + if (listener->onTouchBegan) { - isClaimed = touchEventListener->onTouchBegan(*touchesIter, event); - if (isClaimed && item->listener) + CCLOG("onTouchBegan..."); + isClaimed = listener->onTouchBegan(*touchesIter, event); + if (isClaimed && listener->_isRegistered) { - touchEventListener->_claimedTouches.push_back(*touchesIter); + listener->_claimedTouches.push_back(*touchesIter); } } } - else if (touchEventListener->_claimedTouches.size() > 0 - && ((removedIter = std::find(touchEventListener->_claimedTouches.begin(), touchEventListener->_claimedTouches.end(), *touchesIter)) != touchEventListener->_claimedTouches.end())) + else if (listener->_claimedTouches.size() > 0 + && ((removedIter = std::find(listener->_claimedTouches.begin(), listener->_claimedTouches.end(), *touchesIter)) != listener->_claimedTouches.end())) { isClaimed = true; switch (eventCode) { case EventTouch::EventCode::MOVED: - if (touchEventListener->onTouchMoved) + if (listener->onTouchMoved) { - touchEventListener->onTouchMoved(*touchesIter, event); + listener->onTouchMoved(*touchesIter, event); } break; case EventTouch::EventCode::ENDED: - if (touchEventListener->onTouchEnded) + if (listener->onTouchEnded) { - touchEventListener->onTouchEnded(*touchesIter, event); + listener->onTouchEnded(*touchesIter, event); } - if (item->listener) + if (listener->_isRegistered) { - touchEventListener->_claimedTouches.erase(removedIter); + listener->_claimedTouches.erase(removedIter); } break; case EventTouch::EventCode::CANCELLED: - if (touchEventListener->onTouchCancelled) + if (listener->onTouchCancelled) { - touchEventListener->onTouchCancelled(*touchesIter, event); + listener->onTouchCancelled(*touchesIter, event); } - if (item->listener) + if (listener->_isRegistered) { - touchEventListener->_claimedTouches.erase(removedIter); + listener->_claimedTouches.erase(removedIter); } break; default: @@ -535,21 +685,30 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListenerItems(); - return; + updateListeners(); + return true; } CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), ""); - if (isClaimed && item->listener && touchEventListener->_needSwallow) + if (isClaimed && listener->_isRegistered && listener->_needSwallow) { if (isNeedsMutableSet) { mutableTouchesIter = mutableTouches.erase(mutableTouchesIter); isSwallowed = true; } - break; + return true; } + + return false; + }; + + // + dispatchEventToListeners(oneByOnelisteners, onTouchEvent); + if (event->isStopped()) + { + return; } if (!isSwallowed) @@ -562,40 +721,39 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // if (allAtOncelisteners && mutableTouches.size() > 0) { - for (auto& item : *allAtOncelisteners) - { + + auto onTouchesEvent = [&](EventListener* l) -> bool{ + EventListenerTouchAllAtOnce* listener = static_cast(l); // Skip if the listener was removed. - if (item->listener == nullptr) - continue; + if (!listener->_isRegistered) + return false; - event->setCurrentTarget(item->node); - - auto touchEventListener = static_cast(item->listener); + event->setCurrentTarget(listener->_node); switch (event->getEventCode()) { case EventTouch::EventCode::BEGAN: - if (touchEventListener->onTouchesBegan) + if (listener->onTouchesBegan) { - touchEventListener->onTouchesBegan(mutableTouches, event); + listener->onTouchesBegan(mutableTouches, event); } break; case EventTouch::EventCode::MOVED: - if (touchEventListener->onTouchesMoved) + if (listener->onTouchesMoved) { - touchEventListener->onTouchesMoved(mutableTouches, event); + listener->onTouchesMoved(mutableTouches, event); } break; case EventTouch::EventCode::ENDED: - if (touchEventListener->onTouchesEnded) + if (listener->onTouchesEnded) { - touchEventListener->onTouchesEnded(mutableTouches, event); + listener->onTouchesEnded(mutableTouches, event); } break; case EventTouch::EventCode::CANCELLED: - if (touchEventListener->onTouchesCancelled) + if (listener->onTouchesCancelled) { - touchEventListener->onTouchesCancelled(mutableTouches, event); + listener->onTouchesCancelled(mutableTouches, event); } break; default: @@ -606,120 +764,196 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListenerItems(); - return; + updateListeners(); + return false; } + + return false; + }; + + dispatchEventToListeners(allAtOncelisteners, onTouchesEvent); + if (event->isStopped()) + { + return; } } - updateListenerItems(); + updateListeners(); } -void EventDispatcher::updateListenerItems() +void EventDispatcher::updateListeners() { - auto listenerItemIter = _listeners.begin(); - while (listenerItemIter != _listeners.end()) + auto listenersIter = _listeners.begin(); + while (listenersIter != _listeners.end()) { - for (auto iter = listenerItemIter->second->begin(); iter != listenerItemIter->second->end();) + auto listeners = listenersIter->second; + auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); + auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); + + if (sceneGraphPriorityListeners) { - if ((*iter)->listener == nullptr) + for (auto iter = sceneGraphPriorityListeners->begin(); iter != sceneGraphPriorityListeners->end();) { - delete (*iter); - iter = listenerItemIter->second->erase(iter); - } - else - { - ++iter; + auto l = *iter; + if (!l->_isRegistered) + { + iter = sceneGraphPriorityListeners->erase(iter); + } + else + { + ++iter; + } } } - if (listenerItemIter->second->empty()) + if (fixedPriorityListeners) { - _priorityDirtyFlagMap.erase(listenerItemIter->first); - delete listenerItemIter->second; - listenerItemIter = _listeners.erase(listenerItemIter); + for (auto iter = fixedPriorityListeners->begin(); iter != fixedPriorityListeners->end();) + { + auto l = *iter; + if (!l->_isRegistered) + { + iter = fixedPriorityListeners->erase(iter); + } + else + { + ++iter; + } + } + } + + if (listenersIter->second->empty()) + { + _priorityDirtyFlagMap.erase(listenersIter->first); + delete listenersIter->second; + listenersIter = _listeners.erase(listenersIter); } else { - ++listenerItemIter; + ++listenersIter; } } if (!_toAddedListeners.empty()) { - std::vector* listenerList = nullptr; + EventListenerVector* listeners = nullptr; - for (auto& item : _toAddedListeners) + for (auto& listener : _toAddedListeners) { - auto itr = _listeners.find(item->listener->_type); + auto itr = _listeners.find(listener->_type); if (itr == _listeners.end()) { - listenerList = new std::vector(); - listenerList->reserve(100); - _listeners.insert(std::make_pair(item->listener->_type, listenerList)); + + listeners = new EventListenerVector(); + _listeners.insert(std::make_pair(listener->_type, listeners)); } else { - listenerList = itr->second; + listeners = itr->second; } - listenerList->push_back(item); + listeners->push_back(listener); - setDirtyForEventType(item->listener->_type, true); + if (listener->_fixedPriority == 0) + { + setDirtyForEventType(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + } + else + { + setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); + } } _toAddedListeners.clear(); } } -void EventDispatcher::sortAllEventListenerItemsForType(const std::string &eventType) +void EventDispatcher::updateDirtyFlagForSceneGraph() +{ + if (!_dirtyNodes.empty()) + { + for (auto& node : _dirtyNodes) + { + auto iter = _nodeListenersMap.find(node); + if (iter != _nodeListenersMap.end()) + { + for (auto& l : *iter->second) + { + setDirtyForEventType(l->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + } + } + } + + _dirtyNodes.clear(); + } +} + +void EventDispatcher::sortEventListenersOfSceneGraphPriority(const std::string& eventType) { if (eventType.empty()) return; - auto listenerList = getListenerItemsForType(eventType); - - if (listenerList == nullptr) + auto listeners = getListeners(eventType); + + if (listeners == nullptr) return; - // After sort: priority < 0, = 0, scene graph, > 0 - std::sort(listenerList->begin(), listenerList->end(), [](const EventListenerItem* item1, const EventListenerItem* item2) { - - // item1 and item2 are both using fixed priority. - if (nullptr == item1->node && nullptr == item2->node) - { - return item1->fixedPriority < item2->fixedPriority; - } - // item1 and item2 are both using scene graph based priority. - else if (nullptr != item1->node && nullptr != item2->node) - { - return item1->node->getEventPriority() > item2->node->getEventPriority(); - } - else if (nullptr != item1->node && nullptr == item2->node) - { - return 0 < item2->fixedPriority; - } - else if (nullptr == item1->node && nullptr != item2->node) - { - return item1->fixedPriority <= 0; - } - else - { - CCASSERT(false, "sort event node error..."); - return false; - } + Node* rootNode = (Node*)Director::getInstance()->getRunningScene(); + + visitTarget(rootNode); + + // After sort: priority < 0, > 0 + auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); + std::sort(sceneGraphlisteners->begin(), sceneGraphlisteners->end(), [this](const EventListener* l1, const EventListener* l2) { + return _nodePriorityMap[l1->_node] >= _nodePriorityMap[l2->_node]; }); #if DUMP_LISTENER_ITEM_PRIORITY_INFO log("-----------------------------------"); - for (auto& item : *listenerList) + for (auto& l : *sceneGraphlisteners) { - log("listener item priority: node (%p), fixed (%d)", item->node, item->fixedPriority); + log("listener priority: node ([%s]%p), fixed (%d)", typeid(*l->_node).name(), l->_node, l->_fixedPriority); + } +#endif +} + +void EventDispatcher::sortEventListenersOfFixedPriority(const std::string &eventType) +{ + if (eventType.empty()) + return; + + auto listeners = getListeners(eventType); + + if (listeners == nullptr) + return; + + // After sort: priority < 0, > 0 + auto fixedlisteners = listeners->getFixedPriorityListeners(); + std::sort(fixedlisteners->begin(), fixedlisteners->end(), [](const EventListener* l1, const EventListener* l2) { + return l1->_fixedPriority < l2->_fixedPriority; + }); + + // FIXME: Should use binary search + int index = 0; + for (auto& listener : *fixedlisteners) + { + if (listener->_fixedPriority >= 0) + break; + ++index; + } + + listeners->setGt0Index(index); + +#if DUMP_LISTENER_ITEM_PRIORITY_INFO + log("-----------------------------------"); + for (auto& l : *fixedlisteners) + { + log("listener priority: node (%p), fixed (%d)", l->_node, l->_fixedPriority); } #endif } -std::vector* EventDispatcher::getListenerItemsForType(const std::string &eventType) +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const std::string &eventType) { auto iter = _listeners.find(eventType); if (iter != _listeners.end()) @@ -738,29 +972,42 @@ void EventDispatcher::removeListenersForEventType(const std::string& eventType) auto listenerItemIter = _listeners.find(eventType); if (listenerItemIter != _listeners.end()) { - for (auto iter = listenerItemIter->second->begin(); iter != listenerItemIter->second->end(); ++iter) - { - (*iter)->listener->_isRegistered = false; - if ((*iter)->node != nullptr) - { - (*iter)->node->dissociateEventListener((*iter)->listener); - } + auto listeners = listenerItemIter->second; + auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); + auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); + + auto removeAllListenersInVector = [&](std::vector* listenerVector){ + if (listenerVector == nullptr) + return; - (*iter)->listener->release(); - if (_inDispatch) + for (auto iter = listenerVector->begin(); iter != listenerVector->end();) { - (*iter)->listener = nullptr; + auto l = *iter; + l->_isRegistered = false; + if (l->_node != nullptr) + { + dissociateNodeAndEventListener(l->_node, l); + } + + l->release(); + if (_inDispatch == 0) + { + iter = listenerVector->erase(iter); + } + else + { + ++iter; + } } - else - { - delete (*iter); - } - } + }; + + removeAllListenersInVector(sceneGraphPriorityListeners); + removeAllListenersInVector(fixedPriorityListeners); if (!_inDispatch) { - listenerItemIter->second->clear(); - delete listenerItemIter->second; + listeners->clear(); + delete listeners; _listeners.erase(listenerItemIter); _priorityDirtyFlagMap.erase(eventType); } @@ -769,36 +1016,18 @@ void EventDispatcher::removeListenersForEventType(const std::string& eventType) void EventDispatcher::removeAllListeners() { - for (auto listenerItemIter = _listeners.begin(); listenerItemIter != _listeners.end(); ++listenerItemIter) + std::vector types(_listeners.size()); + + for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) { - for (auto iter = listenerItemIter->second->begin(); iter != listenerItemIter->second->end(); ++iter) - { - (*iter)->listener->_isRegistered = false; - if ((*iter)->node != nullptr) - { - (*iter)->node->dissociateEventListener((*iter)->listener); - } - - (*iter)->listener->release(); - if (_inDispatch) - { - (*iter)->listener = nullptr; - } - else - { - delete (*iter); - } - } - - if (!_inDispatch) - { - listenerItemIter->second->clear(); - delete listenerItemIter->second; - - _priorityDirtyFlagMap.clear(); - } + types.push_back(iter->first); } + for (auto& type : types) + { + removeListenersForEventType(type); + } + if (!_inDispatch) { _listeners.clear(); @@ -816,31 +1045,37 @@ bool EventDispatcher::isEnabled() const return _isEnabled; } -void EventDispatcher::setDirtyForEventType(const std::string& eventType, bool isDirty) +void EventDispatcher::setDirtyForNode(Node* node) +{ + _dirtyNodes.insert(node); +} + +void EventDispatcher::setDirtyForEventType(const std::string& eventType, DirtyFlag flag) { CCASSERT(!eventType.empty(), "Invalid event type."); auto iter = _priorityDirtyFlagMap.find(eventType); if (iter == _priorityDirtyFlagMap.end()) { - _priorityDirtyFlagMap.insert(std::make_pair(eventType, isDirty)); + _priorityDirtyFlagMap.insert(std::make_pair(eventType, flag)); } else { - iter->second = isDirty; + int ret = (int)flag | (int)iter->second; + iter->second = (DirtyFlag) ret; } } -bool EventDispatcher::isDirtyForEventType(const std::string& eventType) +EventDispatcher::DirtyFlag EventDispatcher::isDirtyForEventType(const std::string& eventType) { - bool isDirty = false; + DirtyFlag flag = DirtyFlag::NONE; auto iter = _priorityDirtyFlagMap.find(eventType); if (iter != _priorityDirtyFlagMap.end()) { - isDirty = iter->second; + flag = iter->second; } - return isDirty; + return flag; } NS_CC_END diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 04191ea6d8..dc70491075 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -98,15 +98,31 @@ public: * Also removes all EventListeners marked for deletion from the * event dispatcher list. */ - void dispatchEvent(Event* event, bool forceSortListeners = false); - - void sortSceneGraphListeners(const std::string& eventType); + void dispatchEvent(Event* event); - void setDirtyForEventType(const std::string& eventType, bool isDirty); + /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ + void dispatchTouchEvent(EventTouch* event); - bool isDirtyForEventType(const std::string& eventType); + /// Priority dirty flag + enum class DirtyFlag + { + NONE = 0, + FIXED_PRITORY = 1 << 0, + SCENE_GRAPH_PRIORITY = 1 << 1, + ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY + }; - void visitNode(Node* node); + void setDirtyForNode(Node* node); + + void setDirtyForEventType(const std::string& eventType, DirtyFlag flag); + + DirtyFlag isDirtyForEventType(const std::string& eventType); + + void visitTarget(Node* node); + + void pauseTarget(Node* node); + void resumeTarget(Node* node); + void cleanTarget(Node* node); public: /** Destructor of EventDispatcher */ @@ -114,75 +130,68 @@ public: private: - struct EventListenerItem - { - int fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority. - Node* node; // Weak reference. - EventListener* listener; - - EventListenerItem(); - ~EventListenerItem(); - }; - - - class EventListenerItemVector + class EventListenerVector { public: - EventListenerItemVector(); - ~EventListenerItemVector(); + EventListenerVector(); + ~EventListenerVector(); size_t size() const; bool empty() const; - enum class IterateMode - { - FIXED_PRIORITY_LESS_THAN_0, - SCENE_GRAPH_PRIORITY, - FIXED_PRIORITY_GREATER_THAN_0, - ALL - }; - - typedef std::function::iterator, std::vector*)> IterateCallback; - - void iterate(IterateCallback cb, IterateMode mode = IterateMode::ALL); - void push_back(EventListenerItem* item); - void remove(EventListenerItem* item); + void push_back(EventListener* item); + void clear(); + inline std::vector* getFixedPriorityListeners() const { return _fixedListeners; }; + inline std::vector* getSceneGraphPriorityListeners() const { return _sceneGraphListeners; }; + inline int getGt0Index() const { return _gt0Index; }; + inline void setGt0Index(int index) { _gt0Index = index; }; private: - std::vector* _fixedItems; - std::vector* _sceneGraphItems; + std::vector* _fixedListeners; + std::vector* _sceneGraphListeners; + int _gt0Index; }; /** Constructor of EventDispatcher */ EventDispatcher(); /** Adds event listener with item */ - void addEventListenerWithItem(EventListenerItem* item); - - /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ - void dispatchTouchEvent(EventTouch* event); + void addEventListener(EventListener* listener); /** Gets event the listener list for the event type. */ - EventListenerItemVector* getListenerItemsForType(const std::string& eventType); + EventListenerVector* getListeners(const std::string& eventType); - /** Sorts the listeners of specified type by priority */ - void sortAllEventListenerItemsForType(const std::string& eventType); + void updateDirtyFlagForSceneGraph(); - /** Updates all listener items + /** Sorts the listeners of specified type by scene graph priority */ + void sortEventListenersOfSceneGraphPriority(const std::string& eventType); + + /** Sorts the listeners of specified type by fixed priority */ + void sortEventListenersOfFixedPriority(const std::string& eventType); + + /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. * 2) Adds all listener items that have been marked as 'added' when dispatching event. */ - void updateListenerItems(); + void updateListeners(); + void associateNodeAndEventListener(Node* node, EventListener* listener); + void dissociateNodeAndEventListener(Node* node, EventListener* listener); + + void dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent); + private: /** * Listeners map. */ - std::map _listeners; + std::map _listeners; - /// Priority dirty flag - std::map _priorityDirtyFlagMap; + std::map _priorityDirtyFlagMap; - std::vector _toAddedListeners; + std::map*> _nodeListenersMap; + std::map _nodePriorityMap; + + std::vector _toAddedListeners; + std::set _dirtyNodes; int _inDispatch; ///< Whether it's in dispatching event bool _isEnabled; ///< Whether to enable dispatching event diff --git a/cocos/2d/CCEventListener.cpp b/cocos/2d/CCEventListener.cpp index 451be9a8c8..8b34ca5173 100644 --- a/cocos/2d/CCEventListener.cpp +++ b/cocos/2d/CCEventListener.cpp @@ -40,6 +40,7 @@ bool EventListener::init(const std::string& t, std::function callb _onEvent = callback; _type = t; _isRegistered = false; + _paused = true; return true; } diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index 982531416c..f68f9694f9 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -31,10 +31,12 @@ #include #include #include +#include NS_CC_BEGIN class Event; +class Node; /** * The base class of event listener. @@ -58,13 +60,21 @@ public: /** Clones the listener, its subclasses have to override this method. */ virtual EventListener* clone() = 0; + + inline bool isPaused() const { return _paused; }; + protected: std::function _onEvent; /// Event callback function std::string _type; /// Event type bool _isRegistered; /// Whether the listener has been added to dispatcher. + // The priority of event listener + int _fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority. + Node* _node; // scene graph based priority + bool _paused; + +private: friend class EventDispatcher; - friend class Node; }; NS_CC_END diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index fc38405355..3105a2d8a3 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -188,6 +188,8 @@ void Menu::onEnter() auto eventDispatcher = EventDispatcher::getInstance(); auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->setSwallowTouches(true); + touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index aad3d3fe6d..8b9d41f9ec 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -91,8 +91,7 @@ bool nodeComparisonLess(Object* p1, Object* p2) static int s_globalOrderOfArrival = 1; Node::Node(void) -: _eventPriority(0) -, _rotationX(0.0f) +: _rotationX(0.0f) , _rotationY(0.0f) , _scaleX(1.0f) , _scaleY(1.0f) @@ -134,11 +133,6 @@ Node::Node(void) , _physicsBody(nullptr) #endif { - onEnterHook = nullptr; - onEnterTransitionDidFinishHook = nullptr; - onExitHook = nullptr; - onExitTransitionDidStartHook = nullptr; - // set default scheduler and actionManager Director *director = Director::getInstance(); _actionManager = director->getActionManager(); @@ -188,7 +182,7 @@ Node::~Node() CC_SAFE_DELETE(_componentContainer); - removeAllEventListeners(); + EventDispatcher::getInstance()->cleanTarget(this); #ifdef CC_USE_PHYSICS CC_SAFE_RELEASE(_physicsBody); @@ -243,6 +237,8 @@ void Node::setZOrder(int z) { _parent->reorderChild(this, z); } + + EventDispatcher::getInstance()->setDirtyForNode(this); } /// vertexZ getter @@ -643,6 +639,8 @@ void Node::addChild(Node *child, int zOrder, int tag) child->onEnterTransitionDidFinish(); } } + + EventDispatcher::getInstance()->setDirtyForNode(this); } void Node::addChild(Node *child, int zOrder) @@ -936,7 +934,8 @@ void Node::onEnter() arrayMakeObjectsPerformSelector(_children, onEnter, Node*); this->resumeSchedulerAndActions(); - + EventDispatcher::getInstance()->resumeTarget(this); + _running = true; if (_scriptType != kScriptTypeNone) @@ -946,11 +945,6 @@ void Node::onEnter() ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } - - if (onEnterHook) - { - onEnterHook(); - } } void Node::onEnterTransitionDidFinish() @@ -966,20 +960,10 @@ void Node::onEnterTransitionDidFinish() ScriptEvent scriptEvent(kNodeEvent,(void*)&data); ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); } - - if (onEnterTransitionDidFinishHook) - { - onEnterTransitionDidFinishHook(); - } } void Node::onExitTransitionDidStart() { - if (onExitTransitionDidStartHook) - { - onExitTransitionDidStartHook(); - } - arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*); if (_scriptType != kScriptTypeNone) { @@ -992,10 +976,7 @@ void Node::onExitTransitionDidStart() void Node::onExit() { - if (onExitHook) - { - onExitHook(); - } + EventDispatcher::getInstance()->pauseTarget(this); this->pauseSchedulerAndActions(); @@ -1009,8 +990,6 @@ void Node::onExit() } arrayMakeObjectsPerformSelector(_children, onExit, Node*); - - removeAllEventListeners(); } void Node::setActionManager(ActionManager* actionManager) @@ -1363,28 +1342,6 @@ void Node::removeAllComponents() _componentContainer->removeAll(); } -void Node::associateEventListener(EventListener* listener) -{ - _eventlisteners.insert(listener); -} - -void Node::dissociateEventListener(EventListener* listener) -{ - _eventlisteners.erase(listener); -} - -void Node::removeAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - auto eventListenersCopy = _eventlisteners; - - for (auto& listener : eventListenersCopy) - { - dispatcher->removeEventListener(listener); - } -} - #ifdef CC_USE_PHYSICS void Node::setPhysicsBody(PhysicsBody* body) { diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index b5c42f2301..fcc38b23b5 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -928,7 +928,6 @@ public: * @lua NA */ virtual void onEnter(); - std::function onEnterHook; /** Event callback that is invoked when the Node enters in the 'stage'. * If the Node enters the 'stage' with a transition, this event is called when the transition finishes. @@ -937,7 +936,6 @@ public: * @lua NA */ virtual void onEnterTransitionDidFinish(); - std::function onEnterTransitionDidFinishHook; /** * Event callback that is invoked every time the Node leaves the 'stage'. @@ -948,7 +946,6 @@ public: * @lua NA */ virtual void onExit(); - std::function onExitHook; /** * Event callback that is called every time the Node leaves the 'stage'. @@ -957,7 +954,6 @@ public: * @lua NA */ virtual void onExitTransitionDidStart(); - std::function onExitTransitionDidStartHook; /// @} end of event callbacks. @@ -1401,23 +1397,9 @@ public: virtual void updatePhysicsTransform(); #endif - - -private: - friend class Director; - friend class EventDispatcher; - - void associateEventListener(EventListener* listener); - void dissociateEventListener(EventListener* listener); - - std::set _eventlisteners; - int _eventPriority; protected: - /// Removes all event listeners that associated with this node. - void removeAllEventListeners(); - /// lazy allocs void childrenAlloc(void); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index a7dbdc14d1..788fdd221c 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -144,7 +144,6 @@ void ParticleBatchNode::visit() transform(); draw(); - updateEventPriorityIndex(); if ( _grid && _grid->isActive()) { diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 5bace186cf..d76c258f87 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -465,7 +465,6 @@ void RenderTexture::visit() transform(); _sprite->visit(); draw(); - updateEventPriorityIndex(); if (_grid && _grid->isActive()) { diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index b4be9bd045..195b5fa8eb 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -158,7 +158,6 @@ void SpriteBatchNode::visit(void) transform(); draw(); - updateEventPriorityIndex(); if (_grid && _grid->isActive()) { diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 9b1e943019..094e584e97 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -247,7 +247,7 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y } touchEvent._eventCode = EventTouch::EventCode::BEGAN; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) @@ -294,7 +294,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys } touchEvent._eventCode = EventTouch::EventCode::MOVED; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) @@ -347,7 +347,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } touchEvent._eventCode = eventCode; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); for (auto& touch : touchEvent._touches) { diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 5885cbbd25..5c3b54e3df 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -624,7 +624,6 @@ void Armature::visit() transform(); sortAllChildren(); draw(); - updateEventPriorityIndex(); // reset for next frame _orderOfArrival = 0; diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 0c6f7598ae..7ef2188fb8 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -81,7 +81,6 @@ void BatchNode::visit() transform(); sortAllChildren(); draw(); - updateEventPriorityIndex(); // reset for next frame _orderOfArrival = 0; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index e5f4c0503e..ecc17ef0e7 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -109,16 +109,14 @@ bool ScrollView::initWithViewSize(Size size, Node *container/* = NULL*/) this->setViewSize(size); - this->onEnterHook = [this]() { - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchOneByOne::create(); - listener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this); - listener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this); - listener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); - - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); + + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); _touches.reserve(EventTouch::MAX_TOUCHES); @@ -578,7 +576,6 @@ void ScrollView::visit() // this draw this->draw(); - updateEventPriorityIndex(); // draw children zOrder >= 0 for( ; i < _children->count(); i++ ) @@ -591,7 +588,6 @@ void ScrollView::visit() else { this->draw(); - updateEventPriorityIndex(); } this->afterDraw(); diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index e0e3562a54..0e7a14ffdf 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1375,7 +1375,7 @@ void ActionStacked::onEnter() this->centerSprites(0); - this->setTouchEnabled(true); +//cjh this->setTouchEnabled(true); auto s = Director::getInstance()->getWinSize(); this->addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index 4c958bebaa..9614180fb2 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -33,6 +33,7 @@ MenuLayer::MenuLayer(void) MenuLayer::~MenuLayer(void) { + EventDispatcher::getInstance()->removeEventListener(_touchListener); } MenuLayer* MenuLayer::menuWithEntryID(int entryId) @@ -52,9 +53,6 @@ bool MenuLayer::initWithEntryID(int entryId) m_entryID = entryId; - setTouchEnabled( true ); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - Box2DView* view = Box2DView::viewWithEntryID( entryId ); addChild(view, 0, kTagBox2DNode); view->setScale(15); @@ -81,18 +79,17 @@ bool MenuLayer::initWithEntryID(int entryId) addChild(menu, 1); - // Removes touch event listener - EventDispatcher::getInstance()->removeEventListener(_touchListener); - // Adds touch event listener - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(MenuLayer::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(MenuLayer::onTouchMoved, this); EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, 1); + _touchListener = listener; + return true; } @@ -180,19 +177,16 @@ Box2DView* Box2DView::viewWithEntryID(int entryId) bool Box2DView::initWithEntryID(int entryId) { // setIsAccelerometerEnabled( true ); - setTouchEnabled( true ); +// FIXME cjh: setTouchEnabled( true ); schedule( schedule_selector(Box2DView::tick) ); m_entry = g_testEntries + entryId; m_test = m_entry->createFcn(); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - // Removes Touch Event Listener - EventDispatcher::getInstance()->removeEventListener(_touchListener); // Adds Touch Event Listener - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(Box2DView::onTouchBegan, this); @@ -232,6 +226,8 @@ void Box2DView::draw() Box2DView::~Box2DView() { + // Removes Touch Event Listener + EventDispatcher::getInstance()->removeEventListener(_touchListener); delete m_test; } // diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h index 5f3e785535..681e44de6c 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h @@ -7,7 +7,7 @@ class MenuLayer : public Layer { int m_entryID; - + EventListenerTouchOneByOne* _touchListener; public: MenuLayer(void); virtual ~MenuLayer(void); @@ -30,6 +30,7 @@ struct TestEntry; class Test; class Box2DView : public Layer { + EventListenerTouchOneByOne* _touchListener; TestEntry* m_entry; Test* m_test; int m_entryID; diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index a86859ebb1..9eb6d6ab5c 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,11 +20,9 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f); @@ -63,11 +61,9 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp index 337d9b1006..76ab5b3b31 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp @@ -30,13 +30,11 @@ bool Bug914Layer::init() // Apple recommends to re-assign "self" with the "super" return value if (BugsTestBaseLayer::init()) { - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchAllAtOnce::create(); - listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); - listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp index 237b12077c..7f28de8df8 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp @@ -67,7 +67,7 @@ void BugsTestMainLayer::onEnter() _itmeMenu->setPosition(s_tCurPos); addChild(_itmeMenu); - setTouchEnabled(true); +//cjh setTouchEnabled(true); } void BugsTestMainLayer::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index f617ee501b..46cae7762e 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -21,8 +21,8 @@ ChipmunkTestLayer::ChipmunkTestLayer() { #if CC_ENABLE_CHIPMUNK_INTEGRATION // enable events - setTouchEnabled(true); - setAccelerometerEnabled(true); +//FIXME: setTouchEnabled(true); +// setAccelerometerEnabled(true); // title auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h index 33ae31cee7..3480f0314a 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h @@ -24,8 +24,8 @@ public: void addNewSpriteAtPosition(Point p); void update(float dt); void toggleDebugCallback(Object* sender); - virtual void onTouchesEnded(const std::vector& touches, Event* event) override; - virtual void onAcceleration(Acceleration* acc, Event* event) override; + virtual void onTouchesEnded(const std::vector& touches, Event* event); + virtual void onAcceleration(Acceleration* acc, Event* event); private: Texture2D* _spriteTexture; // weak ref diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp index 5a87658f35..408188925f 100644 --- a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp @@ -17,13 +17,11 @@ void ClickAndMoveTestScene::runThisTest() MainLayer::MainLayer() { - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchOneByOne::create(); - listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this); - listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this); + listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto sprite = Sprite::create(s_pathGrossini); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index fcde7712ad..56ad34de68 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -449,12 +449,10 @@ void HoleDemo::setup() this->addChild(_outerClipper); - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchAllAtOnce::create(); - listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void HoleDemo::pokeHoleAtPoint(Point point) @@ -531,14 +529,12 @@ void ScrollViewDemo::setup() _scrolling = false; - this->onEnterHook = [this](){ - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchAllAtOnce::create(); - listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); - listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); - listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - }; + auto dispatcher = EventDispatcher::getInstance(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp index 207a26a2ab..9589cde586 100644 --- a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp @@ -65,7 +65,7 @@ private: // Director::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, 100, true); // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(Button::onTouchBegan, this); @@ -238,7 +238,7 @@ _sliderMusicVolume(NULL) // "stop all effects" // }; - setTouchEnabled(true); +//cjh setTouchEnabled(true); // preload background music and effect SimpleAudioEngine::getInstance()->preloadBackgroundMusic( MUSIC_FILE ); diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp index b8cfc653b7..83945cd581 100644 --- a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp @@ -9,7 +9,7 @@ CurlTest::CurlTest() addChild(label, 0); label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y-50) ); - setTouchEnabled(true); +//FIXME cjh: setTouchEnabled(true); // create a label to display the tip string _label = LabelTTF::create("Touch the screen to connect", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h index da0290d0bf..9688d03e38 100644 --- a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h +++ b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h @@ -10,7 +10,7 @@ public: CurlTest(); ~CurlTest(); - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event) override; + virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); private: cocos2d::LabelTTF* _label; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 66eb20472b..eaf14546be 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -477,7 +477,7 @@ void TestAnimationEvent::callback2() void TestParticleDisplay::onEnter() { ArmatureTestLayer::onEnter(); - setTouchEnabled(true); +//FIXME cjh: setTouchEnabled(true); animationID = 0; @@ -534,7 +534,7 @@ void TestParticleDisplay::onTouchesEnded(const std::vector& touches, Eve void TestUseMutiplePicture::onEnter() { ArmatureTestLayer::onEnter(); - setTouchEnabled(true); +//cjh setTouchEnabled(true); displayIndex = 0; @@ -935,7 +935,7 @@ std::string TestAnchorPoint::title() void TestArmatureNesting::onEnter() { ArmatureTestLayer::onEnter(); - setTouchEnabled(true); +//cjh setTouchEnabled(true); armature = Armature::create("cyborg"); armature->getAnimation()->playByIndex(1); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 625fdddf88..ccd07d1d72 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -138,7 +138,7 @@ class TestUseMutiplePicture : public ArmatureTestLayer virtual void onExit(); virtual std::string title(); virtual std::string subtitle(); - virtual void onTouchesEnded(const std::vector& touches, Event* event) override; + virtual void onTouchesEnded(const std::vector& touches, Event* event); int displayIndex; cocostudio::Armature *armature; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp index 0c802b3f97..7c95239cfa 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -118,7 +118,7 @@ void ExtensionsMainLayer::onEnter() _itemMenu->addChild(pItem, kItemTagBasic + i); } - setTouchEnabled(true); +//cjh setTouchEnabled(true); addChild(_itemMenu); } diff --git a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp index 9e2fd40647..7140a44e8a 100644 --- a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp @@ -7,7 +7,7 @@ KeyboardTest::KeyboardTest() addChild(label, 0); label->setPosition( Point(s.width/2, s.height-50) ); - setKeyboardEnabled(true); +//cjh setKeyboardEnabled(true); // create a label to display the tip string _label = LabelTTF::create("Please press any key and see console log...", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp index 7cdbebbc6e..5bda6cccf2 100644 --- a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp @@ -7,7 +7,7 @@ KeypadTest::KeypadTest() addChild(label, 0); label->setPosition( Point(s.width/2, s.height-50) ); - setKeyboardEnabled(true); +//cjh setKeyboardEnabled(true); // create a label to display the tip string _label = LabelTTF::create("Please press any key...", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h index 760ab8eb01..e525511e4a 100644 --- a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h +++ b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h @@ -10,7 +10,7 @@ public: KeypadTest(); ~KeypadTest(); - virtual void onKeyReleased(EventKeyboard::KeyCode keycode, Event* event) override; + virtual void onKeyReleased(EventKeyboard::KeyCode keycode, Event* event); private: LabelTTF* _label; diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index 36b434f139..52fc92c2e4 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -1135,7 +1135,7 @@ static float alignmentItemPadding = 50; static float menuItemPaddingCenter = 50; BitmapFontMultiLineAlignment::BitmapFontMultiLineAlignment() { - this->setTouchEnabled(true); +//cjh this->setTouchEnabled(true); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index d822776e62..47173da112 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -650,7 +650,7 @@ static float menuItemPaddingCenter = 50; LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() { - this->setTouchEnabled(true); +//cjh this->setTouchEnabled(true); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index 26175b6e3f..e27b82cf16 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -449,7 +449,7 @@ void LayerTest1::onEnter() { LayerTest::onEnter(); - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto s = Director::getInstance()->getWinSize(); auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); @@ -590,7 +590,7 @@ LayerGradientTest::LayerGradientTest() auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Point(0.9f, 0.9f)); addChild(layer1, 0, kTagLayer); - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto label1 = LabelTTF::create("Compressed Interpolation: Enabled", "Marker Felt", 26); auto label2 = LabelTTF::create("Compressed Interpolation: Disabled", "Marker Felt", 26); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index 8a5809ee6b..a61f15225b 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -25,8 +25,8 @@ enum { //------------------------------------------------------------------ MenuLayerMainMenu::MenuLayerMainMenu() { - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); +//cjh setTouchEnabled(true); +// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); // Font Item auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); @@ -532,8 +532,8 @@ BugsTest::BugsTest() void BugsTest::issue1410MenuCallback(Object *sender) { auto menu = static_cast( static_cast(sender)->getParent() ); - menu->setTouchEnabled(false); - menu->setTouchEnabled(true); +//cjh menu->setTouchEnabled(false); +// menu->setTouchEnabled(true); log("NO CRASHES"); } @@ -541,8 +541,8 @@ void BugsTest::issue1410MenuCallback(Object *sender) void BugsTest::issue1410v2MenuCallback(cocos2d::Object *pSender) { auto menu = static_cast( static_cast(pSender)->getParent() ); - menu->setTouchEnabled(true); - menu->setTouchEnabled(false); +//cjh menu->setTouchEnabled(true); +// menu->setTouchEnabled(false); log("NO CRASHES. AND MENU SHOULD STOP WORKING"); } @@ -571,11 +571,11 @@ RemoveMenuItemWhenMove::RemoveMenuItemWhenMove() menu->setPosition(Point(s.width/2, s.height/2)); - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); +//cjh setTouchEnabled(true); +// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); // Register Touch Event - _touchListener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(false); _touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h index f023871835..41072151c5 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h @@ -113,6 +113,7 @@ public: private: MenuItemFont *item; + EventListenerTouchOneByOne* _touchListener; }; diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp index dcbb3a3beb..7c4fe4340f 100644 --- a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -121,7 +121,7 @@ void MotionStreakTest2::onEnter() { MotionStreakTest::onEnter(); - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp index 9ef9656951..f92fa93299 100644 --- a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp @@ -56,7 +56,7 @@ bool MutiTouchTestLayer::init() { if (Layer::init()) { - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto title = LabelTTF::create("Please touch the screen!", "", 24); title->setPosition(VisibleRect::top()+Point(0, -40)); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 60a2f909a9..797f042ca7 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -141,7 +141,7 @@ void TouchableSpriteTest::onEnter() sprite2->addChild(sprite3, 1); // Make sprite1 touchable - auto listener1 = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); listener1->onTouchBegan = [](Touch* touch, Event* event){ @@ -243,7 +243,7 @@ public: auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [=](Touch* touch, Event* event){ @@ -348,7 +348,7 @@ void RemoveListenerWhenDispatching::onEnter() addChild(sprite1, 10); // Make sprite1 touchable - auto listener1 = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); setUserObject(listener1); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 8689ee9f99..db7f53d7c2 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -723,7 +723,7 @@ std::string CameraCenterTest::subtitle() //------------------------------------------------------------------ ConvertToNode::ConvertToNode() { - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto s = Director::getInstance()->getWinSize(); auto rotate = RotateBy::create(10, 360); diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp index cfa80084b9..bc2a128603 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp @@ -87,7 +87,7 @@ std::string Parallax1::title() Parallax2::Parallax2() { - setTouchEnabled( true ); +//cjh setTouchEnabled( true ); // Top Layer, a simple image auto cocosImage = Sprite::create(s_Power); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index bd4b98dea6..414c915135 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1068,7 +1068,7 @@ void ParticleDemo::onEnter(void) _emitter = NULL; - setTouchEnabled( true ); +//cjh setTouchEnabled( true ); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp index 60c5341463..a928a3bd23 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp @@ -119,9 +119,9 @@ std::string TouchesMainScene::title() void TouchesPerformTest1::onEnter() { TouchesMainScene::onEnter(); - setTouchEnabled(true); - setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - setSwallowsTouches(true); +//cjh setTouchEnabled(true); +// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); +// setSwallowsTouches(true); } std::string TouchesPerformTest1::title() @@ -158,7 +158,7 @@ void TouchesPerformTest1::onTouchCancelled(Touch* touch, Event* event) void TouchesPerformTest2::onEnter() { TouchesMainScene::onEnter(); - setTouchEnabled(true); +//cjh setTouchEnabled(true); } std::string TouchesPerformTest2::title() @@ -231,8 +231,8 @@ void TouchesPerformTest3::onEnter() { int zorder = rand() % TOUCHABLE_NODE_NUM; auto layer = new TouchableLayer(); - layer->setTouchEnabled(true); - layer->setTouchMode(Touch::DispatchMode::ONE_BY_ONE); +//cjh layer->setTouchEnabled(true); +// layer->setTouchMode(Touch::DispatchMode::ONE_BY_ONE); addChild(layer, zorder); layer->release(); } @@ -260,7 +260,7 @@ void TouchesPerformTest3::onEnter() { CC_PROFILER_START(TOUCH_PROFILER_NAME); - dispatcher->dispatchEvent(&event, false); + dispatcher->dispatchEvent(&event); CC_PROFILER_STOP(TOUCH_PROFILER_NAME); } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h index 47029a3bc6..5cb4d35ad9 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h @@ -36,10 +36,10 @@ public: virtual void onEnter() override; virtual std::string title() override; - virtual bool onTouchBegan(Touch* touch, Event* event) override; - virtual void onTouchMoved(Touch* touch, Event* event) override; - virtual void onTouchEnded(Touch* touch, Event* event) override; - virtual void onTouchCancelled(Touch* touch, Event* event) override; + virtual bool onTouchBegan(Touch* touch, Event* event) ; + virtual void onTouchMoved(Touch* touch, Event* event) ; + virtual void onTouchEnded(Touch* touch, Event* event) ; + virtual void onTouchCancelled(Touch* touch, Event* event) ; }; class TouchesPerformTest2 : public TouchesMainScene @@ -53,10 +53,10 @@ public: virtual void onEnter() override; virtual std::string title() override; - void onTouchesBegan(const std::vector& touches, Event* event) override; - void onTouchesMoved(const std::vector& touches, Event* event) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; - void onTouchesCancelled(const std::vector& touches, Event* event) override; + void onTouchesBegan(const std::vector& touches, Event* event) ; + void onTouchesMoved(const std::vector& touches, Event* event) ; + void onTouchesEnded(const std::vector& touches, Event* event) ; + void onTouchesCancelled(const std::vector& touches, Event* event) ; }; class TouchesPerformTest3 : public PerformBasicLayer diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f0ceb3553c..4c56986746 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -197,8 +197,8 @@ void PhysicsDemoClickAdd::onEnter() PhysicsDemo::onEnter(); #ifdef CC_USE_PHYSICS - setTouchEnabled(true); - setAccelerometerEnabled(true); +//cjh setTouchEnabled(true); +// setAccelerometerEnabled(true); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 433415f677..1669b78c1f 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -111,7 +111,7 @@ RenderTextureSave::RenderTextureSave() _brush->retain(); _brush->setColor(Color3B::RED); _brush->setOpacity(20); - this->setTouchEnabled(true); +//cjh this->setTouchEnabled(true); // Save Image menu MenuItemFont::setFontSize(16); @@ -296,7 +296,7 @@ void RenderTextureScene::runThisTest() RenderTextureZbuffer::RenderTextureZbuffer() { - this->setTouchEnabled(true); +//cjh this->setTouchEnabled(true); auto size = Director::getInstance()->getWinSize(); auto label = LabelTTF::create("vertexZ = 50", "Marker Felt", 64); label->setPosition(Point(size.width / 2, size.height * 0.25f)); @@ -627,7 +627,7 @@ void SpriteRenderTextureBug::SimpleSprite::draw() SpriteRenderTextureBug::SpriteRenderTextureBug() { - setTouchEnabled(true); +//cjh setTouchEnabled(true); auto s = Director::getInstance()->getWinSize(); addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 16b0471301..a3d466373a 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -b17d2ec91cd40aaf09376a62f38f97ca3f7da2c7 \ No newline at end of file +4701ba8fb99f70629c5575dcf6fb3536543ac0b6 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index 3392a3e9f8..1645d017d8 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -126,10 +126,10 @@ void TextInputTest::onEnter() KeyboardNotificationLayer::KeyboardNotificationLayer() : _trackNode(0) { - setTouchEnabled(true); +//cjh setTouchEnabled(true); // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchEnded, this); diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 761afa4a71..7be2b29c32 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -1430,7 +1430,7 @@ Layer* restartTileMapAction() TileDemo::TileDemo(void) : BaseTest() { - setTouchEnabled( true ); +//cjh setTouchEnabled( true ); } TileDemo::~TileDemo(void) diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp b/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp index 2e3720d10c..e168d7a1bc 100644 --- a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp +++ b/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp @@ -38,7 +38,7 @@ void Paddle::onEnter() Sprite::onEnter(); // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(Paddle::onTouchBegan, this); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index f78fb2c9af..c7b03f1acf 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -120,12 +120,12 @@ TestController::TestController() _itemMenu->setPosition(s_tCurPos); addChild(_itemMenu); - setTouchEnabled(true); +//cjh setTouchEnabled(true); addChild(menu, 1); // Register Touch Event - auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(TestController::onTouchBegan, this); From 9ed263056c126bf6efc6dc46ddd8154e48244771 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 16:14:03 +0800 Subject: [PATCH 223/557] Use eventDispatcher to dispatch event. Remove controller codes in Layer. --- cocos/2d/CCEventDispatcher.cpp | 159 +++++++++--------- cocos/2d/CCEventListenerTouch.h | 1 - cocos/2d/CCMenu.h | 10 +- .../Cpp/SimpleGame/Classes/HelloWorldScene.h | 2 +- .../Classes/ActionsTest/ActionsTest.cpp | 4 +- .../TestCpp/Classes/ActionsTest/ActionsTest.h | 2 +- .../Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h | 2 +- .../Classes/Box2DTestBed/Box2dView.cpp | 3 - .../TestCpp/Classes/Box2DTestBed/Box2dView.h | 10 +- .../Cpp/TestCpp/Classes/BugsTest/Bug-914.h | 4 +- .../Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp | 7 +- .../Cpp/TestCpp/Classes/BugsTest/BugsTest.h | 4 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 9 +- .../Classes/ChipmunkTest/ChipmunkTest.h | 2 +- .../ClickAndMoveTest/ClickAndMoveTest.h | 4 +- .../ClippingNodeTest/ClippingNodeTest.h | 8 +- .../CocosDenshionTest/CocosDenshionTest.cpp | 13 -- .../Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp | 4 +- .../Cpp/TestCpp/Classes/CurlTest/CurlTest.h | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 15 +- .../CocoStudioArmatureTest/ArmatureScene.h | 6 +- .../PlayerController.h | 2 +- .../Classes/ExtensionsTest/ExtensionsTest.cpp | 6 +- .../Classes/ExtensionsTest/ExtensionsTest.h | 4 +- .../Classes/KeyboardTest/KeyboardTest.cpp | 8 +- .../TestCpp/Classes/KeypadTest/KeypadTest.cpp | 7 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 9 +- .../Cpp/TestCpp/Classes/LabelTest/LabelTest.h | 6 +- .../Classes/LabelTest/LabelTestNew.cpp | 8 +- .../TestCpp/Classes/LabelTest/LabelTestNew.h | 6 +- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 11 +- .../Cpp/TestCpp/Classes/LayerTest/LayerTest.h | 8 +- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 20 ++- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.h | 12 +- .../MotionStreakTest/MotionStreakTest.cpp | 6 +- .../Classes/MutiTouchTest/MutiTouchTest.cpp | 6 +- .../Classes/MutiTouchTest/MutiTouchTest.h | 1 - .../NewEventDispatcherTest.cpp | 87 +++++++++- .../NewEventDispatcherTest.h | 12 ++ .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 5 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 2 +- .../Classes/ParallaxTest/ParallaxTest.cpp | 4 +- .../Classes/ParallaxTest/ParallaxTest.h | 2 +- .../Classes/ParticleTest/ParticleTest.cpp | 6 +- .../Classes/ParticleTest/ParticleTest.h | 6 +- .../PerformanceTouchesTest.cpp | 41 +++-- .../PerformanceTest/PerformanceTouchesTest.h | 8 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 9 +- .../RenderTextureTest/RenderTextureTest.cpp | 18 +- .../RenderTextureTest/RenderTextureTest.h | 10 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../TestCpp/Classes/SpriteTest/SpriteTest.h | 2 +- .../Classes/TextInputTest/TextInputTest.cpp | 4 - .../Classes/TextInputTest/TextInputTest.h | 1 - .../Classes/TileMapTest/TileMapTest.cpp | 4 +- .../TestCpp/Classes/TileMapTest/TileMapTest.h | 2 +- samples/Cpp/TestCpp/Classes/controller.cpp | 2 - 57 files changed, 392 insertions(+), 226 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 7933a5edd6..05a2a66ddf 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -61,85 +61,6 @@ NS_CC_BEGIN static EventDispatcher* g_instance = nullptr; static int s_eventPriorityIndex = 0; -void EventDispatcher::visitTarget(Node* node) -{ - // Reset priority index - s_eventPriorityIndex = 0; - _nodePriorityMap.clear(); - - int i = 0; - Array* children = node->getChildren(); - int childrenCount = children ? children->count() : 0; - - if(childrenCount > 0) - { - - Node* child = nullptr; - // visit children zOrder < 0 - for( ; i < childrenCount; i++ ) - { - child = static_cast( children->getObjectAtIndex(i) ); - - if ( child && child->getZOrder() < 0 ) - visitTarget(child); - else - break; - } - - _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); - - for( ; i < childrenCount; i++ ) - { - child = static_cast( children->getObjectAtIndex(i) ); - if (child) - visitTarget(child); - } - } - else - { - _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); - } -} - -void EventDispatcher::pauseTarget(Node* node) -{ - auto listenerIter = _nodeListenersMap.find(node); - if (listenerIter != _nodeListenersMap.end()) - { - auto listeners = listenerIter->second; - for (auto& l : *listeners) - { - l->_paused = true; - } - } -} - -void EventDispatcher::resumeTarget(Node* node) -{ - auto listenerIter = _nodeListenersMap.find(node); - if (listenerIter != _nodeListenersMap.end()) - { - auto listeners = listenerIter->second; - for (auto& l : *listeners) - { - l->_paused = false; - } - } -} - -void EventDispatcher::cleanTarget(Node* node) -{ - auto listenerIter = _nodeListenersMap.find(node); - if (listenerIter != _nodeListenersMap.end()) - { - auto listeners = listenerIter->second; - for (auto& l : *listeners) - { - removeEventListener(l); - } - } -} - EventDispatcher::EventListenerVector::EventListenerVector() : _sceneGraphListeners(nullptr) , _fixedListeners(nullptr) @@ -239,6 +160,85 @@ void EventDispatcher::destroyInstance() CC_SAFE_DELETE(g_instance); } +void EventDispatcher::visitTarget(Node* node) +{ + // Reset priority index + s_eventPriorityIndex = 0; + _nodePriorityMap.clear(); + + int i = 0; + Array* children = node->getChildren(); + int childrenCount = children ? children->count() : 0; + + if(childrenCount > 0) + { + + Node* child = nullptr; + // visit children zOrder < 0 + for( ; i < childrenCount; i++ ) + { + child = static_cast( children->getObjectAtIndex(i) ); + + if ( child && child->getZOrder() < 0 ) + visitTarget(child); + else + break; + } + + _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); + + for( ; i < childrenCount; i++ ) + { + child = static_cast( children->getObjectAtIndex(i) ); + if (child) + visitTarget(child); + } + } + else + { + _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); + } +} + +void EventDispatcher::pauseTarget(Node* node) +{ + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + l->_paused = true; + } + } +} + +void EventDispatcher::resumeTarget(Node* node) +{ + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + l->_paused = false; + } + } +} + +void EventDispatcher::cleanTarget(Node* node) +{ + auto listenerIter = _nodeListenersMap.find(node); + if (listenerIter != _nodeListenersMap.end()) + { + auto listeners = listenerIter->second; + for (auto& l : *listeners) + { + removeEventListener(l); + } + } +} + void EventDispatcher::associateNodeAndEventListener(Node* node, EventListener* listener) { std::vector* listeners = nullptr; @@ -635,7 +635,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) { if (listener->onTouchBegan) { - CCLOG("onTouchBegan..."); isClaimed = listener->onTouchBegan(*touchesIter, event); if (isClaimed && listener->_isRegistered) { diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index d34de1b237..09e6e6fe0c 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -33,7 +33,6 @@ NS_CC_BEGIN - class EventListenerTouchOneByOne : public EventListener { public: diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index a735d138db..64c275841a 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -112,6 +112,11 @@ public: virtual bool isEnabled() const { return _enabled; } virtual void setEnabled(bool value) { _enabled = value; }; + virtual bool onTouchBegan(Touch* touch, Event* event); + virtual void onTouchEnded(Touch* touch, Event* event); + virtual void onTouchCancelled(Touch* touch, Event* event); + virtual void onTouchMoved(Touch* touch, Event* event); + // overrides virtual void removeChild(Node* child, bool cleanup) override; @@ -119,11 +124,6 @@ public: virtual void addChild(Node * child, int zOrder) override; virtual void addChild(Node * child, int zOrder, int tag) override; - virtual bool onTouchBegan(Touch* touch, Event* event); - virtual void onTouchEnded(Touch* touch, Event* event); - virtual void onTouchCancelled(Touch* touch, Event* event); - virtual void onTouchMoved(Touch* touch, Event* event); - virtual void onEnter() override; virtual void onExit() override; virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);} diff --git a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h index a5f2478391..279f2c4399 100644 --- a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h +++ b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h @@ -30,7 +30,7 @@ public: void updateGame(float dt); - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event* event) override; + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event) override; protected: diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 0e7a14ffdf..c41f06c377 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1375,7 +1375,9 @@ void ActionStacked::onEnter() this->centerSprites(0); -//cjh this->setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(ActionStacked::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); this->addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h index c064ee3436..f67907ceba 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h @@ -305,7 +305,7 @@ public: virtual std::string subtitle(); virtual void addNewSpriteWithCoords(Point p); virtual void runActionsInSprite(Sprite* sprite); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); }; class ActionMoveStacked : public ActionStacked diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h index 480d572f7a..5c22274ba3 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h @@ -21,7 +21,7 @@ public: void addNewSpriteAtPosition(Point p); void update(float dt); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); //CREATE_NODE(Box2DTestLayer); } ; diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index 9614180fb2..0cfbabd90c 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -176,9 +176,6 @@ Box2DView* Box2DView::viewWithEntryID(int entryId) bool Box2DView::initWithEntryID(int entryId) { -// setIsAccelerometerEnabled( true ); -// FIXME cjh: setTouchEnabled( true ); - schedule( schedule_selector(Box2DView::tick) ); m_entry = g_testEntries + entryId; diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h index 681e44de6c..d2afa656d6 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h @@ -19,8 +19,8 @@ public: void backCallback(Object* sender); - virtual bool onTouchBegan(Touch* touch, Event* event); - virtual void onTouchMoved(Touch* touch, Event* event); + bool onTouchBegan(Touch* touch, Event* event); + void onTouchMoved(Touch* touch, Event* event); public: static MenuLayer* menuWithEntryID(int entryId); @@ -44,9 +44,9 @@ public: void draw(); // virtual void registerWithTouchDispatcher(); - virtual bool onTouchBegan(Touch* touch, Event* event); - virtual void onTouchMoved(Touch* touch, Event* event); - virtual void onTouchEnded(Touch* touch, Event* event); + bool onTouchBegan(Touch* touch, Event* event); + void onTouchMoved(Touch* touch, Event* event); + void onTouchEnded(Touch* touch, Event* event); //virtual void accelerometer(UIAccelerometer* accelerometer, Acceleration* acceleration); static Box2DView* viewWithEntryID(int entryId); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h index 41ee2c25c8..d6af9092fe 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h @@ -9,8 +9,8 @@ public: static Scene* scene(); virtual bool init(); - virtual void onTouchesMoved(const std::vector& touches, Event * event); - virtual void onTouchesBegan(const std::vector& touches, Event * event); + void onTouchesMoved(const std::vector& touches, Event * event); + void onTouchesBegan(const std::vector& touches, Event * event); void restart(Object* sender); CREATE_FUNC(Bug914Layer); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp index 7f28de8df8..1d81217bbb 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp @@ -67,7 +67,12 @@ void BugsTestMainLayer::onEnter() _itmeMenu->setPosition(s_tCurPos); addChild(_itmeMenu); -//cjh setTouchEnabled(true); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(BugsTestMainLayer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(BugsTestMainLayer::onTouchesMoved, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } void BugsTestMainLayer::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h index 88de62b0a1..06e6fb535c 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h @@ -8,8 +8,8 @@ class BugsTestMainLayer : public Layer public: virtual void onEnter(); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector&touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector&touches, Event *event); protected: Point _beginPos; diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 46cae7762e..bb3ef0e12f 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -21,9 +21,14 @@ ChipmunkTestLayer::ChipmunkTestLayer() { #if CC_ENABLE_CHIPMUNK_INTEGRATION // enable events -//FIXME: setTouchEnabled(true); -// setAccelerometerEnabled(true); + auto touchListener = EventListenerTouchAllAtOnce::create(); + touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(accListener, this); + // title auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36); label->setPosition(Point( VisibleRect::center().x, VisibleRect::top().y - 30)); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h index 3480f0314a..046f53d3fa 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h @@ -24,7 +24,7 @@ public: void addNewSpriteAtPosition(Point p); void update(float dt); void toggleDebugCallback(Object* sender); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); virtual void onAcceleration(Acceleration* acc, Event* event); private: diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h index 7cb8f7a3b4..833ced291e 100644 --- a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h +++ b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h @@ -13,8 +13,8 @@ class MainLayer : public Layer { public: MainLayer(); - virtual bool onTouchBegan(Touch* touch, Event *event); - virtual void onTouchEnded(Touch* touch, Event *event); + bool onTouchBegan(Touch* touch, Event *event); + void onTouchEnded(Touch* touch, Event *event); }; #endif diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h index 0cb0c21d6d..042e51ddf6 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h @@ -98,7 +98,7 @@ public: virtual std::string title(); virtual std::string subtitle(); void pokeHoleAtPoint(Point point); - virtual void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); private: ClippingNode* _outerClipper; Node* _holes; @@ -111,9 +111,9 @@ public: virtual std::string title(); virtual std::string subtitle(); virtual void setup(); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); private: bool _scrolling; Point _lastPoint; diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp index 9589cde586..e83cb001f1 100644 --- a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp @@ -227,19 +227,6 @@ _sliderMusicVolume(NULL) addSliders(); schedule(schedule_selector(CocosDenshionTest::updateVolumes)); -// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); - -// std::string testItems[] = { -// "unload effect", -// "pause effect", -// "resume effect", -// "pause all effects", -// "resume all effects", -// "stop all effects" -// }; - -//cjh setTouchEnabled(true); - // preload background music and effect SimpleAudioEngine::getInstance()->preloadBackgroundMusic( MUSIC_FILE ); SimpleAudioEngine::getInstance()->preloadEffect( EFFECT_FILE ); diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp index 83945cd581..f3ad65db63 100644 --- a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp @@ -9,7 +9,9 @@ CurlTest::CurlTest() addChild(label, 0); label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y-50) ); -//FIXME cjh: setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(CurlTest::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); // create a label to display the tip string _label = LabelTTF::create("Touch the screen to connect", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h index 9688d03e38..131e3b330a 100644 --- a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h +++ b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h @@ -10,7 +10,7 @@ public: CurlTest(); ~CurlTest(); - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); private: cocos2d::LabelTTF* _label; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index eaf14546be..fef387ac01 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -477,7 +477,10 @@ void TestAnimationEvent::callback2() void TestParticleDisplay::onEnter() { ArmatureTestLayer::onEnter(); -//FIXME cjh: setTouchEnabled(true); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestParticleDisplay::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); animationID = 0; @@ -534,8 +537,11 @@ void TestParticleDisplay::onTouchesEnded(const std::vector& touches, Eve void TestUseMutiplePicture::onEnter() { ArmatureTestLayer::onEnter(); -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestUseMutiplePicture::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + displayIndex = 0; armature = Armature::create("Knight_f/Knight"); @@ -935,7 +941,10 @@ std::string TestAnchorPoint::title() void TestArmatureNesting::onEnter() { ArmatureTestLayer::onEnter(); -//cjh setTouchEnabled(true); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); armature = Armature::create("cyborg"); armature->getAnimation()->playByIndex(1); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index ccd07d1d72..51b47085b5 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -138,7 +138,7 @@ class TestUseMutiplePicture : public ArmatureTestLayer virtual void onExit(); virtual std::string title(); virtual std::string subtitle(); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); int displayIndex; cocostudio::Armature *armature; @@ -150,7 +150,7 @@ class TestParticleDisplay : public ArmatureTestLayer virtual void onExit(); virtual std::string title(); virtual std::string subtitle(); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); int animationID; cocostudio::Armature *armature; @@ -251,7 +251,7 @@ public: virtual void onEnter(); virtual void onExit(); virtual std::string title(); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); cocostudio::Armature *armature; int weaponIndex; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h index 671bdf7833..cc5233b539 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h @@ -13,7 +13,7 @@ protected: virtual ~PlayerController(void); public: - virtual void onTouchesEnded(const std::vector& touches, cocos2d::Event *event) override; + void onTouchesEnded(const std::vector& touches, cocos2d::Event *event) override; public: virtual bool init(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp index 7c95239cfa..5ba010f2a9 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -118,7 +118,11 @@ void ExtensionsMainLayer::onEnter() _itemMenu->addChild(pItem, kItemTagBasic + i); } -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesMoved, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); addChild(_itemMenu); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h index 0b392e4326..abf411fbce 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h @@ -8,8 +8,8 @@ class ExtensionsMainLayer : public Layer public: virtual void onEnter(); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); Point _beginPos; Menu* _itemMenu; diff --git a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp index 7140a44e8a..a8a164da01 100644 --- a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp @@ -7,8 +7,12 @@ KeyboardTest::KeyboardTest() addChild(label, 0); label->setPosition( Point(s.width/2, s.height-50) ); -//cjh setKeyboardEnabled(true); - + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = CC_CALLBACK_2(KeyboardTest::onKeyPressed, this); + listener->onKeyReleased = CC_CALLBACK_2(KeyboardTest::onKeyReleased, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + // create a label to display the tip string _label = LabelTTF::create("Please press any key and see console log...", "Arial", 22); _label->setPosition(Point(s.width / 2, s.height / 2)); diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp index 5bda6cccf2..c3191d5724 100644 --- a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp @@ -7,8 +7,11 @@ KeypadTest::KeypadTest() addChild(label, 0); label->setPosition( Point(s.width/2, s.height-50) ); -//cjh setKeyboardEnabled(true); - + auto listener = EventListenerKeyboard::create(); + listener->onKeyReleased = CC_CALLBACK_2(KeypadTest::onKeyReleased, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + // create a label to display the tip string _label = LabelTTF::create("Please press any key...", "Arial", 22); _label->setPosition(Point(s.width / 2, s.height / 2)); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index 52fc92c2e4..f95831074e 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -1135,8 +1135,13 @@ static float alignmentItemPadding = 50; static float menuItemPaddingCenter = 50; BitmapFontMultiLineAlignment::BitmapFontMultiLineAlignment() { -//cjh this->setTouchEnabled(true); - + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesEnded, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h index 49b121628d..87ff938c97 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h @@ -228,9 +228,9 @@ public: virtual std::string subtitle(); void stringChanged(Object *sender); void alignmentChanged(Object *sender); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); public: LabelBMFont *_labelShouldRetain; diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 47173da112..d6d5777ada 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -650,8 +650,12 @@ static float menuItemPaddingCenter = 50; LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() { -//cjh this->setTouchEnabled(true); - + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h index 1a8035b15f..d494858ffa 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h @@ -156,9 +156,9 @@ public: virtual std::string subtitle(); void stringChanged(Object *sender); void alignmentChanged(Object *sender); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); public: Label *_labelShouldRetain; diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index e27b82cf16..9fcc560cdf 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -449,7 +449,12 @@ void LayerTest1::onEnter() { LayerTest::onEnter(); -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(LayerTest1::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(LayerTest1::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(LayerTest1::onTouchesEnded, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); @@ -590,7 +595,9 @@ LayerGradientTest::LayerGradientTest() auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Point(0.9f, 0.9f)); addChild(layer1, 0, kTagLayer); -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesMoved = CC_CALLBACK_2(LayerGradientTest::onTouchesMoved, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto label1 = LabelTTF::create("Compressed Interpolation: Enabled", "Marker Felt", 26); auto label2 = LabelTTF::create("Compressed Interpolation: Disabled", "Marker Felt", 26); diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h index fbed1e7e91..dd381b001f 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h @@ -74,9 +74,9 @@ public: void updateSize(Point &touchLocation); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); }; class LayerTest2 : public LayerTest @@ -99,7 +99,7 @@ class LayerGradientTest : public LayerTest { public: LayerGradientTest(); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); virtual std::string title(); virtual std::string subtitle(); void toggleItem(cocos2d::Object *sender); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index a61f15225b..e1fb43cf39 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -25,8 +25,13 @@ enum { //------------------------------------------------------------------ MenuLayerMainMenu::MenuLayerMainMenu() { -//cjh setTouchEnabled(true); -// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this); + + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); // Font Item auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); @@ -532,8 +537,8 @@ BugsTest::BugsTest() void BugsTest::issue1410MenuCallback(Object *sender) { auto menu = static_cast( static_cast(sender)->getParent() ); -//cjh menu->setTouchEnabled(false); -// menu->setTouchEnabled(true); + menu->setEnabled(false); + menu->setEnabled(true); log("NO CRASHES"); } @@ -541,8 +546,8 @@ void BugsTest::issue1410MenuCallback(Object *sender) void BugsTest::issue1410v2MenuCallback(cocos2d::Object *pSender) { auto menu = static_cast( static_cast(pSender)->getParent() ); -//cjh menu->setTouchEnabled(true); -// menu->setTouchEnabled(false); + menu->setEnabled(true); + menu->setEnabled(false); log("NO CRASHES. AND MENU SHOULD STOP WORKING"); } @@ -571,9 +576,6 @@ RemoveMenuItemWhenMove::RemoveMenuItemWhenMove() menu->setPosition(Point(s.width/2, s.height/2)); -//cjh setTouchEnabled(true); -// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - // Register Touch Event _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(false); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h index 41072151c5..127f8c1688 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h @@ -14,10 +14,10 @@ public: ~MenuLayerMainMenu(); public: - virtual bool onTouchBegan(Touch *touch, Event * event); - virtual void onTouchEnded(Touch *touch, Event * event); - virtual void onTouchCancelled(Touch *touch, Event * event); - virtual void onTouchMoved(Touch *touch, Event * event); + bool onTouchBegan(Touch *touch, Event * event); + void onTouchEnded(Touch *touch, Event * event); + void onTouchCancelled(Touch *touch, Event * event); + void onTouchMoved(Touch *touch, Event * event); void allowTouches(float dt); void menuCallback(Object* sender); @@ -106,8 +106,8 @@ class RemoveMenuItemWhenMove : public Layer public: RemoveMenuItemWhenMove(); ~RemoveMenuItemWhenMove(); - virtual bool onTouchBegan(Touch *touch, Event *event); - virtual void onTouchMoved(Touch *touch, Event *event); + bool onTouchBegan(Touch *touch, Event *event); + void onTouchMoved(Touch *touch, Event *event); void goBack(Object *pSender); diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp index 7c4fe4340f..13a376ec29 100644 --- a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -121,8 +121,10 @@ void MotionStreakTest2::onEnter() { MotionStreakTest::onEnter(); -//cjh setTouchEnabled(true); - + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + auto s = Director::getInstance()->getWinSize(); // create the streak object and add it to the scene diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp index f92fa93299..42e6634de5 100644 --- a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp @@ -56,7 +56,11 @@ bool MutiTouchTestLayer::init() { if (Layer::init()) { -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto title = LabelTTF::create("Please touch the screen!", "", 24); title->setPosition(VisibleRect::top()+Point(0, -40)); diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h index 397f9ae276..91333d6493 100644 --- a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h +++ b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h @@ -8,7 +8,6 @@ class MutiTouchTestLayer : public Layer public: bool init(); -// virtual void registerWithTouchDispatcher(void); void onTouchesBegan(const std::vector& touches, cocos2d::Event *event); void onTouchesMoved(const std::vector& touches, cocos2d::Event *event); void onTouchesEnded(const std::vector& touches, cocos2d::Event *event); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 797f042ca7..d44129aee5 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -18,7 +18,8 @@ std::function createFunctions[] = CL(RemoveListenerWhenDispatching), CL(CustomEventTest), CL(LabelKeyboardEventTest), - CL(SpriteAccelerationEventTest) + CL(SpriteAccelerationEventTest), + CL(RemoveAndRetainNodeTest) }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -565,4 +566,88 @@ std::string SpriteAccelerationEventTest::title() std::string SpriteAccelerationEventTest::subtitle() { return "Please move your device\n(Only available on mobile)"; +} + +// RemoveAndRetainNodeTest +void RemoveAndRetainNodeTest::onEnter() +{ + _spriteSaved = false; + + EventDispatcherTestDemo::onEnter(); + + auto dispatcher = EventDispatcher::getInstance(); + + Point origin = Director::getInstance()->getVisibleOrigin(); + Size size = Director::getInstance()->getVisibleSize(); + + _sprite = Sprite::create("Images/CyanSquare.png"); + _sprite->setPosition(origin+Point(size.width/2, size.height/2)); + addChild(_sprite, 10); + + // Make sprite1 touchable + auto listener1 = EventListenerTouchOneByOne::create(); + listener1->setSwallowTouches(true); + + listener1->onTouchBegan = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + + Point locationInNode = target->convertToNodeSpace(touch->getLocation()); + Size s = target->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + + if (rect.containsPoint(locationInNode)) + { + log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y); + target->setOpacity(180); + return true; + } + return false; + }; + + listener1->onTouchMoved = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + target->setPosition(target->getPosition() + touch->getDelta()); + }; + + listener1->onTouchEnded = [=](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + log("sprite onTouchesEnded.. "); + target->setOpacity(255); + }; + + dispatcher->addEventListenerWithSceneGraphPriority(listener1, _sprite); + + this->runAction(Sequence::create(DelayTime::create(5.0f), + CallFunc::create([this](){ + _spriteSaved = true; + _sprite->retain(); + _sprite->removeFromParent(); + }), + DelayTime::create(5.0f), + CallFunc::create([this](){ + _spriteSaved = false; + this->addChild(_sprite); + _sprite->release(); + }), + nullptr + )); +} + +void RemoveAndRetainNodeTest::onExit() +{ + EventDispatcherTestDemo::onExit(); + if (_spriteSaved) + { + _sprite->release(); + } +} + +std::string RemoveAndRetainNodeTest::title() +{ + return "RemoveAndRetainNodeTest"; +} + +std::string RemoveAndRetainNodeTest::subtitle() +{ + return ""; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 2f5c186438..9af7022bde 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -83,4 +83,16 @@ public: virtual std::string subtitle() override; }; +class RemoveAndRetainNodeTest : public EventDispatcherTestDemo +{ +public: + virtual void onEnter() override; + virtual void onExit() override; + virtual std::string title() override; + virtual std::string subtitle() override; +private: + Sprite* _sprite; + bool _spriteSaved; +}; + #endif /* defined(__samples__NewEventDispatcherTest__) */ diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index db7f53d7c2..3276a9b620 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -723,7 +723,10 @@ std::string CameraCenterTest::subtitle() //------------------------------------------------------------------ ConvertToNode::ConvertToNode() { -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(ConvertToNode::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + auto s = Director::getInstance()->getWinSize(); auto rotate = RotateBy::create(10, 360); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index b99892e7ee..6bf14f8d5c 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -125,7 +125,7 @@ class ConvertToNode : public TestCocosNodeDemo { public: ConvertToNode(); - virtual void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); virtual std::string title(); virtual std::string subtitle(); }; diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp index bc2a128603..e14105b62e 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp @@ -87,7 +87,9 @@ std::string Parallax1::title() Parallax2::Parallax2() { -//cjh setTouchEnabled( true ); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesMoved = CC_CALLBACK_2(Parallax2::onTouchesMoved, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); // Top Layer, a simple image auto cocosImage = Sprite::create(s_Power); diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h index 5d4b6da085..905e34beae 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h +++ b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h @@ -43,7 +43,7 @@ protected: public: Parallax2(); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); virtual std::string title(); }; diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index 414c915135..9e35114538 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1068,7 +1068,11 @@ void ParticleDemo::onEnter(void) _emitter = NULL; -//cjh setTouchEnabled( true ); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(ParticleDemo::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(ParticleDemo::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(ParticleDemo::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h index c17d8bc73a..4c9e63047f 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h @@ -33,9 +33,9 @@ public: void backCallback(Object* sender); void toggleCallback(Object* sender); - virtual void onTouchesBegan(const std::vector& touches, Event *event); - virtual void onTouchesMoved(const std::vector& touches, Event *event); - virtual void onTouchesEnded(const std::vector& touches, Event *event); + void onTouchesBegan(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesEnded(const std::vector& touches, Event *event); virtual void update(float dt); void setEmitterPosition(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp index a928a3bd23..5f1e9566ab 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp @@ -119,9 +119,13 @@ std::string TouchesMainScene::title() void TouchesPerformTest1::onEnter() { TouchesMainScene::onEnter(); -//cjh setTouchEnabled(true); -// setTouchMode(Touch::DispatchMode::ONE_BY_ONE); -// setSwallowsTouches(true); + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + listener->onTouchBegan = CC_CALLBACK_2(TouchesPerformTest1::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(TouchesPerformTest1::onTouchMoved, this); + listener->onTouchEnded = CC_CALLBACK_2(TouchesPerformTest1::onTouchEnded, this); + listener->onTouchCancelled = CC_CALLBACK_2(TouchesPerformTest1::onTouchCancelled, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } std::string TouchesPerformTest1::title() @@ -158,7 +162,13 @@ void TouchesPerformTest1::onTouchCancelled(Touch* touch, Event* event) void TouchesPerformTest2::onEnter() { TouchesMainScene::onEnter(); -//cjh setTouchEnabled(true); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(TouchesPerformTest2::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(TouchesPerformTest2::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(TouchesPerformTest2::onTouchesEnded, this); + listener->onTouchesCancelled = CC_CALLBACK_2(TouchesPerformTest2::onTouchesCancelled, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } std::string TouchesPerformTest2::title() @@ -194,18 +204,13 @@ void TouchesPerformTest2::onTouchesCancelled(const std::vector& touches, class TouchableLayer : public Layer { public: - virtual bool onTouchBegan(Touch *touch, Event *event) + bool onTouchBegan(Touch *touch, Event *event) { return false; } - virtual void onTouchMoved(Touch *touch, Event *event) {} - virtual void onTouchEnded(Touch *touch, Event *event) {} - virtual void onTouchCancelled(Touch *touch, Event *event) {} - - virtual void onTouchesBegan(const std::vector& touches, Event *event) {} - virtual void onTouchesMoved(const std::vector& touches, Event *event) {} - virtual void onTouchesEnded(const std::vector& touches, Event *event) {} - virtual void onTouchesCancelled(const std::vector&touches, Event *event) {} + void onTouchMoved(Touch *touch, Event *event) {} + void onTouchEnded(Touch *touch, Event *event) {} + void onTouchCancelled(Touch *touch, Event *event) {} }; @@ -231,8 +236,14 @@ void TouchesPerformTest3::onEnter() { int zorder = rand() % TOUCHABLE_NODE_NUM; auto layer = new TouchableLayer(); -//cjh layer->setTouchEnabled(true); -// layer->setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(TouchableLayer::onTouchBegan, layer); + listener->onTouchMoved = CC_CALLBACK_2(TouchableLayer::onTouchMoved, layer); + listener->onTouchEnded = CC_CALLBACK_2(TouchableLayer::onTouchEnded, layer); + listener->onTouchCancelled = CC_CALLBACK_2(TouchableLayer::onTouchCancelled, layer); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, layer); + addChild(layer, zorder); layer->release(); } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h index 5cb4d35ad9..11a93ca3ee 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h @@ -36,10 +36,10 @@ public: virtual void onEnter() override; virtual std::string title() override; - virtual bool onTouchBegan(Touch* touch, Event* event) ; - virtual void onTouchMoved(Touch* touch, Event* event) ; - virtual void onTouchEnded(Touch* touch, Event* event) ; - virtual void onTouchCancelled(Touch* touch, Event* event) ; + bool onTouchBegan(Touch* touch, Event* event) ; + void onTouchMoved(Touch* touch, Event* event) ; + void onTouchEnded(Touch* touch, Event* event) ; + void onTouchCancelled(Touch* touch, Event* event) ; }; class TouchesPerformTest2 : public TouchesMainScene diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 4c56986746..59513a0835 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -197,8 +197,13 @@ void PhysicsDemoClickAdd::onEnter() PhysicsDemo::onEnter(); #ifdef CC_USE_PHYSICS -//cjh setTouchEnabled(true); -// setAccelerometerEnabled(true); + + auto touchListener = EventListenerTouchAllAtOnce::create(); + touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(accListener, this); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 1669b78c1f..113d4adad3 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -111,8 +111,11 @@ RenderTextureSave::RenderTextureSave() _brush->retain(); _brush->setColor(Color3B::RED); _brush->setOpacity(20); -//cjh this->setTouchEnabled(true); - + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesMoved = CC_CALLBACK_2(RenderTextureSave::onTouchesMoved, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + // Save Image menu MenuItemFont::setFontSize(16); auto item1 = MenuItemFont::create("Save Image", CC_CALLBACK_1(RenderTextureSave::saveImage, this)); @@ -296,7 +299,12 @@ void RenderTextureScene::runThisTest() RenderTextureZbuffer::RenderTextureZbuffer() { -//cjh this->setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesBegan, this); + listener->onTouchesMoved = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesMoved, this); + listener->onTouchesEnded = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + auto size = Director::getInstance()->getWinSize(); auto label = LabelTTF::create("vertexZ = 50", "Marker Felt", 64); label->setPosition(Point(size.width / 2, size.height * 0.25f)); @@ -627,7 +635,9 @@ void SpriteRenderTextureBug::SimpleSprite::draw() SpriteRenderTextureBug::SpriteRenderTextureBug() { -//cjh setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(SpriteRenderTextureBug::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h index b6ce107092..afd985ec70 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h @@ -24,7 +24,7 @@ public: ~RenderTextureSave(); virtual std::string title(); virtual std::string subtitle(); - virtual void onTouchesMoved(const std::vector& touches, Event* event); + void onTouchesMoved(const std::vector& touches, Event* event); void clearImage(Object *pSender); void saveImage(Object *pSender); @@ -52,9 +52,9 @@ class RenderTextureZbuffer : public RenderTextureTest public: RenderTextureZbuffer(); - virtual void onTouchesMoved(const std::vector& touches, Event* event); - virtual void onTouchesBegan(const std::vector& touches, Event* event); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesMoved(const std::vector& touches, Event* event); + void onTouchesBegan(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); virtual std::string title(); virtual std::string subtitle(); @@ -116,7 +116,7 @@ class SimpleSprite : public Sprite public: SpriteRenderTextureBug(); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); virtual std::string title(); virtual std::string subtitle(); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index a3d466373a..ee1480acae 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -4701ba8fb99f70629c5575dcf6fb3536543ac0b6 \ No newline at end of file +fdf35bd639fd5d617e5a280530d6aefe63b94857 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h index 413ba75e8b..ca08fb64e3 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h @@ -39,7 +39,7 @@ class SpriteBatchNode1: public SpriteTestDemo public: SpriteBatchNode1(); void addNewSpriteWithCoords(Point p); - virtual void onTouchesEnded(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); virtual std::string title(); }; diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index 1645d017d8..b922271656 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -126,14 +126,10 @@ void TextInputTest::onEnter() KeyboardNotificationLayer::KeyboardNotificationLayer() : _trackNode(0) { -//cjh setTouchEnabled(true); - // Register Touch Event auto listener = EventListenerTouchOneByOne::create(); - listener->onTouchBegan = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h index 65cfb27d9a..7da7b893a1 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h @@ -37,7 +37,6 @@ public: virtual std::string subtitle() = 0; virtual void onClickTrackNode(bool bClicked) = 0; -// virtual void registerWithTouchDispatcher(); virtual void keyboardWillShow(IMEKeyboardNotificationInfo& info); // Layer diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 7be2b29c32..48ed771306 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -1430,7 +1430,9 @@ Layer* restartTileMapAction() TileDemo::TileDemo(void) : BaseTest() { -//cjh setTouchEnabled( true ); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesMoved = CC_CALLBACK_2(TileDemo::onTouchesMoved, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); } TileDemo::~TileDemo(void) diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h index e0039525a3..3331292415 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h @@ -18,7 +18,7 @@ public: void nextCallback(Object* sender); void backCallback(Object* sender); - virtual void onTouchesMoved(const std::vector& touches, Event *event); + void onTouchesMoved(const std::vector& touches, Event *event); }; class TileMapTest : public TileDemo diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index c7b03f1acf..fcd140e4f3 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -120,8 +120,6 @@ TestController::TestController() _itemMenu->setPosition(s_tCurPos); addChild(_itemMenu); -//cjh setTouchEnabled(true); - addChild(menu, 1); // Register Touch Event From 6f9bee5b1a0b2ee66e6614e3f0a31817506b670e Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 16:28:38 +0800 Subject: [PATCH 224/557] bug fix in EventDispatcher. --- cocos/2d/CCEventDispatcher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 05a2a66ddf..ca28314d8c 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -436,7 +436,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) auto found = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener); if (found != fixedPriorityListeners->end()) { - CCASSERT(listener->_node, "Can't set fixed priority with scene graph based listener."); + CCASSERT(listener->_node == nullptr, "Can't set fixed priority with scene graph based listener."); if (listener->_fixedPriority != fixedPriority) { From b131e8c5095cccaa97ce3d08729bef76a5875213 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 16:28:54 +0800 Subject: [PATCH 225/557] Update menu test. --- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 19 +++++++++---------- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.h | 1 + 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index e1fb43cf39..7edfb6fe4e 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -25,13 +25,14 @@ enum { //------------------------------------------------------------------ MenuLayerMainMenu::MenuLayerMainMenu() { - auto listener = EventListenerTouchOneByOne::create(); - listener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::onTouchBegan, this); - listener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::onTouchMoved, this); - listener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this); + _touchListener = EventListenerTouchOneByOne::create(); + _touchListener->setSwallowTouches(true); + _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::onTouchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::onTouchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this); + _touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + EventDispatcher::getInstance()->addEventListenerWithFixedPriority(_touchListener, 1); // Font Item auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); @@ -152,8 +153,7 @@ void MenuLayerMainMenu::menuCallbackConfig(Object* sender) void MenuLayerMainMenu::allowTouches(float dt) { -// auto director = Director::getInstance(); -// director->getTouchDispatcher()->setPriority(Menu::HANDLER_PRIORITY+1, this); + EventDispatcher::getInstance()->setPriority(_touchListener, 1); unscheduleAllSelectors(); log("TOUCHES ALLOWED AGAIN"); } @@ -161,8 +161,7 @@ void MenuLayerMainMenu::allowTouches(float dt) void MenuLayerMainMenu::menuCallbackDisabled(Object* sender) { // hijack all touch events for 5 seconds -// auto director = Director::getInstance(); -// director->getTouchDispatcher()->setPriority(Menu::HANDLER_PRIORITY-1, this); + EventDispatcher::getInstance()->setPriority(_touchListener, -1); schedule(schedule_selector(MenuLayerMainMenu::allowTouches), 5.0f); log("TOUCHES DISABLED FOR 5 SECONDS"); } diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h index 127f8c1688..3a7b09eec9 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h @@ -8,6 +8,7 @@ class MenuLayerMainMenu : public Layer { protected: MenuItem* _disabledItem; + EventListenerTouchOneByOne* _touchListener; public: MenuLayerMainMenu(void); From a56475e872f9c96a44596f72b9fdfabf1f6a24a8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 16:35:37 +0800 Subject: [PATCH 226/557] Updating jsb. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- cocos/scripting/javascript/bindings/cocos2d_specifics.hpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 082d55b8bd..4caa15159c 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -33fef8c7bc7006ad55c27fd0ed9c9dd2c8064079 \ No newline at end of file +0d38b7e53d97995151ea296bdd1f4ed768ce2f9b \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index 2981a726a8..f7e9f2bdb4 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -199,7 +199,8 @@ private: typedef std::pair TouchDelegatePair; static TouchDelegateMap sTouchDelegateMap; bool _needUnroot; - EventListenerTouch* _touchListener; + EventListenerTouchOneByOne* _touchListenerOneByOne; + EventListenerTouchAllAtOnce* _touchListenerAllAtOnce; }; From e59c49a5e3c06609877796d562c03e5776ff01db Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 17:13:03 +0800 Subject: [PATCH 227/557] fix crash. --- cocos/2d/CCEventDispatcher.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index ca28314d8c..71e7b36704 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -232,7 +232,8 @@ void EventDispatcher::cleanTarget(Node* node) if (listenerIter != _nodeListenersMap.end()) { auto listeners = listenerIter->second; - for (auto& l : *listeners) + auto listenersCopy = *listeners; + for (auto& l : listenersCopy) { removeEventListener(l); } From aeef62d893be38a43e971112a8ffd219e1e9a351 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 23 Oct 2013 17:26:14 +0800 Subject: [PATCH 228/557] bug fix for EventDispatcher. --- cocos/2d/CCEventDispatcher.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 71e7b36704..9df198f8e2 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -161,11 +161,7 @@ void EventDispatcher::destroyInstance() } void EventDispatcher::visitTarget(Node* node) -{ - // Reset priority index - s_eventPriorityIndex = 0; - _nodePriorityMap.clear(); - +{ int i = 0; Array* children = node->getChildren(); int childrenCount = children ? children->count() : 0; @@ -898,20 +894,23 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const std::string& return; Node* rootNode = (Node*)Director::getInstance()->getRunningScene(); - + // Reset priority index + s_eventPriorityIndex = 0; + _nodePriorityMap.clear(); + visitTarget(rootNode); // After sort: priority < 0, > 0 auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); std::sort(sceneGraphlisteners->begin(), sceneGraphlisteners->end(), [this](const EventListener* l1, const EventListener* l2) { - return _nodePriorityMap[l1->_node] >= _nodePriorityMap[l2->_node]; + return _nodePriorityMap[l1->_node] > _nodePriorityMap[l2->_node]; }); #if DUMP_LISTENER_ITEM_PRIORITY_INFO log("-----------------------------------"); for (auto& l : *sceneGraphlisteners) { - log("listener priority: node ([%s]%p), fixed (%d)", typeid(*l->_node).name(), l->_node, l->_fixedPriority); + log("listener priority: node ([%s]%p), priority (%d)", typeid(*l->_node).name(), l->_node, _nodePriorityMap[l->_node]); } #endif } From 5ecb664a58f34d80efa44846fab131234dad6008 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 11:17:29 +0800 Subject: [PATCH 229/557] crash and memory leak fix. --- cocos/2d/CCEventDispatcher.cpp | 17 +++++++++-------- cocos/2d/CCEventListener.h | 1 + cocos/2d/CCMenu.cpp | 4 ++++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 9df198f8e2..607c82181f 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -367,14 +367,13 @@ void EventDispatcher::removeEventListener(EventListener* listener) auto l = *iter; if (l == listener) { - CC_SAFE_RETAIN(listener); + CC_SAFE_RETAIN(l); l->_isRegistered = false; if (l->_node != nullptr) { - dissociateNodeAndEventListener(l->_node, listener); + dissociateNodeAndEventListener(l->_node, l); } - l->release(); if (_inDispatch == 0) { listeners->erase(iter); @@ -391,7 +390,7 @@ void EventDispatcher::removeEventListener(EventListener* listener) auto listeners = iter->second; auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); - + removeListenerInVector(sceneGraphPriorityListeners); if (!isFound) { @@ -459,7 +458,7 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s for (; !fixedPriorityListeners->empty() && i < listeners->getGt0Index(); ++i) { auto l = fixedPriorityListeners->at(i); - if (!l->isPaused() && onEvent(l)) + if (!l->isPaused() && l->isRegistered() && onEvent(l)) { shouldStopPropagation = true; break; @@ -472,9 +471,9 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s if (!shouldStopPropagation) { // priority == 0, scene graph priority - for (auto& listener : *sceneGraphPriorityListeners) + for (auto& l : *sceneGraphPriorityListeners) { - if (!listener->isPaused() && onEvent(listener)) + if (!l->isPaused() && l->isRegistered() && onEvent(l)) { shouldStopPropagation = true; break; @@ -492,7 +491,7 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s { auto l = fixedPriorityListeners->at(i); - if (!l->isPaused() && onEvent(fixedPriorityListeners->at(i))) + if (!l->isPaused() && l->isRegistered() && onEvent(fixedPriorityListeners->at(i))) { shouldStopPropagation = true; break; @@ -794,6 +793,7 @@ void EventDispatcher::updateListeners() if (!l->_isRegistered) { iter = sceneGraphPriorityListeners->erase(iter); + l->release(); } else { @@ -810,6 +810,7 @@ void EventDispatcher::updateListeners() if (!l->_isRegistered) { iter = fixedPriorityListeners->erase(iter); + l->release(); } else { diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index f68f9694f9..672d9c98d0 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -62,6 +62,7 @@ public: virtual EventListener* clone() = 0; inline bool isPaused() const { return _paused; }; + inline bool isRegistered() const { return _isRegistered; }; protected: std::function _onEvent; /// Event callback function diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 3105a2d8a3..5a46765d91 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -259,22 +259,26 @@ bool Menu::onTouchBegan(Touch* touch, Event* event) void Menu::onTouchEnded(Touch* touch, Event* event) { CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchEnded] -- invalid state"); + this->retain(); if (_selectedItem) { _selectedItem->unselected(); _selectedItem->activate(); } _state = Menu::State::WAITING; + this->release(); } void Menu::onTouchCancelled(Touch* touch, Event* event) { CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchCancelled] -- invalid state"); + this->retain(); if (_selectedItem) { _selectedItem->unselected(); } _state = Menu::State::WAITING; + this->release(); } void Menu::onTouchMoved(Touch* touch, Event* event) From dc6e201eb61a7ae0bb099c21ad47bb8f55d36cc5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 17:27:22 +0800 Subject: [PATCH 230/557] bug fix for eventdispatcher. --- cocos/2d/CCEventDispatcher.cpp | 32 ++++++++++++++++++++++++++++---- cocos/2d/CCEventDispatcher.h | 2 ++ cocos/2d/CCNode.cpp | 2 +- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 607c82181f..817134ec37 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -115,7 +115,7 @@ void EventDispatcher::EventListenerVector::push_back(EventListener* listener) } } -void EventDispatcher::EventListenerVector::clear() +void EventDispatcher::EventListenerVector::clearSceneGraphListeners() { if (_sceneGraphListeners) { @@ -123,7 +123,10 @@ void EventDispatcher::EventListenerVector::clear() delete _sceneGraphListeners; _sceneGraphListeners = nullptr; } - +} + +void EventDispatcher::EventListenerVector::clearFixedListeners() +{ if (_fixedListeners) { _fixedListeners->clear(); @@ -132,6 +135,12 @@ void EventDispatcher::EventListenerVector::clear() } } +void EventDispatcher::EventListenerVector::clear() +{ + clearSceneGraphListeners(); + clearFixedListeners(); +} + EventDispatcher::EventDispatcher() : _inDispatch(0) @@ -270,6 +279,7 @@ void EventDispatcher::dissociateNodeAndEventListener(Node* node, EventListener* if (listeners->empty()) { _nodeListenersMap.erase(found); + delete listeners; } } } @@ -317,7 +327,6 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list return; listener->_node = node; -// listener->_node->retain(); listener->_fixedPriority = 0; listener->retain(); @@ -377,6 +386,7 @@ void EventDispatcher::removeEventListener(EventListener* listener) if (_inDispatch == 0) { listeners->erase(iter); + CC_SAFE_RELEASE(l); } isFound = true; @@ -819,6 +829,16 @@ void EventDispatcher::updateListeners() } } + if (sceneGraphPriorityListeners && sceneGraphPriorityListeners->empty()) + { + listeners->clearSceneGraphListeners(); + } + + if (fixedPriorityListeners && fixedPriorityListeners->empty()) + { + listeners->clearFixedListeners(); + } + if (listenersIter->second->empty()) { _priorityDirtyFlagMap.erase(listenersIter->first); @@ -1047,7 +1067,11 @@ bool EventDispatcher::isEnabled() const void EventDispatcher::setDirtyForNode(Node* node) { - _dirtyNodes.insert(node); + // Mark the node dirty only when there was an eventlistener associates with it. + if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) + { + _dirtyNodes.insert(node); + } } void EventDispatcher::setDirtyForEventType(const std::string& eventType, DirtyFlag flag) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index dc70491075..75f4f658af 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -139,6 +139,8 @@ private: bool empty() const; void push_back(EventListener* item); + void clearSceneGraphListeners(); + void clearFixedListeners(); void clear(); inline std::vector* getFixedPriorityListeners() const { return _fixedListeners; }; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 8b9d41f9ec..ee19921a8d 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -640,7 +640,7 @@ void Node::addChild(Node *child, int zOrder, int tag) } } - EventDispatcher::getInstance()->setDirtyForNode(this); + EventDispatcher::getInstance()->setDirtyForNode(child); } void Node::addChild(Node *child, int zOrder) From 9632cd7949fa516e031190ea2e0ad84d6e6f021e Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 17:27:57 +0800 Subject: [PATCH 231/557] memoryleak fix. --- cocos/2d/CCLayer.cpp | 9 ++++++++- cocos/2d/CCMenuItem.cpp | 18 +++++++++++++++++- cocos/2d/CCMenuItem.h | 4 ++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 717570e6fe..ed5caf3a71 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -650,7 +650,14 @@ LayerMultiplex::LayerMultiplex() } LayerMultiplex::~LayerMultiplex() { - CC_SAFE_RELEASE(_layers); + if (_layers) + { + for (auto& item : *_layers) + { + static_cast(item)->cleanup(); + } + _layers->release(); + } } LayerMultiplex * LayerMultiplex::create(Layer * layer, ...) diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index c735677e9f..24ec16a3a7 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -410,6 +410,15 @@ MenuItemFont * MenuItemFont::create(const char *value) return pRet; } +MenuItemFont::MenuItemFont() + : _fontSize(0), _fontName("") +{} + +MenuItemFont::~MenuItemFont() +{ + CCLOGINFO("In the destructor of MenuItemFont (%p).", this); +} + // XXX: deprecated bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHandler selector) { @@ -925,7 +934,14 @@ void MenuItemToggle::addSubItem(MenuItem *item) MenuItemToggle::~MenuItemToggle() { - CC_SAFE_RELEASE(_subItems); + if (_subItems) + { + for (auto& item : *_subItems) + { + static_cast(item)->cleanup(); + } + _subItems->release(); + } } void MenuItemToggle::setSelectedIndex(unsigned int index) diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 021832df30..78b8d333ef 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -241,12 +241,12 @@ public: /** * @js ctor */ - MenuItemFont() : _fontSize(0), _fontName(""){} + MenuItemFont(); /** * @js NA * @lua NA */ - virtual ~MenuItemFont(){} + virtual ~MenuItemFont(); /** initializes a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); From 7854a13278ef39c65bec236176a3de9957bde8a6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 17:28:51 +0800 Subject: [PATCH 232/557] Small fix for Bug-422.cpp and MenuTest.cpp. --- samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp | 2 +- samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp index 4ce9ce9190..6f5f7eb542 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp @@ -28,7 +28,7 @@ void Bug422Layer::reset() // => CRASH BOOM BANG auto node = getChildByTag(localtag-1); log("Menu: %p", node); - removeChild(node, false); + removeChild(node, true); // [self removeChildByTag:localtag-1 cleanup:NO]; auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index 7edfb6fe4e..d295de75bc 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -138,6 +138,7 @@ void MenuLayerMainMenu::onTouchMoved(Touch *touch, Event * event) MenuLayerMainMenu::~MenuLayerMainMenu() { + EventDispatcher::getInstance()->removeEventListener(_touchListener); _disabledItem->release(); } From 9c4bc9e8ede2095b57abe3843cd174c3b27303e6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 17:46:13 +0800 Subject: [PATCH 233/557] Update physicsTest. --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 9 +++++++-- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h | 6 ++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 59513a0835..f9b9d209de 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -511,7 +511,10 @@ PhysicsDemoRayCast::PhysicsDemoRayCast() void PhysicsDemoRayCast::onEnter() { PhysicsDemo::onEnter(); - setTouchEnabled(true); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoRayCast::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); _scene->getPhysicsWorld()->setGravity(Point::ZERO); @@ -712,7 +715,9 @@ void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); - setTouchEnabled(true); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchesEnded, this); + EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); _scene->getPhysicsWorld()->setGravity(Point::ZERO); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 7dbb28617b..6d0d9a46c0 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -90,7 +90,7 @@ public: void onEnter() override; std::string title() override; void update(float delta) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + void onTouchesEnded(const std::vector& touches, Event* event); void changeModeCallback(Object* sender); @@ -110,9 +110,7 @@ public: public: void onEnter() override; std::string title() override; - -private: - PhysicsShape* _touchesShape; + void onTouchesEnded(const std::vector& touches, Event* event) override; }; #endif From b5cac51f97ef1cd2f2fc3405c518dc4a6cf5d1dc Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 17:58:30 +0800 Subject: [PATCH 234/557] PhysicsTest update. --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 5 +++++ samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h | 8 ++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f9b9d209de..874f5ebe61 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -722,6 +722,11 @@ void PhysicsDemoJoints::onEnter() _scene->getPhysicsWorld()->setGravity(Point::ZERO); +} + +void PhysicsDemoJoints::onTouchesEnded(const std::vector& touches, Event* event) +{ + } std::string PhysicsDemoJoints::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 6d0d9a46c0..bb737b497d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -41,9 +41,9 @@ public: Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - void onTouchesBegan(const std::vector& touches, Event* event) override; - void onTouchesMoved(const std::vector& touches, Event* event) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + void onTouchesBegan(const std::vector& touches, Event* event); + void onTouchesMoved(const std::vector& touches, Event* event); + void onTouchesEnded(const std::vector& touches, Event* event); protected: Texture2D* _spriteTexture; // weak ref @@ -110,7 +110,7 @@ public: public: void onEnter() override; std::string title() override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + void onTouchesEnded(const std::vector& touches, Event* event); }; #endif From c4f9acbee71f37f7b43bc0f3a0fc165754540ab8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 24 Oct 2013 20:50:21 +0800 Subject: [PATCH 235/557] disable DUMP_LISTENER_ITEM_PRIORITY_INFO. use std::unordered_map instead of std::map. --- cocos/2d/CCEventDispatcher.cpp | 3 ++- cocos/2d/CCEventDispatcher.h | 21 ++++++++++----------- cocos/2d/CCNode.cpp | 2 -- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 817134ec37..f7d593fb8f 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -31,7 +31,7 @@ #include -#define DUMP_LISTENER_ITEM_PRIORITY_INFO 1 +#define DUMP_LISTENER_ITEM_PRIORITY_INFO 0 namespace { @@ -229,6 +229,7 @@ void EventDispatcher::resumeTarget(Node* node) l->_paused = false; } } + setDirtyForNode(node); } void EventDispatcher::cleanTarget(Node* node) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 75f4f658af..26d3154a65 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -30,7 +30,7 @@ #include #include -#include +#include #include #include @@ -114,12 +114,6 @@ public: void setDirtyForNode(Node* node); - void setDirtyForEventType(const std::string& eventType, DirtyFlag flag); - - DirtyFlag isDirtyForEventType(const std::string& eventType); - - void visitTarget(Node* node); - void pauseTarget(Node* node); void resumeTarget(Node* node); void cleanTarget(Node* node); @@ -181,16 +175,21 @@ private: void dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent); + void setDirtyForEventType(const std::string& eventType, DirtyFlag flag); + DirtyFlag isDirtyForEventType(const std::string& eventType); + + void visitTarget(Node* node); + private: /** * Listeners map. */ - std::map _listeners; + std::unordered_map _listeners; - std::map _priorityDirtyFlagMap; + std::unordered_map _priorityDirtyFlagMap; - std::map*> _nodeListenersMap; - std::map _nodePriorityMap; + std::unordered_map*> _nodeListenersMap; + std::unordered_map _nodePriorityMap; std::vector _toAddedListeners; std::set _dirtyNodes; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index ee19921a8d..427884abb0 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -639,8 +639,6 @@ void Node::addChild(Node *child, int zOrder, int tag) child->onEnterTransitionDidFinish(); } } - - EventDispatcher::getInstance()->setDirtyForNode(child); } void Node::addChild(Node *child, int zOrder) From 27b71ba73c7413896d64157790991894da0f2b07 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 10:35:48 +0800 Subject: [PATCH 236/557] Use integer as event type and listener type. --- cocos/2d/CCEvent.cpp | 2 +- cocos/2d/CCEvent.h | 16 +- cocos/2d/CCEventAcceleration.cpp | 4 +- cocos/2d/CCEventAcceleration.h | 3 +- cocos/2d/CCEventCustom.cpp | 6 +- cocos/2d/CCEventCustom.h | 2 +- cocos/2d/CCEventDispatcher.cpp | 190 ++++++++---------- cocos/2d/CCEventDispatcher.h | 29 +-- cocos/2d/CCEventKeyboard.h | 2 +- cocos/2d/CCEventListener.cpp | 2 +- cocos/2d/CCEventListener.h | 17 +- cocos/2d/CCEventListenerAcceleration.cpp | 2 +- cocos/2d/CCEventListenerCustom.cpp | 8 +- cocos/2d/CCEventListenerCustom.h | 4 +- cocos/2d/CCEventListenerKeyboard.cpp | 2 +- cocos/2d/CCEventListenerTouch.cpp | 4 +- cocos/2d/CCEventListenerTouch.h | 4 + cocos/2d/CCEventTouch.cpp | 4 - cocos/2d/CCEventTouch.h | 8 +- cocos/2d/platform/CCEGLViewProtocol.cpp | 6 +- .../NewEventDispatcherTest.cpp | 7 +- 21 files changed, 155 insertions(+), 167 deletions(-) diff --git a/cocos/2d/CCEvent.cpp b/cocos/2d/CCEvent.cpp index 87cce7ab7d..c74beef87e 100644 --- a/cocos/2d/CCEvent.cpp +++ b/cocos/2d/CCEvent.cpp @@ -26,7 +26,7 @@ NS_CC_BEGIN -Event::Event(const std::string& type) +Event::Event(Type type) : _type(type) , _isStopped(false) , _currentTarget(nullptr) diff --git a/cocos/2d/CCEvent.h b/cocos/2d/CCEvent.h index 1652066fd3..348c2ba1d3 100644 --- a/cocos/2d/CCEvent.h +++ b/cocos/2d/CCEvent.h @@ -40,15 +40,25 @@ class Node; */ class Event { +public: + enum EventType + { + TYPE_TOUCH = 1, + TYPE_KEYBOARD = 3, + TYPE_ACCELERATION, + TYPE_CUSTOM + }; + + typedef int Type; protected: /** Constructor */ - Event(const std::string& type); + Event(Type type); public: /** Destructor */ virtual ~Event(); /** Gets the event type */ - inline const std::string& getType() const { return _type; }; + inline int getType() const { return _type; }; /** Stops propagation for current event */ inline void stopPropagation() { _isStopped = true; }; @@ -67,7 +77,7 @@ protected: /** Sets current target */ inline void setCurrentTarget(Node* target) { _currentTarget = target; }; - std::string _type; ///< Event type + Type _type; ///< Event type bool _isStopped; ///< whether the event has been stopped. Node* _currentTarget; ///< Current target diff --git a/cocos/2d/CCEventAcceleration.cpp b/cocos/2d/CCEventAcceleration.cpp index 962408202d..7039c03ff8 100644 --- a/cocos/2d/CCEventAcceleration.cpp +++ b/cocos/2d/CCEventAcceleration.cpp @@ -26,10 +26,8 @@ NS_CC_BEGIN -const char* EventAcceleration::EVENT_TYPE = "AccelerometerEvent"; - EventAcceleration::EventAcceleration(Acceleration acc) -: Event(EVENT_TYPE) +: Event(TYPE_ACCELERATION) , _acc(acc) { } diff --git a/cocos/2d/CCEventAcceleration.h b/cocos/2d/CCEventAcceleration.h index c5dfbe9ef5..1480ee6b0c 100644 --- a/cocos/2d/CCEventAcceleration.h +++ b/cocos/2d/CCEventAcceleration.h @@ -33,8 +33,7 @@ NS_CC_BEGIN class EventAcceleration : public Event { public: - static const char* EVENT_TYPE; - + EventAcceleration(Acceleration acc); private: diff --git a/cocos/2d/CCEventCustom.cpp b/cocos/2d/CCEventCustom.cpp index f9fc9d4a0e..89e56a3a69 100644 --- a/cocos/2d/CCEventCustom.cpp +++ b/cocos/2d/CCEventCustom.cpp @@ -23,13 +23,15 @@ ****************************************************************************/ #include "CCEventCustom.h" +#include "ccMacros.h" NS_CC_BEGIN -EventCustom::EventCustom(const std::string& eventName) -: Event(eventName) +EventCustom::EventCustom(Type type) +: Event(type) , _userData(nullptr) { + CCASSERT(type >= TYPE_CUSTOM, "custom type should be greater than TYPE_CUSTOM."); } NS_CC_END diff --git a/cocos/2d/CCEventCustom.h b/cocos/2d/CCEventCustom.h index c4521e3bbf..96676cdbfd 100644 --- a/cocos/2d/CCEventCustom.h +++ b/cocos/2d/CCEventCustom.h @@ -33,7 +33,7 @@ class EventCustom : public Event { public: /** Constructor */ - EventCustom(const std::string& eventName); + EventCustom(Type type); /** Set user data */ inline void setUserData(void* data) { _userData = data; }; diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index f7d593fb8f..a0e58363a3 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -306,11 +306,11 @@ void EventDispatcher::addEventListener(EventListener* listener) if (listener->_fixedPriority == 0) { - setDirtyForEventType(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); } else { - setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); + setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); } } else @@ -448,7 +448,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) if (listener->_fixedPriority != fixedPriority) { listener->_fixedPriority = fixedPriority; - setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); + setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); } return; } @@ -519,31 +519,17 @@ void EventDispatcher::dispatchEvent(Event* event) updateDirtyFlagForSceneGraph(); - DirtyFlag dirtyFlag = DirtyFlag::NONE; - - auto dirtyIter = _priorityDirtyFlagMap.find(event->_type); - if (dirtyIter != _priorityDirtyFlagMap.end()) - { - dirtyFlag = dirtyIter->second; - } - - if (dirtyFlag != DirtyFlag::NONE) - { - if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) - { - sortEventListenersOfFixedPriority(event->_type); - } - - if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) - { - sortEventListenersOfSceneGraphPriority(event->_type); - } - - dirtyIter->second = DirtyFlag::NONE; - } DispatchGuard guard(_inDispatch); + if (event->getType() == Event::TYPE_TOUCH) + { + dispatchTouchEvent(static_cast(event)); + return; + } + + sortEventListeners(event->getType()); + auto iter = _listeners.find(event->getType()); if (iter != _listeners.end()) { @@ -558,49 +544,16 @@ void EventDispatcher::dispatchEvent(Event* event) dispatchEventToListeners(listeners, onEvent); } - updateListeners(); + updateListeners(event->getType()); } void EventDispatcher::dispatchTouchEvent(EventTouch* event) { - if (!_isEnabled) - return; + sortEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + sortEventListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); - updateDirtyFlagForSceneGraph(); - - auto sortTouchListeners = [this](const std::string& type){ - - DirtyFlag dirtyFlag = DirtyFlag::NONE; - auto dirtyIter = _priorityDirtyFlagMap.find(type); - if (dirtyIter != _priorityDirtyFlagMap.end()) - { - dirtyFlag = dirtyIter->second; - } - - if (dirtyFlag != DirtyFlag::NONE) - { - if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) - { - sortEventListenersOfFixedPriority(type); - } - - if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) - { - sortEventListenersOfSceneGraphPriority(type); - } - - dirtyIter->second = DirtyFlag::NONE; - } - - }; - - sortTouchListeners(EventTouch::MODE_ONE_BY_ONE); - sortTouchListeners(EventTouch::MODE_ALL_AT_ONCE); - - DispatchGuard guard(_inDispatch); - - auto oneByOnelisteners = getListeners(EventTouch::MODE_ONE_BY_ONE); - auto allAtOncelisteners = getListeners(EventTouch::MODE_ALL_AT_ONCE); + auto oneByOnelisteners = getListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + auto allAtOncelisteners = getListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); // If there aren't any touch listeners, return directly. if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) @@ -691,7 +644,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(); + updateListeners(event->getType()); return true; } @@ -770,7 +723,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(); + updateListeners(event->getType()); return false; } @@ -784,14 +737,17 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) } } - updateListeners(); + updateListeners(event->getType()); } -void EventDispatcher::updateListeners() +void EventDispatcher::updateListeners(Event::Type eventType) { - auto listenersIter = _listeners.begin(); - while (listenersIter != _listeners.end()) + auto onUpdateListeners = [this](EventListener::Type listenerType) { + auto listenersIter = _listeners.find(listenerType); + if (listenersIter == _listeners.end()) + return; + auto listeners = listenersIter->second; auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); @@ -850,7 +806,18 @@ void EventDispatcher::updateListeners() { ++listenersIter; } + }; + + if (eventType == Event::TYPE_TOUCH) + { + onUpdateListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + onUpdateListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); } + else + { + onUpdateListeners(eventType); + } + if (!_toAddedListeners.empty()) { @@ -874,11 +841,11 @@ void EventDispatcher::updateListeners() if (listener->_fixedPriority == 0) { - setDirtyForEventType(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); } else { - setDirtyForEventType(listener->_type, DirtyFlag::FIXED_PRITORY); + setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); } } _toAddedListeners.clear(); @@ -896,7 +863,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() { for (auto& l : *iter->second) { - setDirtyForEventType(l->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(l->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); } } } @@ -905,12 +872,35 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(const std::string& eventType) +void EventDispatcher::sortEventListeners(EventListener::Type eventListenerType) { - if (eventType.empty()) - return; + DirtyFlag dirtyFlag = DirtyFlag::NONE; - auto listeners = getListeners(eventType); + auto dirtyIter = _priorityDirtyFlagMap.find(eventListenerType); + if (dirtyIter != _priorityDirtyFlagMap.end()) + { + dirtyFlag = dirtyIter->second; + } + + if (dirtyFlag != DirtyFlag::NONE) + { + if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) + { + sortEventListenersOfFixedPriority(eventListenerType); + } + + if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) + { + sortEventListenersOfSceneGraphPriority(eventListenerType); + } + + dirtyIter->second = DirtyFlag::NONE; + } +} + +void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::Type eventListenerType) +{ + auto listeners = getListeners(eventListenerType); if (listeners == nullptr) return; @@ -937,12 +927,9 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const std::string& #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(const std::string &eventType) +void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::Type eventListenerType) { - if (eventType.empty()) - return; - - auto listeners = getListeners(eventType); + auto listeners = getListeners(eventListenerType); if (listeners == nullptr) return; @@ -974,9 +961,9 @@ void EventDispatcher::sortEventListenersOfFixedPriority(const std::string &event } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const std::string &eventType) +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::Type eventListenerType) { - auto iter = _listeners.find(eventType); + auto iter = _listeners.find(eventListenerType); if (iter != _listeners.end()) { return iter->second; @@ -985,12 +972,9 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const std::s return nullptr; } -void EventDispatcher::removeListenersForEventType(const std::string& eventType) +void EventDispatcher::removeListeners(EventListener::Type eventListenerType) { - if (eventType.empty()) - return; - - auto listenerItemIter = _listeners.find(eventType); + auto listenerItemIter = _listeners.find(eventListenerType); if (listenerItemIter != _listeners.end()) { auto listeners = listenerItemIter->second; @@ -1010,10 +994,10 @@ void EventDispatcher::removeListenersForEventType(const std::string& eventType) dissociateNodeAndEventListener(l->_node, l); } - l->release(); if (_inDispatch == 0) { iter = listenerVector->erase(iter); + CC_SAFE_RELEASE(l); } else { @@ -1030,14 +1014,14 @@ void EventDispatcher::removeListenersForEventType(const std::string& eventType) listeners->clear(); delete listeners; _listeners.erase(listenerItemIter); - _priorityDirtyFlagMap.erase(eventType); + _priorityDirtyFlagMap.erase(eventListenerType); } } } void EventDispatcher::removeAllListeners() { - std::vector types(_listeners.size()); + std::vector types(_listeners.size()); for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) { @@ -1046,7 +1030,7 @@ void EventDispatcher::removeAllListeners() for (auto& type : types) { - removeListenersForEventType(type); + removeListeners(type); } if (!_inDispatch) @@ -1075,14 +1059,12 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirtyForEventType(const std::string& eventType, DirtyFlag flag) -{ - CCASSERT(!eventType.empty(), "Invalid event type."); - - auto iter = _priorityDirtyFlagMap.find(eventType); +void EventDispatcher::setDirty(EventListener::Type eventListenerType, DirtyFlag flag) +{ + auto iter = _priorityDirtyFlagMap.find(eventListenerType); if (iter == _priorityDirtyFlagMap.end()) { - _priorityDirtyFlagMap.insert(std::make_pair(eventType, flag)); + _priorityDirtyFlagMap.insert(std::make_pair(eventListenerType, flag)); } else { @@ -1091,16 +1073,4 @@ void EventDispatcher::setDirtyForEventType(const std::string& eventType, DirtyFl } } -EventDispatcher::DirtyFlag EventDispatcher::isDirtyForEventType(const std::string& eventType) -{ - DirtyFlag flag = DirtyFlag::NONE; - auto iter = _priorityDirtyFlagMap.find(eventType); - if (iter != _priorityDirtyFlagMap.end()) - { - flag = iter->second; - } - - return flag; -} - NS_CC_END diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 26d3154a65..53f2224b2b 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -27,6 +27,7 @@ #include "CCPlatformMacros.h" #include "CCEventListener.h" +#include "CCEvent.h" #include #include @@ -80,7 +81,7 @@ public: void removeEventListener(EventListener* listener); /** Removes all listeners with the same event type */ - void removeListenersForEventType(const std::string& eventType); + void removeListeners(EventListener::Type eventListenerType); /** Removes all listeners */ void removeAllListeners(); @@ -100,9 +101,6 @@ public: */ void dispatchEvent(Event* event); - /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ - void dispatchTouchEvent(EventTouch* event); - /// Priority dirty flag enum class DirtyFlag { @@ -153,30 +151,35 @@ private: /** Adds event listener with item */ void addEventListener(EventListener* listener); - /** Gets event the listener list for the event type. */ - EventListenerVector* getListeners(const std::string& eventType); + /** Gets event the listener list for the event listener type. */ + EventListenerVector* getListeners(EventListener::Type eventListenerType); void updateDirtyFlagForSceneGraph(); + /** Sort event listener */ + void sortEventListeners(EventListener::Type eventListenerType); + /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(const std::string& eventType); + void sortEventListenersOfSceneGraphPriority(EventListener::Type eventListenerType); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(const std::string& eventType); + void sortEventListenersOfFixedPriority(EventListener::Type eventListenerType); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. * 2) Adds all listener items that have been marked as 'added' when dispatching event. */ - void updateListeners(); + void updateListeners(Event::Type eventType); + /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ + void dispatchTouchEvent(EventTouch* event); + void associateNodeAndEventListener(Node* node, EventListener* listener); void dissociateNodeAndEventListener(Node* node, EventListener* listener); void dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent); - void setDirtyForEventType(const std::string& eventType, DirtyFlag flag); - DirtyFlag isDirtyForEventType(const std::string& eventType); + void setDirty(EventListener::Type listenerType, DirtyFlag flag); void visitTarget(Node* node); @@ -184,9 +187,9 @@ private: /** * Listeners map. */ - std::unordered_map _listeners; + std::unordered_map _listeners; - std::unordered_map _priorityDirtyFlagMap; + std::unordered_map _priorityDirtyFlagMap; std::unordered_map*> _nodeListenersMap; std::unordered_map _nodePriorityMap; diff --git a/cocos/2d/CCEventKeyboard.h b/cocos/2d/CCEventKeyboard.h index fffc76e0ac..b8cf7f8976 100644 --- a/cocos/2d/CCEventKeyboard.h +++ b/cocos/2d/CCEventKeyboard.h @@ -199,7 +199,7 @@ public: static const char* EVENT_TYPE; EventKeyboard(KeyCode keyCode, bool isPressed) - : Event(EVENT_TYPE) + : Event(TYPE_KEYBOARD) , _keyCode(keyCode) , _isPressed(isPressed) {}; diff --git a/cocos/2d/CCEventListener.cpp b/cocos/2d/CCEventListener.cpp index 8b34ca5173..9040593e0e 100644 --- a/cocos/2d/CCEventListener.cpp +++ b/cocos/2d/CCEventListener.cpp @@ -35,7 +35,7 @@ EventListener::~EventListener() CCLOGINFO("In the destructor of EventListener. %p", this); } -bool EventListener::init(const std::string& t, std::function callback) +bool EventListener::init(Type t, std::function callback) { _onEvent = callback; _type = t; diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index 672d9c98d0..bcedcec0c8 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -44,13 +44,24 @@ class Node; * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard, EventListenerTouchOneByOne, EventListenerCustom. */ class EventListener : public Object -{ +{ +public: + enum EventListenerType + { + TYPE_TOUCH_ONE_BY_ONE = 1, + TYPE_TOUCH_ALL_AT_ONCE, + TYPE_KEYBOARD, + TYPE_ACCELERATION, + TYPE_CUSTOM + }; + + typedef int Type; protected: /** Constructor */ EventListener(); /** Initializes event with type and callback function */ - bool init(const std::string& t, std::functioncallback); + bool init(Type t, std::functioncallback); public: /** Destructor */ virtual ~EventListener(); @@ -66,7 +77,7 @@ public: protected: std::function _onEvent; /// Event callback function - std::string _type; /// Event type + Type _type; /// Event type bool _isRegistered; /// Whether the listener has been added to dispatcher. // The priority of event listener diff --git a/cocos/2d/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp index d8b01fc4ce..01a9ef6398 100644 --- a/cocos/2d/CCEventListenerAcceleration.cpp +++ b/cocos/2d/CCEventListenerAcceleration.cpp @@ -59,7 +59,7 @@ bool EventListenerAcceleration::init(std::functiononAccelerationEvent(&accEvent->_acc, event); }; - if (EventListener::init(EventAcceleration::EVENT_TYPE, listener)) + if (EventListener::init(TYPE_ACCELERATION, listener)) { onAccelerationEvent = callback; return true; diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index abe4153198..05e562b567 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -32,10 +32,10 @@ EventListenerCustom::EventListenerCustom() { } -EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function callback) +EventListenerCustom* EventListenerCustom::create(int type, std::function callback) { EventListenerCustom* ret = new EventListenerCustom(); - if (ret && ret->init(eventName, callback)) + if (ret && ret->init(type, callback)) { ret->autorelease(); } @@ -46,7 +46,7 @@ EventListenerCustom* EventListenerCustom::create(const std::string& eventName, s return ret; } -bool EventListenerCustom::init(const std::string& eventName, std::functioncallback) +bool EventListenerCustom::init(int type, std::functioncallback) { bool ret = false; @@ -59,7 +59,7 @@ bool EventListenerCustom::init(const std::string& eventName, std::function callback); + static EventListenerCustom* create(int type, std::function callback); /// Overrides virtual bool checkAvailable() override; @@ -67,7 +67,7 @@ protected: EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(const std::string& eventName, std::function callback); + bool init(int type, std::function callback); std::function _onCustomEvent; }; diff --git a/cocos/2d/CCEventListenerKeyboard.cpp b/cocos/2d/CCEventListenerKeyboard.cpp index a6e3b617ae..fb733ed442 100644 --- a/cocos/2d/CCEventListenerKeyboard.cpp +++ b/cocos/2d/CCEventListenerKeyboard.cpp @@ -88,7 +88,7 @@ bool EventListenerKeyboard::init() } }; - if (EventListener::init(EventKeyboard::EVENT_TYPE, listener)) + if (EventListener::init(TYPE_KEYBOARD, listener)) { return true; } diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index 49ec1462c9..e753a113d0 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -46,7 +46,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne() bool EventListenerTouchOneByOne::init() { - if (EventListener::init(EventTouch::MODE_ONE_BY_ONE, nullptr)) + if (EventListener::init(TYPE_TOUCH_ONE_BY_ONE, nullptr)) { return true; } @@ -123,7 +123,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce() bool EventListenerTouchAllAtOnce::init() { - if (EventListener::init(EventTouch::MODE_ALL_AT_ONCE, nullptr)) + if (EventListener::init(TYPE_TOUCH_ALL_AT_ONCE, nullptr)) { return true; } diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 09e6e6fe0c..a73dc1e992 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -36,6 +36,8 @@ NS_CC_BEGIN class EventListenerTouchOneByOne : public EventListener { public: + static const int TYPE = 0x01; + static EventListenerTouchOneByOne* create(); virtual ~EventListenerTouchOneByOne(); @@ -67,6 +69,8 @@ private: class EventListenerTouchAllAtOnce : public EventListener { public: + static const int TYPE = 0x02; + static EventListenerTouchAllAtOnce* create(); virtual ~EventListenerTouchAllAtOnce(); diff --git a/cocos/2d/CCEventTouch.cpp b/cocos/2d/CCEventTouch.cpp index 987d87d0e9..d0df614973 100644 --- a/cocos/2d/CCEventTouch.cpp +++ b/cocos/2d/CCEventTouch.cpp @@ -26,9 +26,5 @@ NS_CC_BEGIN -const char* EventTouch::MODE_ONE_BY_ONE = "TouchEventOneByOne"; -const char* EventTouch::MODE_ALL_AT_ONCE = "TouchEventAllAtOnce"; - -const char* EventTouch::EVENT_TYPE = "TouchEvent"; NS_CC_END diff --git a/cocos/2d/CCEventTouch.h b/cocos/2d/CCEventTouch.h index 558bfe0593..100d67cf95 100644 --- a/cocos/2d/CCEventTouch.h +++ b/cocos/2d/CCEventTouch.h @@ -36,12 +36,6 @@ NS_CC_BEGIN class EventTouch : public Event { public: - static const char* MODE_ONE_BY_ONE; - static const char* MODE_ALL_AT_ONCE; - - static const char* EVENT_TYPE; - - static const int MAX_TOUCHES = 5; enum class EventCode @@ -53,7 +47,7 @@ public: }; EventTouch() - : Event(EVENT_TYPE) + : Event(TYPE_TOUCH) { _touches.reserve(MAX_TOUCHES); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 094e584e97..9b1e943019 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -247,7 +247,7 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y } touchEvent._eventCode = EventTouch::EventCode::BEGAN; - EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) @@ -294,7 +294,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys } touchEvent._eventCode = EventTouch::EventCode::MOVED; - EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) @@ -347,7 +347,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } touchEvent._eventCode = eventCode; - EventDispatcher::getInstance()->dispatchTouchEvent(&touchEvent); + EventDispatcher::getInstance()->dispatchEvent(&touchEvent); for (auto& touch : touchEvent._touches) { diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index d44129aee5..d4b5f9988e 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -189,7 +189,7 @@ void TouchableSpriteTest::onEnter() auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - EventDispatcher::getInstance()->removeListenersForEventType(EventTouch::EVENT_TYPE); + EventDispatcher::getInstance()->removeListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); auto nextItem = MenuItemFont::create("Next", [=](Object* sender){ nextCallback(nullptr); @@ -427,7 +427,8 @@ void CustomEventTest::onEnter() statusLabel->setPosition(origin + Point(size.width/2, size.height-90)); addChild(statusLabel); - _listener = EventListenerCustom::create("game_custom_event", [=](EventCustom* event){ + const int game_custom_event = EventListener::TYPE_CUSTOM + 1; + _listener = EventListenerCustom::create(game_custom_event, [=](EventCustom* event){ std::string str("Custom event received, "); char* buf = static_cast(event->getUserData()); str += buf; @@ -443,7 +444,7 @@ void CustomEventTest::onEnter() ++count; char* buf = new char[10]; sprintf(buf, "%d", count); - EventCustom event("game_custom_event"); + EventCustom event(game_custom_event); event.setUserData(buf); dispatcher->dispatchEvent(&event); }); From 30a3199a9132499143142dfbac9bca6c8908739a Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 15:19:04 +0800 Subject: [PATCH 237/557] [Dispatcher] Removing unused codes. --- cocos/2d/CCEventKeyboard.cpp | 1 - cocos/2d/CCEventListenerAcceleration.cpp | 2 +- cocos/2d/CCEventListenerAcceleration.h | 2 +- cocos/2d/CCEventListenerKeyboard.h | 4 ++-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCEventKeyboard.cpp b/cocos/2d/CCEventKeyboard.cpp index ceb2b49a8f..b02312fce1 100644 --- a/cocos/2d/CCEventKeyboard.cpp +++ b/cocos/2d/CCEventKeyboard.cpp @@ -27,6 +27,5 @@ NS_CC_BEGIN -const char* EventKeyboard::EVENT_TYPE = "KeyboardEvent"; NS_CC_END diff --git a/cocos/2d/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp index 01a9ef6398..d1d5d22206 100644 --- a/cocos/2d/CCEventListenerAcceleration.cpp +++ b/cocos/2d/CCEventListenerAcceleration.cpp @@ -37,7 +37,7 @@ EventListenerAcceleration::~EventListenerAcceleration() CCLOGINFO("In the destructor of AccelerationEventListener. %p", this); } -EventListenerAcceleration* EventListenerAcceleration::create(std::function callback) +EventListenerAcceleration* EventListenerAcceleration::create(std::function callback) { EventListenerAcceleration* ret = new EventListenerAcceleration(); if (ret && ret->init(callback)) diff --git a/cocos/2d/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h index 2905df9486..59ce3d8439 100644 --- a/cocos/2d/CCEventListenerAcceleration.h +++ b/cocos/2d/CCEventListenerAcceleration.h @@ -33,7 +33,7 @@ NS_CC_BEGIN class EventListenerAcceleration : public EventListener { public: - static EventListenerAcceleration* create(std::function callback); + static EventListenerAcceleration* create(std::function callback); virtual ~EventListenerAcceleration(); /// Overrides diff --git a/cocos/2d/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h index dd223da533..c34d2add0d 100644 --- a/cocos/2d/CCEventListenerKeyboard.h +++ b/cocos/2d/CCEventListenerKeyboard.h @@ -42,8 +42,8 @@ public: virtual EventListenerKeyboard* clone() override; virtual bool checkAvailable() override; - std::function onKeyPressed; - std::function onKeyReleased; + std::function onKeyPressed; + std::function onKeyReleased; private: EventListenerKeyboard(); bool init(); From efa5afb1c3f6a67a287c436fd453344159e6be71 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 15:19:25 +0800 Subject: [PATCH 238/557] [Dispatcher] Removing unused codes in Layer. --- cocos/2d/CCLayer.cpp | 25 ------------------------- cocos/2d/CCLayer.h | 7 ------- 2 files changed, 32 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index ed5caf3a71..127261efd5 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -87,31 +87,6 @@ Layer *Layer::create() } } -int Layer::executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch) -{ - if (kScriptTypeNone != _scriptType) - { - TouchScriptData data(eventType, this, touch); - ScriptEvent event(kTouchEvent, &data); - return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } - - //can not reach it - return 0; -} - -int Layer::executeScriptTouchesHandler(EventTouch::EventCode eventType, const std::vector& touches) -{ - if (kScriptTypeNone != _scriptType) - { - TouchesScriptData data(eventType, this, touches); - ScriptEvent event(kTouchesEvent, &data); - return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } - - return 0; -} - #ifdef CC_USE_PHYSICS void Layer::addChild(Node* child) { diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 09effe2fcd..e94224b580 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -118,13 +118,6 @@ public: virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; #endif // CC_USE_PHYSICS - -private: - Touch::DispatchMode _touchMode; - bool _swallowsTouches; - - int executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch); - int executeScriptTouchesHandler(EventTouch::EventCode eventType, const std::vector& touches); }; #ifdef __apple__ From 1339ef7ecbb21c31a55ddcc895dbf62c5e694de3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 15:20:06 +0800 Subject: [PATCH 239/557] [JSB] These are only for v2.x JSB compatibility after removing controller codes in Layer. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 4caa15159c..25626c360d 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -0d38b7e53d97995151ea296bdd1f4ed768ce2f9b \ No newline at end of file +c4104d83bf7e5cc0b0eab7bb3753f9f053358054 \ No newline at end of file From 312e1bd27c14899288dc3e0d090d8f9f15030582 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 15:40:21 +0800 Subject: [PATCH 240/557] [Dispatcher] Updating comments. --- cocos/2d/CCEventDispatcher.h | 54 ++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 53f2224b2b..25f1d8a509 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -80,7 +80,7 @@ public: */ void removeEventListener(EventListener* listener); - /** Removes all listeners with the same event type */ + /** Removes all listeners with the same event listener type */ void removeListeners(EventListener::Type eventListenerType); /** Removes all listeners */ @@ -101,19 +101,16 @@ public: */ void dispatchEvent(Event* event); - /// Priority dirty flag - enum class DirtyFlag - { - NONE = 0, - FIXED_PRITORY = 1 << 0, - SCENE_GRAPH_PRIORITY = 1 << 1, - ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY - }; - + /** Sets the dirty flag for a node. */ void setDirtyForNode(Node* node); + /** Notifys event dispatcher that the node has been paused. */ void pauseTarget(Node* node); + + /** Notifys event dispatcher that the node has been resumed. */ void resumeTarget(Node* node); + + /** Notifys event dispatcher that the node has been deleted. */ void cleanTarget(Node* node); public: @@ -122,6 +119,9 @@ public: private: + /** + * The vector to store event listeners with scene graph based priority and fixed priority. + */ class EventListenerVector { public: @@ -154,6 +154,7 @@ private: /** Gets event the listener list for the event listener type. */ EventListenerVector* getListeners(EventListener::Type eventListenerType); + /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Sort event listener */ @@ -174,31 +175,54 @@ private: /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ void dispatchTouchEvent(EventTouch* event); + /** Associates node with event listener */ void associateNodeAndEventListener(Node* node, EventListener* listener); + + /** Dissociates node with event listener */ void dissociateNodeAndEventListener(Node* node, EventListener* listener); + /** Dispatches event to listeners with a specified listener type */ void dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent); + /// Priority dirty flag + enum class DirtyFlag + { + NONE = 0, + FIXED_PRITORY = 1 << 0, + SCENE_GRAPH_PRIORITY = 1 << 1, + ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY + }; + + /** Sets the dirty flag for a specified listener type */ void setDirty(EventListener::Type listenerType, 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. - */ + /** Listeners map */ std::unordered_map _listeners; + /** The map of dirty flag */ std::unordered_map _priorityDirtyFlagMap; + /** The map of node and event listeners */ std::unordered_map*> _nodeListenersMap; + + /** The map of node and its event priority */ std::unordered_map _nodePriorityMap; + /** The listeners to be added after dispatching event */ std::vector _toAddedListeners; + + /** The nodes were associated with scene graph based priority listeners */ std::set _dirtyNodes; - int _inDispatch; ///< Whether it's in dispatching event - bool _isEnabled; ///< Whether to enable dispatching event + /** Whether the dispatcher is dispatching event */ + int _inDispatch; + + /** Whether to enable dispatching event */ + bool _isEnabled; }; From 262b54eef2cccb4d4b825f262b5c7ac3640b72b3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:06:52 +0800 Subject: [PATCH 241/557] issue #3069: Updating ScrollView. --- extensions/GUI/CCScrollView/CCScrollView.cpp | 43 ++++++++++++-------- extensions/GUI/CCScrollView/CCScrollView.h | 5 ++- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index ecc17ef0e7..35287bb9ce 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -56,6 +56,7 @@ ScrollView::ScrollView() , _touchLength(0.0f) , _minScale(0.0f) , _maxScale(0.0f) +, _touchListener(nullptr) { } @@ -109,14 +110,7 @@ bool ScrollView::initWithViewSize(Size size, Node *container/* = NULL*/) this->setViewSize(size); - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchOneByOne::create(); - listener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this); - listener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this); - listener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); - listener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); - - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + setTouchEnabled(true); _touches.reserve(EventTouch::MAX_TOUCHES); @@ -183,16 +177,29 @@ void ScrollView::resume(Object* sender) _container->resumeSchedulerAndActions(); } -//void ScrollView::setTouchEnabled(bool e) -//{ -// Layer::setTouchEnabled(e); -// if (!e) -// { -// _dragging = false; -// _touchMoved = false; -// _touches.clear(); -// } -//} +void ScrollView::setTouchEnabled(bool enabled) +{ + auto dispatcher = EventDispatcher::getInstance(); + + dispatcher->removeEventListener(_touchListener); + + if (enabled) + { + _touchListener = EventListenerTouchOneByOne::create(); + _touchListener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this); + _touchListener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this); + _touchListener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); + _touchListener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); + + dispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this); + } + else + { + _dragging = false; + _touchMoved = false; + _touches.clear(); + } +} void ScrollView::setContentOffset(Point offset, bool animated/* = false*/) { diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 42b9d78425..bd24efc8fb 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -166,7 +166,7 @@ public: */ void resume(Object* sender); - + void setTouchEnabled(bool enabled); bool isDragging() const {return _dragging;} bool isTouchMoved() const { return _touchMoved; } bool isBounceable() const { return _bounceable; } @@ -347,6 +347,9 @@ protected: */ Rect _parentScissorRect; bool _scissorRestored; + + /** Touch listener */ + EventListenerTouchOneByOne* _touchListener; }; // end of GUI group From 0d2d522f12c3eca2b56c1412450b0171f48f04f6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:15:37 +0800 Subject: [PATCH 242/557] issue #3069: int --> EventListener::Type. --- cocos/2d/CCEventListenerCustom.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index 05e562b567..3875f61c94 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -32,7 +32,7 @@ EventListenerCustom::EventListenerCustom() { } -EventListenerCustom* EventListenerCustom::create(int type, std::function callback) +EventListenerCustom* EventListenerCustom::create(Type type, std::function callback) { EventListenerCustom* ret = new EventListenerCustom(); if (ret && ret->init(type, callback)) From cf20329b71aaa175407175673acbd58351449f14 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:33:54 +0800 Subject: [PATCH 243/557] issue #3069: Removing unused codes in UILayer. --- cocos/gui/UILayer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index 891301bf5b..d3a4e69fc5 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -89,7 +89,6 @@ void UILayer::onEnter() void UILayer::onExit() { -// setTouchEnabled(false); CCLayer::onExit(); } From 9bf44a6c83e67413bb9e245f03358be2e137340f Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:34:26 +0800 Subject: [PATCH 244/557] issue #3069: Renaming 'removeListeners' to 'removeEventListeners'. --- cocos/2d/CCEventDispatcher.cpp | 8 ++++---- cocos/2d/CCEventDispatcher.h | 4 ++-- .../NewEventDispatcherTest/NewEventDispatcherTest.cpp | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index a0e58363a3..386191f8a6 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -151,7 +151,7 @@ EventDispatcher::EventDispatcher() EventDispatcher::~EventDispatcher() { - removeAllListeners(); + removeAllEventListeners(); } EventDispatcher* EventDispatcher::getInstance() @@ -972,7 +972,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene return nullptr; } -void EventDispatcher::removeListeners(EventListener::Type eventListenerType) +void EventDispatcher::removeEventListeners(EventListener::Type eventListenerType) { auto listenerItemIter = _listeners.find(eventListenerType); if (listenerItemIter != _listeners.end()) @@ -1019,7 +1019,7 @@ void EventDispatcher::removeListeners(EventListener::Type eventListenerType) } } -void EventDispatcher::removeAllListeners() +void EventDispatcher::removeAllEventListeners() { std::vector types(_listeners.size()); @@ -1030,7 +1030,7 @@ void EventDispatcher::removeAllListeners() for (auto& type : types) { - removeListeners(type); + removeEventListeners(type); } if (!_inDispatch) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 25f1d8a509..a678431f7d 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -81,10 +81,10 @@ public: void removeEventListener(EventListener* listener); /** Removes all listeners with the same event listener type */ - void removeListeners(EventListener::Type eventListenerType); + void removeEventListeners(EventListener::Type eventListenerType); /** Removes all listeners */ - void removeAllListeners(); + void removeAllEventListeners(); /** Sets listener's priority with fixed value. */ void setPriority(EventListener* listener, int fixedPriority); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index d4b5f9988e..cecb32a6d8 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -189,7 +189,7 @@ void TouchableSpriteTest::onEnter() auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - EventDispatcher::getInstance()->removeListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + EventDispatcher::getInstance()->removeEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); auto nextItem = MenuItemFont::create("Next", [=](Object* sender){ nextCallback(nullptr); From cb7e0b391bffcc32098be8c0fc520cb86e71170f Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:37:40 +0800 Subject: [PATCH 245/557] issue #3069: Removing unused variables in CCEventListenerTouch.h. --- cocos/2d/CCEventListenerTouch.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index a73dc1e992..09e6e6fe0c 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -36,8 +36,6 @@ NS_CC_BEGIN class EventListenerTouchOneByOne : public EventListener { public: - static const int TYPE = 0x01; - static EventListenerTouchOneByOne* create(); virtual ~EventListenerTouchOneByOne(); @@ -69,8 +67,6 @@ private: class EventListenerTouchAllAtOnce : public EventListener { public: - static const int TYPE = 0x02; - static EventListenerTouchAllAtOnce* create(); virtual ~EventListenerTouchAllAtOnce(); From 063b012a9c692576cf4f6d87f6e00a57448df39e Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 16:43:04 +0800 Subject: [PATCH 246/557] int --> Event::Type --- cocos/2d/CCEvent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCEvent.h b/cocos/2d/CCEvent.h index 348c2ba1d3..eecd7f396c 100644 --- a/cocos/2d/CCEvent.h +++ b/cocos/2d/CCEvent.h @@ -58,7 +58,7 @@ public: virtual ~Event(); /** Gets the event type */ - inline int getType() const { return _type; }; + inline Type getType() const { return _type; }; /** Stops propagation for current event */ inline void stopPropagation() { _isStopped = true; }; From 6c6757a04e3d4af114fa279a4930f3ce7b27d390 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 25 Oct 2013 17:03:50 +0800 Subject: [PATCH 247/557] issue #3069: Moving s_eventPriorityIndex to member variable of EventDispatcher. --- cocos/2d/CCEventDispatcher.cpp | 9 +++++---- cocos/2d/CCEventDispatcher.h | 2 ++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 386191f8a6..e8d6331c0a 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -59,7 +59,7 @@ private: NS_CC_BEGIN static EventDispatcher* g_instance = nullptr; -static int s_eventPriorityIndex = 0; + EventDispatcher::EventListenerVector::EventListenerVector() : _sceneGraphListeners(nullptr) @@ -145,6 +145,7 @@ void EventDispatcher::EventListenerVector::clear() EventDispatcher::EventDispatcher() : _inDispatch(0) , _isEnabled(true) +, _nodePriorityIndex(0) { _toAddedListeners.reserve(50); } @@ -190,7 +191,7 @@ void EventDispatcher::visitTarget(Node* node) break; } - _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); + _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); for( ; i < childrenCount; i++ ) { @@ -201,7 +202,7 @@ void EventDispatcher::visitTarget(Node* node) } else { - _nodePriorityMap.insert(std::make_pair(node, ++s_eventPriorityIndex)); + _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); } } @@ -907,7 +908,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::Type Node* rootNode = (Node*)Director::getInstance()->getRunningScene(); // Reset priority index - s_eventPriorityIndex = 0; + _nodePriorityIndex = 0; _nodePriorityMap.clear(); visitTarget(rootNode); diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index a678431f7d..60baf25222 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -223,6 +223,8 @@ private: /** Whether to enable dispatching event */ bool _isEnabled; + + int _nodePriorityIndex; }; From 9ecc0c6db862c1ef09cfef4862a10bbdb2d7ba22 Mon Sep 17 00:00:00 2001 From: psi Date: Sat, 26 Oct 2013 13:33:31 +0900 Subject: [PATCH 248/557] include climits for UINT_MAX --- cocos/physics/CCPhysicsBody.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 109fac9d6f..f1eb18e754 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -24,6 +24,7 @@ #include "CCPhysicsBody.h" #ifdef CC_USE_PHYSICS +#include #include #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) From 48ce5e39fe6d4394c4c175c2690ef3ed119d9e40 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 26 Oct 2013 15:04:01 +0800 Subject: [PATCH 249/557] EventDispatcher is managed by Director now, like Scheduler and ActionManager. --- cocos/2d/CCDirector.cpp | 23 +++++++-- cocos/2d/CCDirector.h | 21 ++++++-- cocos/2d/CCEventDispatcher.cpp | 18 ------- cocos/2d/CCEventDispatcher.h | 14 ++---- cocos/2d/CCMenu.cpp | 4 +- cocos/2d/CCNode.cpp | 48 ++++++++++++++----- cocos/2d/CCNode.h | 28 ++++++++--- cocos/2d/CCTransition.cpp | 8 +--- cocos/2d/platform/CCEGLViewProtocol.cpp | 9 ++-- cocos/2d/platform/ios/CCDevice.mm | 2 +- cocos/2d/platform/mac/CCEGLView.mm | 3 +- .../cocostudio/CCInputDelegate.cpp | 16 ++++--- cocos/gui/UILayer.cpp | 2 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../GUI/CCControlExtension/CCControl.cpp | 2 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 14 +++--- .../AccelerometerTest/AccelerometerTest.cpp | 4 +- .../Classes/ActionsTest/ActionsTest.cpp | 2 +- .../Classes/Box2DTestBed/Box2dView.cpp | 8 ++-- .../Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 6 +-- .../Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp | 3 +- .../Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp | 2 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 4 +- .../ClickAndMoveTest/ClickAndMoveTest.cpp | 3 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 6 +-- .../CocosDenshionTest/CocosDenshionTest.cpp | 2 +- .../Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 6 +-- .../Classes/ExtensionsTest/ExtensionsTest.cpp | 2 +- .../Classes/KeyboardTest/KeyboardTest.cpp | 2 +- .../TestCpp/Classes/KeypadTest/KeypadTest.cpp | 2 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 2 +- .../Classes/LabelTest/LabelTestNew.cpp | 2 +- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 4 +- .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 12 ++--- .../MotionStreakTest/MotionStreakTest.cpp | 2 +- .../Classes/MutiTouchTest/MutiTouchTest.cpp | 2 +- .../NewEventDispatcherTest.cpp | 47 +++++++----------- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 2 +- .../Classes/ParallaxTest/ParallaxTest.cpp | 2 +- .../Classes/ParticleTest/ParticleTest.cpp | 2 +- .../PerformanceTouchesTest.cpp | 12 ++--- .../Classes/PhysicsTest/PhysicsTest.cpp | 8 ++-- .../RenderTextureTest/RenderTextureTest.cpp | 6 +-- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/TextInputTest/TextInputTest.cpp | 2 +- .../Classes/TileMapTest/TileMapTest.cpp | 2 +- .../TestCpp/Classes/TouchesTest/Paddle.cpp | 2 +- samples/Cpp/TestCpp/Classes/controller.cpp | 2 +- 49 files changed, 199 insertions(+), 182 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 9dc388ea11..ef8b38f423 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -59,7 +59,7 @@ THE SOFTWARE. #include "platform/CCImage.h" #include "CCEGLView.h" #include "CCConfiguration.h" - +#include "CCEventDispatcher.h" /** Position of the FPS @@ -143,6 +143,8 @@ bool Director::init(void) _actionManager = new ActionManager(); _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); + _eventDispatcher = new EventDispatcher(); + // create autorelease pool PoolManager::sharedPoolManager()->push(); @@ -162,7 +164,8 @@ Director::~Director(void) CC_SAFE_RELEASE(_scenesStack); CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_actionManager); - + CC_SAFE_RELEASE(_eventDispatcher); + // pop the autorelease pool PoolManager::sharedPoolManager()->pop(); PoolManager::purgePoolManager(); @@ -695,7 +698,6 @@ void Director::purgeDirector() // cocos2d-x specific data structures UserDefault::destroyInstance(); NotificationCenter::destroyInstance(); - EventDispatcher::destroyInstance(); GL::invalidateStateCache(); @@ -966,6 +968,21 @@ ActionManager* Director::getActionManager() const return _actionManager; } +EventDispatcher* Director::getEventDispatcher() const +{ + return _eventDispatcher; +} + +void Director::setEventDispatcher(EventDispatcher* dispatcher) +{ + if (_eventDispatcher != dispatcher) + { + CC_SAFE_RETAIN(dispatcher); + CC_SAFE_RELEASE(_eventDispatcher); + _eventDispatcher = dispatcher; + } +} + /*************************************************** * implementation of DisplayLinkDirector **************************************************/ diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 4da35a96a8..5f0d6eb0a8 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -53,10 +53,7 @@ class DirectorDelegate; class Node; class Scheduler; class ActionManager; -class TouchDispatcher; -class KeyboardDispatcher; -class KeypadDispatcher; -class Accelerometer; +class EventDispatcher; /** @brief Class that creates and handles the main Window and manages how @@ -351,6 +348,17 @@ public: @since v2.0 */ void setActionManager(ActionManager* actionManager); + + /** Gets the EventDispatcher associated with this director + @since v3.0 + */ + EventDispatcher* getEventDispatcher() const; + + /** Sets the EventDispatcher associated with this director + @since v3.0 + */ + void setEventDispatcher(EventDispatcher* dispatcher); + /* Gets delta time since last tick to main loop */ float getDeltaTime() const; @@ -383,6 +391,11 @@ protected: @since v2.0 */ ActionManager* _actionManager; + + /** EventDispatcher associated with this director + @since v3.0 + */ + EventDispatcher* _eventDispatcher; /* delta time since last tick to main loop */ float _deltaTime; diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index e8d6331c0a..e0922b0796 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -58,9 +58,6 @@ private: NS_CC_BEGIN -static EventDispatcher* g_instance = nullptr; - - EventDispatcher::EventListenerVector::EventListenerVector() : _sceneGraphListeners(nullptr) , _fixedListeners(nullptr) @@ -155,21 +152,6 @@ EventDispatcher::~EventDispatcher() removeAllEventListeners(); } -EventDispatcher* EventDispatcher::getInstance() -{ - if (g_instance == nullptr) - { - g_instance = new EventDispatcher(); - } - - return g_instance; -} - -void EventDispatcher::destroyInstance() -{ - CC_SAFE_DELETE(g_instance); -} - void EventDispatcher::visitTarget(Node* node) { int i = 0; diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 60baf25222..e3650a1fae 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -50,15 +50,9 @@ event listeners can be added and removed even from within an EventListener, while events are being dispatched. */ -class EventDispatcher +class EventDispatcher : public Object { public: - /** Gets the singleton of EventDispatcher */ - static EventDispatcher* getInstance(); - - /** Destroys the singleton of EventDispatcher */ - static void destroyInstance(); - /** Adds a event listener for a specified event with the priority of scene graph. * @param listener The listener of a specified event. * @param node The priority of the listener is based on the draw order of this node. @@ -113,7 +107,8 @@ public: /** Notifys event dispatcher that the node has been deleted. */ void cleanTarget(Node* node); -public: + /** Constructor of EventDispatcher */ + EventDispatcher(); /** Destructor of EventDispatcher */ ~EventDispatcher(); @@ -144,9 +139,6 @@ private: std::vector* _sceneGraphListeners; int _gt0Index; }; - - /** Constructor of EventDispatcher */ - EventDispatcher(); /** Adds event listener with item */ void addEventListener(EventListener* listener); diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 5a46765d91..3b0cefbec3 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -185,8 +185,6 @@ void Menu::onEnter() { Layer::onEnter(); - auto eventDispatcher = EventDispatcher::getInstance(); - auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); @@ -195,7 +193,7 @@ void Menu::onEnter() touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this); touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this); - eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); } void Menu::onExit() diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 427884abb0..5302648923 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -139,7 +139,9 @@ Node::Node(void) _actionManager->retain(); _scheduler = director->getScheduler(); _scheduler->retain(); - + _eventDispatcher = director->getEventDispatcher(); + _eventDispatcher->retain(); + ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); _scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone; } @@ -155,6 +157,10 @@ Node::~Node() CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_scheduler); + + _eventDispatcher->cleanTarget(this); + CC_SAFE_RELEASE(_eventDispatcher); + // attributes CC_SAFE_RELEASE(_camera); @@ -182,8 +188,6 @@ Node::~Node() CC_SAFE_DELETE(_componentContainer); - EventDispatcher::getInstance()->cleanTarget(this); - #ifdef CC_USE_PHYSICS CC_SAFE_RELEASE(_physicsBody); #endif @@ -238,7 +242,7 @@ void Node::setZOrder(int z) _parent->reorderChild(this, z); } - EventDispatcher::getInstance()->setDirtyForNode(this); + _eventDispatcher->setDirtyForNode(this); } /// vertexZ getter @@ -931,8 +935,7 @@ void Node::onEnter() arrayMakeObjectsPerformSelector(_children, onEnter, Node*); - this->resumeSchedulerAndActions(); - EventDispatcher::getInstance()->resumeTarget(this); + this->resume(); _running = true; @@ -974,9 +977,7 @@ void Node::onExitTransitionDidStart() void Node::onExit() { - EventDispatcher::getInstance()->pauseTarget(this); - - this->pauseSchedulerAndActions(); + this->pause(); _running = false; if (_scriptType != kScriptTypeNone) @@ -990,6 +991,17 @@ void Node::onExit() arrayMakeObjectsPerformSelector(_children, onExit, Node*); } +void Node::setEventDispatcher(EventDispatcher* dispatcher) +{ + if (dispatcher != _eventDispatcher) + { + _eventDispatcher->cleanTarget(this); + CC_SAFE_RETAIN(dispatcher); + CC_SAFE_RELEASE(_eventDispatcher); + _eventDispatcher = dispatcher; + } +} + void Node::setActionManager(ActionManager* actionManager) { if( actionManager != _actionManager ) { @@ -1115,16 +1127,28 @@ void Node::unscheduleAllSelectors() _scheduler->unscheduleAllForTarget(this); } -void Node::resumeSchedulerAndActions() +void Node::resume() { _scheduler->resumeTarget(this); _actionManager->resumeTarget(this); + _eventDispatcher->resumeTarget(this); +} + +void Node::pause() +{ + _scheduler->pauseTarget(this); + _actionManager->pauseTarget(this); + _eventDispatcher->pauseTarget(this); +} + +void Node::resumeSchedulerAndActions() +{ + resume(); } void Node::pauseSchedulerAndActions() { - _scheduler->pauseTarget(this); - _actionManager->pauseTarget(this); + pause(); } // override me diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index fcc38b23b5..cde05c34c3 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -995,6 +995,9 @@ public: /** @deprecated Use getBoundingBox instead */ CC_DEPRECATED_ATTRIBUTE inline virtual Rect boundingBox() const { return getBoundingBox(); } + virtual void setEventDispatcher(EventDispatcher* dispatcher); + virtual EventDispatcher* getEventDispatcher() const { return _eventDispatcher; }; + /// @{ /// @name Actions @@ -1192,16 +1195,27 @@ public: */ void unscheduleAllSelectors(void); - /** - * Resumes all scheduled selectors and actions. + /** + * Resumes all scheduled selectors, actions and event listeners. * This method is called internally by onEnter */ - void resumeSchedulerAndActions(void); - /** - * Pauses all scheduled selectors and actions. + void resume(void); + /** + * Pauses all scheduled selectors, actions and event listeners.. * This method is called internally by onExit */ - void pauseSchedulerAndActions(void); + void pause(void); + + /** + * Resumes all scheduled selectors, actions and event listeners. + * This method is called internally by onEnter + */ + CC_DEPRECATED_ATTRIBUTE void resumeSchedulerAndActions(void); + /** + * Pauses all scheduled selectors, actions and event listeners.. + * This method is called internally by onExit + */ + CC_DEPRECATED_ATTRIBUTE void pauseSchedulerAndActions(void); /* * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" @@ -1461,6 +1475,8 @@ protected: ActionManager *_actionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions + EventDispatcher* _eventDispatcher; ///< event dispatcher used to dispatch all kinds of events + bool _running; ///< is running bool _visible; ///< is this node visible diff --git a/cocos/2d/CCTransition.cpp b/cocos/2d/CCTransition.cpp index 5dea9ae721..4642b7404b 100644 --- a/cocos/2d/CCTransition.cpp +++ b/cocos/2d/CCTransition.cpp @@ -160,9 +160,7 @@ void TransitionScene::onEnter() Scene::onEnter(); // disable events while transitions -// Director::getInstance()->getTouchDispatcher()->setDispatchEvents(false); - - EventDispatcher::getInstance()->setEnabled(false); + _eventDispatcher->setEnabled(false); // outScene should not receive the onEnter callback // only the onExitTransitionDidStart @@ -177,9 +175,7 @@ void TransitionScene::onExit() Scene::onExit(); // enable events while transitions -// Director::getInstance()->getTouchDispatcher()->setDispatchEvents(true); - - EventDispatcher::getInstance()->setEnabled(true); + _eventDispatcher->setEnabled(true); _outScene->onExit(); // _inScene should not receive the onEnter callback diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 9b1e943019..17eafdf0d6 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -247,7 +247,8 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y } touchEvent._eventCode = EventTouch::EventCode::BEGAN; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) @@ -294,7 +295,8 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys } touchEvent._eventCode = EventTouch::EventCode::MOVED; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&touchEvent); } void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) @@ -347,7 +349,8 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } touchEvent._eventCode = eventCode; - EventDispatcher::getInstance()->dispatchEvent(&touchEvent); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&touchEvent); for (auto& touch : touchEvent._touches) { diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index 83212d575d..fdc9448849 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -100,7 +100,7 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; } cocos2d::EventAcceleration event(*_acceleration); - cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); + cocos2d::_eventDispatcherdispatchEvent(&event); } @end diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index d8dce7ba57..bd3ba3b5c5 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -239,7 +239,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - EventDispatcher::getInstance()->dispatchEvent(&event); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index 968645bc4e..a134e3cdfe 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -43,7 +43,7 @@ InputDelegate::InputDelegate(void) InputDelegate::~InputDelegate(void) { - auto dispatcher = EventDispatcher::getInstance(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->removeEventListener(_touchListener); dispatcher->removeEventListener(_keyboardListener); dispatcher->removeEventListener(_accelerometerListener); @@ -107,6 +107,7 @@ void InputDelegate::setTouchEnabled(bool enabled) { if (_touchEnabled != enabled) { + auto dispatcher = Director::getInstance()->getEventDispatcher(); _touchEnabled = enabled; if (enabled) { @@ -119,7 +120,7 @@ void InputDelegate::setTouchEnabled(bool enabled) listener->onTouchesEnded = CC_CALLBACK_2(InputDelegate::onTouchesEnded, this); listener->onTouchesCancelled = CC_CALLBACK_2(InputDelegate::onTouchesCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, _touchPriority); + dispatcher->addEventListenerWithFixedPriority(listener, _touchPriority); _touchListener = listener; } else { // Register Touch Event @@ -131,13 +132,13 @@ void InputDelegate::setTouchEnabled(bool enabled) listener->onTouchEnded = CC_CALLBACK_2(InputDelegate::onTouchEnded, this); listener->onTouchCancelled = CC_CALLBACK_2(InputDelegate::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, _touchPriority); + dispatcher->addEventListenerWithFixedPriority(listener, _touchPriority); _touchListener = listener; } } else { - EventDispatcher::getInstance()->removeEventListener(_touchListener); + dispatcher->removeEventListener(_touchListener); } } } @@ -191,7 +192,7 @@ void InputDelegate::setAccelerometerEnabled(bool enabled) { _accelerometerEnabled = enabled; - auto dispatcher = EventDispatcher::getInstance(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->removeEventListener(_accelerometerListener); _accelerometerListener = nullptr; @@ -215,7 +216,8 @@ void InputDelegate::setKeypadEnabled(bool enabled) { _keypadEnabled = enabled; - EventDispatcher::getInstance()->removeEventListener(_keyboardListener); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->removeEventListener(_keyboardListener); if (enabled) { @@ -223,7 +225,7 @@ void InputDelegate::setKeypadEnabled(bool enabled) listener->onKeyPressed = CC_CALLBACK_2(InputDelegate::onKeyPressed, this); listener->onKeyReleased = CC_CALLBACK_2(InputDelegate::onKeyReleased, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, -1); + dispatcher->addEventListenerWithFixedPriority(listener, -1); _keyboardListener = listener; } } diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index d3a4e69fc5..bfdea4094f 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -84,7 +84,7 @@ void UILayer::onEnter() listener->onTouchEnded = CC_CALLBACK_2(UILayer::onTouchEnded, this); listener->onTouchCancelled = CC_CALLBACK_2(UILayer::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void UILayer::onExit() diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 25626c360d..c661a05129 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c4104d83bf7e5cc0b0eab7bb3753f9f053358054 \ No newline at end of file +1475f1478d176a00cc8d0f9b3302881dee7a8437 \ No newline at end of file diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 1419edbc36..2b97094acc 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -97,7 +97,7 @@ void Control::onEnter() { Layer::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 35287bb9ce..8db57d6377 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -151,7 +151,7 @@ bool ScrollView::isNodeVisible(Node* node) void ScrollView::pause(Object* sender) { - _container->pauseSchedulerAndActions(); + _container->pause(); Object* pObj = NULL; Array* pChildren = _container->getChildren(); @@ -159,7 +159,7 @@ void ScrollView::pause(Object* sender) CCARRAY_FOREACH(pChildren, pObj) { Node* pChild = static_cast(pObj); - pChild->pauseSchedulerAndActions(); + pChild->pause(); } } @@ -171,17 +171,15 @@ void ScrollView::resume(Object* sender) CCARRAY_FOREACH(pChildren, pObj) { Node* pChild = static_cast(pObj); - pChild->resumeSchedulerAndActions(); + pChild->resume(); } - _container->resumeSchedulerAndActions(); + _container->resume(); } void ScrollView::setTouchEnabled(bool enabled) { - auto dispatcher = EventDispatcher::getInstance(); - - dispatcher->removeEventListener(_touchListener); + _eventDispatcher->removeEventListener(_touchListener); if (enabled) { @@ -191,7 +189,7 @@ void ScrollView::setTouchEnabled(bool enabled) _touchListener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this); _touchListener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this); - dispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this); } else { diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index ada7540cc6..db535fe321 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,10 +32,8 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto label = LabelTTF::create(title().c_str(), "Arial", 32); addChild(label, 1); diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index c41f06c377..703e8bf40b 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1377,7 +1377,7 @@ void ActionStacked::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(ActionStacked::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); this->addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index 0cfbabd90c..e50611afda 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -33,7 +33,7 @@ MenuLayer::MenuLayer(void) MenuLayer::~MenuLayer(void) { - EventDispatcher::getInstance()->removeEventListener(_touchListener); + _eventDispatcher->removeEventListener(_touchListener); } MenuLayer* MenuLayer::menuWithEntryID(int entryId) @@ -86,7 +86,7 @@ bool MenuLayer::initWithEntryID(int entryId) listener->onTouchBegan = CC_CALLBACK_2(MenuLayer::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(MenuLayer::onTouchMoved, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, 1); + _eventDispatcher->addEventListenerWithFixedPriority(listener, 1); _touchListener = listener; @@ -190,7 +190,7 @@ bool Box2DView::initWithEntryID(int entryId) listener->onTouchMoved = CC_CALLBACK_2(Box2DView::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(Box2DView::onTouchEnded, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, -10); + _eventDispatcher->addEventListenerWithFixedPriority(listener, -10); _touchListener = listener; return true; @@ -224,7 +224,7 @@ void Box2DView::draw() Box2DView::~Box2DView() { // Removes Touch Event Listener - EventDispatcher::getInstance()->removeEventListener(_touchListener); + _eventDispatcher->removeEventListener(_touchListener); delete m_test; } // diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index 9eb6d6ab5c..e0c4ba23ed 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,9 +20,8 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f); @@ -61,9 +60,8 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp index 76ab5b3b31..1064524e1c 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp @@ -30,11 +30,10 @@ bool Bug914Layer::init() // Apple recommends to re-assign "self" with the "super" return value if (BugsTestBaseLayer::init()) { - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp index 1d81217bbb..096ca45d21 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp @@ -72,7 +72,7 @@ void BugsTestMainLayer::onEnter() listener->onTouchesBegan = CC_CALLBACK_2(BugsTestMainLayer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(BugsTestMainLayer::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void BugsTestMainLayer::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index bb3ef0e12f..50d5dc7252 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -24,10 +24,10 @@ ChipmunkTestLayer::ChipmunkTestLayer() auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(touchListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(accListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); // title auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36); diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp index 408188925f..6b45dd9c32 100644 --- a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp @@ -17,11 +17,10 @@ void ClickAndMoveTestScene::runThisTest() MainLayer::MainLayer() { - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto sprite = Sprite::create(s_pathGrossini); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 56ad34de68..93e26514a2 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -449,10 +449,9 @@ void HoleDemo::setup() this->addChild(_outerClipper); - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void HoleDemo::pokeHoleAtPoint(Point point) @@ -529,12 +528,11 @@ void ScrollViewDemo::setup() _scrolling = false; - auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void ScrollViewDemo::onTouchesBegan(const std::vector& touches, Event *event) diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp index e83cb001f1..63959537d8 100644 --- a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp @@ -72,7 +72,7 @@ private: listener->onTouchEnded = CC_CALLBACK_2(Button::onTouchEnded, this); listener->onTouchCancelled = CC_CALLBACK_2(Button::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp index f3ad65db63..8d92edf249 100644 --- a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp +++ b/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp @@ -11,7 +11,7 @@ CurlTest::CurlTest() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(CurlTest::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // create a label to display the tip string _label = LabelTTF::create("Touch the screen to connect", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index fef387ac01..1cd233ffd2 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -480,7 +480,7 @@ void TestParticleDisplay::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(TestParticleDisplay::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); animationID = 0; @@ -540,7 +540,7 @@ void TestUseMutiplePicture::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(TestUseMutiplePicture::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); displayIndex = 0; @@ -944,7 +944,7 @@ void TestArmatureNesting::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); armature = Armature::create("cyborg"); armature->getAnimation()->playByIndex(1); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp index 5ba010f2a9..96089e9a2c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -122,7 +122,7 @@ void ExtensionsMainLayer::onEnter() listener->onTouchesBegan = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); addChild(_itemMenu); } diff --git a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp index a8a164da01..24b95f0df6 100644 --- a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp @@ -11,7 +11,7 @@ KeyboardTest::KeyboardTest() listener->onKeyPressed = CC_CALLBACK_2(KeyboardTest::onKeyPressed, this); listener->onKeyReleased = CC_CALLBACK_2(KeyboardTest::onKeyReleased, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // create a label to display the tip string _label = LabelTTF::create("Please press any key and see console log...", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp index c3191d5724..b025680265 100644 --- a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp +++ b/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp @@ -10,7 +10,7 @@ KeypadTest::KeypadTest() auto listener = EventListenerKeyboard::create(); listener->onKeyReleased = CC_CALLBACK_2(KeypadTest::onKeyReleased, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // create a label to display the tip string _label = LabelTTF::create("Please press any key...", "Arial", 22); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index f95831074e..ea9405eabe 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -1140,7 +1140,7 @@ BitmapFontMultiLineAlignment::BitmapFontMultiLineAlignment() listener->onTouchesMoved = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index d6d5777ada..f22c5a7864 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -655,7 +655,7 @@ LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // ask director the the window size auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index 9fcc560cdf..581928a4f3 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -454,7 +454,7 @@ void LayerTest1::onEnter() listener->onTouchesMoved = CC_CALLBACK_2(LayerTest1::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(LayerTest1::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); @@ -597,7 +597,7 @@ LayerGradientTest::LayerGradientTest() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(LayerGradientTest::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto label1 = LabelTTF::create("Compressed Interpolation: Enabled", "Marker Felt", 26); auto label2 = LabelTTF::create("Compressed Interpolation: Disabled", "Marker Felt", 26); diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index d295de75bc..f85bb260cd 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -32,7 +32,7 @@ MenuLayerMainMenu::MenuLayerMainMenu() _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this); _touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(_touchListener, 1); + _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 1); // Font Item auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); @@ -138,7 +138,7 @@ void MenuLayerMainMenu::onTouchMoved(Touch *touch, Event * event) MenuLayerMainMenu::~MenuLayerMainMenu() { - EventDispatcher::getInstance()->removeEventListener(_touchListener); + _eventDispatcher->removeEventListener(_touchListener); _disabledItem->release(); } @@ -154,7 +154,7 @@ void MenuLayerMainMenu::menuCallbackConfig(Object* sender) void MenuLayerMainMenu::allowTouches(float dt) { - EventDispatcher::getInstance()->setPriority(_touchListener, 1); + _eventDispatcher->setPriority(_touchListener, 1); unscheduleAllSelectors(); log("TOUCHES ALLOWED AGAIN"); } @@ -162,7 +162,7 @@ void MenuLayerMainMenu::allowTouches(float dt) void MenuLayerMainMenu::menuCallbackDisabled(Object* sender) { // hijack all touch events for 5 seconds - EventDispatcher::getInstance()->setPriority(_touchListener, -1); + _eventDispatcher->setPriority(_touchListener, -1); schedule(schedule_selector(MenuLayerMainMenu::allowTouches), 5.0f); log("TOUCHES DISABLED FOR 5 SECONDS"); } @@ -583,7 +583,7 @@ RemoveMenuItemWhenMove::RemoveMenuItemWhenMove() _touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this); _touchListener->onTouchMoved = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchMoved, this); - EventDispatcher::getInstance()->addEventListenerWithFixedPriority(_touchListener, -129); + _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, -129); } @@ -594,7 +594,7 @@ void RemoveMenuItemWhenMove::goBack(Object *pSender) RemoveMenuItemWhenMove::~RemoveMenuItemWhenMove() { - EventDispatcher::getInstance()->removeEventListener(_touchListener); + _eventDispatcher->removeEventListener(_touchListener); CC_SAFE_RELEASE(item); } diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp index 13a376ec29..9d9057c3e7 100644 --- a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -123,7 +123,7 @@ void MotionStreakTest2::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp index 42e6634de5..2287ff517a 100644 --- a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp @@ -60,7 +60,7 @@ bool MutiTouchTestLayer::init() listener->onTouchesBegan = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(MutiTouchTestLayer::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto title = LabelTTF::create("Please touch the screen!", "", 24); title->setPosition(VisibleRect::top()+Point(0, -40)); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index cecb32a6d8..aa45afa24d 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -124,8 +124,6 @@ void TouchableSpriteTest::onEnter() { EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -180,16 +178,16 @@ void TouchableSpriteTest::onEnter() } }; - dispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); - dispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2); - dispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3); auto removeAllTouchItem = MenuItemFont::create("Remove All Touch Listeners", [this](Object* sender){ auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - EventDispatcher::getInstance()->removeEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + _eventDispatcher->removeEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); auto nextItem = MenuItemFont::create("Next", [=](Object* sender){ nextCallback(nullptr); @@ -242,8 +240,6 @@ public: { Sprite::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); @@ -271,19 +267,18 @@ public: if (_useNodePriority) { - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } else { - dispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); + _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); } _listener = listener; } void onExit() override { - auto dispatcher = EventDispatcher::getInstance(); - dispatcher->removeEventListener(_listener); + _eventDispatcher->removeEventListener(_listener); Sprite::onExit(); } @@ -339,8 +334,6 @@ void RemoveListenerWhenDispatching::onEnter() { EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -372,7 +365,7 @@ void RemoveListenerWhenDispatching::onEnter() sprite1->setColor(Color3B::WHITE); }; - dispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); auto statusLabel = LabelTTF::create("The sprite could be touched!", "", 20); statusLabel->setPosition(origin + Point(size.width/2, size.height-90)); @@ -382,14 +375,14 @@ void RemoveListenerWhenDispatching::onEnter() auto toggleItem = MenuItemToggle::createWithCallback([=](Object* sender){ if (*enable) { - dispatcher->removeEventListener(listener1); + _eventDispatcher->removeEventListener(listener1); statusLabel->setString("The sprite could not be touched!"); (*enable) = false; } else { - dispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1); statusLabel->setString("The sprite could be touched!"); (*enable) = true; @@ -418,8 +411,6 @@ void CustomEventTest::onEnter() { EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -437,7 +428,7 @@ void CustomEventTest::onEnter() delete[] buf; }); - dispatcher->addEventListenerWithFixedPriority(_listener, 1); + _eventDispatcher->addEventListenerWithFixedPriority(_listener, 1); auto sendItem = MenuItemFont::create("Send Custom Event", [=](Object* sender){ static int count = 0; @@ -446,7 +437,7 @@ void CustomEventTest::onEnter() sprintf(buf, "%d", count); EventCustom event(game_custom_event); event.setUserData(buf); - dispatcher->dispatchEvent(&event); + _eventDispatcher->dispatchEvent(&event); }); sendItem->setPosition(origin + Point(size.width/2, size.height/2)); auto menu = Menu::create(sendItem, nullptr); @@ -457,7 +448,7 @@ void CustomEventTest::onEnter() void CustomEventTest::onExit() { - EventDispatcher::getInstance()->removeEventListener(_listener); + _eventDispatcher->removeEventListener(_listener); EventDispatcherTestDemo::onExit(); } @@ -476,8 +467,6 @@ void LabelKeyboardEventTest::onEnter() { EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -500,7 +489,7 @@ void LabelKeyboardEventTest::onEnter() label->setString(buf); }; - dispatcher->addEventListenerWithSceneGraphPriority(listener, statusLabel); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, statusLabel); } std::string LabelKeyboardEventTest::title() @@ -524,8 +513,6 @@ _pos = _max; \ EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -550,7 +537,7 @@ _pos = _max; \ sprite->setPosition(ptNow); }); - dispatcher->addEventListenerWithSceneGraphPriority(listener, sprite); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, sprite); } void SpriteAccelerationEventTest::onExit() @@ -576,8 +563,6 @@ void RemoveAndRetainNodeTest::onEnter() EventDispatcherTestDemo::onEnter(); - auto dispatcher = EventDispatcher::getInstance(); - Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); @@ -616,7 +601,7 @@ void RemoveAndRetainNodeTest::onEnter() target->setOpacity(255); }; - dispatcher->addEventListenerWithSceneGraphPriority(listener1, _sprite); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, _sprite); this->runAction(Sequence::create(DelayTime::create(5.0f), CallFunc::create([this](){ diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 3276a9b620..82a8a6ebcb 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -725,7 +725,7 @@ ConvertToNode::ConvertToNode() { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(ConvertToNode::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp index e14105b62e..5f58111b6c 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp @@ -89,7 +89,7 @@ Parallax2::Parallax2() { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(Parallax2::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // Top Layer, a simple image auto cocosImage = Sprite::create(s_Power); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index 9e35114538..d238482244 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1072,7 +1072,7 @@ void ParticleDemo::onEnter(void) listener->onTouchesBegan = CC_CALLBACK_2(ParticleDemo::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(ParticleDemo::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(ParticleDemo::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp index 5f1e9566ab..f3a804d907 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp @@ -125,7 +125,7 @@ void TouchesPerformTest1::onEnter() listener->onTouchMoved = CC_CALLBACK_2(TouchesPerformTest1::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(TouchesPerformTest1::onTouchEnded, this); listener->onTouchCancelled = CC_CALLBACK_2(TouchesPerformTest1::onTouchCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } std::string TouchesPerformTest1::title() @@ -168,7 +168,7 @@ void TouchesPerformTest2::onEnter() listener->onTouchesMoved = CC_CALLBACK_2(TouchesPerformTest2::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(TouchesPerformTest2::onTouchesEnded, this); listener->onTouchesCancelled = CC_CALLBACK_2(TouchesPerformTest2::onTouchesCancelled, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } std::string TouchesPerformTest2::title() @@ -242,14 +242,14 @@ void TouchesPerformTest3::onEnter() listener->onTouchMoved = CC_CALLBACK_2(TouchableLayer::onTouchMoved, layer); listener->onTouchEnded = CC_CALLBACK_2(TouchableLayer::onTouchEnded, layer); listener->onTouchCancelled = CC_CALLBACK_2(TouchableLayer::onTouchCancelled, layer); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, layer); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, layer); addChild(layer, zorder); layer->release(); } auto emitEventlabel = LabelTTF::create("Emit Touch Event", "", 24); - auto menuItem = MenuItemLabel::create(emitEventlabel, [](Object* sender){ + auto menuItem = MenuItemLabel::create(emitEventlabel, [this](Object* sender){ CC_PROFILER_PURGE_ALL(); @@ -265,13 +265,11 @@ void TouchesPerformTest3::onEnter() event.setEventCode(EventTouch::EventCode::BEGAN); event.setTouches(touches); - auto dispatcher = EventDispatcher::getInstance(); - for (int i = 0; i < 100; ++i) { CC_PROFILER_START(TOUCH_PROFILER_NAME); - dispatcher->dispatchEvent(&event); + _eventDispatcher->dispatchEvent(&event); CC_PROFILER_STOP(TOUCH_PROFILER_NAME); } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 874f5ebe61..fab2a82437 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -200,10 +200,10 @@ void PhysicsDemoClickAdd::onEnter() auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(touchListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(accListener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); @@ -514,7 +514,7 @@ void PhysicsDemoRayCast::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoRayCast::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); _scene->getPhysicsWorld()->setGravity(Point::ZERO); @@ -717,7 +717,7 @@ void PhysicsDemoJoints::onEnter() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); _scene->getPhysicsWorld()->setGravity(Point::ZERO); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 113d4adad3..baf174ac9b 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -114,7 +114,7 @@ RenderTextureSave::RenderTextureSave() auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(RenderTextureSave::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // Save Image menu MenuItemFont::setFontSize(16); @@ -303,7 +303,7 @@ RenderTextureZbuffer::RenderTextureZbuffer() listener->onTouchesBegan = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(RenderTextureZbuffer::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto size = Director::getInstance()->getWinSize(); auto label = LabelTTF::create("vertexZ = 50", "Marker Felt", 64); @@ -637,7 +637,7 @@ SpriteRenderTextureBug::SpriteRenderTextureBug() { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(SpriteRenderTextureBug::onTouchesEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); auto s = Director::getInstance()->getWinSize(); addNewSpriteWithCoords(Point(s.width/2, s.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index ee1480acae..499b1b8dfe 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -fdf35bd639fd5d617e5a280530d6aefe63b94857 \ No newline at end of file +71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp index b922271656..d0ac2cb6b6 100644 --- a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp @@ -130,7 +130,7 @@ KeyboardNotificationLayer::KeyboardNotificationLayer() auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchBegan, this); listener->onTouchEnded = CC_CALLBACK_2(KeyboardNotificationLayer::onTouchEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } //void KeyboardNotificationLayer::registerWithTouchDispatcher() diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 48ed771306..8b18e2de4c 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -1432,7 +1432,7 @@ TileDemo::TileDemo(void) { auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesMoved = CC_CALLBACK_2(TileDemo::onTouchesMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } TileDemo::~TileDemo(void) diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp b/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp index e168d7a1bc..0919b771eb 100644 --- a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp +++ b/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp @@ -45,7 +45,7 @@ void Paddle::onEnter() listener->onTouchMoved = CC_CALLBACK_2(Paddle::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(Paddle::onTouchEnded, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void Paddle::onExit() diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index fcd140e4f3..32051bbd1b 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -129,7 +129,7 @@ TestController::TestController() listener->onTouchBegan = CC_CALLBACK_2(TestController::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(TestController::onTouchMoved, this); - EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } TestController::~TestController() From 0622434321b4b3620f6242ca35b77ef028f30614 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 28 Oct 2013 10:49:21 +0800 Subject: [PATCH 250/557] issue #3069: Using `std::string` to initialize `EventCustom`. It will be easier for editor parser to emit callback event. --- cocos/2d/CCEventCustom.cpp | 7 ++++--- cocos/2d/CCEventCustom.h | 2 +- cocos/2d/CCEventListenerCustom.cpp | 6 +++--- cocos/2d/CCEventListenerCustom.h | 4 ++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/cocos/2d/CCEventCustom.cpp b/cocos/2d/CCEventCustom.cpp index 89e56a3a69..8960b9fd87 100644 --- a/cocos/2d/CCEventCustom.cpp +++ b/cocos/2d/CCEventCustom.cpp @@ -24,14 +24,15 @@ #include "CCEventCustom.h" #include "ccMacros.h" +#include NS_CC_BEGIN -EventCustom::EventCustom(Type type) -: Event(type) +EventCustom::EventCustom(const std::string& eventName) +: Event(std::hash()(eventName)) , _userData(nullptr) { - CCASSERT(type >= TYPE_CUSTOM, "custom type should be greater than TYPE_CUSTOM."); +// CCASSERT(type >= TYPE_CUSTOM, "custom type should be greater than TYPE_CUSTOM."); } NS_CC_END diff --git a/cocos/2d/CCEventCustom.h b/cocos/2d/CCEventCustom.h index 96676cdbfd..c4521e3bbf 100644 --- a/cocos/2d/CCEventCustom.h +++ b/cocos/2d/CCEventCustom.h @@ -33,7 +33,7 @@ class EventCustom : public Event { public: /** Constructor */ - EventCustom(Type type); + EventCustom(const std::string& eventName); /** Set user data */ inline void setUserData(void* data) { _userData = data; }; diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index 3875f61c94..048fede198 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -32,10 +32,10 @@ EventListenerCustom::EventListenerCustom() { } -EventListenerCustom* EventListenerCustom::create(Type type, std::function callback) +EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function callback) { EventListenerCustom* ret = new EventListenerCustom(); - if (ret && ret->init(type, callback)) + if (ret && ret->init(std::hash()(eventName), callback)) { ret->autorelease(); } @@ -46,7 +46,7 @@ EventListenerCustom* EventListenerCustom::create(Type type, std::functioncallback) +bool EventListenerCustom::init(Type type, std::functioncallback) { bool ret = false; diff --git a/cocos/2d/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h index 285d257cd3..0bd5bec700 100644 --- a/cocos/2d/CCEventListenerCustom.h +++ b/cocos/2d/CCEventListenerCustom.h @@ -56,7 +56,7 @@ public: * @param eventType The type of the event. * @param callback The callback function when the specified event was emitted. */ - static EventListenerCustom* create(int type, std::function callback); + static EventListenerCustom* create(const std::string& eventName, std::function callback); /// Overrides virtual bool checkAvailable() override; @@ -67,7 +67,7 @@ protected: EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(int type, std::function callback); + bool init(Type type, std::function callback); std::function _onCustomEvent; }; From e6b0134080d5fe64f22d384259a2cc2f1b9b2947 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 28 Oct 2013 10:49:43 +0800 Subject: [PATCH 251/557] issue #3069: Updating Custom event test. --- .../NewEventDispatcherTest.cpp | 45 +++++++++++++++---- .../NewEventDispatcherTest.h | 1 + 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index aa45afa24d..1e7c746a56 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -414,33 +414,61 @@ void CustomEventTest::onEnter() Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); - auto statusLabel = LabelTTF::create("No custom event received!", "", 20); + MenuItemFont::setFontSize(20); + + auto statusLabel = LabelTTF::create("No custom event 1 received!", "", 20); statusLabel->setPosition(origin + Point(size.width/2, size.height-90)); addChild(statusLabel); - const int game_custom_event = EventListener::TYPE_CUSTOM + 1; - _listener = EventListenerCustom::create(game_custom_event, [=](EventCustom* event){ - std::string str("Custom event received, "); + _listener = EventListenerCustom::create("game_custom_event1", [=](EventCustom* event){ + std::string str("Custom event 1 received, "); char* buf = static_cast(event->getUserData()); str += buf; str += " times"; statusLabel->setString(str.c_str()); - delete[] buf; }); _eventDispatcher->addEventListenerWithFixedPriority(_listener, 1); - auto sendItem = MenuItemFont::create("Send Custom Event", [=](Object* sender){ + auto sendItem = MenuItemFont::create("Send Custom Event 1", [=](Object* sender){ static int count = 0; ++count; char* buf = new char[10]; sprintf(buf, "%d", count); - EventCustom event(game_custom_event); + EventCustom event("game_custom_event1"); event.setUserData(buf); _eventDispatcher->dispatchEvent(&event); + CC_SAFE_DELETE_ARRAY(buf); }); sendItem->setPosition(origin + Point(size.width/2, size.height/2)); - auto menu = Menu::create(sendItem, nullptr); + + auto statusLabel2 = LabelTTF::create("No custom event 2 received!", "", 20); + statusLabel2->setPosition(origin + Point(size.width/2, size.height-120)); + addChild(statusLabel2); + + _listener2 = EventListenerCustom::create("game_custom_event2", [=](EventCustom* event){ + std::string str("Custom event 2 received, "); + char* buf = static_cast(event->getUserData()); + str += buf; + str += " times"; + statusLabel2->setString(str.c_str()); + }); + + _eventDispatcher->addEventListenerWithFixedPriority(_listener2, 1); + + auto sendItem2 = MenuItemFont::create("Send Custom Event 2", [=](Object* sender){ + static int count = 0; + ++count; + char* buf = new char[10]; + sprintf(buf, "%d", count); + EventCustom event("game_custom_event2"); + event.setUserData(buf); + _eventDispatcher->dispatchEvent(&event); + CC_SAFE_DELETE_ARRAY(buf); + }); + sendItem2->setPosition(origin + Point(size.width/2, size.height/2 - 40)); + + auto menu = Menu::create(sendItem, sendItem2, nullptr); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu, -1); @@ -449,6 +477,7 @@ void CustomEventTest::onEnter() void CustomEventTest::onExit() { _eventDispatcher->removeEventListener(_listener); + _eventDispatcher->removeEventListener(_listener2); EventDispatcherTestDemo::onExit(); } diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 9af7022bde..080e623008 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -64,6 +64,7 @@ public: virtual std::string subtitle() override; private: EventListenerCustom* _listener; + EventListenerCustom* _listener2; }; class LabelKeyboardEventTest : public EventDispatcherTestDemo From 8d11f484a96cee937761254617b61bea2dccabfc Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 28 Oct 2013 10:52:23 +0800 Subject: [PATCH 252/557] issue #3069: Removing unused comments. --- cocos/2d/CCEventCustom.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/2d/CCEventCustom.cpp b/cocos/2d/CCEventCustom.cpp index 8960b9fd87..29d8afc551 100644 --- a/cocos/2d/CCEventCustom.cpp +++ b/cocos/2d/CCEventCustom.cpp @@ -32,7 +32,6 @@ EventCustom::EventCustom(const std::string& eventName) : Event(std::hash()(eventName)) , _userData(nullptr) { -// CCASSERT(type >= TYPE_CUSTOM, "custom type should be greater than TYPE_CUSTOM."); } NS_CC_END From d0d869409195a4c9606b17486061ee3ce22028ea Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 28 Oct 2013 11:08:41 +0800 Subject: [PATCH 253/557] issue #2771: fix some retain/release bugs --- cocos/2d/CCNode.cpp | 8 + cocos/physics/CCPhysicsBody.cpp | 93 ++++++++-- cocos/physics/CCPhysicsBody.h | 11 +- cocos/physics/CCPhysicsJoint.cpp | 17 +- cocos/physics/CCPhysicsJoint.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 166 +++++++++++++----- cocos/physics/CCPhysicsWorld.h | 1 + .../Classes/PhysicsTest/PhysicsTest.cpp | 68 +++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 12 +- 9 files changed, 280 insertions(+), 98 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 2145829c34..99283b95a8 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -749,6 +749,14 @@ void Node::detachChild(Node *child, int childIndex, bool doCleanup) child->onExitTransitionDidStart(); child->onExit(); } + +#ifdef CC_USE_PHYSICS + if (child->_physicsBody != nullptr) + { + child->_physicsBody->removeFromWorld(); + } + +#endif // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 109fac9d6f..e3335c7c16 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -62,6 +62,7 @@ namespace PhysicsBody::PhysicsBody() : _owner(nullptr) +, _shapes(nullptr) , _world(nullptr) , _info(nullptr) , _dynamic(true) @@ -85,18 +86,23 @@ PhysicsBody::PhysicsBody() PhysicsBody::~PhysicsBody() { - CC_SAFE_DELETE(_info); + if (_world) + { + removeFromWorld(); + } removeAllShapes(); for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; - PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyA() : joint->getBodyB(); + PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); other->_joints.erase(std::find(other->_joints.begin(), other->_joints.end(), joint)); + delete joint; } + CC_SAFE_DELETE(_info); } PhysicsBody* PhysicsBody::create() @@ -112,6 +118,45 @@ PhysicsBody* PhysicsBody::create() return nullptr; } +PhysicsBody* PhysicsBody::create(float mass) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; +} + +PhysicsBody* PhysicsBody::create(float mass, float moment) +{ + PhysicsBody* body = new PhysicsBody(); + if (body) + { + body->_mass = mass; + body->_massDefault = false; + body->_moment = moment; + body->_momentDefault = false; + if (body->init()) + { + body->autorelease(); + return body; + } + } + + CC_SAFE_DELETE(body); + return nullptr; + +} + PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) { PhysicsBody* body = new PhysicsBody(); @@ -223,6 +268,9 @@ bool PhysicsBody::init() { _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); + _shapes = Array::create(); + CC_BREAK_IF(_shapes == nullptr); + _shapes->retain(); _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); _info->group = ++GROUP_INDEX; @@ -308,10 +356,9 @@ void PhysicsBody::addShape(PhysicsShape* shape) if (shape == nullptr) return; // add shape to body - if (std::find(_shapes.begin(), _shapes.end(), shape) == _shapes.end()) + if (_shapes->getIndexOfObject(shape) == UINT_MAX) { shape->setBody(this); - _shapes.push_back(shape); // calculate the area, mass, and desity // area must update before mass, because the density changes depend on it. @@ -324,7 +371,7 @@ void PhysicsBody::addShape(PhysicsShape* shape) _world->addShape(shape); } - shape->retain(); + _shapes->addObject(shape); } } @@ -519,8 +566,9 @@ void PhysicsBody::setMoment(float moment) PhysicsShape* PhysicsBody::getShapeByTag(int tag) { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { return shape; @@ -532,8 +580,9 @@ PhysicsShape* PhysicsBody::getShapeByTag(int tag) void PhysicsBody::removeShapeByTag(int tag) { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { removeShape(shape); @@ -544,9 +593,7 @@ void PhysicsBody::removeShapeByTag(int tag) void PhysicsBody::removeShape(PhysicsShape* shape) { - auto it = std::find(_shapes.begin(), _shapes.end(), shape); - - if (it != _shapes.end()) + if (_shapes->getIndexOfObject(shape) == UINT_MAX) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -559,25 +606,39 @@ void PhysicsBody::removeShape(PhysicsShape* shape) { _world->removeShape(shape); } - _shapes.erase(it); shape->setBody(nullptr); - shape->release(); + _shapes->removeObject(shape); } } void PhysicsBody::removeAllShapes() { - for (auto shape : _shapes) + for (auto child : *_shapes) { + PhysicsShape* shape = dynamic_cast(child); + + // deduce the area, mass and moment + // area must update before mass, because the density changes depend on it. + _area -= shape->getArea(); + addMass(-shape->getMass()); + addMoment(-shape->getMoment()); + if (_world) { _world->removeShape(shape); } - - delete shape; + shape->setBody(nullptr); } - _shapes.clear(); + _shapes->removeAllObjects(); +} + +void PhysicsBody::removeFromWorld() +{ + if (_world) + { + _world->removeBody(this); + } } void PhysicsBody::setEnable(bool enable) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index ad3ea332fa..c1a3d4b1a1 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -30,6 +30,7 @@ #include "CCObject.h" #include "CCGeometry.h" +#include "CCArray.h" #include "CCPhysicsShape.h" @@ -53,6 +54,8 @@ class PhysicsBody : public Object//, public Clonable { public: static PhysicsBody* create(); + static PhysicsBody* create(float mass); + static PhysicsBody* create(float mass, float moment); /** * @brief Create a body contains a circle shape. */ @@ -119,11 +122,11 @@ public: /* * @brief get the body shapes. */ - inline std::vector& getShapes() { return _shapes; } + inline Array* getShapes() { return _shapes; } /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } + inline PhysicsShape* getShape() { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } PhysicsShape* getShapeByTag(int tag); /* * @brief remove a shape from body @@ -135,6 +138,8 @@ public: */ void removeAllShapes(); + void removeFromWorld(); + /* * @brief get the world body added to. */ @@ -258,7 +263,7 @@ protected: protected: Sprite* _owner; std::vector _joints; - std::vector _shapes; + Array* _shapes; PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 5e475bf367..c7ca4ef2f9 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -61,9 +61,6 @@ PhysicsJoint::~PhysicsJoint() setCollisionEnable(true); CC_SAFE_DELETE(_info); - - CC_SAFE_RELEASE(_bodyA); - CC_SAFE_RELEASE(_bodyB); } bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) @@ -75,14 +72,12 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) if (a != nullptr) { _bodyA = a; - _bodyA->retain(); _bodyA->_joints.push_back(this); } if (b != nullptr) { _bodyB = b; - _bodyB->retain(); _bodyB->_joints.push_back(this); } @@ -174,7 +169,6 @@ PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, con if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -191,12 +185,12 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) // add a pivot joint to fixed two body together cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); setCollisionEnable(false); @@ -213,7 +207,6 @@ PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const P if (joint && joint->init(a, b, anchr)) { - joint->autorelease(); return joint; } @@ -230,7 +223,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -266,7 +259,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -302,7 +295,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 0, PhysicsHelper::float2cpfloat(anchr1.getDistance(anchr2))); - CC_BREAK_IF(joint); + CC_BREAK_IF(joint == nullptr); _info->add(joint); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 04f85d0d0c..67e05cb858 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -40,7 +40,7 @@ class PhysicsBodyInfo; /* * @brief An PhysicsJoint object connects two physics bodies together. */ -class PhysicsJoint : public Object +class PhysicsJoint { protected: PhysicsJoint(); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 451c7b82a2..915daa040e 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -177,18 +177,27 @@ void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distanc bool PhysicsWorld::init() { - _info = new PhysicsWorldInfo(); + do + { + _info = new PhysicsWorldInfo(); + CC_BREAK_IF(_info == nullptr); + _bodys = Array::create(); + CC_BREAK_IF(_bodys == nullptr); + _bodys->retain(); + + cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + + cpSpaceSetDefaultCollisionHandler(_info->space, + (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, + (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, + (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, + (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, + this); + + return true; + } while (false); - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); - - cpSpaceSetDefaultCollisionHandler(_info->space, - (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, - (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, - (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, - (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, - this); - - return true; + return false; } void PhysicsWorld::addJoint(PhysicsJoint* joint) @@ -197,8 +206,6 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) if (it == _joints.end()) { - _joints.push_back(joint); - for (auto subjoint : joint->_info->joints) { if (!cpSpaceContainsConstraint(_info->space, subjoint)) @@ -206,18 +213,44 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) cpSpaceAddConstraint(_info->space, subjoint); } } + + _joints.push_back(joint); } } void PhysicsWorld::removeJoint(PhysicsJoint* joint) { + auto it = std::find(_joints.begin(), _joints.end(), joint); + if (it != _joints.end()) + { + for (auto subjoint : joint->_info->joints) + { + if (cpSpaceContainsConstraint(_info->space, subjoint)) + { + cpSpaceRemoveConstraint(_info->space, subjoint); + } + } + + _joints.remove(joint); + } } void PhysicsWorld::removeAllJoints() { + for (auto joint : _joints) + { + for (auto subjoint : joint->_info->joints) + { + if (!cpSpaceContainsConstraint(_info->space, subjoint)) + { + cpSpaceRemoveConstraint(_info->space, subjoint); + } + } + } + _joints.clear(); } void PhysicsWorld::addShape(PhysicsShape* shape) @@ -243,8 +276,15 @@ void PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); + if (body->getWorld() != this && body->getWorld() != nullptr) + { + body->removeFromWorld(); + } + if (body->isEnable()) { + body->_world = this; + //is gravity enable if (!body->isGravityEnable()) { @@ -258,45 +298,40 @@ void PhysicsWorld::addBody(PhysicsBody* body) } // add shapes to space - for (auto shape : body->getShapes()) + for (auto shape : *body->getShapes()) { - addShape(shape); + addShape(dynamic_cast(shape)); } } - if (_bodys == nullptr) - { - _bodys = Array::create(body, NULL); - _bodys->retain(); - }else - { - _bodys->addObject(body); - } + _bodys->addObject(body); } void PhysicsWorld::removeBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() == this) + if (body->getWorld() != this) { - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } + return; + } + + // reset the gravity + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + + // remove joints + for (auto joint : body->_joints) + { + removeJoint(joint); } // remove shaps - for (auto shape : body->getShapes()) + for (auto shape : *body->getShapes()) { - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } + removeShape(dynamic_cast(shape)); } // remove body @@ -305,10 +340,8 @@ void PhysicsWorld::removeBody(PhysicsBody* body) cpSpaceRemoveBody(_info->space, body->_info->body); } - if (_bodys != nullptr) - { - _bodys->removeObject(body); - } + body->_world = nullptr; + _bodys->removeObject(body); } void PhysicsWorld::removeBodyByTag(int tag) @@ -324,6 +357,43 @@ void PhysicsWorld::removeBodyByTag(int tag) } } +void PhysicsWorld::removeAllBodys() +{ + for (Object* obj : *_bodys) + { + PhysicsBody* body = dynamic_cast(obj); + + // reset the gravity + if (!body->isGravityEnable()) + { + body->applyForce(-_gravity); + } + + // remove joints + for (auto joint : body->_joints) + { + removeJoint(joint); + } + + // remove shaps + for (auto shape : *body->getShapes()) + { + removeShape(dynamic_cast(shape)); + } + + // remove body + if (cpSpaceContainsBody(_info->space, body->_info->body)) + { + cpSpaceRemoveBody(_info->space, body->_info->body); + } + + body->_world = nullptr; + } + + _bodys->removeAllObjects(); + CC_SAFE_RELEASE(_bodys); +} + void PhysicsWorld::removeShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) @@ -366,11 +436,9 @@ void PhysicsWorld::debugDraw() { PhysicsBody* body = dynamic_cast(obj); - std::vector shapes = body->getShapes(); - - for (auto shape : shapes) + for (auto shape : *body->getShapes()) { - drawWithShape(_drawNode, shape); + drawWithShape(_drawNode, dynamic_cast(shape)); } } @@ -449,6 +517,11 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) // check the joint is collision enable or not for (PhysicsJoint* joint : jointsA) { + if (std::find(_joints.begin(), _joints.end(), joint) == _joints.end()) + { + continue; + } + if (!joint->isCollisionEnable()) { PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; @@ -657,8 +730,9 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { + removeAllBodys(); + removeAllJoints(); CC_SAFE_DELETE(_info); - CC_SAFE_RELEASE(_bodys); } NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 34528d6270..9fa8b28240 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -116,6 +116,7 @@ public: virtual void removeBody(PhysicsBody* body); virtual void removeBodyByTag(int tag); + virtual void removeAllBodys(); protected: static PhysicsWorld* create(); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f0ceb3553c..304981c448 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -92,7 +92,6 @@ PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _ball(nullptr) , _spriteTexture(nullptr) -, _mouse(nullptr) { } @@ -160,7 +159,7 @@ void PhysicsDemo::onEnter() #endif } -void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) +Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { #ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); @@ -178,6 +177,8 @@ void PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); + + return sp; #endif } @@ -367,28 +368,60 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m return triangle; } -void PhysicsDemo::onTouchesBegan(const std::vector& touches, Event* event) +bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { - for( auto &touch: touches) + auto location = touch->getLocation(); + Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + + PhysicsShape* shape = nullptr; + for (Object* obj : *arr) { - auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + shape = dynamic_cast(obj); - PhysicsShape* shape = nullptr; - for (Object* obj : *arr) + if (shape->getTag() == 1) { - + break; } } + + if (shape != nullptr) + { + + Node* mouse = Node::create(); + mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); + mouse->getPhysicsBody()->setDynamic(false); + mouse->setPosition(location); + this->addChild(mouse); + PhysicsJoint* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + _scene->getPhysicsWorld()->addJoint(joint); + _mouses.insert(std::make_pair(touch->getID(), mouse)); + + return true; + } + + return false; +} + +void PhysicsDemo::onTouchMoved(Touch* touch, Event* event) +{ + auto it = _mouses.find(touch->getID()); + + if (it != _mouses.end()) + { + it->second->getPhysicsBody()->setVelocity((touch->getLocation() - it->second->getPosition()) * 60.0f); + it->second->setPosition(touch->getLocation()); + } } -void PhysicsDemo::onTouchesMoved(const std::vector& touches, Event* event) +void PhysicsDemo::onTouchEnded(Touch* touch, Event* event) { + auto it = _mouses.find(touch->getID()); -} - -void PhysicsDemo::onTouchesEnded(const std::vector& touches, Event* event) -{ + if (it != _mouses.end()) + { + this->removeChild(it->second); + _mouses.erase(it); + } } @@ -440,6 +473,9 @@ void PhysicsDemoPyramidStack::onEnter() { PhysicsDemo::onEnter(); + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(node); @@ -454,7 +490,9 @@ void PhysicsDemoPyramidStack::onEnter() { for(int j=0; j<=i; j++) { - addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); + auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); + + sp->getPhysicsBody()->setTag(1); } } } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 0c685ef98e..736c71574a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -5,6 +5,8 @@ #include "../testBasic.h" #include "../BaseTest.h" +#include + class PhysicsTestScene : public TestScene { @@ -36,19 +38,19 @@ public: void backCallback(Object* sender); void toggleDebugCallback(Object* sender); - void addGrossiniAtPosition(Point p, float scale = 1.0); + Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - void onTouchesBegan(const std::vector& touches, Event* event) override; - void onTouchesMoved(const std::vector& touches, Event* event) override; - void onTouchesEnded(const std::vector& touches, Event* event) override; + bool onTouchBegan(Touch* touch, Event* event) override; + void onTouchMoved(Touch* touch, Event* event) override; + void onTouchEnded(Touch* touch, Event* event) override; protected: Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; - DrawNode* _mouse; + std::map _mouses; }; class PhysicsDemoClickAdd : public PhysicsDemo From 8b7d1934c81ac1c59ae46c5a3db91f0d3384d9f7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 28 Oct 2013 16:00:01 +0800 Subject: [PATCH 254/557] issue #3069: Using enum class for define Event type and EventListener type. --- cocos/2d/CCEvent.h | 12 +- cocos/2d/CCEventAcceleration.cpp | 2 +- cocos/2d/CCEventCustom.cpp | 3 +- cocos/2d/CCEventCustom.h | 7 +- cocos/2d/CCEventDispatcher.cpp | 190 ++++++++++++++--------- cocos/2d/CCEventDispatcher.h | 22 +-- cocos/2d/CCEventKeyboard.cpp | 5 + cocos/2d/CCEventKeyboard.h | 8 +- cocos/2d/CCEventListener.cpp | 3 +- cocos/2d/CCEventListener.h | 42 +++-- cocos/2d/CCEventListenerAcceleration.cpp | 2 +- cocos/2d/CCEventListenerAcceleration.h | 2 + cocos/2d/CCEventListenerCustom.cpp | 6 +- cocos/2d/CCEventListenerCustom.h | 2 +- cocos/2d/CCEventListenerKeyboard.cpp | 2 +- cocos/2d/CCEventListenerKeyboard.h | 2 + cocos/2d/CCEventListenerTouch.cpp | 4 +- cocos/2d/CCEventListenerTouch.h | 4 + cocos/2d/CCEventTouch.cpp | 5 + cocos/2d/CCEventTouch.h | 6 +- 20 files changed, 197 insertions(+), 132 deletions(-) diff --git a/cocos/2d/CCEvent.h b/cocos/2d/CCEvent.h index eecd7f396c..cd2be49adb 100644 --- a/cocos/2d/CCEvent.h +++ b/cocos/2d/CCEvent.h @@ -41,15 +41,14 @@ class Node; class Event { public: - enum EventType + enum class Type { - TYPE_TOUCH = 1, - TYPE_KEYBOARD = 3, - TYPE_ACCELERATION, - TYPE_CUSTOM + TOUCH, + KEYBOARD, + ACCELERATION, + CUSTOM }; - typedef int Type; protected: /** Constructor */ Event(Type type); @@ -78,6 +77,7 @@ protected: inline void setCurrentTarget(Node* target) { _currentTarget = target; }; Type _type; ///< Event type + bool _isStopped; ///< whether the event has been stopped. Node* _currentTarget; ///< Current target diff --git a/cocos/2d/CCEventAcceleration.cpp b/cocos/2d/CCEventAcceleration.cpp index 7039c03ff8..1a8a075d88 100644 --- a/cocos/2d/CCEventAcceleration.cpp +++ b/cocos/2d/CCEventAcceleration.cpp @@ -27,7 +27,7 @@ NS_CC_BEGIN EventAcceleration::EventAcceleration(Acceleration acc) -: Event(TYPE_ACCELERATION) +: Event(Type::ACCELERATION) , _acc(acc) { } diff --git a/cocos/2d/CCEventCustom.cpp b/cocos/2d/CCEventCustom.cpp index 29d8afc551..65e9d4c2f5 100644 --- a/cocos/2d/CCEventCustom.cpp +++ b/cocos/2d/CCEventCustom.cpp @@ -29,8 +29,9 @@ NS_CC_BEGIN EventCustom::EventCustom(const std::string& eventName) -: Event(std::hash()(eventName)) +: Event(Type::CUSTOM) , _userData(nullptr) +, _eventName(eventName) { } diff --git a/cocos/2d/CCEventCustom.h b/cocos/2d/CCEventCustom.h index c4521e3bbf..4a7d750940 100644 --- a/cocos/2d/CCEventCustom.h +++ b/cocos/2d/CCEventCustom.h @@ -35,14 +35,17 @@ public: /** Constructor */ EventCustom(const std::string& eventName); - /** Set user data */ + /** Sets user data */ inline void setUserData(void* data) { _userData = data; }; - /** Get user data */ + /** Gets user data */ inline void* getUserData() const { return _userData; }; + /** Gets event name */ + inline const std::string& getEventName() const { return _eventName; }; protected: void* _userData; ///< User data + std::string _eventName; }; NS_CC_END diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index e0922b0796..1ebadf9b74 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -24,6 +24,7 @@ #include "CCEventDispatcher.h" #include "CCEvent.h" #include "CCEventTouch.h" +#include "CCEventCustom.h" #include "CCEventListenerTouch.h" #include "CCNode.h" #include "CCDirector.h" @@ -58,6 +59,37 @@ private: NS_CC_BEGIN +static EventListener::ListenerID getListenerID(Event* event) +{ + EventListener::ListenerID ret; + switch (event->getType()) + { + case Event::Type::ACCELERATION: + ret = static_cast(EventListener::Type::ACCELERATION); + break; + case Event::Type::CUSTOM: + { + auto customEvent = static_cast(event); + auto listenerID = std::hash()(customEvent->getEventName()); + ret = static_cast(listenerID); + } + break; + case Event::Type::KEYBOARD: + ret = static_cast(EventListener::Type::KEYBOARD); + 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::Type::UNKNOWN); + break; + default: + CCASSERT(false, "Invalid type!"); + break; + } + + return ret; +} + EventDispatcher::EventListenerVector::EventListenerVector() : _sceneGraphListeners(nullptr) , _fixedListeners(nullptr) @@ -90,7 +122,7 @@ bool EventDispatcher::EventListenerVector::empty() const void EventDispatcher::EventListenerVector::push_back(EventListener* listener) { - if (listener->_fixedPriority == 0) + if (listener->getFixedPriority() == 0) { if (_sceneGraphListeners == nullptr) { @@ -196,7 +228,7 @@ void EventDispatcher::pauseTarget(Node* node) auto listeners = listenerIter->second; for (auto& l : *listeners) { - l->_paused = true; + l->setPaused(true); } } } @@ -209,7 +241,7 @@ void EventDispatcher::resumeTarget(Node* node) auto listeners = listenerIter->second; for (auto& l : *listeners) { - l->_paused = false; + l->setPaused(false); } } setDirtyForNode(node); @@ -274,11 +306,11 @@ void EventDispatcher::addEventListener(EventListener* listener) { EventListenerVector* listenerList = nullptr; - auto iter = _listeners.find(listener->_type); + auto iter = _listeners.find(listener->getListenerID()); if (iter == _listeners.end()) { listenerList = new EventListenerVector(); - _listeners.insert(std::make_pair(listener->_type, listenerList)); + _listeners.insert(std::make_pair(listener->getListenerID(), listenerList)); } else { @@ -287,13 +319,13 @@ void EventDispatcher::addEventListener(EventListener* listener) listenerList->push_back(listener); - if (listener->_fixedPriority == 0) + if (listener->getFixedPriority() == 0) { - setDirty(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(listener->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY); } else { - setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); + setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRITORY); } } else @@ -305,17 +337,16 @@ void EventDispatcher::addEventListener(EventListener* listener) void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node) { CCASSERT(listener && node, "Invalid parameters."); - CCASSERT(!listener->_isRegistered, "The listener has been registered."); + CCASSERT(!listener->isRegistered(), "The listener has been registered."); if (!listener->checkAvailable()) return; - listener->_node = node; - listener->_fixedPriority = 0; - + listener->setSceneGraphPriority(node); + listener->setFixedPriority(0); + listener->setRegistered(true); + listener->retain(); - listener->_isRegistered = true; - addEventListener(listener); associateNodeAndEventListener(node, listener); @@ -329,17 +360,18 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority) { CCASSERT(listener, "Invalid parameters."); - CCASSERT(!listener->_isRegistered, "The listener has been registered."); + CCASSERT(!listener->isRegistered(), "The listener has been registered."); CCASSERT(fixedPriority != 0, "0 priority is forbidden for fixed priority since it's used for scene graph based priority."); if (!listener->checkAvailable()) return; - listener->_node = nullptr; - listener->_fixedPriority = fixedPriority; + listener->setSceneGraphPriority(nullptr); + listener->setFixedPriority(fixedPriority); + listener->setRegistered(true); + listener->setPaused(false); + listener->retain(); - listener->_isRegistered = true; - listener->_paused = false; addEventListener(listener); } @@ -361,10 +393,10 @@ void EventDispatcher::removeEventListener(EventListener* listener) if (l == listener) { CC_SAFE_RETAIN(l); - l->_isRegistered = false; - if (l->_node != nullptr) + l->setRegistered(false); + if (l->getSceneGraphPriority() != nullptr) { - dissociateNodeAndEventListener(l->_node, l); + dissociateNodeAndEventListener(l->getSceneGraphPriority(), l); } if (_inDispatch == 0) @@ -393,7 +425,7 @@ void EventDispatcher::removeEventListener(EventListener* listener) if (iter->second->empty()) { - _priorityDirtyFlagMap.erase(listener->_type); + _priorityDirtyFlagMap.erase(listener->getListenerID()); auto list = iter->second; iter = _listeners.erase(iter); CC_SAFE_DELETE(list); @@ -426,12 +458,12 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) auto found = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener); if (found != fixedPriorityListeners->end()) { - CCASSERT(listener->_node == nullptr, "Can't set fixed priority with scene graph based listener."); + CCASSERT(listener->getSceneGraphPriority() == nullptr, "Can't set fixed priority with scene graph based listener."); - if (listener->_fixedPriority != fixedPriority) + if (listener->getFixedPriority() != fixedPriority) { - listener->_fixedPriority = fixedPriority; - setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); + listener->setFixedPriority(fixedPriority); + setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRITORY); } return; } @@ -505,21 +537,23 @@ void EventDispatcher::dispatchEvent(Event* event) DispatchGuard guard(_inDispatch); - if (event->getType() == Event::TYPE_TOUCH) + if (event->getType() == Event::Type::TOUCH) { dispatchTouchEvent(static_cast(event)); return; } - sortEventListeners(event->getType()); + auto listenerID = getListenerID(event); - auto iter = _listeners.find(event->getType()); + sortEventListeners(listenerID); + + auto iter = _listeners.find(listenerID); if (iter != _listeners.end()) { auto listeners = iter->second; auto onEvent = [&event](EventListener* listener) -> bool{ - event->setCurrentTarget(listener->_node); + event->setCurrentTarget(listener->getSceneGraphPriority()); listener->_onEvent(event); return event->isStopped(); }; @@ -527,16 +561,19 @@ void EventDispatcher::dispatchEvent(Event* event) dispatchEventToListeners(listeners, onEvent); } - updateListeners(event->getType()); + updateListeners(event); } void EventDispatcher::dispatchTouchEvent(EventTouch* event) { - sortEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); - sortEventListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); + auto touchOneByOneID = static_cast(EventListener::Type::TOUCH_ONE_BY_ONE); + auto touchAllAtOnceID = static_cast(EventListener::Type::TOUCH_ALL_AT_ONCE); - auto oneByOnelisteners = getListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); - auto allAtOncelisteners = getListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); + sortEventListeners(touchOneByOneID); + sortEventListeners(touchAllAtOnceID); + + auto oneByOnelisteners = getListeners(touchOneByOneID); + auto allAtOncelisteners = getListeners(touchAllAtOnceID); // If there aren't any touch listeners, return directly. if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) @@ -627,7 +664,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(event->getType()); + updateListeners(event); return true; } @@ -706,7 +743,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(event->getType()); + updateListeners(event); return false; } @@ -720,14 +757,14 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) } } - updateListeners(event->getType()); + updateListeners(event); } -void EventDispatcher::updateListeners(Event::Type eventType) +void EventDispatcher::updateListeners(Event* event) { - auto onUpdateListeners = [this](EventListener::Type listenerType) + auto onUpdateListeners = [this](EventListener::ListenerID listenerID) { - auto listenersIter = _listeners.find(listenerType); + auto listenersIter = _listeners.find(listenerID); if (listenersIter == _listeners.end()) return; @@ -740,7 +777,7 @@ void EventDispatcher::updateListeners(Event::Type eventType) for (auto iter = sceneGraphPriorityListeners->begin(); iter != sceneGraphPriorityListeners->end();) { auto l = *iter; - if (!l->_isRegistered) + if (!l->isRegistered()) { iter = sceneGraphPriorityListeners->erase(iter); l->release(); @@ -757,7 +794,7 @@ void EventDispatcher::updateListeners(Event::Type eventType) for (auto iter = fixedPriorityListeners->begin(); iter != fixedPriorityListeners->end();) { auto l = *iter; - if (!l->_isRegistered) + if (!l->isRegistered()) { iter = fixedPriorityListeners->erase(iter); l->release(); @@ -791,14 +828,14 @@ void EventDispatcher::updateListeners(Event::Type eventType) } }; - if (eventType == Event::TYPE_TOUCH) + if (event->getType() == Event::Type::TOUCH) { - onUpdateListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); - onUpdateListeners(EventListener::TYPE_TOUCH_ALL_AT_ONCE); + onUpdateListeners(static_cast(EventListener::Type::TOUCH_ONE_BY_ONE)); + onUpdateListeners(static_cast(EventListener::Type::TOUCH_ALL_AT_ONCE)); } else { - onUpdateListeners(eventType); + onUpdateListeners(getListenerID(event)); } @@ -808,12 +845,13 @@ void EventDispatcher::updateListeners(Event::Type eventType) for (auto& listener : _toAddedListeners) { - auto itr = _listeners.find(listener->_type); + EventListener::ListenerID listenerID = listener->getListenerID(); + auto itr = _listeners.find(listenerID); if (itr == _listeners.end()) { listeners = new EventListenerVector(); - _listeners.insert(std::make_pair(listener->_type, listeners)); + _listeners.insert(std::make_pair(listenerID, listeners)); } else { @@ -822,13 +860,13 @@ void EventDispatcher::updateListeners(Event::Type eventType) listeners->push_back(listener); - if (listener->_fixedPriority == 0) + if (listener->getFixedPriority() == 0) { - setDirty(listener->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(listenerID, DirtyFlag::SCENE_GRAPH_PRIORITY); } else { - setDirty(listener->_type, DirtyFlag::FIXED_PRITORY); + setDirty(listenerID, DirtyFlag::FIXED_PRITORY); } } _toAddedListeners.clear(); @@ -846,7 +884,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() { for (auto& l : *iter->second) { - setDirty(l->_type, DirtyFlag::SCENE_GRAPH_PRIORITY); + setDirty(l->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY); } } } @@ -855,11 +893,11 @@ void EventDispatcher::updateDirtyFlagForSceneGraph() } } -void EventDispatcher::sortEventListeners(EventListener::Type eventListenerType) +void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID) { DirtyFlag dirtyFlag = DirtyFlag::NONE; - auto dirtyIter = _priorityDirtyFlagMap.find(eventListenerType); + auto dirtyIter = _priorityDirtyFlagMap.find(listenerID); if (dirtyIter != _priorityDirtyFlagMap.end()) { dirtyFlag = dirtyIter->second; @@ -869,21 +907,21 @@ void EventDispatcher::sortEventListeners(EventListener::Type eventListenerType) { if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) { - sortEventListenersOfFixedPriority(eventListenerType); + sortEventListenersOfFixedPriority(listenerID); } if ((int)dirtyFlag & (int)DirtyFlag::SCENE_GRAPH_PRIORITY) { - sortEventListenersOfSceneGraphPriority(eventListenerType); + sortEventListenersOfSceneGraphPriority(listenerID); } dirtyIter->second = DirtyFlag::NONE; } } -void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::Type eventListenerType) +void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID) { - auto listeners = getListeners(eventListenerType); + auto listeners = getListeners(listenerID); if (listeners == nullptr) return; @@ -898,7 +936,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::Type // After sort: priority < 0, > 0 auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); std::sort(sceneGraphlisteners->begin(), sceneGraphlisteners->end(), [this](const EventListener* l1, const EventListener* l2) { - return _nodePriorityMap[l1->_node] > _nodePriorityMap[l2->_node]; + return _nodePriorityMap[l1->getSceneGraphPriority()] > _nodePriorityMap[l2->getSceneGraphPriority()]; }); #if DUMP_LISTENER_ITEM_PRIORITY_INFO @@ -910,9 +948,9 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::Type #endif } -void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::Type eventListenerType) +void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID) { - auto listeners = getListeners(eventListenerType); + auto listeners = getListeners(listenerID); if (listeners == nullptr) return; @@ -920,14 +958,14 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::Type even // After sort: priority < 0, > 0 auto fixedlisteners = listeners->getFixedPriorityListeners(); std::sort(fixedlisteners->begin(), fixedlisteners->end(), [](const EventListener* l1, const EventListener* l2) { - return l1->_fixedPriority < l2->_fixedPriority; + return l1->getFixedPriority() < l2->getFixedPriority(); }); // FIXME: Should use binary search int index = 0; for (auto& listener : *fixedlisteners) { - if (listener->_fixedPriority >= 0) + if (listener->getFixedPriority() >= 0) break; ++index; } @@ -944,9 +982,9 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::Type even } -EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::Type eventListenerType) +EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::ListenerID listenerID) { - auto iter = _listeners.find(eventListenerType); + auto iter = _listeners.find(listenerID); if (iter != _listeners.end()) { return iter->second; @@ -955,9 +993,9 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene return nullptr; } -void EventDispatcher::removeEventListeners(EventListener::Type eventListenerType) +void EventDispatcher::removeEventListeners(EventListener::ListenerID listenerID) { - auto listenerItemIter = _listeners.find(eventListenerType); + auto listenerItemIter = _listeners.find(listenerID); if (listenerItemIter != _listeners.end()) { auto listeners = listenerItemIter->second; @@ -971,10 +1009,10 @@ void EventDispatcher::removeEventListeners(EventListener::Type eventListenerType for (auto iter = listenerVector->begin(); iter != listenerVector->end();) { auto l = *iter; - l->_isRegistered = false; - if (l->_node != nullptr) + l->setRegistered(false); + if (l->getSceneGraphPriority() != nullptr) { - dissociateNodeAndEventListener(l->_node, l); + dissociateNodeAndEventListener(l->getSceneGraphPriority(), l); } if (_inDispatch == 0) @@ -997,7 +1035,7 @@ void EventDispatcher::removeEventListeners(EventListener::Type eventListenerType listeners->clear(); delete listeners; _listeners.erase(listenerItemIter); - _priorityDirtyFlagMap.erase(eventListenerType); + _priorityDirtyFlagMap.erase(listenerID); } } } @@ -1042,12 +1080,12 @@ void EventDispatcher::setDirtyForNode(Node* node) } } -void EventDispatcher::setDirty(EventListener::Type eventListenerType, DirtyFlag flag) +void EventDispatcher::setDirty(EventListener::ListenerID listenerID, DirtyFlag flag) { - auto iter = _priorityDirtyFlagMap.find(eventListenerType); + auto iter = _priorityDirtyFlagMap.find(listenerID); if (iter == _priorityDirtyFlagMap.end()) { - _priorityDirtyFlagMap.insert(std::make_pair(eventListenerType, flag)); + _priorityDirtyFlagMap.insert(std::make_pair(listenerID, flag)); } else { diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index e3650a1fae..3609c7a591 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -74,8 +74,8 @@ public: */ void removeEventListener(EventListener* listener); - /** Removes all listeners with the same event listener type */ - void removeEventListeners(EventListener::Type eventListenerType); + /** Removes all listeners with the same event listener ID */ + void removeEventListeners(EventListener::ListenerID listenerID); /** Removes all listeners */ void removeAllEventListeners(); @@ -144,25 +144,25 @@ private: void addEventListener(EventListener* listener); /** Gets event the listener list for the event listener type. */ - EventListenerVector* getListeners(EventListener::Type eventListenerType); + EventListenerVector* getListeners(EventListener::ListenerID listenerID); /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); /** Sort event listener */ - void sortEventListeners(EventListener::Type eventListenerType); + void sortEventListeners(EventListener::ListenerID listenerID); /** Sorts the listeners of specified type by scene graph priority */ - void sortEventListenersOfSceneGraphPriority(EventListener::Type eventListenerType); + void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID); /** Sorts the listeners of specified type by fixed priority */ - void sortEventListenersOfFixedPriority(EventListener::Type eventListenerType); + void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID); /** Updates all listeners * 1) Removes all listener items that have been marked as 'removed' when dispatching event. * 2) Adds all listener items that have been marked as 'added' when dispatching event. */ - void updateListeners(Event::Type eventType); + void updateListeners(Event* event); /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ void dispatchTouchEvent(EventTouch* event); @@ -185,18 +185,18 @@ private: ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY }; - /** Sets the dirty flag for a specified listener type */ - void setDirty(EventListener::Type listenerType, DirtyFlag flag); + /** Sets the dirty flag for a specified listener ID */ + void setDirty(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 _listeners; + std::unordered_map _listeners; /** The map of dirty flag */ - std::unordered_map _priorityDirtyFlagMap; + std::unordered_map _priorityDirtyFlagMap; /** The map of node and event listeners */ std::unordered_map*> _nodeListenersMap; diff --git a/cocos/2d/CCEventKeyboard.cpp b/cocos/2d/CCEventKeyboard.cpp index b02312fce1..83bf0a8d0a 100644 --- a/cocos/2d/CCEventKeyboard.cpp +++ b/cocos/2d/CCEventKeyboard.cpp @@ -27,5 +27,10 @@ NS_CC_BEGIN +EventKeyboard::EventKeyboard(KeyCode keyCode, bool isPressed) +: Event(Type::KEYBOARD) +, _keyCode(keyCode) +, _isPressed(isPressed) +{} NS_CC_END diff --git a/cocos/2d/CCEventKeyboard.h b/cocos/2d/CCEventKeyboard.h index b8cf7f8976..e0533e62fd 100644 --- a/cocos/2d/CCEventKeyboard.h +++ b/cocos/2d/CCEventKeyboard.h @@ -196,13 +196,7 @@ public: KEY_SEARCH = 0xFFAA }; - static const char* EVENT_TYPE; - - EventKeyboard(KeyCode keyCode, bool isPressed) - : Event(TYPE_KEYBOARD) - , _keyCode(keyCode) - , _isPressed(isPressed) - {}; + EventKeyboard(KeyCode keyCode, bool isPressed); private: KeyCode _keyCode; diff --git a/cocos/2d/CCEventListener.cpp b/cocos/2d/CCEventListener.cpp index 9040593e0e..b4f9fdd499 100644 --- a/cocos/2d/CCEventListener.cpp +++ b/cocos/2d/CCEventListener.cpp @@ -35,10 +35,11 @@ EventListener::~EventListener() CCLOGINFO("In the destructor of EventListener. %p", this); } -bool EventListener::init(Type t, std::function callback) +bool EventListener::init(Type t, ListenerID listenerID, std::function callback) { _onEvent = callback; _type = t; + _listenerID = listenerID; _isRegistered = false; _paused = true; diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index bcedcec0c8..bbf5121149 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -46,22 +46,24 @@ class Node; class EventListener : public Object { public: - enum EventListenerType + enum class Type { - TYPE_TOUCH_ONE_BY_ONE = 1, - TYPE_TOUCH_ALL_AT_ONCE, - TYPE_KEYBOARD, - TYPE_ACCELERATION, - TYPE_CUSTOM + UNKNOWN, + TOUCH_ONE_BY_ONE, + TOUCH_ALL_AT_ONCE, + KEYBOARD, + ACCELERATION, + CUSTOM }; - typedef int Type; + typedef int ListenerID; + protected: /** Constructor */ EventListener(); /** Initializes event with type and callback function */ - bool init(Type t, std::functioncallback); + bool init(Type t, ListenerID listenerID, std::functioncallback); public: /** Destructor */ virtual ~EventListener(); @@ -72,21 +74,33 @@ public: /** Clones the listener, its subclasses have to override this method. */ virtual EventListener* clone() = 0; + inline void setPaused(bool paused) { _paused = paused; }; inline bool isPaused() const { return _paused; }; + + inline void setRegistered(bool registered) { _isRegistered = registered; }; inline bool isRegistered() const { return _isRegistered; }; -protected: + inline Type getType() const { return _type; }; + inline ListenerID getListenerID() const { return _listenerID; }; + + inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; + inline int getFixedPriority() const { return _fixedPriority; }; + + inline void setSceneGraphPriority(Node* node) { _node = node; }; + inline Node* getSceneGraphPriority() const { return _node; }; + std::function _onEvent; /// Event callback function - Type _type; /// Event type - bool _isRegistered; /// Whether the listener has been added to dispatcher. + +protected: + + Type _type; /// Event listener type + ListenerID _listenerID; /// Event listener ID + bool _isRegistered; /// Whether the listener has been added to dispatcher. // The priority of event listener int _fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority. Node* _node; // scene graph based priority bool _paused; - -private: - friend class EventDispatcher; }; NS_CC_END diff --git a/cocos/2d/CCEventListenerAcceleration.cpp b/cocos/2d/CCEventListenerAcceleration.cpp index d1d5d22206..258af5929e 100644 --- a/cocos/2d/CCEventListenerAcceleration.cpp +++ b/cocos/2d/CCEventListenerAcceleration.cpp @@ -59,7 +59,7 @@ bool EventListenerAcceleration::init(std::functiononAccelerationEvent(&accEvent->_acc, event); }; - if (EventListener::init(TYPE_ACCELERATION, listener)) + if (EventListener::init(Type::ACCELERATION, static_cast(Type::ACCELERATION), listener)) { onAccelerationEvent = callback; return true; diff --git a/cocos/2d/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h index 59ce3d8439..213bac646e 100644 --- a/cocos/2d/CCEventListenerAcceleration.h +++ b/cocos/2d/CCEventListenerAcceleration.h @@ -33,6 +33,8 @@ NS_CC_BEGIN class EventListenerAcceleration : public EventListener { public: + static const ListenerID ID = static_cast(Type::ACCELERATION); + static EventListenerAcceleration* create(std::function callback); virtual ~EventListenerAcceleration(); diff --git a/cocos/2d/CCEventListenerCustom.cpp b/cocos/2d/CCEventListenerCustom.cpp index 048fede198..09e657a9fc 100644 --- a/cocos/2d/CCEventListenerCustom.cpp +++ b/cocos/2d/CCEventListenerCustom.cpp @@ -46,7 +46,7 @@ EventListenerCustom* EventListenerCustom::create(const std::string& eventName, s return ret; } -bool EventListenerCustom::init(Type type, std::functioncallback) +bool EventListenerCustom::init(ListenerID listenerId, std::functioncallback) { bool ret = false; @@ -59,7 +59,7 @@ bool EventListenerCustom::init(Type type, std::functioncallb } }; - if (EventListener::init(type, listener)) + if (EventListener::init(EventListener::Type::CUSTOM, listenerId, listener)) { ret = true; } @@ -69,7 +69,7 @@ bool EventListenerCustom::init(Type type, std::functioncallb EventListenerCustom* EventListenerCustom::clone() { EventListenerCustom* ret = new EventListenerCustom(); - if (ret && ret->init(_type, _onCustomEvent)) + if (ret && ret->init(_listenerID, _onCustomEvent)) { ret->autorelease(); } diff --git a/cocos/2d/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h index 0bd5bec700..eb7e875165 100644 --- a/cocos/2d/CCEventListenerCustom.h +++ b/cocos/2d/CCEventListenerCustom.h @@ -67,7 +67,7 @@ protected: EventListenerCustom(); /** Initializes event with type and callback function */ - bool init(Type type, std::function callback); + bool init(ListenerID listenerId, std::function callback); std::function _onCustomEvent; }; diff --git a/cocos/2d/CCEventListenerKeyboard.cpp b/cocos/2d/CCEventListenerKeyboard.cpp index fb733ed442..c947a43e36 100644 --- a/cocos/2d/CCEventListenerKeyboard.cpp +++ b/cocos/2d/CCEventListenerKeyboard.cpp @@ -88,7 +88,7 @@ bool EventListenerKeyboard::init() } }; - if (EventListener::init(TYPE_KEYBOARD, listener)) + if (EventListener::init(Type::KEYBOARD, static_cast(Type::KEYBOARD), listener)) { return true; } diff --git a/cocos/2d/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h index c34d2add0d..6c59f69121 100644 --- a/cocos/2d/CCEventListenerKeyboard.h +++ b/cocos/2d/CCEventListenerKeyboard.h @@ -36,6 +36,8 @@ class Event; class EventListenerKeyboard : public EventListener { public: + static const ListenerID ID = static_cast(Type::KEYBOARD); + static EventListenerKeyboard* create(); /// Overrides diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index e753a113d0..1367645452 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -46,7 +46,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne() bool EventListenerTouchOneByOne::init() { - if (EventListener::init(TYPE_TOUCH_ONE_BY_ONE, nullptr)) + if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast(Type::TOUCH_ONE_BY_ONE), nullptr)) { return true; } @@ -123,7 +123,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce() bool EventListenerTouchAllAtOnce::init() { - if (EventListener::init(TYPE_TOUCH_ALL_AT_ONCE, nullptr)) + if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast(Type::TOUCH_ALL_AT_ONCE), nullptr)) { return true; } diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 09e6e6fe0c..94b0bd65b7 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -36,6 +36,8 @@ NS_CC_BEGIN class EventListenerTouchOneByOne : public EventListener { public: + static const ListenerID ID = static_cast(Type::TOUCH_ONE_BY_ONE); + static EventListenerTouchOneByOne* create(); virtual ~EventListenerTouchOneByOne(); @@ -67,6 +69,8 @@ private: class EventListenerTouchAllAtOnce : public EventListener { public: + static const ListenerID ID = static_cast(Type::TOUCH_ALL_AT_ONCE); + static EventListenerTouchAllAtOnce* create(); virtual ~EventListenerTouchAllAtOnce(); diff --git a/cocos/2d/CCEventTouch.cpp b/cocos/2d/CCEventTouch.cpp index d0df614973..9cfa0edd8d 100644 --- a/cocos/2d/CCEventTouch.cpp +++ b/cocos/2d/CCEventTouch.cpp @@ -26,5 +26,10 @@ NS_CC_BEGIN +EventTouch::EventTouch() +: Event(Type::TOUCH) +{ + _touches.reserve(MAX_TOUCHES); +} NS_CC_END diff --git a/cocos/2d/CCEventTouch.h b/cocos/2d/CCEventTouch.h index 100d67cf95..3bc18f55ca 100644 --- a/cocos/2d/CCEventTouch.h +++ b/cocos/2d/CCEventTouch.h @@ -46,11 +46,7 @@ public: CANCELLED }; - EventTouch() - : Event(TYPE_TOUCH) - { - _touches.reserve(MAX_TOUCHES); - } + EventTouch(); EventCode getEventCode() { return _eventCode; }; std::vector getTouches() { return _touches; }; From a82932524068dbc3caf1fa4cf55d06d267599dc2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 28 Oct 2013 16:00:19 +0800 Subject: [PATCH 255/557] issue #3069: Updating EventDispatcherTest. --- .../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 1e7c746a56..8aa31bb82f 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -187,7 +187,7 @@ void TouchableSpriteTest::onEnter() auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - _eventDispatcher->removeEventListeners(EventListener::TYPE_TOUCH_ONE_BY_ONE); + _eventDispatcher->removeEventListeners(EventListenerTouchOneByOne::ID); auto nextItem = MenuItemFont::create("Next", [=](Object* sender){ nextCallback(nullptr); @@ -664,5 +664,5 @@ std::string RemoveAndRetainNodeTest::title() std::string RemoveAndRetainNodeTest::subtitle() { - return ""; + return "Sprite should be removed after 5s, add to scene again after 5s"; } \ No newline at end of file From 66d1bbd89f7718cc42045670f612e451e72d6353 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 28 Oct 2013 16:17:19 +0800 Subject: [PATCH 256/557] issue #2771: edit physics effect with all bodies and fix some bugs --- cocos/2d/CCLayer.cpp | 24 ------- cocos/2d/CCLayer.h | 6 -- cocos/2d/CCNode.cpp | 14 ++++ cocos/2d/CCScene.cpp | 28 +++----- cocos/2d/CCScene.h | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 11 --- cocos/physics/CCPhysicsBody.h | 6 +- cocos/physics/CCPhysicsJoint.cpp | 22 +++++- cocos/physics/CCPhysicsJoint.h | 8 ++- cocos/physics/CCPhysicsShape.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 70 +++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 6 +- 13 files changed, 124 insertions(+), 77 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 19346ea844..fe57da15fd 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -476,30 +476,6 @@ void Layer::onTouchesCancelled(const std::vector& pTouches, Event *pEven CC_UNUSED_PARAM(pEvent); } - -#ifdef CC_USE_PHYSICS -void Layer::addChild(Node* child) -{ - Node::addChild(child); -} - -void Layer::addChild(Node* child, int zOrder) -{ - Node::addChild(child, zOrder); -} - -void Layer::addChild(Node* child, int zOrder, int tag) -{ - Node::addChild(child, zOrder, tag); - - if (this->getParent() && - dynamic_cast(this->getParent()) != nullptr) - { - dynamic_cast(this->getParent())->addChildToPhysicsWorld(child); - } -} -#endif - // LayerRGBA LayerRGBA::LayerRGBA() : _displayedOpacity(255) diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 0dad16ff21..9280bdc6aa 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -179,12 +179,6 @@ public: * @lua NA */ virtual void onEnterTransitionDidFinish() override; - -#ifdef CC_USE_PHYSICS - virtual void addChild(Node* child) override; - virtual void addChild(Node* child, int zOrder) override; - virtual void addChild(Node* child, int zOrder, int tag) override; -#endif // CC_USE_PHYSICS protected: void addTouchListener(); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 99283b95a8..53ea8d3f18 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -43,6 +43,7 @@ THE SOFTWARE. #include "CCEventDispatcher.h" #include "CCEvent.h" #include "CCEventTouch.h" +#include "CCScene.h" #ifdef CC_USE_PHYSICS #include "CCPhysicsBody.h" @@ -626,6 +627,17 @@ void Node::addChild(Node *child, int zOrder, int tag) } this->insertChild(child, zOrder); + +#ifdef CC_USE_PHYSICS + for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) + { + if (dynamic_cast(node) != nullptr) + { + (dynamic_cast(node))->addChildToPhysicsWorld(child); + break; + } + } +#endif child->_tag = tag; @@ -1392,10 +1404,12 @@ void Node::setPhysicsBody(PhysicsBody* body) { if (_physicsBody != nullptr) { + _physicsBody->_owner = nullptr; _physicsBody->release(); } _physicsBody = body; + _physicsBody->_owner = this; _physicsBody->retain(); _physicsBody->setPosition(getPosition()); _physicsBody->setRotation(getRotation()); diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index cc8654204b..5d0de936de 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -136,14 +136,8 @@ void Scene::addChildToPhysicsWorld(Node* child) std::function addToPhysicsWorldFunc = nullptr; addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void { - if (dynamic_cast(child) != nullptr) - { - Object* subChild = nullptr; - CCARRAY_FOREACH((dynamic_cast(child))->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else if (dynamic_cast(child) != nullptr) + + if (dynamic_cast(child) != nullptr) { Node* node = dynamic_cast(child); @@ -151,20 +145,16 @@ void Scene::addChildToPhysicsWorld(Node* child) { _physicsWorld->addBody(node->getPhysicsBody()); } + + Object* subChild = nullptr; + CCARRAY_FOREACH(node->getChildren(), subChild) + { + addToPhysicsWorldFunc(subChild); + } } }; - if(dynamic_cast(child) != nullptr) - { - Object* subChild = nullptr; - CCARRAY_FOREACH(child->getChildren(), subChild) - { - addToPhysicsWorldFunc(subChild); - } - }else - { - addToPhysicsWorldFunc(child); - } + addToPhysicsWorldFunc(child); } } diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 11e3e0fbb5..e0f69edd82 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -87,7 +87,7 @@ protected: PhysicsWorld* _physicsWorld; #endif // CC_USE_PHYSICS - friend class Layer; + friend class Node; friend class SpriteBatchNode; }; diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index b4be9bd045..af41111808 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -182,17 +182,6 @@ void SpriteBatchNode::addChild(Node *child, int zOrder, int tag) Node::addChild(child, zOrder, tag); appendChild(sprite); - - - if (this->getParent() && - dynamic_cast(this->getParent()) != nullptr) - { - if (this->getParent()->getParent() && - dynamic_cast(this->getParent()->getParent())) - { - dynamic_cast(this->getParent()->getParent())->addChildToPhysicsWorld(child); - } - } } // override reorderChild diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index c1a3d4b1a1..7d569075f8 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -44,7 +44,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(1.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.01f, 0.5f, 0.5f); /** * A body affect by physics. @@ -152,7 +152,7 @@ public: /* * @brief get the sprite the body set to. */ - inline Sprite* getOwner() const { return _owner; } + inline Node* getOwner() const { return _owner; } inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } inline int getCategoryBitmask() const { return _categoryBitmask; } @@ -261,7 +261,7 @@ protected: virtual ~PhysicsBody(); protected: - Sprite* _owner; + Node* _owner; std::vector _joints; Array* _shapes; PhysicsWorld* _world; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index c7ca4ef2f9..0abca9e9a4 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -41,6 +41,7 @@ #include "box2d/CCPhysicsShapeInfo.h" #include "chipmunk/CCPhysicsHelper.h" #include "box2d/CCPhysicsHelper.h" +#include "CCNode.h" NS_CC_BEGIN @@ -149,6 +150,11 @@ PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const return body->_info; } +Node* PhysicsJoint::bodyOwner(PhysicsBody* body) const +{ + return body->_owner; +} + void PhysicsJoint::setCollisionEnable(bool enable) { @@ -182,6 +188,9 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); + bodyOwner(a)->setPosition(anchr); + bodyOwner(b)->setPosition(anchr); + // add a pivot joint to fixed two body together cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); @@ -219,7 +228,6 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); @@ -227,7 +235,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) _info->add(joint); - setCollisionEnable(false); + //setCollisionEnable(false); return true; } while (false); @@ -235,6 +243,16 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) return false; } +void PhysicsJointPin::setMaxForce(float force) +{ + _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); +} + +float PhysicsJointPin::getMaxForce() +{ + return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); +} + PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) { PhysicsJointSliding* joint = new PhysicsJointSliding(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 67e05cb858..d6c0d5df15 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -63,6 +63,7 @@ protected: * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; + Node* bodyOwner(PhysicsBody* body) const; protected: PhysicsBody* _bodyA; @@ -82,7 +83,7 @@ protected: class PhysicsJointFixed : public PhysicsJoint { public: - PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -98,7 +99,7 @@ protected: class PhysicsJointSliding : public PhysicsJoint { public: - PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); + static PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); @@ -153,6 +154,9 @@ class PhysicsJointPin : public PhysicsJoint public: static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + void setMaxForce(float force); + float getMaxForce(); + protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 6cd5329f6d..02e6f604c0 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -57,7 +57,7 @@ typedef struct PhysicsMaterial {} }PhysicsMaterial; -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 1.0f, 1.0f); +const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT(0.0f, 0.5f, 0.5f); /** * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 915daa040e..c01f9ac640 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -524,7 +524,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (!joint->isCollisionEnable()) { - PhysicsBody* body = joint->getBodyA() == bodyA ? bodyB : bodyA; + PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); if (body == bodyB) { diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 304981c448..51d5d3252c 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -10,6 +10,7 @@ namespace CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), + CL(PhysicsDemoJoints), }; static int sceneIdx=-1; @@ -51,6 +52,7 @@ namespace } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); + static const int DRAG_BODYS_TAG = 100; } @@ -378,7 +380,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { shape = dynamic_cast(obj); - if (shape->getTag() == 1) + if (shape->getTag() == DRAG_BODYS_TAG) { break; } @@ -392,7 +394,8 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); - PhysicsJoint* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + joint->setMaxForce(5000.0f); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -492,7 +495,7 @@ void PhysicsDemoPyramidStack::onEnter() { auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - sp->getPhysicsBody()->setTag(1); + sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); } } } @@ -741,15 +744,74 @@ std::string PhysicsDemoRayCast::title() } +PhysicsDemoJoints::PhysicsDemoJoints() +{ + +} + void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); - _scene->getPhysicsWorld()->setGravity(Point::ZERO); + //_scene->getPhysicsWorld()->setGravity(Point::ZERO); + float width = (VisibleRect::getVisibleRect().size.width - 10) / 4; + float height = (VisibleRect::getVisibleRect().size.height - 50) / 4; + Node* node = Node::create(); + PhysicsBody* box = PhysicsBody::create(); + node->setPhysicsBody(box); + box->setDynamic(false); + node->setPosition(Point::ZERO); + + this->addChild(node); + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + Point offset(VisibleRect::leftBottom().x + 5 + j * width + width/2, VisibleRect::leftBottom().y + 50 + i * height + height/2); + box->addShape(PhysicsShapeEdgeBox::create(Size(width, height), PHYSICSSHAPE_MATERIAL_DEFAULT, 1, offset)); + + switch (i*4 + j) + { + case 0: + { + auto sp1 = makeBall(offset.x - 30, offset.y, 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBall(offset.x + 30, offset.y, 10); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + case 1: + { + + auto sp1 = makeBall(offset.x - 30, offset.y, 10); + sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + auto sp2 = makeBox(offset.x + 30, offset.y, Size(30, 10)); + sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + + PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + _scene->getPhysicsWorld()->addJoint(joint); + + this->addChild(sp1); + this->addChild(sp2); + break; + } + default: + break; + } + } + } } std::string PhysicsDemoJoints::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 736c71574a..fe58196372 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -39,9 +39,9 @@ public: void toggleDebugCallback(Object* sender); Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PhysicsMaterial(1.0f, 1.0f, 1.0f)); + Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); bool onTouchBegan(Touch* touch, Event* event) override; void onTouchMoved(Touch* touch, Event* event) override; From 06bd7fafd51a164c11894f5f44659cd2fcb386ea Mon Sep 17 00:00:00 2001 From: Andrew Glass Date: Mon, 28 Oct 2013 18:40:58 +0000 Subject: [PATCH 257/557] Clear NoSuchMethodError Exception when JniHelper fails to find methodID When calling GetMethodID a NoSuchMethodError will be raised if the method cannot be found. See http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html#wp16660 This exception should be cleared if JNI execution is to be continued. Currently JniHelper informs that the method is not found, but there is no way to continue execution without manually clearing the exception. This prevents checking for the existence of a method and recovering from it being missing. This fix will clear the exception if JniHelper fails to find the method. --- cocos/2d/platform/android/jni/JniHelper.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/2d/platform/android/jni/JniHelper.cpp b/cocos/2d/platform/android/jni/JniHelper.cpp index ab3bfc3855..9555643d7a 100644 --- a/cocos/2d/platform/android/jni/JniHelper.cpp +++ b/cocos/2d/platform/android/jni/JniHelper.cpp @@ -213,6 +213,7 @@ namespace cocos2d { jmethodID methodID = pEnv->GetMethodID(classID, methodName, paramCode); if (! methodID) { LOGD("Failed to find method id of %s", methodName); + pEnv->ExceptionClear(); return false; } @@ -247,6 +248,7 @@ namespace cocos2d { jmethodID methodID = pEnv->GetMethodID(classID, methodName, paramCode); if (! methodID) { LOGD("Failed to find method id of %s", methodName); + pEnv->ExceptionClear(); return false; } From fe180078f07b086c686659f1a192fb6707b229dc Mon Sep 17 00:00:00 2001 From: Michael Contento Date: Mon, 28 Oct 2013 23:12:51 +0100 Subject: [PATCH 258/557] Android: add xlargeScreens="true" to supports-screens --- .../Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml | 7 ++++--- samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml | 7 ++++--- samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml | 7 ++++--- samples/Cpp/TestCpp/proj.android/AndroidManifest.xml | 7 ++++--- .../CocosDragonJS/proj.android/AndroidManifest.xml | 7 ++++--- .../CrystalCraze/proj.android/AndroidManifest.xml | 7 ++++--- .../MoonWarriors/proj.android/AndroidManifest.xml | 7 ++++--- .../TestJavascript/proj.android/AndroidManifest.xml | 7 ++++--- .../WatermelonWithMe/proj.android/AndroidManifest.xml | 7 ++++--- samples/Lua/HelloLua/proj.android/AndroidManifest.xml | 7 ++++--- samples/Lua/TestLua/proj.android/AndroidManifest.xml | 7 ++++--- .../multi-platform-cpp/proj.android/AndroidManifest.xml | 7 ++++--- .../multi-platform-js/proj.android/AndroidManifest.xml | 7 ++++--- .../multi-platform-lua/proj.android/AndroidManifest.xml | 7 ++++--- 14 files changed, 56 insertions(+), 42 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml b/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml index 7f20e0ba1f..764617b6cd 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml +++ b/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml @@ -26,9 +26,10 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml b/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml index d2e4591587..dc1995c822 100644 --- a/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml +++ b/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml b/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml index 2436e1cf1f..840bcce203 100644 --- a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml +++ b/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml @@ -28,8 +28,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml b/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml index 6641325276..43c07631f9 100644 --- a/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml +++ b/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml @@ -27,10 +27,11 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml b/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml index 34607944fc..d68537fcf2 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml +++ b/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml b/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml index 6fa336830f..8a38988fae 100644 --- a/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml +++ b/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml b/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml index 8c1aa00cc0..f61fe3e0db 100644 --- a/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml +++ b/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml b/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml index 3797ac08e2..7beabd487a 100644 --- a/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml +++ b/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml @@ -28,8 +28,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml b/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml index aae0c2ff1d..6bbdd131cb 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml +++ b/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Lua/HelloLua/proj.android/AndroidManifest.xml b/samples/Lua/HelloLua/proj.android/AndroidManifest.xml index 56e3d50105..95394a531e 100644 --- a/samples/Lua/HelloLua/proj.android/AndroidManifest.xml +++ b/samples/Lua/HelloLua/proj.android/AndroidManifest.xml @@ -26,8 +26,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/samples/Lua/TestLua/proj.android/AndroidManifest.xml b/samples/Lua/TestLua/proj.android/AndroidManifest.xml index e131aee1a3..fb1ec4abb6 100644 --- a/samples/Lua/TestLua/proj.android/AndroidManifest.xml +++ b/samples/Lua/TestLua/proj.android/AndroidManifest.xml @@ -26,9 +26,10 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/template/multi-platform-cpp/proj.android/AndroidManifest.xml b/template/multi-platform-cpp/proj.android/AndroidManifest.xml index dc7f8640b6..466677da86 100644 --- a/template/multi-platform-cpp/proj.android/AndroidManifest.xml +++ b/template/multi-platform-cpp/proj.android/AndroidManifest.xml @@ -28,10 +28,11 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/template/multi-platform-js/proj.android/AndroidManifest.xml b/template/multi-platform-js/proj.android/AndroidManifest.xml index e37a9e90f9..0977e3eb08 100644 --- a/template/multi-platform-js/proj.android/AndroidManifest.xml +++ b/template/multi-platform-js/proj.android/AndroidManifest.xml @@ -27,8 +27,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> diff --git a/template/multi-platform-lua/proj.android/AndroidManifest.xml b/template/multi-platform-lua/proj.android/AndroidManifest.xml index b8964e7a15..17a26a9913 100644 --- a/template/multi-platform-lua/proj.android/AndroidManifest.xml +++ b/template/multi-platform-lua/proj.android/AndroidManifest.xml @@ -27,8 +27,9 @@ - + android:normalScreens="true" + android:largeScreens="true" + android:xlargeScreens="true"/> From d11854c11175b8442cae4b4559437abf2022bcf5 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 29 Oct 2013 09:04:11 +0800 Subject: [PATCH 259/557] Update AUTHORS --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 9357213fb6..89cb90728d 100644 --- a/AUTHORS +++ b/AUTHORS @@ -630,6 +630,9 @@ Developers: lite3 Fixed a bug that Node's anchor point was changed after being added to ScrollView. + superrad + Clear NoSuchMethodError Exception when JniHelper fails to find methodID + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From f2c229c722a60382678d92504a10a0bb4886671d Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 29 Oct 2013 09:05:04 +0800 Subject: [PATCH 260/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 567b572bc1..13c23de97a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [FIX] Fixed application will crash when pause and resume. + [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] From d4995a8c9c3b09a48e428d60f705f637aa5115aa Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 29 Oct 2013 10:06:32 +0800 Subject: [PATCH 261/557] Update AUTHORS --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 89cb90728d..469f299f7c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -592,6 +592,7 @@ Developers: Prevent nullptr access in AssetsManager [Android] re-introduce Cocos2dxHelper.runOnGLThread(Runnable) [Android] added EGL_RENDERABLE_TYPE to OpenGL attributes + Android: add xlargeScreens="true" to supports-screens bmanGH Use gl caching functions in TexturePVR::createGLTexture() From df3ebf84519c8337329eaf5fc3ca5abbcdfaf313 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 29 Oct 2013 10:07:43 +0800 Subject: [PATCH 262/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 13c23de97a..8fc9c367ee 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -14,6 +14,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id + [NEW] Added xlargeScreens="true" to supports-screens [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] From a4d028e905c31a8884bed780b158683370e4b500 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Tue, 29 Oct 2013 11:40:41 +0800 Subject: [PATCH 263/557] issue #3409:Add XMLHttpRequest lua binding and corresponding test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/scripting/lua/bindings/CCLuaStack.cpp | 4 + .../lua/bindings/LuaScriptHandlerMgr.h | 2 + .../lua/bindings/lua_xml_http_request.cpp | 195 ++++++++- .../lua/bindings/lua_xml_http_request.h | 10 +- cocos/scripting/lua/script/json.lua | 376 ++++++++++++++++++ .../XMLHttpRequestTest/XMLHttpRequestTest.lua | 147 +++++++ .../TestLua/Resources/luaScript/mainMenu.lua | 4 +- 8 files changed, 723 insertions(+), 17 deletions(-) create mode 100755 cocos/scripting/lua/script/json.lua create mode 100644 samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 70bb169acc..a937cb6412 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -83265c81797ca614f19372a96adf326aeb21b396 \ No newline at end of file +8a22c92b099f198f28124f0d7c6dd031b07d0154 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index be2aa86dd9..bad774b677 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -53,6 +53,7 @@ extern "C" { #include "LuaBasicConversions.h" #include "lua_cocos2dx_extension_manual.h" #include "lua_cocos2dx_deprecated.h" +#include "lua_xml_http_request.h" namespace { int lua_print(lua_State * luastate) @@ -148,6 +149,9 @@ bool LuaStack::init(void) #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) tolua_web_socket_open(_state); #endif + + register_xml_http_request(_state); + tolua_script_handler_mgr_open(_state); // add cocos2dx loader diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h index 44ea6fa103..82bcfee944 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h @@ -95,6 +95,8 @@ public: TABLECELL_SIZE_FOR_INDEX, TABLECELL_AT_INDEX, TABLEVIEW_NUMS_OF_CELLS, + + XMLHTTPREQUEST_READY_STATE_CHANGE, }; typedef int Handler; diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp index eaf2202ba0..f63e55c0b1 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp @@ -7,7 +7,13 @@ extern "C" } #include +#include "CCLuaStack.h" +#include "CCLuaValue.h" +#include "CCLuaEngine.h" +#include "LuaScriptHandlerMgr.h" + +using namespace cocos2d; using namespace std; LuaMinXmlHttpRequest::LuaMinXmlHttpRequest():_isNetwork(true) @@ -203,9 +209,12 @@ void LuaMinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, n /** get the response data **/ std::vector *buffer = response->getResponseData(); +// for (unsigned int i = 0; i < buffer->size(); i++) +// { +// printf("%c", (*buffer)[i]); +// } char* concatenated = (char*) malloc(buffer->size() + 1); std::string s2(buffer->begin(), buffer->end()); - strcpy(concatenated, s2.c_str()); if (statusCode == 200) @@ -225,7 +234,19 @@ void LuaMinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, n free((void*) concatenated); // call back lua function --TODO - int handler = 0; + int handler = cocos2d::ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, cocos2d::ScriptHandlerMgr::HandlerType::XMLHTTPREQUEST_READY_STATE_CHANGE ); + + if (0 != handler) + { + cocos2d::CommonScriptData data(handler,""); + cocos2d::ScriptEvent event(cocos2d::ScriptEventType::kCommonEvent,(void*)&data); + cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); + } +} + +void LuaMinXmlHttpRequest::getByteData(unsigned char* byteData) +{ + _data.read((char*)byteData, _dataSize); } /* function to regType */ @@ -258,6 +279,7 @@ static int lua_cocos2dx_XMLHttpRequest_constructor(lua_State* L) int ID = self? (int)self->_ID : -1; int* luaID = self? &self->_luaID : NULL; toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "XMLHttpRequest"); + return 1; } CCLOG("%s has wrong number of arguments: %d, was expecting %d \n", "XMLHttpRequest",argc, 0); @@ -567,6 +589,33 @@ tolua_lerror: #endif } +static int lua_get_XMLHttpRequest_responseText(lua_State* L) +{ + LuaMinXmlHttpRequest* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_get_XMLHttpRequest_responseText'\n", nullptr); + return 0; + } +#endif + lua_pushstring(L, self->getDataStr().c_str()); + return 1; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_get_XMLHttpRequest_responseText'.",&tolua_err); + return 0; +#endif +} + static int lua_get_XMLHttpRequest_response(lua_State* L) { LuaMinXmlHttpRequest* self = nullptr; @@ -587,17 +636,46 @@ static int lua_get_XMLHttpRequest_response(lua_State* L) if (self->getResponseType() == LuaMinXmlHttpRequest::ResponseType::JSON) { - //TODO - return 0; + lua_pushstring(L, self->getDataStr().c_str()); + return 1; } else if(self->getResponseType() == LuaMinXmlHttpRequest::ResponseType::ARRAY_BUFFER) { - //TODO - return 0; + LuaStack *pStack = LuaEngine::getInstance()->getLuaStack(); + if (NULL == pStack) { + return 0; + } + + lua_State *tolua_s = pStack->getLuaState(); + if (NULL == tolua_s) { + return 0; + } + + int nRet = 0; + LuaValueArray array; + + uint8_t* tmpData = new uint8_t[self->getDataSize()]; + if (nullptr == tmpData) + { + return 0; + } + + self->getByteData(tmpData); + + for (int i = 0 ; i < self->getDataSize(); i++) + { + LuaValue value = LuaValue::intValue(tmpData[i]); + array.push_back(value); + } + + pStack->pushLuaValueArray(array); + + CC_SAFE_DELETE_ARRAY(tmpData); + return 1; } else { - lua_pushstring(L, self->getStatusText().c_str()); + lua_pushstring(L, self->getDataStr().c_str()); return 1; } @@ -694,7 +772,9 @@ static int lua_cocos2dx_XMLHttpRequest_send(lua_State* L) { int argc = 0; LuaMinXmlHttpRequest* self = nullptr; - std::string data = ""; + //std::string data = ""; + const char* data = NULL; + size_t size = 0; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; @@ -718,14 +798,15 @@ static int lua_cocos2dx_XMLHttpRequest_send(lua_State* L) if (!tolua_isstring(L, 2, 0, &tolua_err)) goto tolua_lerror; #endif - data = tolua_tostring(L, 2, ""); + //data = tolua_tostring(L, 2, ""); + data = (const char*) lua_tolstring(L, 2, &size); } - if (data.length() > 0 && + if (size > 0 && (self->getMethod().compare("post") == 0 || self->getMethod().compare("POST") == 0) && nullptr != self->getHttpRequest()) { - self->getHttpRequest()->setRequestData(data.c_str(), data.length()); + self->getHttpRequest()->setRequestData(data,size); } self->_setHttpRequestHeader(); @@ -894,13 +975,98 @@ tolua_lerror: #endif } -TOLUA_API int lua_xml_http_request_open(lua_State* L) +static int lua_cocos2dx_XMLHttpRequest_registerScriptHandler(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + + string responseheader = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_registerScriptHandler'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err)) + goto tolua_lerror; +#endif + + int handler = ( toluafix_ref_function(L,2,0)); + cocos2d::ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, cocos2d::ScriptHandlerMgr::HandlerType::XMLHTTPREQUEST_READY_STATE_CHANGE); + return 0; + } + + CCLOG("'registerScriptHandler' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler(lua_State* L) +{ + int argc = 0; + LuaMinXmlHttpRequest* self = nullptr; + + string responseheader = ""; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + cocos2d::ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, cocos2d::ScriptHandlerMgr::HandlerType::XMLHTTPREQUEST_READY_STATE_CHANGE); + + return 0; + } + + CCLOG("'unregisterScriptHandler' function of XMLHttpRequest wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler'.",&tolua_err); + return 0; +#endif + +} + + +TOLUA_API int register_xml_http_request(lua_State* L) { tolua_open(L); lua_reg_xml_http_request(L); tolua_module(L,NULL,0); tolua_beginmodule(L,NULL); - tolua_cclass(L,"XMLHttpRequest","XMLHttpRequest","",lua_collect_xml_http_request); + tolua_cclass(L,"XMLHttpRequest","XMLHttpRequest","Object",lua_collect_xml_http_request); tolua_beginmodule(L,"XMLHttpRequest"); tolua_variable(L, "responseType", lua_get_XMLHttpRequest_responseType, lua_set_XMLHttpRequest_responseType); tolua_variable(L, "withCredentials", lua_get_XMLHttpRequest_withCredentials, lua_set_XMLHttpRequest_withCredentials); @@ -908,6 +1074,7 @@ TOLUA_API int lua_xml_http_request_open(lua_State* L) tolua_variable(L, "readyState", lua_get_XMLHttpRequest_readyState, nullptr); tolua_variable(L, "status",lua_get_XMLHttpRequest_status,nullptr); tolua_variable(L, "statusText", lua_get_XMLHttpRequest_statusText, nullptr); + tolua_variable(L, "responseText", lua_get_XMLHttpRequest_responseText, nullptr); tolua_variable(L, "response", lua_get_XMLHttpRequest_response, nullptr); tolua_function(L, "new", lua_cocos2dx_XMLHttpRequest_constructor); tolua_function(L, "open", lua_cocos2dx_XMLHttpRequest_open); @@ -916,6 +1083,8 @@ TOLUA_API int lua_xml_http_request_open(lua_State* L) tolua_function(L, "setRequestHeader", lua_cocos2dx_XMLHttpRequest_setRequestHeader); tolua_function(L, "getAllResponseHeaders", lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders); tolua_function(L, "getResponseHeader", lua_cocos2dx_XMLHttpRequest_getResponseHeader); + tolua_function(L, "registerScriptHandler", lua_cocos2dx_XMLHttpRequest_registerScriptHandler); + tolua_function(L, "unregisterScriptHandler", lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler); tolua_endmodule(L); tolua_endmodule(L); return 1; diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.h b/cocos/scripting/lua/bindings/lua_xml_http_request.h index 2b5a3a2f17..900ec6db35 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.h +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.h @@ -66,11 +66,17 @@ public: void setRequestHeader(const char* field, const char* value); std::map getHttpHeader() { return _httpHeader ;} + + void getByteData(unsigned char* byteData); + + inline std::string getDataStr() { return _data.str(); } + + inline size_t getDataSize() { return _dataSize; } + private: void _gotHeader(std::string header); - std::string _url; std::string _meth; std::string _type; @@ -89,6 +95,6 @@ private: std::map _requestHeader; }; -TOLUA_API int lua_xml_http_request_open(lua_State* L); +TOLUA_API int register_xml_http_request(lua_State* L); #endif //#ifndef __COCOS_SCRIPTING_LUA_BINDINGS_LUA_XML_HTTP_REQUEST_H__ diff --git a/cocos/scripting/lua/script/json.lua b/cocos/scripting/lua/script/json.lua new file mode 100755 index 0000000000..e0b3d17c3e --- /dev/null +++ b/cocos/scripting/lua/script/json.lua @@ -0,0 +1,376 @@ +----------------------------------------------------------------------------- +-- JSON4Lua: JSON encoding / decoding support for the Lua language. +-- json Module. +-- Author: Craig Mason-Jones +-- Homepage: http://json.luaforge.net/ +-- Version: 0.9.40 +-- This module is released under the MIT License (MIT). +-- Please see LICENCE.txt for details. +-- +-- USAGE: +-- This module exposes two functions: +-- encode(o) +-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. +-- decode(json_string) +-- Returns a Lua object populated with the data encoded in the JSON string json_string. +-- +-- REQUIREMENTS: +-- compat-5.1 if using Lua 5.0 +-- +-- CHANGELOG +-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). +-- Fixed Lua 5.1 compatibility issues. +-- Introduced json.null to have null values in associative arrays. +-- encode() performance improvement (more than 50%) through table.concat rather than .. +-- Introduced decode ability to ignore /**/ comments in the JSON string. +-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Imports and dependencies +----------------------------------------------------------------------------- +local math = require('math') +local string = require("string") +local table = require("table") + +local base = _G + +----------------------------------------------------------------------------- +-- Module declaration +----------------------------------------------------------------------------- +module("json") + +-- Public functions + +-- Private functions +local decode_scanArray +local decode_scanComment +local decode_scanConstant +local decode_scanNumber +local decode_scanObject +local decode_scanString +local decode_scanWhitespace +local encodeString +local isArray +local isEncodable + +----------------------------------------------------------------------------- +-- PUBLIC FUNCTIONS +----------------------------------------------------------------------------- +--- Encodes an arbitrary Lua object / variable. +-- @param v The Lua object / variable to be JSON encoded. +-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) +function encode (v) + -- Handle nil values + if v==nil then + return "null" + end + + local vtype = base.type(v) + + -- Handle strings + if vtype=='string' then + return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string + end + + -- Handle booleans + if vtype=='number' or vtype=='boolean' then + return base.tostring(v) + end + + -- Handle tables + if vtype=='table' then + local rval = {} + -- Consider arrays separately + local bArray, maxCount = isArray(v) + if bArray then + for i = 1,maxCount do + table.insert(rval, encode(v[i])) + end + else -- An object, not an array + for i,j in base.pairs(v) do + if isEncodable(i) and isEncodable(j) then + table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j)) + end + end + end + if bArray then + return '[' .. table.concat(rval,',') ..']' + else + return '{' .. table.concat(rval,',') .. '}' + end + end + + -- Handle null values + if vtype=='function' and v==null then + return 'null' + end + + base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v)) +end + + +--- Decodes a JSON string and returns the decoded value as a Lua data structure / value. +-- @param s The string to scan. +-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. +-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, +-- and the position of the first character after +-- the scanned JSON object. +function decode(s, startPos) + startPos = startPos and startPos or 1 + startPos = decode_scanWhitespace(s,startPos) + base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') + local curChar = string.sub(s,startPos,startPos) + -- Object + if curChar=='{' then + return decode_scanObject(s,startPos) + end + -- Array + if curChar=='[' then + return decode_scanArray(s,startPos) + end + -- Number + if string.find("+-0123456789.e", curChar, 1, true) then + return decode_scanNumber(s,startPos) + end + -- String + if curChar==[["]] or curChar==[[']] then + return decode_scanString(s,startPos) + end + if string.sub(s,startPos,startPos+1)=='/*' then + return decode(s, decode_scanComment(s,startPos)) + end + -- Otherwise, it must be a constant + return decode_scanConstant(s,startPos) +end + +--- The null function allows one to specify a null value in an associative array (which is otherwise +-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } +function null() + return null -- so json.null() will also return null ;-) +end +----------------------------------------------------------------------------- +-- Internal, PRIVATE functions. +-- Following a Python-like convention, I have prefixed all these 'PRIVATE' +-- functions with an underscore. +----------------------------------------------------------------------------- + +--- Scans an array from JSON into a Lua object +-- startPos begins at the start of the array. +-- Returns the array and the next starting position +-- @param s The string being scanned. +-- @param startPos The starting position for the scan. +-- @return table, int The scanned array as a table, and the position of the next character to scan. +function decode_scanArray(s,startPos) + local array = {} -- The return value + local stringLen = string.len(s) + base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) + startPos = startPos + 1 + -- Infinite loop for array elements + repeat + startPos = decode_scanWhitespace(s,startPos) + base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') + local curChar = string.sub(s,startPos,startPos) + if (curChar==']') then + return array, startPos+1 + end + if (curChar==',') then + startPos = decode_scanWhitespace(s,startPos+1) + end + base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') + object, startPos = decode(s,startPos) + table.insert(array,object) + until false +end + +--- Scans a comment and discards the comment. +-- Returns the position of the next character following the comment. +-- @param string s The JSON string to scan. +-- @param int startPos The starting position of the comment +function decode_scanComment(s, startPos) + base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) + local endPos = string.find(s,'*/',startPos+2) + base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) + return endPos+2 +end + +--- Scans for given constants: true, false or null +-- Returns the appropriate Lua type, and the position of the next character to read. +-- @param s The string being scanned. +-- @param startPos The position in the string at which to start scanning. +-- @return object, int The object (true, false or nil) and the position at which the next character should be +-- scanned. +function decode_scanConstant(s, startPos) + local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } + local constNames = {"true","false","null"} + + for i,k in base.pairs(constNames) do + --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) + if string.sub(s,startPos, startPos + string.len(k) -1 )==k then + return consts[k], startPos + string.len(k) + end + end + base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) +end + +--- Scans a number from the JSON encoded string. +-- (in fact, also is able to scan numeric +- eqns, which is not +-- in the JSON spec.) +-- Returns the number, and the position of the next character +-- after the number. +-- @param s The string being scanned. +-- @param startPos The position at which to start scanning. +-- @return number, int The extracted number and the position of the next character to scan. +function decode_scanNumber(s,startPos) + local endPos = startPos+1 + local stringLen = string.len(s) + local acceptableChars = "+-0123456789.e" + while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) + and endPos<=stringLen + ) do + endPos = endPos + 1 + end + local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) + local stringEval = base.loadstring(stringValue) + base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) + return stringEval(), endPos +end + +--- Scans a JSON object into a Lua object. +-- startPos begins at the start of the object. +-- Returns the object and the next starting position. +-- @param s The string being scanned. +-- @param startPos The starting position of the scan. +-- @return table, int The scanned object as a table and the position of the next character to scan. +function decode_scanObject(s,startPos) + local object = {} + local stringLen = string.len(s) + local key, value + base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) + startPos = startPos + 1 + repeat + startPos = decode_scanWhitespace(s,startPos) + base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') + local curChar = string.sub(s,startPos,startPos) + if (curChar=='}') then + return object,startPos+1 + end + if (curChar==',') then + startPos = decode_scanWhitespace(s,startPos+1) + end + base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') + -- Scan the key + key, startPos = decode(s,startPos) + base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + startPos = decode_scanWhitespace(s,startPos) + base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) + startPos = decode_scanWhitespace(s,startPos+1) + base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + value, startPos = decode(s,startPos) + object[key]=value + until false -- infinite loop while key-value pairs are found +end + +--- Scans a JSON string from the opening inverted comma or single quote to the +-- end of the string. +-- Returns the string extracted as a Lua string, +-- and the position of the next non-string character +-- (after the closing inverted comma or single quote). +-- @param s The string being scanned. +-- @param startPos The starting position of the scan. +-- @return string, int The extracted string as a Lua string, and the next character to parse. +function decode_scanString(s,startPos) + base.assert(startPos, 'decode_scanString(..) called without start position') + local startChar = string.sub(s,startPos,startPos) + base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') + local escaped = false + local endPos = startPos + 1 + local bEnded = false + local stringLen = string.len(s) + repeat + local curChar = string.sub(s,endPos,endPos) + if not escaped then + if curChar==[[\]] then + escaped = true + else + bEnded = curChar==startChar + end + else + -- If we're escaped, we accept the current character come what may + escaped = false + end + endPos = endPos + 1 + base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) + until bEnded + local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) + local stringEval = base.loadstring(stringValue) + base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) + return stringEval(), endPos +end + +--- Scans a JSON string skipping all whitespace from the current start position. +-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. +-- @param s The string being scanned +-- @param startPos The starting position where we should begin removing whitespace. +-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string +-- was reached. +function decode_scanWhitespace(s,startPos) + local whitespace=" \n\r\t" + local stringLen = string.len(s) + while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do + startPos = startPos + 1 + end + return startPos +end + +--- Encodes a string to be JSON-compatible. +-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) +-- @param s The string to return as a JSON encoded (i.e. backquoted string) +-- @return The string appropriately escaped. +function encodeString(s) + s = string.gsub(s,'\\','\\\\') + s = string.gsub(s,'"','\\"') + s = string.gsub(s,"'","\\'") + s = string.gsub(s,'\n','\\n') + s = string.gsub(s,'\t','\\t') + return s +end + +-- Determines whether the given Lua type is an array or a table / dictionary. +-- We consider any table an array if it has indexes 1..n for its n items, and no +-- other data in the table. +-- I think this method is currently a little 'flaky', but can't think of a good way around it yet... +-- @param t The table to evaluate as an array +-- @return boolean, number True if the table can be represented as an array, false otherwise. If true, +-- the second returned value is the maximum +-- number of indexed elements in the array. +function isArray(t) + -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable + -- (with the possible exception of 'n') + local maxIndex = 0 + for k,v in base.pairs(t) do + if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair + if (not isEncodable(v)) then return false end -- All array elements must be encodable + maxIndex = math.max(maxIndex,k) + else + if (k=='n') then + if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements + else -- Else of (k=='n') + if isEncodable(v) then return false end + end -- End of (k~='n') + end -- End of k,v not an indexed pair + end -- End of loop across all pairs + return true, maxIndex +end + +--- Determines whether the given Lua object / table / variable can be JSON encoded. The only +-- types that are JSON encodable are: string, boolean, number, nil, table and json.null. +-- In this implementation, all other types are ignored. +-- @param o The object to examine. +-- @return boolean True if the object should be JSON encoded, false if it should be ignored. +function isEncodable(o) + local t = base.type(o) + return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null) +end + diff --git a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua new file mode 100644 index 0000000000..2456d5d092 --- /dev/null +++ b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua @@ -0,0 +1,147 @@ +require("json") + +local function XMLHttpRequestLayer() + local layer = cc.Layer:create() + local winSize = cc.Director:getInstance():getWinSize() + local margin = 40 + local space = 35 + + local function init() + local label = cc.LabelTTF:create("XML Http Request Test", "Arial", 28) + label:setPosition(cc.p(winSize.width / 2, winSize.height - margin)) + layer:addChild(label, 0) + + --Response Code Label + local labelStatusCode = cc.LabelTTF:create("HTTP Status Code", "Marker Felt", 20) + labelStatusCode:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 6 * space)) + layer:addChild(labelStatusCode) + + local menuRequest = cc.Menu:create() + menuRequest:setPosition(cc.p(0,0)) + layer:addChild(menuRequest) + + --Get + local function onMenuGetClicked() + local xhr = XMLHttpRequest:new() + xhr.responseType = 0 + xhr:open("GET", "http://httpbin.org/get") + + local function onReadyStateChange() + local statusString = "Http Status Code:"..xhr.statusText + labelStatusCode:setString(statusString) + print(xhr.response) + end + + xhr:registerScriptHandler(onReadyStateChange) + xhr:send() + + labelStatusCode:setString("waiting...") + end + + local labelGet = cc.LabelTTF:create("Test Get", "Arial", 22) + local itemGet = cc.MenuItemLabel:create(labelGet) + itemGet:registerScriptTapHandler(onMenuGetClicked) + itemGet:setPosition(cc.p(winSize.width / 2, winSize.height - margin - space)) + menuRequest:addChild(itemGet) + + --Post + local function onMenuPostClicked() + local xhr = XMLHttpRequest:new() + xhr.responseType = 0 + xhr:open("POST", "http://httpbin.org/post") + local function onReadyStateChange() + labelStatusCode:setString("Http Status Code:"..xhr.statusText) + print(xhr.response) + end + xhr:registerScriptHandler(onReadyStateChange) + xhr:send() + + labelStatusCode:setString("waiting...") + end + + local labelPost = cc.LabelTTF:create("Test Post", "Arial", 22) + local itemPost = cc.MenuItemLabel:create(labelPost) + itemPost:registerScriptTapHandler(onMenuPostClicked) + itemPost:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 2 * space)) + menuRequest:addChild(itemPost) + + --Post Binary + local function onMenuPostBinaryClicked() + local xhr = XMLHttpRequest:new() + xhr.responseType = 1 + xhr:open("POST", "http://httpbin.org/post") + + local function onReadyStateChange() + local response = xhr.response + local size = table.getn(response) + local strInfo = "" + + for i = 1,size do + if 0 == response[i] then + strInfo = strInfo.."\'\\0\'" + else + strInfo = strInfo..string.char(response[i]) + end + end + labelStatusCode:setString("Http Status Code:"..xhr.statusText) + print(strInfo) + end + + xhr:registerScriptHandler(onReadyStateChange) + xhr:send() + + labelStatusCode:setString("waiting...") + end + + local labelPostBinary = cc.LabelTTF:create("Test Post Binary", "Arial", 22) + local itemPostBinary = cc.MenuItemLabel:create(labelPostBinary) + itemPostBinary:registerScriptTapHandler(onMenuPostBinaryClicked) + itemPostBinary:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 3 * space)) + menuRequest:addChild(itemPostBinary) + + --Post Json + + local function onMenuPostJsonClicked() + local xhr = XMLHttpRequest:new() + xhr.responseType = 4 + xhr:open("POST", "http://httpbin.org/post") + + local function onReadyStateChange() + labelStatusCode:setString("Http Status Code:"..xhr.statusText) + local response = xhr.response + local output = json.decode(response,1) + table.foreach(output,function(i, v) print (i, v) end) + print("headers are") + table.foreach(output.headers,print) + end + + xhr:registerScriptHandler(onReadyStateChange) + xhr:send() + + labelStatusCode:setString("waiting...") + end + + local labelPostJson = cc.LabelTTF:create("Test Post Json", "Arial", 22) + local itemPostJson = cc.MenuItemLabel:create(labelPostJson) + itemPostJson:registerScriptTapHandler(onMenuPostJsonClicked) + itemPostJson:setPosition(cc.p(winSize.width / 2, winSize.height - margin - 4 * space)) + menuRequest:addChild(itemPostJson) + end + + local function onNodeEvent(eventName) + if "enter" == eventName then + init() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + +function XMLHttpRequestTestMain() + local scene = cc.Scene:create() + scene:addChild(XMLHttpRequestLayer()) + scene:addChild(CreateBackMenuItem()) + return scene +end diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua index 73d79855d6..3129caf5cb 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua @@ -44,6 +44,7 @@ require "luaScript/TransitionsTest/TransitionsTest" require "luaScript/UserDefaultTest/UserDefaultTest" require "luaScript/ZwoptexTest/ZwoptexTest" require "luaScript/LuaBridgeTest/LuaBridgeTest" +require "luaScript/XMLHttpRequestTest/XMLHttpRequestTest" local LINE_SPACE = 40 @@ -97,7 +98,8 @@ local _allTests = { { isSupported = true, name = "TransitionsTest" , create_func = TransitionsTest }, { isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain }, { isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain }, - { isSupported = true, name = "LuaBridgeTest" , create_func = LuaBridgeMainTest } + { isSupported = true, name = "LuaBridgeTest" , create_func = LuaBridgeMainTest }, + { isSupported = true, name = "XMLHttpRequestTest" , create_func = XMLHttpRequestTestMain} } local TESTS_COUNT = table.getn(_allTests) From 296978a9bee8ac85e8d2e8512c3d9781bedfe53c Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 14:57:16 +0800 Subject: [PATCH 264/557] issue #3069: Separate 'EventDispatcher::removeEventListeners' to 'removeEventListeners' and 'removeCustomEventListeners'. --- cocos/2d/CCEventDispatcher.cpp | 16 ++++++++++++++-- cocos/2d/CCEventDispatcher.h | 25 ++++++++++++++++--------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 1ebadf9b74..8d590c033d 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -993,7 +993,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene return nullptr; } -void EventDispatcher::removeEventListeners(EventListener::ListenerID listenerID) +void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerID listenerID) { auto listenerItemIter = _listeners.find(listenerID); if (listenerItemIter != _listeners.end()) @@ -1040,6 +1040,18 @@ void EventDispatcher::removeEventListeners(EventListener::ListenerID listenerID) } } +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(listenerType)); +} + +void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) +{ + removeEventListenersForListenerID(std::hash()(customEventName)); +} + void EventDispatcher::removeAllEventListeners() { std::vector types(_listeners.size()); @@ -1051,7 +1063,7 @@ void EventDispatcher::removeAllEventListeners() for (auto& type : types) { - removeEventListeners(type); + removeEventListenersForListenerID(type); } if (!_inDispatch) diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 3609c7a591..b8b1aa8efb 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -74,8 +74,11 @@ public: */ void removeEventListener(EventListener* listener); - /** Removes all listeners with the same event listener ID */ - void removeEventListeners(EventListener::ListenerID listenerID); + /** 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(); @@ -95,6 +98,14 @@ public: */ void dispatchEvent(Event* event); + /** Constructor of EventDispatcher */ + EventDispatcher(); + /** Destructor of EventDispatcher */ + ~EventDispatcher(); + +private: + friend class Node; + /** Sets the dirty flag for a node. */ void setDirtyForNode(Node* node); @@ -107,13 +118,6 @@ public: /** Notifys event dispatcher that the node has been deleted. */ void cleanTarget(Node* node); - /** Constructor of EventDispatcher */ - EventDispatcher(); - /** Destructor of EventDispatcher */ - ~EventDispatcher(); - -private: - /** * The vector to store event listeners with scene graph based priority and fixed priority. */ @@ -149,6 +153,9 @@ private: /** Update dirty flag */ void updateDirtyFlagForSceneGraph(); + /** Removes all listeners with the same event listener ID */ + void removeEventListenersForListenerID(EventListener::ListenerID listenerID); + /** Sort event listener */ void sortEventListeners(EventListener::ListenerID listenerID); From 5698dcd0e18788a00b9fb6510224f310cbfb856e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 14:58:47 +0800 Subject: [PATCH 265/557] issue #3069: Protecting some methods in EventListener, make EventDispatcher as its friend class. --- cocos/2d/CCEventListener.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCEventListener.h b/cocos/2d/CCEventListener.h index bbf5121149..ea4734f7a3 100644 --- a/cocos/2d/CCEventListener.h +++ b/cocos/2d/CCEventListener.h @@ -74,6 +74,7 @@ public: /** Clones the listener, its subclasses have to override this method. */ virtual EventListener* clone() = 0; +protected: inline void setPaused(bool paused) { _paused = paused; }; inline bool isPaused() const { return _paused; }; @@ -91,16 +92,16 @@ public: std::function _onEvent; /// Event callback function -protected: - Type _type; /// Event listener type ListenerID _listenerID; /// Event listener ID bool _isRegistered; /// Whether the listener has been added to dispatcher. // The priority of event listener int _fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority. - Node* _node; // scene graph based priority - bool _paused; + Node* _node; // scene graph based priority + bool _paused; // Whether the listener is paused + + friend class EventDispatcher; }; NS_CC_END From cb7a762584dd9fcc800ad31ee616bd6b3eff5f06 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 14:59:05 +0800 Subject: [PATCH 266/557] issue #3069: Updating EventDispatcherTest. --- .../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 8aa31bb82f..bbc041c70b 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -187,7 +187,7 @@ void TouchableSpriteTest::onEnter() auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - _eventDispatcher->removeEventListeners(EventListenerTouchOneByOne::ID); + _eventDispatcher->removeEventListeners(EventListener::Type::TOUCH_ONE_BY_ONE); auto nextItem = MenuItemFont::create("Next", [=](Object* sender){ nextCallback(nullptr); From 01579e12b0e87a9ae4affa12a376eb60bfed7e0e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 15:01:39 +0800 Subject: [PATCH 267/557] issue #3069: Remove unused ID. --- cocos/2d/CCEventListenerAcceleration.h | 2 -- cocos/2d/CCEventListenerKeyboard.h | 2 -- cocos/2d/CCEventListenerTouch.h | 2 -- 3 files changed, 6 deletions(-) diff --git a/cocos/2d/CCEventListenerAcceleration.h b/cocos/2d/CCEventListenerAcceleration.h index 213bac646e..59ce3d8439 100644 --- a/cocos/2d/CCEventListenerAcceleration.h +++ b/cocos/2d/CCEventListenerAcceleration.h @@ -33,8 +33,6 @@ NS_CC_BEGIN class EventListenerAcceleration : public EventListener { public: - static const ListenerID ID = static_cast(Type::ACCELERATION); - static EventListenerAcceleration* create(std::function callback); virtual ~EventListenerAcceleration(); diff --git a/cocos/2d/CCEventListenerKeyboard.h b/cocos/2d/CCEventListenerKeyboard.h index 6c59f69121..c34d2add0d 100644 --- a/cocos/2d/CCEventListenerKeyboard.h +++ b/cocos/2d/CCEventListenerKeyboard.h @@ -36,8 +36,6 @@ class Event; class EventListenerKeyboard : public EventListener { public: - static const ListenerID ID = static_cast(Type::KEYBOARD); - static EventListenerKeyboard* create(); /// Overrides diff --git a/cocos/2d/CCEventListenerTouch.h b/cocos/2d/CCEventListenerTouch.h index 94b0bd65b7..80ff176263 100644 --- a/cocos/2d/CCEventListenerTouch.h +++ b/cocos/2d/CCEventListenerTouch.h @@ -36,8 +36,6 @@ NS_CC_BEGIN class EventListenerTouchOneByOne : public EventListener { public: - static const ListenerID ID = static_cast(Type::TOUCH_ONE_BY_ONE); - static EventListenerTouchOneByOne* create(); virtual ~EventListenerTouchOneByOne(); From fbd04a476ab9e151e13627d6da6f906e5f89d469 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 15:02:26 +0800 Subject: [PATCH 268/557] issue #3069: Updating comments in CCEventListenerCustom.h. --- cocos/2d/CCEventListenerCustom.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCEventListenerCustom.h b/cocos/2d/CCEventListenerCustom.h index eb7e875165..e2e750ce56 100644 --- a/cocos/2d/CCEventListenerCustom.h +++ b/cocos/2d/CCEventListenerCustom.h @@ -33,21 +33,21 @@ class EventCustom; /** * Usage: - * auto dispatcher = EventDispatcher::getInstance(); + * auto dispatcher = Director::getInstance()->getEventDispatcher(); * Adds a listener: * - * auto callback = [](CustomEvent* event){ do_some_thing(); }; - * auto listener = CustomEventListener::create(callback); + * auto callback = [](EventCustom* event){ do_some_thing(); }; + * auto listener = EventListenerCustom::create(callback); * dispatcher->addEventListenerWithSceneGraphPriority(listener, one_node); * * Dispatchs a custom event: * - * Event event("your_event_type"); + * EventCustom event("your_event_type"); * dispatcher->dispatchEvent(&event); * * Removes a listener * - * dispatcher->removeListener(listener); + * dispatcher->removeEventListener(listener); */ class EventListenerCustom : public EventListener { From bb568e84e83d9c3b6cae993db4a8dfe827547417 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 15:09:13 +0800 Subject: [PATCH 269/557] Updating auto generated binding codes. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 2f3c531665..4fd4e14912 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 2f3c5316657e64ec38b8ed3ea6826eb48c46f32c +Subproject commit 4fd4e14912165a2c8a5a6faacda2626035af6f36 From 91932ea9063b56c295edfac9c486d55aed726a4b Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 15:36:43 +0800 Subject: [PATCH 270/557] issue #3069: Fixing compilation errors. --- cocos/2d/platform/android/nativeactivity.cpp | 14 ++++++++------ cocos/2d/platform/linux/CCEGLView.cpp | 3 ++- cocos/2d/platform/win32/CCEGLView.cpp | 3 ++- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index fa4fb434d4..5ac17a5ee5 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -422,18 +422,20 @@ static int32_t handle_key_input(AInputEvent *event) { if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) { + auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); + switch (AKeyEvent_getKeyCode(event)) { case AKEYCODE_BACK: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); - cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); + dispatcher->dispatchEvent(&event); } return 1; case AKEYCODE_MENU: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); - cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); + dispatcher->dispatchEvent(&event); } return 1; default: @@ -629,8 +631,8 @@ void android_main(struct android_app* state) { acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); - - cocos2d::EventDispatcher::getInstance()->dispatchEvent(&accEvent); + auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&accEvent); } else { // ACONFIGURATION_ORIENTATION_LAND // swap x and y parameters @@ -640,8 +642,8 @@ void android_main(struct android_app* state) { acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); - - cocos2d::EventDispatcher::getInstance()->dispatchEvent(&accEvent); + auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&accEvent); } } } diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 561fedcca8..172c9d796a 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -223,7 +223,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - EventDispatcher::getInstance()->dispatchEvent(&event); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index d5b2ba0202..92bfbe5cf1 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -341,7 +341,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - EventDispatcher::getInstance()->dispatchEvent(&event); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) From e2ce7144636ca0b7430dfa01fca302f2bd04a8a2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 16:20:42 +0800 Subject: [PATCH 271/557] issue #3069: Update device.mm for iOS. --- cocos/2d/platform/ios/CCDevice.mm | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index fdc9448849..efc42c8788 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -100,7 +100,8 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; } cocos2d::EventAcceleration event(*_acceleration); - cocos2d::_eventDispatcherdispatchEvent(&event); + auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); } @end From 5c8424423e3f55f28ce5ee5b34e0ba00abfc208f Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 29 Oct 2013 16:29:29 +0800 Subject: [PATCH 272/557] issue #3069: Update ios/CCDevice.mm. --- cocos/2d/platform/ios/CCDevice.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index efc42c8788..4555b14df2 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -2,7 +2,7 @@ #include "ccTypes.h" #include "CCEventDispatcher.h" #include "CCEventAcceleration.h" - +#include "CCDirector.h" #import // Accelerometer From 2d3df6998257661005294c1303602f4c8e318448 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 29 Oct 2013 16:57:06 +0800 Subject: [PATCH 273/557] fix add display --- cocos/editor-support/cocostudio/CCArmature.cpp | 11 +++-------- cocos/editor-support/cocostudio/CCBone.cpp | 13 +++++++++++++ .../editor-support/cocostudio/CCDisplayManager.cpp | 1 + cocos/editor-support/cocostudio/CCSkin.cpp | 1 + 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 5c3b54e3df..ca935722c8 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -265,18 +265,12 @@ void Armature::addBone(Bone *bone, const char *parentName) } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } } else { - if (_parentBone) - _parentBone->addChildBone(bone); - else - _topBoneList->addObject(bone); + _topBoneList->addObject(bone); } bone->setArmature(this); @@ -527,6 +521,7 @@ void Armature::draw() } } armature->draw(); + _atlas = armature->getTextureAtlas(); } break; default: diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index abd0cb85a5..574a66e1b0 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -167,6 +167,12 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); + CCBone *armatureParentBone = _armature->getParentBone(); + if (armatureParentBone && !_boneTransformDirty) + { + _boneTransformDirty = armatureParentBone->isTransformDirty(); + } + if (_boneTransformDirty) { if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) @@ -184,6 +190,13 @@ void Bone::update(float delta) { _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); } + else + { + if (armatureParentBone) + { + _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + } + } } DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index b7d337e3a9..ae1ed19781 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -137,6 +137,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); + ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index afd6f5fc51..d1c66ddc3e 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -120,6 +120,7 @@ void Skin::setSkinData(const BaseData &var) setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); + updateArmatureTransform(); } const BaseData &Skin::getSkinData() const From cae9a3e54f0ceef46de85e5cafd516b3b8ef09b1 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 29 Oct 2013 17:31:35 +0800 Subject: [PATCH 274/557] issue #2771: add physics pump demo and fix bugs --- cocos/physics/CCPhysicsBody.cpp | 66 ++++- cocos/physics/CCPhysicsBody.h | 20 +- cocos/physics/CCPhysicsJoint.cpp | 43 ++++ cocos/physics/CCPhysicsJoint.h | 14 ++ cocos/physics/CCPhysicsShape.cpp | 15 ++ cocos/physics/CCPhysicsShape.h | 14 ++ cocos/physics/CCPhysicsWorld.cpp | 139 +++++++--- cocos/physics/CCPhysicsWorld.h | 12 +- cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp | 1 - cocos/physics/chipmunk/CCPhysicsBodyInfo.h | 7 +- cocos/physics/chipmunk/CCPhysicsContactInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsHelper.h | 6 +- cocos/physics/chipmunk/CCPhysicsJointInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsShapeInfo.h | 6 +- cocos/physics/chipmunk/CCPhysicsWorldInfo.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 237 ++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 29 ++- 17 files changed, 529 insertions(+), 98 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index e3335c7c16..a4393c4435 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -57,7 +57,6 @@ namespace { static const float MASS_DEFAULT = 1.0; static const float MOMENT_DEFAULT = 200; - static float GROUP_INDEX = 0; } PhysicsBody::PhysicsBody() @@ -81,6 +80,7 @@ PhysicsBody::PhysicsBody() , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) , _contactTestBitmask(0) +, _group(0) { } @@ -273,7 +273,6 @@ bool PhysicsBody::init() _shapes->retain(); _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); - _info->group = ++GROUP_INDEX; CC_BREAK_IF(_info->body == nullptr); @@ -321,10 +320,10 @@ void PhysicsBody::setGravityEnable(bool enable) { if (enable) { - applyForce(_world->getGravity()); + applyForce(_world->getGravity() * _mass); }else { - applyForce(-_world->getGravity()); + applyForce(-_world->getGravity() * _mass); } } } @@ -351,9 +350,9 @@ float PhysicsBody::getRotation() const return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->body) / 3.14f * 180.0f); } -void PhysicsBody::addShape(PhysicsShape* shape) +PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) { - if (shape == nullptr) return; + if (shape == nullptr) return nullptr; // add shape to body if (_shapes->getIndexOfObject(shape) == UINT_MAX) @@ -372,7 +371,14 @@ void PhysicsBody::addShape(PhysicsShape* shape) } _shapes->addObject(shape); + + if (_group != CP_NO_GROUP && shape->getGroup() == CP_NO_GROUP) + { + shape->setGroup(_group); + } } + + return shape; } void PhysicsBody::applyForce(Point force) @@ -676,6 +682,54 @@ void PhysicsBody::update(float delta) } } +void PhysicsBody::setCategoryBitmask(int bitmask) +{ + _categoryBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCategoryBitmask(bitmask); + } +} + +void PhysicsBody::setContactTestBitmask(int bitmask) +{ + _contactTestBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setContactTestBitmask(bitmask); + } +} + +void PhysicsBody::setCollisionBitmask(int bitmask) +{ + _collisionBitmask = bitmask; + + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setCollisionBitmask(bitmask); + } +} + +void PhysicsBody::setGroup(int group) +{ + for (auto shape : *_shapes) + { + ((PhysicsShape*)shape)->setGroup(group); + } +} + +Point PhysicsBody::world2Local(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->body, PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::local2World(const Point& point) +{ + return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); +} + //Clonable* PhysicsBody::clone() const //{ // PhysicsBody* body = new PhysicsBody(); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 7d569075f8..a82b7dc1d4 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -87,7 +87,7 @@ public: */ static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - virtual void addShape(PhysicsShape* shape); + virtual PhysicsShape* addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. @@ -154,13 +154,16 @@ public: */ inline Node* getOwner() const { return _owner; } - inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + void setCategoryBitmask(int bitmask); + void setContactTestBitmask(int bitmask); + void setCollisionBitmask(int bitmask); inline int getCategoryBitmask() const { return _categoryBitmask; } - inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } inline int getContactTestBitmask() const { return _contactTestBitmask; } - inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } inline int getCollisionBitmask() const { return _collisionBitmask; } + void setGroup(int group); + inline int getGroup() { return _group; } + /* * @brief get the body position. */ @@ -246,6 +249,8 @@ public: inline int getTag() { return _tag; } inline void setTag(int tag) { _tag = tag; } + Point world2Local(const Point& point); + Point local2World(const Point& point); protected: @@ -280,9 +285,10 @@ protected: float _angularDamping; int _tag; - int _categoryBitmask; - int _collisionBitmask; - int _contactTestBitmask; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsShape; diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 0abca9e9a4..1268ac2460 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -144,6 +144,16 @@ PhysicsJointLimit::~PhysicsJointLimit() } +PhysicsJointDistance::PhysicsJointDistance() +{ + +} + +PhysicsJointDistance::~PhysicsJointDistance() +{ + +} + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const { @@ -343,6 +353,39 @@ void PhysicsJointLimit::setMax(float max) cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); } +PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + PhysicsJointDistance* joint = new PhysicsJointDistance(); + + if (joint && joint->init(a, b, anchr1, anchr2)) + { + return joint; + } + + CC_SAFE_DELETE(joint); + return nullptr; +} + +bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +{ + do + { + CC_BREAK_IF(!PhysicsJoint::init(a, b)); + + cpConstraint* joint = cpPinJointNew(bodyInfo(a)->body, + bodyInfo(b)->body, + PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); + + CC_BREAK_IF(joint == nullptr); + + _info->add(joint); + + return true; + } while (false); + + return false; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index d6c0d5df15..298992c5f3 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -165,6 +165,20 @@ protected: virtual ~PhysicsJointPin(); }; +class PhysicsJointDistance : public PhysicsJoint +{ + +public: + static PhysicsJointDistance* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + +protected: + PhysicsJointDistance(); + virtual ~PhysicsJointDistance(); +}; + NS_CC_END #endif // __CCPHYSICS_JOINT_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 77634e9113..6b166da351 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -50,6 +50,10 @@ PhysicsShape::PhysicsShape() , _mass(0) , _moment(0) , _tag(0) +, _categoryBitmask(UINT_MAX) +, _collisionBitmask(UINT_MAX) +, _contactTestBitmask(0) +, _group(0) { } @@ -777,6 +781,17 @@ int PhysicsShapeEdgeChain::getPointsCount() return _info->shapes.size() + 1; } +void PhysicsShape::setGroup(int group) +{ + if (group < 0) + { + for (auto shape : _info->shapes) + { + cpShapeSetGroup(shape, (cpGroup)group); + } + } +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 02e6f604c0..8bc9224bf1 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -102,6 +102,16 @@ public: static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); static Point getPolyonCenter(Point* points, int count); + inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } + inline int getCategoryBitmask() const { return _categoryBitmask; } + inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } + inline int getContactTestBitmask() const { return _contactTestBitmask; } + inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } + inline int getCollisionBitmask() const { return _collisionBitmask; } + + void setGroup(int group); + inline int getGroup() { return _group; } + protected: bool init(Type type); @@ -125,6 +135,10 @@ protected: float _moment; PhysicsMaterial _material; int _tag; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsBody; diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index c01f9ac640..459261f896 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -181,9 +181,9 @@ bool PhysicsWorld::init() { _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); - _bodys = Array::create(); - CC_BREAK_IF(_bodys == nullptr); - _bodys->retain(); + _bodies = Array::create(); + CC_BREAK_IF(_bodies == nullptr); + _bodies->retain(); cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); @@ -253,7 +253,7 @@ void PhysicsWorld::removeAllJoints() _joints.clear(); } -void PhysicsWorld::addShape(PhysicsShape* shape) +PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) { @@ -270,9 +270,11 @@ void PhysicsWorld::addShape(PhysicsShape* shape) cpSpaceAddShape(_info->space, cps); } } + + return shape; } -void PhysicsWorld::addBody(PhysicsBody* body) +PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -304,7 +306,9 @@ void PhysicsWorld::addBody(PhysicsBody* body) } } - _bodys->addObject(body); + _bodies->addObject(body); + + return body; } void PhysicsWorld::removeBody(PhysicsBody* body) @@ -341,12 +345,12 @@ void PhysicsWorld::removeBody(PhysicsBody* body) } body->_world = nullptr; - _bodys->removeObject(body); + _bodies->removeObject(body); } void PhysicsWorld::removeBodyByTag(int tag) { - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == tag) @@ -357,9 +361,9 @@ void PhysicsWorld::removeBodyByTag(int tag) } } -void PhysicsWorld::removeAllBodys() +void PhysicsWorld::removeAllBodies() { - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); @@ -390,8 +394,8 @@ void PhysicsWorld::removeAllBodys() body->_world = nullptr; } - _bodys->removeAllObjects(); - CC_SAFE_RELEASE(_bodys); + _bodies->removeAllObjects(); + CC_SAFE_RELEASE(_bodies); } void PhysicsWorld::removeShape(PhysicsShape* shape) @@ -407,7 +411,7 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) void PhysicsWorld::update(float delta) { - for (auto body : *_bodys) + for (auto body : *_bodies) { body->update(delta); } @@ -428,11 +432,11 @@ void PhysicsWorld::update(float delta) void PhysicsWorld::debugDraw() { - if (_debugDraw && _bodys != nullptr) + if (_debugDraw && _bodies != nullptr) { _drawNode= DrawNode::create(); - for (Object* obj : *_bodys) + for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast(obj); @@ -442,6 +446,11 @@ void PhysicsWorld::debugDraw() } } + for (auto joint : _joints) + { + drawWithJoint(_drawNode, joint); + } + if (_scene) { _scene->addChild(_drawNode); @@ -454,6 +463,58 @@ void PhysicsWorld::setScene(Scene *scene) _scene = scene; } +void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) +{ + for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + { + cpConstraint *constraint = *it; + + + cpBody *body_a = constraint->a; + cpBody *body_b = constraint->b; + + const cpConstraintClass *klass = constraint->klass_private; + if(klass == cpPinJointGetClass()){ + cpPinJoint *joint = (cpPinJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpSlideJointGetClass()){ + cpSlideJoint *joint = (cpSlideJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpPivotJointGetClass()){ + cpPivotJoint *joint = (cpPivotJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); + cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpGrooveJointGetClass()){ + cpGrooveJoint *joint = (cpGrooveJoint *)constraint; + + cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot)); + cpVect b = cpvadd(body_a->p, cpvrotate(joint->grv_b, body_a->rot)); + cpVect c = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot)); + + node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); + node->drawDot(PhysicsHelper::cpv2point(c), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); + } else if(klass == cpDampedSpringGetClass()){ + + } + } +} + void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) { for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) @@ -510,8 +571,10 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; - PhysicsBody* bodyA = contact.getShapeA()->getBody(); - PhysicsBody* bodyB = contact.getShapeB()->getBody(); + PhysicsShape* shapeA = contact.getShapeA(); + PhysicsShape* shapeB = contact.getShapeB(); + PhysicsBody* bodyA = shapeA->getBody(); + PhysicsBody* bodyB = shapeB->getBody(); std::vector jointsA = bodyA->getJoints(); // check the joint is collision enable or not @@ -534,17 +597,24 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } + // bitmask check - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0 - || (bodyB->getContactTestBitmask() & bodyA->getCategoryBitmask()) == 0) + if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 + || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) { contact.setNotify(false); } - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0 - || (bodyB->getCategoryBitmask() & bodyA->getCollisionBitmask()) == 0) + if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) { - ret = false; + ret = shapeA->getGroup() > 0; + }else + { + if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 + || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) + { + ret = false; + } } if (contact.getNotify() && _listener && _listener->onContactBegin) @@ -614,9 +684,9 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) void PhysicsWorld::setGravity(Point gravity) { - if (_bodys != nullptr) + if (_bodies != nullptr) { - for (auto child : *_bodys) + for (auto child : *_bodies) { PhysicsBody* body = dynamic_cast(child); @@ -694,9 +764,22 @@ PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; } -Array* PhysicsWorld::getAllBody() const +Array* PhysicsWorld::getAllBodies() const { - return _bodys; + return _bodies; +} + +PhysicsBody* PhysicsWorld::getBodyByTag(int tag) +{ + for (auto body : *_bodies) + { + if (((PhysicsBody*)body)->getTag() == tag) + { + return (PhysicsBody*)body; + } + } + + return nullptr; } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) @@ -720,7 +803,7 @@ PhysicsWorld::PhysicsWorld() , _speed(1.0f) , _info(nullptr) , _listener(nullptr) -, _bodys(nullptr) +, _bodies(nullptr) , _scene(nullptr) , _debugDraw(false) , _drawNode(nullptr) @@ -730,7 +813,7 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { - removeAllBodys(); + removeAllBodies(); removeAllJoints(); CC_SAFE_DELETE(_info); } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 9fa8b28240..aff9119485 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -97,7 +97,8 @@ public: void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); Array* getShapesAtPoint(Point point); PhysicsShape* getShapeAtPoint(Point point); - Array* getAllBody() const; + Array* getAllBodies() const; + PhysicsBody* getBodyByTag(int tag); /** Register a listener to receive contact callbacks*/ inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } @@ -116,7 +117,7 @@ public: virtual void removeBody(PhysicsBody* body); virtual void removeBodyByTag(int tag); - virtual void removeAllBodys(); + virtual void removeAllBodies(); protected: static PhysicsWorld* create(); @@ -124,13 +125,14 @@ protected: void setScene(Scene* scene); - virtual void addBody(PhysicsBody* body); - virtual void addShape(PhysicsShape* shape); + virtual PhysicsBody* addBody(PhysicsBody* body); + virtual PhysicsShape* addShape(PhysicsShape* shape); virtual void removeShape(PhysicsShape* shape); virtual void update(float delta); virtual void debugDraw(); virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); + virtual void drawWithJoint(DrawNode* node, PhysicsJoint* joint); virtual int collisionBeginCallback(PhysicsContact& contact); @@ -145,7 +147,7 @@ protected: PhysicsContactListener* _listener; - Array* _bodys; + Array* _bodies; std::list _joints; Scene* _scene; diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp index 852dad1eeb..5fd8ceb171 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp @@ -28,7 +28,6 @@ NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() : body(nullptr) -, group(CP_NO_GROUP) { } diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h index ec84526b59..54e4313b38 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" @@ -37,7 +37,6 @@ class PhysicsBodyInfo : public Clonable { public: cpBody* body; - cpGroup group; private: PhysicsBodyInfo(); diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo.h index 6c302947b7..fb455cdfc5 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper.h index bf6f6d14db..8ad6fa29bd 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_HELPER_H__ #define __CCPHYSICS_HELPER_H__ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo.h index 04a2c716bf..5033e4aaba 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h index 83be655b02..9229ba6d7f 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_SHAPE_INFO_H__ #define __CCPHYSICS_SHAPE_INFO_H__ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #include #include #include "chipmunk.h" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h index 71d56f0a5b..8c60cde415 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ + +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 51d5d3252c..ae7f7d07a4 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -11,6 +11,8 @@ namespace CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), CL(PhysicsDemoJoints), + CL(PhysicsDemoActions), + CL(PhysicsDemoPump), }; static int sceneIdx=-1; @@ -52,7 +54,7 @@ namespace } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); - static const int DRAG_BODYS_TAG = 100; + static const int DRAG_BODYS_TAG = 0x80; } @@ -314,7 +316,7 @@ namespace } } -Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBall(Point point, float radius, PhysicsMaterial material) { Sprite* ball = nullptr; if (_ball != nullptr) @@ -329,12 +331,12 @@ Sprite* PhysicsDemo::makeBall(float x, float y, float radius, PhysicsMaterial ma auto body = PhysicsBody::createCircle(radius, material); ball->setPhysicsBody(body); - ball->setPosition(Point(x, y)); + ball->setPosition(Point(point.x, point.y)); return ball; } -Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeBox(Point point, Size size, PhysicsMaterial material) { auto box = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowSquare.png") : Sprite::create("Images/CyanSquare.png"); @@ -343,12 +345,12 @@ Sprite* PhysicsDemo::makeBox(float x, float y, Size size, PhysicsMaterial materi auto body = PhysicsBody::createBox(size); box->setPhysicsBody(body); - box->setPosition(Point(x, y)); + box->setPosition(Point(point.x, point.y)); return box; } -Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial material) +Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial material) { auto triangle = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowTriangle.png") : Sprite::create("Images/CyanTriangle.png"); @@ -365,7 +367,7 @@ Sprite* PhysicsDemo::makeTriangle(float x, float y, Size size, PhysicsMaterial m auto body = PhysicsBody::createPolygon(vers, 3); triangle->setPhysicsBody(body); - triangle->setPosition(Point(x, y)); + triangle->setPosition(Point(point.x, point.y)); return triangle; } @@ -380,7 +382,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { shape = dynamic_cast(obj); - if (shape->getTag() == DRAG_BODYS_TAG) + if ((shape->getTag() & DRAG_BODYS_TAG) != 0) { break; } @@ -395,7 +397,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->setPosition(location); this->addChild(mouse); PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); - joint->setMaxForce(5000.0f); + joint->setMaxForce(5000.0f * shape->getBody()->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -445,9 +447,9 @@ void PhysicsDemoLogoSmash::onEnter() float x_jitter = 0.05*frand(); float y_jitter = 0.05*frand(); - Node* ball = makeBall(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, - 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2, - 0.95f, PhysicsMaterial(1.0f, 0.0f, 0.0f)); + Node* ball = makeBall(Point(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, + 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2), + 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); @@ -459,7 +461,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(400, 0, 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -727,13 +729,13 @@ void PhysicsDemoRayCast::onTouchesEnded(const std::vector& touches, Even if (r < 1.0f/3.0f) { - addChild(makeBall(location.x, location.y, 5 + CCRANDOM_0_1()*10)); + addChild(makeBall(location, 5 + CCRANDOM_0_1()*10)); }else if(r < 2.0f/3.0f) { - addChild(makeBox(location.x, location.y, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); + addChild(makeBox(location, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); }else { - addChild(makeTriangle(location.x, location.y, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); + addChild(makeTriangle(location, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); } } } @@ -743,12 +745,6 @@ std::string PhysicsDemoRayCast::title() return "Ray Cast"; } - -PhysicsDemoJoints::PhysicsDemoJoints() -{ - -} - void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); @@ -780,9 +776,9 @@ void PhysicsDemoJoints::onEnter() { case 0: { - auto sp1 = makeBall(offset.x - 30, offset.y, 10); + auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - auto sp2 = makeBall(offset.x + 30, offset.y, 10); + auto sp2 = makeBall(offset + Point(30, 0), 10); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); @@ -795,9 +791,9 @@ void PhysicsDemoJoints::onEnter() case 1: { - auto sp1 = makeBall(offset.x - 30, offset.y, 10); + auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - auto sp2 = makeBox(offset.x + 30, offset.y, Size(30, 10)); + auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); @@ -817,4 +813,193 @@ void PhysicsDemoJoints::onEnter() std::string PhysicsDemoJoints::title() { return "Joints"; +} + +void PhysicsDemoActions::onEnter() +{ + PhysicsDemo::onEnter(); + + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + + auto node = Node::create(); + node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + node->setPosition(VisibleRect::center()); + this->addChild(node); + + Sprite* sp1 = addGrossiniAtPosition(VisibleRect::center()); + Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Point(50, 0)); + Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Point(20, 0)); + Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Point(50, -50)); + sp4->getPhysicsBody()->setGravityEnable(false); + + + auto actionTo = JumpTo::create(2, Point(100,100), 50, 4); + auto actionBy = JumpBy::create(2, Point(300,0), 50, 4); + auto actionUp = JumpBy::create(2, Point(0,50), 80, 4); + auto actionByBack = actionBy->reverse(); + + sp1->runAction(RepeatForever::create(actionUp)); + sp2->runAction(RepeatForever::create(Sequence::create(actionBy, actionByBack, NULL))); + sp3->runAction(actionTo); + sp4->runAction(RepeatForever::create(Sequence::create(actionBy->clone(), actionByBack->clone(), NULL))); +} + +std::string PhysicsDemoActions::title() +{ + return "Actions"; +} + +void PhysicsDemoPump::onEnter() +{ + PhysicsDemo::onEnter(); + + _distance = 0.0f; + _rotationV = 0.0f; + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + scheduleUpdate(); + + auto node = Node::create(); + auto body = PhysicsBody::create(); + body->setDynamic(false); + + PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, -130), VisibleRect::leftTop() + Point(100, -145), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -145), VisibleRect::leftBottom() + Point(100, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::leftBottom() + Point(150, 80), staticMaterial, 2.0f)); + body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::rightTop() + Point(-100, -150), staticMaterial, 2.0f)); + + body->setCategoryBitmask(0x01); + + // balls + for (int i = 0; i < 6; ++i) + { + auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.5f, 0.0f, 0.1f)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(ball); + } + + node->setPhysicsBody(body); + this->addChild(node); + + Point vec[4] = + { + VisibleRect::leftTop() + Point(102, -146), + VisibleRect::leftTop() + Point(148, -159), + VisibleRect::leftBottom() + Point(148, 20), + VisibleRect::leftBottom() + Point(102, 20) + }; + + auto _world = _scene->getPhysicsWorld(); + + // small gear + auto sgear = Node::create(); + auto sgearB = PhysicsBody::createCircle(50); + sgear->setPhysicsBody(sgearB); + sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); + this->addChild(sgear); + sgearB->setCategoryBitmask(0x04); + sgearB->setCollisionBitmask(0x04); + sgearB->setTag(1); + _world->addJoint(PhysicsJointPin::create(body, sgearB, sgearB->getPosition())); + + + // big gear + auto bgear = Node::create(); + auto bgearB = PhysicsBody::createCircle(100); + bgear->setPhysicsBody(bgearB); + bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); + this->addChild(bgear); + bgearB->setCategoryBitmask(0x04); + _world->addJoint(PhysicsJointPin::create(body, bgearB, bgearB->getPosition())); + + + // pump + auto pump = Node::create(); + pump->setPosition(PhysicsShape::getPolyonCenter(vec, 4)); + auto pumpB = PhysicsBody::createPolygon(PhysicsShape::recenterPoints(vec, 4), 4); + pump->setPhysicsBody(pumpB); + this->addChild(pump); + pumpB->setCategoryBitmask(0x02); + pumpB->setGravityEnable(false); + _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -50))); + + // plugger + Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; + Point segCenter = (seg[1] + seg[0])/2; + seg[1] -= segCenter; + seg[0] -= segCenter; + auto plugger = Node::create(); + auto pluggerB = PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20); + pluggerB->setDynamic(true); + pluggerB->setMass(30); + pluggerB->setMoment(100000); + plugger->setPhysicsBody(pluggerB); + plugger->setPosition(segCenter); + this->addChild(plugger); + pluggerB->setCategoryBitmask(0x02); + sgearB->setCollisionBitmask(0x04 | 0x01); + _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); + _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(50, 0))); +} + +void PhysicsDemoPump::update(float delta) +{ + for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) + { + body->getOwner()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); + body->setVelocity(Point(0, 0)); + } + } + + PhysicsBody* gear = _scene->getPhysicsWorld()->getBodyByTag(1); + + if (gear != nullptr) + { + if (_distance != 0.0f) + { + _rotationV += _distance/2500.0f; + + if (_rotationV > 30) _rotationV = 30.0f; + if (_rotationV < -30) _rotationV = -30.0f; + } + + gear->setAngularVelocity(_rotationV); + _rotationV *= 0.995; + } +} + +bool PhysicsDemoPump::onTouchBegan(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchBegan(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; + + return true; +} + +void PhysicsDemoPump::onTouchMoved(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchMoved(touch, event); + + _distance = touch->getLocation().x - VisibleRect::center().x; +} + +void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) +{ + PhysicsDemo::onTouchEnded(touch, event); + + _distance = 0; +} + +std::string PhysicsDemoPump::title() +{ + return "Pump"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index fe58196372..79932c60a7 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -39,9 +39,9 @@ public: void toggleDebugCallback(Object* sender); Sprite* addGrossiniAtPosition(Point p, float scale = 1.0); - Sprite* makeBall(float x, float y, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - Sprite* makeBox(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - Sprite* makeTriangle(float x, float y, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBall(Point point, float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeBox(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + Sprite* makeTriangle(Point point, Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); bool onTouchBegan(Touch* touch, Event* event) override; void onTouchMoved(Touch* touch, Event* event) override; @@ -107,14 +107,31 @@ private: class PhysicsDemoJoints : public PhysicsDemo { public: - PhysicsDemoJoints(); - + void onEnter() override; + std::string title() override; +}; + +class PhysicsDemoActions : public PhysicsDemo +{ public: void onEnter() override; std::string title() override; +}; + +class PhysicsDemoPump : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + void update(float delta) override; + + bool onTouchBegan(Touch* touch, Event* event) override; + void onTouchMoved(Touch* touch, Event* event) override; + void onTouchEnded(Touch* touch, Event* event) override; private: - PhysicsShape* _touchesShape; + float _distance; + float _rotationV; }; #endif From 70082ddc297d69beb33333c130dfbaaa784759c3 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Tue, 29 Oct 2013 17:54:35 +0800 Subject: [PATCH 275/557] issue #3409:Add XMLHttpRequest lua binding and corresponding test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/network/HttpRequest.h | 5 +- cocos/scripting/lua/bindings/Android.mk | 1 + cocos/scripting/lua/bindings/Makefile | 3 +- cocos/scripting/lua/bindings/liblua.vcxproj | 2 + .../lua/bindings/liblua.vcxproj.filters | 6 +++ samples/Lua/TestLua/proj.android/.project | 52 ++----------------- .../TestLua/proj.android/project.properties | 2 +- .../TestLua/proj.win32/TestLua.win32.vcxproj | 2 +- 9 files changed, 22 insertions(+), 53 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 17e0cee1da..e5e294b55f 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b695026fc3d856d540590ff09112696f66379c22 \ No newline at end of file +51e880f9a11e50fd1bd14a92c4bcf1004dfbc12b \ No newline at end of file diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 81715d7991..141b55df29 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -123,7 +123,10 @@ public: /** Get the request data pointer back */ inline char* getRequestData() { - return &(_requestData.front()); + if(_requestData.size() != 0) + return &(_requestData.front()); + + return nullptr; } /** Get the size of request data back */ inline int getRequestDataSize() diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index a5293f66a2..b39ee5f6a5 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -20,6 +20,7 @@ LOCAL_SRC_FILES := CCLuaBridge.cpp \ lua_cocos2dx_manual.cpp \ lua_cocos2dx_extension_manual.cpp \ lua_cocos2dx_deprecated.cpp \ + lua_xml_http_request.cpp \ platform/android/CCLuaJavaBridge.cpp \ platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxLuaJavaBridge.cpp \ ../../../../external/lua/tolua/tolua_event.c \ diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile index 95145d5fbc..c797ce3b9e 100644 --- a/cocos/scripting/lua/bindings/Makefile +++ b/cocos/scripting/lua/bindings/Makefile @@ -60,7 +60,8 @@ SOURCES = ../../../../external/lua/lua/lapi.c \ LuaBasicConversions.cpp \ lua_cocos2dx_manual.cpp \ lua_cocos2dx_extension_manual.cpp \ - lua_cocos2dx_deprecated.cpp + lua_cocos2dx_deprecated.cpp \ + lua_xml_http_request.cpp include ../../../2d/cocos2dx.mk diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj b/cocos/scripting/lua/bindings/liblua.vcxproj index ed1ef534ed..1f6f39d5c8 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj +++ b/cocos/scripting/lua/bindings/liblua.vcxproj @@ -144,6 +144,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$ + @@ -168,6 +169,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$ + diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj.filters b/cocos/scripting/lua/bindings/liblua.vcxproj.filters index 56f49872c4..d323cdf804 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj.filters +++ b/cocos/scripting/lua/bindings/liblua.vcxproj.filters @@ -81,6 +81,9 @@ cocos2dx_support + + cocos2dx_support + @@ -149,6 +152,9 @@ cocos2dx_support + + cocos2dx_support + diff --git a/samples/Lua/TestLua/proj.android/.project b/samples/Lua/TestLua/proj.android/.project index 3c1261c623..8703060095 100644 --- a/samples/Lua/TestLua/proj.android/.project +++ b/samples/Lua/TestLua/proj.android/.project @@ -6,56 +6,12 @@ - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, + org.eclipse.ui.externaltools.ExternalToolBuilder + full,incremental, - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.buildArguments - ${ProjDirPath}/build_native.sh - - - org.eclipse.cdt.make.core.buildCommand - bash - - - org.eclipse.cdt.make.core.buildLocation - ${ProjDirPath} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - false + LaunchConfigHandle + <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch diff --git a/samples/Lua/TestLua/proj.android/project.properties b/samples/Lua/TestLua/proj.android/project.properties index 0a6dc6664d..94dd07f59d 100644 --- a/samples/Lua/TestLua/proj.android/project.properties +++ b/samples/Lua/TestLua/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-10 +target=android-15 android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj index 0a4ea9edbd..f70904ac2f 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj @@ -84,7 +84,7 @@ MachineX86 true $(OutDir);%(AdditionalLibraryDirectories) - lua51.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) 0x0409 From 663b27d1e76afc89a92ef0b04991430f22c40618 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Tue, 29 Oct 2013 18:06:02 +0800 Subject: [PATCH 276/557] #3049:Add XMLHttpRequest lua binding and corresponding test sample --- cocos/network/HttpRequest.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 141b55df29..4282193043 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -123,8 +123,8 @@ public: /** Get the request data pointer back */ inline char* getRequestData() { - if(_requestData.size() != 0) - return &(_requestData.front()); + if(_requestData.size() != 0) + return &(_requestData.front()); return nullptr; } From 471bbb8af95e7a2879bcd8dc1f41892927572984 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Tue, 29 Oct 2013 18:21:15 +0800 Subject: [PATCH 277/557] issue #3049:Add XMLHttpRequest lua binding and corresponding test sample --- cocos/scripting/lua/bindings/lua_xml_http_request.cpp | 4 ---- samples/Lua/TestLua/proj.android/project.properties | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp index f63e55c0b1..945b36a16a 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp @@ -209,10 +209,6 @@ void LuaMinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, n /** get the response data **/ std::vector *buffer = response->getResponseData(); -// for (unsigned int i = 0; i < buffer->size(); i++) -// { -// printf("%c", (*buffer)[i]); -// } char* concatenated = (char*) malloc(buffer->size() + 1); std::string s2(buffer->begin(), buffer->end()); strcpy(concatenated, s2.c_str()); diff --git a/samples/Lua/TestLua/proj.android/project.properties b/samples/Lua/TestLua/proj.android/project.properties index 94dd07f59d..0a6dc6664d 100644 --- a/samples/Lua/TestLua/proj.android/project.properties +++ b/samples/Lua/TestLua/proj.android/project.properties @@ -8,6 +8,6 @@ # project structure. # Project target. -target=android-15 +target=android-10 android.library.reference.1=../../../../cocos/2d/platform/android/java From 8fa8b9f844ac723f1d9a38699f1d62206c1f8ced Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 09:41:40 +0800 Subject: [PATCH 278/557] update develop --- .../editor-support/cocostudio/CCArmature.cpp | 52 +++- cocos/editor-support/cocostudio/CCArmature.h | 6 +- .../cocostudio/CCArmatureAnimation.cpp | 57 +++- .../cocostudio/CCArmatureAnimation.h | 37 ++- .../cocostudio/CCArmatureDataManager.cpp | 4 +- .../cocostudio/CCArmatureDefine.cpp | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 83 ++++++ cocos/editor-support/cocostudio/CCBatchNode.h | 8 +- cocos/editor-support/cocostudio/CCBone.cpp | 95 ++++-- cocos/editor-support/cocostudio/CCBone.h | 21 +- .../cocostudio/CCColliderDetector.cpp | 10 +- .../cocostudio/CCDataReaderHelper.cpp | 107 +++++-- .../cocostudio/CCDataReaderHelper.h | 24 +- .../cocostudio/CCDisplayFactory.cpp | 51 ++-- .../cocostudio/CCDisplayFactory.h | 7 +- .../cocostudio/CCDisplayManager.cpp | 20 +- .../cocostudio/CCDisplayManager.h | 3 + .../cocostudio/CCProcessBase.cpp | 12 +- .../editor-support/cocostudio/CCProcessBase.h | 3 +- cocos/editor-support/cocostudio/CCSkin.cpp | 61 ++-- cocos/editor-support/cocostudio/CCSkin.h | 3 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 14 - .../cocostudio/CCSpriteFrameCacheHelper.h | 4 - .../cocostudio/CCTransformHelp.cpp | 21 +- cocos/editor-support/cocostudio/CCTween.cpp | 63 ++-- cocos/editor-support/cocostudio/CCTween.h | 13 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 276 +++++++++++++++++- .../CocoStudioArmatureTest/ArmatureScene.h | 54 +++- 28 files changed, 907 insertions(+), 204 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index ca935722c8..ac04de1af5 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -86,6 +86,7 @@ Armature::Armature() , _boneDic(NULL) , _topBoneList(NULL) , _animation(NULL) + , _textureAtlasDic(NULL) { } @@ -103,6 +104,7 @@ Armature::~Armature(void) CC_SAFE_DELETE(_topBoneList); } CC_SAFE_DELETE(_animation); + CC_SAFE_RELEASE_NULL(_textureAtlasDic); } @@ -130,6 +132,8 @@ bool Armature::init(const char *name) _topBoneList = new Array(); _topBoneList->init(); + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); _blendFunc.src = CC_BLEND_SRC; _blendFunc.dst = CC_BLEND_DST; @@ -458,7 +462,7 @@ void Armature::update(float dt) void Armature::draw() { - if (_parentBone == NULL) + if (_parentBone == NULL && _batchNode == NULL) { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); @@ -469,13 +473,12 @@ void Armature::draw() { if (Bone *bone = dynamic_cast(object)) { - DisplayManager *displayManager = bone->getDisplayManager(); - Node *node = displayManager->getDisplayRenderNode(); + Node *node = bone->getDisplayRenderNode(); if (NULL == node) continue; - switch (displayManager->getCurrentDecorativeDisplay()->getDisplayData()->displayType) + switch (bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: { @@ -667,7 +670,7 @@ Rect Armature::getBoundingBox() const } } - return boundingBox; + return RectApplyAffineTransform(boundingBox, getNodeToParentTransform()); } Bone *Armature::getBoneAtPoint(float x, float y) @@ -686,6 +689,45 @@ Bone *Armature::getBoneAtPoint(float x, float y) return NULL; } +TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) +{ + int key = texture->getName(); + + if (_parentBone && _parentBone->getArmature()) + { + return _parentBone->getArmature()->getTexureAtlasWithTexture(texture); + } + else if (_batchNode) + { + _batchNode->getTexureAtlasWithTexture(texture); + } + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == NULL) + { + atlas = TextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + +void Armature::setParentBone(Bone *parentBone) +{ + _parentBone = parentBone; + + DictElement *element = NULL; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setArmature(this); + } +} + +Bone *Armature::getParentBone() +{ + return _parentBone; +} + #if ENABLE_PHYSICS_BOX2D_DETECT b2Body *Armature::getBody() { diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 3e8c521011..15abe96079 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -173,6 +173,8 @@ public: virtual bool getArmatureTransformDirty(); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT @@ -197,7 +199,7 @@ protected: CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); - CC_SYNTHESIZE(Bone *, _parentBone, ParentBone); + CC_PROPERTY(Bone *, _parentBone, ParentBone); CC_SYNTHESIZE(float, _version, Version); @@ -214,6 +216,8 @@ protected: ArmatureAnimation *_animation; + cocos2d::Dictionary *_textureAtlasDic; + #if ENABLE_PHYSICS_BOX2D_DETECT CC_PROPERTY(b2Body *, _body, Body); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index a026fc33c9..ed6e383751 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -54,6 +54,8 @@ ArmatureAnimation::ArmatureAnimation() , _armature(NULL) , _movementID("") , _toIndex(0) + , _tweenList(NULL) + , _ignoreFrameEvent(false) , _movementEventCallFunc(NULL) , _frameEventCallFunc(NULL) @@ -268,6 +270,8 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } } + + _armature->update(0); } @@ -280,7 +284,40 @@ void ArmatureAnimation::playByIndex(int animationIndex, int durationTo, int dura play(animationName.c_str(), durationTo, durationTween, loop, tweenEasing); } +void ArmatureAnimation::gotoAndPlay(int frameIndex) +{ + if (!_movementData || frameIndex < 0 || frameIndex >= _movementData->duration) + { + CCLOG("Please ensure you have played a movement, and the frameIndex is in the range."); + return; + } + bool ignoreFrameEvent = _ignoreFrameEvent; + _ignoreFrameEvent = true; + + _isPlaying = true; + _isComplete = _isPause = false; + + ProcessBase::gotoFrame(frameIndex); + _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; + _currentFrame = _nextFrameIndex * _currentPercent; + + Object *object = NULL; + CCARRAY_FOREACH(_tweenList, object) + { + static_cast(object)->gotoAndPlay(frameIndex); + } + + _armature->update(0); + + _ignoreFrameEvent = ignoreFrameEvent; +} + +void ArmatureAnimation::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} int ArmatureAnimation::getMovementCount() { @@ -295,6 +332,18 @@ void ArmatureAnimation::update(float dt) { static_cast(object)->update(dt); } + + while (_frameEventQueue.size() > 0) + { + FrameEvent *frameEvent = _frameEventQueue.front(); + _frameEventQueue.pop(); + + _ignoreFrameEvent = true; + (_frameEventTarget->*_frameEventCallFunc)(frameEvent->bone, frameEvent->frameEventName, frameEvent->originFrameIndex, frameEvent->currentFrameIndex); + _ignoreFrameEvent = false; + + CC_SAFE_DELETE(frameEvent); + } } void ArmatureAnimation::updateHandler() @@ -402,7 +451,13 @@ void ArmatureAnimation::frameEvent(Bone *bone, const char *frameEventName, int o { if (_frameEventTarget && _frameEventCallFunc) { - (_frameEventTarget->*_frameEventCallFunc)(bone, frameEventName, originFrameIndex, currentFrameIndex); + FrameEvent *frameEvent = new FrameEvent(); + frameEvent->bone = bone; + frameEvent->frameEventName = frameEventName; + frameEvent->originFrameIndex = originFrameIndex; + frameEvent->currentFrameIndex = currentFrameIndex; + + _frameEventQueue.push(frameEvent); } } } diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 9551f97ff9..5fe23543bf 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -27,6 +27,7 @@ THE SOFTWARE. #define __CCANIMATION_H__ #include "cocostudio/CCProcessBase.h" +#include namespace cocostudio { @@ -48,6 +49,13 @@ typedef void (cocos2d::Object::*SEL_FrameEventCallFunc)(Bone *, const char *, in #define movementEvent_selector(_SELECTOR) (cocostudio::SEL_MovementEventCallFunc)(&_SELECTOR) #define frameEvent_selector(_SELECTOR) (cocostudio::SEL_FrameEventCallFunc)(&_SELECTOR) +struct FrameEvent +{ + Bone *bone; + const char *frameEventName; + int originFrameIndex; + int currentFrameIndex; +}; class ArmatureAnimation : public ProcessBase { @@ -76,10 +84,11 @@ public: /** * Scale animation play speed. + * This method is deprecated, please use setSpeedScale. * @param animationScale Scale value */ - virtual void setAnimationScale(float animationScale); - virtual float getAnimationScale() const; + CC_DEPRECATED_ATTRIBUTE virtual void setAnimationScale(float animationScale); + CC_DEPRECATED_ATTRIBUTE virtual float getAnimationScale() const; /** * Scale animation play speed. @@ -123,10 +132,27 @@ public: /** * Play animation by index, the other param is the same to play. - * @param _animationIndex the animation index you want to play + * @param animationIndex the animation index you want to play */ void playByIndex(int animationIndex, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + /** + * Go to specified frame and play current movement. + * You need first switch to the movement you want to play, then call this function. + * + * example : playByIndex(0); + * gotoAndPlay(0); + * playByIndex(1); + * gotoAndPlay(0); + * gotoAndPlay(15); + */ + virtual void gotoAndPlay(int frameIndex); + + /** + * Go to specified frame and pause current movement. + */ + virtual void gotoAndPause(int frameIndex); + /** * Pause the Process */ @@ -183,6 +209,8 @@ protected: */ void frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + inline bool isIgnoreFrameEvent() { return _ignoreFrameEvent; } + friend class Tween; protected: //! AnimationData save all MovementDatas this animation used. @@ -201,6 +229,9 @@ protected: cocos2d::Array *_tweenList; + bool _ignoreFrameEvent; + + std::queue _frameEventQueue; protected: /** * MovementEvent CallFunc. diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 113ff33202..13ca184768 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -186,7 +186,7 @@ void ArmatureDataManager::addArmatureFileInfo(const char *configFilePath) void ArmatureDataManager::addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector) { _autoLoadSpriteFile = true; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath) @@ -199,7 +199,7 @@ void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char void ArmatureDataManager::addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector) { _autoLoadSpriteFile = false; - DataReaderHelper::getInstance()->addDataFromFileAsync(configFilePath, target, selector); + DataReaderHelper::getInstance()->addDataFromFileAsync(imagePath, plistPath, configFilePath, target, selector); addSpriteFrameFromFile(plistPath, imagePath); } diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp index 3672943778..4f48e0024e 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.cpp @@ -28,7 +28,7 @@ namespace cocostudio { const char *armatureVersion() { - return "0.4.0.0"; + return "1.0.0.0"; } } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 7ef2188fb8..bb84576d66 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -25,6 +25,7 @@ THE SOFTWARE. #include "cocostudio/CCBatchNode.h" #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmature.h" +#include "cocostudio/CCSkin.h" using namespace cocos2d; @@ -44,16 +45,36 @@ BatchNode *BatchNode::create() BatchNode::BatchNode() : _atlas(NULL) + , _textureAtlasDic(NULL) { } +BatchNode::~BatchNode() +{ + CC_SAFE_RELEASE_NULL(_textureAtlasDic); +} + bool BatchNode::init() { bool ret = Node::init(); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + + CC_SAFE_DELETE(_textureAtlasDic); + _textureAtlasDic = new Dictionary(); + return ret; } +void BatchNode::addChild(Node *pChild) +{ + Node::addChild(pChild); +} + +void BatchNode::addChild(Node *child, int zOrder) +{ + Node::addChild(child, zOrder); +} + void BatchNode::addChild(Node *child, int zOrder, int tag) { Node::addChild(child, zOrder, tag); @@ -61,9 +82,58 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) if (armature != NULL) { armature->setBatchNode(this); + + Dictionary *dict = armature->getBoneDic(); + DictElement *element = NULL; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(displayList, object) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(getTexureAtlasWithTexture(skin->getTexture())); + } + } + } } } +void BatchNode::removeChild(Node* child, bool cleanup) +{ + Armature *armature = dynamic_cast(child); + if (armature != NULL) + { + armature->setBatchNode(NULL); + + Dictionary *dict = armature->getBoneDic(); + DictElement *element = NULL; + CCDICT_FOREACH(dict, element) + { + Bone *bone = static_cast(element->getObject()); + + Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(displayList, object) + { + DecorativeDisplay *display = static_cast(object); + + if (Skin *skin = dynamic_cast(display->getDisplay())) + { + skin->setTextureAtlas(armature->getTexureAtlasWithTexture(skin->getTexture())); + } + } + } + } + + Node::removeChild(child, cleanup); +} + void BatchNode::visit() { // quick return if not visible. children won't be drawn. @@ -118,4 +188,17 @@ void BatchNode::draw() } } +TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) +{ + int key = texture->getName(); + + TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); + if (atlas == NULL) + { + atlas = CCTextureAtlas::createWithTexture(texture, 4); + _textureAtlasDic->setObject(atlas, key); + } + return atlas; +} + } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index df33e44e0b..44f10872c2 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -38,14 +38,20 @@ public: * @js ctor */ BatchNode(); + ~BatchNode(); virtual bool init(); - virtual void addChild(cocos2d::Node *child, int zOrder, int tag); + virtual void addChild(cocos2d::Node *pChild); + virtual void addChild(cocos2d::Node *pChild, int zOrder); + virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag); + virtual void removeChild(cocos2d::Node* child, bool cleanup); virtual void visit(); void draw(); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); protected: cocos2d::TextureAtlas *_atlas; + cocos2d::Dictionary *_textureAtlasDic; }; } diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 574a66e1b0..804ea5d65a 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -75,6 +75,10 @@ Bone::Bone() _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); _boneTransformDirty = true; _blendType = BLEND_NORMAL; + _worldInfo = NULL; + + _armatureParentBone = NULL; + _dataVersion = 0; } @@ -84,6 +88,7 @@ Bone::~Bone(void) CC_SAFE_DELETE(_children); CC_SAFE_DELETE(_tween); CC_SAFE_DELETE(_displayManager); + CC_SAFE_DELETE(_worldInfo); if(_boneData) { @@ -121,6 +126,8 @@ bool Bone::init(const char *name) _displayManager = new DisplayManager(); _displayManager->init(this); + CC_SAFE_DELETE(_worldInfo); + _worldInfo = new BaseData(); bRet = true; } @@ -153,6 +160,12 @@ void Bone::setArmature(Armature *armature) if (_armature) { _tween->setAnimation(_armature->getAnimation()); + _dataVersion = _armature->getArmatureData()->dataVersion; + _armatureParentBone = _armature->getParentBone(); + } + else + { + _armatureParentBone = NULL; } } @@ -167,39 +180,50 @@ void Bone::update(float delta) if (_parentBone) _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); - CCBone *armatureParentBone = _armature->getParentBone(); - if (armatureParentBone && !_boneTransformDirty) + if (_armatureParentBone && !_boneTransformDirty) { - _boneTransformDirty = armatureParentBone->isTransformDirty(); + _boneTransformDirty = _armatureParentBone->isTransformDirty(); } if (_boneTransformDirty) { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { TransformHelp::nodeConcat(*_tweenData, *_boneData); _tweenData->scaleX -= 1; _tweenData->scaleY -= 1; } - TransformHelp::nodeToMatrix(*_tweenData, _worldTransform); + _worldInfo->copy(_tweenData); - _worldTransform = AffineTransformConcat(getNodeToParentTransform(), _worldTransform); + _worldInfo->x = _tweenData->x + _position.x; + _worldInfo->y = _tweenData->y + _position.y; + _worldInfo->scaleX = _tweenData->scaleX * _scaleX; + _worldInfo->scaleY = _tweenData->scaleY * _scaleY; + _worldInfo->skewX = _tweenData->skewX + _skewX + _rotationX; + _worldInfo->skewY = _tweenData->skewY + _skewY - _rotationY; if(_parentBone) { - _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); + applyParentTransform(_parentBone); } else { - if (armatureParentBone) + if (_armatureParentBone) { - _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); + applyParentTransform(_armatureParentBone); } } + + TransformHelp::nodeToMatrix(*_worldInfo, _worldTransform); + + if (_armatureParentBone) + { + _worldTransform = AffineTransformConcat(_worldTransform, _armature->getNodeToParentTransform()); + } } - DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); + DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); Object *object = NULL; CCARRAY_FOREACH(_children, object) @@ -211,6 +235,18 @@ void Bone::update(float delta) _boneTransformDirty = false; } +void Bone::applyParentTransform(Bone *parent) +{ + float x = _worldInfo->x; + float y = _worldInfo->y; + _worldInfo->x = x * parent->_worldTransform.a + y * parent->_worldTransform.c + parent->_worldInfo->x; + _worldInfo->y = x * parent->_worldTransform.b + y * parent->_worldTransform.d + parent->_worldInfo->y; + _worldInfo->scaleX = _worldInfo->scaleX * parent->_worldInfo->scaleX; + _worldInfo->scaleY = _worldInfo->scaleY * parent->_worldInfo->scaleY; + _worldInfo->skewX = _worldInfo->skewX + parent->_worldInfo->skewX; + _worldInfo->skewY = _worldInfo->skewY + parent->_worldInfo->skewY; +} + void Bone::updateDisplayedColor(const Color3B &parentColor) { @@ -226,6 +262,18 @@ void Bone::updateDisplayedOpacity(GLubyte parentOpacity) updateColor(); } +void Bone::setColor(const Color3B& color) +{ + NodeRGBA::setColor(color); + updateColor(); +} + +void Bone::setOpacity(GLubyte opacity) +{ + NodeRGBA::setOpacity(opacity); + updateColor(); +} + void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); @@ -239,7 +287,7 @@ void Bone::updateColor() void Bone::updateZOrder() { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) + if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; setZOrder(zorder); @@ -313,6 +361,11 @@ void Bone::setChildArmature(Armature *armature) { if (_childArmature != armature) { + if (armature == NULL && _childArmature) + { + _childArmature->setParentBone(NULL); + } + CC_SAFE_RETAIN(armature); CC_SAFE_RELEASE(_childArmature); _childArmature = armature; @@ -335,16 +388,6 @@ void Bone::setZOrder(int zOrder) Node::setZOrder(zOrder); } -void Bone::setTransformDirty(bool dirty) -{ - _boneTransformDirty = dirty; -} - -bool Bone::isTransformDirty() -{ - return _boneTransformDirty; -} - AffineTransform Bone::getNodeToArmatureTransform() const { return _worldTransform; @@ -360,6 +403,11 @@ Node *Bone::getDisplayRenderNode() return _displayManager->getDisplayRenderNode(); } +DisplayType Bone::getDisplayRenderNodeType() +{ + return _displayManager->getDisplayRenderNodeType(); +} + void Bone::addDisplay(DisplayData *displayData, int index) { _displayManager->addDisplay(displayData, index); @@ -370,6 +418,11 @@ void Bone::addDisplay(Node *display, int index) _displayManager->addDisplay(display, index); } +void Bone::removeDisplay(int index) +{ + _displayManager->removeDisplay(index); +} + void Bone::changeDisplayByIndex(int index, bool force) { _displayManager->changeDisplayByIndex(index, force); diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 1163738515..1a1d3c26d6 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -86,6 +86,8 @@ public: void addDisplay(cocos2d::Node *display, int index); + void removeDisplay(int index); + void changeDisplayByIndex(int index, bool force); /** @@ -127,6 +129,9 @@ public: void updateDisplayedColor(const cocos2d::Color3B &parentColor); void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void setColor(const cocos2d::Color3B& color) override; + virtual void setOpacity(GLubyte opacity) override; + //! Update color to render display void updateColor(); @@ -140,14 +145,14 @@ public: /* * Whether or not the bone's transform property changed. if true, the bone will update the transform. */ - virtual void setTransformDirty(bool dirty); - - virtual bool isTransformDirty(); + virtual inline void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } + virtual inline bool isTransformDirty() { return _boneTransformDirty; } virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; Node *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); /* * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. @@ -177,6 +182,8 @@ public: CC_SYNTHESIZE(BlendType, _blendType, BlendType) protected: + void applyParentTransform(Bone *parent); + Tween *_tween; //! Calculate tween effect //! Used for making tween effect in every frame @@ -189,6 +196,14 @@ protected: //! self Transform, use this to change display's state cocos2d::AffineTransform _worldTransform; + + CC_SYNTHESIZE_READONLY(BaseData*, _worldInfo, WorldInfo); + + //! Armature's parent bone + Bone *_armatureParentBone; + + //! Data version + float _dataVersion; }; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 0839a30d7a..341bf503e6 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -197,7 +197,10 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceAddShape(_body->space_private, shape); + if(shape->space_private == NULL) + { + cpSpaceAddShape(_body->space_private, shape); + } } } else @@ -206,7 +209,10 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - cpSpaceRemoveShape(_body->space_private, shape); + if (shape->space_private != NULL) + { + cpSpaceRemoveShape(_body->space_private, shape); + } } } } diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 4749f5eaf9..83151322c5 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -133,13 +133,14 @@ static const char *VERTEX_POINT = "vertex"; static const char *COLOR_INFO = "color"; static const char *CONFIG_FILE_PATH = "config_file_path"; - +static const char *CONTENT_SCALE = "content_scale"; namespace cocostudio { - std::vector s_arrConfigFileList; +std::vector s_arrConfigFileList; float s_PositionReadScale = 1; +float s_ContentScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; @@ -312,7 +313,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) } } -void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector) +void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, Object *target, SEL_SCHEDULE selector) { /* * Check if file is already added to ArmatureDataManager, if then return. @@ -338,15 +339,16 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target s_arrConfigFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = s_BasefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + basefilePath = ""; } @@ -378,11 +380,13 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target // generate async struct AsyncStruct *data = new AsyncStruct(); data->filename = filePath; - data->baseFilePath = s_BasefilePath; + data->baseFilePath = basefilePath; data->target = target; data->selector = selector; data->autoLoadSpriteFile = ArmatureDataManager::getInstance()->isAutoLoadSpriteFile(); + data->imagePath = imagePath; + data->plistPath = plistPath; std::string filePathStr = filePath; size_t startPos = filePathStr.find_last_of("."); @@ -428,10 +432,20 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) AsyncStruct *pAsyncStruct = pDataInfo->asyncStruct; + + if (pAsyncStruct->imagePath != "" && pAsyncStruct->plistPath != "") + { + _getFileMutex.lock(); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile(pAsyncStruct->plistPath.c_str(), pAsyncStruct->imagePath.c_str()); + _getFileMutex.unlock(); + } + while (!pDataInfo->configFileQueue.empty()) { std::string configPath = pDataInfo->configFileQueue.front(); + _getFileMutex.lock(); ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str()); + _getFileMutex.unlock(); pDataInfo->configFileQueue.pop(); } @@ -1123,12 +1137,21 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); + if (dataInfo) + { + dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); + } + else + { + s_ContentScale = json.getItemFloatValue(CONTENT_SCALE, 1); + } + // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); for (int i = 0; i < length; i++) { JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); - ArmatureData *armatureData = decodeArmature(*armatureDic); + ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); if (dataInfo) { @@ -1148,7 +1171,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d for (int i = 0; i < length; i++) { JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); - AnimationData *animationData = decodeAnimation(*animationDic); + AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); if (dataInfo) { @@ -1215,7 +1238,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } } -ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) +ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); @@ -1232,7 +1255,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); - BoneData *boneData = decodeBone(*dic); + BoneData *boneData = decodeBone(*dic, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -1242,12 +1265,12 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json) return armatureData; } -BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) +BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); - decodeNode(boneData, json); + decodeNode(boneData, json, dataInfo); const char *str = json.getItemStringValue(A_NAME); if(str != NULL) @@ -1266,7 +1289,7 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); - DisplayData *displayData = decodeBoneDisplay(*dic); + DisplayData *displayData = decodeBoneDisplay(*dic, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -1276,7 +1299,7 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json) return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) +DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo) { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); @@ -1304,6 +1327,18 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); + + if (dataInfo) + { + sdd->skinData.x *= dataInfo->contentScale; + sdd->skinData.y *= dataInfo->contentScale; + } + else + { + sdd->skinData.x *= s_ContentScale; + sdd->skinData.y *= s_ContentScale; + } + delete dic; } } @@ -1327,7 +1362,14 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) const char *plist = json.getItemStringValue(A_PLIST); if(plist != NULL) { - ((ParticleDisplayData *)displayData)->plist = s_BasefilePath + plist; + if (dataInfo != NULL) + { + static_cast(displayData)->plist = dataInfo->asyncStruct->baseFilePath + plist; + } + else + { + static_cast(displayData)->plist = s_BasefilePath + plist; + } } } break; @@ -1343,7 +1385,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json) return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) +AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); @@ -1358,7 +1400,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); - MovementData *movementData = decodeMovement(*dic); + MovementData *movementData = decodeMovement(*dic, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -1368,7 +1410,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json) return aniData; } -MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) +MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -1389,7 +1431,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); - MovementBoneData *movementBoneData = decodeMovementBone(*dic); + MovementBoneData *movementBoneData = decodeMovementBone(*dic, dataInfo); movementData->addMovementBoneData(movementBoneData); movementBoneData->release(); @@ -1399,7 +1441,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json) return movementData; } -MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) +MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo) { MovementBoneData *movementBoneData = new MovementBoneData(); movementBoneData->init(); @@ -1416,7 +1458,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) for (int i = 0; i < length; i++) { JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); - FrameData *frameData = decodeFrame(*dic); + FrameData *frameData = decodeFrame(*dic, dataInfo); movementBoneData->addFrameData(frameData); frameData->release(); @@ -1471,11 +1513,11 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json) return movementBoneData; } -FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json) +FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInfo) { FrameData *frameData = new FrameData(); - decodeNode(frameData, json); + decodeNode(frameData, json, dataInfo); frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); @@ -1554,10 +1596,23 @@ ContourData *DataReaderHelper::decodeContour(JsonDictionary &json) return contourData; } -void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json) +void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo) { node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; + + if (dataInfo) + { + node->x *= dataInfo->contentScale; + node->y *= dataInfo->contentScale; + } + else + { + node->x *= s_ContentScale; + node->y *= s_ContentScale; + } + + node->zOrder = json.getItemIntValue(A_Z, 0); node->skewX = json.getItemFloatValue(A_SKEW_X, 0); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index d5c8a0d6f5..a9159ef39e 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -63,12 +63,16 @@ protected: cocos2d::Object *target; cocos2d::SEL_SCHEDULE selector; bool autoLoadSpriteFile; + + std::string imagePath; + std::string plistPath; } AsyncStruct; typedef struct _DataInfo { AsyncStruct *asyncStruct; std::queue configFileQueue; + float contentScale; } DataInfo; public: @@ -99,7 +103,7 @@ public: ~DataReaderHelper(); void addDataFromFile(const char *filePath); - void addDataFromFileAsync(const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); + void addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, cocos2d::Object *target, cocos2d::SEL_SCHEDULE selector); void addDataAsyncCallBack(float dt); @@ -145,20 +149,20 @@ public: public: static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); - static ArmatureData *decodeArmature(JsonDictionary &json); - static BoneData *decodeBone(JsonDictionary &json); - static DisplayData *decodeBoneDisplay(JsonDictionary &json); + static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); + static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(JsonDictionary &json, DataInfo *dataInfo); - static AnimationData *decodeAnimation(JsonDictionary &json); - static MovementData *decodeMovement(JsonDictionary &json); - static MovementBoneData *decodeMovementBone(JsonDictionary &json); - static FrameData *decodeFrame(JsonDictionary &json); + static AnimationData *decodeAnimation(JsonDictionary &json, DataInfo *dataInfo); + static MovementData *decodeMovement(JsonDictionary &json, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(JsonDictionary &json, DataInfo *dataInfo); + static FrameData *decodeFrame(JsonDictionary &json, DataInfo *dataInfo); static TextureData *decodeTexture(JsonDictionary &json); static ContourData *decodeContour(JsonDictionary &json); - static void decodeNode(BaseData *node, JsonDictionary &json); + static void decodeNode(BaseData *node, JsonDictionary &json, DataInfo *dataInfo); protected: void loadData(); @@ -177,6 +181,8 @@ protected: std::mutex _addDataMutex; + std::mutex _getFileMutex; + unsigned long _asyncRefCount; unsigned long _asyncRefTotalCount; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 034f115481..b130428ab1 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -70,13 +70,15 @@ void DisplayFactory::createDisplay(Bone *bone, DecorativeDisplay *decoDisplay) } } -void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty) +void DisplayFactory::updateDisplay(Bone *bone, float dt, bool dirty) { - CS_RETURN_IF(!decoDisplay); + Node *display = bone->getDisplayRenderNode(); + CS_RETURN_IF(!display); #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT if (dirty) { + DecorativeDisplay *decoDisplay = bone->getDisplayManager()->getCurrentDecorativeDisplay(); ColliderDetector *detector = decoDisplay->getColliderDetector(); if (detector) { @@ -84,9 +86,8 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f { CC_BREAK_IF(!detector->getBody()); - Node *node = decoDisplay->getDisplay(); - AffineTransform displayTransform = node->getNodeToParentTransform(); - Point anchorPoint = node->getAnchorPointInPoints(); + AffineTransform displayTransform = display->getNodeToParentTransform(); + Point anchorPoint = display->getAnchorPointInPoints(); anchorPoint = PointApplyAffineTransform(anchorPoint, displayTransform); displayTransform.tx = anchorPoint.x; displayTransform.ty = anchorPoint.y; @@ -98,18 +99,19 @@ void DisplayFactory::updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, f } #endif - Node *display = decoDisplay->getDisplay(); - - switch(decoDisplay->getDisplayData()->displayType) + switch(bone->getDisplayRenderNodeType()) { case CS_DISPLAY_SPRITE: - updateSpriteDisplay(bone, display, dt, dirty); + if (dirty) + { + static_cast(display)->updateArmatureTransform(); + } break; case CS_DISPLAY_PARTICLE: - updateParticleDisplay(bone, display, dt, dirty); + updateParticleDisplay(bone, display, dt); break; case CS_DISPLAY_ARMATURE: - updateArmatureDisplay(bone, display, dt, dirty); + updateArmatureDisplay(bone, display, dt); break; default: { @@ -153,6 +155,13 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp skin = Skin::createWithSpriteFrameName((textureName + ".png").c_str()); } + decoDisplay->setDisplay(skin); + + if (skin == NULL) + { + return; + } + skin->setBone(bone); initSpriteDisplay(bone, decoDisplay, displayData->displayName.c_str(), skin); @@ -170,8 +179,6 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp } } - decoDisplay->setDisplay(skin); - } void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin) @@ -206,17 +213,11 @@ void DisplayFactory::initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDispla #endif } -void DisplayFactory::updateSpriteDisplay(Bone *bone, Node *display, float dt, bool dirty) -{ - CS_RETURN_IF(!dirty); - Skin *skin = (Skin *)display; - skin->updateArmatureTransform(); -} void DisplayFactory::addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ArmatureDisplayData *adp = ArmatureDisplayData::create(); ; + ArmatureDisplayData *adp = ArmatureDisplayData::create(); adp->copy((ArmatureDisplayData *)displayData); decoDisplay->setDisplayData(adp); @@ -228,15 +229,9 @@ void DisplayFactory::createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDi Armature *armature = Armature::create(displayData->displayName.c_str(), bone); - /* - * because this bone have called this name, so armature should change it's name, or it can't add to - * Armature's bone children. - */ - armature->setName((bone->getName() + "_armatureChild").c_str()); - decoDisplay->setDisplay(armature); } -void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt) { Armature *armature = (Armature *)display; if(armature) @@ -262,7 +257,7 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi ParticleSystem *system = ParticleSystemQuad::create(displayData->plist.c_str()); decoDisplay->setDisplay(system); } -void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt, bool dirty) +void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt) { ParticleSystem *system = (ParticleSystem *)display; BaseData node; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.h b/cocos/editor-support/cocostudio/CCDisplayFactory.h index 3ef0725ff0..a62329d548 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.h +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.h @@ -40,21 +40,20 @@ class DisplayFactory public: static void addDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateDisplay(Bone *bone, DecorativeDisplay *decoDisplay, float dt, bool dirty); + static void updateDisplay(Bone *bone, float dt, bool dirty); static void addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay); static void initSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay, const char *displayName, Skin *skin); - static void updateSpriteDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); static void addArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createArmatureDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateArmatureDisplay(Bone *bone, cocos2d::Node *display, float dt); static void addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData); static void createParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay); - static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt, bool dirty); + static void updateParticleDisplay(Bone *bone, cocos2d::Node *display, float dt); }; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index ae1ed19781..bffcf80c64 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -48,6 +48,7 @@ DisplayManager *DisplayManager::create(Bone *bone) DisplayManager::DisplayManager() : _decoDisplayList(NULL) , _displayRenderNode(NULL) + , _displayType(CS_DISPLAY_MAX) , _currentDecoDisplay(NULL) , _displayIndex(-1) , _forceChangeDisplay(false) @@ -137,7 +138,7 @@ void DisplayManager::addDisplay(Node *display, int index) if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) { skin->setSkinData(spriteDisplayData->skinData); - ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; + ((SpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; } else { @@ -172,12 +173,13 @@ void DisplayManager::addDisplay(Node *display, int index) void DisplayManager::removeDisplay(int index) { - _decoDisplayList->removeObjectAtIndex(index); - if(index == _displayIndex) { setCurrentDecorativeDisplay(NULL); + _displayIndex = -1; } + + _decoDisplayList->removeObjectAtIndex(index); } Array *DisplayManager::getDecorativeDisplayList() @@ -265,6 +267,12 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) _displayRenderNode->retain(); _displayRenderNode->setVisible(_visible); + + _displayType = _currentDecoDisplay->getDisplayData()->displayType; + } + else + { + _displayType = CS_DISPLAY_MAX; } } @@ -273,6 +281,12 @@ Node *DisplayManager::getDisplayRenderNode() return _displayRenderNode; } + +DisplayType DisplayManager::getDisplayRenderNodeType() +{ + return _displayType; +} + int DisplayManager::getCurrentDisplayIndex() { return _displayIndex; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h index 9953d77995..0856886c57 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -91,6 +91,7 @@ public: cocos2d::Node *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); int getCurrentDisplayIndex(); @@ -133,6 +134,8 @@ protected: cocos2d::Array *_decoDisplayList; //! Display render node. cocos2d::Node *_displayRenderNode; + //! Display render node type + DisplayType _displayType; //! Include current display information, like contour sprite, etc. DecorativeDisplay *_currentDecoDisplay; //! Current display index diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index c3e1bfbc20..1c9bd8965e 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -141,8 +141,18 @@ void ProcessBase::update(float dt) void ProcessBase::gotoFrame(int frameIndex) { + if (_loopType == ANIMATION_NO_LOOP) + { + _loopType = ANIMATION_MAX; + } + else if (_loopType == ANIMATION_TO_LOOP_FRONT) + { + _loopType = ANIMATION_LOOP_FRONT; + } + _curFrameIndex = frameIndex; - pause(); + + _nextFrameIndex = _durationTween; } int ProcessBase::getCurrentFrameIndex() diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 9f80fb2ea7..77c5da4ebb 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -104,8 +104,6 @@ public: virtual void stop(); - virtual void gotoFrame(int frameIndex); - /** * You should never call this function, unless you know what you do * Update the Process, include current process, current frame and son on @@ -118,6 +116,7 @@ public: protected: + virtual void gotoFrame(int frameIndex); /** * Update(float dt) will call this handler, you can handle your logic here diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index d1c66ddc3e..5cb8483a95 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -37,6 +37,8 @@ namespace cocostudio { #define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) #endif +#define SET_VERTEX3F(_v_, _x_, _y_, _z_) (_v_).x = (_x_); (_v_).y = (_y_); (_v_).z = (_z_); + Skin *Skin::create() { Skin *skin = new Skin(); @@ -75,6 +77,7 @@ Skin *Skin::create(const char *pszFileName) Skin::Skin() : _bone(NULL) + , _armature(NULL) , _displayName("") { _skinTransform = AffineTransformIdentity; @@ -82,15 +85,22 @@ Skin::Skin() bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) { - bool ret = Sprite::initWithSpriteFrameName(pszSpriteFrameName); + CCAssert(pszSpriteFrameName != NULL, ""); - if (ret) + SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); + bool ret = true; + + if (pFrame != NULL) { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszSpriteFrameName; + ret = initWithSpriteFrame(pFrame); } + else + { + CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", pszSpriteFrameName); + ret = false; + } + + _displayName = pszSpriteFrameName; return ret; } @@ -99,13 +109,7 @@ bool Skin::initWithFile(const char *pszFilename) { bool ret = Sprite::initWithFile(pszFilename); - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszFilename; - } + _displayName = pszFilename; return ret; } @@ -116,7 +120,8 @@ void Skin::setSkinData(const BaseData &var) setScaleX(_skinData.scaleX); setScaleY(_skinData.scaleY); - setRotation(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationX(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationY(CC_RADIANS_TO_DEGREES(-_skinData.skewY)); setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); @@ -131,6 +136,10 @@ const BaseData &Skin::getSkinData() const void Skin::updateArmatureTransform() { _transform = AffineTransformConcat(_skinTransform, _bone->getNodeToArmatureTransform()); + if(_armature && _armature->getBatchNode()) + { + _transform = AffineTransformConcat(_transform, _armature->getNodeToParentTransform()); + } } void Skin::updateTransform() @@ -173,10 +182,10 @@ void Skin::updateTransform() float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); + SET_VERTEX3F( _quad.bl.vertices, RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); + SET_VERTEX3F( _quad.br.vertices, RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); + SET_VERTEX3F( _quad.tl.vertices, RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); + SET_VERTEX3F( _quad.tr.vertices, RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); } // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS @@ -204,4 +213,20 @@ AffineTransform Skin::getNodeToWorldTransformAR() const return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); } +void Skin::setBone(Bone *bone) +{ + _bone = bone; + if(Armature *armature = _bone->getArmature()) + { + _armature = armature; + TextureAtlas *atlas = armature->getTexureAtlasWithTexture(_texture); + setTextureAtlas(atlas); + } +} + +Bone *Skin::getBone() +{ + return _bone; +} + } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 3494c48436..2d934b8e4b 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -49,9 +49,10 @@ public: cocos2d::AffineTransform getNodeToWorldTransformAR() const; CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); - CC_SYNTHESIZE(Bone *, _bone, Bone); + CC_PROPERTY(Bone *, _bone, Bone); protected: + Armature *_armature; cocos2d::AffineTransform _skinTransform; CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) }; diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index d783c4ba4e..68fa7ebfb5 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -52,26 +52,12 @@ void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); } -TextureAtlas *SpriteFrameCacheHelper::getTexureAtlasWithTexture(Texture2D *texture) -{ - int key = texture->getName(); - TextureAtlas *atlas = (TextureAtlas *)_textureAtlasDic->objectForKey(key); - if (atlas == NULL) - { - atlas = TextureAtlas::createWithTexture(texture, 4); - _textureAtlasDic->setObject(atlas, key); - } - return atlas; -} - SpriteFrameCacheHelper::SpriteFrameCacheHelper() { - _textureAtlasDic = new Dictionary(); } SpriteFrameCacheHelper::~SpriteFrameCacheHelper() { - CC_SAFE_RELEASE_NULL(_textureAtlasDic); } } diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 150fe96aaa..81ccf1b1f9 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -47,8 +47,6 @@ public: */ void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); - cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); - private: /** * @js ctor @@ -60,8 +58,6 @@ private: */ ~SpriteFrameCacheHelper(); - cocos2d::Dictionary *_textureAtlasDic; - static SpriteFrameCacheHelper *_spriteFrameCacheHelper; }; diff --git a/cocos/editor-support/cocostudio/CCTransformHelp.cpp b/cocos/editor-support/cocostudio/CCTransformHelp.cpp index a836055c16..0107760a3b 100644 --- a/cocos/editor-support/cocostudio/CCTransformHelp.cpp +++ b/cocos/editor-support/cocostudio/CCTransformHelp.cpp @@ -96,10 +96,23 @@ void TransformHelp::transformToParentWithoutScale(BaseData &node, const BaseData void TransformHelp::nodeToMatrix(const BaseData &node, AffineTransform &matrix) { - matrix.a = node.scaleX * cos(node.skewY); - matrix.b = node.scaleX * sin(node.skewY); - matrix.c = node.scaleY * sin(node.skewX); - matrix.d = node.scaleY * cos(node.skewX); + if (node.skewX == -node.skewY) + { + double sine = sin(node.skewX); + double cosine = cos(node.skewX); + + matrix.a = node.scaleX * cosine; + matrix.b = node.scaleX * -sine; + matrix.c = node.scaleY * sine; + matrix.d = node.scaleY * cosine; + } + else + { + matrix.a = node.scaleX * cos(node.skewY); + matrix.b = node.scaleX * sin(node.skewY); + matrix.c = node.scaleY * sin(node.skewX); + matrix.d = node.scaleY * cos(node.skewX); + } matrix.tx = node.x; matrix.ty = node.y; diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 8fec95b2a0..5704867a61 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -99,7 +99,14 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio { ProcessBase::play(NULL, durationTo, durationTween, loop, tweenEasing); - _loopType = (AnimationType)loop; + if (loop) + { + _loopType = ANIMATION_TO_LOOP_FRONT; + } + else + { + _loopType = ANIMATION_NO_LOOP; + } _totalDuration = 0; _betweenDuration = 0; @@ -135,15 +142,6 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio } else if (_movementBoneData->frameList.count() > 1) { - if (loop) - { - _loopType = ANIMATION_TO_LOOP_BACK; - } - else - { - _loopType = ANIMATION_NO_LOOP; - } - _durationTween = durationTween * _movementBoneData->scale; if (loop && _movementBoneData->delay != 0) @@ -166,6 +164,27 @@ void Tween::play(MovementBoneData *movementBoneData, int durationTo, int duratio tweenNodeTo(0); } +void Tween::gotoAndPlay(int frameIndex) +{ + ProcessBase::gotoFrame(frameIndex); + + _totalDuration = 0; + _betweenDuration = 0; + _fromIndex = _toIndex = 0; + + _isPlaying = true; + _isComplete = _isPause = false; + + _currentPercent = (float)_curFrameIndex / (float)_rawDuration; + _currentFrame = _nextFrameIndex * _currentPercent; +} + +void Tween::gotoAndPause(int frameIndex) +{ + gotoAndPlay(frameIndex); + pause(); +} + void Tween::updateHandler() { if (_currentPercent >= 1) @@ -211,9 +230,9 @@ void Tween::updateHandler() } } break; - case ANIMATION_TO_LOOP_BACK: + case ANIMATION_TO_LOOP_FRONT: { - _loopType = ANIMATION_LOOP_BACK; + _loopType = ANIMATION_LOOP_FRONT; _nextFrameIndex = _durationTween > 0 ? _durationTween : 1; @@ -244,10 +263,6 @@ void Tween::updateHandler() default: { _currentFrame = fmodf(_currentFrame, _nextFrameIndex); - - _totalDuration = 0; - _betweenDuration = 0; - _fromIndex = _toIndex = 0; } break; } @@ -342,7 +357,7 @@ FrameData *Tween::tweenNodeTo(float percent, FrameData *node) if (!_from->isTween) { - return _from; + percent = 0; } node->x = _from->x + percent * _between->x; @@ -393,6 +408,7 @@ float Tween::updateFrameData(float currentPercent) FrameData *from = NULL; FrameData *to = NULL; + bool passLastFrame = false; if (playedTime < frames[0]->frameID) { @@ -402,32 +418,31 @@ float Tween::updateFrameData(float currentPercent) } else if(playedTime >= frames[length - 1]->frameID) { - from = to = frames[length - 1]; - setBetween(from, to); - return currentPercent; + passLastFrame = true; } do { + _fromIndex = _toIndex; from = frames[_fromIndex]; _totalDuration = from->frameID; - if (++_toIndex >= length) + _toIndex = _fromIndex + 1; + if (_toIndex >= length) { _toIndex = 0; } - _fromIndex = _toIndex; to = frames[_toIndex]; //! Guaranteed to trigger frame event - if(from->strEvent.length() != 0) + if(from->strEvent.length() != 0 && !_animation->isIgnoreFrameEvent()) { _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } - if (playedTime == from->frameID) + if (playedTime == from->frameID || (passLastFrame && _fromIndex == length-1)) { break; } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 80b6c6d7e9..5e5bea6356 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -83,14 +83,11 @@ public: */ virtual void play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing); - inline void setAnimation(ArmatureAnimation *animation) - { - _animation = animation; - } - inline ArmatureAnimation *getAnimation() const - { - return _animation; - } + inline void setAnimation(ArmatureAnimation *animation) { _animation = animation; } + inline ArmatureAnimation *getAnimation() const { return _animation; } + + virtual void gotoAndPlay(int frameIndex); + virtual void gotoAndPause(int frameIndex); protected: /** diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 1cd233ffd2..4421be8ccb 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -30,6 +30,9 @@ Layer *CreateLayer(int index) case TEST_PERFORMANCE: pLayer = new TestPerformance(); break; + case TEST_PERFORMANCE_BATCHNODE: + pLayer = new TestPerformanceBatchNode(); + break; case TEST_CHANGE_ZORDER: pLayer = new TestChangeZorder(); break; @@ -54,6 +57,9 @@ Layer *CreateLayer(int index) case TEST_ARMATURE_NESTING: pLayer = new TestArmatureNesting(); break; + case TEST_ARMATURE_NESTING_2: + pLayer = new TestArmatureNesting2(); + break; default: break; } @@ -235,6 +241,9 @@ void TestAsynchronousLoading::onEnter() ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/Cowboy.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/hero.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/horse.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/bear.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); //! load data directly // ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml"); @@ -314,6 +323,8 @@ std::string TestDragonBones20::title() +#define ArmaturePerformanceTag 20000 + TestPerformance::~TestPerformance() { } @@ -321,10 +332,22 @@ void TestPerformance::onEnter() { ArmatureTestLayer::onEnter(); + + MenuItemFont::setFontSize(65); + MenuItemFont *decrease = MenuItemFont::create(" - ", this, menu_selector(TestPerformance::onDecrease)); + decrease->setColor(ccc3(0,200,20)); + MenuItemFont *increase = MenuItemFont::create(" + ", this, menu_selector(TestPerformance::onIncrease)); + increase->setColor(ccc3(0,200,20)); + + Menu *menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(ccp(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); + addChild(menu, 10000); + armatureCount = frames = times = lastTimes = 0; generated = false; - scheduleUpdate(); + addArmature(100); } std::string TestPerformance::title() @@ -335,37 +358,76 @@ std::string TestPerformance::subtitle() { return "Current Armature Count : "; } -void TestPerformance::addArmature(Armature *armature) +void TestPerformance::onIncrease(Object* pSender) { - armatureCount++; - addChild(armature, armatureCount); + addArmature(20); } -void TestPerformance::update(float delta) +void TestPerformance::onDecrease(Object* pSender) { - frames ++; - times += delta; + if (armatureCount == 0) + return; - if (frames / times > 58) + for (int i = 0; i<20; i++) { + removeArmatureFromParent(ArmaturePerformanceTag + armatureCount); + armatureCount --; + refreshTitile(); + } +} +void TestPerformance::addArmature(int number) +{ + for (int i = 0; iinit("Knight_f/Knight"); armature->getAnimation()->playByIndex(0); armature->setPosition(50 + armatureCount * 2, 150); armature->setScale(0.6f); - addArmature(armature); + addArmatureToParent(armature); armature->release(); - - char pszCount[255]; - sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); - LabelTTF *label = (LabelTTF *)getChildByTag(10001); - label->setString(pszCount); } + + refreshTitile(); +} +void TestPerformance::addArmatureToParent(cocostudio::Armature *armature) +{ + addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::removeArmatureFromParent(int tag) +{ + removeChildByTag(ArmaturePerformanceTag + armatureCount); +} +void TestPerformance::refreshTitile() +{ + char pszCount[255]; + sprintf(pszCount, "%s %i", subtitle().c_str(), armatureCount); + LabelTTF *label = (LabelTTF *)getChildByTag(10001); + label->setString(pszCount); } +void TestPerformanceBatchNode::onEnter() +{ + batchNode = BatchNode::create(); + addChild(batchNode); - + TestPerformance::onEnter(); +} +std::string TestPerformanceBatchNode::title() +{ + return "Test Performance of using BatchNode"; +} +void TestPerformanceBatchNode::addArmatureToParent(cocostudio::Armature *armature) +{ + batchNode->addChild(armature, 0, ArmaturePerformanceTag + armatureCount); +} +void TestPerformanceBatchNode::removeArmatureFromParent(int tag) +{ + batchNode->removeChildByTag(ArmaturePerformanceTag + armatureCount); +} void TestChangeZorder::onEnter() @@ -905,7 +967,7 @@ void TestBoundingBox::draw() { CC_NODE_DRAW_SETUP(); - rect = RectApplyAffineTransform(armature->getBoundingBox(), armature->getNodeToParentTransform()); + rect = armature->getBoundingBox(); DrawPrimitives::setDrawColor4B(100, 100, 100, 255); DrawPrimitives::drawRect(rect.origin, Point(rect.getMaxX(), rect.getMaxY())); @@ -977,3 +1039,185 @@ void TestArmatureNesting::onTouchesEnded(const std::vector& touches, Eve armature->getBone("armOutside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); } } + + + + +Hero *Hero::create(const char *name) +{ + Hero *hero = new Hero(); + if (hero && hero->init(name)) + { + hero->autorelease(); + return hero; + } + CC_SAFE_DELETE(hero); + return NULL; +} + +Hero::Hero() + : m_pMount(NULL) + , m_pLayer(NULL) +{ +} + +void Hero::changeMount(Armature *armature) +{ + if (armature == NULL) + { + retain(); + + playByIndex(0); + //Remove hero from display list + m_pMount->getBone("hero")->removeDisplay(0); + m_pMount->stopAllActions(); + + //Set position to current position + setPosition(m_pMount->getPosition()); + //Add to layer + m_pLayer->addChild(this); + + release(); + + setMount(armature); + } + else + { + setMount(armature); + + retain(); + //Remove from layer + removeFromParentAndCleanup(false); + + //Get the hero bone + Bone *bone = armature->getBone("hero"); + //Add hero as a display to this bone + bone->addDisplay(this, 0); + //Change this bone's display + bone->changeDisplayByIndex(0, true); + bone->setIgnoreMovementBoneData(true); + + setPosition(ccp(0,0)); + //Change animation + playByIndex(1); + + setScale(1); + + release(); + } + +} + +void Hero::playByIndex(int index) +{ + _animation->playByIndex(index); + if (m_pMount) + { + m_pMount->getAnimation()->playByIndex(index); + } +} + +void TestArmatureNesting2::onEnter() +{ + ArmatureTestLayer::onEnter(); + + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting2::onTouchesEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + + touchedMenu = false; + + LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); + MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestArmatureNesting2::ChangeMountCallback)); + + Menu* pMenu =Menu::create(pMenuItem, NULL); + + pMenu->setPosition( CCPointZero ); + pMenuItem->setPosition( ccp( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); + + addChild(pMenu, 2); + + //Create a hero + hero = Hero::create("hero"); + hero->setLayer(this); + hero->playByIndex(0); + hero->setPosition(ccp(VisibleRect::left().x + 20, VisibleRect::left().y)); + addChild(hero); + + //Create 3 mount + horse = createMount("horse", VisibleRect::center()); + + horse2 = createMount("horse", ccp(120, 200)); + horse2->setOpacity(200); + + bear = createMount("bear", ccp(300,70)); +} +void TestArmatureNesting2::onExit() +{ + ArmatureTestLayer::onExit(); +} +std::string TestArmatureNesting2::title() +{ + return "Test CCArmature Nesting 2"; +} +std::string TestArmatureNesting2::subtitle() +{ + return "Move to a mount and press the ChangeMount Button."; +} +void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Event* event) +{ + Point point = touches[0]->getLocation(); + + Armature *armature = hero->getMount() == NULL ? hero : hero->getMount(); + + //Set armature direction + if (point.x < armature->getPositionX()) + { + armature->setScaleX(-1); + } + else + { + armature->setScaleX(1); + } + + ActionInterval *move = CCMoveTo::create(2, point); + armature->stopAllActions(); + armature->runAction(Sequence::create(move, CallFunc::create(this, NULL), NULL)); +} + +void TestArmatureNesting2::ChangeMountCallback(Object* pSender) +{ + hero->stopAllActions(); + + if (hero->getMount()) + { + hero->changeMount(NULL); + } + else + { + if (ccpDistance(hero->getPosition(), horse->getPosition()) < 20) + { + hero->changeMount(horse); + } + else if (ccpDistance(hero->getPosition(), horse2->getPosition()) < 20) + { + hero->changeMount(horse2); + } + else if (ccpDistance(hero->getPosition(), bear->getPosition()) < 30) + { + hero->changeMount(bear); + } + } +} + +Armature * TestArmatureNesting2::createMount(const char *name, Point position) +{ + Armature *armature = Armature::create(name); + armature->getAnimation()->playByIndex(0); + armature->setPosition(position); + addChild(armature); + + return armature; +} + diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index 51b47085b5..f5a7787168 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -30,6 +30,7 @@ enum { TEST_COCOSTUDIO_WITH_SKELETON, TEST_DRAGON_BONES_2_0, TEST_PERFORMANCE, + TEST_PERFORMANCE_BATCHNODE, TEST_CHANGE_ZORDER, TEST_ANIMATION_EVENT, TEST_PARTICLE_DISPLAY, @@ -38,6 +39,7 @@ enum { TEST_BOUDINGBOX, TEST_ANCHORPOINT, TEST_ARMATURE_NESTING, + TEST_ARMATURE_NESTING_2, TEST_LAYER_COUNT }; @@ -97,8 +99,12 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void addArmature(cocostudio::Armature *armature); - void update(float delta); + virtual void onIncrease(Object* pSender); + virtual void onDecrease(Object* pSender); + virtual void addArmature(int number); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + virtual void refreshTitile(); int armatureCount; @@ -108,6 +114,15 @@ public: bool generated; }; +class TestPerformanceBatchNode : public TestPerformance +{ + virtual void onEnter(); + virtual std::string title(); + virtual void addArmatureToParent(cocostudio::Armature *armature); + virtual void removeArmatureFromParent(int tag); + + cocostudio::BatchNode *batchNode; +}; class TestChangeZorder : public ArmatureTestLayer { @@ -256,4 +271,39 @@ public: cocostudio::Armature *armature; int weaponIndex; }; + +class Hero : public cocostudio::Armature +{ +public: + static Hero *create(const char *name); + Hero(); + + virtual void changeMount(cocostudio::Armature *armature); + virtual void playByIndex(int index); + + CC_SYNTHESIZE(cocostudio::Armature*, m_pMount, Mount); + CC_SYNTHESIZE(cocos2d::Layer*, m_pLayer, Layer); +}; + +class TestArmatureNesting2 : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual void onExit(); + virtual std::string title(); + virtual std::string subtitle(); + void onTouchesEnded(const std::vector& touches, Event* event); + + virtual void ChangeMountCallback(Object* pSender); + virtual cocostudio::Armature *createMount(const char *name, Point position); + + Hero *hero; + + cocostudio::Armature *horse; + cocostudio::Armature *horse2; + cocostudio::Armature *bear; + + + bool touchedMenu; +}; #endif // __HELLOWORLD_SCENE_H__ \ No newline at end of file From ef973b5737f8d441f3333c2470e97aae9a91d5eb Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 09:54:05 +0800 Subject: [PATCH 279/557] upload resource --- .../Cpp/TestCpp/Resources/armature/Dragon.xml | 354 ++++++++++++------ 1 file changed, 241 insertions(+), 113 deletions(-) diff --git a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml index 0b4f52cf06..f531349f7c 100644 --- a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml +++ b/samples/Cpp/TestCpp/Resources/armature/Dragon.xml @@ -1,56 +1,56 @@ - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + @@ -58,158 +58,286 @@ - - - + + + - + - + - + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - - - + + + - + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - + - - - + + + - - - + + + - - - + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From c08a09a7e088eaec7b5dbca85e2ca0349a0f45a8 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Wed, 30 Oct 2013 10:52:04 +0800 Subject: [PATCH 280/557] #3049:Add LICENSE_JSON4LUA and some constant values. --- .gitignore | 2 ++ .../scripting/lua/script/Cocos2dConstants.lua | 8 +++++++ licenses/LICENSE_JSON4Lua.txt | 21 +++++++++++++++++++ .../XMLHttpRequestTest/XMLHttpRequestTest.lua | 8 +++---- 4 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 licenses/LICENSE_JSON4Lua.txt diff --git a/.gitignore b/.gitignore index d6bae12eb7..91ab9c7356 100644 --- a/.gitignore +++ b/.gitignore @@ -22,10 +22,12 @@ Thumbs.db *.log [Bb]in [Dd]ebug/ +[Dd]ebug.win32/ *.sbr *.sdf obj/ [Rr]elease/ +[Rr]elease.win32/ _ReSharper*/ [Tt]est[Rr]esult* ipch/ diff --git a/cocos/scripting/lua/script/Cocos2dConstants.lua b/cocos/scripting/lua/script/Cocos2dConstants.lua index 5a8ae27e94..cc43ce5ee3 100644 --- a/cocos/scripting/lua/script/Cocos2dConstants.lua +++ b/cocos/scripting/lua/script/Cocos2dConstants.lua @@ -272,3 +272,11 @@ cc.WEBSOCKET_STATE_CONNECTING = 0 cc.WEBSOCKET_STATE_OPEN = 1 cc.WEBSOCKET_STATE_CLOSING = 2 cc.WEBSOCKET_STATE_CLOSED = 3 + + +cc.XMLHTTPREQUEST_RESPONSE_STRING = 0 +cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER = 1 +cc.XMLHTTPREQUEST_RESPONSE_BLOB = 2 +cc.XMLHTTPREQUEST_RESPONSE_DOCUMENT = 3 +cc.XMLHTTPREQUEST_RESPONSE_JSON = 4 + \ No newline at end of file diff --git a/licenses/LICENSE_JSON4Lua.txt b/licenses/LICENSE_JSON4Lua.txt new file mode 100644 index 0000000000..7e0d778e8c --- /dev/null +++ b/licenses/LICENSE_JSON4Lua.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2009 Craig Mason-Jones + +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 diff --git a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua index 2456d5d092..1cdffa035a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua @@ -23,7 +23,7 @@ local function XMLHttpRequestLayer() --Get local function onMenuGetClicked() local xhr = XMLHttpRequest:new() - xhr.responseType = 0 + xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("GET", "http://httpbin.org/get") local function onReadyStateChange() @@ -47,7 +47,7 @@ local function XMLHttpRequestLayer() --Post local function onMenuPostClicked() local xhr = XMLHttpRequest:new() - xhr.responseType = 0 + xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("POST", "http://httpbin.org/post") local function onReadyStateChange() labelStatusCode:setString("Http Status Code:"..xhr.statusText) @@ -68,7 +68,7 @@ local function XMLHttpRequestLayer() --Post Binary local function onMenuPostBinaryClicked() local xhr = XMLHttpRequest:new() - xhr.responseType = 1 + xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER xhr:open("POST", "http://httpbin.org/post") local function onReadyStateChange() @@ -103,7 +103,7 @@ local function XMLHttpRequestLayer() local function onMenuPostJsonClicked() local xhr = XMLHttpRequest:new() - xhr.responseType = 4 + xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON xhr:open("POST", "http://httpbin.org/post") local function onReadyStateChange() From 80b97be6f4378a2bc0b1b58ead232b98f53ad280 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Wed, 30 Oct 2013 11:34:16 +0800 Subject: [PATCH 281/557] update develop --- .../cocostudio/CCDataReaderHelper.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 33 +++++++++---------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 83151322c5..3fb1b69fb8 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -344,7 +344,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p if (pos != std::string::npos) { - basefilePath = s_BasefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 4421be8ccb..625308dd01 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -334,14 +334,14 @@ void TestPerformance::onEnter() MenuItemFont::setFontSize(65); - MenuItemFont *decrease = MenuItemFont::create(" - ", this, menu_selector(TestPerformance::onDecrease)); - decrease->setColor(ccc3(0,200,20)); - MenuItemFont *increase = MenuItemFont::create(" + ", this, menu_selector(TestPerformance::onIncrease)); - increase->setColor(ccc3(0,200,20)); + MenuItemFont *decrease = MenuItemFont::create(" - ", CC_CALLBACK_1(TestPerformance::onDecrease, this)); + decrease->setColor(Color3B(0,200,20)); + MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); + increase->setColor(Color3B(0,200,20)); Menu *menu = Menu::create(decrease, increase, NULL); menu->alignItemsHorizontally(); - menu->setPosition(ccp(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); + menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); armatureCount = frames = times = lastTimes = 0; @@ -1097,7 +1097,7 @@ void Hero::changeMount(Armature *armature) bone->changeDisplayByIndex(0, true); bone->setIgnoreMovementBoneData(true); - setPosition(ccp(0,0)); + setPosition(Point(0,0)); //Change animation playByIndex(1); @@ -1125,16 +1125,15 @@ void TestArmatureNesting2::onEnter() listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting2::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - touchedMenu = false; LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); - MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(TestArmatureNesting2::ChangeMountCallback)); + MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::ChangeMountCallback, this)); Menu* pMenu =Menu::create(pMenuItem, NULL); - pMenu->setPosition( CCPointZero ); - pMenuItem->setPosition( ccp( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); + pMenu->setPosition( Point() ); + pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); addChild(pMenu, 2); @@ -1142,16 +1141,16 @@ void TestArmatureNesting2::onEnter() hero = Hero::create("hero"); hero->setLayer(this); hero->playByIndex(0); - hero->setPosition(ccp(VisibleRect::left().x + 20, VisibleRect::left().y)); + hero->setPosition(Point(VisibleRect::left().x + 20, VisibleRect::left().y)); addChild(hero); //Create 3 mount horse = createMount("horse", VisibleRect::center()); - horse2 = createMount("horse", ccp(120, 200)); + horse2 = createMount("horse", Point(120, 200)); horse2->setOpacity(200); - bear = createMount("bear", ccp(300,70)); + bear = createMount("bear", Point(300,70)); } void TestArmatureNesting2::onExit() { @@ -1183,7 +1182,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, CallFunc::create(this, NULL), NULL)); + armature->runAction(Sequence::create(move, NULL)); } void TestArmatureNesting2::ChangeMountCallback(Object* pSender) @@ -1196,15 +1195,15 @@ void TestArmatureNesting2::ChangeMountCallback(Object* pSender) } else { - if (ccpDistance(hero->getPosition(), horse->getPosition()) < 20) + if (hero->getPosition().getDistance(horse->getPosition()) < 20) { hero->changeMount(horse); } - else if (ccpDistance(hero->getPosition(), horse2->getPosition()) < 20) + else if (hero->getPosition().getDistance(horse2->getPosition()) < 20) { hero->changeMount(horse2); } - else if (ccpDistance(hero->getPosition(), bear->getPosition()) < 30) + else if (hero->getPosition().getDistance(bear->getPosition()) < 30) { hero->changeMount(bear); } From 4d9b05a67d643088bdddd35132f1a5c006e5b506 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 30 Oct 2013 14:19:07 +0800 Subject: [PATCH 283/557] add script to build android samples --- build/android-build.py | 153 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100755 build/android-build.py diff --git a/build/android-build.py b/build/android-build.py new file mode 100755 index 0000000000..d5f8144ffe --- /dev/null +++ b/build/android-build.py @@ -0,0 +1,153 @@ +#!/usr/bin/python +# android-build.py +# Build android samples + +# You can use + + +# begin +import sys +import os, os.path +from optparse import OptionParser + +CPP_SAMPLES = ['hellocpp', 'testcpp', 'simplegame', 'assetsmanager'] +LUA_SAMPLES = ['hellolua', 'testlua'] +JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] +ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES + + +def usage(): + + print "%prog [-n ndk-build-parameter] target\n\ + valid target are [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon\ +|crystalcraze|moonwarriors|testjavascript|watermelonwithme], of course you can use 'cpp'\ +to build all cpp samples, 'lua' to build all lua samples, 'jsb' to build all javascript samples,\ + and 'all' for all samples" + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def caculate_built_samples(args): + ''' Compute the sampels to be built + 'cpp' for short of all cpp samples + 'lua' for short of all lua smpleas + 'jsb' for short of all javascript samples + ''' + + if 'all' == args: + return ALL_SAMPLES + + targets = [] + if 'cpp' in args: + targets += CPP_SAMPLES + args.remove('cpp') + if 'lua' in args: + targets += LUA_SAMPLES + args.remove('lua') + if 'jsb' in args: + targets += JSB_SAMPLES + args.remove('jsb') + + targets += args + + # remove duplicate elements, for example + # python android-build.py cpp hellocpp + targets = set(targets) + return list(targets) + +def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + if ndk_build_param == None: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) + os.system(command) + +def build_samples(target,ndk_build_param): + + ndk_root = check_environment_variables() + select_toolchain_version() + build_targets = caculate_built_samples(target) + + current_dir = os.getcwd() + cocos_root = os.path.join(current_dir, "..") + + app_android_root = '' + for target in build_targets: + if target == 'hellocpp': + app_android_root = os.path.join(cocos_root, 'samples/Cpp/HelloCpp/proj.android') + elif target == 'testcpp': + app_android_root = os.path.join(cocos_root, 'samples/Cpp/TestCpp/proj.android') + elif target == 'simplegame': + app_android_root = os.path.join(cocos_root, 'samples/Cpp/SimpleGame/proj.android') + elif target == 'assetsmanager': + app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManager/proj.android') + elif target == 'hellolua': + app_android_root = os.path.join(cocos_root, 'samples/Lua/HelloLua/proj.android') + elif target == 'testlua': + app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') + elif target == 'cocosdragon': + app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CocosDragonJS/proj.android') + elif target == 'crystalcraze': + app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CrystalCraze/proj.android') + elif target == 'moonwarriors': + app_android_root = os.path.join(cocos_root, 'samples/JavaScript/MoonWarriors/proj.android') + elif target == 'testjavascript': + app_android_root = os.path.join(cocos_root, 'samples/JavaScript/TestJavascript/proj.android') + elif target == 'watermelonwithme': + app_android_root = os.path.join(cocos_root, 'samples/JavaScript/WatermelonWithMe/proj.android') + else: + print 'unknown target %s, pass it', target + continue + + do_build(cocos_root, ndk_root, app_android_root, ndk_build_param) + +# -------------- main -------------- +if __name__ == '__main__': + + #parse the params + parser = OptionParser() + parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build') + (opts, args) = parser.parse_args() + + if len(args) == 0: + usage() + else: + build_samples(args, opts.ndk_build_param) From 391cda44ef17d514eec4994118a1651f2fec7eb4 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 30 Oct 2013 15:53:58 +0800 Subject: [PATCH 284/557] issue #2771: edit listener --- cocos/physics/CCPhysicsContact.cpp | 99 +++++++++++++++++++ cocos/physics/CCPhysicsContact.h | 31 +++++- .../Classes/PhysicsTest/PhysicsTest.cpp | 25 +++++ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 7 ++ 4 files changed, 159 insertions(+), 3 deletions(-) diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 71ed2beb01..400dc10477 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -186,5 +186,104 @@ PhysicsContactListener::~PhysicsContactListener() } +PhysicsContactListener* PhysicsContactListener::create() +{ + PhysicsContactListener* obj = new PhysicsContactListener(); + + if (obj != nullptr) + { + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool PhysicsContactListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + CC_UNUSED_PARAM(shapeA); + CC_UNUSED_PARAM(shapeB); + return true; +} + +bool PhysicsContactListener::checkAvaiable() +{ + if (onContactBegin == nullptr && onContactPreSolve == nullptr + && onContactPostSolve == nullptr && onContactEnd == nullptr) + { + CCASSERT(false, "Invalid PhysicsContactListener."); + return false; + } + + return true; +} + +EventListener* PhysicsContactListener::clone() +{ + PhysicsContactListener* obj = PhysicsContactListener::create(); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactEnd = onContactEnd; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + + + + +PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + PhysicsContactWithBodysListener* obj = new PhysicsContactWithBodysListener(); + + if (obj != nullptr) + { + obj->_a = shapeA; + obj->_b = shapeB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA == _a && shapeB == _b) + || (shapeA == _b && shapeB == _a)) + { + return true; + } + + return false; +} + +EventListener* PhysicsContactWithBodysListener::clone() +{ + PhysicsContactWithBodysListener* obj = PhysicsContactWithBodysListener::create(_a, _b); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactEnd = onContactEnd; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 6c96539c92..48c234b1ad 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -30,6 +30,7 @@ #include "CCObject.h" #include "CCGeometry.h" +#include "CCEventListener.h" NS_CC_BEGIN @@ -154,11 +155,14 @@ private: /* * @brief contact listener. */ -class PhysicsContactListener +class PhysicsContactListener : public EventListener { public: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); + static PhysicsContactListener* create(); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool checkAvaiable(); + virtual EventListener* clone(); public: /* @@ -178,6 +182,27 @@ public: * onContactBegin and onContactEnd will called in pairs. */ std::function onContactEnd; + +protected: + PhysicsContactListener(); + virtual ~PhysicsContactListener(); +}; + +class PhysicsContactWithBodysListener : public PhysicsContactListener +{ +public: + static PhysicsContactWithBodysListener* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListener* clone(); + +protected: + PhysicsShape* _a; + PhysicsShape* _b; + +protected: + PhysicsContactWithBodysListener(); + virtual ~PhysicsContactWithBodysListener(); }; NS_CC_END diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index ae7f7d07a4..554782bc2d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1002,4 +1002,29 @@ void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) std::string PhysicsDemoPump::title() { return "Pump"; +} + + +void PhysicsDemoOneWayPlatform::onEnter() +{ + PhysicsDemo::onEnter(); + + setTouchEnabled(true); + setTouchMode(Touch::DispatchMode::ONE_BY_ONE); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto platform = Node::create(); + platform->setPhysicsBody(PhysicsBody::createEdgeBox(Size(200, 50))); + platform->setPosition(VisibleRect::center()); + this->addChild(platform); + + this->addChild(makeBall(VisibleRect::center() + Point(0, 50), 5)); +} + +std::string PhysicsDemoOneWayPlatform::title() +{ + return "One Way Platform"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 79932c60a7..7054291dbd 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -134,4 +134,11 @@ private: float _rotationV; }; +class PhysicsDemoOneWayPlatform : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; +}; + #endif From da9f7c912b561f4783f557e063239d885689d4e5 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 30 Oct 2013 18:27:56 +0800 Subject: [PATCH 285/557] use build/android-build to build android samples, and update readme --- README.md | 22 ++- build/android-build.py | 61 +++++++- .../proj.android/build_native.cmd | 87 ----------- .../proj.android/build_native.sh | 123 --------------- .../HelloCpp/proj.android/build_native.cmd | 83 ---------- .../Cpp/HelloCpp/proj.android/build_native.sh | 107 ------------- .../SimpleGame/proj.android/build_native.cmd | 83 ---------- .../SimpleGame/proj.android/build_native.sh | 107 ------------- .../Cpp/TestCpp/proj.android/build_native.cmd | 90 ----------- .../Cpp/TestCpp/proj.android/build_native.sh | 98 ------------ .../proj.android/build_native.cmd | 90 ----------- .../proj.android/build_native.sh | 114 -------------- .../proj.android/build_native.cmd | 90 ----------- .../CrystalCraze/proj.android/build_native.sh | 115 -------------- .../proj.android/build_native.cmd | 96 ------------ .../MoonWarriors/proj.android/build_native.sh | 117 -------------- .../proj.android/build_native.cmd | 90 ----------- .../proj.android/build_native.sh | 114 -------------- .../proj.android/build_native.cmd | 90 ----------- .../proj.android/build_native.sh | 113 -------------- .../HelloLua/proj.android/build_native.cmd | 86 ----------- .../Lua/HelloLua/proj.android/build_native.sh | 116 -------------- .../Lua/TestLua/proj.android/build_native.cmd | 93 ------------ .../Lua/TestLua/proj.android/build_native.sh | 143 ------------------ 24 files changed, 69 insertions(+), 2259 deletions(-) delete mode 100644 samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd delete mode 100755 samples/Cpp/AssetsManagerTest/proj.android/build_native.sh delete mode 100644 samples/Cpp/HelloCpp/proj.android/build_native.cmd delete mode 100755 samples/Cpp/HelloCpp/proj.android/build_native.sh delete mode 100644 samples/Cpp/SimpleGame/proj.android/build_native.cmd delete mode 100755 samples/Cpp/SimpleGame/proj.android/build_native.sh delete mode 100644 samples/Cpp/TestCpp/proj.android/build_native.cmd delete mode 100755 samples/Cpp/TestCpp/proj.android/build_native.sh delete mode 100644 samples/Javascript/CocosDragonJS/proj.android/build_native.cmd delete mode 100755 samples/Javascript/CocosDragonJS/proj.android/build_native.sh delete mode 100644 samples/Javascript/CrystalCraze/proj.android/build_native.cmd delete mode 100755 samples/Javascript/CrystalCraze/proj.android/build_native.sh delete mode 100644 samples/Javascript/MoonWarriors/proj.android/build_native.cmd delete mode 100755 samples/Javascript/MoonWarriors/proj.android/build_native.sh delete mode 100644 samples/Javascript/TestJavascript/proj.android/build_native.cmd delete mode 100755 samples/Javascript/TestJavascript/proj.android/build_native.sh delete mode 100644 samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd delete mode 100755 samples/Javascript/WatermelonWithMe/proj.android/build_native.sh delete mode 100644 samples/Lua/HelloLua/proj.android/build_native.cmd delete mode 100755 samples/Lua/HelloLua/proj.android/build_native.sh delete mode 100644 samples/Lua/TestLua/proj.android/build_native.cmd delete mode 100755 samples/Lua/TestLua/proj.android/build_native.sh diff --git a/README.md b/README.md index 39e47ca9ad..217779827f 100644 --- a/README.md +++ b/README.md @@ -23,14 +23,15 @@ How to start a new game ----------------------- 1. Download the code from [cocos2d download site][4] +2. Enter `tools/project-creator` -2. Run the `create-multi-platform-projects.py` script +2. Run the `create-projects.py` script Example: - $ cd cocos2d-x + $ cd cocos2d-x/tools/project-creator $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp - $ cd projects/mygame + $ cd ../../projects/mygame Main features @@ -79,9 +80,6 @@ Runtime Requirements * Android 2.3+ for Android games * OS X v10.6+ for Mac games * Windows 7+ for Win games - * Tizen 2.2+ - * Emscripten - * Google Native Client Running Tests @@ -92,28 +90,26 @@ Select the test you want from Xcode Scheme chooser. * For OS X / iOS ``` -$ cd cocos2d-x/samples +$ cd cocos2d-x/build $ open samples.xcodeproj ``` * For Linux ``` -$ cd cocos2d-x +$ cd cocos2d-x/build $ ./make-all-linux-projects.sh ``` -or open the `cocos2d-x/cocos2dx-qt5.pro` file using QT Creator 5. - * For Windows -Open the `cocos2d-x/cocos2d-win32.vc2012.sln` +Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln` * For Android ``` -$ cd cocos2d-x/samples/Cpp/HelloCpp/proj.android -$ ./build_native.sh +$ cd cocos2d-x/build +$ python ./android-build.py hellocpp ``` Import HelloCpp Android project using Eclipse(released with Android SDK). The path to be imported is `cocos2d-x/samples/Cpp/HelloCpp/proj.android`. diff --git a/build/android-build.py b/build/android-build.py index d5f8144ffe..62bc226e77 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -8,6 +8,7 @@ # begin import sys import os, os.path +import shutil from optparse import OptionParser CPP_SAMPLES = ['hellocpp', 'testcpp', 'simplegame', 'assetsmanager'] @@ -62,7 +63,7 @@ def caculate_built_samples(args): 'jsb' for short of all javascript samples ''' - if 'all' == args: + if 'all' in args: return ALL_SAMPLES targets = [] @@ -100,6 +101,63 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) os.system(command) +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(target, app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources(cpp samples and lua samples) + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # jsb samples should copy javascript files and resources(shared with cocos2d-html5) + if target in JSB_SAMPLES or target == "assetsmanager": + resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") + copy_files(resources_dir, assets_dir) + + if target == "cocosdragon": + resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android") + if target == "crystalcraze": + resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android") + if target == "moonwarriors": + resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res") + if target == "testjavascript": + resources_dir = os.path.join(app_android_root, "../../Shared/tests/") + if target == "watermelonwithme": + resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe") + copy_files(resources_dir, assets_dir) + + # AssetsManager test should also copy javascript files + if target == "assetsmanager": + resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") + copy_files(resources_dir, assets_dir) + + # lua samples should copy lua script + if target in LUA_SAMPLES: + resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/lua/script") + copy_files(resources_dir, assets_dir) + + # TestLua shared resources with TestCpp + if target == "testlua": + resources_dir = os.path.join(app_android_root, "../../../Cpp/TestCpp/Resources") + copy_files(resources_dir, assets_dir) + def build_samples(target,ndk_build_param): ndk_root = check_environment_variables() @@ -137,6 +195,7 @@ def build_samples(target,ndk_build_param): print 'unknown target %s, pass it', target continue + copy_resources(target, app_android_root) do_build(cocos_root, ndk_root, app_android_root, ndk_build_param) # -------------- main -------------- diff --git a/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd b/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd deleted file mode 100644 index d397bbc901..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/build_native.cmd +++ /dev/null @@ -1,87 +0,0 @@ -@echo off - -set APPNAME="AssetsManager" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh b/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh deleted file mode 100755 index 30549e8869..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/build_native.sh +++ /dev/null @@ -1,123 +0,0 @@ -APPNAME="AssetsManager" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -# copy icons (if they exist) -file="$APP_ANDROID_ROOT"/assets/Icon-72.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-hdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-48.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-mdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-32.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-ldpi/icon.png -fi - - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi diff --git a/samples/Cpp/HelloCpp/proj.android/build_native.cmd b/samples/Cpp/HelloCpp/proj.android/build_native.cmd deleted file mode 100644 index f18ac5f170..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/build_native.cmd +++ /dev/null @@ -1,83 +0,0 @@ -@echo off - -set APPNAME="HelloCpp" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%\external;%COCOS2DX_ROOT%\cocos - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.android/build_native.sh b/samples/Cpp/HelloCpp/proj.android/build_native.sh deleted file mode 100755 index cfd49f5d79..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/build_native.sh +++ /dev/null @@ -1,107 +0,0 @@ -APPNAME="HelloCpp" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - set -x - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" -else - echo "Using prebuilt externals" - set -x - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" - -fi diff --git a/samples/Cpp/SimpleGame/proj.android/build_native.cmd b/samples/Cpp/SimpleGame/proj.android/build_native.cmd deleted file mode 100644 index 437e55298f..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/build_native.cmd +++ /dev/null @@ -1,83 +0,0 @@ -@echo off - -set APPNAME="SimpleGame" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.android/build_native.sh b/samples/Cpp/SimpleGame/proj.android/build_native.sh deleted file mode 100755 index 8f09b2bb6b..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/build_native.sh +++ /dev/null @@ -1,107 +0,0 @@ -APPNAME="SimpleGame" - -# options - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --h this help -EOF -} - -while getopts "h" OPTION; do -case "$OPTION" in -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=$(sed '/\./d' "$_LOCALPROPERTIES_FILE") - for line in $_PROPERTIES; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy icons (if they exist) -file="$APP_ANDROID_ROOT"/assets/Icon-72.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-hdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-48.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-mdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-32.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-ldpi/icon.png -fi - -echo "Building in debug" - -"$NDK_ROOT"/ndk-build NDK_DEBUG=1 -C "$APP_ANDROID_ROOT" \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" diff --git a/samples/Cpp/TestCpp/proj.android/build_native.cmd b/samples/Cpp/TestCpp/proj.android/build_native.cmd deleted file mode 100644 index d8eaaea7c7..0000000000 --- a/samples/Cpp/TestCpp/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="TestCpp" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\external;%COCOS2DX_ROOT%\cocos - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem remove test_image_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_image_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba8888.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgb888.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_a8.pvr.gz - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.android/build_native.sh b/samples/Cpp/TestCpp/proj.android/build_native.sh deleted file mode 100755 index 69464cc437..0000000000 --- a/samples/Cpp/TestCpp/proj.android/build_native.sh +++ /dev/null @@ -1,98 +0,0 @@ -APPNAME="TestCpp" - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --h this help -EOF -} - -while getopts "h" OPTION; do -case "$OPTION" in -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=$(sed '/\./d' "$_LOCALPROPERTIES_FILE") - for line in $_PROPERTIES; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# remove test_image_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_image_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba8888.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgb888.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_a8.pvr.gz - -echo "Using prebuilt externals" -"$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos" diff --git a/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd b/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd deleted file mode 100644 index 76a9a7138f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="CocosDragonJS" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\CocosDragonJS\Published files Android" -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause diff --git a/samples/Javascript/CocosDragonJS/proj.android/build_native.sh b/samples/Javascript/CocosDragonJS/proj.android/build_native.sh deleted file mode 100755 index 768c2caf04..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/build_native.sh +++ /dev/null @@ -1,114 +0,0 @@ -#NDK_ROOT="/opt/android/android-ndk" -APPNAME="CocosDragonJS" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -RESROUCE_ROOT="$APP_ROOT/../Shared/games/CocosDragonJS/Published files Android" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy "Resources" into "assets" -cp -rf "$RESROUCE_ROOT"/* "$APP_ANDROID_ROOT"/assets - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/samples/Javascript/CrystalCraze/proj.android/build_native.cmd b/samples/Javascript/CrystalCraze/proj.android/build_native.cmd deleted file mode 100644 index 22f5ad4442..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="CrystalCraze" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\CrystalCraze\Published-Android" -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause diff --git a/samples/Javascript/CrystalCraze/proj.android/build_native.sh b/samples/Javascript/CrystalCraze/proj.android/build_native.sh deleted file mode 100755 index 102eefa80f..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/build_native.sh +++ /dev/null @@ -1,115 +0,0 @@ -#NDK_ROOT="/opt/android/android-ndk" -APPNAME="CrystalCraze" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -RESROUCE_ROOT="$APP_ROOT/../Shared/games/CrystalCraze/Published-Android" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy "Resources" into "assets" -cp -rf "$RESROUCE_ROOT"/* "$APP_ANDROID_ROOT"/assets - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/samples/Javascript/MoonWarriors/proj.android/build_native.cmd b/samples/Javascript/MoonWarriors/proj.android/build_native.cmd deleted file mode 100644 index e2c1c82c7e..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/build_native.cmd +++ /dev/null @@ -1,96 +0,0 @@ -@echo off - -set APPNAME="MoonWarriors" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\MoonWarriors\res" -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets - -rem copy MoonWarriors js -xcopy /e /q /r /y %RESROUCE_ROOT%\..\src %APP_ANDROID_ROOT%\assets - -rem copy MoonWarriors-native.js -xcopy /e /q /r /y %RESROUCE_ROOT%\..\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause diff --git a/samples/Javascript/MoonWarriors/proj.android/build_native.sh b/samples/Javascript/MoonWarriors/proj.android/build_native.sh deleted file mode 100755 index e97488b40c..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/build_native.sh +++ /dev/null @@ -1,117 +0,0 @@ -APPNAME="MoonWarriors" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -RESROUCE_ROOT="$APP_ROOT/../Shared/games/MoonWarriors/res" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - - -# copy "Resources" into "assets" -cp -rf "$RESROUCE_ROOT" "$APP_ANDROID_ROOT"/assets - -# copy MoonWarriors js -cp -rf "$RESROUCE_ROOT"/../src "$APP_ANDROID_ROOT"/assets -# copy MoonWarriors-native.js -cp "$RESROUCE_ROOT"/../*.js "$APP_ANDROID_ROOT"/assets - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=1 V=1 diff --git a/samples/Javascript/TestJavascript/proj.android/build_native.cmd b/samples/Javascript/TestJavascript/proj.android/build_native.cmd deleted file mode 100644 index a0a5ec0785..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="TestJavascript" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\..\Shared\tests\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.android/build_native.sh b/samples/Javascript/TestJavascript/proj.android/build_native.sh deleted file mode 100755 index 3378f4006a..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/build_native.sh +++ /dev/null @@ -1,114 +0,0 @@ -APPNAME="TestJavascript" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets -mkdir "$APP_ANDROID_ROOT"/assets/res - -# copy src/**/*.js from cocos2d-js-tests into assets' root -cp -rf "$APP_ROOT"/../Shared/tests/* "$APP_ANDROID_ROOT"/assets - - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd b/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd deleted file mode 100644 index a592025ff0..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="WatermelonWithMe" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set RESROUCE_ROOT="%APP_ROOT%\..\Shared\games\WatermelonWithMe" -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %RESROUCE_ROOT%\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause diff --git a/samples/Javascript/WatermelonWithMe/proj.android/build_native.sh b/samples/Javascript/WatermelonWithMe/proj.android/build_native.sh deleted file mode 100755 index e976f1c2b2..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/build_native.sh +++ /dev/null @@ -1,113 +0,0 @@ -APPNAME="TestJavascript" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -RESROUCE_ROOT="$APP_ROOT/../Shared/games/WatermelonWithMe" -BINDINGS_JS_ROOT="$APP_ROOT/../../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy "Resources" into "assets" -cp -rf "$RESROUCE_ROOT"/* "$APP_ANDROID_ROOT"/assets - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/samples/Lua/HelloLua/proj.android/build_native.cmd b/samples/Lua/HelloLua/proj.android/build_native.cmd deleted file mode 100644 index 4116608669..0000000000 --- a/samples/Lua/HelloLua/proj.android/build_native.cmd +++ /dev/null @@ -1,86 +0,0 @@ -@echo off - -set APPNAME="HelloLua" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy common luaScript -xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.android/build_native.sh b/samples/Lua/HelloLua/proj.android/build_native.sh deleted file mode 100755 index 0e0f3662f5..0000000000 --- a/samples/Lua/HelloLua/proj.android/build_native.sh +++ /dev/null @@ -1,116 +0,0 @@ -APPNAME="HelloLua" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -#copy comment script -for file in "$APP_ROOT"/../../../cocos/scripting/lua/script/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}/external:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}" -fi diff --git a/samples/Lua/TestLua/proj.android/build_native.cmd b/samples/Lua/TestLua/proj.android/build_native.cmd deleted file mode 100644 index fa1fc0ad75..0000000000 --- a/samples/Lua/TestLua/proj.android/build_native.cmd +++ /dev/null @@ -1,93 +0,0 @@ -@echo off - -set APPNAME="TestLua" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy common luaScript -xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets - -rem remove test_image_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_image_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba8888.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgb888.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_rgba4444.pvr.gz -del /f /q %APP_ANDROID_ROOT%\assets\Images\test_1021x1024_a8.pvr.gz - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.android/build_native.sh b/samples/Lua/TestLua/proj.android/build_native.sh deleted file mode 100755 index 1774c62c32..0000000000 --- a/samples/Lua/TestLua/proj.android/build_native.sh +++ /dev/null @@ -1,143 +0,0 @@ -APPNAME="TestLua" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=`sed '/\./d' "$_LOCALPROPERTIES_FILE"` - for line in "$_PROPERTIES"; do - declare "$line"; - done -fi - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT"/samples/Lua/"$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT"/samples/Lua/"$APPNAME"/proj.android -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/../../Cpp/TestCpp/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy luaScript -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy common luaScript -for file in "$APP_ROOT"/../../../cocos/scripting/lua/script/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# remove test_image_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_image_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba8888.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgb888.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba4444.pvr.gz -rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_a8.pvr.gz - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi From 5d931dab644a8c8e882d7af854adb814e17edf10 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 30 Oct 2013 18:31:59 +0800 Subject: [PATCH 286/557] Update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 8fc9c367ee..158e288955 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -15,6 +15,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [NEW] Added xlargeScreens="true" to supports-screens + [NEW] Added build/android-build.py to build all Android samples [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] From 1f07a659a6dda6add0c590bf992f1e521fe67315 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 09:49:04 +0800 Subject: [PATCH 287/557] issue #3069:Modify layer lua register and add some compatible lua binding functions --- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../lua/bindings/lua_cocos2dx_manual.cpp | 793 +++++++++++++++++- .../PerformanceTest/PerformanceSpriteTest.cpp | 17 +- tools/tolua/cocos2dx_extension.ini | 2 +- 4 files changed, 797 insertions(+), 17 deletions(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index c661a05129..3237461ed0 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -1475f1478d176a00cc8d0f9b3302881dee7a8437 \ No newline at end of file +d88cc721a9477ddfd6f690121991a620cbd260e6 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp index cb3ab58888..7e5a38abb1 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp @@ -514,6 +514,709 @@ tolua_lerror: #endif } + +static int executeScriptTouchHandler(Layer* layer, EventTouch::EventCode eventType, Touch* touch) +{ + TouchScriptData data(eventType, layer, touch); + ScriptEvent event(kTouchEvent, &data); + return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); +} + +static int executeScriptTouchesHandler(Layer* layer, EventTouch::EventCode eventType, const std::vector& touches) +{ + TouchesScriptData data(eventType, layer, touches); + ScriptEvent event(kTouchesEvent, &data); + return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); +} + +static void setTouchEnabledForLayer(Layer* layer, bool enabled) +{ + if (nullptr == layer) + return; + + auto dict = static_cast(layer->getUserObject()); + if (dict == nullptr) + { + dict = Dictionary::create(); + layer->setUserObject(dict); + } + + dict->setObject(Bool::create(enabled), "touchEnabled"); + + auto touchListenerAllAtOnce = static_cast(dict->objectForKey("touchListenerAllAtOnce")); + auto touchListenerOneByOne = static_cast(dict->objectForKey("touchListenerOneByOne")); + auto touchMode = static_cast(dict->objectForKey("touchMode")); + auto swallowTouches = static_cast(dict->objectForKey("swallowTouches")); + + auto dispatcher = layer->getEventDispatcher(); + if (nullptr != dispatcher) + { + dispatcher->removeEventListener(touchListenerAllAtOnce); + dispatcher->removeEventListener(touchListenerOneByOne); + } + + if (enabled) + { + if (touchMode == nullptr || touchMode->getValue() == (int)Touch::DispatchMode::ALL_AT_ONCE) + { + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = [layer](const std::vector& touches, Event* event){ + executeScriptTouchesHandler(layer, EventTouch::EventCode::BEGAN, touches); + }; + listener->onTouchesMoved = [layer](const std::vector& touches, Event* event){ + executeScriptTouchesHandler(layer, EventTouch::EventCode::MOVED, touches); + }; + listener->onTouchesEnded = [layer](const std::vector& touches, Event* event){ + executeScriptTouchesHandler(layer, EventTouch::EventCode::ENDED, touches); + }; + listener->onTouchesCancelled = [layer](const std::vector& touches, Event* event){ + executeScriptTouchesHandler(layer, EventTouch::EventCode::CANCELLED, touches); + }; + + dispatcher->addEventListenerWithSceneGraphPriority(listener, layer); + + dict->setObject(listener, "touchListenerAllAtOnce"); + } + else + { + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(swallowTouches ? swallowTouches->getValue() : false); + listener->onTouchBegan = [layer](Touch* touch, Event* event) -> bool{ + return executeScriptTouchHandler(layer, EventTouch::EventCode::BEGAN, touch) == 0 ? false : true; + }; + listener->onTouchMoved = [layer](Touch* touch, Event* event){ + executeScriptTouchHandler(layer, EventTouch::EventCode::MOVED, touch); + }; + listener->onTouchEnded = [layer](Touch* touch, Event* event){ + executeScriptTouchHandler(layer, EventTouch::EventCode::ENDED, touch); + }; + listener->onTouchCancelled = [layer](Touch* touch, Event* event){ + executeScriptTouchHandler(layer, EventTouch::EventCode::CANCELLED, touch); + }; + + dispatcher->addEventListenerWithSceneGraphPriority(listener, layer); + + dict->setObject(listener, "touchListenerOneByOne"); + } + } + +} + +//Only for v2.x lua compatibility +static int lua_cocos2dx_Layer_setTouchPriority(lua_State* L) +{ + return 0; +} + +static int lua_cocos2dx_Layer_setTouchEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setTouchEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + { + goto tolua_lerror; + } +#endif + bool enabled = tolua_toboolean(L, 2, 0); + setTouchEnabledForLayer(self, enabled); + return 0; + } + + CCLOG("'setTouchEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setTouchEnabled'.",&tolua_err); + return 0; +#endif + +} + +static int lua_cocos2dx_Layer_isTouchEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_isTouchEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (0 == argc) + { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + Bool* enabled = static_cast(dict->objectForKey("touchEnabled")); + bool ret = enabled ? enabled->getValue() : false; + tolua_pushboolean(L, ret); + return 1; + } + + return 0; + } + + CCLOG("'isTouchEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'isTouchEnabled'.",&tolua_err); + return 0; +#endif + + +} + +static int lua_cocos2dx_Layer_setTouchMode(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setTouchMode'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + { + goto tolua_lerror; + } +#endif + int32_t mode = (int32_t)tolua_tonumber(L, 2, 0); + + auto dict = static_cast(self->getUserObject()); + if ( nullptr == dict) + { + dict = Dictionary::create(); + self->setUserObject(dict); + } + + Integer* touchModeObj = static_cast(dict->objectForKey("touchMode")); + int32_t touchMode = touchModeObj ? touchModeObj->getValue() : 0; + if (touchMode != mode) + { + dict->setObject(Integer::create(mode), "touchMode"); + Bool* enabled = static_cast(dict->objectForKey("touchEnabled")); + if (enabled && enabled->getValue()) + { + setTouchEnabledForLayer(self, false); + setTouchEnabledForLayer(self, true); + } + } + return 0; + } + + CCLOG("'setTouchMode' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setTouchMode'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_getTouchMode(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_getTouchMode'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (0 == argc) + { + int32_t ret = 0; + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + Integer* mode = static_cast(dict->objectForKey("touchMode")); + ret = mode ? mode->getValue() : 0; + tolua_pushnumber(L, (lua_Number)ret); + return 1; + } + + return 0; + } + + CCLOG("'getTouchMode' has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'getTouchMode'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_setSwallowsTouches(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setSwallowsTouches'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + + bool swallowsTouches = tolua_toboolean(L, 2, 0); + Bool* swallowsTouchesObj = nullptr; + + auto dict = static_cast(self->getUserObject()); + if (dict == nullptr) + { + dict = Dictionary::create(); + self->setUserObject(dict); + } + + swallowsTouchesObj = static_cast(dict->objectForKey("swallowTouches")); + bool oldSwallowsTouches = swallowsTouchesObj ? swallowsTouchesObj->getValue() : false; + + if (oldSwallowsTouches != swallowsTouches) + { + dict->setObject(Integer::create(swallowsTouches), "swallowTouches"); + Bool* enabled = static_cast(dict->objectForKey("touchEnabled")); + if (enabled && enabled->getValue()) + { + setTouchEnabledForLayer(self, false); + setTouchEnabledForLayer(self, true); + } + } + + return 0; + } + + CCLOG("'setSwallowsTouches' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setSwallowsTouches'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_isSwallowsTouches(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_isSwallowsTouches'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (0 == argc) + { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + Bool* swallowTouches = static_cast(dict->objectForKey("swallowTouches")); + bool ret = swallowTouches ? swallowTouches->getValue() : false; + lua_pushboolean(L, ret); + return 1; + } + return 0; + } + + CCLOG("'isSwallowsTouches' has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'isSwallowsTouches'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_setKeyboardEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setKeyboardEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + bool enabled = tolua_toboolean(L, 2, 0); + auto dict = static_cast(self->getUserObject()); + if (dict == nullptr) + { + dict = Dictionary::create(); + self->setUserObject(dict); + } + + dict->setObject(Bool::create(enabled), "keyboardEnabled"); + + auto keyboardListener = static_cast(dict->objectForKey("keyboardListener")); + + auto dispatcher = self->getEventDispatcher(); + dispatcher->removeEventListener(keyboardListener); + if (enabled) + { + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [self](EventKeyboard::KeyCode keyCode, Event* event){ + + }; + listener->onKeyReleased = [self](EventKeyboard::KeyCode keyCode, Event* event){ + KeypadScriptData data(keyCode, self); + ScriptEvent scriptEvent(kKeypadEvent,&data); + ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); + }; + CCLOG("come in the keyboardEnable"); + dispatcher->addEventListenerWithSceneGraphPriority(listener, self); + + dict->setObject(listener, "keyboardListener"); + } + return 0; + } + + CCLOG("'setKeyboardEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setKeyboardEnabled'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_isKeyboardEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_isKeyboardEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (0 == argc) + { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + Bool* enabled = static_cast(dict->objectForKey("keyboardEnabled")); + bool ret = enabled ? enabled->getValue() : false; + tolua_pushboolean(L, ret); + return 1; + } + return 0; + } + + CCLOG("'isKeyboardEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'isKeyboardEnabled'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_setAccelerometerEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setAccelerometerEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isboolean(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + bool enabled = tolua_toboolean(L, 2, 0); + auto dict = static_cast(self->getUserObject()); + if (dict == nullptr) + { + dict = Dictionary::create(); + self->setUserObject(dict); + } + + dict->setObject(Bool::create(enabled), "accelerometerEnabled"); + + auto accListener = static_cast(dict->objectForKey("accListener")); + + auto dispatcher = self->getEventDispatcher(); + dispatcher->removeEventListener(accListener); + + Device::setAccelerometerEnabled(enabled); + + if (enabled) + { + auto listener = EventListenerAcceleration::create([self](Acceleration* acc, Event* event){ + BasicScriptData data(self,(void*)acc); + ScriptEvent accEvent(kAccelerometerEvent,&data); + ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&accEvent); + }); + + dispatcher->addEventListenerWithSceneGraphPriority(listener, self); + + dict->setObject(listener, "accListener"); + } + + return 0; + } + + CCLOG("'setAccelerometerEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setAccelerometerEnabled'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_isAccelerometerEnabled(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_isAccelerometerEnabled'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (0 == argc) + { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + Bool* enabled = static_cast(dict->objectForKey("accelerometerEnabled")); + bool ret = enabled ? enabled->getValue() : false; + tolua_pushboolean(L, ret); + return 1; + } + + return 0; + } + + + CCLOG("'isAccelerometerEnabled' has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'isAccelerometerEnabled'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_Layer_setAccelerometerInterval(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + Layer* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"Layer",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Layer_setAccelerometerInterval'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + double interval = tolua_tonumber(L, 2, 0); + Device::setAccelerometerEnabled(interval); + return 0; + } + + CCLOG("'setAccelerometerInterval' has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setAccelerometerInterval'.",&tolua_err); + return 0; +#endif +} + + static int tolua_cocos2d_Layer_registerScriptTouchHandler(lua_State* tolua_S) { if (NULL == tolua_S) @@ -546,6 +1249,7 @@ static int tolua_cocos2d_Layer_registerScriptTouchHandler(lua_State* tolua_S) #endif LUA_FUNCTION handler = ( toluafix_ref_function(tolua_S,2,0)); bool isMultiTouches = false; + //Note:priority is useless int priority = 0; bool swallowTouches = true; @@ -579,9 +1283,43 @@ static int tolua_cocos2d_Layer_registerScriptTouchHandler(lua_State* tolua_S) Touch::DispatchMode touchesMode = Touch::DispatchMode::ALL_AT_ONCE; if (!isMultiTouches) touchesMode = Touch::DispatchMode::ONE_BY_ONE; - self->setTouchMode(touchesMode); -// self->setTouchPriority(priority); - self->setSwallowsTouches(swallowTouches); + + auto dict = static_cast(self->getUserObject()); + if (dict == nullptr) + { + dict = Dictionary::create(); + self->setUserObject(dict); + } + + auto touchModeobj = static_cast(dict->objectForKey("touchMode")); + auto swallowTouchesValue = static_cast(dict->objectForKey("swallowTouches")); + + //touch model + int32_t mode = touchModeobj?touchModeobj->getValue() : 0; + if (mode != (int)touchesMode) + { + dict->setObject(Integer::create((int)touchesMode), "touchMode"); + Bool* enabled = static_cast(dict->objectForKey("touchEnabled")); + if (enabled && enabled->getValue()) + { + setTouchEnabledForLayer(self, false); + setTouchEnabledForLayer(self, true); + } + } + + //swallowsTouches Obj + bool oldSwallowTouchesValue = swallowTouchesValue?swallowTouchesValue->getValue():false; + if (oldSwallowTouchesValue != swallowTouches) + { + dict->setObject(Integer::create(swallowTouches), "swallowTouches"); + Bool* enabled = static_cast(dict->objectForKey("touchEnabled")); + if (enabled && enabled->getValue()) + { + setTouchEnabledForLayer(self, false); + setTouchEnabledForLayer(self, true); + } + } + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, ScriptHandlerMgr::HandlerType::TOUCHES); return 0; } @@ -622,6 +1360,19 @@ static int tolua_cocos2d_Layer_unregisterScriptTouchHandler(lua_State* tolua_S) if (0 == argc) { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + auto touchListenerAllAtOnce = static_cast(dict->objectForKey("touchListenerAllAtOnce")); + auto touchListenerOneByOne = static_cast(dict->objectForKey("touchListenerOneByOne")); + auto dispatcher = self->getEventDispatcher(); + if (nullptr != dispatcher) + { + dispatcher->removeEventListener(touchListenerAllAtOnce); + dispatcher->removeEventListener(touchListenerOneByOne); + } + } + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, ScriptHandlerMgr::HandlerType::TOUCHES); return 0; } @@ -710,6 +1461,18 @@ static int tolua_cocos2d_Layer_unregisterScriptKeypadHandler(lua_State* tolua_S) if (0 == argc) { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + auto keyboardListener = static_cast(dict->objectForKey("keyboardListener")); + + auto dispatcher = self->getEventDispatcher(); + if (dispatcher != nullptr) + { + dispatcher->removeEventListener(keyboardListener); + } + } + ScriptHandlerMgr::getInstance()->removeObjectHandler(self, ScriptHandlerMgr::HandlerType::KEYPAD); return 0; } @@ -795,6 +1558,18 @@ static int tolua_cocos2d_Layer_unregisterScriptAccelerateHandler(lua_State* tolu if (0 == argc) { + auto dict = static_cast(self->getUserObject()); + if (dict != nullptr) + { + auto accListener = static_cast(dict->objectForKey("accListener")); + + auto dispatcher = self->getEventDispatcher(); + if (dispatcher != nullptr) + { + dispatcher->removeEventListener(accListener); + } + } + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, ScriptHandlerMgr::HandlerType::ACCELEROMETER); return 0; } @@ -2503,6 +3278,18 @@ static void extendLayer(lua_State* tolua_S) lua_pushstring(tolua_S, "unregisterScriptAccelerateHandler"); lua_pushcfunction(tolua_S, tolua_cocos2d_Layer_unregisterScriptAccelerateHandler); lua_rawset(tolua_S, -3); + + tolua_function(tolua_S, "setTouchEnabled", lua_cocos2dx_Layer_setTouchEnabled); + tolua_function(tolua_S, "isTouchEnabled", lua_cocos2dx_Layer_isTouchEnabled); + tolua_function(tolua_S, "setTouchMode", lua_cocos2dx_Layer_setTouchMode); + tolua_function(tolua_S, "getTouchMode", lua_cocos2dx_Layer_getTouchMode); + tolua_function(tolua_S, "setSwallowsTouches", lua_cocos2dx_Layer_setSwallowsTouches); + tolua_function(tolua_S, "isSwallowsTouches", lua_cocos2dx_Layer_isSwallowsTouches); + tolua_function(tolua_S, "setKeyboardEnabled", lua_cocos2dx_Layer_setKeyboardEnabled); + tolua_function(tolua_S, "isKeyboardEnabled", lua_cocos2dx_Layer_isKeyboardEnabled); + tolua_function(tolua_S, "setAccelerometerEnabled", lua_cocos2dx_Layer_setAccelerometerEnabled); + tolua_function(tolua_S, "isAccelerometerEnabled", lua_cocos2dx_Layer_isAccelerometerEnabled); + tolua_function(tolua_S, "setAccelerometerInterval", lua_cocos2dx_Layer_setAccelerometerInterval); } } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index b00cef317c..7e290e5e5b 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -480,19 +480,12 @@ void SpriteMainScene::dumpProfilerFPS() float maxFPS = *iter; float totalFPS = 0.0f; float averagerFPS = 0.0f; - for (; iter != _vecFPS.end(); ++iter) + for (auto fps : _vecFPS) { - if (minFPS > *iter) - { - minFPS = *iter; - } - - if (maxFPS < *iter) - { - maxFPS = *iter; - } - - totalFPS += *iter; + CCLOG("fps is :%f\n",fps); + minFPS = std::min(minFPS, fps); + maxFPS = std::max(maxFPS, fps); + totalFPS += fps; } averagerFPS = totalFPS / _vecFPS.size(); diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index 67d87c51d6..40cac55aac 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,7 +13,7 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT cxxgenerator_headers = From 12db6a32ab7f4e651ae4baa166db7747d9d62cb9 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 29 Oct 2013 20:25:03 +0800 Subject: [PATCH 288/557] issues #2893: 1.Texture atlas are create on demand, based on the characters used in the label. 2.Create Quads (and not sprites) for each letter. --- cocos/2d/CCDirector.cpp | 3 + cocos/2d/CCFont.cpp | 16 +- cocos/2d/CCFontAtlas.cpp | 164 ++++++- cocos/2d/CCFontAtlas.h | 13 +- cocos/2d/CCFontAtlasFactory.cpp | 11 +- cocos/2d/CCFontFNT.cpp | 7 +- cocos/2d/CCFontFreeType.cpp | 132 +++--- cocos/2d/CCFontFreeType.h | 13 +- cocos/2d/CCLabel.cpp | 400 +++++++++--------- cocos/2d/CCLabel.h | 35 +- cocos/2d/CCLabelTextFormatProtocol.h | 24 +- cocos/2d/CCLabelTextFormatter.cpp | 78 ++-- .../Classes/LabelTest/LabelTestNew.cpp | 8 +- 13 files changed, 550 insertions(+), 354 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index ef8b38f423..7255659d07 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -60,6 +60,7 @@ THE SOFTWARE. #include "CCEGLView.h" #include "CCConfiguration.h" #include "CCEventDispatcher.h" +#include "CCFontFreeType.h" /** Position of the FPS @@ -686,6 +687,8 @@ void Director::purgeDirector() // purge bitmap cache LabelBMFont::purgeCachedData(); + FontFreeType::shutdownFreeType(); + // purge all managed caches DrawPrimitives::free(); AnimationCache::destroyInstance(); diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 63fe7af7d1..cad004a906 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -73,13 +73,15 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG break; default: - - int lenght = strlen(customGlyphs); - _customGlyphs = new char [lenght + 2]; - memcpy(_customGlyphs, customGlyphs, lenght); - - _customGlyphs[lenght] = 0; - _customGlyphs[lenght+1] = 0; + if (customGlyphs) + { + int lenght = strlen(customGlyphs); + _customGlyphs = new char [lenght + 2]; + memcpy(_customGlyphs, customGlyphs, lenght); + + _customGlyphs[lenght] = 0; + _customGlyphs[lenght+1] = 0; + } break; } diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 6f8adeaa43..2879ac72de 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -9,18 +9,41 @@ #include "cocos2d.h" #include "CCFontAtlas.h" #include "CCFont.h" +#include "CCFontFreeType.h" NS_CC_BEGIN -FontAtlas::FontAtlas(Font &theFont) : _font(theFont) +FontAtlas::FontAtlas(Font &theFont) : +_font(theFont), +_currentPageData(nullptr) { _font.retain(); + + FontFreeType* fontTTf = dynamic_cast(&_font); + if (fontTTf && fontTTf->isDynamicGlyphCollection()) + { + _currentPageLineHeight = _font.getFontMaxHeight(); + _commonLineHeight = _currentPageLineHeight * 0.8f; + Texture2D * tex = new Texture2D; + _currentPage = 0; + _currentPageOrigX = 0; + _currentPageOrigY = 0; + _letterPadding = 5; + _currentPageDataSize = (1024 * 1024 * 4); + + _currentPageData = new unsigned char[_currentPageDataSize]; + memset(_currentPageData, 0, _currentPageDataSize); + addTexture(*tex,0); + } } FontAtlas::~FontAtlas() { _font.release(); relaseTextures(); + + if(_currentPageData) + delete []_currentPageData; } void FontAtlas::relaseTextures() @@ -51,6 +74,145 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL } } +bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) +{ + if(_currentPageData == nullptr) + return false; + + FontFreeType* fontTTf = (FontFreeType*)&_font; + + std::vector fontDefs; + int length = cc_wcslen(utf16String); + + //find out new letter + for (int i = 0; i < length; ++i) + { + auto outIterator = _fontLetterDefinitions.find(utf16String[i]); + + if (outIterator == _fontLetterDefinitions.end()) + { + Rect tempRect; + + FontLetterDefinition tempDef; + tempDef.offsetX = 0; + tempDef.anchorX = 0.0f; + tempDef.anchorY = 1.0f; + + if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect)) + { + //log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[i], _fontName.c_str()); + tempDef.validDefinition = false; + tempDef.letteCharUTF16 = utf16String[i]; + tempDef.commonLineHeight = 0; + tempDef.width = 0; + tempDef.height = 0; + tempDef.U = 0; + tempDef.V = 0; + tempDef.offsetY = 0; + tempDef.textureID = 0; + } + else + { + tempDef.validDefinition = true; + tempDef.letteCharUTF16 = utf16String[i]; + tempDef.width = tempRect.size.width + _letterPadding; + tempDef.height = _currentPageLineHeight - 1; + tempDef.offsetY = tempRect.origin.y; + tempDef.commonLineHeight = _currentPageLineHeight; + + } + fontDefs.push_back(tempDef); + } + } + + float scaleFactor = CC_CONTENT_SCALE_FACTOR(); + int newLetterCount = fontDefs.size(); + float glyphWidth; + for (int i = 0; i < newLetterCount; ++i) + { + if (fontDefs[i].validDefinition) + { + _currentPageOrigX += _letterPadding; + glyphWidth = fontDefs[i].width - _letterPadding; + + if (_currentPageOrigX + glyphWidth > 1024) + { + _currentPageOrigY += _currentPageLineHeight; + if(_currentPageOrigY >= 1024) + { + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); + _currentPageOrigX = 0; + _currentPageOrigY = 0; + + delete []_currentPageData; + _currentPageData = new unsigned char[_currentPageDataSize]; + if(_currentPageData == nullptr) + return false; + memset(_currentPageData, 0, _currentPageDataSize); + _currentPage++; + addTexture(*(new Texture2D),_currentPage); + } + } + renderCharAt(fontDefs[i].letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,1024); + + fontDefs[i].U = _currentPageOrigX - 1; + fontDefs[i].V = _currentPageOrigY; + fontDefs[i].textureID = _currentPage; + // take from pixels to points + fontDefs[i].width = fontDefs[i].width / scaleFactor; + fontDefs[i].height = fontDefs[i].height / scaleFactor; + fontDefs[i].U = fontDefs[i].U / scaleFactor; + fontDefs[i].V = fontDefs[i].V / scaleFactor; + } + else + glyphWidth = 0; + + this->addLetterDefinition(fontDefs[i]); + _currentPageOrigX += glyphWidth; + } + if(newLetterCount > 0) + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); + return true; +} + +bool FontAtlas::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + // get the glyph's bitmap + sourceBitmap = _font.getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if (!sourceBitmap) + return false; + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; + *(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp; + + iX += 1; + } + + iX = posX; + iY += 1; + } + + //everything good + return true; +} + void FontAtlas::addTexture(Texture2D &texture, int slot) { texture.retain(); diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 376da41fa9..b1b6eaa9b4 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -63,6 +63,8 @@ public: void addLetterDefinition(const FontLetterDefinition &letterDefinition); bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition); + bool prepareLetterDefinitions(unsigned short *utf16String); + void addTexture(Texture2D &texture, int slot); float getCommonLineHeight() const; void setCommonLineHeight(float newHeight); @@ -71,13 +73,22 @@ public: Font & getFont() const; private: - + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); + void relaseTextures(); std::map _atlasTextures; std::map _fontLetterDefinitions; float _commonLineHeight; Font & _font; + // Dynamic GlyphCollection related stuff + int _currentPage; + unsigned char *_currentPageData; + int _currentPageDataSize; + float _currentPageOrigX; + float _currentPageOrigY; + float _currentPageLineHeight; + float _letterPadding; }; diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index d80c050def..2b8e0b4ca4 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -16,11 +16,6 @@ NS_CC_BEGIN FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - if( glyphs == GlyphCollection::DYNAMIC ) - { - log("ERROR: GlyphCollection::DYNAMIC is not supported yet!"); - return nullptr; - } Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); if (font) @@ -34,7 +29,11 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) Font *font = Font::createWithFNT(fntFilePath); if(font) - return font->createFontAtlas(); + { + FontAtlas * atlas = font->createFontAtlas(); + font->release(); + return atlas; + } else return nullptr; } diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index ebf7c876d7..cd1e586e62 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -38,8 +38,11 @@ FontFNT * FontFNT::create(const char* fntFilePath) FontFNT::~FontFNT() { - if (_configuration) + //_configuration release when execute LabelBMFont::purgeCachedData(); + /*if (_configuration) + { _configuration->release(); + }*/ } Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const @@ -176,7 +179,7 @@ FontAtlas * FontFNT::createFontAtlas() tempDefinition.anchorX = 0.5f; tempDefinition.anchorY = 0.5f; - + tempDefinition.validDefinition = true; // add the new definition tempAtlas->addLetterDefinition(tempDefinition); } diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index c0522f522b..3fbac58b5b 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -1,28 +1,29 @@ /**************************************************************************** - Copyright (c) 2013 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. - ****************************************************************************/ +Copyright (c) 2013 Zynga Inc. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ #include +#include #include "ccUTF8.h" #include "CCFontFreeType.h" @@ -38,14 +39,12 @@ bool FontFreeType::_FTInitialized = false; FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - if( glyphs == GlyphCollection::DYNAMIC ) - { - log("ERROR: GlyphCollection::DYNAMIC is not supported yet!"); - return nullptr; - } - - FontFreeType *tempFont = new FontFreeType(); + bool dynamicGlyphCollection = false; + if(glyphs == GlyphCollection::DYNAMIC) + dynamicGlyphCollection = true; + FontFreeType *tempFont = new FontFreeType(dynamicGlyphCollection); + if (!tempFont) return nullptr; @@ -56,7 +55,6 @@ FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, G delete tempFont; return nullptr; } - return tempFont; } @@ -79,6 +77,7 @@ void FontFreeType::shutdownFreeType() if (_FTInitialized == true) { FT_Done_FreeType(_FTlibrary); + _FTInitialized = false; } } @@ -88,34 +87,35 @@ FT_Library FontFreeType::getFTLibrary() return _FTlibrary; } -FontFreeType::FontFreeType() : _letterPadding(5) +FontFreeType::FontFreeType(bool dynamicGlyphCollection) + : _letterPadding(5) + ,_ttfData(nullptr), + _dynamicGlyphCollection(dynamicGlyphCollection), + _fontRef(nullptr) { } bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { - int dpi = 72; - - int len = 0; - unsigned char* data = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); - - if (!data) - return false; - - // create the new face FT_Face face; - - // create the face from the data - if (FT_New_Memory_Face(getFTLibrary(), data, len, 0, &face )) + + int len = 0; + _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); + if (!_ttfData) return false; - + + // create the face from the data + if (FT_New_Memory_Face(getFTLibrary(), _ttfData, len, 0, &face )) + return false; + //we want to use unicode if (FT_Select_Charmap(face, FT_ENCODING_UNICODE)) return false; - + // set the requested font size - int fontSizePoints = (int)(64.f * fontSize); - if (FT_Set_Char_Size(face, fontSizePoints, fontSizePoints, dpi, dpi)) + int dpi = 72; + int fontSizePoints = (int)(64.f * fontSize); + if (FT_Set_Char_Size(face, fontSizePoints, fontSizePoints, dpi, dpi)) return false; // store the face globally @@ -132,20 +132,38 @@ FontFreeType::~FontFreeType() { // release the font // TO DO + if (_fontRef) + { + FT_Done_Face(_fontRef); + } + if (_ttfData) + { + delete _ttfData; + _ttfData = nullptr; + } } FontAtlas * FontFreeType::createFontAtlas() { - FontDefinitionTTF *def = FontDefinitionTTF::create(this); - - if (!def) - return nullptr; - - FontAtlas *atlas = def->createFontAtlas(); - - // release the font definition, we don't need it anymore - def->release(); - return atlas; + if (_dynamicGlyphCollection) + { + FontAtlas *atlas = new FontAtlas(*this); + this->release(); + return atlas; + } + else + { + FontDefinitionTTF *def = FontDefinitionTTF::create(this); + + if (!def) + return nullptr; + + FontAtlas *atlas = def->createFontAtlas(); + + // release the font definition, we don't need it anymore + def->release(); + return atlas; + } } bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index 83455d801a..cdf3d1a1ac 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -47,20 +47,22 @@ public: virtual int getFontMaxHeight() const override; virtual int getLetterPadding() const override; - + bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; + + inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} + static void shutdownFreeType(); + protected: - FontFreeType(); + FontFreeType(bool dynamicGlyphCollection = false); virtual ~FontFreeType(); bool createFontObject(const std::string &fontName, int fontSize); private: bool initFreeType(); - void shutdownFreeType(); FT_Library getFTLibrary(); - bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; int getAdvanceForChar(unsigned short theChar) const; int getBearingXForChar(unsigned short theChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; @@ -70,7 +72,8 @@ private: FT_Face _fontRef; const int _letterPadding; std::string _fontName; - + unsigned char* _ttfData; + bool _dynamicGlyphCollection; }; NS_CC_END diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 6164811045..a7ed8e2978 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -46,8 +46,6 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo } return nullptr; - - return 0; } Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) @@ -95,8 +93,8 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li } Label::Label(FontAtlas *atlas, TextHAlignment alignment) -: _currentUTF8String(0) -, _originalUTF8String(0) +: _currentUTF16String(0) +, _originalUTF16String(0) , _fontAtlas(atlas) , _alignment(alignment) , _lineBreakWithoutSpaces(false) @@ -107,32 +105,35 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment) , _cascadeOpacityEnabled(true) , _displayedOpacity(255) , _realOpacity(255) -, _isOpacityModifyRGB(false) +, _isOpacityModifyRGB(true) +,_reusedLetter(nullptr) { } Label::~Label() -{ - CC_SAFE_RELEASE(_spriteArray); - CC_SAFE_RELEASE(_spriteArrayCache); - - if (_currentUTF8String) - delete [] _currentUTF8String; - +{ + if (_currentUTF16String) + delete [] _currentUTF16String; + if (_originalUTF16String) + delete [] _originalUTF16String; if (_advances) delete [] _advances; if (_fontAtlas) FontAtlasCache::releaseFontAtlas(_fontAtlas); + + delete _reusedLetter; } bool Label::init() -{ - _spriteArray = Array::createWithCapacity(30); - _spriteArrayCache = Array::createWithCapacity(30); - - _spriteArray->retain(); - _spriteArrayCache->retain(); +{ + if(_fontAtlas) + { + _reusedLetter = new Sprite; + _reusedLetter->initWithTexture(&_fontAtlas->getTexture(0)); + _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); + return SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); + } return true; } @@ -151,14 +152,10 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment // reset the string resetCurrentString(); - _width = lineWidth; _alignment = alignment; _lineBreakWithoutSpaces = lineBreakWithoutSpaces; - // release all the sprites - moveAllSpritesToCache(); - // store locally common line height _commonLineHeight = _fontAtlas->getCommonLineHeight(); if (_commonLineHeight <= 0) @@ -169,11 +166,8 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment if(!utf16String) return false; - numLetter = cc_wcslen(utf16String); - SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter); _cascadeColorEnabled = true; - // setCurrentString(utf16String); setOriginalString(utf16String); @@ -247,30 +241,56 @@ void Label::setScaleY(float scaleY) } void Label::alignText() -{ - hideAllLetters(); - LabelTextFormatter::createStringSprites(this); - - if( LabelTextFormatter::multilineText(this) ) - { - hideAllLetters(); +{ + if(_textureAtlas) + _textureAtlas->removeAllQuads(); + _fontAtlas->prepareLetterDefinitions(_currentUTF16String); + LabelTextFormatter::createStringSprites(this); + if( LabelTextFormatter::multilineText(this) ) LabelTextFormatter::createStringSprites(this); - } LabelTextFormatter::alignText(this); -} - -void Label::hideAllLetters() -{ - Object* Obj = NULL; - CCARRAY_FOREACH(_spriteArray, Obj) + + int strLen = cc_wcslen(_currentUTF16String); + if (_children && _children->count() != 0) { - ((Sprite *)Obj)->setVisible(false); + Object* child; + CCARRAY_FOREACH(_children, child) + { + Node* pNode = static_cast( child ); + if (pNode) + { + int tag = pNode->getTag(); + if(tag < 0 || tag >= strLen) + SpriteBatchNode::removeChild(pNode, true); + } + } } - - CCARRAY_FOREACH(_spriteArrayCache, Obj) - { - ((Sprite *)Obj)->setVisible(false); + _reusedLetter->setBatchNode(nullptr); + + int vaildIndex = 0; + Sprite* child = nullptr; + Rect uvRect; + for (int ctr = 0; ctr < strLen; ++ctr) + { + if (_lettersInfo[ctr].def.validDefinition) + { + child = (Sprite*)this->getChildByTag(ctr); + if (child) + { + uvRect.size.height = _lettersInfo[ctr].def.height; + uvRect.size.width = _lettersInfo[ctr].def.width; + uvRect.origin.x = _lettersInfo[ctr].def.U; + uvRect.origin.y = _lettersInfo[ctr].def.V; + + child->setTexture(&_fontAtlas->getTexture(_lettersInfo[ctr].def.textureID)); + child->setTextureRect(uvRect); + } + + updateSpriteWithLetterDefinition(_reusedLetter,_lettersInfo[ctr].def,&_fontAtlas->getTexture(_lettersInfo[ctr].def.textureID)); + _reusedLetter->setPosition(_lettersInfo[ctr].position); + insertQuadFromSprite(_reusedLetter,vaildIndex++); + } } } @@ -295,17 +315,17 @@ bool Label::computeAdvancesForString(unsigned short int *stringToRender) bool Label::setOriginalString(unsigned short *stringToSet) { - if (_originalUTF8String) + if (_originalUTF16String) { - delete [] _originalUTF8String; - _originalUTF8String = 0; + delete [] _originalUTF16String; + _originalUTF16String = 0; } int newStringLenght = cc_wcslen(stringToSet); - _originalUTF8String = new unsigned short int [newStringLenght + 1]; - memset(_originalUTF8String, 0, (newStringLenght + 1) * 2); - memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2)); - _originalUTF8String[newStringLenght] = 0; + _originalUTF16String = new unsigned short int [newStringLenght + 1]; + memset(_originalUTF16String, 0, (newStringLenght + 1) * 2); + memcpy(_originalUTF16String, stringToSet, (newStringLenght * 2)); + _originalUTF16String[newStringLenght] = 0; return true; } @@ -313,65 +333,36 @@ bool Label::setOriginalString(unsigned short *stringToSet) bool Label::setCurrentString(unsigned short *stringToSet) { // set the new string - if (_currentUTF8String) + if (_currentUTF16String) { - delete [] _currentUTF8String; - _currentUTF8String = 0; + delete [] _currentUTF16String; + _currentUTF16String = 0; } // - _currentUTF8String = stringToSet; + _currentUTF16String = stringToSet; // compute the advances return computeAdvancesForString(stringToSet); } void Label::resetCurrentString() { - if ((!_currentUTF8String) && (!_originalUTF8String)) + if ((!_currentUTF16String) && (!_originalUTF16String)) return; // set the new string - if (_currentUTF8String) + if (_currentUTF16String) { - delete [] _currentUTF8String; - _currentUTF8String = 0; + delete [] _currentUTF16String; + _currentUTF16String = 0; } - int stringLenght = cc_wcslen(_originalUTF8String); - _currentUTF8String = new unsigned short int [stringLenght + 1]; - memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2); - _currentUTF8String[stringLenght] = 0; + int stringLenght = cc_wcslen(_originalUTF16String); + _currentUTF16String = new unsigned short int [stringLenght + 1]; + memcpy(_currentUTF16String, _originalUTF16String, stringLenght * 2); + _currentUTF16String[stringLenght] = 0; } -Sprite * Label::createNewSpriteFromLetterDefinition(const FontLetterDefinition &theDefinition, Texture2D *theTexture) -{ - Rect uvRect; - uvRect.size.height = theDefinition.height; - uvRect.size.width = theDefinition.width; - uvRect.origin.x = theDefinition.U; - uvRect.origin.y = theDefinition.V; - - SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect); - Sprite *tempSprite = getSprite(); - - if (!tempSprite) - return 0; - - tempSprite->initWithSpriteFrame(pFrame); - tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); - tempSprite->setBatchNode(this); - - // Apply label properties - tempSprite->setOpacityModifyRGB(_isOpacityModifyRGB); - - // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - tempSprite->updateDisplayedColor(_displayedColor); - tempSprite->updateDisplayedOpacity(_displayedOpacity); - - - return tempSprite; -} - Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const FontLetterDefinition &theDefinition, Texture2D *theTexture) { if (!spriteToUpdate) @@ -389,143 +380,93 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); if (frame) { + spriteToUpdate->setBatchNode(this); spriteToUpdate->setTexture(theTexture); spriteToUpdate->setDisplayFrame(frame); - spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); - spriteToUpdate->setBatchNode(this); - } + spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); + } return spriteToUpdate; } } -Sprite * Label::getSpriteForLetter(unsigned short int newLetter) +bool Label::recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) { - if (!_fontAtlas) - return 0; + if (spriteIndex >= _lettersInfo.size()) + { + LetterInfo tmpInfo; + _lettersInfo.push_back(tmpInfo); + } + + _fontAtlas->getLetterDefinitionForChar(theChar, _lettersInfo[spriteIndex].def); + _lettersInfo[spriteIndex].position = point; + _lettersInfo[spriteIndex].contentSize.width = _lettersInfo[spriteIndex].def.width; + _lettersInfo[spriteIndex].contentSize.height = _lettersInfo[spriteIndex].def.height; + + return _lettersInfo[spriteIndex].def.validDefinition; +} + +bool Label::recordPlaceholderInfo(int spriteIndex) +{ + if (spriteIndex >= _lettersInfo.size()) + { + LetterInfo tmpInfo; + _lettersInfo.push_back(tmpInfo); + } + + _lettersInfo[spriteIndex].def.validDefinition = false; - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); - if (validDefinition) - { - Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); - this->addChild(newSprite); - return newSprite; - } - else - { - return 0; - } + return false; } -Sprite * Label::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter) +void Label::addChild(Node * child, int zOrder/* =0 */, int tag/* =0 */) { - if (!spriteToUpdate || !_fontAtlas) - return 0; - else - { - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); - if (validDefinition) - { - Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); - return pNewSprite; - } - else - { - return 0; - } - } -} - -void Label::moveAllSpritesToCache() -{ - Object* pObj = NULL; - CCARRAY_FOREACH(_spriteArray, pObj) - { - ((Sprite *)pObj)->removeFromParent(); - _spriteArrayCache->addObject(pObj); - } - - _spriteArray->removeAllObjects(); -} - -Sprite * Label::getSprite() -{ - if (_spriteArrayCache->count()) - { - Sprite *retSprite = static_cast(_spriteArrayCache->getLastObject()); - _spriteArrayCache->removeLastObject(); - return retSprite; - } - else - { - Sprite *retSprite = new Sprite; - return retSprite; - } + CCASSERT(0, "addChild: is not supported on Label."); } ///// PROTOCOL STUFF -Sprite * Label::getSpriteChild(int ID) const +Sprite * Label::getLetterAt(int ID) { - Object* pObj = NULL; - CCARRAY_FOREACH(_spriteArray, pObj) - { - Sprite *pSprite = (Sprite *)pObj; - if ( pSprite->getTag() == ID) + if (ID < getStringLenght()) + { + if(_lettersInfo[ID].def.validDefinition == false) + return nullptr; + + Sprite* sp = static_cast(this->getChildByTag(ID)); + + if (!sp) { - return pSprite; + Rect uvRect; + uvRect.size.height = _lettersInfo[ID].def.height; + uvRect.size.width = _lettersInfo[ID].def.width; + uvRect.origin.x = _lettersInfo[ID].def.U; + uvRect.origin.y = _lettersInfo[ID].def.V; + + sp = new Sprite(); + sp->initWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); + sp->setBatchNode(this); + sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); + sp->setPosition(_lettersInfo[ID].position); + sp->setOpacity(_realOpacity); + + this->addSpriteWithoutQuad(sp, ID, ID); + sp->release(); } - } - return 0; -} - -Array* Label::getChildrenLetters() const -{ - return _spriteArray; -} - -Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint) -{ - // ret sprite - Sprite *retSprite = 0; - - // look for already existing sprites - retSprite = getSpriteChild(spriteIndexHint); - - if (!retSprite) - { - retSprite = getSpriteForLetter(theChar); - if (!retSprite) - return 0; - - if (retSprite) - retSprite->setTag(spriteIndexHint); - - _spriteArray->addObject(retSprite); + return sp; } - // the sprite is now visible - retSprite->setVisible(true); - - // set the right texture letter to the sprite - updateSpriteForLetter(retSprite, theChar); - - // we are done here - return retSprite; + return nullptr; } -float Label::getLetterPosXLeft( Sprite* sp ) const +float Label::getLetterPosXLeft( int index ) const { - float scaleX = _scaleX; - return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); + return _lettersInfo[index].position.x * _scaleX - (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); } -float Label::getLetterPosXRight( Sprite* sp ) const +float Label::getLetterPosXRight( int index ) const { - float scaleX = _scaleX; - return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); + return _lettersInfo[index].position.x * _scaleX + (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); } int Label::getCommonLineHeight() const @@ -586,14 +527,14 @@ int Label::getStringNumLines() const { int quantityOfLines = 1; - unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; + unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; if (stringLen == 0) return (-1); // count number of lines for (unsigned int i = 0; i < stringLen - 1; ++i) { - unsigned short c = _currentUTF8String[i]; + unsigned short c = _currentUTF16String[i]; if (c == '\n') { quantityOfLines++; @@ -605,17 +546,17 @@ int Label::getStringNumLines() const int Label::getStringLenght() const { - return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; + return _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; } unsigned short Label::getCharAtStringPosition(int position) const { - return _currentUTF8String[position]; + return _currentUTF16String[position]; } unsigned short * Label::getUTF8String() const { - return _currentUTF8String; + return _currentUTF16String; } void Label::assignNewUTF8String(unsigned short *newString) @@ -677,6 +618,7 @@ void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) } } } + _reusedLetter->setOpacityModifyRGB(true); } unsigned char Label::getOpacity() const @@ -692,7 +634,7 @@ unsigned char Label::getDisplayedOpacity() const void Label::setOpacity(GLubyte opacity) { _displayedOpacity = _realOpacity = opacity; - + _reusedLetter->setOpacity(opacity); if( _cascadeOpacityEnabled ) { GLubyte parentOpacity = 255; RGBAProtocol* pParent = dynamic_cast(_parent); @@ -713,6 +655,26 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity) Sprite *item = static_cast( pObj ); item->updateDisplayedOpacity(_displayedOpacity); } + //if (_cascadeOpacityEnabled) + { + V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); + int count = _textureAtlas->getTotalQuads(); + Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); + if (_isOpacityModifyRGB) + { + color4.r *= _displayedOpacity/255.0f; + color4.g *= _displayedOpacity/255.0f; + color4.b *= _displayedOpacity/255.0f; + } + for (int index=0; indexupdateQuad(&quads[index], index); + } + } } bool Label::isCascadeOpacityEnabled() const @@ -738,7 +700,7 @@ const Color3B& Label::getDisplayedColor() const void Label::setColor(const Color3B& color) { _displayedColor = _realColor = color; - + _reusedLetter->setColor(color); if( _cascadeColorEnabled ) { Color3B parentColor = Color3B::WHITE; @@ -763,6 +725,26 @@ void Label::updateDisplayedColor(const Color3B& parentColor) Sprite *item = static_cast( pObj ); item->updateDisplayedColor(_displayedColor); } + + V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); + int count = _textureAtlas->getTotalQuads(); + Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); + + // special opacity for premultiplied textures + if (_isOpacityModifyRGB) + { + color4.r *= _displayedOpacity/255.0f; + color4.g *= _displayedOpacity/255.0f; + color4.b *= _displayedOpacity/255.0f; + } + for (int index=0; indexupdateQuad(&quads[index], index); + } } bool Label::isCascadeColorEnabled() const diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index e65c27eb7b..e9e56e31ca 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -82,12 +82,13 @@ public: virtual unsigned char getDisplayedOpacity() const override; // CCLabelTextFormat protocol implementation - virtual Sprite * getSpriteChild(int ID) const override; - virtual Array * getChildrenLetters() const override; - virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint) override; - virtual float getLetterPosXLeft( Sprite* sp ) const override; - virtual float getLetterPosXRight( Sprite* sp ) const override; + virtual std::vector *getLettersInfo(){ return &_lettersInfo; }; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex); + virtual bool recordPlaceholderInfo(int spriteIndex); + virtual float getLetterPosXLeft( int index ) const override; + virtual float getLetterPosXRight( int index ) const override; + virtual Sprite * getLetterAt(int ID) override; // font related stuff virtual int getCommonLineHeight() const override; @@ -113,7 +114,8 @@ public: // carloX const char * getString() const { return "not implemented"; } - + void addChild(Node * child, int zOrder=0, int tag=0); + private: /** * @js NA @@ -129,29 +131,26 @@ private: bool init(); - void alignText(); - void hideAllLetters(); - void moveAllSpritesToCache(); + void alignText(); bool computeAdvancesForString(unsigned short int *stringToRender); bool setCurrentString(unsigned short *stringToSet); bool setOriginalString(unsigned short *stringToSet); void resetCurrentString(); + + Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const FontLetterDefinition &theDefinition, Texture2D *theTexture); - Sprite * getSprite(); - Sprite * createNewSpriteFromLetterDefinition(const FontLetterDefinition &theDefinition, Texture2D *theTexture); - Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const FontLetterDefinition &theDefinition, Texture2D *theTexture); - Sprite * getSpriteForLetter(unsigned short int newLetter); - Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter); - Array * _spriteArray; - Array * _spriteArrayCache; + //! used for optimization + Sprite *_reusedLetter; + std::vector _lettersInfo; + float _commonLineHeight; bool _lineBreakWithoutSpaces; float _width; TextHAlignment _alignment; - unsigned short int * _currentUTF8String; - unsigned short int * _originalUTF8String; + unsigned short int * _currentUTF16String; + unsigned short int * _originalUTF16String; Size * _advances; FontAtlas * _fontAtlas; Color3B _displayedColor; diff --git a/cocos/2d/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h index 6208cfc493..c2027350fc 100644 --- a/cocos/2d/CCLabelTextFormatProtocol.h +++ b/cocos/2d/CCLabelTextFormatProtocol.h @@ -24,19 +24,31 @@ #ifndef _CCLabelTextFormatProtocol_h_ #define _CCLabelTextFormatProtocol_h_ +#include "CCFontAtlas.h" +#include NS_CC_BEGIN + +struct LetterInfo +{ + FontLetterDefinition def; + + Point position; + Size contentSize; + bool visible; +}; + class CC_DLL LabelTextFormatProtocol { public: - + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) = 0; + virtual bool recordPlaceholderInfo(int spriteIndex) = 0; + virtual std::vector *getLettersInfo() = 0; + virtual float getLetterPosXLeft(int index) const = 0; + virtual float getLetterPosXRight(int index) const = 0; // sprite related stuff - virtual cocos2d::Sprite *getSpriteChild(int ID) const = 0; - virtual cocos2d::Array *getChildrenLetters() const = 0; - virtual cocos2d::Sprite *getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0; - virtual float getLetterPosXLeft(cocos2d::Sprite* sp) const = 0; - virtual float getLetterPosXRight(cocos2d::Sprite* sp) const = 0; + virtual cocos2d::Sprite *getLetterAt(int ID) = 0; // font related stuff virtual int getCommonLineHeight() const = 0; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 0c674a5345..dc3bc82020 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -53,23 +53,26 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) float startOfLine = -1, startOfWord = -1; int skip = 0; - - Array* children = theLabel->getChildrenLetters(); - - for (int j = 0; j < children->count(); j++) - { - Sprite* characterSprite; - unsigned int justSkipped = 0; + + int strLen = theLabel->getStringLenght(); + std::vector *leterInfo = theLabel->getLettersInfo(); + int tIndex = 0; + + for (int j = 0; j < strLen; j++) + { + LetterInfo* info = &leterInfo->at(j+skip); + + unsigned int justSkipped = 0; - while (!(characterSprite = theLabel->getSpriteChild(j + skip + justSkipped))) + while (info->def.validDefinition == false) { justSkipped++; + info = &leterInfo->at( j+skip+justSkipped ); } - skip += justSkipped; - - if (!characterSprite->isVisible()) - continue; + tIndex = j + skip; + //if (!info->visible) + // continue; if (i >= stringLength) break; @@ -78,7 +81,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) if (!isStartOfWord) { - startOfWord = theLabel->getLetterPosXLeft( characterSprite ); + startOfWord = theLabel->getLetterPosXLeft( tIndex ); isStartOfWord = true; } @@ -110,7 +113,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) if (!startOfWord) { - startOfWord = theLabel->getLetterPosXLeft( characterSprite ); + startOfWord = theLabel->getLetterPosXLeft( tIndex ); isStartOfWord = true; } if (!startOfLine) @@ -133,7 +136,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) } // Out of bounds. - if (theLabel->getLetterPosXRight( characterSprite ) - startOfLine > theLabel->getMaxLineWidth()) + if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth()) { if (!theLabel->breakLineWithoutSpace()) { @@ -171,7 +174,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) if (!startOfWord) { - startOfWord = theLabel->getLetterPosXLeft( characterSprite ); + startOfWord = theLabel->getLetterPosXLeft( tIndex ); isStartOfWord = true; } if (!startOfLine) @@ -222,9 +225,10 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) int lineNumber = 0; int strLen = cc_wcslen(theLabel->getUTF8String()); vector lastLine; + std::vector *leterInfo = theLabel->getLettersInfo(); for (int ctr = 0; ctr <= strLen; ++ctr) { - unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr); + unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr); if (currentChar == '\n' || currentChar == 0) { @@ -240,11 +244,12 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) int index = i + lineLength - 1 + lineNumber; if (index < 0) continue; - Sprite* lastChar = theLabel->getSpriteChild(index); - if (lastChar == nullptr) + if(currentChar == 0) continue; - - lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width / 2.0f; + LetterInfo* info = &leterInfo->at( index ); + if(info->def.validDefinition == false) + continue; + lineWidth = info->position.x + info->contentSize.width /2.0f; float shift = 0; switch (theLabel->getTextAlignment()) @@ -266,10 +271,11 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) index = i + j + lineNumber; if (index < 0) continue; - Sprite* characterSprite = theLabel->getSpriteChild(index); - - if (characterSprite) - characterSprite->setPosition( characterSprite->getPosition() + Point(shift, 0.0f)); + info = &leterInfo->at( index ); + if(info) + { + info->position = info->position + Point(shift, 0.0f); + } } } @@ -336,15 +342,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) { nextFontPositionX = 0; nextFontPositionY -= commonLineHeight; - continue; - } - - // get the sprite to this letter - Sprite *letterSprite = theLabel->getSpriteForChar(c, i); - - if (!letterSprite) - { - log("WARNING: can't find letter definition in font file for letter: %c", c); + + theLabel->recordPlaceholderInfo(i); continue; } @@ -354,10 +353,13 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount, (float)nextFontPositionY + yOffset - charRect.size.height * 0.5f); - - // set the sprite position - letterSprite->setPosition(CC_POINT_PIXELS_TO_POINTS(fontPos)); - + + if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false) + { + log("WARNING: can't find letter definition in font file for letter: %c", c); + continue; + } + // update kerning nextFontPositionX += charAdvance + kerningAmount; prev = c; diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index f22c5a7864..9aa5d20947 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -264,9 +264,9 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() label->setAnchorPoint( Point(0.5f, 0.5f) ); - auto BChar = (Sprite*) label->getChildByTag(0); - auto FChar = (Sprite*) label->getChildByTag(7); - auto AChar = (Sprite*) label->getChildByTag(12); + auto BChar = (Sprite*) label->getLetterAt(0); + auto FChar = (Sprite*) label->getLetterAt(7); + auto AChar = (Sprite*) label->getLetterAt(12); auto rotate = RotateBy::create(2, 360); @@ -296,7 +296,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() addChild(label2, 0, kTagBitmapAtlas2); label2->setPosition( Point(s.width/2.0f, 80) ); - auto lastChar = (Sprite*) label2->getChildByTag(1); + auto lastChar = (Sprite*) label2->getLetterAt(3); lastChar->runAction( rot_4ever->clone() ); schedule( schedule_selector(LabelFNTSpriteActions::step), 0.1f); From a68d92ff5a4f695e8d880230c011324aaba151fc Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 29 Oct 2013 20:30:24 +0800 Subject: [PATCH 289/557] perfect vs-project configuration --- .../cocosbuilder/proj.win32/libCocosBuilder.vcxproj | 8 ++++++-- .../cocostudio/proj.win32/libCocosStudio.vcxproj | 8 ++++++-- cocos/editor-support/spine/proj.win32/libSpine.vcxproj | 8 ++++++-- cocos/gui/proj.win32/libGUI.vcxproj | 8 ++++++-- .../local-storage/proj.win32/libLocalStorage.vcxproj | 8 ++++++-- 5 files changed, 30 insertions(+), 10 deletions(-) diff --git a/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj index 2b44d72452..c6238489c7 100644 --- a/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj +++ b/cocos/editor-support/cocosbuilder/proj.win32/libCocosBuilder.vcxproj @@ -18,13 +18,17 @@ StaticLibrary true - v110_xp + v100 + v110 + v110_xp Unicode StaticLibrary false - v110_xp + v100 + v110 + v110_xp true Unicode diff --git a/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj index d52ce8d931..77de7fdb61 100644 --- a/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj +++ b/cocos/editor-support/cocostudio/proj.win32/libCocosStudio.vcxproj @@ -106,13 +106,17 @@ StaticLibrary true - v110_xp + v100 + v110 + v110_xp Unicode StaticLibrary false - v110_xp + v100 + v110 + v110_xp true Unicode diff --git a/cocos/editor-support/spine/proj.win32/libSpine.vcxproj b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj index b4fc436abf..b8bd4306b8 100644 --- a/cocos/editor-support/spine/proj.win32/libSpine.vcxproj +++ b/cocos/editor-support/spine/proj.win32/libSpine.vcxproj @@ -65,13 +65,17 @@ StaticLibrary true - v110_xp + v100 + v110 + v110_xp Unicode StaticLibrary false - v110_xp + v100 + v110 + v110_xp true Unicode diff --git a/cocos/gui/proj.win32/libGUI.vcxproj b/cocos/gui/proj.win32/libGUI.vcxproj index 1e483d4b85..b225eaa127 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj +++ b/cocos/gui/proj.win32/libGUI.vcxproj @@ -67,13 +67,17 @@ StaticLibrary true - v110_xp + v100 + v110 + v110_xp Unicode StaticLibrary false - v110_xp + v100 + v110 + v110_xp true Unicode diff --git a/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj index d79eb7ce1c..3413ec57b0 100644 --- a/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj +++ b/cocos/storage/local-storage/proj.win32/libLocalStorage.vcxproj @@ -24,13 +24,17 @@ StaticLibrary true - v110_xp + v100 + v110 + v110_xp Unicode StaticLibrary false - v110_xp + v100 + v110 + v110_xp true Unicode From 379bcb194c43f1e410d6c5eb18893e9ad398f3a0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 30 Oct 2013 21:55:19 +0800 Subject: [PATCH 290/557] [sp v25] Updating SpiderMonkey library to FFv25. --- .../spidermonkey/include/android/js-config.h | 6 +- external/spidermonkey/include/android/js.msg | 29 +- .../spidermonkey/include/android/js/Anchor.h | 6 +- .../include/android/js/CallArgs.h | 187 ++- .../include/android/js/CharacterEncoding.h | 48 +- .../spidermonkey/include/android/js/Date.h | 6 +- .../spidermonkey/include/android/js/GCAPI.h | 15 +- .../include/android/js/HashTable.h | 132 +- .../spidermonkey/include/android/js/HeapAPI.h | 29 +- .../include/android/js/LegacyIntTypes.h | 11 +- .../include/android/js/MemoryMetrics.h | 27 +- .../include/android/js/PropertyKey.h | 6 +- .../include/android/js/RequiredDefines.h | 6 +- .../include/android/js/RootingAPI.h | 493 +++++-- .../include/android/js/TemplateLib.h | 117 -- .../spidermonkey/include/android/js/Utility.h | 403 +----- .../spidermonkey/include/android/js/Value.h | 152 ++- .../spidermonkey/include/android/js/Vector.h | 1119 +--------------- .../spidermonkey/include/android/jsalloc.h | 37 +- .../include/android/jsapi.h.REMOVED.git-id | 2 +- .../spidermonkey/include/android/jsclass.h | 26 +- .../spidermonkey/include/android/jsclist.h | 6 +- .../spidermonkey/include/android/jscpucfg.h | 6 +- .../spidermonkey/include/android/jsdbgapi.h | 19 +- .../spidermonkey/include/android/jsdhash.h | 612 --------- .../include/android/jsfriendapi.h | 477 ++++++- .../spidermonkey/include/android/jslock.h | 13 +- external/spidermonkey/include/android/json.h | 48 - .../spidermonkey/include/android/jsperf.h | 6 +- external/spidermonkey/include/android/jsprf.h | 12 +- .../include/android/jsprototypes.h | 21 +- .../spidermonkey/include/android/jsproxy.h | 52 +- .../spidermonkey/include/android/jsprvtd.h | 38 +- .../spidermonkey/include/android/jspubtd.h | 66 +- .../spidermonkey/include/android/jstypes.h | 6 +- .../spidermonkey/include/android/jsutil.h | 21 +- .../spidermonkey/include/android/jsversion.h | 8 +- .../spidermonkey/include/android/jswrapper.h | 14 +- .../include/android/mozilla/AllocPolicy.h | 63 + .../include/android/mozilla/Array.h | 51 + .../include/android/mozilla/Assertions.h | 294 ++-- .../include/android/mozilla/Atomics.h | 1014 ++++++++++++++ .../include/android/mozilla/Attributes.h | 46 +- .../include/android/mozilla/BloomFilter.h | 17 +- .../include/android/mozilla/Casting.h | 58 +- .../include/android/mozilla/Char16.h | 15 +- .../include/android/mozilla/CheckedInt.h | 110 +- .../include/android/mozilla/Compiler.h | 9 +- .../include/android/mozilla/Constants.h | 9 +- .../include/android/mozilla/DebugOnly.h | 9 +- .../include/android/mozilla/Decimal.h | 2 +- .../include/android/mozilla/Endian.h | 11 +- .../include/android/mozilla/EnumSet.h | 8 +- .../include/android/mozilla/FloatingPoint.h | 135 +- .../include/android/mozilla/GuardObjects.h | 6 +- .../include/android/mozilla/HashFunctions.h | 23 +- .../include/android/mozilla/Likely.h | 13 +- .../include/android/mozilla/LinkedList.h | 61 +- .../include/android/mozilla/MSStdInt.h | 247 ---- .../include/android/mozilla/MathAlgorithms.h | 293 +++- .../include/android/mozilla/MemoryChecking.h | 9 +- .../include/android/mozilla/MemoryReporting.h | 30 + .../include/android/mozilla/Move.h | 166 +++ .../include/android/mozilla/NullPtr.h | 9 +- .../include/android/mozilla/PodOperations.h | 5 +- .../include/android/mozilla/Poison.h | 13 +- .../include/android/mozilla/Range.h | 18 +- .../include/android/mozilla/RangedPtr.h | 12 +- .../include/android/mozilla/ReentrancyGuard.h | 57 + .../include/android/mozilla/RefPtr.h | 55 +- .../include/android/mozilla/SHA1.h | 11 +- .../include/android/mozilla/Scoped.h | 17 +- .../include/android/mozilla/SplayTree.h | 13 +- .../include/android/mozilla/StandardInteger.h | 43 - .../include/android/mozilla/TemplateLib.h | 111 ++ .../include/android/mozilla/ThreadLocal.h | 22 +- .../include/android/mozilla/TypeTraits.h | 229 +++- .../include/android/mozilla/TypedEnum.h | 47 +- .../include/android/mozilla/Types.h | 28 +- .../include/android/mozilla/Util.h | 63 +- .../include/android/mozilla/Vector.h | 1190 +++++++++++++++++ .../include/android/mozilla/WeakPtr.h | 55 +- external/spidermonkey/include/ios/js-config.h | 6 +- external/spidermonkey/include/ios/js.msg | 29 +- external/spidermonkey/include/ios/js/Anchor.h | 6 +- .../spidermonkey/include/ios/js/CallArgs.h | 187 ++- .../include/ios/js/CharacterEncoding.h | 48 +- external/spidermonkey/include/ios/js/Date.h | 6 +- external/spidermonkey/include/ios/js/GCAPI.h | 15 +- .../spidermonkey/include/ios/js/HashTable.h | 132 +- .../spidermonkey/include/ios/js/HeapAPI.h | 29 +- .../include/ios/js/LegacyIntTypes.h | 11 +- .../include/ios/js/MemoryMetrics.h | 27 +- .../spidermonkey/include/ios/js/PropertyKey.h | 6 +- .../include/ios/js/RequiredDefines.h | 6 +- .../spidermonkey/include/ios/js/RootingAPI.h | 493 +++++-- .../spidermonkey/include/ios/js/TemplateLib.h | 117 -- .../spidermonkey/include/ios/js/Utility.h | 403 +----- external/spidermonkey/include/ios/js/Value.h | 152 ++- external/spidermonkey/include/ios/js/Vector.h | 1119 +--------------- external/spidermonkey/include/ios/jsalloc.h | 37 +- .../include/ios/jsapi.h.REMOVED.git-id | 2 +- external/spidermonkey/include/ios/jsclass.h | 26 +- external/spidermonkey/include/ios/jsclist.h | 6 +- external/spidermonkey/include/ios/jscpucfg.h | 6 +- external/spidermonkey/include/ios/jsdbgapi.h | 19 +- external/spidermonkey/include/ios/jsdhash.h | 612 --------- .../spidermonkey/include/ios/jsfriendapi.h | 477 ++++++- external/spidermonkey/include/ios/jslock.h | 13 +- external/spidermonkey/include/ios/json.h | 48 - external/spidermonkey/include/ios/jsperf.h | 6 +- external/spidermonkey/include/ios/jsprf.h | 12 +- .../spidermonkey/include/ios/jsprototypes.h | 21 +- external/spidermonkey/include/ios/jsproxy.h | 52 +- external/spidermonkey/include/ios/jsprvtd.h | 38 +- external/spidermonkey/include/ios/jspubtd.h | 66 +- external/spidermonkey/include/ios/jstypes.h | 6 +- external/spidermonkey/include/ios/jsutil.h | 21 +- external/spidermonkey/include/ios/jsversion.h | 8 +- external/spidermonkey/include/ios/jswrapper.h | 14 +- .../include/ios/mozilla/AllocPolicy.h | 63 + .../spidermonkey/include/ios/mozilla/Array.h | 51 + .../include/ios/mozilla/Assertions.h | 294 ++-- .../include/ios/mozilla/Atomics.h | 1014 ++++++++++++++ .../include/ios/mozilla/Attributes.h | 46 +- .../include/ios/mozilla/BloomFilter.h | 17 +- .../include/ios/mozilla/Casting.h | 58 +- .../spidermonkey/include/ios/mozilla/Char16.h | 15 +- .../include/ios/mozilla/CheckedInt.h | 110 +- .../include/ios/mozilla/Compiler.h | 9 +- .../include/ios/mozilla/Constants.h | 9 +- .../include/ios/mozilla/DebugOnly.h | 9 +- .../include/ios/mozilla/Decimal.h | 2 +- .../spidermonkey/include/ios/mozilla/Endian.h | 11 +- .../include/ios/mozilla/EnumSet.h | 8 +- .../include/ios/mozilla/FloatingPoint.h | 135 +- .../include/ios/mozilla/GuardObjects.h | 6 +- .../include/ios/mozilla/HashFunctions.h | 23 +- .../spidermonkey/include/ios/mozilla/Likely.h | 13 +- .../include/ios/mozilla/LinkedList.h | 61 +- .../include/ios/mozilla/MSStdInt.h | 247 ---- .../include/ios/mozilla/MathAlgorithms.h | 293 +++- .../include/ios/mozilla/MemoryChecking.h | 9 +- .../include/ios/mozilla/MemoryReporting.h | 30 + .../spidermonkey/include/ios/mozilla/Move.h | 166 +++ .../include/ios/mozilla/NullPtr.h | 9 +- .../include/ios/mozilla/PodOperations.h | 5 +- .../spidermonkey/include/ios/mozilla/Poison.h | 13 +- .../spidermonkey/include/ios/mozilla/Range.h | 18 +- .../include/ios/mozilla/RangedPtr.h | 12 +- .../include/ios/mozilla/ReentrancyGuard.h | 57 + .../spidermonkey/include/ios/mozilla/RefPtr.h | 55 +- .../spidermonkey/include/ios/mozilla/SHA1.h | 11 +- .../spidermonkey/include/ios/mozilla/Scoped.h | 17 +- .../include/ios/mozilla/SplayTree.h | 13 +- .../include/ios/mozilla/StandardInteger.h | 43 - .../include/ios/mozilla/TemplateLib.h | 111 ++ .../include/ios/mozilla/ThreadLocal.h | 22 +- .../include/ios/mozilla/TypeTraits.h | 229 +++- .../include/ios/mozilla/TypedEnum.h | 47 +- .../spidermonkey/include/ios/mozilla/Types.h | 28 +- .../spidermonkey/include/ios/mozilla/Util.h | 63 +- .../spidermonkey/include/ios/mozilla/Vector.h | 1190 +++++++++++++++++ .../include/ios/mozilla/WeakPtr.h | 55 +- external/spidermonkey/include/mac/js-config.h | 6 +- external/spidermonkey/include/mac/js.msg | 29 +- external/spidermonkey/include/mac/js/Anchor.h | 6 +- .../spidermonkey/include/mac/js/CallArgs.h | 187 ++- .../include/mac/js/CharacterEncoding.h | 48 +- external/spidermonkey/include/mac/js/Date.h | 6 +- external/spidermonkey/include/mac/js/GCAPI.h | 15 +- .../spidermonkey/include/mac/js/HashTable.h | 132 +- .../spidermonkey/include/mac/js/HeapAPI.h | 29 +- .../include/mac/js/LegacyIntTypes.h | 11 +- .../include/mac/js/MemoryMetrics.h | 27 +- .../spidermonkey/include/mac/js/PropertyKey.h | 6 +- .../include/mac/js/RequiredDefines.h | 6 +- .../spidermonkey/include/mac/js/RootingAPI.h | 493 +++++-- .../spidermonkey/include/mac/js/TemplateLib.h | 117 -- .../spidermonkey/include/mac/js/Utility.h | 403 +----- external/spidermonkey/include/mac/js/Value.h | 152 ++- external/spidermonkey/include/mac/js/Vector.h | 1119 +--------------- external/spidermonkey/include/mac/jsalloc.h | 37 +- .../include/mac/jsapi.h.REMOVED.git-id | 2 +- external/spidermonkey/include/mac/jsclass.h | 26 +- external/spidermonkey/include/mac/jsclist.h | 6 +- external/spidermonkey/include/mac/jscpucfg.h | 6 +- external/spidermonkey/include/mac/jsdbgapi.h | 19 +- external/spidermonkey/include/mac/jsdhash.h | 612 --------- .../spidermonkey/include/mac/jsfriendapi.h | 477 ++++++- external/spidermonkey/include/mac/jslock.h | 13 +- external/spidermonkey/include/mac/json.h | 48 - external/spidermonkey/include/mac/jsperf.h | 6 +- external/spidermonkey/include/mac/jsprf.h | 12 +- .../spidermonkey/include/mac/jsprototypes.h | 21 +- external/spidermonkey/include/mac/jsproxy.h | 52 +- external/spidermonkey/include/mac/jsprvtd.h | 38 +- external/spidermonkey/include/mac/jspubtd.h | 66 +- external/spidermonkey/include/mac/jstypes.h | 6 +- external/spidermonkey/include/mac/jsutil.h | 21 +- external/spidermonkey/include/mac/jsversion.h | 8 +- external/spidermonkey/include/mac/jswrapper.h | 14 +- .../include/mac/mozilla/AllocPolicy.h | 63 + .../spidermonkey/include/mac/mozilla/Array.h | 51 + .../include/mac/mozilla/Assertions.h | 294 ++-- .../include/mac/mozilla/Atomics.h | 1014 ++++++++++++++ .../include/mac/mozilla/Attributes.h | 46 +- .../include/mac/mozilla/BloomFilter.h | 17 +- .../include/mac/mozilla/Casting.h | 58 +- .../spidermonkey/include/mac/mozilla/Char16.h | 15 +- .../include/mac/mozilla/CheckedInt.h | 110 +- .../include/mac/mozilla/Compiler.h | 9 +- .../include/mac/mozilla/Constants.h | 9 +- .../include/mac/mozilla/DebugOnly.h | 9 +- .../include/mac/mozilla/Decimal.h | 2 +- .../spidermonkey/include/mac/mozilla/Endian.h | 11 +- .../include/mac/mozilla/EnumSet.h | 8 +- .../include/mac/mozilla/FloatingPoint.h | 135 +- .../include/mac/mozilla/GuardObjects.h | 6 +- .../include/mac/mozilla/HashFunctions.h | 23 +- .../spidermonkey/include/mac/mozilla/Likely.h | 13 +- .../include/mac/mozilla/LinkedList.h | 61 +- .../include/mac/mozilla/MSStdInt.h | 247 ---- .../include/mac/mozilla/MathAlgorithms.h | 293 +++- .../include/mac/mozilla/MemoryChecking.h | 9 +- .../include/mac/mozilla/MemoryReporting.h | 30 + .../spidermonkey/include/mac/mozilla/Move.h | 166 +++ .../include/mac/mozilla/NullPtr.h | 9 +- .../include/mac/mozilla/PodOperations.h | 5 +- .../spidermonkey/include/mac/mozilla/Poison.h | 13 +- .../spidermonkey/include/mac/mozilla/Range.h | 18 +- .../include/mac/mozilla/RangedPtr.h | 12 +- .../include/mac/mozilla/ReentrancyGuard.h | 57 + .../spidermonkey/include/mac/mozilla/RefPtr.h | 55 +- .../spidermonkey/include/mac/mozilla/SHA1.h | 11 +- .../spidermonkey/include/mac/mozilla/Scoped.h | 17 +- .../include/mac/mozilla/SplayTree.h | 13 +- .../include/mac/mozilla/StandardInteger.h | 43 - .../include/mac/mozilla/TemplateLib.h | 111 ++ .../include/mac/mozilla/ThreadLocal.h | 22 +- .../include/mac/mozilla/TypeTraits.h | 229 +++- .../include/mac/mozilla/TypedEnum.h | 47 +- .../spidermonkey/include/mac/mozilla/Types.h | 28 +- .../spidermonkey/include/mac/mozilla/Util.h | 63 +- .../spidermonkey/include/mac/mozilla/Vector.h | 1190 +++++++++++++++++ .../include/mac/mozilla/WeakPtr.h | 55 +- .../spidermonkey/include/win32/js-config.h | 6 +- external/spidermonkey/include/win32/js.msg | 29 +- .../spidermonkey/include/win32/js/Anchor.h | 6 +- .../spidermonkey/include/win32/js/CallArgs.h | 187 ++- .../include/win32/js/CharacterEncoding.h | 48 +- external/spidermonkey/include/win32/js/Date.h | 6 +- .../spidermonkey/include/win32/js/GCAPI.h | 15 +- .../spidermonkey/include/win32/js/HashTable.h | 132 +- .../spidermonkey/include/win32/js/HeapAPI.h | 29 +- .../include/win32/js/LegacyIntTypes.h | 11 +- .../include/win32/js/MemoryMetrics.h | 27 +- .../include/win32/js/PropertyKey.h | 6 +- .../include/win32/js/RequiredDefines.h | 6 +- .../include/win32/js/RootingAPI.h | 493 +++++-- .../include/win32/js/TemplateLib.h | 117 -- .../spidermonkey/include/win32/js/Utility.h | 403 +----- .../spidermonkey/include/win32/js/Value.h | 152 ++- .../spidermonkey/include/win32/js/Vector.h | 1119 +--------------- external/spidermonkey/include/win32/jsalloc.h | 37 +- .../include/win32/jsapi.h.REMOVED.git-id | 2 +- external/spidermonkey/include/win32/jsclass.h | 26 +- external/spidermonkey/include/win32/jsclist.h | 6 +- .../spidermonkey/include/win32/jscpucfg.h | 6 +- .../spidermonkey/include/win32/jsdbgapi.h | 19 +- external/spidermonkey/include/win32/jsdhash.h | 612 --------- .../spidermonkey/include/win32/jsfriendapi.h | 477 ++++++- external/spidermonkey/include/win32/jslock.h | 13 +- external/spidermonkey/include/win32/json.h | 48 - external/spidermonkey/include/win32/jsperf.h | 6 +- external/spidermonkey/include/win32/jsprf.h | 12 +- .../spidermonkey/include/win32/jsprototypes.h | 21 +- external/spidermonkey/include/win32/jsproxy.h | 52 +- external/spidermonkey/include/win32/jsprvtd.h | 38 +- external/spidermonkey/include/win32/jspubtd.h | 66 +- external/spidermonkey/include/win32/jstypes.h | 6 +- external/spidermonkey/include/win32/jsutil.h | 21 +- .../spidermonkey/include/win32/jsversion.h | 8 +- .../spidermonkey/include/win32/jswrapper.h | 14 +- .../include/win32/mozilla/AllocPolicy.h | 63 + .../include/win32/mozilla/Array.h | 51 + .../include/win32/mozilla/Assertions.h | 294 ++-- .../include/win32/mozilla/Atomics.h | 1014 ++++++++++++++ .../include/win32/mozilla/Attributes.h | 46 +- .../include/win32/mozilla/BloomFilter.h | 17 +- .../include/win32/mozilla/Casting.h | 58 +- .../include/win32/mozilla/Char16.h | 15 +- .../include/win32/mozilla/CheckedInt.h | 110 +- .../include/win32/mozilla/Compiler.h | 9 +- .../include/win32/mozilla/Constants.h | 9 +- .../include/win32/mozilla/DebugOnly.h | 9 +- .../include/win32/mozilla/Decimal.h | 2 +- .../include/win32/mozilla/Endian.h | 11 +- .../include/win32/mozilla/EnumSet.h | 8 +- .../include/win32/mozilla/FloatingPoint.h | 135 +- .../include/win32/mozilla/GuardObjects.h | 6 +- .../include/win32/mozilla/HashFunctions.h | 23 +- .../include/win32/mozilla/Likely.h | 13 +- .../include/win32/mozilla/LinkedList.h | 61 +- .../include/win32/mozilla/MSStdInt.h | 247 ---- .../include/win32/mozilla/MathAlgorithms.h | 293 +++- .../include/win32/mozilla/MemoryChecking.h | 9 +- .../include/win32/mozilla/MemoryReporting.h | 30 + .../spidermonkey/include/win32/mozilla/Move.h | 166 +++ .../include/win32/mozilla/NullPtr.h | 9 +- .../include/win32/mozilla/PodOperations.h | 5 +- .../include/win32/mozilla/Poison.h | 13 +- .../include/win32/mozilla/Range.h | 18 +- .../include/win32/mozilla/RangedPtr.h | 12 +- .../include/win32/mozilla/ReentrancyGuard.h | 57 + .../include/win32/mozilla/RefPtr.h | 55 +- .../spidermonkey/include/win32/mozilla/SHA1.h | 11 +- .../include/win32/mozilla/Scoped.h | 17 +- .../include/win32/mozilla/SplayTree.h | 13 +- .../include/win32/mozilla/StandardInteger.h | 43 - .../include/win32/mozilla/TemplateLib.h | 111 ++ .../include/win32/mozilla/ThreadLocal.h | 22 +- .../include/win32/mozilla/TypeTraits.h | 229 +++- .../include/win32/mozilla/TypedEnum.h | 47 +- .../include/win32/mozilla/Types.h | 28 +- .../spidermonkey/include/win32/mozilla/Util.h | 63 +- .../include/win32/mozilla/Vector.h | 1190 +++++++++++++++++ .../include/win32/mozilla/WeakPtr.h | 55 +- .../armeabi-v7a/libjs_static.a.REMOVED.git-id | 2 +- .../armeabi/libjs_static.a.REMOVED.git-id | 2 +- .../android/x86/libjs_static.a.REMOVED.git-id | 2 +- .../ios/libjs_static.a.REMOVED.git-id | 2 +- .../mac/libjs_static.a.REMOVED.git-id | 2 +- .../win32/mozjs-23.0.dll.REMOVED.git-id | 1 - .../win32/mozjs-23.0.lib.REMOVED.git-id | 1 - .../win32/mozjs-25.0.dll.REMOVED.git-id | 1 + .../win32/mozjs-25.0.lib.REMOVED.git-id | 1 + 337 files changed, 21639 insertions(+), 14291 deletions(-) delete mode 100644 external/spidermonkey/include/android/js/TemplateLib.h delete mode 100644 external/spidermonkey/include/android/jsdhash.h delete mode 100644 external/spidermonkey/include/android/json.h create mode 100644 external/spidermonkey/include/android/mozilla/AllocPolicy.h create mode 100644 external/spidermonkey/include/android/mozilla/Array.h create mode 100644 external/spidermonkey/include/android/mozilla/Atomics.h delete mode 100644 external/spidermonkey/include/android/mozilla/MSStdInt.h create mode 100644 external/spidermonkey/include/android/mozilla/MemoryReporting.h create mode 100644 external/spidermonkey/include/android/mozilla/Move.h create mode 100644 external/spidermonkey/include/android/mozilla/ReentrancyGuard.h delete mode 100644 external/spidermonkey/include/android/mozilla/StandardInteger.h create mode 100644 external/spidermonkey/include/android/mozilla/TemplateLib.h create mode 100644 external/spidermonkey/include/android/mozilla/Vector.h delete mode 100644 external/spidermonkey/include/ios/js/TemplateLib.h delete mode 100644 external/spidermonkey/include/ios/jsdhash.h delete mode 100644 external/spidermonkey/include/ios/json.h create mode 100644 external/spidermonkey/include/ios/mozilla/AllocPolicy.h create mode 100644 external/spidermonkey/include/ios/mozilla/Array.h create mode 100644 external/spidermonkey/include/ios/mozilla/Atomics.h delete mode 100644 external/spidermonkey/include/ios/mozilla/MSStdInt.h create mode 100644 external/spidermonkey/include/ios/mozilla/MemoryReporting.h create mode 100644 external/spidermonkey/include/ios/mozilla/Move.h create mode 100644 external/spidermonkey/include/ios/mozilla/ReentrancyGuard.h delete mode 100644 external/spidermonkey/include/ios/mozilla/StandardInteger.h create mode 100644 external/spidermonkey/include/ios/mozilla/TemplateLib.h create mode 100644 external/spidermonkey/include/ios/mozilla/Vector.h delete mode 100644 external/spidermonkey/include/mac/js/TemplateLib.h delete mode 100644 external/spidermonkey/include/mac/jsdhash.h delete mode 100644 external/spidermonkey/include/mac/json.h create mode 100644 external/spidermonkey/include/mac/mozilla/AllocPolicy.h create mode 100644 external/spidermonkey/include/mac/mozilla/Array.h create mode 100644 external/spidermonkey/include/mac/mozilla/Atomics.h delete mode 100644 external/spidermonkey/include/mac/mozilla/MSStdInt.h create mode 100644 external/spidermonkey/include/mac/mozilla/MemoryReporting.h create mode 100644 external/spidermonkey/include/mac/mozilla/Move.h create mode 100644 external/spidermonkey/include/mac/mozilla/ReentrancyGuard.h delete mode 100644 external/spidermonkey/include/mac/mozilla/StandardInteger.h create mode 100644 external/spidermonkey/include/mac/mozilla/TemplateLib.h create mode 100644 external/spidermonkey/include/mac/mozilla/Vector.h delete mode 100644 external/spidermonkey/include/win32/js/TemplateLib.h delete mode 100644 external/spidermonkey/include/win32/jsdhash.h delete mode 100644 external/spidermonkey/include/win32/json.h create mode 100644 external/spidermonkey/include/win32/mozilla/AllocPolicy.h create mode 100644 external/spidermonkey/include/win32/mozilla/Array.h create mode 100644 external/spidermonkey/include/win32/mozilla/Atomics.h delete mode 100644 external/spidermonkey/include/win32/mozilla/MSStdInt.h create mode 100644 external/spidermonkey/include/win32/mozilla/MemoryReporting.h create mode 100644 external/spidermonkey/include/win32/mozilla/Move.h create mode 100644 external/spidermonkey/include/win32/mozilla/ReentrancyGuard.h delete mode 100644 external/spidermonkey/include/win32/mozilla/StandardInteger.h create mode 100644 external/spidermonkey/include/win32/mozilla/TemplateLib.h create mode 100644 external/spidermonkey/include/win32/mozilla/Vector.h delete mode 100644 external/spidermonkey/prebuilt/win32/mozjs-23.0.dll.REMOVED.git-id delete mode 100644 external/spidermonkey/prebuilt/win32/mozjs-23.0.lib.REMOVED.git-id create mode 100644 external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id create mode 100644 external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id diff --git a/external/spidermonkey/include/android/js-config.h b/external/spidermonkey/include/android/js-config.h index 793bdb0a9f..4b893482f4 100644 --- a/external/spidermonkey/include/android/js-config.h +++ b/external/spidermonkey/include/android/js-config.h @@ -38,8 +38,8 @@ JS_HAVE_STDINT_H. */ #define JS_BYTES_PER_WORD 4 -/* Some mozilla code uses JS-friend APIs that depend on JS_METHODJIT being - correct. */ -#define JS_METHODJIT 1 +/* MOZILLA JSAPI version number components */ +#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MINOR_VERSION 0 #endif /* js_config_h___ */ diff --git a/external/spidermonkey/include/android/js.msg b/external/spidermonkey/include/android/js.msg index 3e57bdf174..3f665d8d54 100644 --- a/external/spidermonkey/include/android/js.msg +++ b/external/spidermonkey/include/android/js.msg @@ -184,7 +184,7 @@ MSG_DEF(JSMSG_BAD_OPERAND, 130, 1, JSEXN_SYNTAXERR, "invalid {0} oper MSG_DEF(JSMSG_BAD_PROP_ID, 131, 0, JSEXN_SYNTAXERR, "invalid property id") MSG_DEF(JSMSG_RESERVED_ID, 132, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") MSG_DEF(JSMSG_SYNTAX_ERROR, 133, 0, JSEXN_SYNTAXERR, "syntax error") -MSG_DEF(JSMSG_UNUSED134, 134, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 134, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") MSG_DEF(JSMSG_BAD_PROTOTYPE, 135, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") MSG_DEF(JSMSG_MISSING_EXPONENT, 136, 0, JSEXN_SYNTAXERR, "missing exponent") MSG_DEF(JSMSG_OUT_OF_MEMORY, 137, 0, JSEXN_ERR, "out of memory") @@ -193,10 +193,10 @@ MSG_DEF(JSMSG_TOO_MANY_PARENS, 139, 0, JSEXN_INTERNALERR, "too many paren MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 140, 0, JSEXN_SYNTAXERR, "unterminated comment") MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 141, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 142, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_UNUSED143, 143, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 143, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 144, 0, JSEXN_SYNTAXERR, "illegal character") MSG_DEF(JSMSG_BAD_OCTAL, 145, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_UNUSED146, 146, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 146, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 147, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") MSG_DEF(JSMSG_INVALID_BACKREF, 148, 0, JSEXN_SYNTAXERR, "non-octal digit in an escape sequence that doesn't match a back-reference") MSG_DEF(JSMSG_BAD_BACKREF, 149, 0, JSEXN_SYNTAXERR, "back-reference exceeds number of capturing parentheses") @@ -220,7 +220,7 @@ MSG_DEF(JSMSG_RESERVED_SLOT_RANGE, 166, 0, JSEXN_RANGEERR, "reserved slot ind MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode JSPrincipals") MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_UNUSED170, 170, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") @@ -286,7 +286,7 @@ MSG_DEF(JSMSG_DEPRECATED_OCTAL, 232, 0, JSEXN_SYNTAXERR, "octal literals a MSG_DEF(JSMSG_STRICT_CODE_WITH, 233, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 234, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 235, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "assignment to {0} is deprecated") +MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "can't assign to {0} in strict mode") MSG_DEF(JSMSG_BAD_BINDING, 237, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 238, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 239, 1, JSEXN_TYPEERR, "{0} is not extensible") @@ -313,16 +313,16 @@ MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 259, 0, JSEXN_TYPEERR, "can't change ob MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 260, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 261, 0, JSEXN_TYPEERR, "unsupported type for structured data") MSG_DEF(JSMSG_SC_RECURSION, 262, 0, JSEXN_INTERNALERR, "recursive object") -MSG_DEF(JSMSG_UNUSED263, 263, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 263, 0, JSEXN_ERR, "passing non-debuggable global to addDebuggee") MSG_DEF(JSMSG_BAD_CLONE_VERSION, 264, 0, JSEXN_ERR, "unsupported structured clone version") MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 265, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_UNUSED266, 266, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 266, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") MSG_DEF(JSMSG_STRICT_FUNCTION_STATEMENT, 267, 0, JSEXN_SYNTAXERR, "in strict mode code, functions may be declared only at top level or immediately within another function") MSG_DEF(JSMSG_INVALID_FOR_IN_INIT, 268, 0, JSEXN_SYNTAXERR, "for-in loop let declaration may not have an initializer") MSG_DEF(JSMSG_CLEARED_SCOPE, 269, 0, JSEXN_TYPEERR, "attempt to run compile-and-go script on a cleared scope") MSG_DEF(JSMSG_MALFORMED_ESCAPE, 270, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") MSG_DEF(JSMSG_BAD_GENEXP_BODY, 271, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_UNUSED272, 272, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_YIELD_WITHOUT_OPERAND, 272, 0, JSEXN_SYNTAXERR, "yield without a value is deprecated, and illegal in ES6 (use 'yield undefined' instead)") MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 273, 0, JSEXN_SYNTAXERR, "function statement requires a name") MSG_DEF(JSMSG_CCW_REQUIRED, 274, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 275, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") @@ -391,12 +391,21 @@ MSG_DEF(JSMSG_DATE_NOT_FINITE, 337, 0, JSEXN_RANGEERR, "date value is not MSG_DEF(JSMSG_MODULE_STATEMENT, 338, 0, JSEXN_SYNTAXERR, "module declarations may only appear at the top level of a program or module body") MSG_DEF(JSMSG_CURLY_BEFORE_MODULE, 339, 0, JSEXN_SYNTAXERR, "missing { before module body") MSG_DEF(JSMSG_CURLY_AFTER_MODULE, 340, 0, JSEXN_SYNTAXERR, "missing } after module body") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "'use asm' directive only works on function code") +MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 342, 1, JSEXN_TYPEERR, "asm.js type error: {0}") MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 343, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 0, JSEXN_ERR, "successfully compiled asm.js code") +MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 1, JSEXN_ERR, "successfully compiled asm.js code ({0})") MSG_DEF(JSMSG_BAD_ARROW_ARGS, 345, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") +MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") +MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") diff --git a/external/spidermonkey/include/android/js/Anchor.h b/external/spidermonkey/include/android/js/Anchor.h index d0c2476cf7..0d458e6fb6 100644 --- a/external/spidermonkey/include/android/js/Anchor.h +++ b/external/spidermonkey/include/android/js/Anchor.h @@ -6,8 +6,8 @@ /* JS::Anchor implementation. */ -#ifndef js_Anchor_h___ -#define js_Anchor_h___ +#ifndef js_Anchor_h +#define js_Anchor_h #include "mozilla/Attributes.h" @@ -159,4 +159,4 @@ inline Anchor::~Anchor() } // namespace JS -#endif /* js_Anchor_h___ */ +#endif /* js_Anchor_h */ diff --git a/external/spidermonkey/include/android/js/CallArgs.h b/external/spidermonkey/include/android/js/CallArgs.h index af78fde0a0..8027ffc71a 100644 --- a/external/spidermonkey/include/android/js/CallArgs.h +++ b/external/spidermonkey/include/android/js/CallArgs.h @@ -26,11 +26,12 @@ * methods' implementations, potentially under time pressure. */ -#ifndef js_CallArgs_h___ -#define js_CallArgs_h___ +#ifndef js_CallArgs_h +#define js_CallArgs_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/TypeTraits.h" #include "jstypes.h" @@ -44,6 +45,29 @@ class JSObject; typedef JSBool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); +/* Typedef for native functions that may be called in parallel. */ +typedef js::ParallelResult +(* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + +/* + * Typedef for native functions that may be called either in parallel or + * sequential execution. + */ +typedef JSBool +(* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); + +/* + * Convenience wrappers for passing in ThreadSafeNative to places that expect + * a JSNative or a JSParallelNative. + */ +template +inline JSBool +JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); + +template +inline js::ParallelResult +JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + /* * Compute |this| for the |vp| inside a JSNative, either boxing primitives or * replacing with the global object as necessary. @@ -58,6 +82,8 @@ JS_ComputeThis(JSContext *cx, JS::Value *vp); namespace JS { +extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; + /* * JS::CallReceiver encapsulates access to the callee, |this|, and eventual * return value for a function call. The principal way to create a @@ -92,30 +118,55 @@ namespace JS { * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallReceiver + +namespace detail { + +#ifdef DEBUG +extern JS_PUBLIC_API(void) +CheckIsValidConstructible(Value v); +#endif + +enum UsedRval { IncludeUsedRval, NoUsedRval }; + +template +class MOZ_STACK_CLASS UsedRvalBase; + +template<> +class MOZ_STACK_CLASS UsedRvalBase { protected: -#ifdef DEBUG mutable bool usedRval_; void setUsedRval() const { usedRval_ = true; } void clearUsedRval() const { usedRval_ = false; } -#else +}; + +template<> +class MOZ_STACK_CLASS UsedRvalBase +{ + protected: void setUsedRval() const {} void clearUsedRval() const {} +}; + +template +class MOZ_STACK_CLASS CallReceiverBase : public UsedRvalBase< +#ifdef DEBUG + WantUsedRval +#else + NoUsedRval #endif - + > +{ + protected: Value *argv_; - friend CallReceiver CallReceiverFromVp(Value *vp); - friend CallReceiver CallReceiverFromArgv(Value *argv); - public: /* * Returns the function being called, as an object. Must not be called * after rval() has been used! */ JSObject &callee() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return argv_[-2].toObject(); } @@ -124,7 +175,7 @@ class MOZ_STACK_CLASS CallReceiver * rval() has been used! */ HandleValue calleev() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return HandleValue::fromMarkedLocation(&argv_[-2]); } @@ -148,6 +199,14 @@ class MOZ_STACK_CLASS CallReceiver return JS_ComputeThis(cx, base()); } + bool isConstructing() const { +#ifdef DEBUG + if (this->usedRval_) + CheckIsValidConstructible(calleev()); +#endif + return argv_[-1].isMagic(); + } + /* * Returns the currently-set return value. The initial contents of this * value are unspecified. Once this method has been called, callee() and @@ -160,7 +219,7 @@ class MOZ_STACK_CLASS CallReceiver * fails. */ MutableHandleValue rval() const { - setUsedRval(); + this->setUsedRval(); return MutableHandleValue::fromMarkedLocation(&argv_[-2]); } @@ -171,7 +230,7 @@ class MOZ_STACK_CLASS CallReceiver Value *base() const { return argv_ - 2; } Value *spAfterCall() const { - setUsedRval(); + this->setUsedRval(); return argv_ - 1; } @@ -181,7 +240,7 @@ class MOZ_STACK_CLASS CallReceiver // it. You probably don't want to use these! void setCallee(Value aCalleev) const { - clearUsedRval(); + this->clearUsedRval(); argv_[-2] = aCalleev; } @@ -194,6 +253,15 @@ class MOZ_STACK_CLASS CallReceiver } }; +} // namespace detail + +class MOZ_STACK_CLASS CallReceiver : public detail::CallReceiverBase +{ + private: + friend CallReceiver CallReceiverFromVp(Value *vp); + friend CallReceiver CallReceiverFromArgv(Value *argv); +}; + MOZ_ALWAYS_INLINE CallReceiver CallReceiverFromArgv(Value *argv) { @@ -233,11 +301,59 @@ CallReceiverFromVp(Value *vp) * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallArgs : public CallReceiver +namespace detail { + +template +class MOZ_STACK_CLASS CallArgsBase : + public mozilla::Conditional >::Type { protected: unsigned argc_; + public: + /* Returns the number of arguments. */ + unsigned length() const { return argc_; } + + /* Returns the i-th zero-indexed argument. */ + MutableHandleValue operator[](unsigned i) const { + MOZ_ASSERT(i < argc_); + return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); + } + + /* + * Returns the i-th zero-indexed argument, or |undefined| if there's no + * such argument. + */ + HandleValue get(unsigned i) const { + return i < length() + ? HandleValue::fromMarkedLocation(&this->argv_[i]) + : UndefinedHandleValue; + } + + /* + * Returns true if the i-th zero-indexed argument is present and is not + * |undefined|. + */ + bool hasDefined(unsigned i) const { + return i < argc_ && !this->argv_[i].isUndefined(); + } + + public: + // These methods are publicly exposed, but we're less sure of the interface + // here than we'd like (because they're hackish and drop assertions). Try + // to avoid using these if you can. + + Value *array() const { return this->argv_; } + Value *end() const { return this->argv_ + argc_; } +}; + +} // namespace detail + +class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase +{ + private: friend CallArgs CallArgsFromVp(unsigned argc, Value *vp); friend CallArgs CallArgsFromSp(unsigned argc, Value *sp); @@ -249,45 +365,6 @@ class MOZ_STACK_CLASS CallArgs : public CallReceiver return args; } - public: - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - Value &operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return argv_[i]; - } - - /* Returns a mutable handle for the i-th zero-indexed argument. */ - MutableHandleValue handleAt(unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - Value get(unsigned i) const { - return i < length() ? argv_[i] : UndefinedValue(); - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !argv_[i].isUndefined(); - } - - public: - // These methods are publicly exposed, but we're less sure of the interface - // here than we'd like (because they're hackish and drop assertions). Try - // to avoid using these if you can. - - Value *array() const { return argv_; } - Value *end() const { return argv_ + argc_; } }; MOZ_ALWAYS_INLINE CallArgs @@ -345,4 +422,4 @@ JS_THIS(JSContext *cx, JS::Value *vp) */ #define JS_THIS_VALUE(cx,vp) ((vp)[1]) -#endif /* js_CallArgs_h___ */ +#endif /* js_CallArgs_h */ diff --git a/external/spidermonkey/include/android/js/CharacterEncoding.h b/external/spidermonkey/include/android/js/CharacterEncoding.h index 63e5cc6650..e88e08e1be 100644 --- a/external/spidermonkey/include/android/js/CharacterEncoding.h +++ b/external/spidermonkey/include/android/js/CharacterEncoding.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_CharacterEncoding_h___ -#define js_CharacterEncoding_h___ +#ifndef js_CharacterEncoding_h +#define js_CharacterEncoding_h #include "mozilla/Range.h" @@ -58,6 +58,20 @@ class Latin1CharsZ : public mozilla::RangedPtr char *c_str() { return reinterpret_cast(get()); } }; +class UTF8Chars : public mozilla::Range +{ + typedef mozilla::Range Base; + + public: + UTF8Chars() : Base() {} + UTF8Chars(char *aBytes, size_t aLength) + : Base(reinterpret_cast(aBytes), aLength) + {} + UTF8Chars(const char *aBytes, size_t aLength) + : Base(reinterpret_cast(const_cast(aBytes)), aLength) + {} +}; + /* * SpiderMonkey also deals directly with UTF-8 encoded text in some places. */ @@ -124,10 +138,12 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: + TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) { - JS_ASSERT(chars[length] = '\0'); + JS_ASSERT(chars[length] == '\0'); } }; @@ -142,14 +158,34 @@ class TwoByteCharsZ : public mozilla::RangedPtr * This method cannot trigger GC. */ extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(JSContext *cx, TwoByteChars tbchars); +LossyTwoByteCharsToNewLatin1CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); extern UTF8CharsZ -TwoByteCharsToNewUTF8CharsZ(JSContext *cx, TwoByteChars tbchars); +TwoByteCharsToNewUTF8CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); + +uint32_t +Utf8ToOneUcs4Char(const uint8_t *utf8Buffer, int utf8Length); + +/* + * Inflate bytes in UTF-8 encoding to jschars. + * - On error, returns an empty TwoByteCharsZ. + * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold + * its length; the length value excludes the trailing null. + */ +extern TwoByteCharsZ +UTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); + +/* + * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters + * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 + * input. + */ +extern TwoByteCharsZ +LossyUTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); } // namespace JS inline void JS_free(JS::Latin1CharsZ &ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::UTF8CharsZ &ptr) { js_free((void*)ptr.get()); } -#endif // js_CharacterEncoding_h___ +#endif /* js_CharacterEncoding_h */ diff --git a/external/spidermonkey/include/android/js/Date.h b/external/spidermonkey/include/android/js/Date.h index 7ca961e30a..6199f9eca5 100644 --- a/external/spidermonkey/include/android/js/Date.h +++ b/external/spidermonkey/include/android/js/Date.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_Date_h___ -#define js_Date_h___ +#ifndef js_Date_h +#define js_Date_h #include "jstypes.h" @@ -32,4 +32,4 @@ DayFromTime(double time); } // namespace JS -#endif /* js_Date_h___ */ +#endif /* js_Date_h */ diff --git a/external/spidermonkey/include/android/js/GCAPI.h b/external/spidermonkey/include/android/js/GCAPI.h index 1b0036116c..a9bef77c09 100644 --- a/external/spidermonkey/include/android/js/GCAPI.h +++ b/external/spidermonkey/include/android/js/GCAPI.h @@ -4,10 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_gc_api_h___ -#define js_gc_api_h___ +#ifndef js_GCAPI_h +#define js_GCAPI_h -#include "HeapAPI.h" +#include "js/HeapAPI.h" namespace JS { @@ -181,6 +181,9 @@ DisableIncrementalGC(JSRuntime *rt); extern JS_FRIEND_API(void) DisableGenerationalGC(JSRuntime *rt); +extern JS_FRIEND_API(void) +EnableGenerationalGC(JSRuntime *rt); + extern JS_FRIEND_API(bool) IsIncrementalBarrierNeeded(JSRuntime *rt); @@ -205,7 +208,7 @@ WasIncrementalGC(JSRuntime *rt); class ObjectPtr { - JSObject *value; + Heap value; public: ObjectPtr() : value(NULL) {} @@ -240,7 +243,7 @@ class ObjectPtr } void trace(JSTracer *trc, const char *name) { - JS_CallObjectTracer(trc, &value, name); + JS_CallHeapObjectTracer(trc, &value, name); } JSObject &operator*() const { return *value; } @@ -291,4 +294,4 @@ ExposeValueToActiveJS(const Value &v) } /* namespace JS */ -#endif /* js_gc_api_h___ */ +#endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/android/js/HashTable.h b/external/spidermonkey/include/android/js/HashTable.h index 3402bfbff4..aa05b71472 100644 --- a/external/spidermonkey/include/android/js/HashTable.h +++ b/external/spidermonkey/include/android/js/HashTable.h @@ -4,17 +4,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_HashTable_h__ -#define js_HashTable_h__ +#ifndef js_HashTable_h +#define js_HashTable_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" #include "mozilla/PodOperations.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" #include "mozilla/Util.h" -#include "js/TemplateLib.h" #include "js/Utility.h" namespace js { @@ -68,15 +72,7 @@ class HashMap // HashMap construction is fallible (due to OOM); thus the user must call // init after constructing a HashMap and check the return value. - HashMap(AllocPolicy a = AllocPolicy()) - : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Key type must be relocatable"); - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Value type must be relocatable"); - } - + HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -142,18 +138,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, Move(e)); + return impl.relookupOrAdd(p, k, mozilla::Move(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -203,10 +199,10 @@ class HashMap // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -235,7 +231,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, Move(e)); + return impl.putNew(k, mozilla::Move(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -253,9 +249,17 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const Key &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashMap is movable - HashMap(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashMap is not copyable or assignable @@ -303,11 +307,7 @@ class HashSet // HashSet construction is fallible (due to OOM); thus the user must call // init after constructing a HashSet and check the return value. - HashSet(AllocPolicy a = AllocPolicy()) : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Set element type must be relocatable"); - } + HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -411,10 +411,10 @@ class HashSet // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -448,9 +448,17 @@ class HashSet remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const T &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashSet is movable - HashSet(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashSet is not copyable or assignable @@ -532,7 +540,7 @@ struct DefaultHasher // Specialize hashing policy for pointer types. It assumes that the type is // at least word-aligned. For types with smaller size use PointerHasher. template -struct DefaultHasher : PointerHasher::result> +struct DefaultHasher : PointerHasher::value> {}; // For doubles, we can xor the two uint32s. @@ -542,18 +550,11 @@ struct DefaultHasher typedef double Lookup; static HashNumber hash(double d) { JS_STATIC_ASSERT(sizeof(HashNumber) == 4); - union { - struct { - uint32_t lo; - uint32_t hi; - } s; - double d; - } u; - u.d = d; - return u.s.lo ^ u.s.hi; + uint64_t u = mozilla::BitwiseCast(d); + return HashNumber(u ^ (u >> 32)); } static bool match(double lhs, double rhs) { - return lhs == rhs; + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); } }; @@ -577,8 +578,8 @@ class HashMapEntry template HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} - HashMapEntry(MoveRef rhs) - : key(Move(rhs->key)), value(Move(rhs->value)) { } + HashMapEntry(mozilla::MoveRef rhs) + : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -647,8 +648,8 @@ class HashTableEntry } void swap(HashTableEntry *other) { - Swap(keyHash, other->keyHash); - Swap(mem, other->mem); + mozilla::Swap(keyHash, other->keyHash); + mozilla::Swap(mem, other->mem); } T &get() { JS_ASSERT(isLive()); return *mem.addr(); } @@ -807,10 +808,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - typename HashTableEntry::NonConstT t(Move(this->cur->get())); - HashPolicy::setKey(t, const_cast(k)); - table.remove(*this->cur); - table.putNewInfallible(l, Move(t)); + table.rekey(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -832,13 +830,13 @@ class HashTable : private AllocPolicy }; // HashTable is movable - HashTable(MoveRef rhs) + HashTable(mozilla::MoveRef rhs) : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); rhs->table = NULL; } - void operator=(MoveRef rhs) { + void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); @@ -882,7 +880,7 @@ class HashTable : private AllocPolicy # define METER(x) #endif - friend class js::ReentrancyGuard; + friend class mozilla::ReentrancyGuard; mutable mozilla::DebugOnly entered; mozilla::DebugOnly mutationCount; @@ -892,7 +890,7 @@ class HashTable : private AllocPolicy static const unsigned sMinCapacity = 1 << sMinCapacityLog2; static const unsigned sMaxInit = JS_BIT(23); static const unsigned sMaxCapacity = JS_BIT(24); - static const unsigned sHashBits = tl::BitSize::result; + static const unsigned sHashBits = mozilla::tl::BitSize::value; static const uint8_t sMinAlphaFrac = 64; // (0x100 * .25) static const uint8_t sMaxAlphaFrac = 192; // (0x100 * .75) static const uint8_t sInvMaxAlpha = 171; // (ceil(0x100 / .75) >> 1) @@ -1165,7 +1163,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); src->destroy(); } } @@ -1346,19 +1344,19 @@ class HashTable : private AllocPolicy return gen; } - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(table); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); } Ptr lookup(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); return Ptr(lookup(l, keyHash, 0)); } @@ -1371,7 +1369,7 @@ class HashTable : private AllocPolicy AddPtr lookupForAdd(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); Entry &entry = lookup(l, keyHash, sCollisionBit); AddPtr p(entry, keyHash); @@ -1382,7 +1380,7 @@ class HashTable : private AllocPolicy template bool add(AddPtr &p, const U &rhs) { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(mutationCount == p.mutationCount); JS_ASSERT(table); JS_ASSERT(!p.found()); @@ -1443,7 +1441,7 @@ class HashTable : private AllocPolicy { p.mutationCount = mutationCount; { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); p.entry_ = &lookup(l, p.keyHash, sCollisionBit); } return p.found() || add(p, u); @@ -1452,17 +1450,27 @@ class HashTable : private AllocPolicy void remove(Ptr p) { JS_ASSERT(table); - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); remove(*p.entry_); checkUnderloaded(); } + void rekey(Ptr p, const Lookup &l, const Key &k) + { + JS_ASSERT(table); + mozilla::ReentrancyGuard g(*this); + JS_ASSERT(p.found()); + typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + HashPolicy::setKey(t, const_cast(k)); + remove(*p.entry_); + putNewInfallible(l, mozilla::Move(t)); + } + #undef METER }; } // namespace detail } // namespace js -#endif // js_HashTable_h__ - +#endif /* js_HashTable_h */ diff --git a/external/spidermonkey/include/android/js/HeapAPI.h b/external/spidermonkey/include/android/js/HeapAPI.h index f0f4411ac9..4d739304bc 100644 --- a/external/spidermonkey/include/android/js/HeapAPI.h +++ b/external/spidermonkey/include/android/js/HeapAPI.h @@ -4,33 +4,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_heap_api_h___ -#define js_heap_api_h___ +#ifndef js_HeapAPI_h +#define js_HeapAPI_h #include "jspubtd.h" +#include "js/Utility.h" + /* These values are private to the JS engine. */ namespace js { namespace gc { -/* - * Page size must be static to support our arena pointer optimizations, so we - * are forced to support each platform with non-4096 pages as a special case. - * Note: The freelist supports a maximum arena shift of 15. - * Note: Do not use JS_CPU_SPARC here, this header is used outside JS. - */ -#if (defined(SOLARIS) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \ - (defined(__sparc) || defined(__sparcv9) || defined(__ia64)) -const size_t PageShift = 13; -const size_t ArenaShift = PageShift; -#elif defined(__powerpc64__) -const size_t PageShift = 16; const size_t ArenaShift = 12; -#else -const size_t PageShift = 12; -const size_t ArenaShift = PageShift; -#endif -const size_t PageSize = size_t(1) << PageShift; const size_t ArenaSize = size_t(1) << ArenaShift; const size_t ArenaMask = ArenaSize - 1; @@ -67,7 +52,7 @@ namespace shadow { struct ArenaHeader { - js::Zone *zone; + JS::Zone *zone; }; struct Zone @@ -153,10 +138,10 @@ IsIncrementalBarrierNeededOnGCThing(shadow::Runtime *rt, void *thing, JSGCTraceK { if (!rt->needsBarrier_) return false; - js::Zone *zone = GetGCThingZone(thing); + JS::Zone *zone = GetGCThingZone(thing); return reinterpret_cast(zone)->needsBarrier_; } } /* namespace JS */ -#endif /* js_heap_api_h___ */ +#endif /* js_HeapAPI_h */ diff --git a/external/spidermonkey/include/android/js/LegacyIntTypes.h b/external/spidermonkey/include/android/js/LegacyIntTypes.h index 387a68b9e9..2c8498c89e 100644 --- a/external/spidermonkey/include/android/js/LegacyIntTypes.h +++ b/external/spidermonkey/include/android/js/LegacyIntTypes.h @@ -17,13 +17,12 @@ * Indeed, if you use this header and third-party code defining these * types, *expect* to encounter either compile errors or link errors, * depending how these types are used and on the order of inclusion. - * It is safest to use only the JSAPI -style types, - * customizing those types using MOZ_CUSTOM_STDINT_H if necessary. + * It is safest to use only the types. */ -#ifndef PROTYPES_H -#define PROTYPES_H +#ifndef js_LegacyIntTypes_h +#define js_LegacyIntTypes_h -#include "mozilla/StandardInteger.h" +#include #include "js-config.h" @@ -57,4 +56,4 @@ typedef int16_t JSInt16; typedef int32_t JSInt32; typedef int64_t JSInt64; -#endif /* !defined(PROTYPES_H) */ +#endif /* js_LegacyIntTypes_h */ diff --git a/external/spidermonkey/include/android/js/MemoryMetrics.h b/external/spidermonkey/include/android/js/MemoryMetrics.h index 7e84f2ae11..ed61e1c427 100644 --- a/external/spidermonkey/include/android/js/MemoryMetrics.h +++ b/external/spidermonkey/include/android/js/MemoryMetrics.h @@ -10,6 +10,8 @@ // These declarations are not within jsapi.h because they are highly likely to // change in the future. Depend on them at your own risk. +#include "mozilla/MemoryReporting.h" + #include #include "jsalloc.h" @@ -91,7 +93,6 @@ struct TypeInferenceSizes // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t jaeger; size_t ion; size_t asmJS; size_t baseline; @@ -136,7 +137,7 @@ struct RuntimeSizes size_t dtoa; size_t temporary; size_t regexpData; - size_t stack; + size_t interpreterStack; size_t gcMarker; size_t mathCache; size_t scriptData; @@ -153,9 +154,11 @@ struct ZoneStats gcHeapUnusedGcThings(0), gcHeapStringsNormal(0), gcHeapStringsShort(0), + gcHeapLazyScripts(0), gcHeapTypeObjects(0), gcHeapIonCodes(0), stringCharsNonHuge(0), + lazyScripts(0), typeObjects(0), typePool(0), hugeStrings() @@ -167,14 +170,16 @@ struct ZoneStats gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), gcHeapStringsNormal(other.gcHeapStringsNormal), gcHeapStringsShort(other.gcHeapStringsShort), + gcHeapLazyScripts(other.gcHeapLazyScripts), gcHeapTypeObjects(other.gcHeapTypeObjects), gcHeapIonCodes(other.gcHeapIonCodes), stringCharsNonHuge(other.stringCharsNonHuge), + lazyScripts(other.lazyScripts), typeObjects(other.typeObjects), typePool(other.typePool), hugeStrings() { - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // Add other's numbers to this object's numbers. @@ -186,16 +191,18 @@ struct ZoneStats ADD(gcHeapStringsNormal); ADD(gcHeapStringsShort); + ADD(gcHeapLazyScripts); ADD(gcHeapTypeObjects); ADD(gcHeapIonCodes); ADD(stringCharsNonHuge); + ADD(lazyScripts); ADD(typeObjects); ADD(typePool); #undef ADD - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // This field can be used by embedders. @@ -207,10 +214,12 @@ struct ZoneStats size_t gcHeapStringsNormal; size_t gcHeapStringsShort; + size_t gcHeapLazyScripts; size_t gcHeapTypeObjects; size_t gcHeapIonCodes; size_t stringCharsNonHuge; + size_t lazyScripts; size_t typeObjects; size_t typePool; @@ -241,7 +250,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(0), shapesCompartmentTables(0), scriptData(0), - jaegerData(0), baselineData(0), baselineStubsFallback(0), baselineStubsOptimized(0), @@ -271,7 +279,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), shapesCompartmentTables(other.shapesCompartmentTables), scriptData(other.scriptData), - jaegerData(other.jaegerData), baselineData(other.baselineData), baselineStubsFallback(other.baselineStubsFallback), baselineStubsOptimized(other.baselineStubsOptimized), @@ -306,7 +313,6 @@ struct CompartmentStats size_t shapesExtraTreeShapeKids; size_t shapesCompartmentTables; size_t scriptData; - size_t jaegerData; size_t baselineData; size_t baselineStubsFallback; size_t baselineStubsOptimized; @@ -339,7 +345,6 @@ struct CompartmentStats ADD(shapesExtraTreeShapeKids); ADD(shapesCompartmentTables); ADD(scriptData); - ADD(jaegerData); ADD(baselineData); ADD(baselineStubsFallback); ADD(baselineStubsOptimized); @@ -360,7 +365,7 @@ struct CompartmentStats struct RuntimeStats { - RuntimeStats(JSMallocSizeOfFun mallocSizeOf) + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) : runtime(), gcHeapChunkTotal(0), gcHeapDecommittedArenas(0), @@ -417,7 +422,7 @@ struct RuntimeStats ZoneStats *currZoneStats; - JSMallocSizeOfFun mallocSizeOf_; + mozilla::MallocSizeOf mallocSizeOf_; virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; @@ -454,4 +459,4 @@ PeakSizeOfTemporary(const JSRuntime *rt); } // namespace JS -#endif // js_MemoryMetrics_h +#endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/android/js/PropertyKey.h b/external/spidermonkey/include/android/js/PropertyKey.h index 53158c26f3..c949db13a5 100644 --- a/external/spidermonkey/include/android/js/PropertyKey.h +++ b/external/spidermonkey/include/android/js/PropertyKey.h @@ -6,8 +6,8 @@ /* JS::PropertyKey implementation. */ -#ifndef js_PropertyKey_h___ -#define js_PropertyKey_h___ +#ifndef js_PropertyKey_h +#define js_PropertyKey_h #include "mozilla/Attributes.h" @@ -95,4 +95,4 @@ ToPropertyKey(JSContext *cx, HandleValue v, PropertyKey *key) } // namespace JS -#endif /* js_PropertyKey_h___ */ +#endif /* js_PropertyKey_h */ diff --git a/external/spidermonkey/include/android/js/RequiredDefines.h b/external/spidermonkey/include/android/js/RequiredDefines.h index 2be2efbf9a..6af9ca871b 100644 --- a/external/spidermonkey/include/android/js/RequiredDefines.h +++ b/external/spidermonkey/include/android/js/RequiredDefines.h @@ -10,8 +10,8 @@ * or SpiderMonkey public headers may not work correctly. */ -#ifndef js_RequiredDefines_h___ -#define js_RequiredDefines_h___ +#ifndef js_RequiredDefines_h +#define js_RequiredDefines_h /* * The c99 defining the limit macros (UINT32_MAX for example), says: @@ -20,4 +20,4 @@ */ #define __STDC_LIMIT_MACROS -#endif /* js_RequiredDefines_h___ */ +#endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/android/js/RootingAPI.h b/external/spidermonkey/include/android/js/RootingAPI.h index 3e2e0d2a7c..99295f1238 100644 --- a/external/spidermonkey/include/android/js/RootingAPI.h +++ b/external/spidermonkey/include/android/js/RootingAPI.h @@ -4,14 +4,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsgc_root_h__ -#define jsgc_root_h__ +#ifndef js_RootingAPI_h +#define js_RootingAPI_h #include "mozilla/GuardObjects.h" #include "mozilla/TypeTraits.h" #include "js/Utility.h" -#include "js/TemplateLib.h" #include "jspubtd.h" @@ -99,9 +98,10 @@ namespace js { class Module; +class ScriptSourceObject; template -struct RootMethods {}; +struct GCMethods {}; template class RootedBase {}; @@ -112,6 +112,9 @@ class HandleBase {}; template class MutableHandleBase {}; +template +class HeapBase {}; + /* * js::NullPtr acts like a NULL pointer in contexts that require a Handle. * @@ -130,6 +133,10 @@ struct NullPtr static void * const constNullValue; }; +namespace gc { +struct Cell; +} /* namespace gc */ + } /* namespace js */ namespace JS { @@ -161,6 +168,204 @@ struct JS_PUBLIC_API(NullPtr) static void * const constNullValue; }; +/* + * The Heap class is a C/C++ heap-stored reference to a JS GC thing. All + * members of heap classes that refer to GC thing should use Heap (or + * possibly TenuredHeap, described below). + * + * Heap wraps the complex mechanisms required to ensure GC safety for the + * contained reference into a C++ class that behaves similarly to a normal + * pointer. + * + * GC references stored on the C/C++ stack must use Rooted/Handle/MutableHandle + * instead. + * + * Requirements for type T: + * - Must be one of: Value, jsid, JSObject*, JSString*, JSScript* + */ +template +class Heap : public js::HeapBase +{ + public: + Heap() { + static_assert(sizeof(T) == sizeof(Heap), + "Heap must be binary compatible with T."); + init(js::GCMethods::initial()); + } + explicit Heap(T p) { init(p); } + explicit Heap(const Heap &p) { init(p.ptr); } + + ~Heap() { + if (js::GCMethods::needsPostBarrier(ptr)) + relocate(); + } + + bool operator==(const Heap &other) { return ptr == other.ptr; } + bool operator!=(const Heap &other) { return ptr != other.ptr; } + + bool operator==(const T &other) const { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + + operator T() const { return ptr; } + T operator->() const { return ptr; } + const T *address() const { return &ptr; } + const T &get() const { return ptr; } + + T *unsafeGet() { return &ptr; } + + Heap &operator=(T p) { + set(p); + return *this; + } + + void set(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (js::GCMethods::needsPostBarrier(newPtr)) { + ptr = newPtr; + post(); + } else if (js::GCMethods::needsPostBarrier(ptr)) { + relocate(); /* Called before overwriting ptr. */ + ptr = newPtr; + } else { + ptr = newPtr; + } + } + + private: + void init(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + ptr = newPtr; + if (js::GCMethods::needsPostBarrier(ptr)) + post(); + } + + void post() { +#ifdef JSGC_GENERATIONAL + JS_ASSERT(js::GCMethods::needsPostBarrier(ptr)); + js::GCMethods::postBarrier(&ptr); +#endif + } + + void relocate() { +#ifdef JSGC_GENERATIONAL + js::GCMethods::relocate(&ptr); +#endif + } + + T ptr; +}; + +#ifdef DEBUG +/* + * For generational GC, assert that an object is in the tenured generation as + * opposed to being in the nursery. + */ +extern JS_FRIEND_API(void) +AssertGCThingMustBeTenured(JSObject* obj); +#else +inline void +AssertGCThingMustBeTenured(JSObject *obj) {} +#endif + +/* + * The TenuredHeap class is similar to the Heap class above in that it + * encapsulates the GC concerns of an on-heap reference to a JS object. However, + * it has two important differences: + * + * 1) Pointers which are statically known to only reference "tenured" objects + * can avoid the extra overhead of SpiderMonkey's write barriers. + * + * 2) Objects in the "tenured" heap have stronger alignment restrictions than + * those in the "nursery", so it is possible to store flags in the lower + * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged + * pointer with a nice API for accessing the flag bits and adds various + * assertions to ensure that it is not mis-used. + * + * GC things are said to be "tenured" when they are located in the long-lived + * heap: e.g. they have gained tenure as an object by surviving past at least + * one GC. For performance, SpiderMonkey allocates some things which are known + * to normally be long lived directly into the tenured generation; for example, + * global objects. Additionally, SpiderMonkey does not visit individual objects + * when deleting non-tenured objects, so object with finalizers are also always + * tenured; for instance, this includes most DOM objects. + * + * The considerations to keep in mind when using a TenuredHeap vs a normal + * Heap are: + * + * - It is invalid for a TenuredHeap to refer to a non-tenured thing. + * - It is however valid for a Heap to refer to a tenured thing. + * - It is not possible to store flag bits in a Heap. + */ +template +class TenuredHeap : public js::HeapBase +{ + public: + TenuredHeap() : bits(0) { + static_assert(sizeof(T) == sizeof(TenuredHeap), + "TenuredHeap must be binary compatible with T."); + } + explicit TenuredHeap(T p) : bits(0) { setPtr(p); } + explicit TenuredHeap(const TenuredHeap &p) : bits(0) { setPtr(p.ptr); } + + bool operator==(const TenuredHeap &other) { return bits == other.bits; } + bool operator!=(const TenuredHeap &other) { return bits != other.bits; } + + void setPtr(T newPtr) { + JS_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (newPtr) + AssertGCThingMustBeTenured(newPtr); + bits = (bits & flagsMask) | reinterpret_cast(newPtr); + } + + void setFlags(uintptr_t flagsToSet) { + JS_ASSERT((flagsToSet & ~flagsMask) == 0); + bits |= flagsToSet; + } + + void unsetFlags(uintptr_t flagsToUnset) { + JS_ASSERT((flagsToUnset & ~flagsMask) == 0); + bits &= ~flagsToUnset; + } + + bool hasFlag(uintptr_t flag) const { + JS_ASSERT((flag & ~flagsMask) == 0); + return (bits & flag) != 0; + } + + T getPtr() const { return reinterpret_cast(bits & ~flagsMask); } + uintptr_t getFlags() const { return bits & flagsMask; } + + operator T() const { return getPtr(); } + T operator->() const { return getPtr(); } + + TenuredHeap &operator=(T p) { + setPtr(p); + return *this; + } + + /* + * Set the pointer to a value which will cause a crash if it is + * dereferenced. + */ + void setToCrashOnTouch() { + bits = (bits & flagsMask) | crashOnTouchPointer; + } + + bool isSetToCrashOnTouch() { + return (bits & ~flagsMask) == crashOnTouchPointer; + } + + private: + enum { + maskBits = 3, + flagsMask = (1 << maskBits) - 1, + crashOnTouchPointer = 1 << maskBits + }; + + uintptr_t bits; +}; + /* * Reference to a T that has been rooted elsewhere. This is most useful * as a parameter type, which guarantees that the T lvalue is properly @@ -170,7 +375,7 @@ struct JS_PUBLIC_API(NullPtr) * specialization, define a HandleBase specialization containing them. */ template -class MOZ_STACK_CLASS Handle : public js::HandleBase +class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { friend class MutableHandle; @@ -180,20 +385,22 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase Handle(Handle handle, typename mozilla::EnableIf::value, int>::Type dummy = 0) { + static_assert(sizeof(Handle) == sizeof(T *), + "Handle must be binary compatible with T*."); ptr = reinterpret_cast(handle.address()); } /* Create a handle for a NULL pointer. */ Handle(js::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "js::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } /* Create a handle for a NULL pointer. */ Handle(JS::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "JS::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "JS::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&JS::NullPtr::constNullValue); } @@ -202,11 +409,19 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase } /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. + * Take care when calling this method! * - * Create a Handle from a raw location of a T. + * This creates a Handle from the raw location of a T. + * + * It should be called only if the following conditions hold: + * + * 1) the location of the T is guaranteed to be marked (for some reason + * other than being a Rooted), e.g., if it is guaranteed to be reachable + * from an implicit root. + * + * 2) the contents of the location are immutable, or at least cannot change + * for the lifetime of the handle, as its users may not expect its value + * to change underneath them. */ static Handle fromMarkedLocation(const T *p) { Handle h; @@ -230,13 +445,17 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase typename mozilla::EnableIf::value, int>::Type dummy = 0); const T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a Handle to something that + * takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } - bool operator!=(const T &other) { return *ptr != other; } - bool operator==(const T &other) { return *ptr == other; } + bool operator!=(const T &other) const { return *ptr != other; } + bool operator==(const T &other) const { return *ptr == other; } private: Handle() {} @@ -247,13 +466,14 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase void operator=(S v) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; +typedef Handle HandleObject; +typedef Handle HandleModule; +typedef Handle HandleScriptSource; +typedef Handle HandleFunction; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleId; +typedef Handle HandleValue; /* * Similar to a handle, but the underlying storage can be changed. This is @@ -270,7 +490,7 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase inline MutableHandle(Rooted *root); void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -288,9 +508,13 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase } T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a MutableHandle to something that takes + * a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } private: @@ -298,8 +522,8 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S v) MOZ_DELETE; + void operator=(MutableHandle other) MOZ_DELETE; }; typedef MutableHandle MutableHandleObject; @@ -309,6 +533,11 @@ typedef MutableHandle MutableHandleString; typedef MutableHandle MutableHandleId; typedef MutableHandle MutableHandleValue; +#ifdef JSGC_GENERATIONAL +JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); +JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); +#endif + } /* namespace JS */ namespace js { @@ -383,13 +612,28 @@ struct RootKind }; template -struct RootMethods +struct GCMethods { static T *initial() { return NULL; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } + static bool needsPostBarrier(T *v) { return v; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(T **vp) { + JS::HeapCellPostBarrier(reinterpret_cast(vp)); + } + static void relocate(T **vp) { + JS::HeapCellRelocate(reinterpret_cast(vp)); + } +#endif }; +#if defined(DEBUG) +/* This helper allows us to assert that Rooted is scoped within a request. */ +extern JS_PUBLIC_API(bool) +IsInRequest(JSContext *cx); +#endif + } /* namespace js */ namespace JS { @@ -405,46 +649,63 @@ namespace JS { template class MOZ_STACK_CLASS Rooted : public js::RootedBase { - void init(JSContext *cxArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ContextFriendFields *cx = js::ContextFriendFields::get(cxArg); - commonInit(cx->thingGCRooters); -#endif - } + /* Note: CX is a subclass of either ContextFriendFields or PerThreadDataFriendFields. */ + template + void init(CX *cx) { +#ifdef JSGC_TRACK_EXACT_ROOTS + js::ThingRootKind kind = js::GCMethods::kind(); + this->stack = &cx->thingGCRooters[kind]; + this->prev = *stack; + *stack = reinterpret_cast*>(this); - void init(js::PerThreadData *ptArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::PerThreadDataFriendFields *pt = js::PerThreadDataFriendFields::get(ptArg); - commonInit(pt->thingGCRooters); + JS_ASSERT(!js::GCMethods::poisoned(ptr)); #endif } public: Rooted(JSContext *cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; - init(cx); + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); } Rooted(JSContext *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); + } + + Rooted(js::ContextFriendFields *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(cx); } - Rooted(js::PerThreadData *pt + Rooted(js::ContextFriendFields *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(cx); + } + + Rooted(js::PerThreadDataFriendFields *pt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(pt); } - Rooted(js::PerThreadData *pt, T initial + Rooted(js::PerThreadDataFriendFields *pt, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { @@ -452,18 +713,38 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(pt); } + Rooted(JSRuntime *rt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + + Rooted(JSRuntime *rt, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + ~Rooted() { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; #endif } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } #endif - operator T() const { return ptr; } + /* + * Important: Return a reference here so passing a Rooted to + * something that takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return ptr; } T operator->() const { return ptr; } T *address() { return &ptr; } const T *address() const { return &ptr; } @@ -471,7 +752,7 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!js::RootMethods::poisoned(value)); + JS_ASSERT(!js::GCMethods::poisoned(value)); ptr = value; return ptr; } @@ -481,28 +762,25 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } - - private: - void commonInit(Rooted **thingGCRooters) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ThingRootKind kind = js::RootMethods::kind(); - this->stack = &thingGCRooters[kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - - JS_ASSERT(!js::RootMethods::poisoned(ptr)); -#endif + void set(T value) { + JS_ASSERT(!js::GCMethods::poisoned(value)); + ptr = value; } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } + + private: +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted **stack, *prev; #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) /* Has the rooting analysis ever scanned this Rooted's stack location? */ friend void JS::CheckStackRoots(JSContext*); +#endif + +#ifdef JSGC_ROOT_ANALYSIS bool scanned; #endif @@ -523,13 +801,14 @@ template <> class Rooted; #endif -typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedId; -typedef Rooted RootedValue; +typedef Rooted RootedObject; +typedef Rooted RootedModule; +typedef Rooted RootedScriptSource; +typedef Rooted RootedFunction; +typedef Rooted RootedScript; +typedef Rooted RootedString; +typedef Rooted RootedId; +typedef Rooted RootedValue; } /* namespace JS */ @@ -549,8 +828,9 @@ class SkipRoot const uint8_t *start; const uint8_t *end; - template - void init(SkipRoot **head, const T *ptr, size_t count) { + template + void init(CX *cx, const T *ptr, size_t count) { + SkipRoot **head = &cx->skipGCRooters; this->stack = head; this->prev = *stack; *stack = this; @@ -559,23 +839,6 @@ class SkipRoot } public: - template - SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - init(&ContextFriendFields::get(cx)->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - template - SkipRoot(js::PerThreadData *ptd, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - PerThreadDataFriendFields *ptff = PerThreadDataFriendFields::get(ptd); - init(&ptff->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - ~SkipRoot() { JS_ASSERT(*stack == this); *stack = prev; @@ -589,22 +852,36 @@ class SkipRoot #else /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} + public: + +#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(ContextFriendFields::get(cx), ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } template - SkipRoot(PerThreadData *ptd, const T *ptr, size_t count = 1 + SkipRoot(ContextFriendFields *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(cx, ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } -#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + SkipRoot(PerThreadData *pt, const T *ptr, size_t count = 1 + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + { + init(PerThreadDataFriendFields::get(pt), ptr, count); + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + } MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; @@ -614,15 +891,17 @@ template class FakeRooted : public RootedBase { public: - FakeRooted(JSContext *cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(RootMethods::initial()) + template + FakeRooted(CX *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } - FakeRooted(JSContext *cx, T initial - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + template + FakeRooted(CX *cx, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; @@ -636,13 +915,13 @@ class FakeRooted : public RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!RootMethods::poisoned(value)); + JS_ASSERT(!GCMethods::poisoned(value)); ptr = value; return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } private: T ptr; @@ -666,7 +945,7 @@ class FakeMutableHandle : public js::MutableHandleBase } void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -727,13 +1006,11 @@ template class MaybeRooted typedef FakeMutableHandle MutableHandleType; static inline JS::Handle toHandle(HandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::Handle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::MutableHandle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } }; @@ -761,6 +1038,8 @@ template inline MutableHandle::MutableHandle(Rooted *root) { + static_assert(sizeof(MutableHandle) == sizeof(T *), + "MutableHandle must be binary compatible with T*."); ptr = root->address(); } @@ -779,10 +1058,6 @@ inline void MaybeCheckStackRoots(JSContext *cx) #endif } -namespace gc { -struct Cell; -} /* namespace gc */ - /* Base class for automatic read-only object rooting during compilation. */ class CompilerRootNode { @@ -801,4 +1076,4 @@ class CompilerRootNode } /* namespace js */ -#endif /* jsgc_root_h___ */ +#endif /* js_RootingAPI_h */ diff --git a/external/spidermonkey/include/android/js/TemplateLib.h b/external/spidermonkey/include/android/js/TemplateLib.h deleted file mode 100644 index a4ff682912..0000000000 --- a/external/spidermonkey/include/android/js/TemplateLib.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_template_lib_h__ -#define js_template_lib_h__ - -#include "jstypes.h" - -/* - * Library of reusable template meta-functions (that is, functions on types and - * compile-time values). Meta-functions are placed inside the 'tl' namespace to - * avoid conflict with non-meta functions that logically have the same name - * (e.g., js::tl::Min vs. js::Min). - */ - -namespace js { -namespace tl { - -/* Compute min/max/clamp. */ -template struct Min { - static const size_t result = i < j ? i : j; -}; -template struct Max { - static const size_t result = i > j ? i : j; -}; -template struct Clamp { - static const size_t result = i < min ? min : (i > max ? max : i); -}; - -/* Compute x^y. */ -template struct Pow { - static const size_t result = x * Pow::result; -}; -template struct Pow { - static const size_t result = 1; -}; - -/* Compute floor(log2(i)). */ -template struct FloorLog2 { - static const size_t result = 1 + FloorLog2::result; -}; -template <> struct FloorLog2<0> { /* Error */ }; -template <> struct FloorLog2<1> { static const size_t result = 0; }; - -/* Compute ceiling(log2(i)). */ -template struct CeilingLog2 { - static const size_t result = FloorLog2<2 * i - 1>::result; -}; - -/* Round up to the nearest power of 2. */ -template struct RoundUpPow2 { - static const size_t result = size_t(1) << CeilingLog2::result; -}; -template <> struct RoundUpPow2<0> { - static const size_t result = 1; -}; - -/* Compute the number of bits in the given unsigned type. */ -template struct BitSize { - static const size_t result = sizeof(T) * JS_BITS_PER_BYTE; -}; - -/* - * Produce an N-bit mask, where N <= BitSize::result. Handle the - * language-undefined edge case when N = BitSize::result. - */ -template struct NBitMask { - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |result| to assure - // its computation. - static const size_t checkPrecondition = 0 / size_t(N < BitSize::result); - static const size_t result = (size_t(1) << N) - 1 + checkPrecondition; -}; -template <> struct NBitMask::result> { - static const size_t result = size_t(-1); -}; - -/* - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template struct MulOverflowMask { - static const size_t result = - ~NBitMask::result - CeilingLog2::result>::result; -}; -template <> struct MulOverflowMask<0> { /* Error */ }; -template <> struct MulOverflowMask<1> { static const size_t result = 0; }; - -/* - * Generate a mask for T such that if (X & sUnsafeRangeSizeMask), an X-sized - * array of T's is big enough to cause a ptrdiff_t overflow when subtracting - * a pointer to the end of the array from the beginning. - */ -template struct UnsafeRangeSizeMask { - /* - * The '2' factor means the top bit is clear, sizeof(T) converts from - * units of elements to bytes. - */ - static const size_t result = MulOverflowMask<2 * sizeof(T)>::result; -}; - -template struct If { static const T result = v1; }; -template struct If { static const T result = v2; }; - -/* - * Traits class for identifying types that are implicitly barriered. - */ -template struct IsRelocatableHeapType { static const bool result = true; }; - -} /* namespace tl */ -} /* namespace js */ - -#endif /* js_template_lib_h__ */ diff --git a/external/spidermonkey/include/android/js/Utility.h b/external/spidermonkey/include/android/js/Utility.h index c4ebf7ced6..9d391e5c8a 100644 --- a/external/spidermonkey/include/android/js/Utility.h +++ b/external/spidermonkey/include/android/js/Utility.h @@ -4,13 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_utility_h__ -#define js_utility_h__ +#ifndef js_Utility_h +#define js_Utility_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" +#include "mozilla/Move.h" #include "mozilla/Scoped.h" +#include "mozilla/TemplateLib.h" #include #include @@ -22,8 +24,6 @@ #include "jstypes.h" -#include "js/TemplateLib.h" - /* The public JS engine namespace. */ namespace JS {} @@ -41,7 +41,6 @@ namespace js {} #define JS_ASSERT(expr) MOZ_ASSERT(expr) #define JS_ASSERT_IF(cond, expr) MOZ_ASSERT_IF(cond, expr) -#define JS_NOT_REACHED(reason) MOZ_NOT_REACHED(reason) #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) @@ -63,7 +62,7 @@ namespace js {} # define JS_DIAGNOSTICS_ASSERT(expr) ((void) 0) #endif -#define JS_STATIC_ASSERT(cond) MOZ_STATIC_ASSERT(cond, "JS_STATIC_ASSERT") +#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") #define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") extern MOZ_NORETURN JS_PUBLIC_API(void) @@ -84,10 +83,11 @@ extern JS_PUBLIC_API(void) JS_Abort(void); #else # ifdef DEBUG /* - * In order to test OOM conditions, when the shell command-line option - * |-A NUM| is passed, we fail continuously after the NUM'th allocation. + * In order to test OOM conditions, when the testing function + * oomAfterAllocations COUNT is passed, we fail continuously after the NUM'th + * allocation from now. */ -extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set from shell/js.cpp */ +extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set in builtins/TestingFunctions.cpp */ extern JS_PUBLIC_DATA(uint32_t) OOM_counter; /* data race, who cares. */ #ifdef JS_OOM_DO_BACKTRACES @@ -157,6 +157,12 @@ static JS_INLINE void* js_calloc(size_t bytes) return calloc(bytes, 1); } +static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +{ + JS_OOM_POSSIBLY_FAIL(); + return calloc(nmemb, size); +} + static JS_INLINE void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); @@ -169,205 +175,6 @@ static JS_INLINE void js_free(void* p) } #endif/* JS_USE_CUSTOM_ALLOCATOR */ -JS_BEGIN_EXTERN_C - -/* - * Replace bit-scanning code sequences with CPU-specific instructions to - * speedup calculations of ceiling/floor log2. - * - * With GCC 3.4 or later we can use __builtin_clz for that, see bug 327129. - * - * SWS: Added MSVC intrinsic bitscan support. See bugs 349364 and 356856. - */ -#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) - -unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask); -unsigned char _BitScanReverse(unsigned long * Index, unsigned long Mask); -# pragma intrinsic(_BitScanForward,_BitScanReverse) - -__forceinline static int -__BitScanForward32(unsigned int val) -{ - unsigned long idx; - - _BitScanForward(&idx, (unsigned long)val); - return (int)idx; -} -__forceinline static int -__BitScanReverse32(unsigned int val) -{ - unsigned long idx; - - _BitScanReverse(&idx, (unsigned long)val); - return (int)(31-idx); -} -# define js_bitscan_ctz32(val) __BitScanForward32(val) -# define js_bitscan_clz32(val) __BitScanReverse32(val) -# define JS_HAS_BUILTIN_BITSCAN32 - -#if defined(_M_AMD64) || defined(_M_X64) -unsigned char _BitScanForward64(unsigned long * Index, unsigned __int64 Mask); -unsigned char _BitScanReverse64(unsigned long * Index, unsigned __int64 Mask); -# pragma intrinsic(_BitScanForward64,_BitScanReverse64) - -__forceinline static int -__BitScanForward64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanForward64(&idx, val); - return (int)idx; -} -__forceinline static int -__BitScanReverse64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanReverse64(&idx, val); - return (int)(63-idx); -} -# define js_bitscan_ctz64(val) __BitScanForward64(val) -# define js_bitscan_clz64(val) __BitScanReverse64(val) -# define JS_HAS_BUILTIN_BITSCAN64 -#endif -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(3, 4, 0) -# define USE_BUILTIN_CTZ -#endif - -#elif defined(__clang__) - -#if __has_builtin(__builtin_ctz) -# define USE_BUILTIN_CTZ -#endif - -#endif - -#if defined(USE_BUILTIN_CTZ) -# define js_bitscan_ctz32(val) __builtin_ctz(val) -# define js_bitscan_clz32(val) __builtin_clz(val) -# define JS_HAS_BUILTIN_BITSCAN32 -# if (JS_BYTES_PER_WORD == 8) -# define js_bitscan_ctz64(val) __builtin_ctzll(val) -# define js_bitscan_clz64(val) __builtin_clzll(val) -# define JS_HAS_BUILTIN_BITSCAN64 -# endif - -# undef USE_BUILTIN_CTZ - -#endif - -/* -** Macro version of JS_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use intrinsic function or count-leading-zeros to calculate ceil(log2(_n)). - * The macro checks for "n <= 1" and not "n != 0" as js_bitscan_clz32(0) is - * undefined. - */ -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - unsigned int j_ = (unsigned int)(_n); \ - (_log2) = (j_ <= 1 ? 0 : 32 - js_bitscan_clz32(j_ - 1)); \ - JS_END_MACRO -#else -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -/* -** Macro version of JS_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use js_bitscan_clz32 or count-leading-zeros to calculate floor(log2(_n)). - * Since js_bitscan_clz32(0) is undefined, the macro set the loweset bit to 1 - * to ensure 0 result when _n == 0. - */ -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - (_log2) = 31 - js_bitscan_clz32(((unsigned int)(_n)) | 1); \ - JS_END_MACRO -#else -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -#if JS_BYTES_PER_WORD == 4 -# ifdef JS_HAS_BUILTIN_BITSCAN32 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz32(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#elif JS_BYTES_PER_WORD == 8 -# ifdef JS_HAS_BUILTIN_BITSCAN64 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz64(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#else -# error "NOT SUPPORTED" -#endif - -JS_END_EXTERN_C - -/* - * Internal function. - * Compute the log of the least power of 2 greater than or equal to n. This is - * a version of JS_CeilingLog2 that operates on unsigned integers with - * CPU-dependant size. - */ -#define JS_CEILING_LOG2W(n) ((n) <= 1 ? 0 : 1 + JS_FLOOR_LOG2W((n) - 1)) - -/* - * Internal function. - * Compute the log of the greatest power of 2 less than or equal to n. - * This is a version of JS_FloorLog2 that operates on unsigned integers with - * CPU-dependant size and requires that n != 0. - */ -static MOZ_ALWAYS_INLINE size_t -JS_FLOOR_LOG2W(size_t n) -{ - JS_ASSERT(n != 0); - return js_FloorLog2wImpl(n); -} - /* * JS_ROTATE_LEFT32 * @@ -552,7 +359,7 @@ template static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_malloc(numElems * sizeof(T)); } @@ -561,7 +368,7 @@ template static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_calloc(numElems * sizeof(T)); } @@ -595,175 +402,6 @@ SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) namespace js { -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables also need to - * be resized. - * - * The details of the optimization, and whether it's worth applying, vary from - * one type to the next. And while some constructor calls are moves, many really - * are copies, and can't be optimized this way. So we need: - * - * 1) a way for a particular invocation of a copy constructor to say that it's - * really a move, and that the value of the original isn't important - * afterwards (althought it must still be safe to destroy); and - * - * 2) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation. - * - * The Move(T &) function takes a reference to a T, and returns an MoveRef - * referring to the same value; that's 1). An MoveRef is simply a reference - * to a T, annotated to say that a copy constructor applied to it may move that - * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). - * - * So, where we might define a copy constructor for a class C like this: - * - * C(const C &rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(MoveRef rhs) { ... move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)) - * - * Note that MoveRef implicitly converts to T &, so you can pass an - * MoveRef to an ordinary copy constructor for a type that doesn't support a - * special move constructor, and you'll just get a copy. This means that - * templates can use Move whenever they know they won't use the original value - * any more, even if they're not sure whether the type at hand has a specialized - * move constructor. If it doesn't, the MoveRef will just convert to a T &, - * and the ordinary copy constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator, - * which runs this's destructor, and then applies the move constructor to - * *this's memory. A typical definition: - * - * C &operator=(MoveRef rhs) { - * this->~C(); - * new(this) C(rhs); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * This header file defines MoveRef and Move in the js namespace. It's up to - * individual containers to annotate moves as such, by calling Move; and it's up - * to individual types to define move constructors. - * - * One hint: if you're writing a move constructor where the type has members - * that should be moved themselves, it's much nicer to write this: - * - * C(MoveRef c) : x(c->x), y(c->y) { } - * - * than the equivalent: - * - * C(MoveRef c) { new(&x) X(c->x); new(&y) Y(c->y); } - * - * especially since GNU C++ fails to notice that this does indeed initialize x - * and y, which may matter if they're const. - */ -template -class MoveRef { - public: - typedef T Referent; - explicit MoveRef(T &t) : pointer(&t) { } - T &operator*() const { return *pointer; } - T *operator->() const { return pointer; } - operator T& () const { return *pointer; } - private: - T *pointer; -}; - -template -MoveRef Move(T &t) { return MoveRef(t); } - -template -MoveRef Move(const T &t) { return MoveRef(const_cast(t)); } - -/* Useful for implementing containers that assert non-reentrancy */ -class ReentrancyGuard -{ - /* ReentrancyGuard is not copyable. */ - ReentrancyGuard(const ReentrancyGuard &); - void operator=(const ReentrancyGuard &); - -#ifdef DEBUG - bool &entered; -#endif - public: - template -#ifdef DEBUG - ReentrancyGuard(T &obj) - : entered(obj.entered) -#else - ReentrancyGuard(T &/*obj*/) -#endif - { -#ifdef DEBUG - JS_ASSERT(!entered); - entered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - entered = false; -#endif - } -}; - -template -JS_ALWAYS_INLINE static void -Swap(T &t, T &u) -{ - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); -} - -/* - * Round x up to the nearest power of 2. This function assumes that the most - * significant bit of x is not set, which would lead to overflow. - */ -JS_ALWAYS_INLINE size_t -RoundUpPow2(size_t x) -{ - return size_t(1) << JS_CEILING_LOG2W(x); -} - /* Integral types for all hash functions. */ typedef uint32_t HashNumber; const unsigned HashNumberSizeBits = 32; @@ -845,11 +483,6 @@ inline bool IsPoisonedPtr(T *v) } -/* - * This is SpiderMonkey's equivalent to |nsMallocSizeOfFun|. - */ -typedef size_t(*JSMallocSizeOfFun)(const void *p); - /* sixgill annotation defines */ #ifndef HAVE_STATIC_ANNOTATIONS # define HAVE_STATIC_ANNOTATIONS @@ -891,4 +524,4 @@ typedef size_t(*JSMallocSizeOfFun)(const void *p); # define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) #endif /* HAVE_STATIC_ANNOTATIONS */ -#endif /* js_utility_h__ */ +#endif /* js_Utility_h */ diff --git a/external/spidermonkey/include/android/js/Value.h b/external/spidermonkey/include/android/js/Value.h index 2c7fa1a600..9b2c5dd6f9 100644 --- a/external/spidermonkey/include/android/js/Value.h +++ b/external/spidermonkey/include/android/js/Value.h @@ -6,8 +6,8 @@ /* JS::Value implementation. */ -#ifndef js_Value_h___ -#define js_Value_h___ +#ifndef js_Value_h +#define js_Value_h #include "mozilla/Attributes.h" #include "mozilla/FloatingPoint.h" @@ -53,7 +53,7 @@ namespace JS { class Value; } * nice symbolic type tags, however we can only do this when we can force the * underlying type of the enum to be the desired size. */ -#if defined(__cplusplus) && !defined(__SUNPRO_CC) && !defined(__xlC__) +#if !defined(__SUNPRO_CC) && !defined(__xlC__) #if defined(_MSC_VER) # define JS_ENUM_HEADER(id, type) enum id : type @@ -132,7 +132,7 @@ JS_STATIC_ASSERT(sizeof(JSValueShiftedTag) == sizeof(uint64_t)); #endif -#else /* defined(__cplusplus) */ +#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ typedef uint8_t JSValueType; #define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) @@ -180,7 +180,7 @@ typedef uint64_t JSValueShiftedTag; #define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) #endif /* JS_BITS_PER_WORD */ -#endif /* defined(__cplusplus) && !defined(__SUNPRO_CC) */ +#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ #define JSVAL_LOWER_INCL_TYPE_OF_OBJ_OR_NULL_SET JSVAL_TYPE_NULL #define JSVAL_UPPER_EXCL_TYPE_OF_PRIMITIVE_SET JSVAL_TYPE_OBJECT @@ -265,7 +265,7 @@ typedef union jsval_layout typedef union jsval_layout { uint64_t asBits; -#if (!defined(_WIN64) && defined(__cplusplus)) +#if !defined(_WIN64) /* MSVC does not pack these correctly :-( */ struct { uint64_t payload47 : 47; @@ -321,7 +321,6 @@ typedef union jsval_layout int32_t i32; uint32_t u32; JSWhyMagic why; - uintptr_t word; } payload; } s; double asDouble; @@ -803,22 +802,31 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ -static inline double -JS_CANONICALIZE_NAN(double d) -{ - if (MOZ_UNLIKELY(d != d)) { - jsval_layout l; - l.asBits = 0x7FF8000000000000LL; - return l.asDouble; - } - return d; -} - static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +/** + * Returns a generic quiet NaN value, with all payload bits set to zero. + * + * Among other properties, this NaN's bit pattern conforms to JS::Value's + * bit pattern restrictions. + */ +static MOZ_ALWAYS_INLINE double +GenericNaN() +{ + return mozilla::SpecificNaN(0, 0x8000000000000ULL); +} + +static inline double +CanonicalizeNaN(double d) +{ + if (MOZ_UNLIKELY(mozilla::IsNaN(d))) + return GenericNaN(); + return d; +} + /* * JS::Value is the interface for a single JavaScript Engine value. A few * general notes on JS::Value: @@ -1393,22 +1401,35 @@ SameType(const Value &lhs, const Value &rhs) /************************************************************************/ +#ifdef JSGC_GENERATIONAL +namespace JS { +JS_PUBLIC_API(void) HeapValuePostBarrier(Value *valuep); +JS_PUBLIC_API(void) HeapValueRelocate(Value *valuep); +} +#endif + namespace js { -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } }; -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } + static bool needsPostBarrier(const JS::Value &v) { return v.isMarkable(); } +#ifdef JSGC_GENERATIONAL + static void postBarrier(JS::Value *v) { JS::HeapValuePostBarrier(v); } + static void relocate(JS::Value *v) { JS::HeapValueRelocate(v); } +#endif }; +template class UnbarrieredMutableValueOperations; template class MutableValueOperations; /* @@ -1420,7 +1441,9 @@ template class MutableValueOperations; template class ValueOperations { + friend class UnbarrieredMutableValueOperations; friend class MutableValueOperations; + const JS::Value * value() const { return static_cast(this)->extract(); } public: @@ -1453,19 +1476,22 @@ class ValueOperations void *toGCThing() const { return value()->toGCThing(); } JSValueType extractNonDoubleType() const { return value()->extractNonDoubleType(); } + uint32_t toPrivateUint32() const { return value()->toPrivateUint32(); } JSWhyMagic whyMagic() const { return value()->whyMagic(); } }; /* - * A class designed for CRTP use in implementing the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible extractMutable() and extract() - * methods returning the const Value* and Value* abstracted by Outer. + * A class designed for CRTP use in implementing the mutating parts of the Value + * interface in Value-like classes that don't need post barriers. Outer must be + * a class inheriting UnbarrieredMutableValueOperations with visible + * extractMutable() and extract() methods returning the const Value* and Value* + * abstracted by Outer. */ template -class MutableValueOperations : public ValueOperations +class UnbarrieredMutableValueOperations : public ValueOperations { + friend class MutableValueOperations; JS::Value * value() { return static_cast(this)->extractMutable(); } public: @@ -1473,14 +1499,66 @@ class MutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } - void setString(JSString *str) { value()->setString(str); } - void setString(const JS::Anchor &str) { value()->setString(str); } - void setObject(JSObject &obj) { value()->setObject(obj); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } bool setNumber(double d) { return value()->setNumber(d); } - void setObjectOrNull(JSObject *arg) { value()->setObjectOrNull(arg); } +}; + +/* + * A class designed for CRTP use in implementing all the mutating parts of the + * Value interface in Value-like classes. Outer must be a class inheriting + * MutableValueOperations with visible extractMutable() and extract() + * methods returning the const Value* and Value* abstracted by Outer. + */ +template +class MutableValueOperations : public UnbarrieredMutableValueOperations +{ + public: + void setString(JSString *str) { this->value()->setString(str); } + void setString(const JS::Anchor &str) { this->value()->setString(str); } + void setObject(JSObject &obj) { this->value()->setObject(obj); } + void setObjectOrNull(JSObject *arg) { this->value()->setObjectOrNull(arg); } +}; + +/* + * Augment the generic Heap interface when T = Value with + * type-querying, value-extracting, and mutating operations. + */ +template <> +class HeapBase : public UnbarrieredMutableValueOperations > +{ + typedef JS::Heap Outer; + + friend class ValueOperations; + friend class UnbarrieredMutableValueOperations; + + const JS::Value * extract() const { return static_cast(this)->address(); } + JS::Value * extractMutable() { return static_cast(this)->unsafeGet(); } + + /* + * Setters that potentially change the value to a GC thing from a non-GC + * thing must call JS::Heap::set() to trigger the post barrier. + * + * Changing from a GC thing to a non-GC thing value will leave the heap + * value in the store buffer, but it will be ingored so this is not a + * problem. + */ + void setBarriered(const JS::Value &v) { + static_cast *>(this)->set(v); + } + + public: + void setString(JSString *str) { setBarriered(JS::StringValue(str)); } + void setString(const JS::Anchor &str) { setBarriered(JS::StringValue(str.get())); } + void setObject(JSObject &obj) { setBarriered(JS::ObjectValue(obj)); } + + void setObjectOrNull(JSObject *arg) { + if (arg) + setObject(*arg); + else + setNull(); + } }; /* @@ -1508,6 +1586,7 @@ class MutableHandleBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1526,6 +1605,7 @@ class RootedBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1574,12 +1654,12 @@ inline Anchor::~Anchor() namespace detail { struct ValueAlignmentTester { char c; JS::Value v; }; -MOZ_STATIC_ASSERT(sizeof(ValueAlignmentTester) == 16, - "JS::Value must be 16-byte-aligned"); +static_assert(sizeof(ValueAlignmentTester) == 16, + "JS::Value must be 16-byte-aligned"); struct LayoutAlignmentTester { char c; jsval_layout l; }; -MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, - "jsval_layout must be 16-byte-aligned"); +static_assert(sizeof(LayoutAlignmentTester) == 16, + "jsval_layout must be 16-byte-aligned"); } // namespace detail #endif /* DEBUG */ @@ -1593,8 +1673,8 @@ MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, */ typedef JS::Value jsval; -MOZ_STATIC_ASSERT(sizeof(jsval_layout) == sizeof(JS::Value), - "jsval_layout and JS::Value must have identical layouts"); +static_assert(sizeof(jsval_layout) == sizeof(JS::Value), + "jsval_layout and JS::Value must have identical layouts"); /************************************************************************/ @@ -1762,4 +1842,4 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } -#endif /* js_Value_h___ */ +#endif /* js_Value_h */ diff --git a/external/spidermonkey/include/android/js/Vector.h b/external/spidermonkey/include/android/js/Vector.h index 5f40dd634b..b14d75c758 100644 --- a/external/spidermonkey/include/android/js/Vector.h +++ b/external/spidermonkey/include/android/js/Vector.h @@ -4,14 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsvector_h_ -#define jsvector_h_ +#ifndef js_Vector_h +#define js_Vector_h -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "TemplateLib.h" -#include "Utility.h" +#include "mozilla/Vector.h" /* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ #ifdef _MSC_VER @@ -23,1085 +19,48 @@ namespace js { class TempAllocPolicy; -template +// using Vector = mozilla::Vector; +// +// ...and get rid of all the CRTP madness in mozilla::Vector(Base). But we +// can't because compiler support's not up to snuff. (Template aliases are in +// gcc 4.7 and clang 3.0 and are expected to be in MSVC 2013.) Instead, have a +// completely separate class inheriting from mozilla::Vector, and throw CRTP at +// the problem til things work. +// +// This workaround presents a couple issues. First, because js::Vector is a +// distinct type from mozilla::Vector, overload resolution, method calls, etc. +// are affected. *Hopefully* this won't be too bad in practice. (A bunch of +// places had to be fixed when mozilla::Vector was introduced, but it wasn't a +// crazy number.) Second, mozilla::Vector's interface has to be made subclass- +// ready via CRTP -- or rather, via mozilla::VectorBase, which basically no one +// should use. :-) Third, we have to redefine the constructors and the non- +// inherited operators. Blech. Happily there aren't too many of these, so it +// isn't the end of the world. + +template -class Vector; - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that cap*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring - * this. - */ -template -static bool CapacityHasExcessSpace(size_t cap) +class Vector + : public mozilla::VectorBase > { - size_t size = cap * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* Destroys constructed objects in the range [begin, end). */ - static inline void destroy(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - p->~T(); - } - - /* Constructs objects in the uninitialized range [begin, end). */ - static inline void initialize(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - /* - * Copy-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(*p); - } - - /* - * Move-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(Move(*p)); - } - - /* - * Copy-constructs objects in the uninitialized range [dst, dst+n) from the - * same object u. - */ - template - static inline void copyConstructN(T *dst, size_t n, const U &u) { - for (T *end = dst + n; dst != end; ++dst) - new(dst) T(u); - } - - /* - * Grows the given buffer to have capacity newCap, preserving the objects - * constructed in the range [begin, end) and updating v. Assumes that (1) - * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will - * not overflow. - */ - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); - if (!newbuf) - return false; - for (T *dst = newbuf, *src = v.beginNoCheck(); src != v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); - VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); - v.free_(v.mBegin); - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - static inline void destroy(T *, T *) {} - - static inline void initialize(T *begin, T *end) { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(begin, 0, sizeof(T) * (end-begin)); - */ - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); - */ - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - *dst = *p; - } - - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - copyConstruct(dst, srcbeg, srcend); - } - - static inline void copyConstructN(T *dst, size_t n, const T &t) { - for (T *p = dst, *end = dst + n; p != end; ++p) - *p = t; - } - - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - size_t oldSize = sizeof(T) * v.mCapacity; - size_t newSize = sizeof(T) * newCap; - T *newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); - if (!newbuf) - return false; - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * JS-friendly, STL-like container providing a short-lived, dynamic buffer. - * Vector calls the constructors/destructors of all elements stored in - * its internal buffer, so non-PODs may be safely used. Additionally, - * Vector will store the first N elements in-place before resorting to - * dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * N requirements: - * - any value, however, N is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in jsalloc.h (default js::TempAllocPolicy) - * - * N.B: Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object. - */ -template -class Vector : private AllocPolicy -{ - // typedef typename tl::StaticAssert::result>::result _; - - /* utilities */ - - static const bool sElemIsPod = mozilla::IsPod::value; - typedef VectorImpl Impl; - friend struct VectorImpl; - - bool growStorageBy(size_t incr); - bool convertToHeapStorage(size_t newCap); - - template inline bool growByImpl(size_t inc); - - /* magic constants */ - - static const int sMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are - * 0 inline elements. This allows us to compile when the definition - * of the element type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so - * in order to keep everything here, we use a dummy template - * parameter with partial specialization. - */ - template - struct ElemSize { - static const size_t result = sizeof(T); - }; - template - struct ElemSize<0, Dummy> { - static const size_t result = 1; - }; - - static const size_t sInlineCapacity = - tl::Min::result>::result; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t sInlineBytes = - tl::Max<1, sInlineCapacity * ElemSize::result>::result; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T *mBegin; - size_t mLength; /* Number of elements in the Vector. */ - size_t mCapacity; /* Max number of elements storable in the Vector without resizing. */ -#ifdef DEBUG - size_t mReserved; /* Max elements of reserved or used space in this vector. */ -#endif - - mozilla::AlignedStorage storage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool entered; -#endif - - Vector(const Vector &) MOZ_DELETE; - Vector &operator=(const Vector &) MOZ_DELETE; - - /* private accessors */ - - bool usingInlineStorage() const { - return mBegin == inlineStorage(); - } - - T *inlineStorage() const { - return (T *)storage.addr(); - } - - T *beginNoCheck() const { - return mBegin; - } - - T *endNoCheck() { - return mBegin + mLength; - } - - const T *endNoCheck() const { - return mBegin + mLength; - } - -#ifdef DEBUG - size_t reserved() const { - JS_ASSERT(mReserved <= mCapacity); - JS_ASSERT(mLength <= mReserved); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U u); - void internalAppendN(const T &t, size_t n); - template void internalAppend(const U *begin, size_t length); - template void internalAppend(const Vector &other); + typedef typename mozilla::VectorBase Base; public: - static const size_t sMaxInlineStorage = N; - - typedef T ElementType; - - Vector(AllocPolicy = AllocPolicy()); - Vector(MoveRef); /* Move constructor. */ - Vector &operator=(MoveRef); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy &allocPolicy() const { - return *this; + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector &operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); } - - AllocPolicy &allocPolicy() { - return *this; - } - - enum { InlineLength = N }; - - size_t length() const { - return mLength; - } - - bool empty() const { - return mLength == 0; - } - - size_t capacity() const { - return mCapacity; - } - - T *begin() { - JS_ASSERT(!entered); - return mBegin; - } - - const T *begin() const { - JS_ASSERT(!entered); - return mBegin; - } - - T *end() { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - const T *end() const { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - T &operator[](size_t i) { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - const T &operator[](size_t i) const { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - T &back() { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - const T &back() const { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - class Range { - friend class Vector; - T *cur_, *end_; - Range(T *cur, T *end) : cur_(cur), end_(end) {} - public: - Range() {} - bool empty() const { return cur_ == end_; } - size_t remain() const { return end_ - cur_; } - T &front() const { return *cur_; } - void popFront() { JS_ASSERT(!empty()); ++cur_; } - T popCopyFront() { JS_ASSERT(!empty()); return *cur_++; } - }; - - Range all() { - return Range(begin(), end()); - } - - /* mutators */ - - /* Given that the Vector is empty and has no inline storage, grow to |capacity|. */ - bool initCapacity(size_t request); - - /* If reserve(length() + N) succeeds, the N next appends are guaranteed to succeed. */ - bool reserve(size_t request); - - /* - * Destroy elements in the range [end() - incr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t incr); - - /* Grow the vector by incr elements. */ - bool growBy(size_t incr); - - /* Call shrinkBy or growBy based on whether newSize > length(). */ - bool resize(size_t newLength); - - /* Leave new elements as uninitialized memory. */ - bool growByUninitialized(size_t incr); - bool resizeUninitialized(size_t newLength); - - /* Shorthand for shrinkBy(length()). */ - void clear(); - - /* Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /* If true, appending |needed| elements will not call realloc(). */ - bool canAppendWithoutRealloc(size_t needed) const; - - /* - * Potentially fallible append operations. - * - * The function templates that take an unspecified type U require a - * const T & or a MoveRef. The MoveRef variants move their - * operands into the vector, instead of copying them. If they fail, the - * operand is left unmoved. - */ - template bool append(U t); - bool appendN(const T &t, size_t n); - template bool append(const U *begin, const U *end); - template bool append(const U *begin, size_t length); - template bool append(const Vector &other); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. - */ - template void infallibleAppend(const U &u) { - internalAppend(u); - } - void infallibleAppendN(const T &t, size_t n) { - internalAppendN(t, n); - } - template void infallibleAppend(const U *aBegin, const U *aEnd) { - internalAppend(aBegin, mozilla::PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U *aBegin, size_t aLength) { - internalAppend(aBegin, aLength); - } - template void infallibleAppend(const Vector &other) { - internalAppend(other); - } - - void popBack(); - - T popCopy(); - - /* - * Transfers ownership of the internal buffer used by Vector to the caller. - * After this call, the Vector is empty. Since the returned buffer may need - * to be allocated (if the elements are currently stored in-place), the - * call can fail, returning NULL. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - T *extractRawBuffer(); - - /* - * Transfer ownership of an array of objects into the Vector. - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T *p, size_t length); - - /* - * Places |val| at position |p|, shifting existing elements from |p| - * onward one position higher. On success, |p| should not be reused - * because it will be a dangling pointer if reallocation of the vector - * storage occurred; the return value should be used instead. On failure, - * NULL is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) - * - * - */ - T *insert(T *p, const T &val); - - /* - * Removes the element |t|, which must fall in the bounds [begin, end), - * shifting existing elements from |t + 1| onward one position lower. - */ - void erase(T *t); - - /* - * Measure the size of the Vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - /* - * Like sizeOfExcludingThis, but also measures the size of the Vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - void swap(Vector &other); }; -/* This does the re-entrancy check plus several other sanity checks. */ -#define REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - JS_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ - JS_ASSERT(reserved() <= mCapacity); \ - JS_ASSERT(mLength <= reserved()); \ - JS_ASSERT(mLength <= mCapacity) +} // namespace js -/* Vector Implementation */ - -template -JS_ALWAYS_INLINE -Vector::Vector(AllocPolicy ap) - : AllocPolicy(ap), mBegin((T *)storage.addr()), mLength(0), - mCapacity(sInlineCapacity) -#ifdef DEBUG - , mReserved(sInlineCapacity), entered(false) -#endif -{} - -/* Move constructor. */ -template -JS_ALWAYS_INLINE -Vector::Vector(MoveRef rhs) - : AllocPolicy(rhs) -#ifdef DEBUG - , entered(false) -#endif -{ - mLength = rhs->mLength; - mCapacity = rhs->mCapacity; -#ifdef DEBUG - mReserved = rhs->mReserved; -#endif - - if (rhs->usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = (T *)storage.addr(); - Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); - /* - * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = rhs->mBegin; - rhs->mBegin = (T *) rhs->storage.addr(); - rhs->mCapacity = sInlineCapacity; - rhs->mLength = 0; -#ifdef DEBUG - rhs->mReserved = sInlineCapacity; -#endif - } -} - -/* Move assignment. */ -template -JS_ALWAYS_INLINE -Vector & -Vector::operator=(MoveRef rhs) -{ - this->~Vector(); - new(this) Vector(rhs); - return *this; -} - -template -JS_ALWAYS_INLINE -Vector::~Vector() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); -} - -/* - * This function will create a new heap buffer with capacity newCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t newCap) -{ - JS_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); - if (!newBuf) - return false; - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = newCap; - return true; -} - -template -JS_NEVER_INLINE bool -Vector::growStorageBy(size_t incr) -{ - JS_ASSERT(mLength + incr > mCapacity); - JS_ASSERT_IF(!usingInlineStorage(), !CapacityHasExcessSpace(mCapacity)); - - /* - * When choosing a new capacity, its size should is as close to 2^N bytes - * as possible. 2^N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2^N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2^N request size. - */ - - size_t newCap; - - if (incr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::result; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength*4*sizeof(T) overflow? This condition limits a Vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. - * It also ensures that the ((char *)end() - (char *)begin()) does not - * overflow ptrdiff_t (see Bug 510319). - */ - if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::result) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is - * already as close to 2^N as sizeof(T) will allow. Just double the - * capacity, and then there might be space for one more element. - */ - newCap = mLength * 2; - if (CapacityHasExcessSpace(newCap)) - newCap += 1; - - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + incr; - - /* Did mLength+incr overflow? Will newCap*sizeof(T) overflow? */ - if (newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::result) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { - convert: - return convertToHeapStorage(newCap); - } - - grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t request) -{ - JS_ASSERT(empty()); - JS_ASSERT(usingInlineStorage()); - if (request == 0) - return true; - T *newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); - if (!newbuf) - return false; - mBegin = newbuf; - mCapacity = request; -#ifdef DEBUG - mReserved = request; -#endif - return true; -} - -template -inline bool -Vector::reserve(size_t request) -{ - REENTRANCY_GUARD_ET_AL; - if (request > mCapacity && !growStorageBy(request - mLength)) - return false; - -#ifdef DEBUG - if (request > mReserved) - mReserved = request; - JS_ASSERT(mLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(incr <= mLength); - Impl::destroy(endNoCheck() - incr, endNoCheck()); - mLength -= incr; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::growByImpl(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - if (incr > mCapacity - mLength && !growStorageBy(incr)) - return false; - - JS_ASSERT(mLength + incr <= mCapacity); - T *newend = endNoCheck() + incr; - if (InitNewElems) - Impl::initialize(endNoCheck(), newend); - mLength += incr; -#ifdef DEBUG - if (mLength > mReserved) - mReserved = mLength; -#endif - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::growBy(size_t incr) -{ - return growByImpl(incr); -} - -template -JS_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t incr) -{ - return growByImpl(incr); -} - -template -STATIC_POSTCONDITION(!return || ubound(this->begin()) >= newLength) -inline bool -Vector::resize(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growBy(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growByUninitialized(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -inline void -Vector::clear() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) - return; - - this->free_(beginNoCheck()); - mBegin = (T *)storage.addr(); - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t needed) const -{ - return mLength + needed <= mCapacity; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(U t) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity && !growStorageBy(1)) - return false; - -#ifdef DEBUG - if (mLength + 1 > mReserved) - mReserved = mLength + 1; -#endif - internalAppend(t); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(U u) -{ - JS_ASSERT(mLength + 1 <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - new(endNoCheck()) T(u); - ++mLength; -} - -template -JS_ALWAYS_INLINE bool -Vector::appendN(const T &t, size_t needed) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppendN(t, needed); - return true; -} - -template -JS_ALWAYS_INLINE void -Vector::internalAppendN(const T &t, size_t needed) -{ - JS_ASSERT(mLength + needed <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), needed, t); - mLength += needed; -} - -template -inline T * -Vector::insert(T *p, const T &val) -{ - JS_ASSERT(begin() <= p && p <= end()); - size_t pos = p - begin(); - JS_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(val)) - return NULL; - } else { - T oldBack = back(); - if (!append(oldBack)) /* Dup the last element. */ - return NULL; - for (size_t i = oldLength; i > pos; --i) - (*this)[i] = (*this)[i - 1]; - (*this)[pos] = val; - } - return begin() + pos; -} - -template -inline void -Vector::erase(T *it) -{ - JS_ASSERT(begin() <= it && it < end()); - while (it + 1 != end()) { - *it = *(it + 1); - ++it; - } - popBack(); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, const U *insEnd) -{ - REENTRANCY_GUARD_ET_AL; - size_t needed = mozilla::PointerRangeSize(insBegin, insEnd); - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppend(insBegin, needed); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(const U *insBegin, size_t insLength) -{ - JS_ASSERT(mLength + insLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); - mLength += insLength; -} - -template -template -inline bool -Vector::append(const Vector &other) -{ - return append(other.begin(), other.end()); -} - -template -template -inline void -Vector::internalAppend(const Vector &other) -{ - internalAppend(other.begin(), other.length()); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, size_t insLength) -{ - return this->append(insBegin, insBegin + insLength); -} - -template -JS_ALWAYS_INLINE void -Vector::popBack() -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -JS_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T * -Vector::extractRawBuffer() -{ - T *ret; - if (usingInlineStorage()) { - ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); - if (!ret) - return NULL; - Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - /* mBegin, mCapacity are unchanged. */ - mLength = 0; - } else { - ret = mBegin; - mBegin = (T *)storage.addr(); - mLength = 0; - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif - } - return ret; -} - -template -inline void -Vector::replaceRawBuffer(T *p, size_t aLength) -{ - REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); - - /* Take in the new buffer. */ - if (aLength <= sInlineCapacity) { - /* - * We convert to inline storage if possible, even though p might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = (T *)storage.addr(); - mLength = aLength; - mCapacity = sInlineCapacity; - Impl::moveConstruct(mBegin, p, p + aLength); - Impl::destroy(p, p + aLength); - this->free_(p); - } else { - mBegin = p; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); -} - -template -inline void -Vector::swap(Vector &other) -{ - // TODO Implement N != 0 - JS_STATIC_ASSERT(N == 0); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && other.usingInlineStorage()) { - other.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !other.usingInlineStorage()) { - mBegin = other.mBegin; - other.mBegin = other.inlineStorage(); - } else if (!usingInlineStorage() && !other.usingInlineStorage()) { - Swap(mBegin, other.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, other.mLength); - Swap(mCapacity, other.mCapacity); -#ifdef DEBUG - Swap(mReserved, other.mReserved); -#endif -} - -} /* namespace js */ - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* jsvector_h_ */ +#endif /* js_Vector_h */ diff --git a/external/spidermonkey/include/android/jsalloc.h b/external/spidermonkey/include/android/jsalloc.h index e7e64fc540..3abc4966d1 100644 --- a/external/spidermonkey/include/android/jsalloc.h +++ b/external/spidermonkey/include/android/jsalloc.h @@ -4,32 +4,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsalloc_h_ -#define jsalloc_h_ +/* JS allocation policies. */ + +#ifndef jsalloc_h +#define jsalloc_h + +#include "mozilla/AllocPolicy.h" #include "js/Utility.h" -#include "jstypes.h" struct JSContext; namespace js { -/* - * Allocation policies. These model the concept: - * - public copy constructor, assignment, destructor - * - void *malloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *calloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *realloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * The *used* bytes of the previous buffer is passed in - * (rather than the old allocation size), in addition to - * the *new* allocation size requested. - * - void free_(void *) - * - reportAllocOverflow() - * Called on overflow before the container returns NULL. - */ +class ContextFriendFields; /* Policy for using system memory functions and doing no error reporting. */ class SystemAllocPolicy @@ -53,7 +41,7 @@ class SystemAllocPolicy */ class TempAllocPolicy { - JSContext *const cx_; + ContextFriendFields *const cx_; /* * Non-inline helper to call JSRuntime::onOutOfMemory with minimal @@ -62,11 +50,8 @@ class TempAllocPolicy JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes); public: - TempAllocPolicy(JSContext *cx) : cx_(cx) {} - - JSContext *context() const { - return cx_; - } + TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :( + TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {} void *malloc_(size_t bytes) { void *p = js_malloc(bytes); @@ -98,4 +83,4 @@ class TempAllocPolicy } /* namespace js */ -#endif /* jsalloc_h_ */ +#endif /* jsalloc_h */ diff --git a/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id index db9dbac6b4..27b6bbed78 100644 --- a/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -0ec74a6f5f2aa9bbaa6a8cbf6e2ae95ec7c4ee43 \ No newline at end of file +e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file diff --git a/external/spidermonkey/include/android/jsclass.h b/external/spidermonkey/include/android/jsclass.h index c9b53c7679..def641715d 100644 --- a/external/spidermonkey/include/android/jsclass.h +++ b/external/spidermonkey/include/android/jsclass.h @@ -4,14 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclass_h__ -#define jsclass_h__ +#ifndef jsclass_h +#define jsclass_h /* * A JSClass acts as a vtable for JS objects that allows JSAPI clients to * control various aspects of the behavior of an object like property lookup. * js::Class is an engine-private extension that allows more control over * object behavior and, e.g., allows custom slow layout. */ + #include "jsapi.h" #include "jsprvtd.h" @@ -21,6 +22,10 @@ class PropertyName; class SpecialId; class PropertyId; +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; + static JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); @@ -195,7 +200,7 @@ typedef void const char *name; \ uint32_t flags; \ \ - /* Mandatory non-null function pointer members. */ \ + /* Mandatory function pointer members. */ \ JSPropertyOp addProperty; \ JSDeletePropertyOp delProperty; \ JSPropertyOp getProperty; \ @@ -203,9 +208,9 @@ typedef void JSEnumerateOp enumerate; \ JSResolveOp resolve; \ JSConvertOp convert; \ - FinalizeOp finalize; \ \ - /* Optionally non-null members start here. */ \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ JSCheckAccessOp checkAccess; \ JSNative call; \ JSHasInstanceOp hasInstance; \ @@ -214,7 +219,7 @@ typedef void /* * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to padd js::Class to match the size of JSClass; + * we have to pad js::Class to match the size of JSClass. */ struct ClassSizeMeasurement { @@ -312,8 +317,9 @@ struct Class return flags & JSCLASS_EMULATES_UNDEFINED; } - /* Defined in jsfuninlines.h */ - inline bool isCallable() const; + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } static size_t offsetOfFlags() { return offsetof(Class, flags); } }; @@ -387,7 +393,7 @@ IsPoisonedSpecialId(js::SpecialId iden) return false; } -template <> struct RootMethods +template <> struct GCMethods { static SpecialId initial() { return SpecialId(); } static ThingRootKind kind() { return THING_ROOT_ID; } @@ -396,4 +402,4 @@ template <> struct RootMethods } /* namespace js */ -#endif /* jsclass_h__ */ +#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/android/jsclist.h b/external/spidermonkey/include/android/jsclist.h index 8782307fa4..23da9b8cd5 100644 --- a/external/spidermonkey/include/android/jsclist.h +++ b/external/spidermonkey/include/android/jsclist.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclist_h___ -#define jsclist_h___ +#ifndef jsclist_h +#define jsclist_h #include "jstypes.h" @@ -104,4 +104,4 @@ typedef struct JSCListStr { #define JS_INIT_STATIC_CLIST(_l) \ {(_l), (_l)} -#endif /* jsclist_h___ */ +#endif /* jsclist_h */ diff --git a/external/spidermonkey/include/android/jscpucfg.h b/external/spidermonkey/include/android/jscpucfg.h index 6bb62b420f..c79bd7ad14 100644 --- a/external/spidermonkey/include/android/jscpucfg.h +++ b/external/spidermonkey/include/android/jscpucfg.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_cpucfg___ -#define js_cpucfg___ +#ifndef jscpucfg_h +#define jscpucfg_h #define JS_HAVE_LONG_LONG @@ -114,4 +114,4 @@ # endif #endif -#endif /* js_cpucfg___ */ +#endif /* jscpucfg_h */ diff --git a/external/spidermonkey/include/android/jsdbgapi.h b/external/spidermonkey/include/android/jsdbgapi.h index 4907d913a0..0ce7101337 100644 --- a/external/spidermonkey/include/android/jsdbgapi.h +++ b/external/spidermonkey/include/android/jsdbgapi.h @@ -4,12 +4,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsdbgapi_h___ -#define jsdbgapi_h___ +#ifndef jsdbgapi_h +#define jsdbgapi_h /* * JS debugger API. */ -#include "jsapi.h" + #include "jsprvtd.h" namespace JS { @@ -111,7 +111,7 @@ JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, JSTrapHandler *handlerp, jsval *closurep); extern JS_PUBLIC_API(void) -JS_ClearScriptTraps(JSContext *cx, JSScript *script); +JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); @@ -224,12 +224,6 @@ JS_GetScriptLineExtent(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(JSVersion) JS_GetScriptVersion(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(bool) -JS_GetScriptUserBit(JSScript *script); - -extern JS_PUBLIC_API(void) -JS_SetScriptUserBit(JSScript *script, bool b); - extern JS_PUBLIC_API(bool) JS_GetScriptIsSelfHosted(JSScript *script); @@ -433,9 +427,6 @@ JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ -extern JS_FRIEND_API(void) -js_RevertVersion(JSContext *cx); - extern JS_PUBLIC_API(const JSDebugHooks *) JS_GetGlobalDebugHooks(JSRuntime *rt); @@ -465,4 +456,4 @@ JS_DumpCompartmentPCCounts(JSContext *cx); extern JS_FRIEND_API(JSBool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h___ */ +#endif /* jsdbgapi_h */ diff --git a/external/spidermonkey/include/android/jsdhash.h b/external/spidermonkey/include/android/jsdhash.h deleted file mode 100644 index 1f7830fd2b..0000000000 --- a/external/spidermonkey/include/android/jsdhash.h +++ /dev/null @@ -1,612 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsdhash_h___ -#define jsdhash_h___ - -/* - * Double hashing, a la Knuth 6. - * - * Try to keep this file in sync with xpcom/glue/pldhash.h. - */ -#include "jstypes.h" -#include "jsutil.h" - -#if defined(__GNUC__) && defined(__i386__) && !defined(XP_OS2) -#define JS_DHASH_FASTCALL __attribute__ ((regparm (3),stdcall)) -#elif defined(XP_WIN) -#define JS_DHASH_FASTCALL __fastcall -#else -#define JS_DHASH_FASTCALL -#endif - -#ifdef DEBUG_XXXbrendan -#define JS_DHASHMETER 1 -#endif - -/* Table size limit, do not equal or exceed (see min&maxAlphaFrac, below). */ -#undef JS_DHASH_SIZE_LIMIT -#define JS_DHASH_SIZE_LIMIT JS_BIT(24) - -/* Minimum table size, or gross entry count (net is at most .75 loaded). */ -#ifndef JS_DHASH_MIN_SIZE -#define JS_DHASH_MIN_SIZE 16 -#elif (JS_DHASH_MIN_SIZE & (JS_DHASH_MIN_SIZE - 1)) != 0 -#error "JS_DHASH_MIN_SIZE must be a power of two!" -#endif - -/* - * Multiplicative hash uses an unsigned 32 bit integer and the golden ratio, - * expressed as a fixed-point 32-bit fraction. - */ -#define JS_DHASH_BITS 32 -#define JS_DHASH_GOLDEN_RATIO 0x9E3779B9U - -/* Primitive and forward-struct typedefs. */ -typedef uint32_t JSDHashNumber; -typedef struct JSDHashEntryHdr JSDHashEntryHdr; -typedef struct JSDHashEntryStub JSDHashEntryStub; -typedef struct JSDHashTable JSDHashTable; -typedef struct JSDHashTableOps JSDHashTableOps; - -/* - * Table entry header structure. - * - * In order to allow in-line allocation of key and value, we do not declare - * either here. Instead, the API uses const void *key as a formal parameter. - * The key need not be stored in the entry; it may be part of the value, but - * need not be stored at all. - * - * Callback types are defined below and grouped into the JSDHashTableOps - * structure, for single static initialization per hash table sub-type. - * - * Each hash table sub-type should nest the JSDHashEntryHdr structure at the - * front of its particular entry type. The keyHash member contains the result - * of multiplying the hash code returned from the hashKey callback (see below) - * by JS_DHASH_GOLDEN_RATIO, then constraining the result to avoid the magic 0 - * and 1 values. The stored keyHash value is table size invariant, and it is - * maintained automatically by JS_DHashTableOperate -- users should never set - * it, and its only uses should be via the entry macros below. - * - * The JS_DHASH_ENTRY_IS_LIVE macro tests whether entry is neither free nor - * removed. An entry may be either busy or free; if busy, it may be live or - * removed. Consumers of this API should not access members of entries that - * are not live. - * - * However, use JS_DHASH_ENTRY_IS_BUSY for faster liveness testing of entries - * returned by JS_DHashTableOperate, as JS_DHashTableOperate never returns a - * non-live, busy (i.e., removed) entry pointer to its caller. See below for - * more details on JS_DHashTableOperate's calling rules. - */ -struct JSDHashEntryHdr { - JSDHashNumber keyHash; /* every entry must begin like this */ -}; - -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_FREE(JSDHashEntryHdr* entry) -{ - return entry->keyHash == 0; -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_BUSY(JSDHashEntryHdr* entry) -{ - return !JS_DHASH_ENTRY_IS_FREE(entry); -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_LIVE(JSDHashEntryHdr* entry) -{ - return entry->keyHash >= 2; -} - -/* - * A JSDHashTable is currently 8 words (without the JS_DHASHMETER overhead) - * on most architectures, and may be allocated on the stack or within another - * structure or class (see below for the Init and Finish functions to use). - * - * To decide whether to use double hashing vs. chaining, we need to develop a - * trade-off relation, as follows: - * - * Let alpha be the load factor, esize the entry size in words, count the - * entry count, and pow2 the power-of-two table size in entries. - * - * (JSDHashTable overhead) > (JSHashTable overhead) - * (unused table entry space) > (malloc and .next overhead per entry) + - * (buckets overhead) - * (1 - alpha) * esize * pow2 > 2 * count + pow2 - * - * Notice that alpha is by definition (count / pow2): - * - * (1 - alpha) * esize * pow2 > 2 * alpha * pow2 + pow2 - * (1 - alpha) * esize > 2 * alpha + 1 - * - * esize > (1 + 2 * alpha) / (1 - alpha) - * - * This assumes both tables must keep keyHash, key, and value for each entry, - * where key and value point to separately allocated strings or structures. - * If key and value can be combined into one pointer, then the trade-off is: - * - * esize > (1 + 3 * alpha) / (1 - alpha) - * - * If the entry value can be a subtype of JSDHashEntryHdr, rather than a type - * that must be allocated separately and referenced by an entry.value pointer - * member, and provided key's allocation can be fused with its entry's, then - * k (the words wasted per entry with chaining) is 4. - * - * To see these curves, feed gnuplot input like so: - * - * gnuplot> f(x,k) = (1 + k * x) / (1 - x) - * gnuplot> plot [0:.75] f(x,2), f(x,3), f(x,4) - * - * For k of 2 and a well-loaded table (alpha > .5), esize must be more than 4 - * words for chaining to be more space-efficient than double hashing. - * - * Solving for alpha helps us decide when to shrink an underloaded table: - * - * esize > (1 + k * alpha) / (1 - alpha) - * esize - alpha * esize > 1 + k * alpha - * esize - 1 > (k + esize) * alpha - * (esize - 1) / (k + esize) > alpha - * - * alpha < (esize - 1) / (esize + k) - * - * Therefore double hashing should keep alpha >= (esize - 1) / (esize + k), - * assuming esize is not too large (in which case, chaining should probably be - * used for any alpha). For esize=2 and k=3, we want alpha >= .2; for esize=3 - * and k=2, we want alpha >= .4. For k=4, esize could be 6, and alpha >= .5 - * would still obtain. See the JS_DHASH_MIN_ALPHA macro further below. - * - * The current implementation uses a configurable lower bound on alpha, which - * defaults to .25, when deciding to shrink the table (while still respecting - * JS_DHASH_MIN_SIZE). - * - * Note a qualitative difference between chaining and double hashing: under - * chaining, entry addresses are stable across table shrinks and grows. With - * double hashing, you can't safely hold an entry pointer and use it after an - * ADD or REMOVE operation, unless you sample table->generation before adding - * or removing, and compare the sample after, dereferencing the entry pointer - * only if table->generation has not changed. - * - * The moral of this story: there is no one-size-fits-all hash table scheme, - * but for small table entry size, and assuming entry address stability is not - * required, double hashing wins. - */ -struct JSDHashTable { - const JSDHashTableOps *ops; /* virtual operations, see below */ - void *data; /* ops- and instance-specific data */ - int16_t hashShift; /* multiplicative hash shift */ - uint8_t maxAlphaFrac; /* 8-bit fixed point max alpha */ - uint8_t minAlphaFrac; /* 8-bit fixed point min alpha */ - uint32_t entrySize; /* number of bytes in an entry */ - uint32_t entryCount; /* number of entries in table */ - uint32_t removedCount; /* removed entry sentinels in table */ - uint32_t generation; /* entry storage generation number */ - char *entryStore; /* entry storage */ -#ifdef JS_DHASHMETER - struct JSDHashStats { - uint32_t searches; /* total number of table searches */ - uint32_t steps; /* hash chain links traversed */ - uint32_t hits; /* searches that found key */ - uint32_t misses; /* searches that didn't find key */ - uint32_t lookups; /* number of JS_DHASH_LOOKUPs */ - uint32_t addMisses; /* adds that miss, and do work */ - uint32_t addOverRemoved; /* adds that recycled a removed entry */ - uint32_t addHits; /* adds that hit an existing entry */ - uint32_t addFailures; /* out-of-memory during add growth */ - uint32_t removeHits; /* removes that hit, and do work */ - uint32_t removeMisses; /* useless removes that miss */ - uint32_t removeFrees; /* removes that freed entry directly */ - uint32_t removeEnums; /* removes done by Enumerate */ - uint32_t grows; /* table expansions */ - uint32_t shrinks; /* table contractions */ - uint32_t compresses; /* table compressions */ - uint32_t enumShrinks; /* contractions after Enumerate */ - } stats; -#endif -}; - -/* - * Size in entries (gross, not net of free and removed sentinels) for table. - * We store hashShift rather than sizeLog2 to optimize the collision-free case - * in SearchTable. - */ -#define JS_DHASH_TABLE_SIZE(table) JS_BIT(JS_DHASH_BITS - (table)->hashShift) - -/* - * Table space at entryStore is allocated and freed using these callbacks. - * The allocator should return null on error only (not if called with nbytes - * equal to 0; but note that jsdhash.c code will never call with 0 nbytes). - */ -typedef void * -(* JSDHashAllocTable)(JSDHashTable *table, uint32_t nbytes); - -typedef void -(* JSDHashFreeTable) (JSDHashTable *table, void *ptr); - -/* - * Compute the hash code for a given key to be looked up, added, or removed - * from table. A hash code may have any JSDHashNumber value. - */ -typedef JSDHashNumber -(* JSDHashHashKey) (JSDHashTable *table, const void *key); - -/* - * Compare the key identifying entry in table with the provided key parameter. - * Return JS_TRUE if keys match, JS_FALSE otherwise. - */ -typedef JSBool -(* JSDHashMatchEntry)(JSDHashTable *table, const JSDHashEntryHdr *entry, - const void *key); - -/* - * Copy the data starting at from to the new entry storage at to. Do not add - * reference counts for any strong references in the entry, however, as this - * is a "move" operation: the old entry storage at from will be freed without - * any reference-decrementing callback shortly. - */ -typedef void -(* JSDHashMoveEntry)(JSDHashTable *table, const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -/* - * Clear the entry and drop any strong references it holds. This callback is - * invoked during a JS_DHASH_REMOVE operation (see below for operation codes), - * but only if the given key is found in the table. - */ -typedef void -(* JSDHashClearEntry)(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Called when a table (whether allocated dynamically by itself, or nested in - * a larger structure, or allocated on the stack) is finished. This callback - * allows table->ops-specific code to finalize table->data. - */ -typedef void -(* JSDHashFinalize) (JSDHashTable *table); - -/* - * Initialize a new entry, apart from keyHash. This function is called when - * JS_DHashTableOperate's JS_DHASH_ADD case finds no existing entry for the - * given key, and must add a new one. At that point, entry->keyHash is not - * set yet, to avoid claiming the last free entry in a severely overloaded - * table. - */ -typedef JSBool -(* JSDHashInitEntry)(JSDHashTable *table, JSDHashEntryHdr *entry, - const void *key); - -/* - * Finally, the "vtable" structure for JSDHashTable. The first eight hooks - * must be provided by implementations; they're called unconditionally by the - * generic jsdhash.c code. Hooks after these may be null. - * - * Summary of allocation-related hook usage with C++ placement new emphasis: - * allocTable Allocate raw bytes with malloc, no ctors run. - * freeTable Free raw bytes with free, no dtors run. - * initEntry Call placement new using default key-based ctor. - * Return JS_TRUE on success, JS_FALSE on error. - * moveEntry Call placement new using copy ctor, run dtor on old - * entry storage. - * clearEntry Run dtor on entry. - * finalize Stub unless table->data was initialized and needs to - * be finalized. - * - * Note the reason why initEntry is optional: the default hooks (stubs) clear - * entry storage: On successful JS_DHashTableOperate(tbl, key, JS_DHASH_ADD), - * the returned entry pointer addresses an entry struct whose keyHash member - * has been set non-zero, but all other entry members are still clear (null). - * JS_DHASH_ADD callers can test such members to see whether the entry was - * newly created by the JS_DHASH_ADD call that just succeeded. If placement - * new or similar initialization is required, define an initEntry hook. Of - * course, the clearEntry hook must zero or null appropriately. - * - * XXX assumes 0 is null for pointer types. - */ -struct JSDHashTableOps { - /* Mandatory hooks. All implementations must provide these. */ - JSDHashAllocTable allocTable; - JSDHashFreeTable freeTable; - JSDHashHashKey hashKey; - JSDHashMatchEntry matchEntry; - JSDHashMoveEntry moveEntry; - JSDHashClearEntry clearEntry; - JSDHashFinalize finalize; - - /* Optional hooks start here. If null, these are not called. */ - JSDHashInitEntry initEntry; -}; - -/* - * Default implementations for the above ops. - */ -extern JS_PUBLIC_API(void *) -JS_DHashAllocTable(JSDHashTable *table, uint32_t nbytes); - -extern JS_PUBLIC_API(void) -JS_DHashFreeTable(JSDHashTable *table, void *ptr); - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashStringKey(JSDHashTable *table, const void *key); - -/* A minimal entry contains a keyHash header and a void key pointer. */ -struct JSDHashEntryStub { - JSDHashEntryHdr hdr; - const void *key; -}; - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashVoidPtrKeyStub(JSDHashTable *table, const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchStringKey(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(void) -JS_DHashMoveEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -extern JS_PUBLIC_API(void) -JS_DHashClearEntryStub(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFreeStringKey(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFinalizeStub(JSDHashTable *table); - -/* - * If you use JSDHashEntryStub or a subclass of it as your entry struct, and - * if your entries move via memcpy and clear via memset(0), you can use these - * stub operations. - */ -extern JS_PUBLIC_API(const JSDHashTableOps *) -JS_DHashGetStubOps(void); - -/* - * Dynamically allocate a new JSDHashTable using malloc, initialize it using - * JS_DHashTableInit, and return its address. Return null on malloc failure. - * Note that the entry storage at table->entryStore will be allocated using - * the ops->allocTable callback. - */ -extern JS_PUBLIC_API(JSDHashTable *) -JS_NewDHashTable(const JSDHashTableOps *ops, void *data, uint32_t entrySize, - uint32_t capacity); - -/* - * Finalize table's data, free its entry storage (via table->ops->freeTable), - * and return the memory starting at table to the malloc heap. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableDestroy(JSDHashTable *table); - -/* - * Initialize table with ops, data, entrySize, and capacity. Capacity is a - * guess for the smallest table size at which the table will usually be less - * than 75% loaded (the table will grow or shrink as needed; capacity serves - * only to avoid inevitable early growth from JS_DHASH_MIN_SIZE). - */ -extern JS_PUBLIC_API(JSBool) -JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data, - uint32_t entrySize, uint32_t capacity); - -/* - * Set maximum and minimum alpha for table. The defaults are 0.75 and .25. - * maxAlpha must be in [0.5, 0.9375] for the default JS_DHASH_MIN_SIZE; or if - * MinSize=JS_DHASH_MIN_SIZE <= 256, in [0.5, (float)(MinSize-1)/MinSize]; or - * else in [0.5, 255.0/256]. minAlpha must be in [0, maxAlpha / 2), so that - * we don't shrink on the very next remove after growing a table upon adding - * an entry that brings entryCount past maxAlpha * tableSize. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableSetAlphaBounds(JSDHashTable *table, - float maxAlpha, - float minAlpha); - -/* - * Call this macro with k, the number of pointer-sized words wasted per entry - * under chaining, to compute the minimum alpha at which double hashing still - * beats chaining. - */ -#define JS_DHASH_MIN_ALPHA(table, k) \ - ((float)((table)->entrySize / sizeof(void *) - 1) \ - / ((table)->entrySize / sizeof(void *) + (k))) - -/* - * Default max/min alpha, and macros to compute the value for the |capacity| - * parameter to JS_NewDHashTable and JS_DHashTableInit, given default or any - * max alpha, such that adding entryCount entries right after initializing the - * table will not require a reallocation (so JS_DHASH_ADD can't fail for those - * JS_DHashTableOperate calls). - * - * NB: JS_DHASH_CAP is a helper macro meant for use only in JS_DHASH_CAPACITY. - * Don't use it directly! - */ -#define JS_DHASH_DEFAULT_MAX_ALPHA 0.75 -#define JS_DHASH_DEFAULT_MIN_ALPHA 0.25 - -#define JS_DHASH_CAP(entryCount, maxAlpha) \ - ((uint32_t)((double)(entryCount) / (maxAlpha))) - -#define JS_DHASH_CAPACITY(entryCount, maxAlpha) \ - (JS_DHASH_CAP(entryCount, maxAlpha) + \ - (((JS_DHASH_CAP(entryCount, maxAlpha) * (uint8_t)(0x100 * (maxAlpha))) \ - >> 8) < (entryCount))) - -#define JS_DHASH_DEFAULT_CAPACITY(entryCount) \ - JS_DHASH_CAPACITY(entryCount, JS_DHASH_DEFAULT_MAX_ALPHA) - -/* - * Finalize table's data, free its entry storage using table->ops->freeTable, - * and leave its members unchanged from their last live values (which leaves - * pointers dangling). If you want to burn cycles clearing table, it's up to - * your code to call memset. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableFinish(JSDHashTable *table); - -/* - * To consolidate keyHash computation and table grow/shrink code, we use a - * single entry point for lookup, add, and remove operations. The operation - * codes are declared here, along with codes returned by JSDHashEnumerator - * functions, which control JS_DHashTableEnumerate's behavior. - */ -typedef enum JSDHashOperator { - JS_DHASH_LOOKUP = 0, /* lookup entry */ - JS_DHASH_ADD = 1, /* add entry */ - JS_DHASH_REMOVE = 2, /* remove entry, or enumerator says remove */ - JS_DHASH_NEXT = 0, /* enumerator says continue */ - JS_DHASH_STOP = 1 /* enumerator says stop */ -} JSDHashOperator; - -/* - * To lookup a key in table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_LOOKUP); - * - * If JS_DHASH_ENTRY_IS_BUSY(entry) is true, key was found and it identifies - * entry. If JS_DHASH_ENTRY_IS_FREE(entry) is true, key was not found. - * - * To add an entry identified by key to table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_ADD); - * - * If entry is null upon return, then either the table is severely overloaded, - * and memory can't be allocated for entry storage via table->ops->allocTable; - * Or if table->ops->initEntry is non-null, the table->ops->initEntry op may - * have returned false. - * - * Otherwise, entry->keyHash has been set so that JS_DHASH_ENTRY_IS_BUSY(entry) - * is true, and it is up to the caller to initialize the key and value parts - * of the entry sub-type, if they have not been set already (i.e. if entry was - * not already in the table, and if the optional initEntry hook was not used). - * - * To remove an entry identified by key from table, call: - * - * (void) JS_DHashTableOperate(table, key, JS_DHASH_REMOVE); - * - * If key's entry is found, it is cleared (via table->ops->clearEntry) and - * the entry is marked so that JS_DHASH_ENTRY_IS_FREE(entry). This operation - * returns null unconditionally; you should ignore its return value. - */ -extern JS_PUBLIC_API(JSDHashEntryHdr *) JS_DHASH_FASTCALL -JS_DHashTableOperate(JSDHashTable *table, const void *key, JSDHashOperator op); - -/* - * Remove an entry already accessed via LOOKUP or ADD. - * - * NB: this is a "raw" or low-level routine, intended to be used only where - * the inefficiency of a full JS_DHashTableOperate (which rehashes in order - * to find the entry given its key) is not tolerable. This function does not - * shrink the table if it is underloaded. It does not update stats #ifdef - * JS_DHASHMETER, either. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableRawRemove(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Enumerate entries in table using etor: - * - * count = JS_DHashTableEnumerate(table, etor, arg); - * - * JS_DHashTableEnumerate calls etor like so: - * - * op = etor(table, entry, number, arg); - * - * where number is a zero-based ordinal assigned to live entries according to - * their order in table->entryStore. - * - * The return value, op, is treated as a set of flags. If op is JS_DHASH_NEXT, - * then continue enumerating. If op contains JS_DHASH_REMOVE, then clear (via - * table->ops->clearEntry) and free entry. Then we check whether op contains - * JS_DHASH_STOP; if so, stop enumerating and return the number of live entries - * that were enumerated so far. Return the total number of live entries when - * enumeration completes normally. - * - * If etor calls JS_DHashTableOperate on table with op != JS_DHASH_LOOKUP, it - * must return JS_DHASH_STOP; otherwise undefined behavior results. - * - * If any enumerator returns JS_DHASH_REMOVE, table->entryStore may be shrunk - * or compressed after enumeration, but before JS_DHashTableEnumerate returns. - * Such an enumerator therefore can't safely set aside entry pointers, but an - * enumerator that never returns JS_DHASH_REMOVE can set pointers to entries - * aside, e.g., to avoid copying live entries into an array of the entry type. - * Copying entry pointers is cheaper, and safe so long as the caller of such a - * "stable" Enumerate doesn't use the set-aside pointers after any call either - * to PL_DHashTableOperate, or to an "unstable" form of Enumerate, which might - * grow or shrink entryStore. - * - * If your enumerator wants to remove certain entries, but set aside pointers - * to other entries that it retains, it can use JS_DHashTableRawRemove on the - * entries to be removed, returning JS_DHASH_NEXT to skip them. Likewise, if - * you want to remove entries, but for some reason you do not want entryStore - * to be shrunk or compressed, you can call JS_DHashTableRawRemove safely on - * the entry being enumerated, rather than returning JS_DHASH_REMOVE. - */ -typedef JSDHashOperator -(* JSDHashEnumerator)(JSDHashTable *table, JSDHashEntryHdr *hdr, uint32_t number, void *arg); - -extern JS_PUBLIC_API(uint32_t) -JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg); - -typedef size_t -(* JSDHashSizeOfEntryExcludingThisFun)(JSDHashEntryHdr *hdr, - JSMallocSizeOfFun mallocSizeOf, - void *arg); - -/** - * Measure the size of the table's entry storage, and if - * |sizeOfEntryExcludingThis| is non-NULL, measure the size of things pointed - * to by entries. Doesn't measure |ops| because it's often shared between - * tables, nor |data| because it's opaque. - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfExcludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -/** - * Like JS_DHashTableSizeOfExcludingThis, but includes sizeof(*this). - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfIncludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -#ifdef DEBUG -/** - * Mark a table as immutable for the remainder of its lifetime. This - * changes the implementation from ASSERTing one set of invariants to - * ASSERTing a different set. - * - * When a table is NOT marked as immutable, the table implementation - * asserts that the table is not mutated from its own callbacks. It - * assumes the caller protects the table from being accessed on multiple - * threads simultaneously. - * - * When the table is marked as immutable, the re-entry assertions will - * no longer trigger erroneously due to multi-threaded access. Instead, - * mutations will cause assertions. - */ -extern JS_PUBLIC_API(void) -JS_DHashMarkTableImmutable(JSDHashTable *table); -#endif - -#ifdef JS_DHASHMETER -#include - -extern JS_PUBLIC_API(void) -JS_DHashTableDumpMeter(JSDHashTable *table, JSDHashEnumerator dump, FILE *fp); -#endif - -#endif /* jsdhash_h___ */ diff --git a/external/spidermonkey/include/android/jsfriendapi.h b/external/spidermonkey/include/android/jsfriendapi.h index 848049ffe3..a1c3024fed 100644 --- a/external/spidermonkey/include/android/jsfriendapi.h +++ b/external/spidermonkey/include/android/jsfriendapi.h @@ -4,15 +4,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsfriendapi_h___ -#define jsfriendapi_h___ +#ifndef jsfriendapi_h +#define jsfriendapi_h -#include "mozilla/GuardObjects.h" +#include "mozilla/MemoryReporting.h" #include "jsclass.h" -#include "jscpucfg.h" -#include "jspubtd.h" #include "jsprvtd.h" +#include "jspubtd.h" + +#include "js/CallArgs.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -29,6 +30,11 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +namespace JS { +template +class Heap; +} /* namespace JS */ + extern JS_FRIEND_API(void) JS_SetGrayGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data); @@ -48,7 +54,7 @@ extern JS_FRIEND_API(JSObject *) JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JSHandleObject obj); +JS_ObjectCountDynamicSlots(JS::HandleObject obj); extern JS_FRIEND_API(size_t) JS_SetProtoCalled(JSContext *cx); @@ -118,14 +124,27 @@ extern JS_FRIEND_API(JSObject *) JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) -JS_BasicObjectToString(JSContext *cx, JSHandleObject obj); +JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp); +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, + JS::MutableHandleValue vp); JS_FRIEND_API(void) js_ReportOverRecursed(JSContext *maybecx); +JS_FRIEND_API(bool) +js_ObjectClassIs(JSContext *cx, JS::HandleObject obj, js::ESClassValue classValue); + +JS_FRIEND_API(const char *) +js_ObjectClassName(JSContext *cx, JS::HandleObject obj); + +JS_FRIEND_API(bool) +js_AddObjectRoot(JSRuntime *rt, JSObject **objp); + +JS_FRIEND_API(void) +js_RemoveObjectRoot(JSRuntime *rt, JSObject **objp); + #ifdef DEBUG /* @@ -157,7 +176,7 @@ extern JS_FRIEND_API(JSBool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); extern JS_FRIEND_API(JSBool) -JS_EnumerateState(JSContext *cx, JSHandleObject obj, JSIterateOp enum_op, +JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, js::MutableHandleValue statep, js::MutableHandleId idp); struct JSFunctionSpecWithHelp { @@ -177,25 +196,24 @@ struct JSFunctionSpecWithHelp { extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JSScript *script, jschar **src, uint32_t *length); +typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, + jschar **src, uint32_t *length); extern JS_FRIEND_API(void) JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); namespace js { -extern mozilla::ThreadLocal TlsPerThreadData; - inline JSRuntime * GetRuntime(const JSContext *cx) { - return ContextFriendFields::get(cx)->runtime; + return ContextFriendFields::get(cx)->runtime_; } inline JSCompartment * GetContextCompartment(const JSContext *cx) { - return ContextFriendFields::get(cx)->compartment; + return ContextFriendFields::get(cx)->compartment_; } inline JS::Zone * @@ -217,19 +235,6 @@ typedef bool extern JS_FRIEND_API(void) DumpHeapComplete(JSRuntime *rt, FILE *fp); -class JS_FRIEND_API(AutoSwitchCompartment) { - private: - JSContext *cx; - JSCompartment *oldCompartment; - public: - AutoSwitchCompartment(JSContext *cx, JSCompartment *newCompartment - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - AutoSwitchCompartment(JSContext *cx, JSHandleObject target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoSwitchCompartment(); - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - #ifdef OLD_GETTER_SETTER_METHODS JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); @@ -254,6 +259,15 @@ IsAtomsCompartment(JSCompartment *comp); extern JS_FRIEND_API(bool) ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +/* + * Returns whether we're in a non-strict property set (in that we're in a + * non-strict script and the bytecode we're on is a property set). The return + * value does NOT indicate any sort of exception was thrown: it's just a + * boolean. + */ +extern JS_FRIEND_API(bool) +IsInNonStrictPropertySet(JSContext *cx); + struct WeakMapTracer; /* @@ -301,7 +315,7 @@ IterateGrayObjects(JS::Zone *zone, GCThingCallback cellCallback, void *data); #ifdef JS_HAS_CTYPES extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(JSMallocSizeOfFun mallocSizeOf, JSObject *obj); +SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject *obj); #endif extern JS_FRIEND_API(JSCompartment *) @@ -321,8 +335,9 @@ struct TypeObject { }; struct BaseShape { - js::Class *clasp; - JSObject *parent; + js::Class *clasp; + JSObject *parent; + JSObject *_1; JSCompartment *compartment; }; @@ -365,19 +380,22 @@ struct Function { }; struct Atom { - size_t _; + static const size_t LENGTH_SHIFT = 4; + size_t lengthAndFlags; const jschar *chars; }; } /* namespace shadow */ -extern JS_FRIEND_DATA(js::Class) CallClass; -extern JS_FRIEND_DATA(js::Class) DeclEnvClass; -extern JS_FRIEND_DATA(js::Class) FunctionClass; -extern JS_FRIEND_DATA(js::Class) FunctionProxyClass; -extern JS_FRIEND_DATA(js::Class) OuterWindowProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectClass; +// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use +// them in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; + +// This is equal to |&JSObject::class_|. Use it in places where you don't want +// to #include jsobj.h. +extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; inline js::Class * GetObjectClass(JSObject *obj) @@ -401,9 +419,15 @@ IsOuterObject(JSObject *obj) { return !!GetObjectClass(obj)->ext.innerObject; } +JS_FRIEND_API(bool) +IsFunctionObject(JSObject *obj); + JS_FRIEND_API(bool) IsScopeObject(JSObject *obj); +JS_FRIEND_API(bool) +IsCallObject(JSObject *obj); + inline JSObject * GetObjectParent(JSObject *obj) { @@ -423,6 +447,13 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +// For legacy consumers only. This whole concept is going away soon. +JS_FRIEND_API(JSObject *) +DefaultObjectForContextOrNull(JSContext *cx); + +JS_FRIEND_API(void) +SetDefaultObjectForContext(JSContext *cx, JSObject *obj); + JS_FRIEND_API(void) NotifyAnimationActivity(JSObject *obj); @@ -469,11 +500,11 @@ inline bool GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) { js::Class *clasp = GetObjectClass(obj); - if (clasp == &js::ObjectProxyClass || - clasp == &js::OuterWindowProxyClass || - clasp == &js::FunctionProxyClass) + if (clasp == js::ObjectProxyClassPtr || + clasp == js::OuterWindowProxyClassPtr || + clasp == js::FunctionProxyClassPtr) { - return JS_GetPrototype(cx, obj, proto.address()); + return JS_GetPrototype(cx, obj, proto); } proto.set(reinterpret_cast(obj.get())->type->proto); @@ -535,6 +566,13 @@ GetAtomChars(JSAtom *atom) return reinterpret_cast(atom)->chars; } +inline size_t +GetAtomLength(JSAtom *atom) +{ + using shadow::Atom; + return reinterpret_cast(atom)->lengthAndFlags >> Atom::LENGTH_SHIFT; +} + inline JSLinearString * AtomToLinearString(JSAtom *atom) { @@ -589,6 +627,12 @@ GetNativeStackLimit(const JSRuntime *rt) return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; } +inline uintptr_t +GetNativeStackLimit(JSContext *cx) +{ + return GetNativeStackLimit(GetRuntime(cx)); +} + /* * These macros report a stack overflow and run |onerror| if we are close to * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a little @@ -598,18 +642,15 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), &stackDummy_)) { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), &stackDummy_)) { \ js_ReportOverRecursed(cx); \ onerror; \ } \ JS_END_MACRO -#define JS_CHECK_RECURSION_WITH_EXTRA_DONT_REPORT(cx, extra, onerror) \ +#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ JS_BEGIN_MACRO \ - uint8_t stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ - &stackDummy_ - (extra))) \ - { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ onerror; \ } \ JS_END_MACRO @@ -617,7 +658,7 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ + if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(cx), \ &stackDummy_, \ 1024 * sizeof(size_t))) \ { \ @@ -754,13 +795,13 @@ extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JSFlatString *desc); +(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); extern JS_FRIEND_API(AnalysisPurgeCallback) SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); typedef JSBool -(* DOMInstanceClassMatchesProto)(JSHandleObject protoObject, uint32_t protoID, +(* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { DOMInstanceClassMatchesProto instanceClassMatchesProto; @@ -851,10 +892,10 @@ NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& targetFilter, NukeReferencesToWindow nukeReferencesToWindow); -/* Specify information about ListBase proxies in the DOM, for use by ICs. */ +/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ /* - * The ListBaseShadowsCheck function will be called to check if the property for + * The DOMProxyShadowsCheck function will be called to check if the property for * id should be gotten from the prototype, or if there is an own property that * shadows it. * If DoesntShadow is returned then the slot at listBaseExpandoSlot should @@ -873,25 +914,31 @@ struct ExpandoAndGeneration { generation(0) {} - Value expando; + void Unlink() + { + ++generation; + expando.setUndefined(); + } + + JS::Heap expando; uint32_t generation; }; -typedef enum ListBaseShadowsResult { +typedef enum DOMProxyShadowsResult { ShadowCheckFailed, Shadows, DoesntShadow, DoesntShadowUnique -} ListBaseShadowsResult; -typedef ListBaseShadowsResult -(* ListBaseShadowsCheck)(JSContext* cx, JSHandleObject object, JSHandleId id); +} DOMProxyShadowsResult; +typedef DOMProxyShadowsResult +(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetListBaseInformation(void *listBaseHandlerFamily, uint32_t listBaseExpandoSlot, - ListBaseShadowsCheck listBaseShadowsCheck); +SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, + DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetListBaseHandlerFamily(); -uint32_t GetListBaseExpandoSlot(); -ListBaseShadowsCheck GetListBaseShadowsCheck(); +void *GetDOMProxyHandlerFamily(); +uint32_t GetDOMProxyExpandoSlot(); +DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); } /* namespace js */ @@ -960,6 +1007,137 @@ enum ViewType { }; } /* namespace ArrayBufferView */ + +/* + * A helper for building up an ArrayBuffer object's data + * before creating the ArrayBuffer itself. Will do doubling + * based reallocation, up to an optional maximum growth given. + * + * When all the data has been appended, call getArrayBuffer, + * passing in the JSContext* for which the ArrayBuffer object + * is to be created. This also implicitly resets the builder, + * or it can be reset explicitly at any point by calling reset(). + */ +class ArrayBufferBuilder +{ + void *rawcontents_; + uint8_t *dataptr_; + uint32_t capacity_; + uint32_t length_; + public: + ArrayBufferBuilder() + : rawcontents_(NULL), + dataptr_(NULL), + capacity_(0), + length_(0) + { + } + + ~ArrayBufferBuilder() { + reset(); + } + + void reset() { + if (rawcontents_) + JS_free(NULL, rawcontents_); + rawcontents_ = dataptr_ = NULL; + capacity_ = length_ = 0; + } + + // will truncate if newcap is < length() + bool setCapacity(uint32_t newcap) { + if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) + return false; + + capacity_ = newcap; + if (length_ > newcap) + length_ = newcap; + + return true; + } + + // Append datalen bytes from data to the current buffer. If we + // need to grow the buffer, grow by doubling the size up to a + // maximum of maxgrowth (if given). If datalen is greater than + // what the new capacity would end up as, then grow by datalen. + // + // The data parameter must not overlap with anything beyond the + // builder's current valid contents [0..length) + bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { + if (length_ + datalen > capacity_) { + uint32_t newcap; + // double while under maxgrowth or if not specified + if (!maxgrowth || capacity_ < maxgrowth) + newcap = capacity_ * 2; + else + newcap = capacity_ + maxgrowth; + + // but make sure there's always enough to satisfy our request + if (newcap < length_ + datalen) + newcap = length_ + datalen; + + // did we overflow? + if (newcap < capacity_) + return false; + + if (!setCapacity(newcap)) + return false; + } + + // assert that the region isn't overlapping so we can memcpy; + JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); + + memcpy(dataptr_ + length_, newdata, datalen); + length_ += datalen; + + return true; + } + + uint8_t *data() { + return dataptr_; + } + + uint32_t length() { + return length_; + } + + uint32_t capacity() { + return capacity_; + } + + JSObject* getArrayBuffer(JSContext *cx) { + // we need to check for length_ == 0, because nothing may have been + // added + if (capacity_ > length_ || length_ == 0) { + if (!setCapacity(length_)) + return NULL; + } + + JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); + if (!obj) + return NULL; + + rawcontents_ = dataptr_ = NULL; + length_ = capacity_ = 0; + + return obj; + } + +protected: + + static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, + const uint8_t *start2, uint32_t length2) + { + const uint8_t *end1 = start1 + length1; + const uint8_t *end2 = start2 + length2; + + const uint8_t *max_start = start1 > start2 ? start1 : start2; + const uint8_t *min_end = end1 < end2 ? end1 : end2; + + return max_start < min_end; + } +}; + } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1296,26 +1474,116 @@ JS_GetDataViewByteLength(JSObject *obj); JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitGetterOp. + */ +class JSJitGetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitGetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args.rval()) + {} + + explicit JSJitGetterCallArgs(JS::Rooted* rooted) + : JS::MutableHandleValue(rooted) + {} + + JS::MutableHandleValue rval() { + return *this; + } +}; + +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitSetterOp. + */ +class JSJitSetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitSetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args[0]) + {} + + JS::MutableHandleValue operator[](unsigned i) { + MOZ_ASSERT(i == 0); + return *this; + } + + unsigned length() const { return 1; } + + // Add get() or maybe hasDefined() as needed +}; + +struct JSJitMethodCallArgsTraits; + +/* + * A class, expected to be passed by reference, which represents the CallArgs + * for a JSJitMethodOp. + */ +class JSJitMethodCallArgs : protected JS::detail::CallArgsBase +{ + private: + typedef JS::detail::CallArgsBase Base; + friend struct JSJitMethodCallArgsTraits; + + public: + explicit JSJitMethodCallArgs(const JS::CallArgs& args) { + argv_ = args.array(); + argc_ = args.length(); + } + + JS::MutableHandleValue rval() const { + return Base::rval(); + } + + unsigned length() const { return Base::length(); } + + JS::MutableHandleValue operator[](unsigned i) const { + return Base::operator[](i); + } + + bool hasDefined(unsigned i) const { + return Base::hasDefined(i); + } + + // Add get() as needed +}; + +struct JSJitMethodCallArgsTraits +{ + static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); + static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); +}; + /* * This struct contains metadata passed from the DOM to the JS Engine for JIT * optimizations on DOM property accessors. Eventually, this should be made * available to general JSAPI users, but we are not currently ready to do so. */ typedef bool -(* JSJitPropertyOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, JS::Value *vp); +(* JSJitGetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitGetterCallArgs args); typedef bool -(* JSJitMethodOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, unsigned argc, JS::Value *vp); +(* JSJitSetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitSetterCallArgs args); +typedef bool +(* JSJitMethodOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, const JSJitMethodCallArgs& args); struct JSJitInfo { enum OpType { Getter, Setter, - Method + Method, + OpType_None }; - JSJitPropertyOp op; + union { + JSJitGetterOp getter; + JSJitSetterOp setter; + JSJitMethodOp method; + }; uint32_t protoID; uint32_t depth; OpType type; @@ -1325,12 +1593,18 @@ struct JSJitInfo { keep returning the same value for the given "this" object" */ JSValueType returnType; /* The return type tag. Might be JSVAL_TYPE_UNKNOWN */ + + /* An alternative native that's safe to call in parallel mode. */ + JSParallelNative parallelNative; }; +#define JS_JITINFO_NATIVE_PARALLEL(op) \ + {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) { - JS_ASSERT(js::GetObjectClass(&v.toObject()) == &js::FunctionClass); + JS_ASSERT(js::GetObjectClass(&v.toObject()) == js::FunctionClassPtr); return reinterpret_cast(&v.toObject())->jitinfo; } @@ -1482,9 +1756,46 @@ assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id); inline void assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id) {}; #endif +typedef bool +(* ObjectMetadataCallback)(JSContext *cx, JSObject **pmetadata); + +/* + * Specify a callback to invoke when creating each JS object in the current + * compartment, which may return a metadata object to associate with the + * object. Objects with different metadata have different shape hierarchies, + * so for efficiency, objects should generally try to share metadata objects. + */ +JS_FRIEND_API(void) +SetObjectMetadataCallback(JSContext *cx, ObjectMetadataCallback callback); + +/* Manipulate the metadata associated with an object. */ + +JS_FRIEND_API(bool) +SetObjectMetadata(JSContext *cx, JS::HandleObject obj, JS::HandleObject metadata); + +JS_FRIEND_API(JSObject *) +GetObjectMetadata(JSObject *obj); + /* ES5 8.12.8. */ extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); + +/* + * Helper function. To approximate a call to the [[DefineOwnProperty]] internal + * method described in ES5, first call this, then call JS_DefinePropertyById. + * + * JS_DefinePropertyById by itself does not enforce the invariants on + * non-configurable properties when obj->isNative(). This function performs the + * relevant checks (specified in ES5 8.12.9 [[DefineOwnProperty]] steps 1-11), + * but only if obj is native. + * + * The reason for the messiness here is that ES5 uses [[DefineOwnProperty]] as + * a sort of extension point, but there is no hook in js::Class, + * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. + */ +extern JS_FRIEND_API(bool) +CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, + PropertyOp getter, StrictPropertyOp setter, unsigned attrs); } /* namespace js */ @@ -1495,4 +1806,26 @@ js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, extern JS_FRIEND_API(JSBool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); -#endif /* jsfriendapi_h___ */ +#ifdef JSGC_GENERATIONAL +extern JS_FRIEND_API(void) +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data); + +extern JS_FRIEND_API(void) +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data); +#else +inline void +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data) {} + +inline void +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data) {} +#endif /* JSGC_GENERATIONAL */ + +#endif /* jsfriendapi_h */ diff --git a/external/spidermonkey/include/android/jslock.h b/external/spidermonkey/include/android/jslock.h index b4a28a9fa9..522034ad68 100644 --- a/external/spidermonkey/include/android/jslock.h +++ b/external/spidermonkey/include/android/jslock.h @@ -4,18 +4,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jslock_h__ -#define jslock_h__ - -#include "jsapi.h" +#ifndef jslock_h +#define jslock_h #ifdef JS_THREADSAFE +# include "jsapi.h" # include "pratom.h" -# include "prlock.h" # include "prcvar.h" -# include "prthread.h" # include "prinit.h" +# include "prlock.h" +# include "prthread.h" # define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) # define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) @@ -40,4 +39,4 @@ typedef struct PRLock PRLock; #endif /* JS_THREADSAFE */ -#endif /* jslock_h___ */ +#endif /* jslock_h */ diff --git a/external/spidermonkey/include/android/json.h b/external/spidermonkey/include/android/json.h deleted file mode 100644 index 7fa2c117c8..0000000000 --- a/external/spidermonkey/include/android/json.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef json_h___ -#define json_h___ - -#include "jsprvtd.h" -#include "jspubtd.h" -#include "jsapi.h" - -#include "js/Vector.h" - -#define JSON_MAX_DEPTH 2048 -#define JSON_PARSER_BUFSIZE 1024 - -extern JSObject * -js_InitJSONClass(JSContext *cx, js::HandleObject obj); - -extern JSBool -js_Stringify(JSContext *cx, js::MutableHandleValue vp, - JSObject *replacer, js::Value space, - js::StringBuffer &sb); - -// Avoid build errors on certain platforms that define these names as constants -#undef STRICT -#undef LEGACY - -/* - * The type of JSON decoding to perform. Strict decoding is to-the-spec; - * legacy decoding accepts a few non-JSON syntaxes historically accepted by the - * implementation. (Full description of these deviations is deliberately - * omitted.) New users should use strict decoding rather than legacy decoding, - * as legacy decoding might be removed at a future time. - */ -enum DecodingMode { STRICT, LEGACY }; - -namespace js { - -extern JS_FRIEND_API(JSBool) -ParseJSONWithReviver(JSContext *cx, JS::StableCharPtr chars, size_t length, HandleValue filter, - MutableHandleValue vp, DecodingMode decodingMode = STRICT); - -} /* namespace js */ - -#endif /* json_h___ */ diff --git a/external/spidermonkey/include/android/jsperf.h b/external/spidermonkey/include/android/jsperf.h index a0287b4a57..468ce8609c 100644 --- a/external/spidermonkey/include/android/jsperf.h +++ b/external/spidermonkey/include/android/jsperf.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsperf_h___ -#define jsperf_h___ +#ifndef perf_jsperf_h +#define perf_jsperf_h #include "jsapi.h" @@ -127,4 +127,4 @@ extern JS_FRIEND_API(PerfMeasurement*) } // namespace JS -#endif // jsperf_h___ +#endif /* perf_jsperf_h */ diff --git a/external/spidermonkey/include/android/jsprf.h b/external/spidermonkey/include/android/jsprf.h index c0891f0e9e..ce159d8115 100644 --- a/external/spidermonkey/include/android/jsprf.h +++ b/external/spidermonkey/include/android/jsprf.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprf_h___ -#define jsprf_h___ +#ifndef jsprf_h +#define jsprf_h /* ** API for PR printf like routines. Supports the following formats @@ -24,9 +24,11 @@ ** %f - float ** %g - float */ -#include "jstypes.h" -#include + #include +#include + +#include "jstypes.h" /* ** sprintf into a fixed size buffer. Guarantees that a NUL is at the end @@ -75,4 +77,4 @@ extern JS_PUBLIC_API(char*) JS_vsmprintf(const char *fmt, va_list ap); extern JS_PUBLIC_API(char*) JS_vsprintf_append(char *last, const char *fmt, va_list ap); extern JS_PUBLIC_API(uint32_t) JS_vsxprintf(JSStuffFunc f, void *arg, const char *fmt, va_list ap); -#endif /* jsprf_h___ */ +#endif /* jsprf_h */ diff --git a/external/spidermonkey/include/android/jsprototypes.h b/external/spidermonkey/include/android/jsprototypes.h index 007d25d720..f9bacac409 100644 --- a/external/spidermonkey/include/android/jsprototypes.h +++ b/external/spidermonkey/include/android/jsprototypes.h @@ -6,8 +6,8 @@ /* A higher-order macro for enumerating all JSProtoKey values. */ -#ifndef jsprototypes_h___ -#define jsprototypes_h___ +#ifndef jsprototypes_h +#define jsprototypes_h #include "jsversion.h" @@ -56,5 +56,20 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ + macro(Type, 38, js_InitBinaryDataClasses) \ + macro(Data, 39, js_InitBinaryDataClasses) \ + macro(uint8, 40, js_InitBinaryDataClasses) \ + macro(uint16, 41, js_InitBinaryDataClasses) \ + macro(uint32, 42, js_InitBinaryDataClasses) \ + macro(uint64, 43, js_InitBinaryDataClasses) \ + macro(int8, 44, js_InitBinaryDataClasses) \ + macro(int16, 45, js_InitBinaryDataClasses) \ + macro(int32, 46, js_InitBinaryDataClasses) \ + macro(int64, 47, js_InitBinaryDataClasses) \ + macro(float32, 48, js_InitBinaryDataClasses) \ + macro(float64, 49, js_InitBinaryDataClasses) \ + macro(ArrayType, 50, js_InitBinaryDataClasses) \ + macro(StructType, 51, js_InitBinaryDataClasses) \ + macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ -#endif /* jsprototypes_h___ */ +#endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/android/jsproxy.h b/external/spidermonkey/include/android/jsproxy.h index 399490eddc..56868a05c3 100644 --- a/external/spidermonkey/include/android/jsproxy.h +++ b/external/spidermonkey/include/android/jsproxy.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsproxy_h___ -#define jsproxy_h___ +#ifndef jsproxy_h +#define jsproxy_h #include "jsapi.h" #include "jsfriendapi.h" @@ -129,7 +129,7 @@ class JS_FRIEND_API(BaseProxyHandler) MutableHandleValue vp); /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) = 0; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) = 0; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -190,7 +190,7 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -242,7 +242,7 @@ class Proxy static bool iterate(JSContext *cx, HandleObject proxy, unsigned flags, MutableHandleValue vp); /* Spidermonkey extensions. */ - static bool isExtensible(JSObject *proxy); + static bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible); static bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -259,12 +259,17 @@ class Proxy inline bool IsObjectProxyClass(const Class *clasp) { - return clasp == &js::ObjectProxyClass || clasp == &js::OuterWindowProxyClass; + return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; } inline bool IsFunctionProxyClass(const Class *clasp) { - return clasp == &js::FunctionProxyClass; + return clasp == js::FunctionProxyClassPtr; +} + +inline bool IsProxyClass(const Class *clasp) +{ + return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); } inline bool IsObjectProxy(JSObject *obj) @@ -279,36 +284,33 @@ inline bool IsFunctionProxy(JSObject *obj) inline bool IsProxy(JSObject *obj) { - Class *clasp = GetObjectClass(obj); - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); + return IsProxyClass(GetObjectClass(obj)); } -/* Shared between object and function proxies. */ /* - * NOTE: JSSLOT_PROXY_PRIVATE is 0, because that way slot 0 is usable by API + * These are part of the API. + * + * NOTE: PROXY_PRIVATE_SLOT is 0 because that way slot 0 is usable by API * clients for both proxy and non-proxy objects. So an API client that only * needs to store one slot's worth of data doesn't need to branch on what sort * of object it has. */ -const uint32_t JSSLOT_PROXY_PRIVATE = 0; -const uint32_t JSSLOT_PROXY_HANDLER = 1; -const uint32_t JSSLOT_PROXY_EXTRA = 2; -/* Function proxies only. */ -const uint32_t JSSLOT_PROXY_CALL = 4; -const uint32_t JSSLOT_PROXY_CONSTRUCT = 5; +const uint32_t PROXY_PRIVATE_SLOT = 0; +const uint32_t PROXY_HANDLER_SLOT = 1; +const uint32_t PROXY_EXTRA_SLOT = 2; inline BaseProxyHandler * GetProxyHandler(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return (BaseProxyHandler *) GetReservedSlot(obj, JSSLOT_PROXY_HANDLER).toPrivate(); + return (BaseProxyHandler *) GetReservedSlot(obj, PROXY_HANDLER_SLOT).toPrivate(); } inline const Value & GetProxyPrivate(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_PRIVATE); + return GetReservedSlot(obj, PROXY_PRIVATE_SLOT); } inline JSObject * @@ -322,14 +324,14 @@ inline const Value & GetProxyExtra(JSObject *obj, size_t n) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n); + return GetReservedSlot(obj, PROXY_EXTRA_SLOT + n); } inline void SetProxyHandler(JSObject *obj, BaseProxyHandler *handler) { JS_ASSERT(IsProxy(obj)); - SetReservedSlot(obj, JSSLOT_PROXY_HANDLER, PrivateValue(handler)); + SetReservedSlot(obj, PROXY_HANDLER_SLOT, PrivateValue(handler)); } inline void @@ -337,7 +339,7 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) { JS_ASSERT(IsProxy(obj)); JS_ASSERT(n <= 1); - SetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n, extra); + SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } enum ProxyCallable { @@ -346,7 +348,7 @@ enum ProxyCallable { }; JS_FRIEND_API(JSObject *) -NewProxyObject(JSContext *cx, BaseProxyHandler *handler, const Value &priv, +NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); JSObject * @@ -426,6 +428,6 @@ class JS_FRIEND_API(AutoWaivePolicy) { } /* namespace js */ extern JS_FRIEND_API(JSObject *) -js_InitProxyClass(JSContext *cx, JSHandleObject obj); +js_InitProxyClass(JSContext *cx, JS::HandleObject obj); -#endif +#endif /* jsproxy_h */ diff --git a/external/spidermonkey/include/android/jsprvtd.h b/external/spidermonkey/include/android/jsprvtd.h index 4db5ed8c36..1fbc086a7c 100644 --- a/external/spidermonkey/include/android/jsprvtd.h +++ b/external/spidermonkey/include/android/jsprvtd.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprvtd_h___ -#define jsprvtd_h___ +#ifndef jsprvtd_h +#define jsprvtd_h /* * JS private typename definitions. * @@ -56,13 +56,7 @@ typedef struct JSStackHeader JSStackHeader; typedef struct JSSubString JSSubString; typedef struct JSSpecializedNative JSSpecializedNative; -/* - * Template declarations. - * - * jsprvtd.h can be included in both C and C++ translation units. For C++, it - * may possibly be wrapped in an extern "C" block which does not agree with - * templates. - */ +/* String typedefs. */ class JSDependentString; class JSExtensibleString; class JSExternalString; @@ -76,6 +70,7 @@ namespace js { struct ArgumentsData; struct Class; +class AutoNameVector; class RegExpGuard; class RegExpObject; class RegExpObjectBuilder; @@ -83,6 +78,7 @@ class RegExpShared; class RegExpStatics; class MatchPairs; class PropertyName; +class LazyScript; enum RegExpFlag { @@ -95,19 +91,14 @@ enum RegExpFlag AllFlags = 0x0f }; -class ExecuteArgsGuard; -class InvokeFrameGuard; -class InvokeArgsGuard; class StringBuffer; class FrameRegs; class StackFrame; -class StackSegment; -class StackSpace; -class ContextStack; class ScriptFrameIter; class Proxy; +class JS_FRIEND_API(AutoEnterPolicy); class JS_FRIEND_API(BaseProxyHandler); class JS_FRIEND_API(Wrapper); class JS_FRIEND_API(CrossCompartmentWrapper); @@ -140,24 +131,29 @@ class WatchpointMap; typedef JSObject Env; typedef JSNative Native; +typedef JSParallelNative ParallelNative; +typedef JSThreadSafeNative ThreadSafeNative; typedef JSPropertyOp PropertyOp; typedef JSStrictPropertyOp StrictPropertyOp; typedef JSPropertyDescriptor PropertyDescriptor; +struct SourceCompressionToken; + namespace frontend { struct BytecodeEmitter; struct Definition; +class FullParseHandler; class FunctionBox; class ObjectBox; struct Token; struct TokenPos; class TokenStream; class ParseMapPool; -struct ParseNode; +class ParseNode; template -struct Parser; +class Parser; } /* namespace frontend */ @@ -284,18 +280,18 @@ typedef void * if an error or exception was thrown on cx. */ typedef JSObject * -(* JSObjectOp)(JSContext *cx, JSHandleObject obj); +(* JSObjectOp)(JSContext *cx, JS::Handle obj); /* Signature for class initialization ops. */ typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JSHandleObject obj); +(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); /* * Hook that creates an iterator object for a given object. Returns the * iterator object or null if an error or exception was thrown on cx. */ typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JSHandleObject obj, JSBool keysonly); +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); -#endif /* jsprvtd_h___ */ +#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/android/jspubtd.h b/external/spidermonkey/include/android/jspubtd.h index 6b7e63e6ba..96f5dd8297 100644 --- a/external/spidermonkey/include/android/jspubtd.h +++ b/external/spidermonkey/include/android/jspubtd.h @@ -4,16 +4,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jspubtd_h___ -#define jspubtd_h___ +#ifndef jspubtd_h +#define jspubtd_h /* * JS public API typedefs. */ +#include "mozilla/PodOperations.h" + #include "jsprototypes.h" #include "jstypes.h" +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) +# define JSGC_TRACK_EXACT_ROOTS +#endif + namespace JS { /* @@ -25,6 +31,8 @@ class Value; template class Rooted; +class JS_PUBLIC_API(AutoGCRooter); + struct Zone; } /* namespace JS */ @@ -44,10 +52,8 @@ struct Zone; * oblivious to the change. This feature can be explicitly disabled in debug * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. */ - // Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES - +#define JS_NO_JSVAL_JSID_STRUCT_TYPES # if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) # define JS_USE_JSID_STRUCT_TYPES # endif @@ -154,9 +160,10 @@ typedef enum { JSTRACE_SCRIPT, /* - * Trace kinds internal to the engine. The embedding can only them if it - * implements JSTraceCallback. + * Trace kinds internal to the engine. The embedding can only see them if + * it implements JSTraceCallback. */ + JSTRACE_LAZY_SCRIPT, JSTRACE_IONCODE, JSTRACE_SHAPE, JSTRACE_BASE_SHAPE, @@ -229,6 +236,18 @@ struct Runtime namespace js { +/* + * Parallel operations in general can have one of three states. They may + * succeed, fail, or "bail", where bail indicates that the code encountered an + * unexpected condition and should be re-run sequentially. Different + * subcategories of the "bail" state are encoded as variants of TP_RETRY_*. + */ +enum ParallelResult { TP_SUCCESS, TP_RETRY_SEQUENTIALLY, TP_RETRY_AFTER_GC, TP_FATAL }; + +struct ThreadSafeContext; +struct ForkJoinSlice; +class ExclusiveContext; + class Allocator; class SkipRoot; @@ -273,18 +292,28 @@ template <> struct RootKind : SpecificRootKind struct RootKind : SpecificRootKind {}; template <> struct RootKind : SpecificRootKind {}; -struct ContextFriendFields { - JSRuntime *const runtime; +struct ContextFriendFields +{ + protected: + JSRuntime *const runtime_; /* The current compartment. */ - JSCompartment *compartment; + JSCompartment *compartment_; /* The current zone. */ JS::Zone *zone_; + public: explicit ContextFriendFields(JSRuntime *rt) - : runtime(rt), compartment(NULL), zone_(NULL) - { } + : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + { +#ifdef JSGC_TRACK_EXACT_ROOTS + mozilla::PodArrayZero(thingGCRooters); +#endif +#if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) + skipGCRooters = NULL; +#endif + } static const ContextFriendFields *get(const JSContext *cx) { return reinterpret_cast(cx); @@ -294,7 +323,7 @@ struct ContextFriendFields { return reinterpret_cast(cx); } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -313,6 +342,13 @@ struct ContextFriendFields { */ SkipRoot *skipGCRooters; #endif + + /* Stack of thread-stack-allocated GC roots. */ + JS::AutoGCRooter *autoGCRooters; + + friend JSRuntime *GetRuntime(const JSContext *cx); + friend JSCompartment *GetContextCompartment(const JSContext *cx); + friend JS::Zone *GetContextZone(const JSContext *cx); }; class PerThreadData; @@ -338,7 +374,7 @@ struct PerThreadDataFriendFields PerThreadDataFriendFields(); -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -384,4 +420,4 @@ struct PerThreadDataFriendFields } /* namespace js */ -#endif /* jspubtd_h___ */ +#endif /* jspubtd_h */ diff --git a/external/spidermonkey/include/android/jstypes.h b/external/spidermonkey/include/android/jstypes.h index e4c02f8d8d..17f67f70e1 100644 --- a/external/spidermonkey/include/android/jstypes.h +++ b/external/spidermonkey/include/android/jstypes.h @@ -18,8 +18,8 @@ ** for all C files. **/ -#ifndef jstypes_h___ -#define jstypes_h___ +#ifndef jstypes_h +#define jstypes_h #include "mozilla/Attributes.h" #include "mozilla/Util.h" @@ -279,4 +279,4 @@ typedef int JSBool; # define JS_EXTENSION_(s) s #endif -#endif /* jstypes_h___ */ +#endif /* jstypes_h */ diff --git a/external/spidermonkey/include/android/jsutil.h b/external/spidermonkey/include/android/jsutil.h index 49e1641c61..4020822be1 100644 --- a/external/spidermonkey/include/android/jsutil.h +++ b/external/spidermonkey/include/android/jsutil.h @@ -8,19 +8,19 @@ * PR assertion checker. */ -#ifndef jsutil_h___ -#define jsutil_h___ +#ifndef jsutil_h +#define jsutil_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/GuardObjects.h" -#include "js/Utility.h" - #ifdef USE_ZLIB -#include "zlib.h" +#include #endif +#include "js/Utility.h" + /* Forward declarations. */ struct JSContext; @@ -204,15 +204,6 @@ UnsignedPtrDiff(const void *bigger, const void *smaller) return size_t(bigger) - size_t(smaller); } -/* - * Ordinarily, a function taking a JSContext* 'cx' parameter reports errors on - * the context. In some cases, functions optionally report and indicate this by - * taking a nullable 'maybecx' parameter. In some cases, though, a function - * always needs a 'cx', but optionally reports. This option is presented by the - * MaybeReportError. - */ -enum MaybeReportError { REPORT_ERROR = true, DONT_REPORT_ERROR = false }; - /*****************************************************************************/ /* A bit array is an array of bits represented by an array of words (size_t). */ @@ -391,4 +382,4 @@ typedef size_t jsbitmap; JS_END_MACRO #endif -#endif /* jsutil_h___ */ +#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/android/jsversion.h b/external/spidermonkey/include/android/jsversion.h index f3169fb5d1..1780616a32 100644 --- a/external/spidermonkey/include/android/jsversion.h +++ b/external/spidermonkey/include/android/jsversion.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsversion_h___ -#define jsversion_h___ +#ifndef jsversion_h +#define jsversion_h /* * Deprecated JS_VERSION handler. @@ -61,7 +61,7 @@ # define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else # define NEW_OBJECT_REPRESENTATION_ONLY() \ - MOZ_NOT_REACHED("don't call this! to be used in the new object representation") + MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif -#endif /* jsversion_h___ */ +#endif /* jsversion_h */ diff --git a/external/spidermonkey/include/android/jswrapper.h b/external/spidermonkey/include/android/jswrapper.h index d0c0fc625c..f78df7db60 100644 --- a/external/spidermonkey/include/android/jswrapper.h +++ b/external/spidermonkey/include/android/jswrapper.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jswrapper_h___ -#define jswrapper_h___ +#ifndef jswrapper_h +#define jswrapper_h #include "mozilla/Attributes.h" @@ -66,8 +66,6 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler static Wrapper singleton; static Wrapper singletonWithPrototype; - - static void *getWrapperFamily(); }; /* Base class for all cross compartment wrapper handlers. */ @@ -105,7 +103,7 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -139,7 +137,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base public: SecurityWrapper(unsigned flags); - virtual bool isExtensible(JSObject *wrapper) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool enter(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool *bp) MOZ_OVERRIDE; @@ -185,7 +183,7 @@ class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler virtual bool enumerate(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -297,4 +295,4 @@ struct JS_FRIEND_API(AutoMaybeTouchDeadZones) } /* namespace js */ -#endif +#endif /* jswrapper_h */ diff --git a/external/spidermonkey/include/android/mozilla/AllocPolicy.h b/external/spidermonkey/include/android/mozilla/AllocPolicy.h new file mode 100644 index 0000000000..20087e93bb --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/AllocPolicy.h @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * An allocation policy concept, usable for structures and algorithms to + * control how memory is allocated and how failures are handled. + */ + +#ifndef mozilla_AllocPolicy_h +#define mozilla_AllocPolicy_h + +#include +#include + +namespace mozilla { + +/* + * Allocation policies are used to implement the standard allocation behaviors + * in a customizable way. Additionally, custom behaviors may be added to these + * behaviors, such as additionally reporting an error through an out-of-band + * mechanism when OOM occurs. The concept modeled here is as follows: + * + * - public copy constructor, assignment, destructor + * - void* malloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* calloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* realloc_(void*, size_t, size_t) + * Responsible for OOM reporting when null is returned. The *used* bytes + * of the previous buffer is passed in (rather than the old allocation + * size), in addition to the *new* allocation size requested. + * - void free_(void*) + * - void reportAllocOverflow() const + * Called on allocation overflow (that is, an allocation implicitly tried + * to allocate more than the available memory space -- think allocating an + * array of large-size objects, where N * size overflows) before null is + * returned. + * + * mfbt provides (and typically uses by default) only MallocAllocPolicy, which + * does nothing more than delegate to the malloc/alloc/free functions. + */ + +/* + * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no + * extra behaviors. + */ +class MallocAllocPolicy +{ + public: + void* malloc_(size_t bytes) { return malloc(bytes); } + void* calloc_(size_t bytes) { return calloc(bytes, 1); } + void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } + void free_(void* p) { free(p); } + void reportAllocOverflow() const {} +}; + + +} // namespace mozilla + +#endif /* mozilla_AllocPolicy_h */ diff --git a/external/spidermonkey/include/android/mozilla/Array.h b/external/spidermonkey/include/android/mozilla/Array.h new file mode 100644 index 0000000000..5af9aaa133 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Array.h @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A compile-time constant-length array with bounds-checking assertions. */ + +#ifndef mozilla_Array_h +#define mozilla_Array_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" + +#include + +namespace mozilla { + +template +class Array +{ + T arr[Length]; + + public: + T& operator[](size_t i) { + MOZ_ASSERT(i < Length); + return arr[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(i < Length); + return arr[i]; + } +}; + +template +class Array +{ + public: + T& operator[](size_t i) { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } + + const T& operator[](size_t i) const { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Array_h */ diff --git a/external/spidermonkey/include/android/mozilla/Assertions.h b/external/spidermonkey/include/android/mozilla/Assertions.h index 5ead7f493e..00b7037802 100644 --- a/external/spidermonkey/include/android/mozilla/Assertions.h +++ b/external/spidermonkey/include/android/mozilla/Assertions.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of runtime and static assertion macros for C and C++. */ -#ifndef mozilla_Assertions_h_ -#define mozilla_Assertions_h_ +#ifndef mozilla_Assertions_h +#define mozilla_Assertions_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" @@ -39,44 +40,24 @@ #endif /* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This - * can be useful when you make certain assumptions about what must hold for + * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. + * In C++11, static_assert is provided by the compiler to the same effect. + * This can be useful when you make certain assumptions about what must hold for * optimal, or even correct, behavior. For example, you might assert that the * size of a struct is a multiple of the target architecture's word size: * * struct S { ... }; + * // C * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, * "S should be a multiple of word size for efficiency"); + * // C++11 + * static_assert(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); * * This macro can be used in any location where both an extern declaration and a * typedef could be used. - * - * Be aware of the gcc 4.2 concerns noted further down when writing patches that - * use this macro, particularly if a patch only bounces on OS X. */ -#ifdef __cplusplus -# if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__HP_aCC) -# if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# endif -#endif -#ifndef MOZ_STATIC_ASSERT +#ifndef __cplusplus /* * Some of the definitions below create an otherwise-unused typedef. This * triggers compiler warnings with some versions of gcc, so mark the typedefs @@ -124,78 +105,23 @@ # define MOZ_STATIC_ASSERT(cond, reason) \ extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE # endif -#endif #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) +#else +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) +#endif #ifdef __cplusplus extern "C" { #endif -/* - * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible - * way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. We use TerminateProcess - * with the exit code aborting would generate because we don't want to invoke - * atexit handlers, destructors, library unload handlers, and so on when our - * process might be in a compromised state. We don't use abort() because - * it'd cause Windows to annoyingly pop up the process error dialog multiple - * times. See bug 345118 and bug 426163. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - TerminateProcess(GetCurrentProcess(), 3); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - ::abort(); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - abort(); \ - } while (0) -# endif -#endif - /* * Prints |s| as an assertion failure (using file and ln as the location of the * assertion) to the standard debug-output channel. * - * Usually you should use MOZ_ASSERT instead of this method. This method is - * primarily for internal use in this header, and only secondarily for use in - * implementing release-build assertions. + * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This + * method is primarily for internal use in this header, and only secondarily + * for use in implementing release-build assertions. */ static MOZ_ALWAYS_INLINE void MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) @@ -209,6 +135,112 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif } +static MOZ_ALWAYS_INLINE void +MOZ_ReportCrash(const char* s, const char* file, int ln) +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", + "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); +#else + fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); + fflush(stderr); +#endif +} + +/** + * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should + * call MOZ_CRASH instead. + */ +#if defined(_MSC_VER) + /* + * On MSVC use the __debugbreak compiler intrinsic, which produces an inline + * (not nested in a system function) breakpoint. This distinctively invokes + * Breakpad without requiring system library symbols on all stack-processing + * machines, as a nested breakpoint would require. + * + * We use TerminateProcess with the exit code aborting would generate + * because we don't want to invoke atexit handlers, destructors, library + * unload handlers, and so on when our process might be in a compromised + * state. + * + * We don't use abort() because it'd cause Windows to annoyingly pop up the + * process error dialog multiple times. See bug 345118 and bug 426163. + * + * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the + * compiler doesn't hassle us to provide a return statement after a + * MOZ_REALLY_CRASH() call. + * + * (Technically these are Windows requirements, not MSVC requirements. But + * practically you need MSVC for debugging, and we only ship builds created + * by MSVC, so doing it this way reduces complexity.) + */ + +__declspec(noreturn) __inline void MOZ_NoReturn() {} + +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + ::TerminateProcess(::GetCurrentProcess(), 3); \ + ::MOZ_NoReturn(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + TerminateProcess(GetCurrentProcess(), 3); \ + MOZ_NoReturn(); \ + } while (0) +# endif +#else +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + ::abort(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + abort(); \ + } while (0) +# endif +#endif + +/* + * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a + * Breakpad-compatible way, in both debug and release builds. + * + * MOZ_CRASH is a good solution for "handling" failure cases when you're + * unwilling or unable to handle them more cleanly -- for OOM, for likely memory + * corruption, and so on. It's also a good solution if you need safe behavior + * in release builds as well as debug builds. But if the failure is one that + * should be debugged and fixed, MOZ_ASSERT is generally preferable. + * + * The optional explanation-string, if provided, must be a string literal + * explaining why we're crashing. This argument is intended for use with + * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's + * obvious why we're crashing. + * + * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an + * explanation-string, we print the string to stderr. Otherwise, we don't + * print anything; this is because we want MOZ_CRASH to be 100% safe in release + * builds, and it's hard to print to stderr safely when memory might have been + * corrupted. + */ +#ifndef DEBUG +# define MOZ_CRASH(...) MOZ_REALLY_CRASH() +#else +# define MOZ_CRASH(...) \ + do { \ + MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } while(0) +#endif + #ifdef __cplusplus } /* extern "C" */ #endif @@ -251,7 +283,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* Now the two-argument form. */ @@ -259,7 +291,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* And now, helper macrology up the wazoo. */ @@ -310,14 +342,14 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif /* - * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is + * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is * undefined behavior for execution to reach this point. No guarantees are made * about what will happen if this is reached at runtime. Most code should - * probably use the higher level MOZ_NOT_REACHED, which uses this when + * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when * appropriate. */ #if defined(__clang__) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() #elif defined(__GNUC__) /* * __builtin_unreachable() was implemented in gcc 4.5. If we don't have @@ -325,49 +357,71 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) * in C++ in case there's another abort() visible in local scope. */ # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() # else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif # endif #elif defined(_MSC_VER) -# define MOZ_NOT_REACHED_MARKER() __assume(0) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) #else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif #endif /* - * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached - * during execution: simply reaching that point in execution is a bug. It takes - * as an argument an error message indicating the reason why that point should - * not have been reachable. + * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that + * the macro call cannot be reached during execution. This lets the compiler + * generate better-optimized code under some circumstances, at the expense of + * the program's behavior being undefined if control reaches the + * MOZ_ASSUME_UNREACHABLE. * - * // ...in a language parser... - * void handle(BooleanLiteralNode node) + * In Gecko, you probably should not use this macro outside of performance- or + * size-critical code, because it's unsafe. If you don't care about code size + * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. + * + * SpiderMonkey is a different beast, and there it's acceptable to use + * MOZ_ASSUME_UNREACHABLE more widely. + * + * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a + * value following a MOZ_ASSUME_UNREACHABLE call. + * + * Example usage: + * + * enum ValueType { + * VALUE_STRING, + * VALUE_INT, + * VALUE_FLOAT + * }; + * + * int ptrToInt(ValueType type, void* value) { * { - * if (node.isTrue()) - * handleTrueLiteral(); - * else if (node.isFalse()) - * handleFalseLiteral(); - * else - * MOZ_NOT_REACHED("boolean literal that's not true or false?"); + * // We know for sure that type is either INT or FLOAT, and we want this + * // code to run as quickly as possible. + * switch (type) { + * case VALUE_INT: + * return *(int*) value; + * case VALUE_FLOAT: + * return (int) *(float*) value; + * default: + * MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT"); + * } * } */ #if defined(DEBUG) -# define MOZ_NOT_REACHED(reason) \ +# define MOZ_ASSUME_UNREACHABLE(...) \ do { \ - MOZ_ASSERT(false, reason); \ - MOZ_NOT_REACHED_MARKER(); \ + MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \ + MOZ_ASSUME_UNREACHABLE_MARKER(); \ } while (0) #else -# define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER() +# define MOZ_ASSUME_UNREACHABLE(reason) MOZ_ASSUME_UNREACHABLE_MARKER() #endif /* @@ -384,4 +438,4 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) # define MOZ_ALWAYS_FALSE(expr) ((void)(expr)) #endif -#endif /* mozilla_Assertions_h_ */ +#endif /* mozilla_Assertions_h */ diff --git a/external/spidermonkey/include/android/mozilla/Atomics.h b/external/spidermonkey/include/android/mozilla/Atomics.h new file mode 100644 index 0000000000..f876683c3e --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Atomics.h @@ -0,0 +1,1014 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Implements (almost always) lock-free atomic operations. The operations here + * are a subset of that which can be found in C++11's header, with a + * different API to enforce consistent memory ordering constraints. + * + * Anyone caught using |volatile| for inter-thread memory safety needs to be + * sent a copy of this header and the C++11 standard. + */ + +#ifndef mozilla_Atomics_h +#define mozilla_Atomics_h + +#include "mozilla/Assertions.h" +#include "mozilla/TypeTraits.h" + +#include + +/* + * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK + * does not have . So be sure to check for support + * along with C++0x support. + */ +#if defined(__clang__) + /* + * clang doesn't like libstdc++'s version of before GCC 4.7, + * due to the loose typing of the __sync_* family of functions done by + * GCC. We do not have a particularly good way to detect this sort of + * case at this point, so just assume that if we're on a Linux system, + * we can't use the system's . + * + * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + */ +# if !defined(__linux__) && !defined(__OpenBSD__) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ + __has_include() +# define MOZ_HAVE_CXX11_ATOMICS +# endif +/* + * Android uses a different C++ standard library that does not provide + * support for . + * + * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include + * inline definitions for the functions declared therein. This oversight + * leads to linking errors when using atomic enums. We therefore require + * GCC 4.7 or higher. + */ +#elif defined(__GNUC__) && !defined(__ANDROID__) +# include "mozilla/Compiler.h" +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ + MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# define MOZ_HAVE_CXX11_ATOMICS +# endif +#elif defined(_MSC_VER) && _MSC_VER >= 1700 +# define MOZ_HAVE_CXX11_ATOMICS +#endif + +namespace mozilla { + +/** + * An enum of memory ordering possibilities for atomics. + * + * Memory ordering is the observable state of distinct values in memory. + * (It's a separate concept from atomicity, which concerns whether an + * operation can ever be observed in an intermediate state. Don't + * conflate the two!) Given a sequence of operations in source code on + * memory, it is *not* always the case that, at all times and on all + * cores, those operations will appear to have occurred in that exact + * sequence. First, the compiler might reorder that sequence, if it + * thinks another ordering will be more efficient. Second, the CPU may + * not expose so consistent a view of memory. CPUs will often perform + * their own instruction reordering, above and beyond that performed by + * the compiler. And each core has its own memory caches, and accesses + * (reads and writes both) to "memory" may only resolve to out-of-date + * cache entries -- not to the "most recently" performed operation in + * some global sense. Any access to a value that may be used by + * multiple threads, potentially across multiple cores, must therefore + * have a memory ordering imposed on it, for all code on all + * threads/cores to have a sufficiently coherent worldview. + * + * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and + * http://en.cppreference.com/w/cpp/atomic/memory_order go into more + * detail on all this, including examples of how each mode works. + * + * Note that for simplicity and practicality, not all of the modes in + * C++11 are supported. The missing C++11 modes are either subsumed by + * the modes we provide below, or not relevant for the CPUs we support + * in Gecko. These three modes are confusing enough as it is! + */ +enum MemoryOrdering { + /* + * Relaxed ordering is the simplest memory ordering: none at all. + * When the result of a write is observed, nothing may be inferred + * about other memory. Writes ostensibly performed "before" on the + * writing thread may not yet be visible. Writes performed "after" on + * the writing thread may already be visible, if the compiler or CPU + * reordered them. (The latter can happen if reads and/or writes get + * held up in per-processor caches.) Relaxed ordering means + * operations can always use cached values (as long as the actual + * updates to atomic values actually occur, correctly, eventually), so + * it's usually the fastest sort of atomic access. For this reason, + * *it's also the most dangerous kind of access*. + * + * Relaxed ordering is good for things like process-wide statistics + * counters that don't need to be consistent with anything else, so + * long as updates themselves are atomic. (And so long as any + * observations of that value can tolerate being out-of-date -- if you + * need some sort of up-to-date value, you need some sort of other + * synchronizing operation.) It's *not* good for locks, mutexes, + * reference counts, etc. that mediate access to other memory, or must + * be observably consistent with other memory. + * + * x86 architectures don't take advantage of the optimization + * opportunities that relaxed ordering permits. Thus it's possible + * that using relaxed ordering will "work" on x86 but fail elsewhere + * (ARM, say, which *does* implement non-sequentially-consistent + * relaxed ordering semantics). Be extra-careful using relaxed + * ordering if you can't easily test non-x86 architectures! + */ + Relaxed, + /* + * When an atomic value is updated with ReleaseAcquire ordering, and + * that new value is observed with ReleaseAcquire ordering, prior + * writes (atomic or not) are also observable. What ReleaseAcquire + * *doesn't* give you is any observable ordering guarantees for + * ReleaseAcquire-ordered operations on different objects. For + * example, if there are two cores that each perform ReleaseAcquire + * operations on separate objects, each core may or may not observe + * the operations made by the other core. The only way the cores can + * be synchronized with ReleaseAcquire is if they both + * ReleaseAcquire-access the same object. This implies that you can't + * necessarily describe some global total ordering of ReleaseAcquire + * operations. + * + * ReleaseAcquire ordering is good for (as the name implies) atomic + * operations on values controlling ownership of things: reference + * counts, mutexes, and the like. However, if you are thinking about + * using these to implement your own locks or mutexes, you should take + * a good, hard look at actual lock or mutex primitives first. + */ + ReleaseAcquire, + /* + * When an atomic value is updated with SequentiallyConsistent + * ordering, all writes observable when the update is observed, just + * as with ReleaseAcquire ordering. But, furthermore, a global total + * ordering of SequentiallyConsistent operations *can* be described. + * For example, if two cores perform SequentiallyConsistent operations + * on separate objects, one core will observably perform its update + * (and all previous operations will have completed), then the other + * core will observably perform its update (and all previous + * operations will have completed). (Although those previous + * operations aren't themselves ordered -- they could be intermixed, + * or ordered if they occur on atomic values with ordering + * requirements.) SequentiallyConsistent is the *simplest and safest* + * ordering of atomic operations -- it's always as if one operation + * happens, then another, then another, in some order -- and every + * core observes updates to happen in that single order. Because it + * has the most synchronization requirements, operations ordered this + * way also tend to be slowest. + * + * SequentiallyConsistent ordering can be desirable when multiple + * threads observe objects, and they all have to agree on the + * observable order of changes to them. People expect + * SequentiallyConsistent ordering, even if they shouldn't, when + * writing code, atomic or otherwise. SequentiallyConsistent is also + * the ordering of choice when designing lockless data structures. If + * you don't know what order to use, use this one. + */ + SequentiallyConsistent, +}; + +} // namespace mozilla + +// Build up the underlying intrinsics. +#ifdef MOZ_HAVE_CXX11_ATOMICS + +# include + +namespace mozilla { +namespace detail { + +/* + * We provide CompareExchangeFailureOrder to work around a bug in some + * versions of GCC's header. See bug 898491. + */ +template struct AtomicOrderConstraints; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; + static const std::memory_order LoadOrder = std::memory_order_relaxed; + static const std::memory_order StoreOrder = std::memory_order_relaxed; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_relaxed; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; + static const std::memory_order LoadOrder = std::memory_order_acquire; + static const std::memory_order StoreOrder = std::memory_order_release; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_acquire; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; + static const std::memory_order LoadOrder = std::memory_order_seq_cst; + static const std::memory_order StoreOrder = std::memory_order_seq_cst; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_seq_cst; +}; + +template +struct IntrinsicBase +{ + typedef std::atomic ValueType; + typedef AtomicOrderConstraints OrderedOp; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T load(const typename Base::ValueType& ptr) { + return ptr.load(Base::OrderedOp::LoadOrder); + } + static void store(typename Base::ValueType& ptr, T val) { + ptr.store(val, Base::OrderedOp::StoreOrder); + } + static T exchange(typename Base::ValueType& ptr, T val) { + return ptr.exchange(val, Base::OrderedOp::AtomicRMWOrder); + } + static bool compareExchange(typename Base::ValueType& ptr, T oldVal, T newVal) { + return ptr.compare_exchange_strong(oldVal, newVal, + Base::OrderedOp::AtomicRMWOrder, + Base::OrderedOp::CompareExchangeFailureOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T add(typename Base::ValueType& ptr, T val) { + return ptr.fetch_add(val, Base::OrderedOp::AtomicRMWOrder); + } + static T sub(typename Base::ValueType& ptr, T val) { + return ptr.fetch_sub(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T* add(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_add(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + static T* sub(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_sub(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + private: + /* + * GCC 4.6's header has a bug where adding X to an + * atomic is not the same as adding X to a T*. Hence the need + * for this function to provide the correct addend. + */ + static ptrdiff_t fixupAddend(ptrdiff_t val) { +#if defined(__clang__) || defined(_MSC_VER) + return val; +#elif defined(__GNUC__) && MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) && \ + !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) + return val * sizeof(T); +#else + return val; +#endif + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + typedef IntrinsicBase Base; + static T inc(typename Base::ValueType& ptr) { + return IntrinsicAddSub::add(ptr, 1); + } + static T dec(typename Base::ValueType& ptr) { + return IntrinsicAddSub::sub(ptr, 1); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + typedef IntrinsicBase Base; + static T or_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_or(val, Base::OrderedOp::AtomicRMWOrder); + } + static T xor_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_xor(val, Base::OrderedOp::AtomicRMWOrder); + } + static T and_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_and(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct AtomicIntrinsics + : public IntrinsicMemoryOps, public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(__GNUC__) + +namespace mozilla { +namespace detail { + +/* + * The __sync_* family of intrinsics is documented here: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html + * + * While these intrinsics are deprecated in favor of the newer __atomic_* + * family of intrincs: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html + * + * any GCC version that supports the __atomic_* intrinsics will also support + * the header and so will be handled above. We provide a version of + * atomics using the __sync_* intrinsics to support older versions of GCC. + * + * All __sync_* intrinsics that we use below act as full memory barriers, for + * both compiler and hardware reordering, except for __sync_lock_test_and_set, + * which is a only an acquire barrier. When we call __sync_lock_test_and_set, + * we add a barrier above it as appropriate. + */ + +template struct Barrier; + +/* + * Some processors (in particular, x86) don't require quite so many calls to + * __sync_sychronize as our specializations of Barrier produce. If + * performance turns out to be an issue, defining these specializations + * on a per-processor basis would be a good first tuning step. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() { __sync_synchronize(); } + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() { __sync_synchronize(); } +}; + +template +struct IntrinsicMemoryOps +{ + static T load(const T& ptr) { + Barrier::beforeLoad(); + T val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(T& ptr, T val) { + Barrier::beforeStore(); + ptr = val; + Barrier::afterStore(); + } + static T exchange(T& ptr, T val) { + // __sync_lock_test_and_set is only an acquire barrier; loads and stores + // can't be moved up from after to before it, but they can be moved down + // from before to after it. We may want a stricter ordering, so we need + // an explicit barrier. + + Barrier::beforeStore(); + return __sync_lock_test_and_set(&ptr, val); + } + static bool compareExchange(T& ptr, T oldVal, T newVal) { + return __sync_bool_compare_and_swap(&ptr, oldVal, newVal); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T ValueType; + static T add(T& ptr, T val) { + return __sync_fetch_and_add(&ptr, val); + } + static T sub(T& ptr, T val) { + return __sync_fetch_and_sub(&ptr, val); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T* ValueType; + /* + * The reinterpret_casts are needed so that + * __sync_fetch_and_{add,sub} will properly type-check. + * + * Also, these functions do not provide standard semantics for + * pointer types, so we need to adjust the addend. + */ + static ValueType add(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_add(&ptr, amount); + } + static ValueType sub(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_sub(&ptr, amount); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static T inc(T& ptr) { return IntrinsicAddSub::add(ptr, 1); } + static T dec(T& ptr) { return IntrinsicAddSub::sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static T or_(T& ptr, T val) { + return __sync_fetch_and_or(&ptr, val); + } + static T xor_(T& ptr, T val) { + return __sync_fetch_and_xor(&ptr, val); + } + static T and_(T& ptr, T val) { + return __sync_fetch_and_and(&ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(_MSC_VER) + +/* + * Windows comes with a full complement of atomic operations. + * Unfortunately, most of those aren't available for Windows XP (even if + * the compiler supports intrinsics for them), which is the oldest + * version of Windows we support. Therefore, we only provide operations + * on 32-bit datatypes for 32-bit Windows versions; for 64-bit Windows + * versions, we support 64-bit datatypes as well. + * + * To avoid namespace pollution issues, we declare whatever functions we + * need ourselves. + */ + +extern "C" { +long __cdecl _InterlockedExchangeAdd(long volatile* dst, long value); +long __cdecl _InterlockedOr(long volatile* dst, long value); +long __cdecl _InterlockedXor(long volatile* dst, long value); +long __cdecl _InterlockedAnd(long volatile* dst, long value); +long __cdecl _InterlockedExchange(long volatile *dst, long value); +long __cdecl _InterlockedCompareExchange(long volatile *dst, long newVal, long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd) +# pragma intrinsic(_InterlockedOr) +# pragma intrinsic(_InterlockedXor) +# pragma intrinsic(_InterlockedAnd) +# pragma intrinsic(_InterlockedExchange) +# pragma intrinsic(_InterlockedCompareExchange) + +namespace mozilla { +namespace detail { + +# if !defined(_M_IX86) && !defined(_M_X64) + /* + * The implementations below are optimized for x86ish systems. You + * will have to modify them if you are porting to Windows on a + * different architecture. + */ +# error "Unknown CPU type" +# endif + +/* + * The PrimitiveIntrinsics template should define |Type|, the datatype of size + * DataSize upon which we operate, and the following eight functions. + * + * static Type add(Type* ptr, Type val); + * static Type sub(Type* ptr, Type val); + * static Type or_(Type* ptr, Type val); + * static Type xor_(Type* ptr, Type val); + * static Type and_(Type* ptr, Type val); + * + * These functions perform the obvious operation on the value contained in + * |*ptr| combined with |val| and return the value previously stored in + * |*ptr|. + * + * static void store(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and must provide a full + * memory fence after the store to prevent compiler and hardware instruction + * reordering. It should also act as a compiler barrier to prevent reads and + * writes from moving to after the store. + * + * static Type exchange(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and returns the previous + * contents of *ptr; + * + * static bool compareExchange(Type* ptr, Type oldVal, Type newVal); + * + * This function atomically performs the following operation: + * + * if (*ptr == oldVal) { + * *ptr = newVal; + * return true; + * } else { + * return false; + * } + * + */ +template struct PrimitiveIntrinsics; + +template<> +struct PrimitiveIntrinsics<4> +{ + typedef long Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * _InterlockedExchangeSubtract isn't available before Windows 7, + * and we must support Windows XP. + */ + return _InterlockedExchangeAdd(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange(ptr, newVal, oldVal) == oldVal; + } +}; + +# if defined(_M_X64) + +extern "C" { +long long __cdecl _InterlockedExchangeAdd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedOr64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedXor64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedAnd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedExchange64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedCompareExchange64(long long volatile* dst, + long long newVal, + long long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd64) +# pragma intrinsic(_InterlockedOr64) +# pragma intrinsic(_InterlockedXor64) +# pragma intrinsic(_InterlockedAnd64) +# pragma intrinsic(_InterlockedExchange64) +# pragma intrinsic(_InterlockedCompareExchange64) + +template <> +struct PrimitiveIntrinsics<8> +{ + typedef __int64 Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd64(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * There is no _InterlockedExchangeSubtract64. + */ + return _InterlockedExchangeAdd64(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr64(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor64(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd64(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange64(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange64(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange64(ptr, newVal, oldVal) == oldVal; + } +}; + +# endif + +extern "C" { void _ReadWriteBarrier(); } + +# pragma intrinsic(_ReadWriteBarrier) + +template struct Barrier; + +/* + * We do not provide an afterStore method in Barrier, as Relaxed and + * ReleaseAcquire orderings do not require one, and the required barrier + * for SequentiallyConsistent is handled by PrimitiveIntrinsics. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template<> +struct Barrier +{ + static void beforeLoad() { _ReadWriteBarrier(); } + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T val) { return static_cast(val); } + static T fromPrimType(PrimType val) { return static_cast(val); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T* val) { return reinterpret_cast(val); } + static T* fromPrimType(PrimType val) { return reinterpret_cast(val); } +}; + +template +struct IntrinsicBase +{ + typedef T ValueType; + typedef PrimitiveIntrinsics Primitives; + typedef typename Primitives::Type PrimType; + static_assert(sizeof(PrimType) == sizeof(T), + "Selection of PrimitiveIntrinsics was wrong"); + typedef CastHelper Cast; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + static ValueType load(const ValueType& ptr) { + Barrier::beforeLoad(); + ValueType val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(ValueType& ptr, ValueType val) { + // For SequentiallyConsistent, Primitives::store() will generate the + // proper memory fence. Everything else just needs a barrier before + // the store. + if (Order == SequentiallyConsistent) { + Primitives::store(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + } else { + Barrier::beforeStore(); + ptr = val; + } + } + static ValueType exchange(ValueType& ptr, ValueType val) { + PrimType oldval = + Primitives::exchange(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + return Cast::fromPrimType(oldval); + } + static bool compareExchange(ValueType& ptr, ValueType oldVal, ValueType newVal) { + return Primitives::compareExchange(reinterpret_cast(&ptr), + Cast::toPrimType(oldVal), + Cast::toPrimType(newVal)); + } +}; + +template +struct IntrinsicApplyHelper : public IntrinsicBase +{ + typedef PrimType (*BinaryOp)(PrimType*, PrimType); + typedef PrimType (*UnaryOp)(PrimType*); + + static ValueType applyBinaryFunction(BinaryOp op, ValueType& ptr, + ValueType val) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + PrimType primTypeVal = Cast::toPrimType(val); + return Cast::fromPrimType(op(primTypePtr, primTypeVal)); + } + + static ValueType applyUnaryFunction(UnaryOp op, ValueType& ptr) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + return Cast::fromPrimType(op(primTypePtr)); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::add, ptr, val); + } + static ValueType sub(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::sub, ptr, val); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::add, ptr, + (ValueType)(amount * sizeof(ValueType))); + } + static ValueType sub(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::sub, ptr, + (ValueType)(amount * sizeof(ValueType))); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static ValueType inc(ValueType& ptr) { return add(ptr, 1); } + static ValueType dec(ValueType& ptr) { return sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static ValueType or_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::or_, ptr, val); + } + static ValueType xor_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::xor_, ptr, val); + } + static ValueType and_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::and_, ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#else +# error "Atomic compiler intrinsics are not supported on your platform" +#endif + +namespace mozilla { + +namespace detail { + +template +class AtomicBase +{ + // We only support 32-bit types on 32-bit Windows, which constrains our + // implementation elsewhere. But we support pointer-sized types everywhere. + static_assert(sizeof(T) == 4 || (sizeof(uintptr_t) == 8 && sizeof(T) == 8), + "mozilla/Atomics.h only supports 32-bit and pointer-sized types"); + + protected: + typedef typename detail::AtomicIntrinsics Intrinsics; + typename Intrinsics::ValueType mValue; + + public: + AtomicBase() : mValue() {} + AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + + operator T() const { return Intrinsics::load(mValue); } + + T operator=(T aValue) { + Intrinsics::store(mValue, aValue); + return aValue; + } + + /** + * Performs an atomic swap operation. aValue is stored and the previous + * value of this variable is returned. + */ + T exchange(T aValue) { + return Intrinsics::exchange(mValue, aValue); + } + + /** + * Performs an atomic compare-and-swap operation and returns true if it + * succeeded. This is equivalent to atomically doing + * + * if (mValue == aOldValue) { + * mValue = aNewValue; + * return true; + * } else { + * return false; + * } + */ + bool compareExchange(T aOldValue, T aNewValue) { + return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); + } + + private: + template + AtomicBase(const AtomicBase& aCopy) MOZ_DELETE; +}; + +template +class AtomicBaseIncDec : public AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + AtomicBaseIncDec() : Base() {} + AtomicBaseIncDec(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } + T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } + T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } + T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } + + private: + template + AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) MOZ_DELETE; +}; + +} // namespace detail + +/** + * A wrapper for a type that enforces that all memory accesses are atomic. + * + * In general, where a variable |T foo| exists, |Atomic foo| can be used in + * its place. Implementations for integral and pointer types are provided + * below. + * + * Atomic accesses are sequentially consistent by default. You should + * use the default unless you are tall enough to ride the + * memory-ordering roller coaster (if you're not sure, you aren't) and + * you have a compelling reason to do otherwise. + * + * There is one exception to the case of atomic memory accesses: providing an + * initial value of the atomic value is not guaranteed to be atomic. This is a + * deliberate design choice that enables static atomic variables to be declared + * without introducing extra static constructors. + */ +template +class Atomic; + +/** + * Atomic implementation for integral types. + * + * In addition to atomic store and load operations, compound assignment and + * increment/decrement operators are implemented which perform the + * corresponding read-modify-write operation atomically. Finally, an atomic + * swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator+=(T delta) { return Base::Intrinsics::add(Base::mValue, delta) + delta; } + T operator-=(T delta) { return Base::Intrinsics::sub(Base::mValue, delta) - delta; } + T operator|=(T val) { return Base::Intrinsics::or_(Base::mValue, val) | val; } + T operator^=(T val) { return Base::Intrinsics::xor_(Base::mValue, val) ^ val; } + T operator&=(T val) { return Base::Intrinsics::and_(Base::mValue, val) & val; } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for pointer types. + * + * An atomic compare-and-swap primitive for pointer variables is provided, as + * are atomic increment and decement operators. Also provided are the compound + * assignment operators for addition and subtraction. Atomic swap (via + * exchange()) is included as well. + */ +template +class Atomic : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T* aInit) : Base(aInit) {} + + using Base::operator=; + + T* operator+=(ptrdiff_t delta) { + return Base::Intrinsics::add(Base::mValue, delta) + delta; + } + T* operator-=(ptrdiff_t delta) { + return Base::Intrinsics::sub(Base::mValue, delta) - delta; + } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for enum types. + * + * The atomic store and load operations and the atomic swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Atomics_h */ diff --git a/external/spidermonkey/include/android/mozilla/Attributes.h b/external/spidermonkey/include/android/mozilla/Attributes.h index 89f3641fc9..6ea9776fbf 100644 --- a/external/spidermonkey/include/android/mozilla/Attributes.h +++ b/external/spidermonkey/include/android/mozilla/Attributes.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of various class and method modifier attributes. */ -#ifndef mozilla_Attributes_h_ -#define mozilla_Attributes_h_ +#ifndef mozilla_Attributes_h +#define mozilla_Attributes_h #include "mozilla/Compiler.h" @@ -117,11 +118,18 @@ * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a * function at compile time. A constexpr function cannot examine any values * except its arguments and can have no side effects except its return value. + * The MOZ_CONSTEXPR_VAR specifier tells a C++11 compiler that a variable's + * value may be computed at compile time. It should be prefered to just + * marking variables as MOZ_CONSTEXPR because if the compiler does not support + * constexpr it will fall back to making the variable const, and some compilers + * do not accept variables being marked both const and constexpr. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR # define MOZ_CONSTEXPR constexpr +# define MOZ_CONSTEXPR_VAR constexpr #else # define MOZ_CONSTEXPR /* no support */ +# define MOZ_CONSTEXPR_VAR const #endif /* @@ -382,18 +390,42 @@ * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is * expected to live on the stack, so it is a compile-time error to use it, or * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). It may be a base or - * a member of another class only if both classes are marked with this - * annotation. + * a new expression (unless placement new is being used). If a member of + * another class uses this class, or if another class inherits from this + * class, then it is considered to be a stack class as well, although this + * attribute need not be provided in such cases. + * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack or in static storage, so it is a compile-time + * error to use it, or an array of such objects, as the type of a new + * expression (unless placement new is being used). If a member of another + * class uses this class, or if another class inherits from this class, then + * it is considered to be a non-heap class as well, although this attribute + * need not be provided in such cases. */ #ifdef MOZ_CLANG_PLUGIN # define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) # define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) +# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) #else # define MOZ_MUST_OVERRIDE /* nothing */ # define MOZ_STACK_CLASS /* nothing */ +# define MOZ_NONHEAP_CLASS /* nothing */ #endif /* MOZ_CLANG_PLUGIN */ +/* + * MOZ_THIS_IN_INITIALIZER_LIST is used to avoid a warning when we know that + * it's safe to use 'this' in an initializer list. + */ +#ifdef _MSC_VER +# define MOZ_THIS_IN_INITIALIZER_LIST() \ + __pragma(warning(push)) \ + __pragma(warning(disable:4355)) \ + this \ + __pragma(warning(pop)) +#else +# define MOZ_THIS_IN_INITIALIZER_LIST() this +#endif + #endif /* __cplusplus */ -#endif /* mozilla_Attributes_h_ */ +#endif /* mozilla_Attributes_h */ diff --git a/external/spidermonkey/include/android/mozilla/BloomFilter.h b/external/spidermonkey/include/android/mozilla/BloomFilter.h index 8680ef2907..afe4b72b80 100644 --- a/external/spidermonkey/include/android/mozilla/BloomFilter.h +++ b/external/spidermonkey/include/android/mozilla/BloomFilter.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * A counting Bloom filter implementation. This allows consumers to @@ -10,14 +11,14 @@ * incorrectly answer "yes" when the correct answer is "no"). */ -#ifndef mozilla_BloomFilter_h_ -#define mozilla_BloomFilter_h_ +#ifndef mozilla_BloomFilter_h +#define mozilla_BloomFilter_h #include "mozilla/Assertions.h" #include "mozilla/Likely.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Util.h" +#include #include namespace mozilla { @@ -105,7 +106,7 @@ class BloomFilter */ public: BloomFilter() { - MOZ_STATIC_ASSERT(KeySize <= keyShift, "KeySize too big"); + static_assert(KeySize <= keyShift, "KeySize too big"); // Should we have a custom operator new using calloc instead and // require that we're allocated via the operator? @@ -231,4 +232,4 @@ BloomFilter::mightContain(const T* t) const } // namespace mozilla -#endif /* mozilla_BloomFilter_h_ */ +#endif /* mozilla_BloomFilter_h */ diff --git a/external/spidermonkey/include/android/mozilla/Casting.h b/external/spidermonkey/include/android/mozilla/Casting.h index b1e81c33fa..76df0ef27e 100644 --- a/external/spidermonkey/include/android/mozilla/Casting.h +++ b/external/spidermonkey/include/android/mozilla/Casting.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cast operations to supplement the built-in casting operations. */ -#ifndef mozilla_Casting_h_ -#define mozilla_Casting_h_ +#ifndef mozilla_Casting_h +#define mozilla_Casting_h #include "mozilla/Assertions.h" #include "mozilla/TypeTraits.h" @@ -15,6 +16,27 @@ namespace mozilla { +/** + * Return a value of type |To|, containing the underlying bit pattern of |from|. + * + * |To| and |From| must be types of the same size; be careful of cross-platform + * size differences, or this might fail to compile on some but not all + * platforms. + */ +template +inline To +BitwiseCast(const From from) +{ + static_assert(sizeof(From) == sizeof(To), + "To and From must have the same size"); + union { + From from; + To to; + } u; + u.from = from; + return u.to; +} + namespace detail { enum ToSignedness { ToIsSigned, ToIsUnsigned }; @@ -43,7 +65,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return from <= From(To(-1)); } }; @@ -52,7 +74,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -61,8 +83,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedUnsignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedUnsignedCheck::checkBounds(from); } }; @@ -72,7 +94,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (from < 0) return false; if (sizeof(To) >= sizeof(From)) @@ -93,7 +115,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -102,7 +124,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); return from <= From(MaxValue); } @@ -112,8 +134,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedSignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedSignedCheck::checkBounds(from); } }; @@ -123,7 +145,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (sizeof(From) <= sizeof(To)) return true; const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); @@ -141,15 +163,15 @@ template class BoundsChecker { public: - static bool check(const From from) { return true; } + static bool checkBounds(const From from) { return true; } }; template class BoundsChecker { public: - static bool check(const From from) { - return BoundsCheckImpl::check(from); + static bool checkBounds(const From from) { + return BoundsCheckImpl::checkBounds(from); } }; @@ -157,7 +179,7 @@ template inline bool IsInBounds(const From from) { - return BoundsChecker::check(from); + return BoundsChecker::checkBounds(from); } } // namespace detail @@ -177,4 +199,4 @@ SafeCast(const From from) } // namespace mozilla -#endif /* mozilla_Casting_h_ */ +#endif /* mozilla_Casting_h */ diff --git a/external/spidermonkey/include/android/mozilla/Char16.h b/external/spidermonkey/include/android/mozilla/Char16.h index c6f9f87d44..e4b184f950 100644 --- a/external/spidermonkey/include/android/mozilla/Char16.h +++ b/external/spidermonkey/include/android/mozilla/Char16.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implements a UTF-16 character type. */ -#ifndef mozilla_Char16_h_ -#define mozilla_Char16_h_ +#ifndef mozilla_Char16_h +#define mozilla_Char16_h #include "mozilla/Assertions.h" @@ -49,8 +50,8 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) -MOZ_STATIC_ASSERT(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); +static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); -#endif /* mozilla_Char16_h_ */ +#endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/android/mozilla/CheckedInt.h b/external/spidermonkey/include/android/mozilla/CheckedInt.h index 1dc80b032b..050cef8ed8 100644 --- a/external/spidermonkey/include/android/mozilla/CheckedInt.h +++ b/external/spidermonkey/include/android/mozilla/CheckedInt.h @@ -1,23 +1,23 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Provides checked integers, detecting integer overflow and divide-by-0. */ -#ifndef mozilla_CheckedInt_h_ -#define mozilla_CheckedInt_h_ +#ifndef mozilla_CheckedInt_h +#define mozilla_CheckedInt_h // Enable relying of Mozilla's MFBT for possibly-available C++11 features #define MOZ_CHECKEDINT_USE_MFBT +#include + #ifdef MOZ_CHECKEDINT_USE_MFBT # include "mozilla/Assertions.h" -# include "mozilla/StandardInteger.h" #else # include -# include -# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_DELETE #endif @@ -450,6 +450,44 @@ IsDivValid(T x, T y) !(IsSigned::value && x == MinValue::value && y == T(-1)); } +template::value> +struct IsModValidImpl; + +template +inline bool +IsModValid(T x, T y) +{ + return IsModValidImpl::run(x, y); +} + +/* + * Mod is pretty simple. + * For now, let's just use the ANSI C definition: + * If x or y are negative, the results are implementation defined. + * Consider these invalid. + * Undefined for y=0. + * The result will never exceed either x or y. + * + * Checking that x>=0 is a warning when T is unsigned. + */ + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + return y >= 1; + } +}; + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + if (x < 0) + return false; + + return y >= 1; + } +}; + template::value> struct NegateImpl; @@ -528,7 +566,7 @@ struct NegateImpl CheckedInt x(-1); // 1000 is of type int16_t, is found not to be in range for int8_t, // x is invalid - CheckedInt x(int16_t(1000)); + CheckedInt x(int16_t(1000)); // 3123456789 is of type uint32_t, is found not to be in range for int32_t, // x is invalid CheckedInt x(uint32_t(3123456789)); @@ -561,12 +599,12 @@ class CheckedInt template CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); } - friend class detail::NegateImpl; + friend struct detail::NegateImpl; public: /** @@ -585,16 +623,27 @@ class CheckedInt : mValue(T(value)), mIsValid(detail::IsInRange(value)) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); + } + + template + friend class CheckedInt; + + template + CheckedInt toChecked() const + { + CheckedInt ret(mValue); + ret.mIsValid = ret.mIsValid && mIsValid; + return ret; } /** Constructs a valid checked integer with initial value 0 */ CheckedInt() : mValue(0), mIsValid(true) { - MOZ_STATIC_ASSERT(detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value, + "This type is not supported by CheckedInt"); } /** @returns the actual value */ @@ -619,22 +668,31 @@ class CheckedInt const CheckedInt& rhs); template CheckedInt& operator +=(U rhs); + template friend CheckedInt operator -(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator -=(U rhs); + template friend CheckedInt operator *(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator *=(U rhs); + template friend CheckedInt operator /(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator /=(U rhs); + template + friend CheckedInt operator %(const CheckedInt& lhs, + const CheckedInt& rhs); + template + CheckedInt& operator %=(U rhs); + CheckedInt operator -() const { return detail::NegateImpl::negate(*this); @@ -726,6 +784,7 @@ MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) +MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) #undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR @@ -757,9 +816,9 @@ template inline typename detail::CastToCheckedIntImpl::ReturnType castToCheckedInt(U u) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); return detail::CastToCheckedIntImpl::run(u); } @@ -786,6 +845,7 @@ MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) +MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) #undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS @@ -815,4 +875,4 @@ typedef CheckedInt CheckedUint64; } // namespace mozilla -#endif /* mozilla_CheckedInt_h_ */ +#endif /* mozilla_CheckedInt_h */ diff --git a/external/spidermonkey/include/android/mozilla/Compiler.h b/external/spidermonkey/include/android/mozilla/Compiler.h index 58239b0e30..d1ef1e79aa 100644 --- a/external/spidermonkey/include/android/mozilla/Compiler.h +++ b/external/spidermonkey/include/android/mozilla/Compiler.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ -#ifndef mozilla_Compiler_h_ -#define mozilla_Compiler_h_ +#ifndef mozilla_Compiler_h +#define mozilla_Compiler_h #if !defined(__clang__) && defined(__GNUC__) @@ -28,4 +29,4 @@ #endif -#endif /* mozilla_Compiler_h_ */ +#endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/android/mozilla/Constants.h b/external/spidermonkey/include/android/mozilla/Constants.h index 904b30145a..86bbb6b354 100644 --- a/external/spidermonkey/include/android/mozilla/Constants.h +++ b/external/spidermonkey/include/android/mozilla/Constants.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt math constants. */ -#ifndef mozilla_Constants_h_ -#define mozilla_Constants_h_ +#ifndef mozilla_Constants_h +#define mozilla_Constants_h #ifndef M_PI # define M_PI 3.14159265358979323846 #endif -#endif /* mozilla_Constants_h_ */ +#endif /* mozilla_Constants_h */ diff --git a/external/spidermonkey/include/android/mozilla/DebugOnly.h b/external/spidermonkey/include/android/mozilla/DebugOnly.h index 1f78ed7989..e5f0d729b5 100644 --- a/external/spidermonkey/include/android/mozilla/DebugOnly.h +++ b/external/spidermonkey/include/android/mozilla/DebugOnly.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * assertions). */ -#ifndef mozilla_DebugOnly_h_ -#define mozilla_DebugOnly_h_ +#ifndef mozilla_DebugOnly_h +#define mozilla_DebugOnly_h namespace mozilla { @@ -74,4 +75,4 @@ class DebugOnly } -#endif /* mozilla_DebugOnly_h_ */ +#endif /* mozilla_DebugOnly_h */ diff --git a/external/spidermonkey/include/android/mozilla/Decimal.h b/external/spidermonkey/include/android/mozilla/Decimal.h index 8032fd6e23..3c67d784c9 100644 --- a/external/spidermonkey/include/android/mozilla/Decimal.h +++ b/external/spidermonkey/include/android/mozilla/Decimal.h @@ -38,7 +38,7 @@ #define Decimal_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" +#include #include "mozilla/Types.h" #include diff --git a/external/spidermonkey/include/android/mozilla/Endian.h b/external/spidermonkey/include/android/mozilla/Endian.h index 5d2f905b41..dc6d11d3ba 100644 --- a/external/spidermonkey/include/android/mozilla/Endian.h +++ b/external/spidermonkey/include/android/mozilla/Endian.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -59,16 +60,16 @@ * }; */ -#ifndef mozilla_Endian_h_ -#define mozilla_Endian_h_ +#ifndef mozilla_Endian_h +#define mozilla_Endian_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/DebugOnly.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" +#include #include #if defined(_MSC_VER) && _MSC_VER >= 1300 @@ -636,4 +637,4 @@ class NativeEndian MOZ_FINAL : public detail::Endian } /* namespace mozilla */ -#endif /* mozilla_Endian_h_ */ +#endif /* mozilla_Endian_h */ diff --git a/external/spidermonkey/include/android/mozilla/EnumSet.h b/external/spidermonkey/include/android/mozilla/EnumSet.h index b18b005669..95c5608cf4 100644 --- a/external/spidermonkey/include/android/mozilla/EnumSet.h +++ b/external/spidermonkey/include/android/mozilla/EnumSet.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,7 +10,8 @@ #define mozilla_EnumSet_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" + +#include namespace mozilla { @@ -172,4 +174,4 @@ class EnumSet } // namespace mozilla -#endif // mozilla_EnumSet_h_ +#endif /* mozilla_EnumSet_h_*/ diff --git a/external/spidermonkey/include/android/mozilla/FloatingPoint.h b/external/spidermonkey/include/android/mozilla/FloatingPoint.h index 30af2217b1..d80f6a7234 100644 --- a/external/spidermonkey/include/android/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/android/mozilla/FloatingPoint.h @@ -1,16 +1,19 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various predicates and operations on IEEE-754 floating point types. */ -#ifndef mozilla_FloatingPoint_h_ -#define mozilla_FloatingPoint_h_ +#ifndef mozilla_FloatingPoint_h +#define mozilla_FloatingPoint_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" +#include "mozilla/Casting.h" + +#include namespace mozilla { @@ -35,80 +38,58 @@ namespace mozilla { * the case. But we required this in implementations of these algorithms that * preceded this header, so we shouldn't break anything if we continue doing so. */ -MOZ_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); +static_assert(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); const unsigned DoubleExponentBias = 1023; const unsigned DoubleExponentShift = 52; -namespace detail { - const uint64_t DoubleSignBit = 0x8000000000000000ULL; const uint64_t DoubleExponentBits = 0x7ff0000000000000ULL; const uint64_t DoubleSignificandBits = 0x000fffffffffffffULL; -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleExponentBits) == 0, - "sign bit doesn't overlap exponent bits"); -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleSignificandBits) == 0, - "sign bit doesn't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleExponentBits & DoubleSignificandBits) == 0, - "exponent bits don't overlap significand bits"); +static_assert((DoubleSignBit & DoubleExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((DoubleSignBit & DoubleSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((DoubleExponentBits & DoubleSignificandBits) == 0, + "exponent bits don't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == - ~uint64_t(0), - "all bits accounted for"); - -union DoublePun -{ - /* - * Every way to pun the bits of a double introduces an additional layer of - * complexity, across a multitude of platforms, architectures, and ABIs. - * Use *only* uint64_t to reduce complexity. Don't add new punning here - * without discussion! - */ - uint64_t u; - double d; -}; - -} /* namespace detail */ +static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == + ~uint64_t(0), + "all bits accounted for"); /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * A double is NaN if all exponent bits are 1 and the significand contains at * least one non-zero bit. */ - return (pun.u & detail::DoubleExponentBits) == detail::DoubleExponentBits && - (pun.u & detail::DoubleSignificandBits) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) == DoubleExponentBits && + (bits & DoubleSignificandBits) != 0; } /** Determines whether a double is +Infinity or -Infinity. */ static MOZ_ALWAYS_INLINE bool IsInfinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - return (pun.u & ~detail::DoubleSignBit) == detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & ~DoubleSignBit) == DoubleExponentBits; } /** Determines whether a double is not NaN or infinite. */ static MOZ_ALWAYS_INLINE bool IsFinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * NaN and Infinities are the only non-finite doubles, and both have all * exponent bits set to 1. */ - return (pun.u & detail::DoubleExponentBits) != detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) != DoubleExponentBits; } /** @@ -120,36 +101,30 @@ IsNegative(double d) { MOZ_ASSERT(!IsNaN(d), "NaN does not have a sign"); - union detail::DoublePun pun; - pun.d = d; - /* The sign bit is set if the double is negative. */ - return (pun.u & detail::DoubleSignBit) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleSignBit) != 0; } /** Determines whether a double represents -0. */ static MOZ_ALWAYS_INLINE bool IsNegativeZero(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Only the sign bit is set if the double is -0. */ - return pun.u == detail::DoubleSignBit; + uint64_t bits = BitwiseCast(d); + return bits == DoubleSignBit; } /** Returns the exponent portion of the double. */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * The exponent component of a double is an unsigned number, biased from its * actual value. Subtract the bias to retrieve the actual exponent. */ - return int_fast16_t((pun.u & detail::DoubleExponentBits) >> DoubleExponentShift) - + uint64_t bits = BitwiseCast(d); + return int_fast16_t((bits & DoubleExponentBits) >> DoubleExponentShift) - int_fast16_t(DoubleExponentBias); } @@ -157,28 +132,22 @@ ExponentComponent(double d) static MOZ_ALWAYS_INLINE double PositiveInfinity() { - union detail::DoublePun pun; - /* * Positive infinity has all exponent bits set, sign bit set to 0, and no * significand. */ - pun.u = detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleExponentBits); } /** Returns -Infinity. */ static MOZ_ALWAYS_INLINE double NegativeInfinity() { - union detail::DoublePun pun; - /* * Negative infinity has all exponent bits set, sign bit set to 1, and no * significand. */ - pun.u = detail::DoubleSignBit | detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleSignBit | DoubleExponentBits); } /** Constructs a NaN value with the specified sign bit and significand bits. */ @@ -186,24 +155,21 @@ static MOZ_ALWAYS_INLINE double SpecificNaN(int signbit, uint64_t significand) { MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~detail::DoubleSignificandBits) == 0); - MOZ_ASSERT(significand & detail::DoubleSignificandBits); + MOZ_ASSERT((significand & ~DoubleSignificandBits) == 0); + MOZ_ASSERT(significand & DoubleSignificandBits); - union detail::DoublePun pun; - pun.u = (signbit ? detail::DoubleSignBit : 0) | - detail::DoubleExponentBits | - significand; - MOZ_ASSERT(IsNaN(pun.d)); - return pun.d; + double d = BitwiseCast((signbit ? DoubleSignBit : 0) | + DoubleExponentBits | + significand); + MOZ_ASSERT(IsNaN(d)); + return d; } /** Computes the smallest non-zero positive double value. */ static MOZ_ALWAYS_INLINE double MinDoubleValue() { - union detail::DoublePun pun; - pun.u = 1; - return pun.d; + return BitwiseCast(uint64_t(1)); } static MOZ_ALWAYS_INLINE bool @@ -224,9 +190,22 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return mozilla::SpecificNaN(0, 0xfffffffffffffULL); + return SpecificNaN(0, 0xfffffffffffffULL); +} + +/** + * Compare two doubles for equality, *without* equating -0 to +0, and equating + * any NaN value to any other NaN value. (The normal equality operators equate + * -0 with +0, and they equate NaN to no other value.) + */ +static inline bool +DoublesAreIdentical(double d1, double d2) +{ + if (IsNaN(d1)) + return IsNaN(d2); + return BitwiseCast(d1) == BitwiseCast(d2); } } /* namespace mozilla */ -#endif /* mozilla_FloatingPoint_h_ */ +#endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/android/mozilla/GuardObjects.h b/external/spidermonkey/include/android/mozilla/GuardObjects.h index 6c2058938c..aeae7dcbc0 100644 --- a/external/spidermonkey/include/android/mozilla/GuardObjects.h +++ b/external/spidermonkey/include/android/mozilla/GuardObjects.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,6 +10,7 @@ #define mozilla_GuardObjects_h #include "mozilla/Assertions.h" +#include "mozilla/NullPtr.h" #include "mozilla/Types.h" #ifdef __cplusplus @@ -72,7 +74,7 @@ class MOZ_EXPORT GuardObjectNotifier bool* statementDone; public: - GuardObjectNotifier() : statementDone(NULL) { } + GuardObjectNotifier() : statementDone(nullptr) { } ~GuardObjectNotifier() { *statementDone = true; diff --git a/external/spidermonkey/include/android/mozilla/HashFunctions.h b/external/spidermonkey/include/android/mozilla/HashFunctions.h index 96242b629a..6d0d24e7b1 100644 --- a/external/spidermonkey/include/android/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/android/mozilla/HashFunctions.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Utilities for hashing. */ @@ -39,17 +40,18 @@ * }; * * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKey.h. + * in nsHashKeys.h. */ -#ifndef mozilla_HashFunctions_h_ -#define mozilla_HashFunctions_h_ +#ifndef mozilla_HashFunctions_h +#define mozilla_HashFunctions_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + #ifdef __cplusplus namespace mozilla { @@ -173,8 +175,8 @@ AddToHash(uint32_t hash, A* a) * catch data pointers and couldn't handle function pointers. */ - MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t), - "Strange pointer!"); + static_assert(sizeof(a) == sizeof(uintptr_t), + "Strange pointer!"); return detail::AddUintptrToHash(hash, uintptr_t(a)); } @@ -356,4 +358,5 @@ HashBytes(const void* bytes, size_t length); } /* namespace mozilla */ #endif /* __cplusplus */ -#endif /* mozilla_HashFunctions_h_ */ + +#endif /* mozilla_HashFunctions_h */ diff --git a/external/spidermonkey/include/android/mozilla/Likely.h b/external/spidermonkey/include/android/mozilla/Likely.h index 6412b4943b..4f21609295 100644 --- a/external/spidermonkey/include/android/mozilla/Likely.h +++ b/external/spidermonkey/include/android/mozilla/Likely.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a * boolean predicate should be branch-predicted. */ -#ifndef mozilla_Likely_h_ -#define mozilla_Likely_h_ +#ifndef mozilla_Likely_h +#define mozilla_Likely_h #if defined(__clang__) || defined(__GNUC__) # define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) @@ -19,4 +20,4 @@ # define MOZ_UNLIKELY(x) (!!(x)) #endif -#endif /* mozilla_Likely_h_ */ +#endif /* mozilla_Likely_h */ diff --git a/external/spidermonkey/include/android/mozilla/LinkedList.h b/external/spidermonkey/include/android/mozilla/LinkedList.h index 5cfd60e4ac..c29760b3e7 100644 --- a/external/spidermonkey/include/android/mozilla/LinkedList.h +++ b/external/spidermonkey/include/android/mozilla/LinkedList.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -45,18 +46,19 @@ * } * * void notifyObservers(char* topic) { - * for (Observer* o = list.getFirst(); o != NULL; o = o->getNext()) - * o->Observe(topic); + * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) + * o->observe(topic); * } * }; * */ -#ifndef mozilla_LinkedList_h_ -#define mozilla_LinkedList_h_ +#ifndef mozilla_LinkedList_h +#define mozilla_LinkedList_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -69,10 +71,10 @@ template class LinkedListElement { /* - * It's convenient that we return NULL when getNext() or getPrevious() hits - * the end of the list, but doing so costs an extra word of storage in each - * linked list node (to keep track of whether |this| is the sentinel node) - * and a branch on this value in getNext/getPrevious. + * It's convenient that we return nullptr when getNext() or getPrevious() + * hits the end of the list, but doing so costs an extra word of storage in + * each linked list node (to keep track of whether |this| is the sentinel + * node) and a branch on this value in getNext/getPrevious. * * We could get rid of the extra word of storage by shoving the "is * sentinel" bit into one of the pointers, although this would, of course, @@ -107,12 +109,10 @@ class LinkedListElement LinkedListElement* prev; const bool isSentinel; - LinkedListElement* thisDuringConstruction() { return this; } - public: LinkedListElement() - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(false) { } @@ -122,8 +122,8 @@ class LinkedListElement } /* - * Get the next element in the list, or NULL if this is the last element in - * the list. + * Get the next element in the list, or nullptr if this is the last element + * in the list. */ T* getNext() { return next->asT(); @@ -133,8 +133,8 @@ class LinkedListElement } /* - * Get the previous element in the list, or NULL if this is the first element - * in the list. + * Get the previous element in the list, or nullptr if this is the first + * element in the list. */ T* getPrevious() { return prev->asT(); @@ -201,24 +201,24 @@ class LinkedListElement }; LinkedListElement(NodeKind nodeKind) - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(nodeKind == NODE_KIND_SENTINEL) { } /* - * Return |this| cast to T* if we're a normal node, or return NULL if we're - * a sentinel node. + * Return |this| cast to T* if we're a normal node, or return nullptr if + * we're a sentinel node. */ T* asT() { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } const T* asT() const { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } @@ -285,7 +285,7 @@ class LinkedList } /* - * Get the first element of the list, or NULL if the list is empty. + * Get the first element of the list, or nullptr if the list is empty. */ T* getFirst() { return sentinel.getNext(); @@ -295,7 +295,7 @@ class LinkedList } /* - * Get the last element of the list, or NULL if the list is empty. + * Get the last element of the list, or nullptr if the list is empty. */ T* getLast() { return sentinel.getPrevious(); @@ -306,7 +306,7 @@ class LinkedList /* * Get and remove the first element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popFirst() { T* ret = sentinel.getNext(); @@ -317,7 +317,7 @@ class LinkedList /* * Get and remove the last element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popLast() { T* ret = sentinel.getPrevious(); @@ -415,7 +415,7 @@ class LinkedList if (elem == t) return; } - MOZ_NOT_REACHED("element wasn't found in this list!"); + MOZ_CRASH("element wasn't found in this list!"); #endif } @@ -425,5 +425,6 @@ class LinkedList } /* namespace mozilla */ -#endif /* ifdef __cplusplus */ -#endif /* ifdef mozilla_LinkedList_h_ */ +#endif /* __cplusplus */ + +#endif /* mozilla_LinkedList_h */ diff --git a/external/spidermonkey/include/android/mozilla/MSStdInt.h b/external/spidermonkey/include/android/mozilla/MSStdInt.h deleted file mode 100644 index 0447f2f11b..0000000000 --- a/external/spidermonkey/include/android/mozilla/MSStdInt.h +++ /dev/null @@ -1,247 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// Redistribution and use in source and binary forms, 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. -// -// 3. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 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 _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int32_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint32_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - - -#endif // _MSC_STDINT_H_ ] diff --git a/external/spidermonkey/include/android/mozilla/MathAlgorithms.h b/external/spidermonkey/include/android/mozilla/MathAlgorithms.h index 0a47810553..6d58691e06 100644 --- a/external/spidermonkey/include/android/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/android/mozilla/MathAlgorithms.h @@ -1,19 +1,20 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt maths algorithms. */ -#ifndef mozilla_MathAlgorithms_h_ -#define mozilla_MathAlgorithms_h_ +#ifndef mozilla_MathAlgorithms_h +#define mozilla_MathAlgorithms_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" #include #include +#include namespace mozilla { @@ -142,6 +143,288 @@ Abs(const long double d) return std::fabs(d); } +} // namespace mozilla + +#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) +# define MOZ_BITSCAN_WINDOWS + + extern "C" { + unsigned char _BitScanForward(unsigned long* Index, unsigned long mask); + unsigned char _BitScanReverse(unsigned long* Index, unsigned long mask); +# pragma intrinsic(_BitScanForward, _BitScanReverse) + +# if defined(_M_AMD64) || defined(_M_X64) +# define MOZ_BITSCAN_WINDOWS64 + unsigned char _BitScanForward64(unsigned long* index, unsigned __int64 mask); + unsigned char _BitScanReverse64(unsigned long* index, unsigned __int64 mask); +# pragma intrinsic(_BitScanForward64, _BitScanReverse64) +# endif + } // extern "C" + +#endif + +namespace mozilla { + +namespace detail { + +#if defined(MOZ_BITSCAN_WINDOWS) + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanReverse(&index, static_cast(u)); + return uint_fast8_t(31 - index); + } + + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanForward(&index, static_cast(u)); + return uint_fast8_t(index); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanReverse64(&index, static_cast(u)); + return uint_fast8_t(63 - index); +# else + uint32_t hi = uint32_t(u >> 32); + if (hi != 0) + return CountLeadingZeroes32(hi); + return 32 + CountLeadingZeroes32(uint32_t(u)); +# endif + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanForward64(&index, static_cast(u)); + return uint_fast8_t(index); +# else + uint32_t lo = uint32_t(u); + if (lo != 0) + return CountTrailingZeroes32(lo); + return 32 + CountTrailingZeroes32(uint32_t(u >> 32)); +# endif + } + +# ifdef MOZ_HAVE_BITSCAN64 +# undef MOZ_HAVE_BITSCAN64 +# endif + +#elif defined(__clang__) || defined(__GNUC__) + +# if defined(__clang__) +# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) +# error "A clang providing __builtin_c[lt]z is required to build" +# endif +# else + // gcc has had __builtin_clz and friends since 3.4: no need to check. +# endif + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + return __builtin_clz(u); + } + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + return __builtin_ctz(u); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { + return __builtin_clzll(u); + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { + return __builtin_ctzll(u); + } + +#else +# error "Implement these!" + inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; +#endif + +} // namespace detail + +/** + * Compute the number of high-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the highest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountLeadingZeroes32(0xF0FF1000) is 0; + * CountLeadingZeroes32(0x7F8F0001) is 1; + * CountLeadingZeroes32(0x3FFF0100) is 2; + * CountLeadingZeroes32(0x1FF50010) is 3; and so on. + */ +inline uint_fast8_t +CountLeadingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes32(u); +} + +/** + * Compute the number of low-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the lowest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountTrailingZeroes32(0x0100FFFF) is 0; + * CountTrailingZeroes32(0x7000FFFE) is 1; + * CountTrailingZeroes32(0x0080FFFC) is 2; + * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. + */ +inline uint_fast8_t +CountTrailingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes32(u); +} + +/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountLeadingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes64(u); +} + +/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountTrailingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes64(u); +} + +namespace detail { + +template +class CeilingLog2; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 32 - CountLeadingZeroes32(t - 1); + } +}; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 64 - CountLeadingZeroes64(t - 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the least power of 2 greater than or equal to |t|. + * + * CeilingLog2(0..1) is 0; + * CeilingLog2(2) is 1; + * CeilingLog2(3..4) is 2; + * CeilingLog2(5..8) is 3; + * CeilingLog2(9..16) is 4; and so on. + */ +template +inline uint_fast8_t +CeilingLog2(const T t) +{ + return detail::CeilingLog2::compute(t); +} + +/** A CeilingLog2 variant that accepts only size_t. */ +inline uint_fast8_t +CeilingLog2Size(size_t n) +{ + return CeilingLog2(n); +} + +namespace detail { + +template +class FloorLog2; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 31 - CountLeadingZeroes32(t | 1); + } +}; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 63 - CountLeadingZeroes64(t | 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the greatest power of 2 less than or equal to |t|. + * + * FloorLog2(0..1) is 0; + * FloorLog2(2..3) is 1; + * FloorLog2(4..7) is 2; + * FloorLog2(8..15) is 3; and so on. + */ +template +inline uint_fast8_t +FloorLog2(const T t) +{ + return detail::FloorLog2::compute(t); +} + +/** A FloorLog2 variant that accepts only size_t. */ +inline uint_fast8_t +FloorLog2Size(size_t n) +{ + return FloorLog2(n); +} + +/* + * Compute the smallest power of 2 greater than or equal to |x|. |x| must not + * be so great that the computed value would overflow |size_t|. + */ +inline size_t +RoundUpPow2(size_t x) +{ + MOZ_ASSERT(x <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), + "can't round up -- will overflow!"); + return size_t(1) << CeilingLog2(x); +} + } /* namespace mozilla */ -#endif /* mozilla_MathAlgorithms_h_ */ +#endif /* mozilla_MathAlgorithms_h */ diff --git a/external/spidermonkey/include/android/mozilla/MemoryChecking.h b/external/spidermonkey/include/android/mozilla/MemoryChecking.h index 3287e57ba1..2130990c6b 100644 --- a/external/spidermonkey/include/android/mozilla/MemoryChecking.h +++ b/external/spidermonkey/include/android/mozilla/MemoryChecking.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -19,8 +20,8 @@ * With no memory checker available, all macros expand to the empty statement. */ -#ifndef mozilla_MemoryChecking_h_ -#define mozilla_MemoryChecking_h_ +#ifndef mozilla_MemoryChecking_h +#define mozilla_MemoryChecking_h #if defined(MOZ_VALGRIND) #include "valgrind/memcheck.h" @@ -68,4 +69,4 @@ extern "C" { #endif -#endif /* mozilla_MemoryChecking_h_ */ +#endif /* mozilla_MemoryChecking_h */ diff --git a/external/spidermonkey/include/android/mozilla/MemoryReporting.h b/external/spidermonkey/include/android/mozilla/MemoryReporting.h new file mode 100644 index 0000000000..d2340ecf09 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/MemoryReporting.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Memory reporting infrastructure. */ + +#ifndef mozilla_MemoryReporting_h +#define mozilla_MemoryReporting_h + +#include + +#ifdef __cplusplus + +namespace mozilla { + +/* + * This is for functions that are like malloc_usable_size. Such functions are + * used for measuring the size of data structures. + */ +typedef size_t (*MallocSizeOf)(const void* p); + +} /* namespace mozilla */ + +#endif /* __cplusplus */ + +typedef size_t (*MozMallocSizeOf)(const void* p); + +#endif /* mozilla_MemoryReporting_h */ diff --git a/external/spidermonkey/include/android/mozilla/Move.h b/external/spidermonkey/include/android/mozilla/Move.h new file mode 100644 index 0000000000..97178daaa6 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Move.h @@ -0,0 +1,166 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* C++11-style, but C++98-usable, "move references" implementation. */ + +#ifndef mozilla_Move_h +#define mozilla_Move_h + +namespace mozilla { + +/* + * "Move" References + * + * Some types can be copied much more efficiently if we know the original's + * value need not be preserved --- that is, if we are doing a "move", not a + * "copy". For example, if we have: + * + * Vector u; + * Vector v(u); + * + * the constructor for v must apply a copy constructor to each element of u --- + * taking time linear in the length of u. However, if we know we will not need u + * any more once v has been initialized, then we could initialize v very + * efficiently simply by stealing u's dynamically allocated buffer and giving it + * to v --- a constant-time operation, regardless of the size of u. + * + * Moves often appear in container implementations. For example, when we append + * to a vector, we may need to resize its buffer. This entails moving each of + * its extant elements from the old, smaller buffer to the new, larger buffer. + * But once the elements have been migrated, we're just going to throw away the + * old buffer; we don't care if they still have their values. So if the vector's + * element type can implement "move" more efficiently than "copy", the vector + * resizing should by all means use a "move" operation. Hash tables also need to + * be resized. + * + * The details of the optimization, and whether it's worth applying, vary from + * one type to the next. And while some constructor calls are moves, many really + * are copies, and can't be optimized this way. So we need: + * + * 1) a way for a particular invocation of a copy constructor to say that it's + * really a move, and that the value of the original isn't important + * afterwards (although it must still be safe to destroy); and + * + * 2) a way for a type (like Vector) to announce that it can be moved more + * efficiently than it can be copied, and provide an implementation of that + * move operation. + * + * The Move(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's 1). A MoveRef is simply a reference + * to a T, annotated to say that a copy constructor applied to it may move that + * T, instead of copying it. Finally, a constructor that accepts an MoveRef + * should perform a more efficient move, instead of a copy, providing 2). + * + * So, where we might define a copy constructor for a class C like this: + * + * C(const C& rhs) { ... copy rhs to this ... } + * + * we would declare a move constructor like this: + * + * C(MoveRef rhs) { ... move rhs to this ... } + * + * And where we might perform a copy like this: + * + * C c2(c1); + * + * we would perform a move like this: + * + * C c2(Move(c1)) + * + * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef + * to an ordinary copy constructor for a type that doesn't support a special + * move constructor, and you'll just get a copy. This means that templates can + * use Move whenever they know they won't use the original value any more, even + * if they're not sure whether the type at hand has a specialized move + * constructor. If it doesn't, the MoveRef will just convert to a T&, and + * the ordinary copy constructor will apply. + * + * A class with a move constructor can also provide a move assignment operator, + * which runs this's destructor, and then applies the move constructor to + * *this's memory. A typical definition: + * + * C& operator=(MoveRef rhs) { + * this->~C(); + * new(this) C(rhs); + * return *this; + * } + * + * With that in place, one can write move assignments like this: + * + * c2 = Move(c1); + * + * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but + * destructible state. + * + * This header file defines MoveRef and Move in the mozilla namespace. It's up + * to individual containers to annotate moves as such, by calling Move; and it's + * up to individual types to define move constructors. + * + * One hint: if you're writing a move constructor where the type has members + * that should be moved themselves, it's much nicer to write this: + * + * C(MoveRef c) : x(Move(c->x)), y(Move(c->y)) { } + * + * than the equivalent: + * + * C(MoveRef c) { new(&x) X(Move(c->x)); new(&y) Y(Move(c->y)); } + * + * especially since GNU C++ fails to notice that this does indeed initialize x + * and y, which may matter if they're const. + */ +template +class MoveRef +{ + T* pointer; + + public: + explicit MoveRef(T& t) : pointer(&t) { } + T& operator*() const { return *pointer; } + T* operator->() const { return pointer; } + operator T& () const { return *pointer; } +}; + +template +inline MoveRef +Move(T& t) +{ + return MoveRef(t); +} + +template +inline MoveRef +Move(const T& t) +{ + // With some versions of gcc, for a class C, there's an (incorrect) ambiguity + // between the C(const C&) constructor and the default C(C&&) C++11 move + // constructor, when the constructor is called with a const C& argument. + // + // This ambiguity manifests with the Move implementation above when Move is + // passed const U& for some class U. Calling Move(const U&) returns a + // MoveRef, which is then commonly passed to the U constructor, + // triggering an implicit conversion to const U&. gcc doesn't know whether to + // call U(const U&) or U(U&&), so it wrongly reports a compile error. + // + // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50442 has since been fixed, so + // this is no longer an issue for up-to-date compilers. But there's no harm + // in keeping it around for older compilers, so we might as well. See also + // bug 686280. + return MoveRef(const_cast(t)); +} + +/** Swap |t| and |u| using move-construction if possible. */ +template +inline void +Swap(T& t, T& u) +{ + T tmp(Move(t)); + t = Move(u); + u = Move(tmp); +} + +} // namespace mozilla + +#endif /* mozilla_Move_h */ diff --git a/external/spidermonkey/include/android/mozilla/NullPtr.h b/external/spidermonkey/include/android/mozilla/NullPtr.h index 7dcb03d734..14c0f07df2 100644 --- a/external/spidermonkey/include/android/mozilla/NullPtr.h +++ b/external/spidermonkey/include/android/mozilla/NullPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * constant. */ -#ifndef mozilla_NullPtr_h_ -#define mozilla_NullPtr_h_ +#ifndef mozilla_NullPtr_h +#define mozilla_NullPtr_h #include "mozilla/Compiler.h" @@ -45,4 +46,4 @@ # endif #endif -#endif /* mozilla_NullPtr_h_ */ +#endif /* mozilla_NullPtr_h */ diff --git a/external/spidermonkey/include/android/mozilla/PodOperations.h b/external/spidermonkey/include/android/mozilla/PodOperations.h index 6c6af27fc9..bec89fa928 100644 --- a/external/spidermonkey/include/android/mozilla/PodOperations.h +++ b/external/spidermonkey/include/android/mozilla/PodOperations.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -156,4 +157,4 @@ PodEqual(const T* one, const T* two, size_t len) } // namespace mozilla -#endif // mozilla_PodOperations_h_ +#endif /* mozilla_PodOperations_h */ diff --git a/external/spidermonkey/include/android/mozilla/Poison.h b/external/spidermonkey/include/android/mozilla/Poison.h index c4adc23e71..75e0f081cd 100644 --- a/external/spidermonkey/include/android/mozilla/Poison.h +++ b/external/spidermonkey/include/android/mozilla/Poison.h @@ -9,13 +9,14 @@ * an address that leads to a safe crash when dereferenced. */ -#ifndef mozilla_Poison_h_ -#define mozilla_Poison_h_ +#ifndef mozilla_Poison_h +#define mozilla_Poison_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + MOZ_BEGIN_EXTERN_C extern MFBT_DATA uintptr_t gMozillaPoisonValue; @@ -36,11 +37,11 @@ inline uintptr_t mozPoisonValue() */ inline void mozWritePoison(void* aPtr, size_t aSize) { - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); const uintptr_t POISON = mozPoisonValue(); char* p = (char*)aPtr; char* limit = p + aSize; + MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); + MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); for (; p < limit; p += sizeof(uintptr_t)) { *((uintptr_t*)p) = POISON; } @@ -58,4 +59,4 @@ extern MFBT_DATA uintptr_t gMozillaPoisonSize; MOZ_END_EXTERN_C -#endif /* mozilla_Poison_h_ */ +#endif /* mozilla_Poison_h */ diff --git a/external/spidermonkey/include/android/mozilla/Range.h b/external/spidermonkey/include/android/mozilla/Range.h index e14594d09d..4e02d962b5 100644 --- a/external/spidermonkey/include/android/mozilla/Range.h +++ b/external/spidermonkey/include/android/mozilla/Range.h @@ -1,12 +1,11 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef mozilla_Range_h_ -#define mozilla_Range_h_ +#ifndef mozilla_Range_h +#define mozilla_Range_h #include "mozilla/NullPtr.h" #include "mozilla/RangedPtr.h" @@ -40,10 +39,13 @@ class Range return mStart[offset]; } + const T& operator[](size_t offset) const { + return mStart[offset]; + } + operator ConvertibleToBool() const { return mStart ? &Range::nonNull : 0; } }; } // namespace mozilla -#endif // mozilla_Range_h_ - +#endif /* mozilla_Range_h */ diff --git a/external/spidermonkey/include/android/mozilla/RangedPtr.h b/external/spidermonkey/include/android/mozilla/RangedPtr.h index 7ce19d071f..493fcdbaee 100644 --- a/external/spidermonkey/include/android/mozilla/RangedPtr.h +++ b/external/spidermonkey/include/android/mozilla/RangedPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,11 +9,12 @@ * construction. */ -#ifndef mozilla_RangedPtr_h_ -#define mozilla_RangedPtr_h_ +#ifndef mozilla_RangedPtr_h +#define mozilla_RangedPtr_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #include "mozilla/Util.h" namespace mozilla { @@ -59,7 +61,7 @@ class RangedPtr #ifdef DEBUG return RangedPtr(p, rangeStart, rangeEnd); #else - return RangedPtr(p, NULL, size_t(0)); + return RangedPtr(p, nullptr, size_t(0)); #endif } @@ -251,4 +253,4 @@ class RangedPtr } /* namespace mozilla */ -#endif /* mozilla_RangedPtr_h_ */ +#endif /* mozilla_RangedPtr_h */ diff --git a/external/spidermonkey/include/android/mozilla/ReentrancyGuard.h b/external/spidermonkey/include/android/mozilla/ReentrancyGuard.h new file mode 100644 index 0000000000..d589f368a2 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/ReentrancyGuard.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Small helper class for asserting uses of a class are non-reentrant. */ + +#ifndef mozilla_ReentrancyGuard_h +#define mozilla_ReentrancyGuard_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/GuardObjects.h" + +namespace mozilla { + +/* Useful for implementing containers that assert non-reentrancy */ +class ReentrancyGuard +{ + MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER +#ifdef DEBUG + bool& entered; +#endif + + public: + template +#ifdef DEBUG + ReentrancyGuard(T& obj + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : entered(obj.entered) +#else + ReentrancyGuard(T& + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) +#endif + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; +#ifdef DEBUG + MOZ_ASSERT(!entered); + entered = true; +#endif + } + ~ReentrancyGuard() + { +#ifdef DEBUG + entered = false; +#endif + } + + private: + ReentrancyGuard(const ReentrancyGuard&) MOZ_DELETE; + void operator=(const ReentrancyGuard&) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_ReentrancyGuard_h */ diff --git a/external/spidermonkey/include/android/mozilla/RefPtr.h b/external/spidermonkey/include/android/mozilla/RefPtr.h index 9f4163a21a..3c275afdc7 100644 --- a/external/spidermonkey/include/android/mozilla/RefPtr.h +++ b/external/spidermonkey/include/android/mozilla/RefPtr.h @@ -1,14 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Helpers for defining and using refcounted objects. */ -#ifndef mozilla_RefPtr_h_ -#define mozilla_RefPtr_h_ +#ifndef mozilla_RefPtr_h +#define mozilla_RefPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/Attributes.h" #include "mozilla/TypeTraits.h" @@ -41,13 +43,19 @@ template OutParamRef byRef(RefPtr&); * state distinguishes use-before-ref (refcount==0) from * use-after-destroy (refcount==0xffffdead). */ -#ifdef DEBUG namespace detail { +#ifdef DEBUG static const int DEAD = 0xffffdead; -} #endif -template +// This is used WeakPtr.h as well as this file. +enum RefCountAtomicity +{ + AtomicRefCount, + NonAtomicRefCount +}; + +template class RefCounted { friend class RefPtr; @@ -56,8 +64,6 @@ class RefCounted RefCounted() : refCnt(0) { } ~RefCounted() { MOZ_ASSERT(refCnt == detail::DEAD); - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from RefCounted"); } public: @@ -87,7 +93,33 @@ class RefCounted } private: - int refCnt; + typename Conditional, int>::Type refCnt; +}; + +} + +template +class RefCounted : public detail::RefCounted +{ + public: + ~RefCounted() { + static_assert(IsBaseOf::value, + "T must derive from RefCounted"); + } +}; + +/** + * AtomicRefCounted is like RefCounted, with an atomically updated + * reference counter. + */ +template +class AtomicRefCounted : public detail::RefCounted +{ + public: + ~AtomicRefCounted() { + static_assert(IsBaseOf::value, + "T must derive from AtomicRefCounted"); + } }; /** @@ -259,9 +291,6 @@ byRef(RefPtr& ptr) } // namespace mozilla -#endif // mozilla_RefPtr_h_ - - #if 0 // Command line that builds these tests @@ -416,3 +445,5 @@ main(int argc, char** argv) } #endif + +#endif /* mozilla_RefPtr_h */ diff --git a/external/spidermonkey/include/android/mozilla/SHA1.h b/external/spidermonkey/include/android/mozilla/SHA1.h index a6604e699f..b167648540 100644 --- a/external/spidermonkey/include/android/mozilla/SHA1.h +++ b/external/spidermonkey/include/android/mozilla/SHA1.h @@ -1,17 +1,18 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Simple class for computing SHA1. */ -#ifndef mozilla_SHA1_h_ -#define mozilla_SHA1_h_ +#ifndef mozilla_SHA1_h +#define mozilla_SHA1_h -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" #include +#include namespace mozilla { @@ -58,4 +59,4 @@ class SHA1Sum } /* namespace mozilla */ -#endif /* mozilla_SHA1_h_ */ +#endif /* mozilla_SHA1_h */ diff --git a/external/spidermonkey/include/android/mozilla/Scoped.h b/external/spidermonkey/include/android/mozilla/Scoped.h index 677a1a3797..fc48584b3e 100644 --- a/external/spidermonkey/include/android/mozilla/Scoped.h +++ b/external/spidermonkey/include/android/mozilla/Scoped.h @@ -1,11 +1,13 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A number of structures to simplify scope-based RAII management. */ -#ifndef mozilla_Scoped_h_ -#define mozilla_Scoped_h_ +#ifndef mozilla_Scoped_h +#define mozilla_Scoped_h /* * Resource Acquisition Is Initialization is a programming idiom used @@ -52,6 +54,7 @@ #include "mozilla/Attributes.h" #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -193,7 +196,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { free(ptr); } }; SCOPED_TEMPLATE(ScopedFreePtr, ScopedFreePtrTraits) @@ -256,7 +259,7 @@ template struct TypeSpecificScopedPointerTraits { typedef T* type; - const static type empty() { return NULL; } + const static type empty() { return nullptr; } const static void release(type value) { if (value) @@ -268,4 +271,4 @@ SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) } /* namespace mozilla */ -#endif // mozilla_Scoped_h_ +#endif /* mozilla_Scoped_h */ diff --git a/external/spidermonkey/include/android/mozilla/SplayTree.h b/external/spidermonkey/include/android/mozilla/SplayTree.h index f9a10d36dd..de0235aec9 100644 --- a/external/spidermonkey/include/android/mozilla/SplayTree.h +++ b/external/spidermonkey/include/android/mozilla/SplayTree.h @@ -1,7 +1,6 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=99 ft=cpp: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,8 +9,8 @@ * are faster to access again. */ -#ifndef mozilla_SplayTree_h_ -#define mozilla_SplayTree_h_ +#ifndef mozilla_SplayTree_h +#define mozilla_SplayTree_h #include "mozilla/Assertions.h" #include "mozilla/NullPtr.h" @@ -282,4 +281,4 @@ class SplayTree } /* namespace mozilla */ -#endif /* mozilla_SplayTree_h_ */ +#endif /* mozilla_SplayTree_h */ diff --git a/external/spidermonkey/include/android/mozilla/StandardInteger.h b/external/spidermonkey/include/android/mozilla/StandardInteger.h deleted file mode 100644 index 8e4c8578f1..0000000000 --- a/external/spidermonkey/include/android/mozilla/StandardInteger.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface for C and C++ code. */ - -#ifndef mozilla_StandardInteger_h_ -#define mozilla_StandardInteger_h_ - -/* - * The C99 standard header exposes typedefs for common fixed-width - * integer types. It would be feasible to simply #include , but - * MSVC++ versions prior to 2010 don't provide . We could solve this - * by reimplementing for MSVC++ 2008 and earlier. But then we reach - * a second problem: our custom might conflict with a - * defined by an embedder already looking to work around the MSVC++ - * absence. - * - * We address these issues in this manner: - * - * 1. If the preprocessor macro MOZ_CUSTOM_STDINT_H is defined to a path to a - * custom implementation, we will #include it. Embedders using - * a custom must define this macro to an implementation that - * will work with their embedding. - * 2. Otherwise, if we are compiling with a an MSVC++ version without - * , #include our custom reimplementation. - * 3. Otherwise, #include the standard provided by the compiler. - * - * Note that we can't call this file "stdint.h" or something case-insensitively - * equal to "stdint.h" because then MSVC (and other compilers on - * case-insensitive file systems) will include this file, rather than the system - * stdint.h, when we ask for below. - */ -#if defined(MOZ_CUSTOM_STDINT_H) -# include MOZ_CUSTOM_STDINT_H -#elif defined(_MSC_VER) && _MSC_VER < 1600 -# include "mozilla/MSStdInt.h" -#else -# include -#endif - -#endif /* mozilla_StandardInteger_h_ */ diff --git a/external/spidermonkey/include/android/mozilla/TemplateLib.h b/external/spidermonkey/include/android/mozilla/TemplateLib.h new file mode 100644 index 0000000000..50275fdadb --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/TemplateLib.h @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Reusable template meta-functions on types and compile-time values. Meta- + * functions are placed inside the 'tl' namespace to avoid conflict with non- + * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. + * mozilla::FloorLog2). + * + * When constexpr support becomes universal, we should probably use that instead + * of some of these templates, for simplicity. + */ + +#ifndef mozilla_TemplateLib_h +#define mozilla_TemplateLib_h + +#include +#include + +namespace mozilla { + +namespace tl { + +/** Compute min/max. */ +template +struct Min +{ + static const size_t value = I < J ? I : J; +}; +template +struct Max +{ + static const size_t value = I > J ? I : J; +}; + +/** Compute floor(log2(i)). */ +template +struct FloorLog2 +{ + static const size_t value = 1 + FloorLog2::value; +}; +template<> struct FloorLog2<0> { /* Error */ }; +template<> struct FloorLog2<1> { static const size_t value = 0; }; + +/** Compute ceiling(log2(i)). */ +template +struct CeilingLog2 +{ + static const size_t value = FloorLog2<2 * I - 1>::value; +}; + +/** Round up to the nearest power of 2. */ +template +struct RoundUpPow2 +{ + static const size_t value = size_t(1) << CeilingLog2::value; +}; +template<> +struct RoundUpPow2<0> +{ + static const size_t value = 1; +}; + +/** Compute the number of bits in the given unsigned type. */ +template +struct BitSize +{ + static const size_t value = sizeof(T) * CHAR_BIT; +}; + +/** + * Produce an N-bit mask, where N <= BitSize::value. Handle the + * language-undefined edge case when N = BitSize::value. + */ +template +struct NBitMask +{ + // Assert the precondition. On success this evaluates to 0. Otherwise it + // triggers divide-by-zero at compile time: a guaranteed compile error in + // C++11, and usually one in C++98. Add this value to |value| to assure + // its computation. + static const size_t checkPrecondition = 0 / size_t(N < BitSize::value); + static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; +}; +template<> +struct NBitMask::value> +{ + static const size_t value = size_t(-1); +}; + +/** + * For the unsigned integral type size_t, compute a mask M for N such that + * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) + */ +template +struct MulOverflowMask +{ + static const size_t value = + ~NBitMask::value - CeilingLog2::value>::value; +}; +template<> struct MulOverflowMask<0> { /* Error */ }; +template<> struct MulOverflowMask<1> { static const size_t value = 0; }; + +} // namespace tl + +} // namespace mozilla + +#endif /* mozilla_TemplateLib_h */ diff --git a/external/spidermonkey/include/android/mozilla/ThreadLocal.h b/external/spidermonkey/include/android/mozilla/ThreadLocal.h index 2b4eb30207..6df109821f 100644 --- a/external/spidermonkey/include/android/mozilla/ThreadLocal.h +++ b/external/spidermonkey/include/android/mozilla/ThreadLocal.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cross-platform lightweight thread local data wrappers. */ -#ifndef mozilla_ThreadLocal_h_ -#define mozilla_ThreadLocal_h_ +#ifndef mozilla_ThreadLocal_h +#define mozilla_ThreadLocal_h #if defined(XP_WIN) // This file will get included in any file that wants to add a profiler mark. @@ -28,6 +29,7 @@ __declspec(dllimport) unsigned long __stdcall TlsAlloc(); #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -98,15 +100,15 @@ template inline bool ThreadLocal::init() { - MOZ_STATIC_ASSERT(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); + static_assert(sizeof(T) <= sizeof(void*), + "mozilla::ThreadLocal can't be used for types larger than " + "a pointer"); MOZ_ASSERT(!initialized()); #ifdef XP_WIN key = TlsAlloc(); inited = key != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES #else - inited = !pthread_key_create(&key, NULL); + inited = !pthread_key_create(&key, nullptr); #endif return inited; } @@ -144,4 +146,4 @@ ThreadLocal::set(const T value) } // namespace mozilla -#endif // mozilla_ThreadLocal_h_ +#endif /* mozilla_ThreadLocal_h */ diff --git a/external/spidermonkey/include/android/mozilla/TypeTraits.h b/external/spidermonkey/include/android/mozilla/TypeTraits.h index 656bc775f8..53c0b5c2f6 100644 --- a/external/spidermonkey/include/android/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/android/mozilla/TypeTraits.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Template-based metaprogramming and type-testing facilities. */ -#ifndef mozilla_TypeTraits_h_ -#define mozilla_TypeTraits_h_ +#ifndef mozilla_TypeTraits_h +#define mozilla_TypeTraits_h /* * These traits are approximate copies of the traits and semantics from C++11's @@ -126,6 +127,28 @@ struct IsPointer : FalseType {}; template struct IsPointer : TrueType {}; +namespace detail { + +// __is_enum is a supported extension across all of our supported compilers. +template +struct IsEnumHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsEnum determines whether a type is an enum type. + * + * mozilla::IsEnum::value is true; + * mozilla::IsEnum::value is false; + * mozilla::IsEnum::value is false; + */ +template +struct IsEnum + : detail::IsEnumHelper::Type> +{}; + /* 20.9.4.2 Composite type traits [meta.unary.comp] */ /** @@ -197,8 +220,24 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template struct IsPod : TrueType {}; +namespace detail { + +template::value> +struct IsSignedHelper; + +template +struct IsSignedHelper : TrueType {}; + +template +struct IsSignedHelper + : IntegralConstant::value && T(-1) < T(1)> +{}; + +} // namespace detail + /** - * IsSigned determines whether a type is a signed arithmetic type. + * IsSigned determines whether a type is a signed arithmetic type. |char| is + * considered a signed type if it has the same representation as |signed char|. * * Don't use this if the type might be user-defined! You might or might not get * a compile error, depending. @@ -209,10 +248,26 @@ template struct IsPod : TrueType {}; * mozilla::IsSigned::value is true. */ template -struct IsSigned - : IntegralConstant::value && T(-1) < T(0)> +struct IsSigned : detail::IsSignedHelper {}; + +namespace detail { + +template::value> +struct IsUnsignedHelper; + +template +struct IsUnsignedHelper : FalseType {}; + +template +struct IsUnsignedHelper + : IntegralConstant::value && + (IsSame::Type, bool>::value || + T(1) < T(-1))> {}; +} // namespace detail + /** * IsUnsigned determines whether a type is an unsigned arithmetic type. * @@ -225,9 +280,7 @@ struct IsSigned * mozilla::IsUnsigned::value is false. */ template -struct IsUnsigned - : IntegralConstant::value && T(0) < T(-1)> -{}; +struct IsUnsigned : detail::IsUnsignedHelper {}; /* 20.9.5 Type property queries [meta.unary.prop.query] */ @@ -427,6 +480,160 @@ struct RemoveCV /* 20.9.7.3 Sign modifications [meta.trans.sign] */ +template +struct EnableIf; + +template +struct Conditional; + +namespace detail { + +template +struct WithC : Conditional +{}; + +template +struct WithV : Conditional +{}; + + +template +struct WithCV : WithC::Type> +{}; + +template +struct CorrespondingSigned; + +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef short Type; }; +template<> +struct CorrespondingSigned { typedef int Type; }; +template<> +struct CorrespondingSigned { typedef long Type; }; +template<> +struct CorrespondingSigned { typedef long long Type; }; + +template::Type, + bool IsSignedIntegerType = IsSigned::value && + !IsSame::value> +struct MakeSigned; + +template +struct MakeSigned +{ + typedef T Type; +}; + +template +struct MakeSigned + : WithCV::value, IsVolatile::value, + typename CorrespondingSigned::Type> +{}; + +} // namespace detail + +/** + * MakeSigned produces the corresponding signed integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already a signed integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an unsigned integer type, the signed variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the integral type of the same size as T, with the lowest rank, + * with T's const/volatile qualifiers, is produced. (This basically only acts + * to produce signed char when T = char.) + * + * mozilla::MakeSigned::Type is signed long; + * mozilla::MakeSigned::Type is volatile int; + * mozilla::MakeSigned::Type is const signed short; + * mozilla::MakeSigned::Type is const signed char; + * mozilla::MakeSigned is an error; + * mozilla::MakeSigned is an error. + */ +template +struct MakeSigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeSigned + >::Type +{}; + +namespace detail { + +template +struct CorrespondingUnsigned; + +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned short Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned int Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long long Type; }; + + +template::Type, + bool IsUnsignedIntegerType = IsUnsigned::value && + !IsSame::value> +struct MakeUnsigned; + +template +struct MakeUnsigned +{ + typedef T Type; +}; + +template +struct MakeUnsigned + : WithCV::value, IsVolatile::value, + typename CorrespondingUnsigned::Type> +{}; + +} // namespace detail + +/** + * MakeUnsigned produces the corresponding unsigned integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already an unsigned integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an signed integer type, the unsigned variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the unsigned integral type of the same size as T, with the lowest + * rank, with T's const/volatile qualifiers, is produced. (This basically only + * acts to produce unsigned char when T = char.) + * + * mozilla::MakeUnsigned::Type is unsigned long; + * mozilla::MakeUnsigned::Type is volatile unsigned int; + * mozilla::MakeUnsigned::Type is const unsigned short; + * mozilla::MakeUnsigned::Type is const unsigned char; + * mozilla::MakeUnsigned is an error; + * mozilla::MakeUnsigned is an error. + */ +template +struct MakeUnsigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeUnsigned + >::Type +{}; + /* 20.9.7.4 Array modifications [meta.trans.arr] */ /* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ @@ -451,7 +658,7 @@ struct RemoveCV * ... * }; */ -template +template struct EnableIf {}; @@ -481,4 +688,4 @@ struct Conditional } /* namespace mozilla */ -#endif /* mozilla_TypeTraits_h_ */ +#endif /* mozilla_TypeTraits_h */ diff --git a/external/spidermonkey/include/android/mozilla/TypedEnum.h b/external/spidermonkey/include/android/mozilla/TypedEnum.h index 889960a32d..6f595cb4c5 100644 --- a/external/spidermonkey/include/android/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/android/mozilla/TypedEnum.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Macros to emulate C++11 typed enums and enum classes. */ -#ifndef mozilla_TypedEnum_h_ -#define mozilla_TypedEnum_h_ +#ifndef mozilla_TypedEnum_h +#define mozilla_TypedEnum_h #include "mozilla/Attributes.h" @@ -91,16 +92,33 @@ * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do * not support it. * - * Note that the workaround implemented here is not compatible with enums - * nested inside a class. + * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested + * inside classes. To define an enum class nested inside another class, use + * MOZ_{BEGIN,END}_NESTED_ENUM_CLASS, and place a MOZ_FINISH_NESTED_ENUM_CLASS + * in namespace scope to handle bits that can only be implemented with + * namespace-scoped code. For example: + * + * class FooBar { + * + * MOZ_BEGIN_NESTED_ENUM_CLASS(Enum, int32_t) + * A, + * B = 6 + * MOZ_END_NESTED_ENUM_CLASS(Enum) + * + * }; + * + * MOZ_FINISH_NESTED_ENUM_CLASS(FooBar::Enum) */ #if defined(MOZ_HAVE_CXX11_STRONG_ENUMS) /* * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) enum class Name : type { -# define MOZ_END_ENUM_CLASS(Name) }; +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + enum class Name : type { +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) /* nothing */ #else /** * We need Name to both name a type, and scope the provided enumerator @@ -136,14 +154,14 @@ * { * return Enum::A; * } - */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) \ + */\ +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ class Name \ { \ public: \ enum Enum MOZ_ENUM_TYPE(type) \ { -# define MOZ_END_ENUM_CLASS(Name) \ +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; \ Name() {} \ Name(Enum aEnum) : mEnum(aEnum) {} \ @@ -151,7 +169,8 @@ operator Enum() const { return mEnum; } \ private: \ Enum mEnum; \ - }; \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) \ inline int operator+(const int&, const Name::Enum&) MOZ_DELETE; \ inline int operator+(const Name::Enum&, const int&) MOZ_DELETE; \ inline int operator-(const int&, const Name::Enum&) MOZ_DELETE; \ @@ -207,7 +226,11 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif +# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) +# define MOZ_END_ENUM_CLASS(Name) \ + MOZ_END_NESTED_ENUM_CLASS(Name) \ + MOZ_FINISH_NESTED_ENUM_CLASS(Name) #endif /* __cplusplus */ -#endif /* mozilla_TypedEnum_h_ */ +#endif /* mozilla_TypedEnum_h */ diff --git a/external/spidermonkey/include/android/mozilla/Types.h b/external/spidermonkey/include/android/mozilla/Types.h index 56e5cb82fb..5340b2b600 100644 --- a/external/spidermonkey/include/android/mozilla/Types.h +++ b/external/spidermonkey/include/android/mozilla/Types.h @@ -1,28 +1,22 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt foundational types and macros. */ -#ifndef mozilla_Types_h_ -#define mozilla_Types_h_ +#ifndef mozilla_Types_h +#define mozilla_Types_h /* * This header must be valid C and C++, includable by code embedding either * SpiderMonkey or Gecko. */ -/* - * Expose all the integer types defined in C99's (and the integer - * limit and constant macros, if compiling C code or if compiling C++ code and - * the right __STDC_*_MACRO has been defined for each). These are all usable - * throughout mfbt code, and throughout Mozilla code more generally. - */ -#include "mozilla/StandardInteger.h" - -/* Also expose size_t. */ +/* Expose all types and size_t. */ #include +#include /* Implement compiler and linker macros needed for APIs. */ @@ -133,4 +127,12 @@ # define MOZ_END_EXTERN_C #endif -#endif /* mozilla_Types_h_ */ +/* + * GCC's typeof is available when decltype is not. + */ +#if defined(__GNUC__) && defined(__cplusplus) && \ + !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +# define decltype __typeof__ +#endif + +#endif /* mozilla_Types_h */ diff --git a/external/spidermonkey/include/android/mozilla/Util.h b/external/spidermonkey/include/android/mozilla/Util.h index 097c5478eb..4f1c634a59 100644 --- a/external/spidermonkey/include/android/mozilla/Util.h +++ b/external/spidermonkey/include/android/mozilla/Util.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * new headers, or to other appropriate existing headers, not here. */ -#ifndef mozilla_Util_h_ -#define mozilla_Util_h_ +#ifndef mozilla_Util_h +#define mozilla_Util_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -196,6 +197,58 @@ class Maybe constructed = true; } + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + T* addr() { MOZ_ASSERT(constructed); return &asT(); @@ -271,7 +324,7 @@ ArrayEnd(T (&arr)[N]) /* * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for MOZ_STATIC_ASSERT() calls that + * that can't use C++ template functions and for static_assert() calls that * can't call ArrayLength() when it is not a C++11 constexpr function. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR @@ -280,4 +333,4 @@ ArrayEnd(T (&arr)[N]) # define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) #endif -#endif /* mozilla_Util_h_ */ +#endif /* mozilla_Util_h */ diff --git a/external/spidermonkey/include/android/mozilla/Vector.h b/external/spidermonkey/include/android/mozilla/Vector.h new file mode 100644 index 0000000000..8759df8c06 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Vector.h @@ -0,0 +1,1190 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A type/length-parametrized vector class. */ + +#ifndef mozilla_Vector_h +#define mozilla_Vector_h + +#include "mozilla/AllocPolicy.h" +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/MathAlgorithms.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" +#include "mozilla/NullPtr.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" +#include "mozilla/TypeTraits.h" +#include "mozilla/Util.h" + +#include // for placement new + +/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4345) +#endif + +namespace mozilla { + +template +class VectorBase; + +namespace detail { + +/* + * Check that the given capacity wastes the minimal amount of space if + * allocated on the heap. This means that cap*sizeof(T) is as close to a + * power-of-two as possible. growStorageBy() is responsible for ensuring + * this. + */ +template +static bool CapacityHasExcessSpace(size_t cap) +{ + size_t size = cap * sizeof(T); + return RoundUpPow2(size) - size >= sizeof(T); +} + +/* + * This template class provides a default implementation for vector operations + * when the element type is not known to be a POD, as judged by IsPod. + */ +template +struct VectorImpl +{ + /* Destroys constructed objects in the range [begin, end). */ + static inline void destroy(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + p->~T(); + } + + /* Constructs objects in the uninitialized range [begin, end). */ + static inline void initialize(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + /* + * Copy-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(*p); + } + + /* + * Move-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(Move(*p)); + } + + /* + * Copy-constructs objects in the uninitialized range [dst, dst+n) from the + * same object u. + */ + template + static inline void copyConstructN(T* dst, size_t n, const U& u) { + for (T* end = dst + n; dst < end; ++dst) + new(dst) T(u); + } + + /* + * Grows the given buffer to have capacity newCap, preserving the objects + * constructed in the range [begin, end) and updating v. Assumes that (1) + * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will + * not overflow. + */ + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + T* newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); + if (!newbuf) + return false; + T* dst = newbuf; + T* src = v.beginNoCheck(); + for (; src < v.endNoCheck(); ++dst, ++src) + new(dst) T(Move(*src)); + VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); + v.free_(v.mBegin); + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +/* + * This partial template specialization provides a default implementation for + * vector operations when the element type is known to be a POD, as judged by + * IsPod. + */ +template +struct VectorImpl +{ + static inline void destroy(T*, T*) {} + + static inline void initialize(T* begin, T* end) { + /* + * You would think that memset would be a big win (or even break even) + * when we know T is a POD. But currently it's not. This is probably + * because |append| tends to be given small ranges and memset requires + * a function call that doesn't get inlined. + * + * memset(begin, 0, sizeof(T) * (end-begin)); + */ + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + /* + * See above memset comment. Also, notice that copyConstruct is + * currently templated (T != U), so memcpy won't work without + * requiring T == U. + * + * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); + */ + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + *dst = *p; + } + + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + copyConstruct(dst, srcbeg, srcend); + } + + static inline void copyConstructN(T* dst, size_t n, const T& t) { + for (T* end = dst + n; dst < end; ++dst) + *dst = t; + } + + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + size_t oldSize = sizeof(T) * v.mCapacity; + size_t newSize = sizeof(T) * newCap; + T* newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); + if (!newbuf) + return false; + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +} // namespace detail + +/* + * A CRTP base class for vector-like classes. Unless you really really want + * your own vector class -- and you almost certainly don't -- you should use + * mozilla::Vector instead! + * + * See mozilla::Vector for interface requirements. + */ +template +class VectorBase : private AllocPolicy +{ + /* utilities */ + + static const bool sElemIsPod = IsPod::value; + typedef detail::VectorImpl Impl; + friend struct detail::VectorImpl; + + bool growStorageBy(size_t incr); + bool convertToHeapStorage(size_t newCap); + + /* magic constants */ + + static const int sMaxInlineBytes = 1024; + + /* compute constants */ + + /* + * Consider element size to be 1 for buffer sizing if there are 0 inline + * elements. This allows us to compile when the definition of the element + * type is not visible here. + * + * Explicit specialization is only allowed at namespace scope, so in order + * to keep everything here, we use a dummy template parameter with partial + * specialization. + */ + template + struct ElemSize + { + static const size_t value = sizeof(T); + }; + template + struct ElemSize<0, Dummy> + { + static const size_t value = 1; + }; + + static const size_t sInlineCapacity = + tl::Min::value>::value; + + /* Calculate inline buffer size; avoid 0-sized array. */ + static const size_t sInlineBytes = + tl::Max<1, sInlineCapacity * ElemSize::value>::value; + + /* member data */ + + /* + * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, + * mBegin + mLength) hold valid constructed T objects. The range [mBegin + + * mLength, mBegin + mCapacity) holds uninitialized memory. The range + * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory + * previously allocated by a call to reserve(). + */ + T* mBegin; + + /* Number of elements in the vector. */ + size_t mLength; + + /* Max number of elements storable in the vector without resizing. */ + size_t mCapacity; + +#ifdef DEBUG + /* Max elements of reserved or used space in this vector. */ + size_t mReserved; +#endif + + /* Memory used for inline storage. */ + AlignedStorage storage; + +#ifdef DEBUG + friend class ReentrancyGuard; + bool entered; +#endif + + /* private accessors */ + + bool usingInlineStorage() const { + return mBegin == const_cast(this)->inlineStorage(); + } + + T* inlineStorage() { + return static_cast(storage.addr()); + } + + T* beginNoCheck() const { + return mBegin; + } + + T* endNoCheck() { + return mBegin + mLength; + } + + const T* endNoCheck() const { + return mBegin + mLength; + } + +#ifdef DEBUG + size_t reserved() const { + MOZ_ASSERT(mReserved <= mCapacity); + MOZ_ASSERT(mLength <= mReserved); + return mReserved; + } +#endif + + /* Append operations guaranteed to succeed due to pre-reserved space. */ + template void internalAppend(const U& u); + template + void internalAppendAll(const VectorBase& u); + void internalAppendN(const T& t, size_t n); + template void internalAppend(const U* begin, size_t length); + + public: + static const size_t sMaxInlineStorage = N; + + typedef T ElementType; + + VectorBase(AllocPolicy = AllocPolicy()); + VectorBase(MoveRef); /* Move constructor. */ + ThisVector& operator=(MoveRef); /* Move assignment. */ + ~VectorBase(); + + /* accessors */ + + const AllocPolicy& allocPolicy() const { + return *this; + } + + AllocPolicy& allocPolicy() { + return *this; + } + + enum { InlineLength = N }; + + size_t length() const { + return mLength; + } + + bool empty() const { + return mLength == 0; + } + + size_t capacity() const { + return mCapacity; + } + + T* begin() { + MOZ_ASSERT(!entered); + return mBegin; + } + + const T* begin() const { + MOZ_ASSERT(!entered); + return mBegin; + } + + T* end() { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + const T* end() const { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + T& operator[](size_t i) { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + T& back() { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + const T& back() const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + class Range + { + friend class VectorBase; + T* cur_; + T* end_; + Range(T* cur, T* end) : cur_(cur), end_(end) {} + + public: + Range() {} + bool empty() const { return cur_ == end_; } + size_t remain() const { return end_ - cur_; } + T& front() const { return *cur_; } + void popFront() { MOZ_ASSERT(!empty()); ++cur_; } + T popCopyFront() { MOZ_ASSERT(!empty()); return *cur_++; } + }; + + Range all() { + return Range(begin(), end()); + } + + /* mutators */ + + /** + * Given that the vector is empty and has no inline storage, grow to + * |capacity|. + */ + bool initCapacity(size_t request); + + /** + * If reserve(length() + N) succeeds, the N next appends are guaranteed to + * succeed. + */ + bool reserve(size_t request); + + /** + * Destroy elements in the range [end() - incr, end()). Does not deallocate + * or unreserve storage for those elements. + */ + void shrinkBy(size_t incr); + + /** Grow the vector by incr elements. */ + bool growBy(size_t incr); + + /** Call shrinkBy or growBy based on whether newSize > length(). */ + bool resize(size_t newLength); + + /** + * Increase the length of the vector, but don't initialize the new elements + * -- leave them as uninitialized memory. + */ + bool growByUninitialized(size_t incr); + bool resizeUninitialized(size_t newLength); + + /** Shorthand for shrinkBy(length()). */ + void clear(); + + /** Clears and releases any heap-allocated storage. */ + void clearAndFree(); + + /** + * If true, appending |needed| elements won't reallocate elements storage. + * This *doesn't* mean that infallibleAppend may be used! You still must + * reserve the extra space, even if this method indicates that appends won't + * need to reallocate elements storage. + */ + bool canAppendWithoutRealloc(size_t needed) const; + + /** + * Potentially fallible append operations. + * + * The function templates that take an unspecified type U require a const T& + * or a MoveRef. The MoveRef variants move their operands into the + * vector, instead of copying them. If they fail, the operand is left + * unmoved. + */ + template bool append(const U& u); + template + bool appendAll(const VectorBase& u); + bool appendN(const T& t, size_t n); + template bool append(const U* begin, const U* end); + template bool append(const U* begin, size_t length); + + /* + * Guaranteed-infallible append operations for use upon vectors whose + * memory has been pre-reserved. Don't use this if you haven't reserved the + * memory! + */ + template void infallibleAppend(const U& u) { + internalAppend(u); + } + void infallibleAppendN(const T& t, size_t n) { + internalAppendN(t, n); + } + template void infallibleAppend(const U* aBegin, const U* aEnd) { + internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); + } + template void infallibleAppend(const U* aBegin, size_t aLength) { + internalAppend(aBegin, aLength); + } + + void popBack(); + + T popCopy(); + + /** + * Transfers ownership of the internal buffer used by this vector to the + * caller. (It's the caller's responsibility to properly deallocate this + * buffer, in accordance with this vector's AllocPolicy.) After this call, + * the vector is empty. Since the returned buffer may need to be allocated + * (if the elements are currently stored in-place), the call can fail, + * returning nullptr. + * + * N.B. Although a T*, only the range [0, length()) is constructed. + */ + T* extractRawBuffer(); + + /** + * Transfer ownership of an array of objects into the vector. The caller + * must have allocated the array in accordance with this vector's + * AllocPolicy. + * + * N.B. This call assumes that there are no uninitialized elements in the + * passed array. + */ + void replaceRawBuffer(T* p, size_t length); + + /** + * Places |val| at position |p|, shifting existing elements from |p| onward + * one position higher. On success, |p| should not be reused because it'll + * be a dangling pointer if reallocation of the vector storage occurred; the + * return value should be used instead. On failure, nullptr is returned. + * + * Example usage: + * + * if (!(p = vec.insert(p, val))) + * + * + * + * This is inherently a linear-time operation. Be careful! + */ + T* insert(T* p, const T& val); + + /** + * Removes the element |t|, which must fall in the bounds [begin, end), + * shifting existing elements from |t + 1| onward one position lower. + */ + void erase(T* t); + + /** + * Measure the size of the vector's heap-allocated storage. + */ + size_t sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const; + + /** + * Like sizeOfExcludingThis, but also measures the size of the vector + * object (which must be heap-allocated) itself. + */ + size_t sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const; + + void swap(ThisVector& other); + + private: + VectorBase(const ThisVector&) MOZ_DELETE; + void operator=(const ThisVector&) MOZ_DELETE; +}; + +/* This does the re-entrancy check plus several other sanity checks. */ +#define MOZ_REENTRANCY_GUARD_ET_AL \ + ReentrancyGuard g(*this); \ + MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ + MOZ_ASSERT(reserved() <= mCapacity); \ + MOZ_ASSERT(mLength <= reserved()); \ + MOZ_ASSERT(mLength <= mCapacity) + +/* Vector Implementation */ + +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(AP ap) + : AP(ap), + mBegin(static_cast(storage.addr())), + mLength(0), + mCapacity(sInlineCapacity) +#ifdef DEBUG + , mReserved(sInlineCapacity), + entered(false) +#endif +{} + +/* Move constructor. */ +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(MoveRef rhs) + : AllocPolicy(rhs) +#ifdef DEBUG + , entered(false) +#endif +{ + mLength = rhs->mLength; + mCapacity = rhs->mCapacity; +#ifdef DEBUG + mReserved = rhs->mReserved; +#endif + + if (rhs->usingInlineStorage()) { + /* We can't move the buffer over in this case, so copy elements. */ + mBegin = static_cast(storage.addr()); + Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); + /* + * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. + * The elements in its in-line storage still need to be destroyed. + */ + } else { + /* + * Take src's buffer, and turn src into an empty vector using + * in-line storage. + */ + mBegin = rhs->mBegin; + rhs->mBegin = static_cast(rhs->storage.addr()); + rhs->mCapacity = sInlineCapacity; + rhs->mLength = 0; +#ifdef DEBUG + rhs->mReserved = sInlineCapacity; +#endif + } +} + +/* Move assignment. */ +template +MOZ_ALWAYS_INLINE +TV& +VectorBase::operator=(MoveRef rhs) +{ + TV* tv = static_cast(this); + tv->~TV(); + new(tv) TV(rhs); + return *tv; +} + +template +MOZ_ALWAYS_INLINE +VectorBase::~VectorBase() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); +} + +/* + * This function will create a new heap buffer with capacity newCap, + * move all elements in the inline buffer to this new buffer, + * and fail on OOM. + */ +template +inline bool +VectorBase::convertToHeapStorage(size_t newCap) +{ + MOZ_ASSERT(usingInlineStorage()); + + /* Allocate buffer. */ + MOZ_ASSERT(!detail::CapacityHasExcessSpace(newCap)); + T* newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); + if (!newBuf) + return false; + + /* Copy inline elements into heap buffer. */ + Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + + /* Switch in heap buffer. */ + mBegin = newBuf; + /* mLength is unchanged. */ + mCapacity = newCap; + return true; +} + +template +MOZ_NEVER_INLINE bool +VectorBase::growStorageBy(size_t incr) +{ + MOZ_ASSERT(mLength + incr > mCapacity); + MOZ_ASSERT_IF(!usingInlineStorage(), + !detail::CapacityHasExcessSpace(mCapacity)); + + /* + * When choosing a new capacity, its size should is as close to 2**N bytes + * as possible. 2**N-sized requests are best because they are unlikely to + * be rounded up by the allocator. Asking for a 2**N number of elements + * isn't as good, because if sizeof(T) is not a power-of-two that would + * result in a non-2**N request size. + */ + + size_t newCap; + + if (incr == 1) { + if (usingInlineStorage()) { + /* This case occurs in ~70--80% of the calls to this function. */ + size_t newSize = + tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::value; + newCap = newSize / sizeof(T); + goto convert; + } + + if (mLength == 0) { + /* This case occurs in ~0--10% of the calls to this function. */ + newCap = 1; + goto grow; + } + + /* This case occurs in ~15--20% of the calls to this function. */ + + /* + * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector + * to 1GB of memory on a 32-bit system, which is a reasonable limit. It + * also ensures that + * + * static_cast(end()) - static_cast(begin()) + * + * doesn't overflow ptrdiff_t (see bug 510319). + */ + if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::value) { + this->reportAllocOverflow(); + return false; + } + + /* + * If we reach here, the existing capacity will have a size that is already + * as close to 2^N as sizeof(T) will allow. Just double the capacity, and + * then there might be space for one more element. + */ + newCap = mLength * 2; + if (detail::CapacityHasExcessSpace(newCap)) + newCap += 1; + } else { + /* This case occurs in ~2% of the calls to this function. */ + size_t newMinCap = mLength + incr; + + /* Did mLength + incr overflow? Will newCap * sizeof(T) overflow? */ + if (newMinCap < mLength || + newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value) + { + this->reportAllocOverflow(); + return false; + } + + size_t newMinSize = newMinCap * sizeof(T); + size_t newSize = RoundUpPow2(newMinSize); + newCap = newSize / sizeof(T); + } + + if (usingInlineStorage()) { + convert: + return convertToHeapStorage(newCap); + } + +grow: + return Impl::growTo(*this, newCap); +} + +template +inline bool +VectorBase::initCapacity(size_t request) +{ + MOZ_ASSERT(empty()); + MOZ_ASSERT(usingInlineStorage()); + if (request == 0) + return true; + T* newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); + if (!newbuf) + return false; + mBegin = newbuf; + mCapacity = request; +#ifdef DEBUG + mReserved = request; +#endif + return true; +} + +template +inline bool +VectorBase::reserve(size_t request) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (request > mCapacity && !growStorageBy(request - mLength)) + return false; + +#ifdef DEBUG + if (request > mReserved) + mReserved = request; + MOZ_ASSERT(mLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); +#endif + return true; +} + +template +inline void +VectorBase::shrinkBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(incr <= mLength); + Impl::destroy(endNoCheck() - incr, endNoCheck()); + mLength -= incr; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + T* newend = endNoCheck() + incr; + Impl::initialize(endNoCheck(), newend); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growByUninitialized(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +inline bool +VectorBase::resize(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growBy(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::resizeUninitialized(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growByUninitialized(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +inline void +VectorBase::clear() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + mLength = 0; +} + +template +inline void +VectorBase::clearAndFree() +{ + clear(); + + if (usingInlineStorage()) + return; + + this->free_(beginNoCheck()); + mBegin = static_cast(storage.addr()); + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif +} + +template +inline bool +VectorBase::canAppendWithoutRealloc(size_t needed) const +{ + return mLength + needed <= mCapacity; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendAll(const VectorBase& other) +{ + internalAppend(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U& u) +{ + MOZ_ASSERT(mLength + 1 <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + new(endNoCheck()) T(u); + ++mLength; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendN(const T& t, size_t needed) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppendN(t, needed); + return true; +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendN(const T& t, size_t needed) +{ + MOZ_ASSERT(mLength + needed <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstructN(endNoCheck(), needed, t); + mLength += needed; +} + +template +inline T* +VectorBase::insert(T* p, const T& val) +{ + MOZ_ASSERT(begin() <= p); + MOZ_ASSERT(p <= end()); + size_t pos = p - begin(); + MOZ_ASSERT(pos <= mLength); + size_t oldLength = mLength; + if (pos == oldLength) { + if (!append(val)) + return nullptr; + } else { + T oldBack = back(); + if (!append(oldBack)) /* Dup the last element. */ + return nullptr; + for (size_t i = oldLength; i > pos; --i) + (*this)[i] = (*this)[i - 1]; + (*this)[pos] = val; + } + return begin() + pos; +} + +template +inline void +VectorBase::erase(T* it) +{ + MOZ_ASSERT(begin() <= it); + MOZ_ASSERT(it < end()); + while (it + 1 < end()) { + *it = *(it + 1); + ++it; + } + popBack(); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U* insBegin, const U* insEnd) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + size_t needed = PointerRangeSize(insBegin, insEnd); + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppend(insBegin, needed); + return true; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U* insBegin, size_t insLength) +{ + MOZ_ASSERT(mLength + insLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); + mLength += insLength; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U& u) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength == mCapacity && !growStorageBy(1)) + return false; + +#ifdef DEBUG + if (mLength + 1 > mReserved) + mReserved = mLength + 1; +#endif + internalAppend(u); + return true; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendAll(const VectorBase& other) +{ + return append(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U *insBegin, size_t insLength) +{ + return append(insBegin, insBegin + insLength); +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::popBack() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(!empty()); + --mLength; + endNoCheck()->~T(); +} + +template +MOZ_ALWAYS_INLINE T +VectorBase::popCopy() +{ + T ret = back(); + popBack(); + return ret; +} + +template +inline T* +VectorBase::extractRawBuffer() +{ + T* ret; + if (usingInlineStorage()) { + ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); + if (!ret) + return nullptr; + Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + /* mBegin, mCapacity are unchanged. */ + mLength = 0; + } else { + ret = mBegin; + mBegin = static_cast(storage.addr()); + mLength = 0; + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif + } + return ret; +} + +template +inline void +VectorBase::replaceRawBuffer(T* p, size_t aLength) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + + /* Destroy what we have. */ + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); + + /* Take in the new buffer. */ + if (aLength <= sInlineCapacity) { + /* + * We convert to inline storage if possible, even though p might + * otherwise be acceptable. Maybe this behaviour should be + * specifiable with an argument to this function. + */ + mBegin = static_cast(storage.addr()); + mLength = aLength; + mCapacity = sInlineCapacity; + Impl::moveConstruct(mBegin, p, p + aLength); + Impl::destroy(p, p + aLength); + this->free_(p); + } else { + mBegin = p; + mLength = aLength; + mCapacity = aLength; + } +#ifdef DEBUG + mReserved = aLength; +#endif +} + +template +inline size_t +VectorBase::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const +{ + return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); +} + +template +inline size_t +VectorBase::sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const +{ + return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); +} + +template +inline void +VectorBase::swap(TV& other) +{ + static_assert(N == 0, + "still need to implement this for N != 0"); + + // This only works when inline storage is always empty. + if (!usingInlineStorage() && other.usingInlineStorage()) { + other.mBegin = mBegin; + mBegin = inlineStorage(); + } else if (usingInlineStorage() && !other.usingInlineStorage()) { + mBegin = other.mBegin; + other.mBegin = other.inlineStorage(); + } else if (!usingInlineStorage() && !other.usingInlineStorage()) { + Swap(mBegin, other.mBegin); + } else { + // This case is a no-op, since we'd set both to use their inline storage. + } + + Swap(mLength, other.mLength); + Swap(mCapacity, other.mCapacity); +#ifdef DEBUG + Swap(mReserved, other.mReserved); +#endif +} + +/* + * STL-like container providing a short-lived, dynamic buffer. Vector calls the + * constructors/destructors of all elements stored in its internal buffer, so + * non-PODs may be safely used. Additionally, Vector will store the first N + * elements in-place before resorting to dynamic allocation. + * + * T requirements: + * - default and copy constructible, assignable, destructible + * - operations do not throw + * N requirements: + * - any value, however, N is clamped to min/max values + * AllocPolicy: + * - see "Allocation policies" in AllocPolicy.h (defaults to + * mozilla::MallocAllocPolicy) + * + * Vector is not reentrant: T member functions called during Vector member + * functions must not call back into the same object! + */ +template +class Vector + : public VectorBase > +{ + typedef VectorBase Base; + + public: + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector& operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); + } +}; + +} // namespace mozilla + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif /* mozilla_Vector_h */ diff --git a/external/spidermonkey/include/android/mozilla/WeakPtr.h b/external/spidermonkey/include/android/mozilla/WeakPtr.h index d61b0b37d3..c714ebf565 100644 --- a/external/spidermonkey/include/android/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/android/mozilla/WeakPtr.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Weak pointer functionality, implemented as a mixin for use with any class. */ @@ -13,6 +14,9 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * + * AtomicSupportsWeakPtr can be used for a variant with an atomically updated + * reference counter. + * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -55,10 +59,11 @@ * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h */ -#ifndef mozilla_WeakPtr_h_ -#define mozilla_WeakPtr_h_ +#ifndef mozilla_WeakPtr_h +#define mozilla_WeakPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -71,8 +76,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted > +template +class WeakReference : public RefCounted, Atomicity> { public: explicit WeakReference(T* p) : ptr(p) {} @@ -81,8 +86,8 @@ class WeakReference : public RefCounted > } private: - friend class WeakPtrBase >; - friend class SupportsWeakPtrBase >; + friend class WeakPtrBase; + friend class SupportsWeakPtrBase; void detach() { ptr = nullptr; } @@ -103,8 +108,8 @@ class SupportsWeakPtrBase protected: ~SupportsWeakPtrBase() { - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from SupportsWeakPtrBase"); + static_assert(IsBaseOf, T>::value, + "T must derive from SupportsWeakPtrBase"); if (weakRef) weakRef->detach(); } @@ -116,10 +121,30 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr : public SupportsWeakPtrBase > +class SupportsWeakPtr + : public SupportsWeakPtrBase > { }; +template +class AtomicSupportsWeakPtr + : public SupportsWeakPtrBase > +{ +}; + +namespace detail { + +template +struct WeakReferenceCount +{ + static const RefCountAtomicity atomicity = + IsBaseOf, T>::value + ? AtomicRefCount + : NonAtomicRefCount; +}; + +} + template class WeakPtrBase { @@ -152,9 +177,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase > +class WeakPtr : public WeakPtrBase::atomicity> > { - typedef WeakPtrBase > Base; + typedef WeakPtrBase::atomicity> > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} @@ -163,4 +188,4 @@ class WeakPtr : public WeakPtrBase > } // namespace mozilla -#endif /* ifdef mozilla_WeakPtr_h_ */ +#endif /* mozilla_WeakPtr_h */ diff --git a/external/spidermonkey/include/ios/js-config.h b/external/spidermonkey/include/ios/js-config.h index 7c6c37636a..4b893482f4 100644 --- a/external/spidermonkey/include/ios/js-config.h +++ b/external/spidermonkey/include/ios/js-config.h @@ -38,8 +38,8 @@ JS_HAVE_STDINT_H. */ #define JS_BYTES_PER_WORD 4 -/* Some mozilla code uses JS-friend APIs that depend on JS_METHODJIT being - correct. */ -/* #undef JS_METHODJIT */ +/* MOZILLA JSAPI version number components */ +#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MINOR_VERSION 0 #endif /* js_config_h___ */ diff --git a/external/spidermonkey/include/ios/js.msg b/external/spidermonkey/include/ios/js.msg index 3e57bdf174..3f665d8d54 100644 --- a/external/spidermonkey/include/ios/js.msg +++ b/external/spidermonkey/include/ios/js.msg @@ -184,7 +184,7 @@ MSG_DEF(JSMSG_BAD_OPERAND, 130, 1, JSEXN_SYNTAXERR, "invalid {0} oper MSG_DEF(JSMSG_BAD_PROP_ID, 131, 0, JSEXN_SYNTAXERR, "invalid property id") MSG_DEF(JSMSG_RESERVED_ID, 132, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") MSG_DEF(JSMSG_SYNTAX_ERROR, 133, 0, JSEXN_SYNTAXERR, "syntax error") -MSG_DEF(JSMSG_UNUSED134, 134, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 134, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") MSG_DEF(JSMSG_BAD_PROTOTYPE, 135, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") MSG_DEF(JSMSG_MISSING_EXPONENT, 136, 0, JSEXN_SYNTAXERR, "missing exponent") MSG_DEF(JSMSG_OUT_OF_MEMORY, 137, 0, JSEXN_ERR, "out of memory") @@ -193,10 +193,10 @@ MSG_DEF(JSMSG_TOO_MANY_PARENS, 139, 0, JSEXN_INTERNALERR, "too many paren MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 140, 0, JSEXN_SYNTAXERR, "unterminated comment") MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 141, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 142, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_UNUSED143, 143, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 143, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 144, 0, JSEXN_SYNTAXERR, "illegal character") MSG_DEF(JSMSG_BAD_OCTAL, 145, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_UNUSED146, 146, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 146, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 147, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") MSG_DEF(JSMSG_INVALID_BACKREF, 148, 0, JSEXN_SYNTAXERR, "non-octal digit in an escape sequence that doesn't match a back-reference") MSG_DEF(JSMSG_BAD_BACKREF, 149, 0, JSEXN_SYNTAXERR, "back-reference exceeds number of capturing parentheses") @@ -220,7 +220,7 @@ MSG_DEF(JSMSG_RESERVED_SLOT_RANGE, 166, 0, JSEXN_RANGEERR, "reserved slot ind MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode JSPrincipals") MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_UNUSED170, 170, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") @@ -286,7 +286,7 @@ MSG_DEF(JSMSG_DEPRECATED_OCTAL, 232, 0, JSEXN_SYNTAXERR, "octal literals a MSG_DEF(JSMSG_STRICT_CODE_WITH, 233, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 234, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 235, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "assignment to {0} is deprecated") +MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "can't assign to {0} in strict mode") MSG_DEF(JSMSG_BAD_BINDING, 237, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 238, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 239, 1, JSEXN_TYPEERR, "{0} is not extensible") @@ -313,16 +313,16 @@ MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 259, 0, JSEXN_TYPEERR, "can't change ob MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 260, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 261, 0, JSEXN_TYPEERR, "unsupported type for structured data") MSG_DEF(JSMSG_SC_RECURSION, 262, 0, JSEXN_INTERNALERR, "recursive object") -MSG_DEF(JSMSG_UNUSED263, 263, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 263, 0, JSEXN_ERR, "passing non-debuggable global to addDebuggee") MSG_DEF(JSMSG_BAD_CLONE_VERSION, 264, 0, JSEXN_ERR, "unsupported structured clone version") MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 265, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_UNUSED266, 266, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 266, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") MSG_DEF(JSMSG_STRICT_FUNCTION_STATEMENT, 267, 0, JSEXN_SYNTAXERR, "in strict mode code, functions may be declared only at top level or immediately within another function") MSG_DEF(JSMSG_INVALID_FOR_IN_INIT, 268, 0, JSEXN_SYNTAXERR, "for-in loop let declaration may not have an initializer") MSG_DEF(JSMSG_CLEARED_SCOPE, 269, 0, JSEXN_TYPEERR, "attempt to run compile-and-go script on a cleared scope") MSG_DEF(JSMSG_MALFORMED_ESCAPE, 270, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") MSG_DEF(JSMSG_BAD_GENEXP_BODY, 271, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_UNUSED272, 272, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_YIELD_WITHOUT_OPERAND, 272, 0, JSEXN_SYNTAXERR, "yield without a value is deprecated, and illegal in ES6 (use 'yield undefined' instead)") MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 273, 0, JSEXN_SYNTAXERR, "function statement requires a name") MSG_DEF(JSMSG_CCW_REQUIRED, 274, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 275, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") @@ -391,12 +391,21 @@ MSG_DEF(JSMSG_DATE_NOT_FINITE, 337, 0, JSEXN_RANGEERR, "date value is not MSG_DEF(JSMSG_MODULE_STATEMENT, 338, 0, JSEXN_SYNTAXERR, "module declarations may only appear at the top level of a program or module body") MSG_DEF(JSMSG_CURLY_BEFORE_MODULE, 339, 0, JSEXN_SYNTAXERR, "missing { before module body") MSG_DEF(JSMSG_CURLY_AFTER_MODULE, 340, 0, JSEXN_SYNTAXERR, "missing } after module body") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "'use asm' directive only works on function code") +MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 342, 1, JSEXN_TYPEERR, "asm.js type error: {0}") MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 343, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 0, JSEXN_ERR, "successfully compiled asm.js code") +MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 1, JSEXN_ERR, "successfully compiled asm.js code ({0})") MSG_DEF(JSMSG_BAD_ARROW_ARGS, 345, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") +MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") +MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") diff --git a/external/spidermonkey/include/ios/js/Anchor.h b/external/spidermonkey/include/ios/js/Anchor.h index d0c2476cf7..0d458e6fb6 100644 --- a/external/spidermonkey/include/ios/js/Anchor.h +++ b/external/spidermonkey/include/ios/js/Anchor.h @@ -6,8 +6,8 @@ /* JS::Anchor implementation. */ -#ifndef js_Anchor_h___ -#define js_Anchor_h___ +#ifndef js_Anchor_h +#define js_Anchor_h #include "mozilla/Attributes.h" @@ -159,4 +159,4 @@ inline Anchor::~Anchor() } // namespace JS -#endif /* js_Anchor_h___ */ +#endif /* js_Anchor_h */ diff --git a/external/spidermonkey/include/ios/js/CallArgs.h b/external/spidermonkey/include/ios/js/CallArgs.h index af78fde0a0..8027ffc71a 100644 --- a/external/spidermonkey/include/ios/js/CallArgs.h +++ b/external/spidermonkey/include/ios/js/CallArgs.h @@ -26,11 +26,12 @@ * methods' implementations, potentially under time pressure. */ -#ifndef js_CallArgs_h___ -#define js_CallArgs_h___ +#ifndef js_CallArgs_h +#define js_CallArgs_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/TypeTraits.h" #include "jstypes.h" @@ -44,6 +45,29 @@ class JSObject; typedef JSBool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); +/* Typedef for native functions that may be called in parallel. */ +typedef js::ParallelResult +(* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + +/* + * Typedef for native functions that may be called either in parallel or + * sequential execution. + */ +typedef JSBool +(* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); + +/* + * Convenience wrappers for passing in ThreadSafeNative to places that expect + * a JSNative or a JSParallelNative. + */ +template +inline JSBool +JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); + +template +inline js::ParallelResult +JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + /* * Compute |this| for the |vp| inside a JSNative, either boxing primitives or * replacing with the global object as necessary. @@ -58,6 +82,8 @@ JS_ComputeThis(JSContext *cx, JS::Value *vp); namespace JS { +extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; + /* * JS::CallReceiver encapsulates access to the callee, |this|, and eventual * return value for a function call. The principal way to create a @@ -92,30 +118,55 @@ namespace JS { * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallReceiver + +namespace detail { + +#ifdef DEBUG +extern JS_PUBLIC_API(void) +CheckIsValidConstructible(Value v); +#endif + +enum UsedRval { IncludeUsedRval, NoUsedRval }; + +template +class MOZ_STACK_CLASS UsedRvalBase; + +template<> +class MOZ_STACK_CLASS UsedRvalBase { protected: -#ifdef DEBUG mutable bool usedRval_; void setUsedRval() const { usedRval_ = true; } void clearUsedRval() const { usedRval_ = false; } -#else +}; + +template<> +class MOZ_STACK_CLASS UsedRvalBase +{ + protected: void setUsedRval() const {} void clearUsedRval() const {} +}; + +template +class MOZ_STACK_CLASS CallReceiverBase : public UsedRvalBase< +#ifdef DEBUG + WantUsedRval +#else + NoUsedRval #endif - + > +{ + protected: Value *argv_; - friend CallReceiver CallReceiverFromVp(Value *vp); - friend CallReceiver CallReceiverFromArgv(Value *argv); - public: /* * Returns the function being called, as an object. Must not be called * after rval() has been used! */ JSObject &callee() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return argv_[-2].toObject(); } @@ -124,7 +175,7 @@ class MOZ_STACK_CLASS CallReceiver * rval() has been used! */ HandleValue calleev() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return HandleValue::fromMarkedLocation(&argv_[-2]); } @@ -148,6 +199,14 @@ class MOZ_STACK_CLASS CallReceiver return JS_ComputeThis(cx, base()); } + bool isConstructing() const { +#ifdef DEBUG + if (this->usedRval_) + CheckIsValidConstructible(calleev()); +#endif + return argv_[-1].isMagic(); + } + /* * Returns the currently-set return value. The initial contents of this * value are unspecified. Once this method has been called, callee() and @@ -160,7 +219,7 @@ class MOZ_STACK_CLASS CallReceiver * fails. */ MutableHandleValue rval() const { - setUsedRval(); + this->setUsedRval(); return MutableHandleValue::fromMarkedLocation(&argv_[-2]); } @@ -171,7 +230,7 @@ class MOZ_STACK_CLASS CallReceiver Value *base() const { return argv_ - 2; } Value *spAfterCall() const { - setUsedRval(); + this->setUsedRval(); return argv_ - 1; } @@ -181,7 +240,7 @@ class MOZ_STACK_CLASS CallReceiver // it. You probably don't want to use these! void setCallee(Value aCalleev) const { - clearUsedRval(); + this->clearUsedRval(); argv_[-2] = aCalleev; } @@ -194,6 +253,15 @@ class MOZ_STACK_CLASS CallReceiver } }; +} // namespace detail + +class MOZ_STACK_CLASS CallReceiver : public detail::CallReceiverBase +{ + private: + friend CallReceiver CallReceiverFromVp(Value *vp); + friend CallReceiver CallReceiverFromArgv(Value *argv); +}; + MOZ_ALWAYS_INLINE CallReceiver CallReceiverFromArgv(Value *argv) { @@ -233,11 +301,59 @@ CallReceiverFromVp(Value *vp) * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallArgs : public CallReceiver +namespace detail { + +template +class MOZ_STACK_CLASS CallArgsBase : + public mozilla::Conditional >::Type { protected: unsigned argc_; + public: + /* Returns the number of arguments. */ + unsigned length() const { return argc_; } + + /* Returns the i-th zero-indexed argument. */ + MutableHandleValue operator[](unsigned i) const { + MOZ_ASSERT(i < argc_); + return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); + } + + /* + * Returns the i-th zero-indexed argument, or |undefined| if there's no + * such argument. + */ + HandleValue get(unsigned i) const { + return i < length() + ? HandleValue::fromMarkedLocation(&this->argv_[i]) + : UndefinedHandleValue; + } + + /* + * Returns true if the i-th zero-indexed argument is present and is not + * |undefined|. + */ + bool hasDefined(unsigned i) const { + return i < argc_ && !this->argv_[i].isUndefined(); + } + + public: + // These methods are publicly exposed, but we're less sure of the interface + // here than we'd like (because they're hackish and drop assertions). Try + // to avoid using these if you can. + + Value *array() const { return this->argv_; } + Value *end() const { return this->argv_ + argc_; } +}; + +} // namespace detail + +class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase +{ + private: friend CallArgs CallArgsFromVp(unsigned argc, Value *vp); friend CallArgs CallArgsFromSp(unsigned argc, Value *sp); @@ -249,45 +365,6 @@ class MOZ_STACK_CLASS CallArgs : public CallReceiver return args; } - public: - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - Value &operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return argv_[i]; - } - - /* Returns a mutable handle for the i-th zero-indexed argument. */ - MutableHandleValue handleAt(unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - Value get(unsigned i) const { - return i < length() ? argv_[i] : UndefinedValue(); - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !argv_[i].isUndefined(); - } - - public: - // These methods are publicly exposed, but we're less sure of the interface - // here than we'd like (because they're hackish and drop assertions). Try - // to avoid using these if you can. - - Value *array() const { return argv_; } - Value *end() const { return argv_ + argc_; } }; MOZ_ALWAYS_INLINE CallArgs @@ -345,4 +422,4 @@ JS_THIS(JSContext *cx, JS::Value *vp) */ #define JS_THIS_VALUE(cx,vp) ((vp)[1]) -#endif /* js_CallArgs_h___ */ +#endif /* js_CallArgs_h */ diff --git a/external/spidermonkey/include/ios/js/CharacterEncoding.h b/external/spidermonkey/include/ios/js/CharacterEncoding.h index 63e5cc6650..e88e08e1be 100644 --- a/external/spidermonkey/include/ios/js/CharacterEncoding.h +++ b/external/spidermonkey/include/ios/js/CharacterEncoding.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_CharacterEncoding_h___ -#define js_CharacterEncoding_h___ +#ifndef js_CharacterEncoding_h +#define js_CharacterEncoding_h #include "mozilla/Range.h" @@ -58,6 +58,20 @@ class Latin1CharsZ : public mozilla::RangedPtr char *c_str() { return reinterpret_cast(get()); } }; +class UTF8Chars : public mozilla::Range +{ + typedef mozilla::Range Base; + + public: + UTF8Chars() : Base() {} + UTF8Chars(char *aBytes, size_t aLength) + : Base(reinterpret_cast(aBytes), aLength) + {} + UTF8Chars(const char *aBytes, size_t aLength) + : Base(reinterpret_cast(const_cast(aBytes)), aLength) + {} +}; + /* * SpiderMonkey also deals directly with UTF-8 encoded text in some places. */ @@ -124,10 +138,12 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: + TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) { - JS_ASSERT(chars[length] = '\0'); + JS_ASSERT(chars[length] == '\0'); } }; @@ -142,14 +158,34 @@ class TwoByteCharsZ : public mozilla::RangedPtr * This method cannot trigger GC. */ extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(JSContext *cx, TwoByteChars tbchars); +LossyTwoByteCharsToNewLatin1CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); extern UTF8CharsZ -TwoByteCharsToNewUTF8CharsZ(JSContext *cx, TwoByteChars tbchars); +TwoByteCharsToNewUTF8CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); + +uint32_t +Utf8ToOneUcs4Char(const uint8_t *utf8Buffer, int utf8Length); + +/* + * Inflate bytes in UTF-8 encoding to jschars. + * - On error, returns an empty TwoByteCharsZ. + * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold + * its length; the length value excludes the trailing null. + */ +extern TwoByteCharsZ +UTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); + +/* + * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters + * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 + * input. + */ +extern TwoByteCharsZ +LossyUTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); } // namespace JS inline void JS_free(JS::Latin1CharsZ &ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::UTF8CharsZ &ptr) { js_free((void*)ptr.get()); } -#endif // js_CharacterEncoding_h___ +#endif /* js_CharacterEncoding_h */ diff --git a/external/spidermonkey/include/ios/js/Date.h b/external/spidermonkey/include/ios/js/Date.h index 7ca961e30a..6199f9eca5 100644 --- a/external/spidermonkey/include/ios/js/Date.h +++ b/external/spidermonkey/include/ios/js/Date.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_Date_h___ -#define js_Date_h___ +#ifndef js_Date_h +#define js_Date_h #include "jstypes.h" @@ -32,4 +32,4 @@ DayFromTime(double time); } // namespace JS -#endif /* js_Date_h___ */ +#endif /* js_Date_h */ diff --git a/external/spidermonkey/include/ios/js/GCAPI.h b/external/spidermonkey/include/ios/js/GCAPI.h index 1b0036116c..a9bef77c09 100644 --- a/external/spidermonkey/include/ios/js/GCAPI.h +++ b/external/spidermonkey/include/ios/js/GCAPI.h @@ -4,10 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_gc_api_h___ -#define js_gc_api_h___ +#ifndef js_GCAPI_h +#define js_GCAPI_h -#include "HeapAPI.h" +#include "js/HeapAPI.h" namespace JS { @@ -181,6 +181,9 @@ DisableIncrementalGC(JSRuntime *rt); extern JS_FRIEND_API(void) DisableGenerationalGC(JSRuntime *rt); +extern JS_FRIEND_API(void) +EnableGenerationalGC(JSRuntime *rt); + extern JS_FRIEND_API(bool) IsIncrementalBarrierNeeded(JSRuntime *rt); @@ -205,7 +208,7 @@ WasIncrementalGC(JSRuntime *rt); class ObjectPtr { - JSObject *value; + Heap value; public: ObjectPtr() : value(NULL) {} @@ -240,7 +243,7 @@ class ObjectPtr } void trace(JSTracer *trc, const char *name) { - JS_CallObjectTracer(trc, &value, name); + JS_CallHeapObjectTracer(trc, &value, name); } JSObject &operator*() const { return *value; } @@ -291,4 +294,4 @@ ExposeValueToActiveJS(const Value &v) } /* namespace JS */ -#endif /* js_gc_api_h___ */ +#endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/ios/js/HashTable.h b/external/spidermonkey/include/ios/js/HashTable.h index 3402bfbff4..aa05b71472 100644 --- a/external/spidermonkey/include/ios/js/HashTable.h +++ b/external/spidermonkey/include/ios/js/HashTable.h @@ -4,17 +4,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_HashTable_h__ -#define js_HashTable_h__ +#ifndef js_HashTable_h +#define js_HashTable_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" #include "mozilla/PodOperations.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" #include "mozilla/Util.h" -#include "js/TemplateLib.h" #include "js/Utility.h" namespace js { @@ -68,15 +72,7 @@ class HashMap // HashMap construction is fallible (due to OOM); thus the user must call // init after constructing a HashMap and check the return value. - HashMap(AllocPolicy a = AllocPolicy()) - : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Key type must be relocatable"); - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Value type must be relocatable"); - } - + HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -142,18 +138,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, Move(e)); + return impl.relookupOrAdd(p, k, mozilla::Move(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -203,10 +199,10 @@ class HashMap // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -235,7 +231,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, Move(e)); + return impl.putNew(k, mozilla::Move(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -253,9 +249,17 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const Key &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashMap is movable - HashMap(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashMap is not copyable or assignable @@ -303,11 +307,7 @@ class HashSet // HashSet construction is fallible (due to OOM); thus the user must call // init after constructing a HashSet and check the return value. - HashSet(AllocPolicy a = AllocPolicy()) : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Set element type must be relocatable"); - } + HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -411,10 +411,10 @@ class HashSet // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -448,9 +448,17 @@ class HashSet remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const T &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashSet is movable - HashSet(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashSet is not copyable or assignable @@ -532,7 +540,7 @@ struct DefaultHasher // Specialize hashing policy for pointer types. It assumes that the type is // at least word-aligned. For types with smaller size use PointerHasher. template -struct DefaultHasher : PointerHasher::result> +struct DefaultHasher : PointerHasher::value> {}; // For doubles, we can xor the two uint32s. @@ -542,18 +550,11 @@ struct DefaultHasher typedef double Lookup; static HashNumber hash(double d) { JS_STATIC_ASSERT(sizeof(HashNumber) == 4); - union { - struct { - uint32_t lo; - uint32_t hi; - } s; - double d; - } u; - u.d = d; - return u.s.lo ^ u.s.hi; + uint64_t u = mozilla::BitwiseCast(d); + return HashNumber(u ^ (u >> 32)); } static bool match(double lhs, double rhs) { - return lhs == rhs; + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); } }; @@ -577,8 +578,8 @@ class HashMapEntry template HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} - HashMapEntry(MoveRef rhs) - : key(Move(rhs->key)), value(Move(rhs->value)) { } + HashMapEntry(mozilla::MoveRef rhs) + : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -647,8 +648,8 @@ class HashTableEntry } void swap(HashTableEntry *other) { - Swap(keyHash, other->keyHash); - Swap(mem, other->mem); + mozilla::Swap(keyHash, other->keyHash); + mozilla::Swap(mem, other->mem); } T &get() { JS_ASSERT(isLive()); return *mem.addr(); } @@ -807,10 +808,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - typename HashTableEntry::NonConstT t(Move(this->cur->get())); - HashPolicy::setKey(t, const_cast(k)); - table.remove(*this->cur); - table.putNewInfallible(l, Move(t)); + table.rekey(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -832,13 +830,13 @@ class HashTable : private AllocPolicy }; // HashTable is movable - HashTable(MoveRef rhs) + HashTable(mozilla::MoveRef rhs) : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); rhs->table = NULL; } - void operator=(MoveRef rhs) { + void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); @@ -882,7 +880,7 @@ class HashTable : private AllocPolicy # define METER(x) #endif - friend class js::ReentrancyGuard; + friend class mozilla::ReentrancyGuard; mutable mozilla::DebugOnly entered; mozilla::DebugOnly mutationCount; @@ -892,7 +890,7 @@ class HashTable : private AllocPolicy static const unsigned sMinCapacity = 1 << sMinCapacityLog2; static const unsigned sMaxInit = JS_BIT(23); static const unsigned sMaxCapacity = JS_BIT(24); - static const unsigned sHashBits = tl::BitSize::result; + static const unsigned sHashBits = mozilla::tl::BitSize::value; static const uint8_t sMinAlphaFrac = 64; // (0x100 * .25) static const uint8_t sMaxAlphaFrac = 192; // (0x100 * .75) static const uint8_t sInvMaxAlpha = 171; // (ceil(0x100 / .75) >> 1) @@ -1165,7 +1163,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); src->destroy(); } } @@ -1346,19 +1344,19 @@ class HashTable : private AllocPolicy return gen; } - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(table); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); } Ptr lookup(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); return Ptr(lookup(l, keyHash, 0)); } @@ -1371,7 +1369,7 @@ class HashTable : private AllocPolicy AddPtr lookupForAdd(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); Entry &entry = lookup(l, keyHash, sCollisionBit); AddPtr p(entry, keyHash); @@ -1382,7 +1380,7 @@ class HashTable : private AllocPolicy template bool add(AddPtr &p, const U &rhs) { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(mutationCount == p.mutationCount); JS_ASSERT(table); JS_ASSERT(!p.found()); @@ -1443,7 +1441,7 @@ class HashTable : private AllocPolicy { p.mutationCount = mutationCount; { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); p.entry_ = &lookup(l, p.keyHash, sCollisionBit); } return p.found() || add(p, u); @@ -1452,17 +1450,27 @@ class HashTable : private AllocPolicy void remove(Ptr p) { JS_ASSERT(table); - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); remove(*p.entry_); checkUnderloaded(); } + void rekey(Ptr p, const Lookup &l, const Key &k) + { + JS_ASSERT(table); + mozilla::ReentrancyGuard g(*this); + JS_ASSERT(p.found()); + typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + HashPolicy::setKey(t, const_cast(k)); + remove(*p.entry_); + putNewInfallible(l, mozilla::Move(t)); + } + #undef METER }; } // namespace detail } // namespace js -#endif // js_HashTable_h__ - +#endif /* js_HashTable_h */ diff --git a/external/spidermonkey/include/ios/js/HeapAPI.h b/external/spidermonkey/include/ios/js/HeapAPI.h index f0f4411ac9..4d739304bc 100644 --- a/external/spidermonkey/include/ios/js/HeapAPI.h +++ b/external/spidermonkey/include/ios/js/HeapAPI.h @@ -4,33 +4,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_heap_api_h___ -#define js_heap_api_h___ +#ifndef js_HeapAPI_h +#define js_HeapAPI_h #include "jspubtd.h" +#include "js/Utility.h" + /* These values are private to the JS engine. */ namespace js { namespace gc { -/* - * Page size must be static to support our arena pointer optimizations, so we - * are forced to support each platform with non-4096 pages as a special case. - * Note: The freelist supports a maximum arena shift of 15. - * Note: Do not use JS_CPU_SPARC here, this header is used outside JS. - */ -#if (defined(SOLARIS) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \ - (defined(__sparc) || defined(__sparcv9) || defined(__ia64)) -const size_t PageShift = 13; -const size_t ArenaShift = PageShift; -#elif defined(__powerpc64__) -const size_t PageShift = 16; const size_t ArenaShift = 12; -#else -const size_t PageShift = 12; -const size_t ArenaShift = PageShift; -#endif -const size_t PageSize = size_t(1) << PageShift; const size_t ArenaSize = size_t(1) << ArenaShift; const size_t ArenaMask = ArenaSize - 1; @@ -67,7 +52,7 @@ namespace shadow { struct ArenaHeader { - js::Zone *zone; + JS::Zone *zone; }; struct Zone @@ -153,10 +138,10 @@ IsIncrementalBarrierNeededOnGCThing(shadow::Runtime *rt, void *thing, JSGCTraceK { if (!rt->needsBarrier_) return false; - js::Zone *zone = GetGCThingZone(thing); + JS::Zone *zone = GetGCThingZone(thing); return reinterpret_cast(zone)->needsBarrier_; } } /* namespace JS */ -#endif /* js_heap_api_h___ */ +#endif /* js_HeapAPI_h */ diff --git a/external/spidermonkey/include/ios/js/LegacyIntTypes.h b/external/spidermonkey/include/ios/js/LegacyIntTypes.h index 387a68b9e9..2c8498c89e 100644 --- a/external/spidermonkey/include/ios/js/LegacyIntTypes.h +++ b/external/spidermonkey/include/ios/js/LegacyIntTypes.h @@ -17,13 +17,12 @@ * Indeed, if you use this header and third-party code defining these * types, *expect* to encounter either compile errors or link errors, * depending how these types are used and on the order of inclusion. - * It is safest to use only the JSAPI -style types, - * customizing those types using MOZ_CUSTOM_STDINT_H if necessary. + * It is safest to use only the types. */ -#ifndef PROTYPES_H -#define PROTYPES_H +#ifndef js_LegacyIntTypes_h +#define js_LegacyIntTypes_h -#include "mozilla/StandardInteger.h" +#include #include "js-config.h" @@ -57,4 +56,4 @@ typedef int16_t JSInt16; typedef int32_t JSInt32; typedef int64_t JSInt64; -#endif /* !defined(PROTYPES_H) */ +#endif /* js_LegacyIntTypes_h */ diff --git a/external/spidermonkey/include/ios/js/MemoryMetrics.h b/external/spidermonkey/include/ios/js/MemoryMetrics.h index 7e84f2ae11..ed61e1c427 100644 --- a/external/spidermonkey/include/ios/js/MemoryMetrics.h +++ b/external/spidermonkey/include/ios/js/MemoryMetrics.h @@ -10,6 +10,8 @@ // These declarations are not within jsapi.h because they are highly likely to // change in the future. Depend on them at your own risk. +#include "mozilla/MemoryReporting.h" + #include #include "jsalloc.h" @@ -91,7 +93,6 @@ struct TypeInferenceSizes // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t jaeger; size_t ion; size_t asmJS; size_t baseline; @@ -136,7 +137,7 @@ struct RuntimeSizes size_t dtoa; size_t temporary; size_t regexpData; - size_t stack; + size_t interpreterStack; size_t gcMarker; size_t mathCache; size_t scriptData; @@ -153,9 +154,11 @@ struct ZoneStats gcHeapUnusedGcThings(0), gcHeapStringsNormal(0), gcHeapStringsShort(0), + gcHeapLazyScripts(0), gcHeapTypeObjects(0), gcHeapIonCodes(0), stringCharsNonHuge(0), + lazyScripts(0), typeObjects(0), typePool(0), hugeStrings() @@ -167,14 +170,16 @@ struct ZoneStats gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), gcHeapStringsNormal(other.gcHeapStringsNormal), gcHeapStringsShort(other.gcHeapStringsShort), + gcHeapLazyScripts(other.gcHeapLazyScripts), gcHeapTypeObjects(other.gcHeapTypeObjects), gcHeapIonCodes(other.gcHeapIonCodes), stringCharsNonHuge(other.stringCharsNonHuge), + lazyScripts(other.lazyScripts), typeObjects(other.typeObjects), typePool(other.typePool), hugeStrings() { - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // Add other's numbers to this object's numbers. @@ -186,16 +191,18 @@ struct ZoneStats ADD(gcHeapStringsNormal); ADD(gcHeapStringsShort); + ADD(gcHeapLazyScripts); ADD(gcHeapTypeObjects); ADD(gcHeapIonCodes); ADD(stringCharsNonHuge); + ADD(lazyScripts); ADD(typeObjects); ADD(typePool); #undef ADD - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // This field can be used by embedders. @@ -207,10 +214,12 @@ struct ZoneStats size_t gcHeapStringsNormal; size_t gcHeapStringsShort; + size_t gcHeapLazyScripts; size_t gcHeapTypeObjects; size_t gcHeapIonCodes; size_t stringCharsNonHuge; + size_t lazyScripts; size_t typeObjects; size_t typePool; @@ -241,7 +250,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(0), shapesCompartmentTables(0), scriptData(0), - jaegerData(0), baselineData(0), baselineStubsFallback(0), baselineStubsOptimized(0), @@ -271,7 +279,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), shapesCompartmentTables(other.shapesCompartmentTables), scriptData(other.scriptData), - jaegerData(other.jaegerData), baselineData(other.baselineData), baselineStubsFallback(other.baselineStubsFallback), baselineStubsOptimized(other.baselineStubsOptimized), @@ -306,7 +313,6 @@ struct CompartmentStats size_t shapesExtraTreeShapeKids; size_t shapesCompartmentTables; size_t scriptData; - size_t jaegerData; size_t baselineData; size_t baselineStubsFallback; size_t baselineStubsOptimized; @@ -339,7 +345,6 @@ struct CompartmentStats ADD(shapesExtraTreeShapeKids); ADD(shapesCompartmentTables); ADD(scriptData); - ADD(jaegerData); ADD(baselineData); ADD(baselineStubsFallback); ADD(baselineStubsOptimized); @@ -360,7 +365,7 @@ struct CompartmentStats struct RuntimeStats { - RuntimeStats(JSMallocSizeOfFun mallocSizeOf) + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) : runtime(), gcHeapChunkTotal(0), gcHeapDecommittedArenas(0), @@ -417,7 +422,7 @@ struct RuntimeStats ZoneStats *currZoneStats; - JSMallocSizeOfFun mallocSizeOf_; + mozilla::MallocSizeOf mallocSizeOf_; virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; @@ -454,4 +459,4 @@ PeakSizeOfTemporary(const JSRuntime *rt); } // namespace JS -#endif // js_MemoryMetrics_h +#endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/ios/js/PropertyKey.h b/external/spidermonkey/include/ios/js/PropertyKey.h index 53158c26f3..c949db13a5 100644 --- a/external/spidermonkey/include/ios/js/PropertyKey.h +++ b/external/spidermonkey/include/ios/js/PropertyKey.h @@ -6,8 +6,8 @@ /* JS::PropertyKey implementation. */ -#ifndef js_PropertyKey_h___ -#define js_PropertyKey_h___ +#ifndef js_PropertyKey_h +#define js_PropertyKey_h #include "mozilla/Attributes.h" @@ -95,4 +95,4 @@ ToPropertyKey(JSContext *cx, HandleValue v, PropertyKey *key) } // namespace JS -#endif /* js_PropertyKey_h___ */ +#endif /* js_PropertyKey_h */ diff --git a/external/spidermonkey/include/ios/js/RequiredDefines.h b/external/spidermonkey/include/ios/js/RequiredDefines.h index 2be2efbf9a..6af9ca871b 100644 --- a/external/spidermonkey/include/ios/js/RequiredDefines.h +++ b/external/spidermonkey/include/ios/js/RequiredDefines.h @@ -10,8 +10,8 @@ * or SpiderMonkey public headers may not work correctly. */ -#ifndef js_RequiredDefines_h___ -#define js_RequiredDefines_h___ +#ifndef js_RequiredDefines_h +#define js_RequiredDefines_h /* * The c99 defining the limit macros (UINT32_MAX for example), says: @@ -20,4 +20,4 @@ */ #define __STDC_LIMIT_MACROS -#endif /* js_RequiredDefines_h___ */ +#endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/ios/js/RootingAPI.h b/external/spidermonkey/include/ios/js/RootingAPI.h index 3e2e0d2a7c..99295f1238 100644 --- a/external/spidermonkey/include/ios/js/RootingAPI.h +++ b/external/spidermonkey/include/ios/js/RootingAPI.h @@ -4,14 +4,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsgc_root_h__ -#define jsgc_root_h__ +#ifndef js_RootingAPI_h +#define js_RootingAPI_h #include "mozilla/GuardObjects.h" #include "mozilla/TypeTraits.h" #include "js/Utility.h" -#include "js/TemplateLib.h" #include "jspubtd.h" @@ -99,9 +98,10 @@ namespace js { class Module; +class ScriptSourceObject; template -struct RootMethods {}; +struct GCMethods {}; template class RootedBase {}; @@ -112,6 +112,9 @@ class HandleBase {}; template class MutableHandleBase {}; +template +class HeapBase {}; + /* * js::NullPtr acts like a NULL pointer in contexts that require a Handle. * @@ -130,6 +133,10 @@ struct NullPtr static void * const constNullValue; }; +namespace gc { +struct Cell; +} /* namespace gc */ + } /* namespace js */ namespace JS { @@ -161,6 +168,204 @@ struct JS_PUBLIC_API(NullPtr) static void * const constNullValue; }; +/* + * The Heap class is a C/C++ heap-stored reference to a JS GC thing. All + * members of heap classes that refer to GC thing should use Heap (or + * possibly TenuredHeap, described below). + * + * Heap wraps the complex mechanisms required to ensure GC safety for the + * contained reference into a C++ class that behaves similarly to a normal + * pointer. + * + * GC references stored on the C/C++ stack must use Rooted/Handle/MutableHandle + * instead. + * + * Requirements for type T: + * - Must be one of: Value, jsid, JSObject*, JSString*, JSScript* + */ +template +class Heap : public js::HeapBase +{ + public: + Heap() { + static_assert(sizeof(T) == sizeof(Heap), + "Heap must be binary compatible with T."); + init(js::GCMethods::initial()); + } + explicit Heap(T p) { init(p); } + explicit Heap(const Heap &p) { init(p.ptr); } + + ~Heap() { + if (js::GCMethods::needsPostBarrier(ptr)) + relocate(); + } + + bool operator==(const Heap &other) { return ptr == other.ptr; } + bool operator!=(const Heap &other) { return ptr != other.ptr; } + + bool operator==(const T &other) const { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + + operator T() const { return ptr; } + T operator->() const { return ptr; } + const T *address() const { return &ptr; } + const T &get() const { return ptr; } + + T *unsafeGet() { return &ptr; } + + Heap &operator=(T p) { + set(p); + return *this; + } + + void set(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (js::GCMethods::needsPostBarrier(newPtr)) { + ptr = newPtr; + post(); + } else if (js::GCMethods::needsPostBarrier(ptr)) { + relocate(); /* Called before overwriting ptr. */ + ptr = newPtr; + } else { + ptr = newPtr; + } + } + + private: + void init(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + ptr = newPtr; + if (js::GCMethods::needsPostBarrier(ptr)) + post(); + } + + void post() { +#ifdef JSGC_GENERATIONAL + JS_ASSERT(js::GCMethods::needsPostBarrier(ptr)); + js::GCMethods::postBarrier(&ptr); +#endif + } + + void relocate() { +#ifdef JSGC_GENERATIONAL + js::GCMethods::relocate(&ptr); +#endif + } + + T ptr; +}; + +#ifdef DEBUG +/* + * For generational GC, assert that an object is in the tenured generation as + * opposed to being in the nursery. + */ +extern JS_FRIEND_API(void) +AssertGCThingMustBeTenured(JSObject* obj); +#else +inline void +AssertGCThingMustBeTenured(JSObject *obj) {} +#endif + +/* + * The TenuredHeap class is similar to the Heap class above in that it + * encapsulates the GC concerns of an on-heap reference to a JS object. However, + * it has two important differences: + * + * 1) Pointers which are statically known to only reference "tenured" objects + * can avoid the extra overhead of SpiderMonkey's write barriers. + * + * 2) Objects in the "tenured" heap have stronger alignment restrictions than + * those in the "nursery", so it is possible to store flags in the lower + * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged + * pointer with a nice API for accessing the flag bits and adds various + * assertions to ensure that it is not mis-used. + * + * GC things are said to be "tenured" when they are located in the long-lived + * heap: e.g. they have gained tenure as an object by surviving past at least + * one GC. For performance, SpiderMonkey allocates some things which are known + * to normally be long lived directly into the tenured generation; for example, + * global objects. Additionally, SpiderMonkey does not visit individual objects + * when deleting non-tenured objects, so object with finalizers are also always + * tenured; for instance, this includes most DOM objects. + * + * The considerations to keep in mind when using a TenuredHeap vs a normal + * Heap are: + * + * - It is invalid for a TenuredHeap to refer to a non-tenured thing. + * - It is however valid for a Heap to refer to a tenured thing. + * - It is not possible to store flag bits in a Heap. + */ +template +class TenuredHeap : public js::HeapBase +{ + public: + TenuredHeap() : bits(0) { + static_assert(sizeof(T) == sizeof(TenuredHeap), + "TenuredHeap must be binary compatible with T."); + } + explicit TenuredHeap(T p) : bits(0) { setPtr(p); } + explicit TenuredHeap(const TenuredHeap &p) : bits(0) { setPtr(p.ptr); } + + bool operator==(const TenuredHeap &other) { return bits == other.bits; } + bool operator!=(const TenuredHeap &other) { return bits != other.bits; } + + void setPtr(T newPtr) { + JS_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (newPtr) + AssertGCThingMustBeTenured(newPtr); + bits = (bits & flagsMask) | reinterpret_cast(newPtr); + } + + void setFlags(uintptr_t flagsToSet) { + JS_ASSERT((flagsToSet & ~flagsMask) == 0); + bits |= flagsToSet; + } + + void unsetFlags(uintptr_t flagsToUnset) { + JS_ASSERT((flagsToUnset & ~flagsMask) == 0); + bits &= ~flagsToUnset; + } + + bool hasFlag(uintptr_t flag) const { + JS_ASSERT((flag & ~flagsMask) == 0); + return (bits & flag) != 0; + } + + T getPtr() const { return reinterpret_cast(bits & ~flagsMask); } + uintptr_t getFlags() const { return bits & flagsMask; } + + operator T() const { return getPtr(); } + T operator->() const { return getPtr(); } + + TenuredHeap &operator=(T p) { + setPtr(p); + return *this; + } + + /* + * Set the pointer to a value which will cause a crash if it is + * dereferenced. + */ + void setToCrashOnTouch() { + bits = (bits & flagsMask) | crashOnTouchPointer; + } + + bool isSetToCrashOnTouch() { + return (bits & ~flagsMask) == crashOnTouchPointer; + } + + private: + enum { + maskBits = 3, + flagsMask = (1 << maskBits) - 1, + crashOnTouchPointer = 1 << maskBits + }; + + uintptr_t bits; +}; + /* * Reference to a T that has been rooted elsewhere. This is most useful * as a parameter type, which guarantees that the T lvalue is properly @@ -170,7 +375,7 @@ struct JS_PUBLIC_API(NullPtr) * specialization, define a HandleBase specialization containing them. */ template -class MOZ_STACK_CLASS Handle : public js::HandleBase +class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { friend class MutableHandle; @@ -180,20 +385,22 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase Handle(Handle handle, typename mozilla::EnableIf::value, int>::Type dummy = 0) { + static_assert(sizeof(Handle) == sizeof(T *), + "Handle must be binary compatible with T*."); ptr = reinterpret_cast(handle.address()); } /* Create a handle for a NULL pointer. */ Handle(js::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "js::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } /* Create a handle for a NULL pointer. */ Handle(JS::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "JS::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "JS::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&JS::NullPtr::constNullValue); } @@ -202,11 +409,19 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase } /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. + * Take care when calling this method! * - * Create a Handle from a raw location of a T. + * This creates a Handle from the raw location of a T. + * + * It should be called only if the following conditions hold: + * + * 1) the location of the T is guaranteed to be marked (for some reason + * other than being a Rooted), e.g., if it is guaranteed to be reachable + * from an implicit root. + * + * 2) the contents of the location are immutable, or at least cannot change + * for the lifetime of the handle, as its users may not expect its value + * to change underneath them. */ static Handle fromMarkedLocation(const T *p) { Handle h; @@ -230,13 +445,17 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase typename mozilla::EnableIf::value, int>::Type dummy = 0); const T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a Handle to something that + * takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } - bool operator!=(const T &other) { return *ptr != other; } - bool operator==(const T &other) { return *ptr == other; } + bool operator!=(const T &other) const { return *ptr != other; } + bool operator==(const T &other) const { return *ptr == other; } private: Handle() {} @@ -247,13 +466,14 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase void operator=(S v) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; +typedef Handle HandleObject; +typedef Handle HandleModule; +typedef Handle HandleScriptSource; +typedef Handle HandleFunction; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleId; +typedef Handle HandleValue; /* * Similar to a handle, but the underlying storage can be changed. This is @@ -270,7 +490,7 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase inline MutableHandle(Rooted *root); void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -288,9 +508,13 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase } T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a MutableHandle to something that takes + * a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } private: @@ -298,8 +522,8 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S v) MOZ_DELETE; + void operator=(MutableHandle other) MOZ_DELETE; }; typedef MutableHandle MutableHandleObject; @@ -309,6 +533,11 @@ typedef MutableHandle MutableHandleString; typedef MutableHandle MutableHandleId; typedef MutableHandle MutableHandleValue; +#ifdef JSGC_GENERATIONAL +JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); +JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); +#endif + } /* namespace JS */ namespace js { @@ -383,13 +612,28 @@ struct RootKind }; template -struct RootMethods +struct GCMethods { static T *initial() { return NULL; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } + static bool needsPostBarrier(T *v) { return v; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(T **vp) { + JS::HeapCellPostBarrier(reinterpret_cast(vp)); + } + static void relocate(T **vp) { + JS::HeapCellRelocate(reinterpret_cast(vp)); + } +#endif }; +#if defined(DEBUG) +/* This helper allows us to assert that Rooted is scoped within a request. */ +extern JS_PUBLIC_API(bool) +IsInRequest(JSContext *cx); +#endif + } /* namespace js */ namespace JS { @@ -405,46 +649,63 @@ namespace JS { template class MOZ_STACK_CLASS Rooted : public js::RootedBase { - void init(JSContext *cxArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ContextFriendFields *cx = js::ContextFriendFields::get(cxArg); - commonInit(cx->thingGCRooters); -#endif - } + /* Note: CX is a subclass of either ContextFriendFields or PerThreadDataFriendFields. */ + template + void init(CX *cx) { +#ifdef JSGC_TRACK_EXACT_ROOTS + js::ThingRootKind kind = js::GCMethods::kind(); + this->stack = &cx->thingGCRooters[kind]; + this->prev = *stack; + *stack = reinterpret_cast*>(this); - void init(js::PerThreadData *ptArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::PerThreadDataFriendFields *pt = js::PerThreadDataFriendFields::get(ptArg); - commonInit(pt->thingGCRooters); + JS_ASSERT(!js::GCMethods::poisoned(ptr)); #endif } public: Rooted(JSContext *cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; - init(cx); + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); } Rooted(JSContext *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); + } + + Rooted(js::ContextFriendFields *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(cx); } - Rooted(js::PerThreadData *pt + Rooted(js::ContextFriendFields *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(cx); + } + + Rooted(js::PerThreadDataFriendFields *pt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(pt); } - Rooted(js::PerThreadData *pt, T initial + Rooted(js::PerThreadDataFriendFields *pt, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { @@ -452,18 +713,38 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(pt); } + Rooted(JSRuntime *rt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + + Rooted(JSRuntime *rt, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + ~Rooted() { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; #endif } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } #endif - operator T() const { return ptr; } + /* + * Important: Return a reference here so passing a Rooted to + * something that takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return ptr; } T operator->() const { return ptr; } T *address() { return &ptr; } const T *address() const { return &ptr; } @@ -471,7 +752,7 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!js::RootMethods::poisoned(value)); + JS_ASSERT(!js::GCMethods::poisoned(value)); ptr = value; return ptr; } @@ -481,28 +762,25 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } - - private: - void commonInit(Rooted **thingGCRooters) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ThingRootKind kind = js::RootMethods::kind(); - this->stack = &thingGCRooters[kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - - JS_ASSERT(!js::RootMethods::poisoned(ptr)); -#endif + void set(T value) { + JS_ASSERT(!js::GCMethods::poisoned(value)); + ptr = value; } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } + + private: +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted **stack, *prev; #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) /* Has the rooting analysis ever scanned this Rooted's stack location? */ friend void JS::CheckStackRoots(JSContext*); +#endif + +#ifdef JSGC_ROOT_ANALYSIS bool scanned; #endif @@ -523,13 +801,14 @@ template <> class Rooted; #endif -typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedId; -typedef Rooted RootedValue; +typedef Rooted RootedObject; +typedef Rooted RootedModule; +typedef Rooted RootedScriptSource; +typedef Rooted RootedFunction; +typedef Rooted RootedScript; +typedef Rooted RootedString; +typedef Rooted RootedId; +typedef Rooted RootedValue; } /* namespace JS */ @@ -549,8 +828,9 @@ class SkipRoot const uint8_t *start; const uint8_t *end; - template - void init(SkipRoot **head, const T *ptr, size_t count) { + template + void init(CX *cx, const T *ptr, size_t count) { + SkipRoot **head = &cx->skipGCRooters; this->stack = head; this->prev = *stack; *stack = this; @@ -559,23 +839,6 @@ class SkipRoot } public: - template - SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - init(&ContextFriendFields::get(cx)->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - template - SkipRoot(js::PerThreadData *ptd, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - PerThreadDataFriendFields *ptff = PerThreadDataFriendFields::get(ptd); - init(&ptff->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - ~SkipRoot() { JS_ASSERT(*stack == this); *stack = prev; @@ -589,22 +852,36 @@ class SkipRoot #else /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} + public: + +#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(ContextFriendFields::get(cx), ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } template - SkipRoot(PerThreadData *ptd, const T *ptr, size_t count = 1 + SkipRoot(ContextFriendFields *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(cx, ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } -#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + SkipRoot(PerThreadData *pt, const T *ptr, size_t count = 1 + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + { + init(PerThreadDataFriendFields::get(pt), ptr, count); + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + } MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; @@ -614,15 +891,17 @@ template class FakeRooted : public RootedBase { public: - FakeRooted(JSContext *cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(RootMethods::initial()) + template + FakeRooted(CX *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } - FakeRooted(JSContext *cx, T initial - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + template + FakeRooted(CX *cx, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; @@ -636,13 +915,13 @@ class FakeRooted : public RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!RootMethods::poisoned(value)); + JS_ASSERT(!GCMethods::poisoned(value)); ptr = value; return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } private: T ptr; @@ -666,7 +945,7 @@ class FakeMutableHandle : public js::MutableHandleBase } void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -727,13 +1006,11 @@ template class MaybeRooted typedef FakeMutableHandle MutableHandleType; static inline JS::Handle toHandle(HandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::Handle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::MutableHandle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } }; @@ -761,6 +1038,8 @@ template inline MutableHandle::MutableHandle(Rooted *root) { + static_assert(sizeof(MutableHandle) == sizeof(T *), + "MutableHandle must be binary compatible with T*."); ptr = root->address(); } @@ -779,10 +1058,6 @@ inline void MaybeCheckStackRoots(JSContext *cx) #endif } -namespace gc { -struct Cell; -} /* namespace gc */ - /* Base class for automatic read-only object rooting during compilation. */ class CompilerRootNode { @@ -801,4 +1076,4 @@ class CompilerRootNode } /* namespace js */ -#endif /* jsgc_root_h___ */ +#endif /* js_RootingAPI_h */ diff --git a/external/spidermonkey/include/ios/js/TemplateLib.h b/external/spidermonkey/include/ios/js/TemplateLib.h deleted file mode 100644 index a4ff682912..0000000000 --- a/external/spidermonkey/include/ios/js/TemplateLib.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_template_lib_h__ -#define js_template_lib_h__ - -#include "jstypes.h" - -/* - * Library of reusable template meta-functions (that is, functions on types and - * compile-time values). Meta-functions are placed inside the 'tl' namespace to - * avoid conflict with non-meta functions that logically have the same name - * (e.g., js::tl::Min vs. js::Min). - */ - -namespace js { -namespace tl { - -/* Compute min/max/clamp. */ -template struct Min { - static const size_t result = i < j ? i : j; -}; -template struct Max { - static const size_t result = i > j ? i : j; -}; -template struct Clamp { - static const size_t result = i < min ? min : (i > max ? max : i); -}; - -/* Compute x^y. */ -template struct Pow { - static const size_t result = x * Pow::result; -}; -template struct Pow { - static const size_t result = 1; -}; - -/* Compute floor(log2(i)). */ -template struct FloorLog2 { - static const size_t result = 1 + FloorLog2::result; -}; -template <> struct FloorLog2<0> { /* Error */ }; -template <> struct FloorLog2<1> { static const size_t result = 0; }; - -/* Compute ceiling(log2(i)). */ -template struct CeilingLog2 { - static const size_t result = FloorLog2<2 * i - 1>::result; -}; - -/* Round up to the nearest power of 2. */ -template struct RoundUpPow2 { - static const size_t result = size_t(1) << CeilingLog2::result; -}; -template <> struct RoundUpPow2<0> { - static const size_t result = 1; -}; - -/* Compute the number of bits in the given unsigned type. */ -template struct BitSize { - static const size_t result = sizeof(T) * JS_BITS_PER_BYTE; -}; - -/* - * Produce an N-bit mask, where N <= BitSize::result. Handle the - * language-undefined edge case when N = BitSize::result. - */ -template struct NBitMask { - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |result| to assure - // its computation. - static const size_t checkPrecondition = 0 / size_t(N < BitSize::result); - static const size_t result = (size_t(1) << N) - 1 + checkPrecondition; -}; -template <> struct NBitMask::result> { - static const size_t result = size_t(-1); -}; - -/* - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template struct MulOverflowMask { - static const size_t result = - ~NBitMask::result - CeilingLog2::result>::result; -}; -template <> struct MulOverflowMask<0> { /* Error */ }; -template <> struct MulOverflowMask<1> { static const size_t result = 0; }; - -/* - * Generate a mask for T such that if (X & sUnsafeRangeSizeMask), an X-sized - * array of T's is big enough to cause a ptrdiff_t overflow when subtracting - * a pointer to the end of the array from the beginning. - */ -template struct UnsafeRangeSizeMask { - /* - * The '2' factor means the top bit is clear, sizeof(T) converts from - * units of elements to bytes. - */ - static const size_t result = MulOverflowMask<2 * sizeof(T)>::result; -}; - -template struct If { static const T result = v1; }; -template struct If { static const T result = v2; }; - -/* - * Traits class for identifying types that are implicitly barriered. - */ -template struct IsRelocatableHeapType { static const bool result = true; }; - -} /* namespace tl */ -} /* namespace js */ - -#endif /* js_template_lib_h__ */ diff --git a/external/spidermonkey/include/ios/js/Utility.h b/external/spidermonkey/include/ios/js/Utility.h index c4ebf7ced6..9d391e5c8a 100644 --- a/external/spidermonkey/include/ios/js/Utility.h +++ b/external/spidermonkey/include/ios/js/Utility.h @@ -4,13 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_utility_h__ -#define js_utility_h__ +#ifndef js_Utility_h +#define js_Utility_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" +#include "mozilla/Move.h" #include "mozilla/Scoped.h" +#include "mozilla/TemplateLib.h" #include #include @@ -22,8 +24,6 @@ #include "jstypes.h" -#include "js/TemplateLib.h" - /* The public JS engine namespace. */ namespace JS {} @@ -41,7 +41,6 @@ namespace js {} #define JS_ASSERT(expr) MOZ_ASSERT(expr) #define JS_ASSERT_IF(cond, expr) MOZ_ASSERT_IF(cond, expr) -#define JS_NOT_REACHED(reason) MOZ_NOT_REACHED(reason) #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) @@ -63,7 +62,7 @@ namespace js {} # define JS_DIAGNOSTICS_ASSERT(expr) ((void) 0) #endif -#define JS_STATIC_ASSERT(cond) MOZ_STATIC_ASSERT(cond, "JS_STATIC_ASSERT") +#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") #define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") extern MOZ_NORETURN JS_PUBLIC_API(void) @@ -84,10 +83,11 @@ extern JS_PUBLIC_API(void) JS_Abort(void); #else # ifdef DEBUG /* - * In order to test OOM conditions, when the shell command-line option - * |-A NUM| is passed, we fail continuously after the NUM'th allocation. + * In order to test OOM conditions, when the testing function + * oomAfterAllocations COUNT is passed, we fail continuously after the NUM'th + * allocation from now. */ -extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set from shell/js.cpp */ +extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set in builtins/TestingFunctions.cpp */ extern JS_PUBLIC_DATA(uint32_t) OOM_counter; /* data race, who cares. */ #ifdef JS_OOM_DO_BACKTRACES @@ -157,6 +157,12 @@ static JS_INLINE void* js_calloc(size_t bytes) return calloc(bytes, 1); } +static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +{ + JS_OOM_POSSIBLY_FAIL(); + return calloc(nmemb, size); +} + static JS_INLINE void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); @@ -169,205 +175,6 @@ static JS_INLINE void js_free(void* p) } #endif/* JS_USE_CUSTOM_ALLOCATOR */ -JS_BEGIN_EXTERN_C - -/* - * Replace bit-scanning code sequences with CPU-specific instructions to - * speedup calculations of ceiling/floor log2. - * - * With GCC 3.4 or later we can use __builtin_clz for that, see bug 327129. - * - * SWS: Added MSVC intrinsic bitscan support. See bugs 349364 and 356856. - */ -#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) - -unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask); -unsigned char _BitScanReverse(unsigned long * Index, unsigned long Mask); -# pragma intrinsic(_BitScanForward,_BitScanReverse) - -__forceinline static int -__BitScanForward32(unsigned int val) -{ - unsigned long idx; - - _BitScanForward(&idx, (unsigned long)val); - return (int)idx; -} -__forceinline static int -__BitScanReverse32(unsigned int val) -{ - unsigned long idx; - - _BitScanReverse(&idx, (unsigned long)val); - return (int)(31-idx); -} -# define js_bitscan_ctz32(val) __BitScanForward32(val) -# define js_bitscan_clz32(val) __BitScanReverse32(val) -# define JS_HAS_BUILTIN_BITSCAN32 - -#if defined(_M_AMD64) || defined(_M_X64) -unsigned char _BitScanForward64(unsigned long * Index, unsigned __int64 Mask); -unsigned char _BitScanReverse64(unsigned long * Index, unsigned __int64 Mask); -# pragma intrinsic(_BitScanForward64,_BitScanReverse64) - -__forceinline static int -__BitScanForward64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanForward64(&idx, val); - return (int)idx; -} -__forceinline static int -__BitScanReverse64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanReverse64(&idx, val); - return (int)(63-idx); -} -# define js_bitscan_ctz64(val) __BitScanForward64(val) -# define js_bitscan_clz64(val) __BitScanReverse64(val) -# define JS_HAS_BUILTIN_BITSCAN64 -#endif -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(3, 4, 0) -# define USE_BUILTIN_CTZ -#endif - -#elif defined(__clang__) - -#if __has_builtin(__builtin_ctz) -# define USE_BUILTIN_CTZ -#endif - -#endif - -#if defined(USE_BUILTIN_CTZ) -# define js_bitscan_ctz32(val) __builtin_ctz(val) -# define js_bitscan_clz32(val) __builtin_clz(val) -# define JS_HAS_BUILTIN_BITSCAN32 -# if (JS_BYTES_PER_WORD == 8) -# define js_bitscan_ctz64(val) __builtin_ctzll(val) -# define js_bitscan_clz64(val) __builtin_clzll(val) -# define JS_HAS_BUILTIN_BITSCAN64 -# endif - -# undef USE_BUILTIN_CTZ - -#endif - -/* -** Macro version of JS_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use intrinsic function or count-leading-zeros to calculate ceil(log2(_n)). - * The macro checks for "n <= 1" and not "n != 0" as js_bitscan_clz32(0) is - * undefined. - */ -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - unsigned int j_ = (unsigned int)(_n); \ - (_log2) = (j_ <= 1 ? 0 : 32 - js_bitscan_clz32(j_ - 1)); \ - JS_END_MACRO -#else -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -/* -** Macro version of JS_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use js_bitscan_clz32 or count-leading-zeros to calculate floor(log2(_n)). - * Since js_bitscan_clz32(0) is undefined, the macro set the loweset bit to 1 - * to ensure 0 result when _n == 0. - */ -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - (_log2) = 31 - js_bitscan_clz32(((unsigned int)(_n)) | 1); \ - JS_END_MACRO -#else -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -#if JS_BYTES_PER_WORD == 4 -# ifdef JS_HAS_BUILTIN_BITSCAN32 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz32(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#elif JS_BYTES_PER_WORD == 8 -# ifdef JS_HAS_BUILTIN_BITSCAN64 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz64(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#else -# error "NOT SUPPORTED" -#endif - -JS_END_EXTERN_C - -/* - * Internal function. - * Compute the log of the least power of 2 greater than or equal to n. This is - * a version of JS_CeilingLog2 that operates on unsigned integers with - * CPU-dependant size. - */ -#define JS_CEILING_LOG2W(n) ((n) <= 1 ? 0 : 1 + JS_FLOOR_LOG2W((n) - 1)) - -/* - * Internal function. - * Compute the log of the greatest power of 2 less than or equal to n. - * This is a version of JS_FloorLog2 that operates on unsigned integers with - * CPU-dependant size and requires that n != 0. - */ -static MOZ_ALWAYS_INLINE size_t -JS_FLOOR_LOG2W(size_t n) -{ - JS_ASSERT(n != 0); - return js_FloorLog2wImpl(n); -} - /* * JS_ROTATE_LEFT32 * @@ -552,7 +359,7 @@ template static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_malloc(numElems * sizeof(T)); } @@ -561,7 +368,7 @@ template static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_calloc(numElems * sizeof(T)); } @@ -595,175 +402,6 @@ SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) namespace js { -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables also need to - * be resized. - * - * The details of the optimization, and whether it's worth applying, vary from - * one type to the next. And while some constructor calls are moves, many really - * are copies, and can't be optimized this way. So we need: - * - * 1) a way for a particular invocation of a copy constructor to say that it's - * really a move, and that the value of the original isn't important - * afterwards (althought it must still be safe to destroy); and - * - * 2) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation. - * - * The Move(T &) function takes a reference to a T, and returns an MoveRef - * referring to the same value; that's 1). An MoveRef is simply a reference - * to a T, annotated to say that a copy constructor applied to it may move that - * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). - * - * So, where we might define a copy constructor for a class C like this: - * - * C(const C &rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(MoveRef rhs) { ... move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)) - * - * Note that MoveRef implicitly converts to T &, so you can pass an - * MoveRef to an ordinary copy constructor for a type that doesn't support a - * special move constructor, and you'll just get a copy. This means that - * templates can use Move whenever they know they won't use the original value - * any more, even if they're not sure whether the type at hand has a specialized - * move constructor. If it doesn't, the MoveRef will just convert to a T &, - * and the ordinary copy constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator, - * which runs this's destructor, and then applies the move constructor to - * *this's memory. A typical definition: - * - * C &operator=(MoveRef rhs) { - * this->~C(); - * new(this) C(rhs); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * This header file defines MoveRef and Move in the js namespace. It's up to - * individual containers to annotate moves as such, by calling Move; and it's up - * to individual types to define move constructors. - * - * One hint: if you're writing a move constructor where the type has members - * that should be moved themselves, it's much nicer to write this: - * - * C(MoveRef c) : x(c->x), y(c->y) { } - * - * than the equivalent: - * - * C(MoveRef c) { new(&x) X(c->x); new(&y) Y(c->y); } - * - * especially since GNU C++ fails to notice that this does indeed initialize x - * and y, which may matter if they're const. - */ -template -class MoveRef { - public: - typedef T Referent; - explicit MoveRef(T &t) : pointer(&t) { } - T &operator*() const { return *pointer; } - T *operator->() const { return pointer; } - operator T& () const { return *pointer; } - private: - T *pointer; -}; - -template -MoveRef Move(T &t) { return MoveRef(t); } - -template -MoveRef Move(const T &t) { return MoveRef(const_cast(t)); } - -/* Useful for implementing containers that assert non-reentrancy */ -class ReentrancyGuard -{ - /* ReentrancyGuard is not copyable. */ - ReentrancyGuard(const ReentrancyGuard &); - void operator=(const ReentrancyGuard &); - -#ifdef DEBUG - bool &entered; -#endif - public: - template -#ifdef DEBUG - ReentrancyGuard(T &obj) - : entered(obj.entered) -#else - ReentrancyGuard(T &/*obj*/) -#endif - { -#ifdef DEBUG - JS_ASSERT(!entered); - entered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - entered = false; -#endif - } -}; - -template -JS_ALWAYS_INLINE static void -Swap(T &t, T &u) -{ - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); -} - -/* - * Round x up to the nearest power of 2. This function assumes that the most - * significant bit of x is not set, which would lead to overflow. - */ -JS_ALWAYS_INLINE size_t -RoundUpPow2(size_t x) -{ - return size_t(1) << JS_CEILING_LOG2W(x); -} - /* Integral types for all hash functions. */ typedef uint32_t HashNumber; const unsigned HashNumberSizeBits = 32; @@ -845,11 +483,6 @@ inline bool IsPoisonedPtr(T *v) } -/* - * This is SpiderMonkey's equivalent to |nsMallocSizeOfFun|. - */ -typedef size_t(*JSMallocSizeOfFun)(const void *p); - /* sixgill annotation defines */ #ifndef HAVE_STATIC_ANNOTATIONS # define HAVE_STATIC_ANNOTATIONS @@ -891,4 +524,4 @@ typedef size_t(*JSMallocSizeOfFun)(const void *p); # define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) #endif /* HAVE_STATIC_ANNOTATIONS */ -#endif /* js_utility_h__ */ +#endif /* js_Utility_h */ diff --git a/external/spidermonkey/include/ios/js/Value.h b/external/spidermonkey/include/ios/js/Value.h index 2c7fa1a600..9b2c5dd6f9 100644 --- a/external/spidermonkey/include/ios/js/Value.h +++ b/external/spidermonkey/include/ios/js/Value.h @@ -6,8 +6,8 @@ /* JS::Value implementation. */ -#ifndef js_Value_h___ -#define js_Value_h___ +#ifndef js_Value_h +#define js_Value_h #include "mozilla/Attributes.h" #include "mozilla/FloatingPoint.h" @@ -53,7 +53,7 @@ namespace JS { class Value; } * nice symbolic type tags, however we can only do this when we can force the * underlying type of the enum to be the desired size. */ -#if defined(__cplusplus) && !defined(__SUNPRO_CC) && !defined(__xlC__) +#if !defined(__SUNPRO_CC) && !defined(__xlC__) #if defined(_MSC_VER) # define JS_ENUM_HEADER(id, type) enum id : type @@ -132,7 +132,7 @@ JS_STATIC_ASSERT(sizeof(JSValueShiftedTag) == sizeof(uint64_t)); #endif -#else /* defined(__cplusplus) */ +#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ typedef uint8_t JSValueType; #define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) @@ -180,7 +180,7 @@ typedef uint64_t JSValueShiftedTag; #define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) #endif /* JS_BITS_PER_WORD */ -#endif /* defined(__cplusplus) && !defined(__SUNPRO_CC) */ +#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ #define JSVAL_LOWER_INCL_TYPE_OF_OBJ_OR_NULL_SET JSVAL_TYPE_NULL #define JSVAL_UPPER_EXCL_TYPE_OF_PRIMITIVE_SET JSVAL_TYPE_OBJECT @@ -265,7 +265,7 @@ typedef union jsval_layout typedef union jsval_layout { uint64_t asBits; -#if (!defined(_WIN64) && defined(__cplusplus)) +#if !defined(_WIN64) /* MSVC does not pack these correctly :-( */ struct { uint64_t payload47 : 47; @@ -321,7 +321,6 @@ typedef union jsval_layout int32_t i32; uint32_t u32; JSWhyMagic why; - uintptr_t word; } payload; } s; double asDouble; @@ -803,22 +802,31 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ -static inline double -JS_CANONICALIZE_NAN(double d) -{ - if (MOZ_UNLIKELY(d != d)) { - jsval_layout l; - l.asBits = 0x7FF8000000000000LL; - return l.asDouble; - } - return d; -} - static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +/** + * Returns a generic quiet NaN value, with all payload bits set to zero. + * + * Among other properties, this NaN's bit pattern conforms to JS::Value's + * bit pattern restrictions. + */ +static MOZ_ALWAYS_INLINE double +GenericNaN() +{ + return mozilla::SpecificNaN(0, 0x8000000000000ULL); +} + +static inline double +CanonicalizeNaN(double d) +{ + if (MOZ_UNLIKELY(mozilla::IsNaN(d))) + return GenericNaN(); + return d; +} + /* * JS::Value is the interface for a single JavaScript Engine value. A few * general notes on JS::Value: @@ -1393,22 +1401,35 @@ SameType(const Value &lhs, const Value &rhs) /************************************************************************/ +#ifdef JSGC_GENERATIONAL +namespace JS { +JS_PUBLIC_API(void) HeapValuePostBarrier(Value *valuep); +JS_PUBLIC_API(void) HeapValueRelocate(Value *valuep); +} +#endif + namespace js { -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } }; -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } + static bool needsPostBarrier(const JS::Value &v) { return v.isMarkable(); } +#ifdef JSGC_GENERATIONAL + static void postBarrier(JS::Value *v) { JS::HeapValuePostBarrier(v); } + static void relocate(JS::Value *v) { JS::HeapValueRelocate(v); } +#endif }; +template class UnbarrieredMutableValueOperations; template class MutableValueOperations; /* @@ -1420,7 +1441,9 @@ template class MutableValueOperations; template class ValueOperations { + friend class UnbarrieredMutableValueOperations; friend class MutableValueOperations; + const JS::Value * value() const { return static_cast(this)->extract(); } public: @@ -1453,19 +1476,22 @@ class ValueOperations void *toGCThing() const { return value()->toGCThing(); } JSValueType extractNonDoubleType() const { return value()->extractNonDoubleType(); } + uint32_t toPrivateUint32() const { return value()->toPrivateUint32(); } JSWhyMagic whyMagic() const { return value()->whyMagic(); } }; /* - * A class designed for CRTP use in implementing the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible extractMutable() and extract() - * methods returning the const Value* and Value* abstracted by Outer. + * A class designed for CRTP use in implementing the mutating parts of the Value + * interface in Value-like classes that don't need post barriers. Outer must be + * a class inheriting UnbarrieredMutableValueOperations with visible + * extractMutable() and extract() methods returning the const Value* and Value* + * abstracted by Outer. */ template -class MutableValueOperations : public ValueOperations +class UnbarrieredMutableValueOperations : public ValueOperations { + friend class MutableValueOperations; JS::Value * value() { return static_cast(this)->extractMutable(); } public: @@ -1473,14 +1499,66 @@ class MutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } - void setString(JSString *str) { value()->setString(str); } - void setString(const JS::Anchor &str) { value()->setString(str); } - void setObject(JSObject &obj) { value()->setObject(obj); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } bool setNumber(double d) { return value()->setNumber(d); } - void setObjectOrNull(JSObject *arg) { value()->setObjectOrNull(arg); } +}; + +/* + * A class designed for CRTP use in implementing all the mutating parts of the + * Value interface in Value-like classes. Outer must be a class inheriting + * MutableValueOperations with visible extractMutable() and extract() + * methods returning the const Value* and Value* abstracted by Outer. + */ +template +class MutableValueOperations : public UnbarrieredMutableValueOperations +{ + public: + void setString(JSString *str) { this->value()->setString(str); } + void setString(const JS::Anchor &str) { this->value()->setString(str); } + void setObject(JSObject &obj) { this->value()->setObject(obj); } + void setObjectOrNull(JSObject *arg) { this->value()->setObjectOrNull(arg); } +}; + +/* + * Augment the generic Heap interface when T = Value with + * type-querying, value-extracting, and mutating operations. + */ +template <> +class HeapBase : public UnbarrieredMutableValueOperations > +{ + typedef JS::Heap Outer; + + friend class ValueOperations; + friend class UnbarrieredMutableValueOperations; + + const JS::Value * extract() const { return static_cast(this)->address(); } + JS::Value * extractMutable() { return static_cast(this)->unsafeGet(); } + + /* + * Setters that potentially change the value to a GC thing from a non-GC + * thing must call JS::Heap::set() to trigger the post barrier. + * + * Changing from a GC thing to a non-GC thing value will leave the heap + * value in the store buffer, but it will be ingored so this is not a + * problem. + */ + void setBarriered(const JS::Value &v) { + static_cast *>(this)->set(v); + } + + public: + void setString(JSString *str) { setBarriered(JS::StringValue(str)); } + void setString(const JS::Anchor &str) { setBarriered(JS::StringValue(str.get())); } + void setObject(JSObject &obj) { setBarriered(JS::ObjectValue(obj)); } + + void setObjectOrNull(JSObject *arg) { + if (arg) + setObject(*arg); + else + setNull(); + } }; /* @@ -1508,6 +1586,7 @@ class MutableHandleBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1526,6 +1605,7 @@ class RootedBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1574,12 +1654,12 @@ inline Anchor::~Anchor() namespace detail { struct ValueAlignmentTester { char c; JS::Value v; }; -MOZ_STATIC_ASSERT(sizeof(ValueAlignmentTester) == 16, - "JS::Value must be 16-byte-aligned"); +static_assert(sizeof(ValueAlignmentTester) == 16, + "JS::Value must be 16-byte-aligned"); struct LayoutAlignmentTester { char c; jsval_layout l; }; -MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, - "jsval_layout must be 16-byte-aligned"); +static_assert(sizeof(LayoutAlignmentTester) == 16, + "jsval_layout must be 16-byte-aligned"); } // namespace detail #endif /* DEBUG */ @@ -1593,8 +1673,8 @@ MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, */ typedef JS::Value jsval; -MOZ_STATIC_ASSERT(sizeof(jsval_layout) == sizeof(JS::Value), - "jsval_layout and JS::Value must have identical layouts"); +static_assert(sizeof(jsval_layout) == sizeof(JS::Value), + "jsval_layout and JS::Value must have identical layouts"); /************************************************************************/ @@ -1762,4 +1842,4 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } -#endif /* js_Value_h___ */ +#endif /* js_Value_h */ diff --git a/external/spidermonkey/include/ios/js/Vector.h b/external/spidermonkey/include/ios/js/Vector.h index 5f40dd634b..b14d75c758 100644 --- a/external/spidermonkey/include/ios/js/Vector.h +++ b/external/spidermonkey/include/ios/js/Vector.h @@ -4,14 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsvector_h_ -#define jsvector_h_ +#ifndef js_Vector_h +#define js_Vector_h -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "TemplateLib.h" -#include "Utility.h" +#include "mozilla/Vector.h" /* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ #ifdef _MSC_VER @@ -23,1085 +19,48 @@ namespace js { class TempAllocPolicy; -template +// using Vector = mozilla::Vector; +// +// ...and get rid of all the CRTP madness in mozilla::Vector(Base). But we +// can't because compiler support's not up to snuff. (Template aliases are in +// gcc 4.7 and clang 3.0 and are expected to be in MSVC 2013.) Instead, have a +// completely separate class inheriting from mozilla::Vector, and throw CRTP at +// the problem til things work. +// +// This workaround presents a couple issues. First, because js::Vector is a +// distinct type from mozilla::Vector, overload resolution, method calls, etc. +// are affected. *Hopefully* this won't be too bad in practice. (A bunch of +// places had to be fixed when mozilla::Vector was introduced, but it wasn't a +// crazy number.) Second, mozilla::Vector's interface has to be made subclass- +// ready via CRTP -- or rather, via mozilla::VectorBase, which basically no one +// should use. :-) Third, we have to redefine the constructors and the non- +// inherited operators. Blech. Happily there aren't too many of these, so it +// isn't the end of the world. + +template -class Vector; - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that cap*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring - * this. - */ -template -static bool CapacityHasExcessSpace(size_t cap) +class Vector + : public mozilla::VectorBase > { - size_t size = cap * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* Destroys constructed objects in the range [begin, end). */ - static inline void destroy(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - p->~T(); - } - - /* Constructs objects in the uninitialized range [begin, end). */ - static inline void initialize(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - /* - * Copy-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(*p); - } - - /* - * Move-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(Move(*p)); - } - - /* - * Copy-constructs objects in the uninitialized range [dst, dst+n) from the - * same object u. - */ - template - static inline void copyConstructN(T *dst, size_t n, const U &u) { - for (T *end = dst + n; dst != end; ++dst) - new(dst) T(u); - } - - /* - * Grows the given buffer to have capacity newCap, preserving the objects - * constructed in the range [begin, end) and updating v. Assumes that (1) - * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will - * not overflow. - */ - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); - if (!newbuf) - return false; - for (T *dst = newbuf, *src = v.beginNoCheck(); src != v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); - VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); - v.free_(v.mBegin); - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - static inline void destroy(T *, T *) {} - - static inline void initialize(T *begin, T *end) { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(begin, 0, sizeof(T) * (end-begin)); - */ - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); - */ - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - *dst = *p; - } - - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - copyConstruct(dst, srcbeg, srcend); - } - - static inline void copyConstructN(T *dst, size_t n, const T &t) { - for (T *p = dst, *end = dst + n; p != end; ++p) - *p = t; - } - - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - size_t oldSize = sizeof(T) * v.mCapacity; - size_t newSize = sizeof(T) * newCap; - T *newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); - if (!newbuf) - return false; - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * JS-friendly, STL-like container providing a short-lived, dynamic buffer. - * Vector calls the constructors/destructors of all elements stored in - * its internal buffer, so non-PODs may be safely used. Additionally, - * Vector will store the first N elements in-place before resorting to - * dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * N requirements: - * - any value, however, N is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in jsalloc.h (default js::TempAllocPolicy) - * - * N.B: Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object. - */ -template -class Vector : private AllocPolicy -{ - // typedef typename tl::StaticAssert::result>::result _; - - /* utilities */ - - static const bool sElemIsPod = mozilla::IsPod::value; - typedef VectorImpl Impl; - friend struct VectorImpl; - - bool growStorageBy(size_t incr); - bool convertToHeapStorage(size_t newCap); - - template inline bool growByImpl(size_t inc); - - /* magic constants */ - - static const int sMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are - * 0 inline elements. This allows us to compile when the definition - * of the element type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so - * in order to keep everything here, we use a dummy template - * parameter with partial specialization. - */ - template - struct ElemSize { - static const size_t result = sizeof(T); - }; - template - struct ElemSize<0, Dummy> { - static const size_t result = 1; - }; - - static const size_t sInlineCapacity = - tl::Min::result>::result; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t sInlineBytes = - tl::Max<1, sInlineCapacity * ElemSize::result>::result; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T *mBegin; - size_t mLength; /* Number of elements in the Vector. */ - size_t mCapacity; /* Max number of elements storable in the Vector without resizing. */ -#ifdef DEBUG - size_t mReserved; /* Max elements of reserved or used space in this vector. */ -#endif - - mozilla::AlignedStorage storage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool entered; -#endif - - Vector(const Vector &) MOZ_DELETE; - Vector &operator=(const Vector &) MOZ_DELETE; - - /* private accessors */ - - bool usingInlineStorage() const { - return mBegin == inlineStorage(); - } - - T *inlineStorage() const { - return (T *)storage.addr(); - } - - T *beginNoCheck() const { - return mBegin; - } - - T *endNoCheck() { - return mBegin + mLength; - } - - const T *endNoCheck() const { - return mBegin + mLength; - } - -#ifdef DEBUG - size_t reserved() const { - JS_ASSERT(mReserved <= mCapacity); - JS_ASSERT(mLength <= mReserved); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U u); - void internalAppendN(const T &t, size_t n); - template void internalAppend(const U *begin, size_t length); - template void internalAppend(const Vector &other); + typedef typename mozilla::VectorBase Base; public: - static const size_t sMaxInlineStorage = N; - - typedef T ElementType; - - Vector(AllocPolicy = AllocPolicy()); - Vector(MoveRef); /* Move constructor. */ - Vector &operator=(MoveRef); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy &allocPolicy() const { - return *this; + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector &operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); } - - AllocPolicy &allocPolicy() { - return *this; - } - - enum { InlineLength = N }; - - size_t length() const { - return mLength; - } - - bool empty() const { - return mLength == 0; - } - - size_t capacity() const { - return mCapacity; - } - - T *begin() { - JS_ASSERT(!entered); - return mBegin; - } - - const T *begin() const { - JS_ASSERT(!entered); - return mBegin; - } - - T *end() { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - const T *end() const { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - T &operator[](size_t i) { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - const T &operator[](size_t i) const { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - T &back() { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - const T &back() const { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - class Range { - friend class Vector; - T *cur_, *end_; - Range(T *cur, T *end) : cur_(cur), end_(end) {} - public: - Range() {} - bool empty() const { return cur_ == end_; } - size_t remain() const { return end_ - cur_; } - T &front() const { return *cur_; } - void popFront() { JS_ASSERT(!empty()); ++cur_; } - T popCopyFront() { JS_ASSERT(!empty()); return *cur_++; } - }; - - Range all() { - return Range(begin(), end()); - } - - /* mutators */ - - /* Given that the Vector is empty and has no inline storage, grow to |capacity|. */ - bool initCapacity(size_t request); - - /* If reserve(length() + N) succeeds, the N next appends are guaranteed to succeed. */ - bool reserve(size_t request); - - /* - * Destroy elements in the range [end() - incr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t incr); - - /* Grow the vector by incr elements. */ - bool growBy(size_t incr); - - /* Call shrinkBy or growBy based on whether newSize > length(). */ - bool resize(size_t newLength); - - /* Leave new elements as uninitialized memory. */ - bool growByUninitialized(size_t incr); - bool resizeUninitialized(size_t newLength); - - /* Shorthand for shrinkBy(length()). */ - void clear(); - - /* Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /* If true, appending |needed| elements will not call realloc(). */ - bool canAppendWithoutRealloc(size_t needed) const; - - /* - * Potentially fallible append operations. - * - * The function templates that take an unspecified type U require a - * const T & or a MoveRef. The MoveRef variants move their - * operands into the vector, instead of copying them. If they fail, the - * operand is left unmoved. - */ - template bool append(U t); - bool appendN(const T &t, size_t n); - template bool append(const U *begin, const U *end); - template bool append(const U *begin, size_t length); - template bool append(const Vector &other); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. - */ - template void infallibleAppend(const U &u) { - internalAppend(u); - } - void infallibleAppendN(const T &t, size_t n) { - internalAppendN(t, n); - } - template void infallibleAppend(const U *aBegin, const U *aEnd) { - internalAppend(aBegin, mozilla::PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U *aBegin, size_t aLength) { - internalAppend(aBegin, aLength); - } - template void infallibleAppend(const Vector &other) { - internalAppend(other); - } - - void popBack(); - - T popCopy(); - - /* - * Transfers ownership of the internal buffer used by Vector to the caller. - * After this call, the Vector is empty. Since the returned buffer may need - * to be allocated (if the elements are currently stored in-place), the - * call can fail, returning NULL. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - T *extractRawBuffer(); - - /* - * Transfer ownership of an array of objects into the Vector. - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T *p, size_t length); - - /* - * Places |val| at position |p|, shifting existing elements from |p| - * onward one position higher. On success, |p| should not be reused - * because it will be a dangling pointer if reallocation of the vector - * storage occurred; the return value should be used instead. On failure, - * NULL is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) - * - * - */ - T *insert(T *p, const T &val); - - /* - * Removes the element |t|, which must fall in the bounds [begin, end), - * shifting existing elements from |t + 1| onward one position lower. - */ - void erase(T *t); - - /* - * Measure the size of the Vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - /* - * Like sizeOfExcludingThis, but also measures the size of the Vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - void swap(Vector &other); }; -/* This does the re-entrancy check plus several other sanity checks. */ -#define REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - JS_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ - JS_ASSERT(reserved() <= mCapacity); \ - JS_ASSERT(mLength <= reserved()); \ - JS_ASSERT(mLength <= mCapacity) +} // namespace js -/* Vector Implementation */ - -template -JS_ALWAYS_INLINE -Vector::Vector(AllocPolicy ap) - : AllocPolicy(ap), mBegin((T *)storage.addr()), mLength(0), - mCapacity(sInlineCapacity) -#ifdef DEBUG - , mReserved(sInlineCapacity), entered(false) -#endif -{} - -/* Move constructor. */ -template -JS_ALWAYS_INLINE -Vector::Vector(MoveRef rhs) - : AllocPolicy(rhs) -#ifdef DEBUG - , entered(false) -#endif -{ - mLength = rhs->mLength; - mCapacity = rhs->mCapacity; -#ifdef DEBUG - mReserved = rhs->mReserved; -#endif - - if (rhs->usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = (T *)storage.addr(); - Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); - /* - * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = rhs->mBegin; - rhs->mBegin = (T *) rhs->storage.addr(); - rhs->mCapacity = sInlineCapacity; - rhs->mLength = 0; -#ifdef DEBUG - rhs->mReserved = sInlineCapacity; -#endif - } -} - -/* Move assignment. */ -template -JS_ALWAYS_INLINE -Vector & -Vector::operator=(MoveRef rhs) -{ - this->~Vector(); - new(this) Vector(rhs); - return *this; -} - -template -JS_ALWAYS_INLINE -Vector::~Vector() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); -} - -/* - * This function will create a new heap buffer with capacity newCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t newCap) -{ - JS_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); - if (!newBuf) - return false; - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = newCap; - return true; -} - -template -JS_NEVER_INLINE bool -Vector::growStorageBy(size_t incr) -{ - JS_ASSERT(mLength + incr > mCapacity); - JS_ASSERT_IF(!usingInlineStorage(), !CapacityHasExcessSpace(mCapacity)); - - /* - * When choosing a new capacity, its size should is as close to 2^N bytes - * as possible. 2^N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2^N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2^N request size. - */ - - size_t newCap; - - if (incr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::result; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength*4*sizeof(T) overflow? This condition limits a Vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. - * It also ensures that the ((char *)end() - (char *)begin()) does not - * overflow ptrdiff_t (see Bug 510319). - */ - if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::result) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is - * already as close to 2^N as sizeof(T) will allow. Just double the - * capacity, and then there might be space for one more element. - */ - newCap = mLength * 2; - if (CapacityHasExcessSpace(newCap)) - newCap += 1; - - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + incr; - - /* Did mLength+incr overflow? Will newCap*sizeof(T) overflow? */ - if (newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::result) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { - convert: - return convertToHeapStorage(newCap); - } - - grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t request) -{ - JS_ASSERT(empty()); - JS_ASSERT(usingInlineStorage()); - if (request == 0) - return true; - T *newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); - if (!newbuf) - return false; - mBegin = newbuf; - mCapacity = request; -#ifdef DEBUG - mReserved = request; -#endif - return true; -} - -template -inline bool -Vector::reserve(size_t request) -{ - REENTRANCY_GUARD_ET_AL; - if (request > mCapacity && !growStorageBy(request - mLength)) - return false; - -#ifdef DEBUG - if (request > mReserved) - mReserved = request; - JS_ASSERT(mLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(incr <= mLength); - Impl::destroy(endNoCheck() - incr, endNoCheck()); - mLength -= incr; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::growByImpl(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - if (incr > mCapacity - mLength && !growStorageBy(incr)) - return false; - - JS_ASSERT(mLength + incr <= mCapacity); - T *newend = endNoCheck() + incr; - if (InitNewElems) - Impl::initialize(endNoCheck(), newend); - mLength += incr; -#ifdef DEBUG - if (mLength > mReserved) - mReserved = mLength; -#endif - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::growBy(size_t incr) -{ - return growByImpl(incr); -} - -template -JS_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t incr) -{ - return growByImpl(incr); -} - -template -STATIC_POSTCONDITION(!return || ubound(this->begin()) >= newLength) -inline bool -Vector::resize(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growBy(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growByUninitialized(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -inline void -Vector::clear() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) - return; - - this->free_(beginNoCheck()); - mBegin = (T *)storage.addr(); - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t needed) const -{ - return mLength + needed <= mCapacity; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(U t) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity && !growStorageBy(1)) - return false; - -#ifdef DEBUG - if (mLength + 1 > mReserved) - mReserved = mLength + 1; -#endif - internalAppend(t); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(U u) -{ - JS_ASSERT(mLength + 1 <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - new(endNoCheck()) T(u); - ++mLength; -} - -template -JS_ALWAYS_INLINE bool -Vector::appendN(const T &t, size_t needed) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppendN(t, needed); - return true; -} - -template -JS_ALWAYS_INLINE void -Vector::internalAppendN(const T &t, size_t needed) -{ - JS_ASSERT(mLength + needed <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), needed, t); - mLength += needed; -} - -template -inline T * -Vector::insert(T *p, const T &val) -{ - JS_ASSERT(begin() <= p && p <= end()); - size_t pos = p - begin(); - JS_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(val)) - return NULL; - } else { - T oldBack = back(); - if (!append(oldBack)) /* Dup the last element. */ - return NULL; - for (size_t i = oldLength; i > pos; --i) - (*this)[i] = (*this)[i - 1]; - (*this)[pos] = val; - } - return begin() + pos; -} - -template -inline void -Vector::erase(T *it) -{ - JS_ASSERT(begin() <= it && it < end()); - while (it + 1 != end()) { - *it = *(it + 1); - ++it; - } - popBack(); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, const U *insEnd) -{ - REENTRANCY_GUARD_ET_AL; - size_t needed = mozilla::PointerRangeSize(insBegin, insEnd); - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppend(insBegin, needed); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(const U *insBegin, size_t insLength) -{ - JS_ASSERT(mLength + insLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); - mLength += insLength; -} - -template -template -inline bool -Vector::append(const Vector &other) -{ - return append(other.begin(), other.end()); -} - -template -template -inline void -Vector::internalAppend(const Vector &other) -{ - internalAppend(other.begin(), other.length()); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, size_t insLength) -{ - return this->append(insBegin, insBegin + insLength); -} - -template -JS_ALWAYS_INLINE void -Vector::popBack() -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -JS_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T * -Vector::extractRawBuffer() -{ - T *ret; - if (usingInlineStorage()) { - ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); - if (!ret) - return NULL; - Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - /* mBegin, mCapacity are unchanged. */ - mLength = 0; - } else { - ret = mBegin; - mBegin = (T *)storage.addr(); - mLength = 0; - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif - } - return ret; -} - -template -inline void -Vector::replaceRawBuffer(T *p, size_t aLength) -{ - REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); - - /* Take in the new buffer. */ - if (aLength <= sInlineCapacity) { - /* - * We convert to inline storage if possible, even though p might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = (T *)storage.addr(); - mLength = aLength; - mCapacity = sInlineCapacity; - Impl::moveConstruct(mBegin, p, p + aLength); - Impl::destroy(p, p + aLength); - this->free_(p); - } else { - mBegin = p; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); -} - -template -inline void -Vector::swap(Vector &other) -{ - // TODO Implement N != 0 - JS_STATIC_ASSERT(N == 0); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && other.usingInlineStorage()) { - other.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !other.usingInlineStorage()) { - mBegin = other.mBegin; - other.mBegin = other.inlineStorage(); - } else if (!usingInlineStorage() && !other.usingInlineStorage()) { - Swap(mBegin, other.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, other.mLength); - Swap(mCapacity, other.mCapacity); -#ifdef DEBUG - Swap(mReserved, other.mReserved); -#endif -} - -} /* namespace js */ - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* jsvector_h_ */ +#endif /* js_Vector_h */ diff --git a/external/spidermonkey/include/ios/jsalloc.h b/external/spidermonkey/include/ios/jsalloc.h index e7e64fc540..3abc4966d1 100644 --- a/external/spidermonkey/include/ios/jsalloc.h +++ b/external/spidermonkey/include/ios/jsalloc.h @@ -4,32 +4,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsalloc_h_ -#define jsalloc_h_ +/* JS allocation policies. */ + +#ifndef jsalloc_h +#define jsalloc_h + +#include "mozilla/AllocPolicy.h" #include "js/Utility.h" -#include "jstypes.h" struct JSContext; namespace js { -/* - * Allocation policies. These model the concept: - * - public copy constructor, assignment, destructor - * - void *malloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *calloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *realloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * The *used* bytes of the previous buffer is passed in - * (rather than the old allocation size), in addition to - * the *new* allocation size requested. - * - void free_(void *) - * - reportAllocOverflow() - * Called on overflow before the container returns NULL. - */ +class ContextFriendFields; /* Policy for using system memory functions and doing no error reporting. */ class SystemAllocPolicy @@ -53,7 +41,7 @@ class SystemAllocPolicy */ class TempAllocPolicy { - JSContext *const cx_; + ContextFriendFields *const cx_; /* * Non-inline helper to call JSRuntime::onOutOfMemory with minimal @@ -62,11 +50,8 @@ class TempAllocPolicy JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes); public: - TempAllocPolicy(JSContext *cx) : cx_(cx) {} - - JSContext *context() const { - return cx_; - } + TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :( + TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {} void *malloc_(size_t bytes) { void *p = js_malloc(bytes); @@ -98,4 +83,4 @@ class TempAllocPolicy } /* namespace js */ -#endif /* jsalloc_h_ */ +#endif /* jsalloc_h */ diff --git a/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id index db9dbac6b4..27b6bbed78 100644 --- a/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -0ec74a6f5f2aa9bbaa6a8cbf6e2ae95ec7c4ee43 \ No newline at end of file +e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file diff --git a/external/spidermonkey/include/ios/jsclass.h b/external/spidermonkey/include/ios/jsclass.h index c9b53c7679..def641715d 100644 --- a/external/spidermonkey/include/ios/jsclass.h +++ b/external/spidermonkey/include/ios/jsclass.h @@ -4,14 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclass_h__ -#define jsclass_h__ +#ifndef jsclass_h +#define jsclass_h /* * A JSClass acts as a vtable for JS objects that allows JSAPI clients to * control various aspects of the behavior of an object like property lookup. * js::Class is an engine-private extension that allows more control over * object behavior and, e.g., allows custom slow layout. */ + #include "jsapi.h" #include "jsprvtd.h" @@ -21,6 +22,10 @@ class PropertyName; class SpecialId; class PropertyId; +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; + static JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); @@ -195,7 +200,7 @@ typedef void const char *name; \ uint32_t flags; \ \ - /* Mandatory non-null function pointer members. */ \ + /* Mandatory function pointer members. */ \ JSPropertyOp addProperty; \ JSDeletePropertyOp delProperty; \ JSPropertyOp getProperty; \ @@ -203,9 +208,9 @@ typedef void JSEnumerateOp enumerate; \ JSResolveOp resolve; \ JSConvertOp convert; \ - FinalizeOp finalize; \ \ - /* Optionally non-null members start here. */ \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ JSCheckAccessOp checkAccess; \ JSNative call; \ JSHasInstanceOp hasInstance; \ @@ -214,7 +219,7 @@ typedef void /* * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to padd js::Class to match the size of JSClass; + * we have to pad js::Class to match the size of JSClass. */ struct ClassSizeMeasurement { @@ -312,8 +317,9 @@ struct Class return flags & JSCLASS_EMULATES_UNDEFINED; } - /* Defined in jsfuninlines.h */ - inline bool isCallable() const; + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } static size_t offsetOfFlags() { return offsetof(Class, flags); } }; @@ -387,7 +393,7 @@ IsPoisonedSpecialId(js::SpecialId iden) return false; } -template <> struct RootMethods +template <> struct GCMethods { static SpecialId initial() { return SpecialId(); } static ThingRootKind kind() { return THING_ROOT_ID; } @@ -396,4 +402,4 @@ template <> struct RootMethods } /* namespace js */ -#endif /* jsclass_h__ */ +#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/ios/jsclist.h b/external/spidermonkey/include/ios/jsclist.h index 8782307fa4..23da9b8cd5 100644 --- a/external/spidermonkey/include/ios/jsclist.h +++ b/external/spidermonkey/include/ios/jsclist.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclist_h___ -#define jsclist_h___ +#ifndef jsclist_h +#define jsclist_h #include "jstypes.h" @@ -104,4 +104,4 @@ typedef struct JSCListStr { #define JS_INIT_STATIC_CLIST(_l) \ {(_l), (_l)} -#endif /* jsclist_h___ */ +#endif /* jsclist_h */ diff --git a/external/spidermonkey/include/ios/jscpucfg.h b/external/spidermonkey/include/ios/jscpucfg.h index 6bb62b420f..c79bd7ad14 100644 --- a/external/spidermonkey/include/ios/jscpucfg.h +++ b/external/spidermonkey/include/ios/jscpucfg.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_cpucfg___ -#define js_cpucfg___ +#ifndef jscpucfg_h +#define jscpucfg_h #define JS_HAVE_LONG_LONG @@ -114,4 +114,4 @@ # endif #endif -#endif /* js_cpucfg___ */ +#endif /* jscpucfg_h */ diff --git a/external/spidermonkey/include/ios/jsdbgapi.h b/external/spidermonkey/include/ios/jsdbgapi.h index 4907d913a0..0ce7101337 100644 --- a/external/spidermonkey/include/ios/jsdbgapi.h +++ b/external/spidermonkey/include/ios/jsdbgapi.h @@ -4,12 +4,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsdbgapi_h___ -#define jsdbgapi_h___ +#ifndef jsdbgapi_h +#define jsdbgapi_h /* * JS debugger API. */ -#include "jsapi.h" + #include "jsprvtd.h" namespace JS { @@ -111,7 +111,7 @@ JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, JSTrapHandler *handlerp, jsval *closurep); extern JS_PUBLIC_API(void) -JS_ClearScriptTraps(JSContext *cx, JSScript *script); +JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); @@ -224,12 +224,6 @@ JS_GetScriptLineExtent(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(JSVersion) JS_GetScriptVersion(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(bool) -JS_GetScriptUserBit(JSScript *script); - -extern JS_PUBLIC_API(void) -JS_SetScriptUserBit(JSScript *script, bool b); - extern JS_PUBLIC_API(bool) JS_GetScriptIsSelfHosted(JSScript *script); @@ -433,9 +427,6 @@ JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ -extern JS_FRIEND_API(void) -js_RevertVersion(JSContext *cx); - extern JS_PUBLIC_API(const JSDebugHooks *) JS_GetGlobalDebugHooks(JSRuntime *rt); @@ -465,4 +456,4 @@ JS_DumpCompartmentPCCounts(JSContext *cx); extern JS_FRIEND_API(JSBool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h___ */ +#endif /* jsdbgapi_h */ diff --git a/external/spidermonkey/include/ios/jsdhash.h b/external/spidermonkey/include/ios/jsdhash.h deleted file mode 100644 index 1f7830fd2b..0000000000 --- a/external/spidermonkey/include/ios/jsdhash.h +++ /dev/null @@ -1,612 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsdhash_h___ -#define jsdhash_h___ - -/* - * Double hashing, a la Knuth 6. - * - * Try to keep this file in sync with xpcom/glue/pldhash.h. - */ -#include "jstypes.h" -#include "jsutil.h" - -#if defined(__GNUC__) && defined(__i386__) && !defined(XP_OS2) -#define JS_DHASH_FASTCALL __attribute__ ((regparm (3),stdcall)) -#elif defined(XP_WIN) -#define JS_DHASH_FASTCALL __fastcall -#else -#define JS_DHASH_FASTCALL -#endif - -#ifdef DEBUG_XXXbrendan -#define JS_DHASHMETER 1 -#endif - -/* Table size limit, do not equal or exceed (see min&maxAlphaFrac, below). */ -#undef JS_DHASH_SIZE_LIMIT -#define JS_DHASH_SIZE_LIMIT JS_BIT(24) - -/* Minimum table size, or gross entry count (net is at most .75 loaded). */ -#ifndef JS_DHASH_MIN_SIZE -#define JS_DHASH_MIN_SIZE 16 -#elif (JS_DHASH_MIN_SIZE & (JS_DHASH_MIN_SIZE - 1)) != 0 -#error "JS_DHASH_MIN_SIZE must be a power of two!" -#endif - -/* - * Multiplicative hash uses an unsigned 32 bit integer and the golden ratio, - * expressed as a fixed-point 32-bit fraction. - */ -#define JS_DHASH_BITS 32 -#define JS_DHASH_GOLDEN_RATIO 0x9E3779B9U - -/* Primitive and forward-struct typedefs. */ -typedef uint32_t JSDHashNumber; -typedef struct JSDHashEntryHdr JSDHashEntryHdr; -typedef struct JSDHashEntryStub JSDHashEntryStub; -typedef struct JSDHashTable JSDHashTable; -typedef struct JSDHashTableOps JSDHashTableOps; - -/* - * Table entry header structure. - * - * In order to allow in-line allocation of key and value, we do not declare - * either here. Instead, the API uses const void *key as a formal parameter. - * The key need not be stored in the entry; it may be part of the value, but - * need not be stored at all. - * - * Callback types are defined below and grouped into the JSDHashTableOps - * structure, for single static initialization per hash table sub-type. - * - * Each hash table sub-type should nest the JSDHashEntryHdr structure at the - * front of its particular entry type. The keyHash member contains the result - * of multiplying the hash code returned from the hashKey callback (see below) - * by JS_DHASH_GOLDEN_RATIO, then constraining the result to avoid the magic 0 - * and 1 values. The stored keyHash value is table size invariant, and it is - * maintained automatically by JS_DHashTableOperate -- users should never set - * it, and its only uses should be via the entry macros below. - * - * The JS_DHASH_ENTRY_IS_LIVE macro tests whether entry is neither free nor - * removed. An entry may be either busy or free; if busy, it may be live or - * removed. Consumers of this API should not access members of entries that - * are not live. - * - * However, use JS_DHASH_ENTRY_IS_BUSY for faster liveness testing of entries - * returned by JS_DHashTableOperate, as JS_DHashTableOperate never returns a - * non-live, busy (i.e., removed) entry pointer to its caller. See below for - * more details on JS_DHashTableOperate's calling rules. - */ -struct JSDHashEntryHdr { - JSDHashNumber keyHash; /* every entry must begin like this */ -}; - -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_FREE(JSDHashEntryHdr* entry) -{ - return entry->keyHash == 0; -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_BUSY(JSDHashEntryHdr* entry) -{ - return !JS_DHASH_ENTRY_IS_FREE(entry); -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_LIVE(JSDHashEntryHdr* entry) -{ - return entry->keyHash >= 2; -} - -/* - * A JSDHashTable is currently 8 words (without the JS_DHASHMETER overhead) - * on most architectures, and may be allocated on the stack or within another - * structure or class (see below for the Init and Finish functions to use). - * - * To decide whether to use double hashing vs. chaining, we need to develop a - * trade-off relation, as follows: - * - * Let alpha be the load factor, esize the entry size in words, count the - * entry count, and pow2 the power-of-two table size in entries. - * - * (JSDHashTable overhead) > (JSHashTable overhead) - * (unused table entry space) > (malloc and .next overhead per entry) + - * (buckets overhead) - * (1 - alpha) * esize * pow2 > 2 * count + pow2 - * - * Notice that alpha is by definition (count / pow2): - * - * (1 - alpha) * esize * pow2 > 2 * alpha * pow2 + pow2 - * (1 - alpha) * esize > 2 * alpha + 1 - * - * esize > (1 + 2 * alpha) / (1 - alpha) - * - * This assumes both tables must keep keyHash, key, and value for each entry, - * where key and value point to separately allocated strings or structures. - * If key and value can be combined into one pointer, then the trade-off is: - * - * esize > (1 + 3 * alpha) / (1 - alpha) - * - * If the entry value can be a subtype of JSDHashEntryHdr, rather than a type - * that must be allocated separately and referenced by an entry.value pointer - * member, and provided key's allocation can be fused with its entry's, then - * k (the words wasted per entry with chaining) is 4. - * - * To see these curves, feed gnuplot input like so: - * - * gnuplot> f(x,k) = (1 + k * x) / (1 - x) - * gnuplot> plot [0:.75] f(x,2), f(x,3), f(x,4) - * - * For k of 2 and a well-loaded table (alpha > .5), esize must be more than 4 - * words for chaining to be more space-efficient than double hashing. - * - * Solving for alpha helps us decide when to shrink an underloaded table: - * - * esize > (1 + k * alpha) / (1 - alpha) - * esize - alpha * esize > 1 + k * alpha - * esize - 1 > (k + esize) * alpha - * (esize - 1) / (k + esize) > alpha - * - * alpha < (esize - 1) / (esize + k) - * - * Therefore double hashing should keep alpha >= (esize - 1) / (esize + k), - * assuming esize is not too large (in which case, chaining should probably be - * used for any alpha). For esize=2 and k=3, we want alpha >= .2; for esize=3 - * and k=2, we want alpha >= .4. For k=4, esize could be 6, and alpha >= .5 - * would still obtain. See the JS_DHASH_MIN_ALPHA macro further below. - * - * The current implementation uses a configurable lower bound on alpha, which - * defaults to .25, when deciding to shrink the table (while still respecting - * JS_DHASH_MIN_SIZE). - * - * Note a qualitative difference between chaining and double hashing: under - * chaining, entry addresses are stable across table shrinks and grows. With - * double hashing, you can't safely hold an entry pointer and use it after an - * ADD or REMOVE operation, unless you sample table->generation before adding - * or removing, and compare the sample after, dereferencing the entry pointer - * only if table->generation has not changed. - * - * The moral of this story: there is no one-size-fits-all hash table scheme, - * but for small table entry size, and assuming entry address stability is not - * required, double hashing wins. - */ -struct JSDHashTable { - const JSDHashTableOps *ops; /* virtual operations, see below */ - void *data; /* ops- and instance-specific data */ - int16_t hashShift; /* multiplicative hash shift */ - uint8_t maxAlphaFrac; /* 8-bit fixed point max alpha */ - uint8_t minAlphaFrac; /* 8-bit fixed point min alpha */ - uint32_t entrySize; /* number of bytes in an entry */ - uint32_t entryCount; /* number of entries in table */ - uint32_t removedCount; /* removed entry sentinels in table */ - uint32_t generation; /* entry storage generation number */ - char *entryStore; /* entry storage */ -#ifdef JS_DHASHMETER - struct JSDHashStats { - uint32_t searches; /* total number of table searches */ - uint32_t steps; /* hash chain links traversed */ - uint32_t hits; /* searches that found key */ - uint32_t misses; /* searches that didn't find key */ - uint32_t lookups; /* number of JS_DHASH_LOOKUPs */ - uint32_t addMisses; /* adds that miss, and do work */ - uint32_t addOverRemoved; /* adds that recycled a removed entry */ - uint32_t addHits; /* adds that hit an existing entry */ - uint32_t addFailures; /* out-of-memory during add growth */ - uint32_t removeHits; /* removes that hit, and do work */ - uint32_t removeMisses; /* useless removes that miss */ - uint32_t removeFrees; /* removes that freed entry directly */ - uint32_t removeEnums; /* removes done by Enumerate */ - uint32_t grows; /* table expansions */ - uint32_t shrinks; /* table contractions */ - uint32_t compresses; /* table compressions */ - uint32_t enumShrinks; /* contractions after Enumerate */ - } stats; -#endif -}; - -/* - * Size in entries (gross, not net of free and removed sentinels) for table. - * We store hashShift rather than sizeLog2 to optimize the collision-free case - * in SearchTable. - */ -#define JS_DHASH_TABLE_SIZE(table) JS_BIT(JS_DHASH_BITS - (table)->hashShift) - -/* - * Table space at entryStore is allocated and freed using these callbacks. - * The allocator should return null on error only (not if called with nbytes - * equal to 0; but note that jsdhash.c code will never call with 0 nbytes). - */ -typedef void * -(* JSDHashAllocTable)(JSDHashTable *table, uint32_t nbytes); - -typedef void -(* JSDHashFreeTable) (JSDHashTable *table, void *ptr); - -/* - * Compute the hash code for a given key to be looked up, added, or removed - * from table. A hash code may have any JSDHashNumber value. - */ -typedef JSDHashNumber -(* JSDHashHashKey) (JSDHashTable *table, const void *key); - -/* - * Compare the key identifying entry in table with the provided key parameter. - * Return JS_TRUE if keys match, JS_FALSE otherwise. - */ -typedef JSBool -(* JSDHashMatchEntry)(JSDHashTable *table, const JSDHashEntryHdr *entry, - const void *key); - -/* - * Copy the data starting at from to the new entry storage at to. Do not add - * reference counts for any strong references in the entry, however, as this - * is a "move" operation: the old entry storage at from will be freed without - * any reference-decrementing callback shortly. - */ -typedef void -(* JSDHashMoveEntry)(JSDHashTable *table, const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -/* - * Clear the entry and drop any strong references it holds. This callback is - * invoked during a JS_DHASH_REMOVE operation (see below for operation codes), - * but only if the given key is found in the table. - */ -typedef void -(* JSDHashClearEntry)(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Called when a table (whether allocated dynamically by itself, or nested in - * a larger structure, or allocated on the stack) is finished. This callback - * allows table->ops-specific code to finalize table->data. - */ -typedef void -(* JSDHashFinalize) (JSDHashTable *table); - -/* - * Initialize a new entry, apart from keyHash. This function is called when - * JS_DHashTableOperate's JS_DHASH_ADD case finds no existing entry for the - * given key, and must add a new one. At that point, entry->keyHash is not - * set yet, to avoid claiming the last free entry in a severely overloaded - * table. - */ -typedef JSBool -(* JSDHashInitEntry)(JSDHashTable *table, JSDHashEntryHdr *entry, - const void *key); - -/* - * Finally, the "vtable" structure for JSDHashTable. The first eight hooks - * must be provided by implementations; they're called unconditionally by the - * generic jsdhash.c code. Hooks after these may be null. - * - * Summary of allocation-related hook usage with C++ placement new emphasis: - * allocTable Allocate raw bytes with malloc, no ctors run. - * freeTable Free raw bytes with free, no dtors run. - * initEntry Call placement new using default key-based ctor. - * Return JS_TRUE on success, JS_FALSE on error. - * moveEntry Call placement new using copy ctor, run dtor on old - * entry storage. - * clearEntry Run dtor on entry. - * finalize Stub unless table->data was initialized and needs to - * be finalized. - * - * Note the reason why initEntry is optional: the default hooks (stubs) clear - * entry storage: On successful JS_DHashTableOperate(tbl, key, JS_DHASH_ADD), - * the returned entry pointer addresses an entry struct whose keyHash member - * has been set non-zero, but all other entry members are still clear (null). - * JS_DHASH_ADD callers can test such members to see whether the entry was - * newly created by the JS_DHASH_ADD call that just succeeded. If placement - * new or similar initialization is required, define an initEntry hook. Of - * course, the clearEntry hook must zero or null appropriately. - * - * XXX assumes 0 is null for pointer types. - */ -struct JSDHashTableOps { - /* Mandatory hooks. All implementations must provide these. */ - JSDHashAllocTable allocTable; - JSDHashFreeTable freeTable; - JSDHashHashKey hashKey; - JSDHashMatchEntry matchEntry; - JSDHashMoveEntry moveEntry; - JSDHashClearEntry clearEntry; - JSDHashFinalize finalize; - - /* Optional hooks start here. If null, these are not called. */ - JSDHashInitEntry initEntry; -}; - -/* - * Default implementations for the above ops. - */ -extern JS_PUBLIC_API(void *) -JS_DHashAllocTable(JSDHashTable *table, uint32_t nbytes); - -extern JS_PUBLIC_API(void) -JS_DHashFreeTable(JSDHashTable *table, void *ptr); - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashStringKey(JSDHashTable *table, const void *key); - -/* A minimal entry contains a keyHash header and a void key pointer. */ -struct JSDHashEntryStub { - JSDHashEntryHdr hdr; - const void *key; -}; - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashVoidPtrKeyStub(JSDHashTable *table, const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchStringKey(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(void) -JS_DHashMoveEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -extern JS_PUBLIC_API(void) -JS_DHashClearEntryStub(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFreeStringKey(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFinalizeStub(JSDHashTable *table); - -/* - * If you use JSDHashEntryStub or a subclass of it as your entry struct, and - * if your entries move via memcpy and clear via memset(0), you can use these - * stub operations. - */ -extern JS_PUBLIC_API(const JSDHashTableOps *) -JS_DHashGetStubOps(void); - -/* - * Dynamically allocate a new JSDHashTable using malloc, initialize it using - * JS_DHashTableInit, and return its address. Return null on malloc failure. - * Note that the entry storage at table->entryStore will be allocated using - * the ops->allocTable callback. - */ -extern JS_PUBLIC_API(JSDHashTable *) -JS_NewDHashTable(const JSDHashTableOps *ops, void *data, uint32_t entrySize, - uint32_t capacity); - -/* - * Finalize table's data, free its entry storage (via table->ops->freeTable), - * and return the memory starting at table to the malloc heap. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableDestroy(JSDHashTable *table); - -/* - * Initialize table with ops, data, entrySize, and capacity. Capacity is a - * guess for the smallest table size at which the table will usually be less - * than 75% loaded (the table will grow or shrink as needed; capacity serves - * only to avoid inevitable early growth from JS_DHASH_MIN_SIZE). - */ -extern JS_PUBLIC_API(JSBool) -JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data, - uint32_t entrySize, uint32_t capacity); - -/* - * Set maximum and minimum alpha for table. The defaults are 0.75 and .25. - * maxAlpha must be in [0.5, 0.9375] for the default JS_DHASH_MIN_SIZE; or if - * MinSize=JS_DHASH_MIN_SIZE <= 256, in [0.5, (float)(MinSize-1)/MinSize]; or - * else in [0.5, 255.0/256]. minAlpha must be in [0, maxAlpha / 2), so that - * we don't shrink on the very next remove after growing a table upon adding - * an entry that brings entryCount past maxAlpha * tableSize. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableSetAlphaBounds(JSDHashTable *table, - float maxAlpha, - float minAlpha); - -/* - * Call this macro with k, the number of pointer-sized words wasted per entry - * under chaining, to compute the minimum alpha at which double hashing still - * beats chaining. - */ -#define JS_DHASH_MIN_ALPHA(table, k) \ - ((float)((table)->entrySize / sizeof(void *) - 1) \ - / ((table)->entrySize / sizeof(void *) + (k))) - -/* - * Default max/min alpha, and macros to compute the value for the |capacity| - * parameter to JS_NewDHashTable and JS_DHashTableInit, given default or any - * max alpha, such that adding entryCount entries right after initializing the - * table will not require a reallocation (so JS_DHASH_ADD can't fail for those - * JS_DHashTableOperate calls). - * - * NB: JS_DHASH_CAP is a helper macro meant for use only in JS_DHASH_CAPACITY. - * Don't use it directly! - */ -#define JS_DHASH_DEFAULT_MAX_ALPHA 0.75 -#define JS_DHASH_DEFAULT_MIN_ALPHA 0.25 - -#define JS_DHASH_CAP(entryCount, maxAlpha) \ - ((uint32_t)((double)(entryCount) / (maxAlpha))) - -#define JS_DHASH_CAPACITY(entryCount, maxAlpha) \ - (JS_DHASH_CAP(entryCount, maxAlpha) + \ - (((JS_DHASH_CAP(entryCount, maxAlpha) * (uint8_t)(0x100 * (maxAlpha))) \ - >> 8) < (entryCount))) - -#define JS_DHASH_DEFAULT_CAPACITY(entryCount) \ - JS_DHASH_CAPACITY(entryCount, JS_DHASH_DEFAULT_MAX_ALPHA) - -/* - * Finalize table's data, free its entry storage using table->ops->freeTable, - * and leave its members unchanged from their last live values (which leaves - * pointers dangling). If you want to burn cycles clearing table, it's up to - * your code to call memset. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableFinish(JSDHashTable *table); - -/* - * To consolidate keyHash computation and table grow/shrink code, we use a - * single entry point for lookup, add, and remove operations. The operation - * codes are declared here, along with codes returned by JSDHashEnumerator - * functions, which control JS_DHashTableEnumerate's behavior. - */ -typedef enum JSDHashOperator { - JS_DHASH_LOOKUP = 0, /* lookup entry */ - JS_DHASH_ADD = 1, /* add entry */ - JS_DHASH_REMOVE = 2, /* remove entry, or enumerator says remove */ - JS_DHASH_NEXT = 0, /* enumerator says continue */ - JS_DHASH_STOP = 1 /* enumerator says stop */ -} JSDHashOperator; - -/* - * To lookup a key in table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_LOOKUP); - * - * If JS_DHASH_ENTRY_IS_BUSY(entry) is true, key was found and it identifies - * entry. If JS_DHASH_ENTRY_IS_FREE(entry) is true, key was not found. - * - * To add an entry identified by key to table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_ADD); - * - * If entry is null upon return, then either the table is severely overloaded, - * and memory can't be allocated for entry storage via table->ops->allocTable; - * Or if table->ops->initEntry is non-null, the table->ops->initEntry op may - * have returned false. - * - * Otherwise, entry->keyHash has been set so that JS_DHASH_ENTRY_IS_BUSY(entry) - * is true, and it is up to the caller to initialize the key and value parts - * of the entry sub-type, if they have not been set already (i.e. if entry was - * not already in the table, and if the optional initEntry hook was not used). - * - * To remove an entry identified by key from table, call: - * - * (void) JS_DHashTableOperate(table, key, JS_DHASH_REMOVE); - * - * If key's entry is found, it is cleared (via table->ops->clearEntry) and - * the entry is marked so that JS_DHASH_ENTRY_IS_FREE(entry). This operation - * returns null unconditionally; you should ignore its return value. - */ -extern JS_PUBLIC_API(JSDHashEntryHdr *) JS_DHASH_FASTCALL -JS_DHashTableOperate(JSDHashTable *table, const void *key, JSDHashOperator op); - -/* - * Remove an entry already accessed via LOOKUP or ADD. - * - * NB: this is a "raw" or low-level routine, intended to be used only where - * the inefficiency of a full JS_DHashTableOperate (which rehashes in order - * to find the entry given its key) is not tolerable. This function does not - * shrink the table if it is underloaded. It does not update stats #ifdef - * JS_DHASHMETER, either. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableRawRemove(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Enumerate entries in table using etor: - * - * count = JS_DHashTableEnumerate(table, etor, arg); - * - * JS_DHashTableEnumerate calls etor like so: - * - * op = etor(table, entry, number, arg); - * - * where number is a zero-based ordinal assigned to live entries according to - * their order in table->entryStore. - * - * The return value, op, is treated as a set of flags. If op is JS_DHASH_NEXT, - * then continue enumerating. If op contains JS_DHASH_REMOVE, then clear (via - * table->ops->clearEntry) and free entry. Then we check whether op contains - * JS_DHASH_STOP; if so, stop enumerating and return the number of live entries - * that were enumerated so far. Return the total number of live entries when - * enumeration completes normally. - * - * If etor calls JS_DHashTableOperate on table with op != JS_DHASH_LOOKUP, it - * must return JS_DHASH_STOP; otherwise undefined behavior results. - * - * If any enumerator returns JS_DHASH_REMOVE, table->entryStore may be shrunk - * or compressed after enumeration, but before JS_DHashTableEnumerate returns. - * Such an enumerator therefore can't safely set aside entry pointers, but an - * enumerator that never returns JS_DHASH_REMOVE can set pointers to entries - * aside, e.g., to avoid copying live entries into an array of the entry type. - * Copying entry pointers is cheaper, and safe so long as the caller of such a - * "stable" Enumerate doesn't use the set-aside pointers after any call either - * to PL_DHashTableOperate, or to an "unstable" form of Enumerate, which might - * grow or shrink entryStore. - * - * If your enumerator wants to remove certain entries, but set aside pointers - * to other entries that it retains, it can use JS_DHashTableRawRemove on the - * entries to be removed, returning JS_DHASH_NEXT to skip them. Likewise, if - * you want to remove entries, but for some reason you do not want entryStore - * to be shrunk or compressed, you can call JS_DHashTableRawRemove safely on - * the entry being enumerated, rather than returning JS_DHASH_REMOVE. - */ -typedef JSDHashOperator -(* JSDHashEnumerator)(JSDHashTable *table, JSDHashEntryHdr *hdr, uint32_t number, void *arg); - -extern JS_PUBLIC_API(uint32_t) -JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg); - -typedef size_t -(* JSDHashSizeOfEntryExcludingThisFun)(JSDHashEntryHdr *hdr, - JSMallocSizeOfFun mallocSizeOf, - void *arg); - -/** - * Measure the size of the table's entry storage, and if - * |sizeOfEntryExcludingThis| is non-NULL, measure the size of things pointed - * to by entries. Doesn't measure |ops| because it's often shared between - * tables, nor |data| because it's opaque. - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfExcludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -/** - * Like JS_DHashTableSizeOfExcludingThis, but includes sizeof(*this). - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfIncludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -#ifdef DEBUG -/** - * Mark a table as immutable for the remainder of its lifetime. This - * changes the implementation from ASSERTing one set of invariants to - * ASSERTing a different set. - * - * When a table is NOT marked as immutable, the table implementation - * asserts that the table is not mutated from its own callbacks. It - * assumes the caller protects the table from being accessed on multiple - * threads simultaneously. - * - * When the table is marked as immutable, the re-entry assertions will - * no longer trigger erroneously due to multi-threaded access. Instead, - * mutations will cause assertions. - */ -extern JS_PUBLIC_API(void) -JS_DHashMarkTableImmutable(JSDHashTable *table); -#endif - -#ifdef JS_DHASHMETER -#include - -extern JS_PUBLIC_API(void) -JS_DHashTableDumpMeter(JSDHashTable *table, JSDHashEnumerator dump, FILE *fp); -#endif - -#endif /* jsdhash_h___ */ diff --git a/external/spidermonkey/include/ios/jsfriendapi.h b/external/spidermonkey/include/ios/jsfriendapi.h index 848049ffe3..a1c3024fed 100644 --- a/external/spidermonkey/include/ios/jsfriendapi.h +++ b/external/spidermonkey/include/ios/jsfriendapi.h @@ -4,15 +4,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsfriendapi_h___ -#define jsfriendapi_h___ +#ifndef jsfriendapi_h +#define jsfriendapi_h -#include "mozilla/GuardObjects.h" +#include "mozilla/MemoryReporting.h" #include "jsclass.h" -#include "jscpucfg.h" -#include "jspubtd.h" #include "jsprvtd.h" +#include "jspubtd.h" + +#include "js/CallArgs.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -29,6 +30,11 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +namespace JS { +template +class Heap; +} /* namespace JS */ + extern JS_FRIEND_API(void) JS_SetGrayGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data); @@ -48,7 +54,7 @@ extern JS_FRIEND_API(JSObject *) JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JSHandleObject obj); +JS_ObjectCountDynamicSlots(JS::HandleObject obj); extern JS_FRIEND_API(size_t) JS_SetProtoCalled(JSContext *cx); @@ -118,14 +124,27 @@ extern JS_FRIEND_API(JSObject *) JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) -JS_BasicObjectToString(JSContext *cx, JSHandleObject obj); +JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp); +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, + JS::MutableHandleValue vp); JS_FRIEND_API(void) js_ReportOverRecursed(JSContext *maybecx); +JS_FRIEND_API(bool) +js_ObjectClassIs(JSContext *cx, JS::HandleObject obj, js::ESClassValue classValue); + +JS_FRIEND_API(const char *) +js_ObjectClassName(JSContext *cx, JS::HandleObject obj); + +JS_FRIEND_API(bool) +js_AddObjectRoot(JSRuntime *rt, JSObject **objp); + +JS_FRIEND_API(void) +js_RemoveObjectRoot(JSRuntime *rt, JSObject **objp); + #ifdef DEBUG /* @@ -157,7 +176,7 @@ extern JS_FRIEND_API(JSBool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); extern JS_FRIEND_API(JSBool) -JS_EnumerateState(JSContext *cx, JSHandleObject obj, JSIterateOp enum_op, +JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, js::MutableHandleValue statep, js::MutableHandleId idp); struct JSFunctionSpecWithHelp { @@ -177,25 +196,24 @@ struct JSFunctionSpecWithHelp { extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JSScript *script, jschar **src, uint32_t *length); +typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, + jschar **src, uint32_t *length); extern JS_FRIEND_API(void) JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); namespace js { -extern mozilla::ThreadLocal TlsPerThreadData; - inline JSRuntime * GetRuntime(const JSContext *cx) { - return ContextFriendFields::get(cx)->runtime; + return ContextFriendFields::get(cx)->runtime_; } inline JSCompartment * GetContextCompartment(const JSContext *cx) { - return ContextFriendFields::get(cx)->compartment; + return ContextFriendFields::get(cx)->compartment_; } inline JS::Zone * @@ -217,19 +235,6 @@ typedef bool extern JS_FRIEND_API(void) DumpHeapComplete(JSRuntime *rt, FILE *fp); -class JS_FRIEND_API(AutoSwitchCompartment) { - private: - JSContext *cx; - JSCompartment *oldCompartment; - public: - AutoSwitchCompartment(JSContext *cx, JSCompartment *newCompartment - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - AutoSwitchCompartment(JSContext *cx, JSHandleObject target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoSwitchCompartment(); - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - #ifdef OLD_GETTER_SETTER_METHODS JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); @@ -254,6 +259,15 @@ IsAtomsCompartment(JSCompartment *comp); extern JS_FRIEND_API(bool) ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +/* + * Returns whether we're in a non-strict property set (in that we're in a + * non-strict script and the bytecode we're on is a property set). The return + * value does NOT indicate any sort of exception was thrown: it's just a + * boolean. + */ +extern JS_FRIEND_API(bool) +IsInNonStrictPropertySet(JSContext *cx); + struct WeakMapTracer; /* @@ -301,7 +315,7 @@ IterateGrayObjects(JS::Zone *zone, GCThingCallback cellCallback, void *data); #ifdef JS_HAS_CTYPES extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(JSMallocSizeOfFun mallocSizeOf, JSObject *obj); +SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject *obj); #endif extern JS_FRIEND_API(JSCompartment *) @@ -321,8 +335,9 @@ struct TypeObject { }; struct BaseShape { - js::Class *clasp; - JSObject *parent; + js::Class *clasp; + JSObject *parent; + JSObject *_1; JSCompartment *compartment; }; @@ -365,19 +380,22 @@ struct Function { }; struct Atom { - size_t _; + static const size_t LENGTH_SHIFT = 4; + size_t lengthAndFlags; const jschar *chars; }; } /* namespace shadow */ -extern JS_FRIEND_DATA(js::Class) CallClass; -extern JS_FRIEND_DATA(js::Class) DeclEnvClass; -extern JS_FRIEND_DATA(js::Class) FunctionClass; -extern JS_FRIEND_DATA(js::Class) FunctionProxyClass; -extern JS_FRIEND_DATA(js::Class) OuterWindowProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectClass; +// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use +// them in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; + +// This is equal to |&JSObject::class_|. Use it in places where you don't want +// to #include jsobj.h. +extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; inline js::Class * GetObjectClass(JSObject *obj) @@ -401,9 +419,15 @@ IsOuterObject(JSObject *obj) { return !!GetObjectClass(obj)->ext.innerObject; } +JS_FRIEND_API(bool) +IsFunctionObject(JSObject *obj); + JS_FRIEND_API(bool) IsScopeObject(JSObject *obj); +JS_FRIEND_API(bool) +IsCallObject(JSObject *obj); + inline JSObject * GetObjectParent(JSObject *obj) { @@ -423,6 +447,13 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +// For legacy consumers only. This whole concept is going away soon. +JS_FRIEND_API(JSObject *) +DefaultObjectForContextOrNull(JSContext *cx); + +JS_FRIEND_API(void) +SetDefaultObjectForContext(JSContext *cx, JSObject *obj); + JS_FRIEND_API(void) NotifyAnimationActivity(JSObject *obj); @@ -469,11 +500,11 @@ inline bool GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) { js::Class *clasp = GetObjectClass(obj); - if (clasp == &js::ObjectProxyClass || - clasp == &js::OuterWindowProxyClass || - clasp == &js::FunctionProxyClass) + if (clasp == js::ObjectProxyClassPtr || + clasp == js::OuterWindowProxyClassPtr || + clasp == js::FunctionProxyClassPtr) { - return JS_GetPrototype(cx, obj, proto.address()); + return JS_GetPrototype(cx, obj, proto); } proto.set(reinterpret_cast(obj.get())->type->proto); @@ -535,6 +566,13 @@ GetAtomChars(JSAtom *atom) return reinterpret_cast(atom)->chars; } +inline size_t +GetAtomLength(JSAtom *atom) +{ + using shadow::Atom; + return reinterpret_cast(atom)->lengthAndFlags >> Atom::LENGTH_SHIFT; +} + inline JSLinearString * AtomToLinearString(JSAtom *atom) { @@ -589,6 +627,12 @@ GetNativeStackLimit(const JSRuntime *rt) return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; } +inline uintptr_t +GetNativeStackLimit(JSContext *cx) +{ + return GetNativeStackLimit(GetRuntime(cx)); +} + /* * These macros report a stack overflow and run |onerror| if we are close to * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a little @@ -598,18 +642,15 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), &stackDummy_)) { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), &stackDummy_)) { \ js_ReportOverRecursed(cx); \ onerror; \ } \ JS_END_MACRO -#define JS_CHECK_RECURSION_WITH_EXTRA_DONT_REPORT(cx, extra, onerror) \ +#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ JS_BEGIN_MACRO \ - uint8_t stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ - &stackDummy_ - (extra))) \ - { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ onerror; \ } \ JS_END_MACRO @@ -617,7 +658,7 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ + if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(cx), \ &stackDummy_, \ 1024 * sizeof(size_t))) \ { \ @@ -754,13 +795,13 @@ extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JSFlatString *desc); +(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); extern JS_FRIEND_API(AnalysisPurgeCallback) SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); typedef JSBool -(* DOMInstanceClassMatchesProto)(JSHandleObject protoObject, uint32_t protoID, +(* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { DOMInstanceClassMatchesProto instanceClassMatchesProto; @@ -851,10 +892,10 @@ NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& targetFilter, NukeReferencesToWindow nukeReferencesToWindow); -/* Specify information about ListBase proxies in the DOM, for use by ICs. */ +/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ /* - * The ListBaseShadowsCheck function will be called to check if the property for + * The DOMProxyShadowsCheck function will be called to check if the property for * id should be gotten from the prototype, or if there is an own property that * shadows it. * If DoesntShadow is returned then the slot at listBaseExpandoSlot should @@ -873,25 +914,31 @@ struct ExpandoAndGeneration { generation(0) {} - Value expando; + void Unlink() + { + ++generation; + expando.setUndefined(); + } + + JS::Heap expando; uint32_t generation; }; -typedef enum ListBaseShadowsResult { +typedef enum DOMProxyShadowsResult { ShadowCheckFailed, Shadows, DoesntShadow, DoesntShadowUnique -} ListBaseShadowsResult; -typedef ListBaseShadowsResult -(* ListBaseShadowsCheck)(JSContext* cx, JSHandleObject object, JSHandleId id); +} DOMProxyShadowsResult; +typedef DOMProxyShadowsResult +(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetListBaseInformation(void *listBaseHandlerFamily, uint32_t listBaseExpandoSlot, - ListBaseShadowsCheck listBaseShadowsCheck); +SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, + DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetListBaseHandlerFamily(); -uint32_t GetListBaseExpandoSlot(); -ListBaseShadowsCheck GetListBaseShadowsCheck(); +void *GetDOMProxyHandlerFamily(); +uint32_t GetDOMProxyExpandoSlot(); +DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); } /* namespace js */ @@ -960,6 +1007,137 @@ enum ViewType { }; } /* namespace ArrayBufferView */ + +/* + * A helper for building up an ArrayBuffer object's data + * before creating the ArrayBuffer itself. Will do doubling + * based reallocation, up to an optional maximum growth given. + * + * When all the data has been appended, call getArrayBuffer, + * passing in the JSContext* for which the ArrayBuffer object + * is to be created. This also implicitly resets the builder, + * or it can be reset explicitly at any point by calling reset(). + */ +class ArrayBufferBuilder +{ + void *rawcontents_; + uint8_t *dataptr_; + uint32_t capacity_; + uint32_t length_; + public: + ArrayBufferBuilder() + : rawcontents_(NULL), + dataptr_(NULL), + capacity_(0), + length_(0) + { + } + + ~ArrayBufferBuilder() { + reset(); + } + + void reset() { + if (rawcontents_) + JS_free(NULL, rawcontents_); + rawcontents_ = dataptr_ = NULL; + capacity_ = length_ = 0; + } + + // will truncate if newcap is < length() + bool setCapacity(uint32_t newcap) { + if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) + return false; + + capacity_ = newcap; + if (length_ > newcap) + length_ = newcap; + + return true; + } + + // Append datalen bytes from data to the current buffer. If we + // need to grow the buffer, grow by doubling the size up to a + // maximum of maxgrowth (if given). If datalen is greater than + // what the new capacity would end up as, then grow by datalen. + // + // The data parameter must not overlap with anything beyond the + // builder's current valid contents [0..length) + bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { + if (length_ + datalen > capacity_) { + uint32_t newcap; + // double while under maxgrowth or if not specified + if (!maxgrowth || capacity_ < maxgrowth) + newcap = capacity_ * 2; + else + newcap = capacity_ + maxgrowth; + + // but make sure there's always enough to satisfy our request + if (newcap < length_ + datalen) + newcap = length_ + datalen; + + // did we overflow? + if (newcap < capacity_) + return false; + + if (!setCapacity(newcap)) + return false; + } + + // assert that the region isn't overlapping so we can memcpy; + JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); + + memcpy(dataptr_ + length_, newdata, datalen); + length_ += datalen; + + return true; + } + + uint8_t *data() { + return dataptr_; + } + + uint32_t length() { + return length_; + } + + uint32_t capacity() { + return capacity_; + } + + JSObject* getArrayBuffer(JSContext *cx) { + // we need to check for length_ == 0, because nothing may have been + // added + if (capacity_ > length_ || length_ == 0) { + if (!setCapacity(length_)) + return NULL; + } + + JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); + if (!obj) + return NULL; + + rawcontents_ = dataptr_ = NULL; + length_ = capacity_ = 0; + + return obj; + } + +protected: + + static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, + const uint8_t *start2, uint32_t length2) + { + const uint8_t *end1 = start1 + length1; + const uint8_t *end2 = start2 + length2; + + const uint8_t *max_start = start1 > start2 ? start1 : start2; + const uint8_t *min_end = end1 < end2 ? end1 : end2; + + return max_start < min_end; + } +}; + } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1296,26 +1474,116 @@ JS_GetDataViewByteLength(JSObject *obj); JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitGetterOp. + */ +class JSJitGetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitGetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args.rval()) + {} + + explicit JSJitGetterCallArgs(JS::Rooted* rooted) + : JS::MutableHandleValue(rooted) + {} + + JS::MutableHandleValue rval() { + return *this; + } +}; + +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitSetterOp. + */ +class JSJitSetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitSetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args[0]) + {} + + JS::MutableHandleValue operator[](unsigned i) { + MOZ_ASSERT(i == 0); + return *this; + } + + unsigned length() const { return 1; } + + // Add get() or maybe hasDefined() as needed +}; + +struct JSJitMethodCallArgsTraits; + +/* + * A class, expected to be passed by reference, which represents the CallArgs + * for a JSJitMethodOp. + */ +class JSJitMethodCallArgs : protected JS::detail::CallArgsBase +{ + private: + typedef JS::detail::CallArgsBase Base; + friend struct JSJitMethodCallArgsTraits; + + public: + explicit JSJitMethodCallArgs(const JS::CallArgs& args) { + argv_ = args.array(); + argc_ = args.length(); + } + + JS::MutableHandleValue rval() const { + return Base::rval(); + } + + unsigned length() const { return Base::length(); } + + JS::MutableHandleValue operator[](unsigned i) const { + return Base::operator[](i); + } + + bool hasDefined(unsigned i) const { + return Base::hasDefined(i); + } + + // Add get() as needed +}; + +struct JSJitMethodCallArgsTraits +{ + static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); + static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); +}; + /* * This struct contains metadata passed from the DOM to the JS Engine for JIT * optimizations on DOM property accessors. Eventually, this should be made * available to general JSAPI users, but we are not currently ready to do so. */ typedef bool -(* JSJitPropertyOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, JS::Value *vp); +(* JSJitGetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitGetterCallArgs args); typedef bool -(* JSJitMethodOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, unsigned argc, JS::Value *vp); +(* JSJitSetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitSetterCallArgs args); +typedef bool +(* JSJitMethodOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, const JSJitMethodCallArgs& args); struct JSJitInfo { enum OpType { Getter, Setter, - Method + Method, + OpType_None }; - JSJitPropertyOp op; + union { + JSJitGetterOp getter; + JSJitSetterOp setter; + JSJitMethodOp method; + }; uint32_t protoID; uint32_t depth; OpType type; @@ -1325,12 +1593,18 @@ struct JSJitInfo { keep returning the same value for the given "this" object" */ JSValueType returnType; /* The return type tag. Might be JSVAL_TYPE_UNKNOWN */ + + /* An alternative native that's safe to call in parallel mode. */ + JSParallelNative parallelNative; }; +#define JS_JITINFO_NATIVE_PARALLEL(op) \ + {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) { - JS_ASSERT(js::GetObjectClass(&v.toObject()) == &js::FunctionClass); + JS_ASSERT(js::GetObjectClass(&v.toObject()) == js::FunctionClassPtr); return reinterpret_cast(&v.toObject())->jitinfo; } @@ -1482,9 +1756,46 @@ assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id); inline void assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id) {}; #endif +typedef bool +(* ObjectMetadataCallback)(JSContext *cx, JSObject **pmetadata); + +/* + * Specify a callback to invoke when creating each JS object in the current + * compartment, which may return a metadata object to associate with the + * object. Objects with different metadata have different shape hierarchies, + * so for efficiency, objects should generally try to share metadata objects. + */ +JS_FRIEND_API(void) +SetObjectMetadataCallback(JSContext *cx, ObjectMetadataCallback callback); + +/* Manipulate the metadata associated with an object. */ + +JS_FRIEND_API(bool) +SetObjectMetadata(JSContext *cx, JS::HandleObject obj, JS::HandleObject metadata); + +JS_FRIEND_API(JSObject *) +GetObjectMetadata(JSObject *obj); + /* ES5 8.12.8. */ extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); + +/* + * Helper function. To approximate a call to the [[DefineOwnProperty]] internal + * method described in ES5, first call this, then call JS_DefinePropertyById. + * + * JS_DefinePropertyById by itself does not enforce the invariants on + * non-configurable properties when obj->isNative(). This function performs the + * relevant checks (specified in ES5 8.12.9 [[DefineOwnProperty]] steps 1-11), + * but only if obj is native. + * + * The reason for the messiness here is that ES5 uses [[DefineOwnProperty]] as + * a sort of extension point, but there is no hook in js::Class, + * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. + */ +extern JS_FRIEND_API(bool) +CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, + PropertyOp getter, StrictPropertyOp setter, unsigned attrs); } /* namespace js */ @@ -1495,4 +1806,26 @@ js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, extern JS_FRIEND_API(JSBool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); -#endif /* jsfriendapi_h___ */ +#ifdef JSGC_GENERATIONAL +extern JS_FRIEND_API(void) +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data); + +extern JS_FRIEND_API(void) +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data); +#else +inline void +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data) {} + +inline void +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data) {} +#endif /* JSGC_GENERATIONAL */ + +#endif /* jsfriendapi_h */ diff --git a/external/spidermonkey/include/ios/jslock.h b/external/spidermonkey/include/ios/jslock.h index b4a28a9fa9..522034ad68 100644 --- a/external/spidermonkey/include/ios/jslock.h +++ b/external/spidermonkey/include/ios/jslock.h @@ -4,18 +4,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jslock_h__ -#define jslock_h__ - -#include "jsapi.h" +#ifndef jslock_h +#define jslock_h #ifdef JS_THREADSAFE +# include "jsapi.h" # include "pratom.h" -# include "prlock.h" # include "prcvar.h" -# include "prthread.h" # include "prinit.h" +# include "prlock.h" +# include "prthread.h" # define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) # define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) @@ -40,4 +39,4 @@ typedef struct PRLock PRLock; #endif /* JS_THREADSAFE */ -#endif /* jslock_h___ */ +#endif /* jslock_h */ diff --git a/external/spidermonkey/include/ios/json.h b/external/spidermonkey/include/ios/json.h deleted file mode 100644 index 7fa2c117c8..0000000000 --- a/external/spidermonkey/include/ios/json.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef json_h___ -#define json_h___ - -#include "jsprvtd.h" -#include "jspubtd.h" -#include "jsapi.h" - -#include "js/Vector.h" - -#define JSON_MAX_DEPTH 2048 -#define JSON_PARSER_BUFSIZE 1024 - -extern JSObject * -js_InitJSONClass(JSContext *cx, js::HandleObject obj); - -extern JSBool -js_Stringify(JSContext *cx, js::MutableHandleValue vp, - JSObject *replacer, js::Value space, - js::StringBuffer &sb); - -// Avoid build errors on certain platforms that define these names as constants -#undef STRICT -#undef LEGACY - -/* - * The type of JSON decoding to perform. Strict decoding is to-the-spec; - * legacy decoding accepts a few non-JSON syntaxes historically accepted by the - * implementation. (Full description of these deviations is deliberately - * omitted.) New users should use strict decoding rather than legacy decoding, - * as legacy decoding might be removed at a future time. - */ -enum DecodingMode { STRICT, LEGACY }; - -namespace js { - -extern JS_FRIEND_API(JSBool) -ParseJSONWithReviver(JSContext *cx, JS::StableCharPtr chars, size_t length, HandleValue filter, - MutableHandleValue vp, DecodingMode decodingMode = STRICT); - -} /* namespace js */ - -#endif /* json_h___ */ diff --git a/external/spidermonkey/include/ios/jsperf.h b/external/spidermonkey/include/ios/jsperf.h index a0287b4a57..468ce8609c 100644 --- a/external/spidermonkey/include/ios/jsperf.h +++ b/external/spidermonkey/include/ios/jsperf.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsperf_h___ -#define jsperf_h___ +#ifndef perf_jsperf_h +#define perf_jsperf_h #include "jsapi.h" @@ -127,4 +127,4 @@ extern JS_FRIEND_API(PerfMeasurement*) } // namespace JS -#endif // jsperf_h___ +#endif /* perf_jsperf_h */ diff --git a/external/spidermonkey/include/ios/jsprf.h b/external/spidermonkey/include/ios/jsprf.h index c0891f0e9e..ce159d8115 100644 --- a/external/spidermonkey/include/ios/jsprf.h +++ b/external/spidermonkey/include/ios/jsprf.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprf_h___ -#define jsprf_h___ +#ifndef jsprf_h +#define jsprf_h /* ** API for PR printf like routines. Supports the following formats @@ -24,9 +24,11 @@ ** %f - float ** %g - float */ -#include "jstypes.h" -#include + #include +#include + +#include "jstypes.h" /* ** sprintf into a fixed size buffer. Guarantees that a NUL is at the end @@ -75,4 +77,4 @@ extern JS_PUBLIC_API(char*) JS_vsmprintf(const char *fmt, va_list ap); extern JS_PUBLIC_API(char*) JS_vsprintf_append(char *last, const char *fmt, va_list ap); extern JS_PUBLIC_API(uint32_t) JS_vsxprintf(JSStuffFunc f, void *arg, const char *fmt, va_list ap); -#endif /* jsprf_h___ */ +#endif /* jsprf_h */ diff --git a/external/spidermonkey/include/ios/jsprototypes.h b/external/spidermonkey/include/ios/jsprototypes.h index 007d25d720..f9bacac409 100644 --- a/external/spidermonkey/include/ios/jsprototypes.h +++ b/external/spidermonkey/include/ios/jsprototypes.h @@ -6,8 +6,8 @@ /* A higher-order macro for enumerating all JSProtoKey values. */ -#ifndef jsprototypes_h___ -#define jsprototypes_h___ +#ifndef jsprototypes_h +#define jsprototypes_h #include "jsversion.h" @@ -56,5 +56,20 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ + macro(Type, 38, js_InitBinaryDataClasses) \ + macro(Data, 39, js_InitBinaryDataClasses) \ + macro(uint8, 40, js_InitBinaryDataClasses) \ + macro(uint16, 41, js_InitBinaryDataClasses) \ + macro(uint32, 42, js_InitBinaryDataClasses) \ + macro(uint64, 43, js_InitBinaryDataClasses) \ + macro(int8, 44, js_InitBinaryDataClasses) \ + macro(int16, 45, js_InitBinaryDataClasses) \ + macro(int32, 46, js_InitBinaryDataClasses) \ + macro(int64, 47, js_InitBinaryDataClasses) \ + macro(float32, 48, js_InitBinaryDataClasses) \ + macro(float64, 49, js_InitBinaryDataClasses) \ + macro(ArrayType, 50, js_InitBinaryDataClasses) \ + macro(StructType, 51, js_InitBinaryDataClasses) \ + macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ -#endif /* jsprototypes_h___ */ +#endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/ios/jsproxy.h b/external/spidermonkey/include/ios/jsproxy.h index 399490eddc..56868a05c3 100644 --- a/external/spidermonkey/include/ios/jsproxy.h +++ b/external/spidermonkey/include/ios/jsproxy.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsproxy_h___ -#define jsproxy_h___ +#ifndef jsproxy_h +#define jsproxy_h #include "jsapi.h" #include "jsfriendapi.h" @@ -129,7 +129,7 @@ class JS_FRIEND_API(BaseProxyHandler) MutableHandleValue vp); /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) = 0; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) = 0; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -190,7 +190,7 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -242,7 +242,7 @@ class Proxy static bool iterate(JSContext *cx, HandleObject proxy, unsigned flags, MutableHandleValue vp); /* Spidermonkey extensions. */ - static bool isExtensible(JSObject *proxy); + static bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible); static bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -259,12 +259,17 @@ class Proxy inline bool IsObjectProxyClass(const Class *clasp) { - return clasp == &js::ObjectProxyClass || clasp == &js::OuterWindowProxyClass; + return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; } inline bool IsFunctionProxyClass(const Class *clasp) { - return clasp == &js::FunctionProxyClass; + return clasp == js::FunctionProxyClassPtr; +} + +inline bool IsProxyClass(const Class *clasp) +{ + return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); } inline bool IsObjectProxy(JSObject *obj) @@ -279,36 +284,33 @@ inline bool IsFunctionProxy(JSObject *obj) inline bool IsProxy(JSObject *obj) { - Class *clasp = GetObjectClass(obj); - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); + return IsProxyClass(GetObjectClass(obj)); } -/* Shared between object and function proxies. */ /* - * NOTE: JSSLOT_PROXY_PRIVATE is 0, because that way slot 0 is usable by API + * These are part of the API. + * + * NOTE: PROXY_PRIVATE_SLOT is 0 because that way slot 0 is usable by API * clients for both proxy and non-proxy objects. So an API client that only * needs to store one slot's worth of data doesn't need to branch on what sort * of object it has. */ -const uint32_t JSSLOT_PROXY_PRIVATE = 0; -const uint32_t JSSLOT_PROXY_HANDLER = 1; -const uint32_t JSSLOT_PROXY_EXTRA = 2; -/* Function proxies only. */ -const uint32_t JSSLOT_PROXY_CALL = 4; -const uint32_t JSSLOT_PROXY_CONSTRUCT = 5; +const uint32_t PROXY_PRIVATE_SLOT = 0; +const uint32_t PROXY_HANDLER_SLOT = 1; +const uint32_t PROXY_EXTRA_SLOT = 2; inline BaseProxyHandler * GetProxyHandler(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return (BaseProxyHandler *) GetReservedSlot(obj, JSSLOT_PROXY_HANDLER).toPrivate(); + return (BaseProxyHandler *) GetReservedSlot(obj, PROXY_HANDLER_SLOT).toPrivate(); } inline const Value & GetProxyPrivate(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_PRIVATE); + return GetReservedSlot(obj, PROXY_PRIVATE_SLOT); } inline JSObject * @@ -322,14 +324,14 @@ inline const Value & GetProxyExtra(JSObject *obj, size_t n) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n); + return GetReservedSlot(obj, PROXY_EXTRA_SLOT + n); } inline void SetProxyHandler(JSObject *obj, BaseProxyHandler *handler) { JS_ASSERT(IsProxy(obj)); - SetReservedSlot(obj, JSSLOT_PROXY_HANDLER, PrivateValue(handler)); + SetReservedSlot(obj, PROXY_HANDLER_SLOT, PrivateValue(handler)); } inline void @@ -337,7 +339,7 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) { JS_ASSERT(IsProxy(obj)); JS_ASSERT(n <= 1); - SetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n, extra); + SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } enum ProxyCallable { @@ -346,7 +348,7 @@ enum ProxyCallable { }; JS_FRIEND_API(JSObject *) -NewProxyObject(JSContext *cx, BaseProxyHandler *handler, const Value &priv, +NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); JSObject * @@ -426,6 +428,6 @@ class JS_FRIEND_API(AutoWaivePolicy) { } /* namespace js */ extern JS_FRIEND_API(JSObject *) -js_InitProxyClass(JSContext *cx, JSHandleObject obj); +js_InitProxyClass(JSContext *cx, JS::HandleObject obj); -#endif +#endif /* jsproxy_h */ diff --git a/external/spidermonkey/include/ios/jsprvtd.h b/external/spidermonkey/include/ios/jsprvtd.h index 4db5ed8c36..1fbc086a7c 100644 --- a/external/spidermonkey/include/ios/jsprvtd.h +++ b/external/spidermonkey/include/ios/jsprvtd.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprvtd_h___ -#define jsprvtd_h___ +#ifndef jsprvtd_h +#define jsprvtd_h /* * JS private typename definitions. * @@ -56,13 +56,7 @@ typedef struct JSStackHeader JSStackHeader; typedef struct JSSubString JSSubString; typedef struct JSSpecializedNative JSSpecializedNative; -/* - * Template declarations. - * - * jsprvtd.h can be included in both C and C++ translation units. For C++, it - * may possibly be wrapped in an extern "C" block which does not agree with - * templates. - */ +/* String typedefs. */ class JSDependentString; class JSExtensibleString; class JSExternalString; @@ -76,6 +70,7 @@ namespace js { struct ArgumentsData; struct Class; +class AutoNameVector; class RegExpGuard; class RegExpObject; class RegExpObjectBuilder; @@ -83,6 +78,7 @@ class RegExpShared; class RegExpStatics; class MatchPairs; class PropertyName; +class LazyScript; enum RegExpFlag { @@ -95,19 +91,14 @@ enum RegExpFlag AllFlags = 0x0f }; -class ExecuteArgsGuard; -class InvokeFrameGuard; -class InvokeArgsGuard; class StringBuffer; class FrameRegs; class StackFrame; -class StackSegment; -class StackSpace; -class ContextStack; class ScriptFrameIter; class Proxy; +class JS_FRIEND_API(AutoEnterPolicy); class JS_FRIEND_API(BaseProxyHandler); class JS_FRIEND_API(Wrapper); class JS_FRIEND_API(CrossCompartmentWrapper); @@ -140,24 +131,29 @@ class WatchpointMap; typedef JSObject Env; typedef JSNative Native; +typedef JSParallelNative ParallelNative; +typedef JSThreadSafeNative ThreadSafeNative; typedef JSPropertyOp PropertyOp; typedef JSStrictPropertyOp StrictPropertyOp; typedef JSPropertyDescriptor PropertyDescriptor; +struct SourceCompressionToken; + namespace frontend { struct BytecodeEmitter; struct Definition; +class FullParseHandler; class FunctionBox; class ObjectBox; struct Token; struct TokenPos; class TokenStream; class ParseMapPool; -struct ParseNode; +class ParseNode; template -struct Parser; +class Parser; } /* namespace frontend */ @@ -284,18 +280,18 @@ typedef void * if an error or exception was thrown on cx. */ typedef JSObject * -(* JSObjectOp)(JSContext *cx, JSHandleObject obj); +(* JSObjectOp)(JSContext *cx, JS::Handle obj); /* Signature for class initialization ops. */ typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JSHandleObject obj); +(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); /* * Hook that creates an iterator object for a given object. Returns the * iterator object or null if an error or exception was thrown on cx. */ typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JSHandleObject obj, JSBool keysonly); +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); -#endif /* jsprvtd_h___ */ +#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/ios/jspubtd.h b/external/spidermonkey/include/ios/jspubtd.h index 6b7e63e6ba..96f5dd8297 100644 --- a/external/spidermonkey/include/ios/jspubtd.h +++ b/external/spidermonkey/include/ios/jspubtd.h @@ -4,16 +4,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jspubtd_h___ -#define jspubtd_h___ +#ifndef jspubtd_h +#define jspubtd_h /* * JS public API typedefs. */ +#include "mozilla/PodOperations.h" + #include "jsprototypes.h" #include "jstypes.h" +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) +# define JSGC_TRACK_EXACT_ROOTS +#endif + namespace JS { /* @@ -25,6 +31,8 @@ class Value; template class Rooted; +class JS_PUBLIC_API(AutoGCRooter); + struct Zone; } /* namespace JS */ @@ -44,10 +52,8 @@ struct Zone; * oblivious to the change. This feature can be explicitly disabled in debug * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. */ - // Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES - +#define JS_NO_JSVAL_JSID_STRUCT_TYPES # if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) # define JS_USE_JSID_STRUCT_TYPES # endif @@ -154,9 +160,10 @@ typedef enum { JSTRACE_SCRIPT, /* - * Trace kinds internal to the engine. The embedding can only them if it - * implements JSTraceCallback. + * Trace kinds internal to the engine. The embedding can only see them if + * it implements JSTraceCallback. */ + JSTRACE_LAZY_SCRIPT, JSTRACE_IONCODE, JSTRACE_SHAPE, JSTRACE_BASE_SHAPE, @@ -229,6 +236,18 @@ struct Runtime namespace js { +/* + * Parallel operations in general can have one of three states. They may + * succeed, fail, or "bail", where bail indicates that the code encountered an + * unexpected condition and should be re-run sequentially. Different + * subcategories of the "bail" state are encoded as variants of TP_RETRY_*. + */ +enum ParallelResult { TP_SUCCESS, TP_RETRY_SEQUENTIALLY, TP_RETRY_AFTER_GC, TP_FATAL }; + +struct ThreadSafeContext; +struct ForkJoinSlice; +class ExclusiveContext; + class Allocator; class SkipRoot; @@ -273,18 +292,28 @@ template <> struct RootKind : SpecificRootKind struct RootKind : SpecificRootKind {}; template <> struct RootKind : SpecificRootKind {}; -struct ContextFriendFields { - JSRuntime *const runtime; +struct ContextFriendFields +{ + protected: + JSRuntime *const runtime_; /* The current compartment. */ - JSCompartment *compartment; + JSCompartment *compartment_; /* The current zone. */ JS::Zone *zone_; + public: explicit ContextFriendFields(JSRuntime *rt) - : runtime(rt), compartment(NULL), zone_(NULL) - { } + : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + { +#ifdef JSGC_TRACK_EXACT_ROOTS + mozilla::PodArrayZero(thingGCRooters); +#endif +#if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) + skipGCRooters = NULL; +#endif + } static const ContextFriendFields *get(const JSContext *cx) { return reinterpret_cast(cx); @@ -294,7 +323,7 @@ struct ContextFriendFields { return reinterpret_cast(cx); } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -313,6 +342,13 @@ struct ContextFriendFields { */ SkipRoot *skipGCRooters; #endif + + /* Stack of thread-stack-allocated GC roots. */ + JS::AutoGCRooter *autoGCRooters; + + friend JSRuntime *GetRuntime(const JSContext *cx); + friend JSCompartment *GetContextCompartment(const JSContext *cx); + friend JS::Zone *GetContextZone(const JSContext *cx); }; class PerThreadData; @@ -338,7 +374,7 @@ struct PerThreadDataFriendFields PerThreadDataFriendFields(); -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -384,4 +420,4 @@ struct PerThreadDataFriendFields } /* namespace js */ -#endif /* jspubtd_h___ */ +#endif /* jspubtd_h */ diff --git a/external/spidermonkey/include/ios/jstypes.h b/external/spidermonkey/include/ios/jstypes.h index e4c02f8d8d..17f67f70e1 100644 --- a/external/spidermonkey/include/ios/jstypes.h +++ b/external/spidermonkey/include/ios/jstypes.h @@ -18,8 +18,8 @@ ** for all C files. **/ -#ifndef jstypes_h___ -#define jstypes_h___ +#ifndef jstypes_h +#define jstypes_h #include "mozilla/Attributes.h" #include "mozilla/Util.h" @@ -279,4 +279,4 @@ typedef int JSBool; # define JS_EXTENSION_(s) s #endif -#endif /* jstypes_h___ */ +#endif /* jstypes_h */ diff --git a/external/spidermonkey/include/ios/jsutil.h b/external/spidermonkey/include/ios/jsutil.h index 49e1641c61..4020822be1 100644 --- a/external/spidermonkey/include/ios/jsutil.h +++ b/external/spidermonkey/include/ios/jsutil.h @@ -8,19 +8,19 @@ * PR assertion checker. */ -#ifndef jsutil_h___ -#define jsutil_h___ +#ifndef jsutil_h +#define jsutil_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/GuardObjects.h" -#include "js/Utility.h" - #ifdef USE_ZLIB -#include "zlib.h" +#include #endif +#include "js/Utility.h" + /* Forward declarations. */ struct JSContext; @@ -204,15 +204,6 @@ UnsignedPtrDiff(const void *bigger, const void *smaller) return size_t(bigger) - size_t(smaller); } -/* - * Ordinarily, a function taking a JSContext* 'cx' parameter reports errors on - * the context. In some cases, functions optionally report and indicate this by - * taking a nullable 'maybecx' parameter. In some cases, though, a function - * always needs a 'cx', but optionally reports. This option is presented by the - * MaybeReportError. - */ -enum MaybeReportError { REPORT_ERROR = true, DONT_REPORT_ERROR = false }; - /*****************************************************************************/ /* A bit array is an array of bits represented by an array of words (size_t). */ @@ -391,4 +382,4 @@ typedef size_t jsbitmap; JS_END_MACRO #endif -#endif /* jsutil_h___ */ +#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/ios/jsversion.h b/external/spidermonkey/include/ios/jsversion.h index f3169fb5d1..1780616a32 100644 --- a/external/spidermonkey/include/ios/jsversion.h +++ b/external/spidermonkey/include/ios/jsversion.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsversion_h___ -#define jsversion_h___ +#ifndef jsversion_h +#define jsversion_h /* * Deprecated JS_VERSION handler. @@ -61,7 +61,7 @@ # define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else # define NEW_OBJECT_REPRESENTATION_ONLY() \ - MOZ_NOT_REACHED("don't call this! to be used in the new object representation") + MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif -#endif /* jsversion_h___ */ +#endif /* jsversion_h */ diff --git a/external/spidermonkey/include/ios/jswrapper.h b/external/spidermonkey/include/ios/jswrapper.h index d0c0fc625c..f78df7db60 100644 --- a/external/spidermonkey/include/ios/jswrapper.h +++ b/external/spidermonkey/include/ios/jswrapper.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jswrapper_h___ -#define jswrapper_h___ +#ifndef jswrapper_h +#define jswrapper_h #include "mozilla/Attributes.h" @@ -66,8 +66,6 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler static Wrapper singleton; static Wrapper singletonWithPrototype; - - static void *getWrapperFamily(); }; /* Base class for all cross compartment wrapper handlers. */ @@ -105,7 +103,7 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -139,7 +137,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base public: SecurityWrapper(unsigned flags); - virtual bool isExtensible(JSObject *wrapper) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool enter(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool *bp) MOZ_OVERRIDE; @@ -185,7 +183,7 @@ class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler virtual bool enumerate(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -297,4 +295,4 @@ struct JS_FRIEND_API(AutoMaybeTouchDeadZones) } /* namespace js */ -#endif +#endif /* jswrapper_h */ diff --git a/external/spidermonkey/include/ios/mozilla/AllocPolicy.h b/external/spidermonkey/include/ios/mozilla/AllocPolicy.h new file mode 100644 index 0000000000..20087e93bb --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/AllocPolicy.h @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * An allocation policy concept, usable for structures and algorithms to + * control how memory is allocated and how failures are handled. + */ + +#ifndef mozilla_AllocPolicy_h +#define mozilla_AllocPolicy_h + +#include +#include + +namespace mozilla { + +/* + * Allocation policies are used to implement the standard allocation behaviors + * in a customizable way. Additionally, custom behaviors may be added to these + * behaviors, such as additionally reporting an error through an out-of-band + * mechanism when OOM occurs. The concept modeled here is as follows: + * + * - public copy constructor, assignment, destructor + * - void* malloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* calloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* realloc_(void*, size_t, size_t) + * Responsible for OOM reporting when null is returned. The *used* bytes + * of the previous buffer is passed in (rather than the old allocation + * size), in addition to the *new* allocation size requested. + * - void free_(void*) + * - void reportAllocOverflow() const + * Called on allocation overflow (that is, an allocation implicitly tried + * to allocate more than the available memory space -- think allocating an + * array of large-size objects, where N * size overflows) before null is + * returned. + * + * mfbt provides (and typically uses by default) only MallocAllocPolicy, which + * does nothing more than delegate to the malloc/alloc/free functions. + */ + +/* + * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no + * extra behaviors. + */ +class MallocAllocPolicy +{ + public: + void* malloc_(size_t bytes) { return malloc(bytes); } + void* calloc_(size_t bytes) { return calloc(bytes, 1); } + void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } + void free_(void* p) { free(p); } + void reportAllocOverflow() const {} +}; + + +} // namespace mozilla + +#endif /* mozilla_AllocPolicy_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Array.h b/external/spidermonkey/include/ios/mozilla/Array.h new file mode 100644 index 0000000000..5af9aaa133 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Array.h @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A compile-time constant-length array with bounds-checking assertions. */ + +#ifndef mozilla_Array_h +#define mozilla_Array_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" + +#include + +namespace mozilla { + +template +class Array +{ + T arr[Length]; + + public: + T& operator[](size_t i) { + MOZ_ASSERT(i < Length); + return arr[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(i < Length); + return arr[i]; + } +}; + +template +class Array +{ + public: + T& operator[](size_t i) { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } + + const T& operator[](size_t i) const { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Array_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Assertions.h b/external/spidermonkey/include/ios/mozilla/Assertions.h index 5ead7f493e..00b7037802 100644 --- a/external/spidermonkey/include/ios/mozilla/Assertions.h +++ b/external/spidermonkey/include/ios/mozilla/Assertions.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of runtime and static assertion macros for C and C++. */ -#ifndef mozilla_Assertions_h_ -#define mozilla_Assertions_h_ +#ifndef mozilla_Assertions_h +#define mozilla_Assertions_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" @@ -39,44 +40,24 @@ #endif /* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This - * can be useful when you make certain assumptions about what must hold for + * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. + * In C++11, static_assert is provided by the compiler to the same effect. + * This can be useful when you make certain assumptions about what must hold for * optimal, or even correct, behavior. For example, you might assert that the * size of a struct is a multiple of the target architecture's word size: * * struct S { ... }; + * // C * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, * "S should be a multiple of word size for efficiency"); + * // C++11 + * static_assert(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); * * This macro can be used in any location where both an extern declaration and a * typedef could be used. - * - * Be aware of the gcc 4.2 concerns noted further down when writing patches that - * use this macro, particularly if a patch only bounces on OS X. */ -#ifdef __cplusplus -# if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__HP_aCC) -# if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# endif -#endif -#ifndef MOZ_STATIC_ASSERT +#ifndef __cplusplus /* * Some of the definitions below create an otherwise-unused typedef. This * triggers compiler warnings with some versions of gcc, so mark the typedefs @@ -124,78 +105,23 @@ # define MOZ_STATIC_ASSERT(cond, reason) \ extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE # endif -#endif #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) +#else +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) +#endif #ifdef __cplusplus extern "C" { #endif -/* - * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible - * way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. We use TerminateProcess - * with the exit code aborting would generate because we don't want to invoke - * atexit handlers, destructors, library unload handlers, and so on when our - * process might be in a compromised state. We don't use abort() because - * it'd cause Windows to annoyingly pop up the process error dialog multiple - * times. See bug 345118 and bug 426163. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - TerminateProcess(GetCurrentProcess(), 3); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - ::abort(); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - abort(); \ - } while (0) -# endif -#endif - /* * Prints |s| as an assertion failure (using file and ln as the location of the * assertion) to the standard debug-output channel. * - * Usually you should use MOZ_ASSERT instead of this method. This method is - * primarily for internal use in this header, and only secondarily for use in - * implementing release-build assertions. + * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This + * method is primarily for internal use in this header, and only secondarily + * for use in implementing release-build assertions. */ static MOZ_ALWAYS_INLINE void MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) @@ -209,6 +135,112 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif } +static MOZ_ALWAYS_INLINE void +MOZ_ReportCrash(const char* s, const char* file, int ln) +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", + "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); +#else + fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); + fflush(stderr); +#endif +} + +/** + * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should + * call MOZ_CRASH instead. + */ +#if defined(_MSC_VER) + /* + * On MSVC use the __debugbreak compiler intrinsic, which produces an inline + * (not nested in a system function) breakpoint. This distinctively invokes + * Breakpad without requiring system library symbols on all stack-processing + * machines, as a nested breakpoint would require. + * + * We use TerminateProcess with the exit code aborting would generate + * because we don't want to invoke atexit handlers, destructors, library + * unload handlers, and so on when our process might be in a compromised + * state. + * + * We don't use abort() because it'd cause Windows to annoyingly pop up the + * process error dialog multiple times. See bug 345118 and bug 426163. + * + * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the + * compiler doesn't hassle us to provide a return statement after a + * MOZ_REALLY_CRASH() call. + * + * (Technically these are Windows requirements, not MSVC requirements. But + * practically you need MSVC for debugging, and we only ship builds created + * by MSVC, so doing it this way reduces complexity.) + */ + +__declspec(noreturn) __inline void MOZ_NoReturn() {} + +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + ::TerminateProcess(::GetCurrentProcess(), 3); \ + ::MOZ_NoReturn(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + TerminateProcess(GetCurrentProcess(), 3); \ + MOZ_NoReturn(); \ + } while (0) +# endif +#else +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + ::abort(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + abort(); \ + } while (0) +# endif +#endif + +/* + * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a + * Breakpad-compatible way, in both debug and release builds. + * + * MOZ_CRASH is a good solution for "handling" failure cases when you're + * unwilling or unable to handle them more cleanly -- for OOM, for likely memory + * corruption, and so on. It's also a good solution if you need safe behavior + * in release builds as well as debug builds. But if the failure is one that + * should be debugged and fixed, MOZ_ASSERT is generally preferable. + * + * The optional explanation-string, if provided, must be a string literal + * explaining why we're crashing. This argument is intended for use with + * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's + * obvious why we're crashing. + * + * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an + * explanation-string, we print the string to stderr. Otherwise, we don't + * print anything; this is because we want MOZ_CRASH to be 100% safe in release + * builds, and it's hard to print to stderr safely when memory might have been + * corrupted. + */ +#ifndef DEBUG +# define MOZ_CRASH(...) MOZ_REALLY_CRASH() +#else +# define MOZ_CRASH(...) \ + do { \ + MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } while(0) +#endif + #ifdef __cplusplus } /* extern "C" */ #endif @@ -251,7 +283,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* Now the two-argument form. */ @@ -259,7 +291,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* And now, helper macrology up the wazoo. */ @@ -310,14 +342,14 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif /* - * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is + * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is * undefined behavior for execution to reach this point. No guarantees are made * about what will happen if this is reached at runtime. Most code should - * probably use the higher level MOZ_NOT_REACHED, which uses this when + * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when * appropriate. */ #if defined(__clang__) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() #elif defined(__GNUC__) /* * __builtin_unreachable() was implemented in gcc 4.5. If we don't have @@ -325,49 +357,71 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) * in C++ in case there's another abort() visible in local scope. */ # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() # else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif # endif #elif defined(_MSC_VER) -# define MOZ_NOT_REACHED_MARKER() __assume(0) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) #else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif #endif /* - * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached - * during execution: simply reaching that point in execution is a bug. It takes - * as an argument an error message indicating the reason why that point should - * not have been reachable. + * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that + * the macro call cannot be reached during execution. This lets the compiler + * generate better-optimized code under some circumstances, at the expense of + * the program's behavior being undefined if control reaches the + * MOZ_ASSUME_UNREACHABLE. * - * // ...in a language parser... - * void handle(BooleanLiteralNode node) + * In Gecko, you probably should not use this macro outside of performance- or + * size-critical code, because it's unsafe. If you don't care about code size + * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. + * + * SpiderMonkey is a different beast, and there it's acceptable to use + * MOZ_ASSUME_UNREACHABLE more widely. + * + * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a + * value following a MOZ_ASSUME_UNREACHABLE call. + * + * Example usage: + * + * enum ValueType { + * VALUE_STRING, + * VALUE_INT, + * VALUE_FLOAT + * }; + * + * int ptrToInt(ValueType type, void* value) { * { - * if (node.isTrue()) - * handleTrueLiteral(); - * else if (node.isFalse()) - * handleFalseLiteral(); - * else - * MOZ_NOT_REACHED("boolean literal that's not true or false?"); + * // We know for sure that type is either INT or FLOAT, and we want this + * // code to run as quickly as possible. + * switch (type) { + * case VALUE_INT: + * return *(int*) value; + * case VALUE_FLOAT: + * return (int) *(float*) value; + * default: + * MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT"); + * } * } */ #if defined(DEBUG) -# define MOZ_NOT_REACHED(reason) \ +# define MOZ_ASSUME_UNREACHABLE(...) \ do { \ - MOZ_ASSERT(false, reason); \ - MOZ_NOT_REACHED_MARKER(); \ + MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \ + MOZ_ASSUME_UNREACHABLE_MARKER(); \ } while (0) #else -# define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER() +# define MOZ_ASSUME_UNREACHABLE(reason) MOZ_ASSUME_UNREACHABLE_MARKER() #endif /* @@ -384,4 +438,4 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) # define MOZ_ALWAYS_FALSE(expr) ((void)(expr)) #endif -#endif /* mozilla_Assertions_h_ */ +#endif /* mozilla_Assertions_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Atomics.h b/external/spidermonkey/include/ios/mozilla/Atomics.h new file mode 100644 index 0000000000..f876683c3e --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Atomics.h @@ -0,0 +1,1014 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Implements (almost always) lock-free atomic operations. The operations here + * are a subset of that which can be found in C++11's header, with a + * different API to enforce consistent memory ordering constraints. + * + * Anyone caught using |volatile| for inter-thread memory safety needs to be + * sent a copy of this header and the C++11 standard. + */ + +#ifndef mozilla_Atomics_h +#define mozilla_Atomics_h + +#include "mozilla/Assertions.h" +#include "mozilla/TypeTraits.h" + +#include + +/* + * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK + * does not have . So be sure to check for support + * along with C++0x support. + */ +#if defined(__clang__) + /* + * clang doesn't like libstdc++'s version of before GCC 4.7, + * due to the loose typing of the __sync_* family of functions done by + * GCC. We do not have a particularly good way to detect this sort of + * case at this point, so just assume that if we're on a Linux system, + * we can't use the system's . + * + * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + */ +# if !defined(__linux__) && !defined(__OpenBSD__) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ + __has_include() +# define MOZ_HAVE_CXX11_ATOMICS +# endif +/* + * Android uses a different C++ standard library that does not provide + * support for . + * + * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include + * inline definitions for the functions declared therein. This oversight + * leads to linking errors when using atomic enums. We therefore require + * GCC 4.7 or higher. + */ +#elif defined(__GNUC__) && !defined(__ANDROID__) +# include "mozilla/Compiler.h" +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ + MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# define MOZ_HAVE_CXX11_ATOMICS +# endif +#elif defined(_MSC_VER) && _MSC_VER >= 1700 +# define MOZ_HAVE_CXX11_ATOMICS +#endif + +namespace mozilla { + +/** + * An enum of memory ordering possibilities for atomics. + * + * Memory ordering is the observable state of distinct values in memory. + * (It's a separate concept from atomicity, which concerns whether an + * operation can ever be observed in an intermediate state. Don't + * conflate the two!) Given a sequence of operations in source code on + * memory, it is *not* always the case that, at all times and on all + * cores, those operations will appear to have occurred in that exact + * sequence. First, the compiler might reorder that sequence, if it + * thinks another ordering will be more efficient. Second, the CPU may + * not expose so consistent a view of memory. CPUs will often perform + * their own instruction reordering, above and beyond that performed by + * the compiler. And each core has its own memory caches, and accesses + * (reads and writes both) to "memory" may only resolve to out-of-date + * cache entries -- not to the "most recently" performed operation in + * some global sense. Any access to a value that may be used by + * multiple threads, potentially across multiple cores, must therefore + * have a memory ordering imposed on it, for all code on all + * threads/cores to have a sufficiently coherent worldview. + * + * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and + * http://en.cppreference.com/w/cpp/atomic/memory_order go into more + * detail on all this, including examples of how each mode works. + * + * Note that for simplicity and practicality, not all of the modes in + * C++11 are supported. The missing C++11 modes are either subsumed by + * the modes we provide below, or not relevant for the CPUs we support + * in Gecko. These three modes are confusing enough as it is! + */ +enum MemoryOrdering { + /* + * Relaxed ordering is the simplest memory ordering: none at all. + * When the result of a write is observed, nothing may be inferred + * about other memory. Writes ostensibly performed "before" on the + * writing thread may not yet be visible. Writes performed "after" on + * the writing thread may already be visible, if the compiler or CPU + * reordered them. (The latter can happen if reads and/or writes get + * held up in per-processor caches.) Relaxed ordering means + * operations can always use cached values (as long as the actual + * updates to atomic values actually occur, correctly, eventually), so + * it's usually the fastest sort of atomic access. For this reason, + * *it's also the most dangerous kind of access*. + * + * Relaxed ordering is good for things like process-wide statistics + * counters that don't need to be consistent with anything else, so + * long as updates themselves are atomic. (And so long as any + * observations of that value can tolerate being out-of-date -- if you + * need some sort of up-to-date value, you need some sort of other + * synchronizing operation.) It's *not* good for locks, mutexes, + * reference counts, etc. that mediate access to other memory, or must + * be observably consistent with other memory. + * + * x86 architectures don't take advantage of the optimization + * opportunities that relaxed ordering permits. Thus it's possible + * that using relaxed ordering will "work" on x86 but fail elsewhere + * (ARM, say, which *does* implement non-sequentially-consistent + * relaxed ordering semantics). Be extra-careful using relaxed + * ordering if you can't easily test non-x86 architectures! + */ + Relaxed, + /* + * When an atomic value is updated with ReleaseAcquire ordering, and + * that new value is observed with ReleaseAcquire ordering, prior + * writes (atomic or not) are also observable. What ReleaseAcquire + * *doesn't* give you is any observable ordering guarantees for + * ReleaseAcquire-ordered operations on different objects. For + * example, if there are two cores that each perform ReleaseAcquire + * operations on separate objects, each core may or may not observe + * the operations made by the other core. The only way the cores can + * be synchronized with ReleaseAcquire is if they both + * ReleaseAcquire-access the same object. This implies that you can't + * necessarily describe some global total ordering of ReleaseAcquire + * operations. + * + * ReleaseAcquire ordering is good for (as the name implies) atomic + * operations on values controlling ownership of things: reference + * counts, mutexes, and the like. However, if you are thinking about + * using these to implement your own locks or mutexes, you should take + * a good, hard look at actual lock or mutex primitives first. + */ + ReleaseAcquire, + /* + * When an atomic value is updated with SequentiallyConsistent + * ordering, all writes observable when the update is observed, just + * as with ReleaseAcquire ordering. But, furthermore, a global total + * ordering of SequentiallyConsistent operations *can* be described. + * For example, if two cores perform SequentiallyConsistent operations + * on separate objects, one core will observably perform its update + * (and all previous operations will have completed), then the other + * core will observably perform its update (and all previous + * operations will have completed). (Although those previous + * operations aren't themselves ordered -- they could be intermixed, + * or ordered if they occur on atomic values with ordering + * requirements.) SequentiallyConsistent is the *simplest and safest* + * ordering of atomic operations -- it's always as if one operation + * happens, then another, then another, in some order -- and every + * core observes updates to happen in that single order. Because it + * has the most synchronization requirements, operations ordered this + * way also tend to be slowest. + * + * SequentiallyConsistent ordering can be desirable when multiple + * threads observe objects, and they all have to agree on the + * observable order of changes to them. People expect + * SequentiallyConsistent ordering, even if they shouldn't, when + * writing code, atomic or otherwise. SequentiallyConsistent is also + * the ordering of choice when designing lockless data structures. If + * you don't know what order to use, use this one. + */ + SequentiallyConsistent, +}; + +} // namespace mozilla + +// Build up the underlying intrinsics. +#ifdef MOZ_HAVE_CXX11_ATOMICS + +# include + +namespace mozilla { +namespace detail { + +/* + * We provide CompareExchangeFailureOrder to work around a bug in some + * versions of GCC's header. See bug 898491. + */ +template struct AtomicOrderConstraints; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; + static const std::memory_order LoadOrder = std::memory_order_relaxed; + static const std::memory_order StoreOrder = std::memory_order_relaxed; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_relaxed; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; + static const std::memory_order LoadOrder = std::memory_order_acquire; + static const std::memory_order StoreOrder = std::memory_order_release; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_acquire; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; + static const std::memory_order LoadOrder = std::memory_order_seq_cst; + static const std::memory_order StoreOrder = std::memory_order_seq_cst; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_seq_cst; +}; + +template +struct IntrinsicBase +{ + typedef std::atomic ValueType; + typedef AtomicOrderConstraints OrderedOp; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T load(const typename Base::ValueType& ptr) { + return ptr.load(Base::OrderedOp::LoadOrder); + } + static void store(typename Base::ValueType& ptr, T val) { + ptr.store(val, Base::OrderedOp::StoreOrder); + } + static T exchange(typename Base::ValueType& ptr, T val) { + return ptr.exchange(val, Base::OrderedOp::AtomicRMWOrder); + } + static bool compareExchange(typename Base::ValueType& ptr, T oldVal, T newVal) { + return ptr.compare_exchange_strong(oldVal, newVal, + Base::OrderedOp::AtomicRMWOrder, + Base::OrderedOp::CompareExchangeFailureOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T add(typename Base::ValueType& ptr, T val) { + return ptr.fetch_add(val, Base::OrderedOp::AtomicRMWOrder); + } + static T sub(typename Base::ValueType& ptr, T val) { + return ptr.fetch_sub(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T* add(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_add(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + static T* sub(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_sub(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + private: + /* + * GCC 4.6's header has a bug where adding X to an + * atomic is not the same as adding X to a T*. Hence the need + * for this function to provide the correct addend. + */ + static ptrdiff_t fixupAddend(ptrdiff_t val) { +#if defined(__clang__) || defined(_MSC_VER) + return val; +#elif defined(__GNUC__) && MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) && \ + !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) + return val * sizeof(T); +#else + return val; +#endif + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + typedef IntrinsicBase Base; + static T inc(typename Base::ValueType& ptr) { + return IntrinsicAddSub::add(ptr, 1); + } + static T dec(typename Base::ValueType& ptr) { + return IntrinsicAddSub::sub(ptr, 1); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + typedef IntrinsicBase Base; + static T or_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_or(val, Base::OrderedOp::AtomicRMWOrder); + } + static T xor_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_xor(val, Base::OrderedOp::AtomicRMWOrder); + } + static T and_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_and(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct AtomicIntrinsics + : public IntrinsicMemoryOps, public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(__GNUC__) + +namespace mozilla { +namespace detail { + +/* + * The __sync_* family of intrinsics is documented here: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html + * + * While these intrinsics are deprecated in favor of the newer __atomic_* + * family of intrincs: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html + * + * any GCC version that supports the __atomic_* intrinsics will also support + * the header and so will be handled above. We provide a version of + * atomics using the __sync_* intrinsics to support older versions of GCC. + * + * All __sync_* intrinsics that we use below act as full memory barriers, for + * both compiler and hardware reordering, except for __sync_lock_test_and_set, + * which is a only an acquire barrier. When we call __sync_lock_test_and_set, + * we add a barrier above it as appropriate. + */ + +template struct Barrier; + +/* + * Some processors (in particular, x86) don't require quite so many calls to + * __sync_sychronize as our specializations of Barrier produce. If + * performance turns out to be an issue, defining these specializations + * on a per-processor basis would be a good first tuning step. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() { __sync_synchronize(); } + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() { __sync_synchronize(); } +}; + +template +struct IntrinsicMemoryOps +{ + static T load(const T& ptr) { + Barrier::beforeLoad(); + T val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(T& ptr, T val) { + Barrier::beforeStore(); + ptr = val; + Barrier::afterStore(); + } + static T exchange(T& ptr, T val) { + // __sync_lock_test_and_set is only an acquire barrier; loads and stores + // can't be moved up from after to before it, but they can be moved down + // from before to after it. We may want a stricter ordering, so we need + // an explicit barrier. + + Barrier::beforeStore(); + return __sync_lock_test_and_set(&ptr, val); + } + static bool compareExchange(T& ptr, T oldVal, T newVal) { + return __sync_bool_compare_and_swap(&ptr, oldVal, newVal); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T ValueType; + static T add(T& ptr, T val) { + return __sync_fetch_and_add(&ptr, val); + } + static T sub(T& ptr, T val) { + return __sync_fetch_and_sub(&ptr, val); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T* ValueType; + /* + * The reinterpret_casts are needed so that + * __sync_fetch_and_{add,sub} will properly type-check. + * + * Also, these functions do not provide standard semantics for + * pointer types, so we need to adjust the addend. + */ + static ValueType add(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_add(&ptr, amount); + } + static ValueType sub(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_sub(&ptr, amount); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static T inc(T& ptr) { return IntrinsicAddSub::add(ptr, 1); } + static T dec(T& ptr) { return IntrinsicAddSub::sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static T or_(T& ptr, T val) { + return __sync_fetch_and_or(&ptr, val); + } + static T xor_(T& ptr, T val) { + return __sync_fetch_and_xor(&ptr, val); + } + static T and_(T& ptr, T val) { + return __sync_fetch_and_and(&ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(_MSC_VER) + +/* + * Windows comes with a full complement of atomic operations. + * Unfortunately, most of those aren't available for Windows XP (even if + * the compiler supports intrinsics for them), which is the oldest + * version of Windows we support. Therefore, we only provide operations + * on 32-bit datatypes for 32-bit Windows versions; for 64-bit Windows + * versions, we support 64-bit datatypes as well. + * + * To avoid namespace pollution issues, we declare whatever functions we + * need ourselves. + */ + +extern "C" { +long __cdecl _InterlockedExchangeAdd(long volatile* dst, long value); +long __cdecl _InterlockedOr(long volatile* dst, long value); +long __cdecl _InterlockedXor(long volatile* dst, long value); +long __cdecl _InterlockedAnd(long volatile* dst, long value); +long __cdecl _InterlockedExchange(long volatile *dst, long value); +long __cdecl _InterlockedCompareExchange(long volatile *dst, long newVal, long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd) +# pragma intrinsic(_InterlockedOr) +# pragma intrinsic(_InterlockedXor) +# pragma intrinsic(_InterlockedAnd) +# pragma intrinsic(_InterlockedExchange) +# pragma intrinsic(_InterlockedCompareExchange) + +namespace mozilla { +namespace detail { + +# if !defined(_M_IX86) && !defined(_M_X64) + /* + * The implementations below are optimized for x86ish systems. You + * will have to modify them if you are porting to Windows on a + * different architecture. + */ +# error "Unknown CPU type" +# endif + +/* + * The PrimitiveIntrinsics template should define |Type|, the datatype of size + * DataSize upon which we operate, and the following eight functions. + * + * static Type add(Type* ptr, Type val); + * static Type sub(Type* ptr, Type val); + * static Type or_(Type* ptr, Type val); + * static Type xor_(Type* ptr, Type val); + * static Type and_(Type* ptr, Type val); + * + * These functions perform the obvious operation on the value contained in + * |*ptr| combined with |val| and return the value previously stored in + * |*ptr|. + * + * static void store(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and must provide a full + * memory fence after the store to prevent compiler and hardware instruction + * reordering. It should also act as a compiler barrier to prevent reads and + * writes from moving to after the store. + * + * static Type exchange(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and returns the previous + * contents of *ptr; + * + * static bool compareExchange(Type* ptr, Type oldVal, Type newVal); + * + * This function atomically performs the following operation: + * + * if (*ptr == oldVal) { + * *ptr = newVal; + * return true; + * } else { + * return false; + * } + * + */ +template struct PrimitiveIntrinsics; + +template<> +struct PrimitiveIntrinsics<4> +{ + typedef long Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * _InterlockedExchangeSubtract isn't available before Windows 7, + * and we must support Windows XP. + */ + return _InterlockedExchangeAdd(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange(ptr, newVal, oldVal) == oldVal; + } +}; + +# if defined(_M_X64) + +extern "C" { +long long __cdecl _InterlockedExchangeAdd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedOr64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedXor64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedAnd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedExchange64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedCompareExchange64(long long volatile* dst, + long long newVal, + long long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd64) +# pragma intrinsic(_InterlockedOr64) +# pragma intrinsic(_InterlockedXor64) +# pragma intrinsic(_InterlockedAnd64) +# pragma intrinsic(_InterlockedExchange64) +# pragma intrinsic(_InterlockedCompareExchange64) + +template <> +struct PrimitiveIntrinsics<8> +{ + typedef __int64 Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd64(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * There is no _InterlockedExchangeSubtract64. + */ + return _InterlockedExchangeAdd64(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr64(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor64(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd64(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange64(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange64(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange64(ptr, newVal, oldVal) == oldVal; + } +}; + +# endif + +extern "C" { void _ReadWriteBarrier(); } + +# pragma intrinsic(_ReadWriteBarrier) + +template struct Barrier; + +/* + * We do not provide an afterStore method in Barrier, as Relaxed and + * ReleaseAcquire orderings do not require one, and the required barrier + * for SequentiallyConsistent is handled by PrimitiveIntrinsics. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template<> +struct Barrier +{ + static void beforeLoad() { _ReadWriteBarrier(); } + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T val) { return static_cast(val); } + static T fromPrimType(PrimType val) { return static_cast(val); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T* val) { return reinterpret_cast(val); } + static T* fromPrimType(PrimType val) { return reinterpret_cast(val); } +}; + +template +struct IntrinsicBase +{ + typedef T ValueType; + typedef PrimitiveIntrinsics Primitives; + typedef typename Primitives::Type PrimType; + static_assert(sizeof(PrimType) == sizeof(T), + "Selection of PrimitiveIntrinsics was wrong"); + typedef CastHelper Cast; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + static ValueType load(const ValueType& ptr) { + Barrier::beforeLoad(); + ValueType val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(ValueType& ptr, ValueType val) { + // For SequentiallyConsistent, Primitives::store() will generate the + // proper memory fence. Everything else just needs a barrier before + // the store. + if (Order == SequentiallyConsistent) { + Primitives::store(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + } else { + Barrier::beforeStore(); + ptr = val; + } + } + static ValueType exchange(ValueType& ptr, ValueType val) { + PrimType oldval = + Primitives::exchange(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + return Cast::fromPrimType(oldval); + } + static bool compareExchange(ValueType& ptr, ValueType oldVal, ValueType newVal) { + return Primitives::compareExchange(reinterpret_cast(&ptr), + Cast::toPrimType(oldVal), + Cast::toPrimType(newVal)); + } +}; + +template +struct IntrinsicApplyHelper : public IntrinsicBase +{ + typedef PrimType (*BinaryOp)(PrimType*, PrimType); + typedef PrimType (*UnaryOp)(PrimType*); + + static ValueType applyBinaryFunction(BinaryOp op, ValueType& ptr, + ValueType val) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + PrimType primTypeVal = Cast::toPrimType(val); + return Cast::fromPrimType(op(primTypePtr, primTypeVal)); + } + + static ValueType applyUnaryFunction(UnaryOp op, ValueType& ptr) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + return Cast::fromPrimType(op(primTypePtr)); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::add, ptr, val); + } + static ValueType sub(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::sub, ptr, val); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::add, ptr, + (ValueType)(amount * sizeof(ValueType))); + } + static ValueType sub(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::sub, ptr, + (ValueType)(amount * sizeof(ValueType))); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static ValueType inc(ValueType& ptr) { return add(ptr, 1); } + static ValueType dec(ValueType& ptr) { return sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static ValueType or_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::or_, ptr, val); + } + static ValueType xor_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::xor_, ptr, val); + } + static ValueType and_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::and_, ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#else +# error "Atomic compiler intrinsics are not supported on your platform" +#endif + +namespace mozilla { + +namespace detail { + +template +class AtomicBase +{ + // We only support 32-bit types on 32-bit Windows, which constrains our + // implementation elsewhere. But we support pointer-sized types everywhere. + static_assert(sizeof(T) == 4 || (sizeof(uintptr_t) == 8 && sizeof(T) == 8), + "mozilla/Atomics.h only supports 32-bit and pointer-sized types"); + + protected: + typedef typename detail::AtomicIntrinsics Intrinsics; + typename Intrinsics::ValueType mValue; + + public: + AtomicBase() : mValue() {} + AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + + operator T() const { return Intrinsics::load(mValue); } + + T operator=(T aValue) { + Intrinsics::store(mValue, aValue); + return aValue; + } + + /** + * Performs an atomic swap operation. aValue is stored and the previous + * value of this variable is returned. + */ + T exchange(T aValue) { + return Intrinsics::exchange(mValue, aValue); + } + + /** + * Performs an atomic compare-and-swap operation and returns true if it + * succeeded. This is equivalent to atomically doing + * + * if (mValue == aOldValue) { + * mValue = aNewValue; + * return true; + * } else { + * return false; + * } + */ + bool compareExchange(T aOldValue, T aNewValue) { + return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); + } + + private: + template + AtomicBase(const AtomicBase& aCopy) MOZ_DELETE; +}; + +template +class AtomicBaseIncDec : public AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + AtomicBaseIncDec() : Base() {} + AtomicBaseIncDec(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } + T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } + T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } + T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } + + private: + template + AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) MOZ_DELETE; +}; + +} // namespace detail + +/** + * A wrapper for a type that enforces that all memory accesses are atomic. + * + * In general, where a variable |T foo| exists, |Atomic foo| can be used in + * its place. Implementations for integral and pointer types are provided + * below. + * + * Atomic accesses are sequentially consistent by default. You should + * use the default unless you are tall enough to ride the + * memory-ordering roller coaster (if you're not sure, you aren't) and + * you have a compelling reason to do otherwise. + * + * There is one exception to the case of atomic memory accesses: providing an + * initial value of the atomic value is not guaranteed to be atomic. This is a + * deliberate design choice that enables static atomic variables to be declared + * without introducing extra static constructors. + */ +template +class Atomic; + +/** + * Atomic implementation for integral types. + * + * In addition to atomic store and load operations, compound assignment and + * increment/decrement operators are implemented which perform the + * corresponding read-modify-write operation atomically. Finally, an atomic + * swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator+=(T delta) { return Base::Intrinsics::add(Base::mValue, delta) + delta; } + T operator-=(T delta) { return Base::Intrinsics::sub(Base::mValue, delta) - delta; } + T operator|=(T val) { return Base::Intrinsics::or_(Base::mValue, val) | val; } + T operator^=(T val) { return Base::Intrinsics::xor_(Base::mValue, val) ^ val; } + T operator&=(T val) { return Base::Intrinsics::and_(Base::mValue, val) & val; } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for pointer types. + * + * An atomic compare-and-swap primitive for pointer variables is provided, as + * are atomic increment and decement operators. Also provided are the compound + * assignment operators for addition and subtraction. Atomic swap (via + * exchange()) is included as well. + */ +template +class Atomic : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T* aInit) : Base(aInit) {} + + using Base::operator=; + + T* operator+=(ptrdiff_t delta) { + return Base::Intrinsics::add(Base::mValue, delta) + delta; + } + T* operator-=(ptrdiff_t delta) { + return Base::Intrinsics::sub(Base::mValue, delta) - delta; + } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for enum types. + * + * The atomic store and load operations and the atomic swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Atomics_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Attributes.h b/external/spidermonkey/include/ios/mozilla/Attributes.h index 89f3641fc9..6ea9776fbf 100644 --- a/external/spidermonkey/include/ios/mozilla/Attributes.h +++ b/external/spidermonkey/include/ios/mozilla/Attributes.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of various class and method modifier attributes. */ -#ifndef mozilla_Attributes_h_ -#define mozilla_Attributes_h_ +#ifndef mozilla_Attributes_h +#define mozilla_Attributes_h #include "mozilla/Compiler.h" @@ -117,11 +118,18 @@ * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a * function at compile time. A constexpr function cannot examine any values * except its arguments and can have no side effects except its return value. + * The MOZ_CONSTEXPR_VAR specifier tells a C++11 compiler that a variable's + * value may be computed at compile time. It should be prefered to just + * marking variables as MOZ_CONSTEXPR because if the compiler does not support + * constexpr it will fall back to making the variable const, and some compilers + * do not accept variables being marked both const and constexpr. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR # define MOZ_CONSTEXPR constexpr +# define MOZ_CONSTEXPR_VAR constexpr #else # define MOZ_CONSTEXPR /* no support */ +# define MOZ_CONSTEXPR_VAR const #endif /* @@ -382,18 +390,42 @@ * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is * expected to live on the stack, so it is a compile-time error to use it, or * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). It may be a base or - * a member of another class only if both classes are marked with this - * annotation. + * a new expression (unless placement new is being used). If a member of + * another class uses this class, or if another class inherits from this + * class, then it is considered to be a stack class as well, although this + * attribute need not be provided in such cases. + * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack or in static storage, so it is a compile-time + * error to use it, or an array of such objects, as the type of a new + * expression (unless placement new is being used). If a member of another + * class uses this class, or if another class inherits from this class, then + * it is considered to be a non-heap class as well, although this attribute + * need not be provided in such cases. */ #ifdef MOZ_CLANG_PLUGIN # define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) # define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) +# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) #else # define MOZ_MUST_OVERRIDE /* nothing */ # define MOZ_STACK_CLASS /* nothing */ +# define MOZ_NONHEAP_CLASS /* nothing */ #endif /* MOZ_CLANG_PLUGIN */ +/* + * MOZ_THIS_IN_INITIALIZER_LIST is used to avoid a warning when we know that + * it's safe to use 'this' in an initializer list. + */ +#ifdef _MSC_VER +# define MOZ_THIS_IN_INITIALIZER_LIST() \ + __pragma(warning(push)) \ + __pragma(warning(disable:4355)) \ + this \ + __pragma(warning(pop)) +#else +# define MOZ_THIS_IN_INITIALIZER_LIST() this +#endif + #endif /* __cplusplus */ -#endif /* mozilla_Attributes_h_ */ +#endif /* mozilla_Attributes_h */ diff --git a/external/spidermonkey/include/ios/mozilla/BloomFilter.h b/external/spidermonkey/include/ios/mozilla/BloomFilter.h index 8680ef2907..afe4b72b80 100644 --- a/external/spidermonkey/include/ios/mozilla/BloomFilter.h +++ b/external/spidermonkey/include/ios/mozilla/BloomFilter.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * A counting Bloom filter implementation. This allows consumers to @@ -10,14 +11,14 @@ * incorrectly answer "yes" when the correct answer is "no"). */ -#ifndef mozilla_BloomFilter_h_ -#define mozilla_BloomFilter_h_ +#ifndef mozilla_BloomFilter_h +#define mozilla_BloomFilter_h #include "mozilla/Assertions.h" #include "mozilla/Likely.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Util.h" +#include #include namespace mozilla { @@ -105,7 +106,7 @@ class BloomFilter */ public: BloomFilter() { - MOZ_STATIC_ASSERT(KeySize <= keyShift, "KeySize too big"); + static_assert(KeySize <= keyShift, "KeySize too big"); // Should we have a custom operator new using calloc instead and // require that we're allocated via the operator? @@ -231,4 +232,4 @@ BloomFilter::mightContain(const T* t) const } // namespace mozilla -#endif /* mozilla_BloomFilter_h_ */ +#endif /* mozilla_BloomFilter_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Casting.h b/external/spidermonkey/include/ios/mozilla/Casting.h index b1e81c33fa..76df0ef27e 100644 --- a/external/spidermonkey/include/ios/mozilla/Casting.h +++ b/external/spidermonkey/include/ios/mozilla/Casting.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cast operations to supplement the built-in casting operations. */ -#ifndef mozilla_Casting_h_ -#define mozilla_Casting_h_ +#ifndef mozilla_Casting_h +#define mozilla_Casting_h #include "mozilla/Assertions.h" #include "mozilla/TypeTraits.h" @@ -15,6 +16,27 @@ namespace mozilla { +/** + * Return a value of type |To|, containing the underlying bit pattern of |from|. + * + * |To| and |From| must be types of the same size; be careful of cross-platform + * size differences, or this might fail to compile on some but not all + * platforms. + */ +template +inline To +BitwiseCast(const From from) +{ + static_assert(sizeof(From) == sizeof(To), + "To and From must have the same size"); + union { + From from; + To to; + } u; + u.from = from; + return u.to; +} + namespace detail { enum ToSignedness { ToIsSigned, ToIsUnsigned }; @@ -43,7 +65,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return from <= From(To(-1)); } }; @@ -52,7 +74,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -61,8 +83,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedUnsignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedUnsignedCheck::checkBounds(from); } }; @@ -72,7 +94,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (from < 0) return false; if (sizeof(To) >= sizeof(From)) @@ -93,7 +115,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -102,7 +124,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); return from <= From(MaxValue); } @@ -112,8 +134,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedSignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedSignedCheck::checkBounds(from); } }; @@ -123,7 +145,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (sizeof(From) <= sizeof(To)) return true; const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); @@ -141,15 +163,15 @@ template class BoundsChecker { public: - static bool check(const From from) { return true; } + static bool checkBounds(const From from) { return true; } }; template class BoundsChecker { public: - static bool check(const From from) { - return BoundsCheckImpl::check(from); + static bool checkBounds(const From from) { + return BoundsCheckImpl::checkBounds(from); } }; @@ -157,7 +179,7 @@ template inline bool IsInBounds(const From from) { - return BoundsChecker::check(from); + return BoundsChecker::checkBounds(from); } } // namespace detail @@ -177,4 +199,4 @@ SafeCast(const From from) } // namespace mozilla -#endif /* mozilla_Casting_h_ */ +#endif /* mozilla_Casting_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Char16.h b/external/spidermonkey/include/ios/mozilla/Char16.h index c6f9f87d44..e4b184f950 100644 --- a/external/spidermonkey/include/ios/mozilla/Char16.h +++ b/external/spidermonkey/include/ios/mozilla/Char16.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implements a UTF-16 character type. */ -#ifndef mozilla_Char16_h_ -#define mozilla_Char16_h_ +#ifndef mozilla_Char16_h +#define mozilla_Char16_h #include "mozilla/Assertions.h" @@ -49,8 +50,8 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) -MOZ_STATIC_ASSERT(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); +static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); -#endif /* mozilla_Char16_h_ */ +#endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/ios/mozilla/CheckedInt.h b/external/spidermonkey/include/ios/mozilla/CheckedInt.h index 1dc80b032b..050cef8ed8 100644 --- a/external/spidermonkey/include/ios/mozilla/CheckedInt.h +++ b/external/spidermonkey/include/ios/mozilla/CheckedInt.h @@ -1,23 +1,23 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Provides checked integers, detecting integer overflow and divide-by-0. */ -#ifndef mozilla_CheckedInt_h_ -#define mozilla_CheckedInt_h_ +#ifndef mozilla_CheckedInt_h +#define mozilla_CheckedInt_h // Enable relying of Mozilla's MFBT for possibly-available C++11 features #define MOZ_CHECKEDINT_USE_MFBT +#include + #ifdef MOZ_CHECKEDINT_USE_MFBT # include "mozilla/Assertions.h" -# include "mozilla/StandardInteger.h" #else # include -# include -# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_DELETE #endif @@ -450,6 +450,44 @@ IsDivValid(T x, T y) !(IsSigned::value && x == MinValue::value && y == T(-1)); } +template::value> +struct IsModValidImpl; + +template +inline bool +IsModValid(T x, T y) +{ + return IsModValidImpl::run(x, y); +} + +/* + * Mod is pretty simple. + * For now, let's just use the ANSI C definition: + * If x or y are negative, the results are implementation defined. + * Consider these invalid. + * Undefined for y=0. + * The result will never exceed either x or y. + * + * Checking that x>=0 is a warning when T is unsigned. + */ + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + return y >= 1; + } +}; + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + if (x < 0) + return false; + + return y >= 1; + } +}; + template::value> struct NegateImpl; @@ -528,7 +566,7 @@ struct NegateImpl CheckedInt x(-1); // 1000 is of type int16_t, is found not to be in range for int8_t, // x is invalid - CheckedInt x(int16_t(1000)); + CheckedInt x(int16_t(1000)); // 3123456789 is of type uint32_t, is found not to be in range for int32_t, // x is invalid CheckedInt x(uint32_t(3123456789)); @@ -561,12 +599,12 @@ class CheckedInt template CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); } - friend class detail::NegateImpl; + friend struct detail::NegateImpl; public: /** @@ -585,16 +623,27 @@ class CheckedInt : mValue(T(value)), mIsValid(detail::IsInRange(value)) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); + } + + template + friend class CheckedInt; + + template + CheckedInt toChecked() const + { + CheckedInt ret(mValue); + ret.mIsValid = ret.mIsValid && mIsValid; + return ret; } /** Constructs a valid checked integer with initial value 0 */ CheckedInt() : mValue(0), mIsValid(true) { - MOZ_STATIC_ASSERT(detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value, + "This type is not supported by CheckedInt"); } /** @returns the actual value */ @@ -619,22 +668,31 @@ class CheckedInt const CheckedInt& rhs); template CheckedInt& operator +=(U rhs); + template friend CheckedInt operator -(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator -=(U rhs); + template friend CheckedInt operator *(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator *=(U rhs); + template friend CheckedInt operator /(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator /=(U rhs); + template + friend CheckedInt operator %(const CheckedInt& lhs, + const CheckedInt& rhs); + template + CheckedInt& operator %=(U rhs); + CheckedInt operator -() const { return detail::NegateImpl::negate(*this); @@ -726,6 +784,7 @@ MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) +MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) #undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR @@ -757,9 +816,9 @@ template inline typename detail::CastToCheckedIntImpl::ReturnType castToCheckedInt(U u) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); return detail::CastToCheckedIntImpl::run(u); } @@ -786,6 +845,7 @@ MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) +MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) #undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS @@ -815,4 +875,4 @@ typedef CheckedInt CheckedUint64; } // namespace mozilla -#endif /* mozilla_CheckedInt_h_ */ +#endif /* mozilla_CheckedInt_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Compiler.h b/external/spidermonkey/include/ios/mozilla/Compiler.h index 58239b0e30..d1ef1e79aa 100644 --- a/external/spidermonkey/include/ios/mozilla/Compiler.h +++ b/external/spidermonkey/include/ios/mozilla/Compiler.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ -#ifndef mozilla_Compiler_h_ -#define mozilla_Compiler_h_ +#ifndef mozilla_Compiler_h +#define mozilla_Compiler_h #if !defined(__clang__) && defined(__GNUC__) @@ -28,4 +29,4 @@ #endif -#endif /* mozilla_Compiler_h_ */ +#endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Constants.h b/external/spidermonkey/include/ios/mozilla/Constants.h index 904b30145a..86bbb6b354 100644 --- a/external/spidermonkey/include/ios/mozilla/Constants.h +++ b/external/spidermonkey/include/ios/mozilla/Constants.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt math constants. */ -#ifndef mozilla_Constants_h_ -#define mozilla_Constants_h_ +#ifndef mozilla_Constants_h +#define mozilla_Constants_h #ifndef M_PI # define M_PI 3.14159265358979323846 #endif -#endif /* mozilla_Constants_h_ */ +#endif /* mozilla_Constants_h */ diff --git a/external/spidermonkey/include/ios/mozilla/DebugOnly.h b/external/spidermonkey/include/ios/mozilla/DebugOnly.h index 1f78ed7989..e5f0d729b5 100644 --- a/external/spidermonkey/include/ios/mozilla/DebugOnly.h +++ b/external/spidermonkey/include/ios/mozilla/DebugOnly.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * assertions). */ -#ifndef mozilla_DebugOnly_h_ -#define mozilla_DebugOnly_h_ +#ifndef mozilla_DebugOnly_h +#define mozilla_DebugOnly_h namespace mozilla { @@ -74,4 +75,4 @@ class DebugOnly } -#endif /* mozilla_DebugOnly_h_ */ +#endif /* mozilla_DebugOnly_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Decimal.h b/external/spidermonkey/include/ios/mozilla/Decimal.h index 8032fd6e23..3c67d784c9 100644 --- a/external/spidermonkey/include/ios/mozilla/Decimal.h +++ b/external/spidermonkey/include/ios/mozilla/Decimal.h @@ -38,7 +38,7 @@ #define Decimal_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" +#include #include "mozilla/Types.h" #include diff --git a/external/spidermonkey/include/ios/mozilla/Endian.h b/external/spidermonkey/include/ios/mozilla/Endian.h index 5d2f905b41..dc6d11d3ba 100644 --- a/external/spidermonkey/include/ios/mozilla/Endian.h +++ b/external/spidermonkey/include/ios/mozilla/Endian.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -59,16 +60,16 @@ * }; */ -#ifndef mozilla_Endian_h_ -#define mozilla_Endian_h_ +#ifndef mozilla_Endian_h +#define mozilla_Endian_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/DebugOnly.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" +#include #include #if defined(_MSC_VER) && _MSC_VER >= 1300 @@ -636,4 +637,4 @@ class NativeEndian MOZ_FINAL : public detail::Endian } /* namespace mozilla */ -#endif /* mozilla_Endian_h_ */ +#endif /* mozilla_Endian_h */ diff --git a/external/spidermonkey/include/ios/mozilla/EnumSet.h b/external/spidermonkey/include/ios/mozilla/EnumSet.h index b18b005669..95c5608cf4 100644 --- a/external/spidermonkey/include/ios/mozilla/EnumSet.h +++ b/external/spidermonkey/include/ios/mozilla/EnumSet.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,7 +10,8 @@ #define mozilla_EnumSet_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" + +#include namespace mozilla { @@ -172,4 +174,4 @@ class EnumSet } // namespace mozilla -#endif // mozilla_EnumSet_h_ +#endif /* mozilla_EnumSet_h_*/ diff --git a/external/spidermonkey/include/ios/mozilla/FloatingPoint.h b/external/spidermonkey/include/ios/mozilla/FloatingPoint.h index 30af2217b1..d80f6a7234 100644 --- a/external/spidermonkey/include/ios/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/ios/mozilla/FloatingPoint.h @@ -1,16 +1,19 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various predicates and operations on IEEE-754 floating point types. */ -#ifndef mozilla_FloatingPoint_h_ -#define mozilla_FloatingPoint_h_ +#ifndef mozilla_FloatingPoint_h +#define mozilla_FloatingPoint_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" +#include "mozilla/Casting.h" + +#include namespace mozilla { @@ -35,80 +38,58 @@ namespace mozilla { * the case. But we required this in implementations of these algorithms that * preceded this header, so we shouldn't break anything if we continue doing so. */ -MOZ_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); +static_assert(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); const unsigned DoubleExponentBias = 1023; const unsigned DoubleExponentShift = 52; -namespace detail { - const uint64_t DoubleSignBit = 0x8000000000000000ULL; const uint64_t DoubleExponentBits = 0x7ff0000000000000ULL; const uint64_t DoubleSignificandBits = 0x000fffffffffffffULL; -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleExponentBits) == 0, - "sign bit doesn't overlap exponent bits"); -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleSignificandBits) == 0, - "sign bit doesn't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleExponentBits & DoubleSignificandBits) == 0, - "exponent bits don't overlap significand bits"); +static_assert((DoubleSignBit & DoubleExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((DoubleSignBit & DoubleSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((DoubleExponentBits & DoubleSignificandBits) == 0, + "exponent bits don't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == - ~uint64_t(0), - "all bits accounted for"); - -union DoublePun -{ - /* - * Every way to pun the bits of a double introduces an additional layer of - * complexity, across a multitude of platforms, architectures, and ABIs. - * Use *only* uint64_t to reduce complexity. Don't add new punning here - * without discussion! - */ - uint64_t u; - double d; -}; - -} /* namespace detail */ +static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == + ~uint64_t(0), + "all bits accounted for"); /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * A double is NaN if all exponent bits are 1 and the significand contains at * least one non-zero bit. */ - return (pun.u & detail::DoubleExponentBits) == detail::DoubleExponentBits && - (pun.u & detail::DoubleSignificandBits) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) == DoubleExponentBits && + (bits & DoubleSignificandBits) != 0; } /** Determines whether a double is +Infinity or -Infinity. */ static MOZ_ALWAYS_INLINE bool IsInfinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - return (pun.u & ~detail::DoubleSignBit) == detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & ~DoubleSignBit) == DoubleExponentBits; } /** Determines whether a double is not NaN or infinite. */ static MOZ_ALWAYS_INLINE bool IsFinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * NaN and Infinities are the only non-finite doubles, and both have all * exponent bits set to 1. */ - return (pun.u & detail::DoubleExponentBits) != detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) != DoubleExponentBits; } /** @@ -120,36 +101,30 @@ IsNegative(double d) { MOZ_ASSERT(!IsNaN(d), "NaN does not have a sign"); - union detail::DoublePun pun; - pun.d = d; - /* The sign bit is set if the double is negative. */ - return (pun.u & detail::DoubleSignBit) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleSignBit) != 0; } /** Determines whether a double represents -0. */ static MOZ_ALWAYS_INLINE bool IsNegativeZero(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Only the sign bit is set if the double is -0. */ - return pun.u == detail::DoubleSignBit; + uint64_t bits = BitwiseCast(d); + return bits == DoubleSignBit; } /** Returns the exponent portion of the double. */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * The exponent component of a double is an unsigned number, biased from its * actual value. Subtract the bias to retrieve the actual exponent. */ - return int_fast16_t((pun.u & detail::DoubleExponentBits) >> DoubleExponentShift) - + uint64_t bits = BitwiseCast(d); + return int_fast16_t((bits & DoubleExponentBits) >> DoubleExponentShift) - int_fast16_t(DoubleExponentBias); } @@ -157,28 +132,22 @@ ExponentComponent(double d) static MOZ_ALWAYS_INLINE double PositiveInfinity() { - union detail::DoublePun pun; - /* * Positive infinity has all exponent bits set, sign bit set to 0, and no * significand. */ - pun.u = detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleExponentBits); } /** Returns -Infinity. */ static MOZ_ALWAYS_INLINE double NegativeInfinity() { - union detail::DoublePun pun; - /* * Negative infinity has all exponent bits set, sign bit set to 1, and no * significand. */ - pun.u = detail::DoubleSignBit | detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleSignBit | DoubleExponentBits); } /** Constructs a NaN value with the specified sign bit and significand bits. */ @@ -186,24 +155,21 @@ static MOZ_ALWAYS_INLINE double SpecificNaN(int signbit, uint64_t significand) { MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~detail::DoubleSignificandBits) == 0); - MOZ_ASSERT(significand & detail::DoubleSignificandBits); + MOZ_ASSERT((significand & ~DoubleSignificandBits) == 0); + MOZ_ASSERT(significand & DoubleSignificandBits); - union detail::DoublePun pun; - pun.u = (signbit ? detail::DoubleSignBit : 0) | - detail::DoubleExponentBits | - significand; - MOZ_ASSERT(IsNaN(pun.d)); - return pun.d; + double d = BitwiseCast((signbit ? DoubleSignBit : 0) | + DoubleExponentBits | + significand); + MOZ_ASSERT(IsNaN(d)); + return d; } /** Computes the smallest non-zero positive double value. */ static MOZ_ALWAYS_INLINE double MinDoubleValue() { - union detail::DoublePun pun; - pun.u = 1; - return pun.d; + return BitwiseCast(uint64_t(1)); } static MOZ_ALWAYS_INLINE bool @@ -224,9 +190,22 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return mozilla::SpecificNaN(0, 0xfffffffffffffULL); + return SpecificNaN(0, 0xfffffffffffffULL); +} + +/** + * Compare two doubles for equality, *without* equating -0 to +0, and equating + * any NaN value to any other NaN value. (The normal equality operators equate + * -0 with +0, and they equate NaN to no other value.) + */ +static inline bool +DoublesAreIdentical(double d1, double d2) +{ + if (IsNaN(d1)) + return IsNaN(d2); + return BitwiseCast(d1) == BitwiseCast(d2); } } /* namespace mozilla */ -#endif /* mozilla_FloatingPoint_h_ */ +#endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/ios/mozilla/GuardObjects.h b/external/spidermonkey/include/ios/mozilla/GuardObjects.h index 6c2058938c..aeae7dcbc0 100644 --- a/external/spidermonkey/include/ios/mozilla/GuardObjects.h +++ b/external/spidermonkey/include/ios/mozilla/GuardObjects.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,6 +10,7 @@ #define mozilla_GuardObjects_h #include "mozilla/Assertions.h" +#include "mozilla/NullPtr.h" #include "mozilla/Types.h" #ifdef __cplusplus @@ -72,7 +74,7 @@ class MOZ_EXPORT GuardObjectNotifier bool* statementDone; public: - GuardObjectNotifier() : statementDone(NULL) { } + GuardObjectNotifier() : statementDone(nullptr) { } ~GuardObjectNotifier() { *statementDone = true; diff --git a/external/spidermonkey/include/ios/mozilla/HashFunctions.h b/external/spidermonkey/include/ios/mozilla/HashFunctions.h index 96242b629a..6d0d24e7b1 100644 --- a/external/spidermonkey/include/ios/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/ios/mozilla/HashFunctions.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Utilities for hashing. */ @@ -39,17 +40,18 @@ * }; * * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKey.h. + * in nsHashKeys.h. */ -#ifndef mozilla_HashFunctions_h_ -#define mozilla_HashFunctions_h_ +#ifndef mozilla_HashFunctions_h +#define mozilla_HashFunctions_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + #ifdef __cplusplus namespace mozilla { @@ -173,8 +175,8 @@ AddToHash(uint32_t hash, A* a) * catch data pointers and couldn't handle function pointers. */ - MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t), - "Strange pointer!"); + static_assert(sizeof(a) == sizeof(uintptr_t), + "Strange pointer!"); return detail::AddUintptrToHash(hash, uintptr_t(a)); } @@ -356,4 +358,5 @@ HashBytes(const void* bytes, size_t length); } /* namespace mozilla */ #endif /* __cplusplus */ -#endif /* mozilla_HashFunctions_h_ */ + +#endif /* mozilla_HashFunctions_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Likely.h b/external/spidermonkey/include/ios/mozilla/Likely.h index 6412b4943b..4f21609295 100644 --- a/external/spidermonkey/include/ios/mozilla/Likely.h +++ b/external/spidermonkey/include/ios/mozilla/Likely.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a * boolean predicate should be branch-predicted. */ -#ifndef mozilla_Likely_h_ -#define mozilla_Likely_h_ +#ifndef mozilla_Likely_h +#define mozilla_Likely_h #if defined(__clang__) || defined(__GNUC__) # define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) @@ -19,4 +20,4 @@ # define MOZ_UNLIKELY(x) (!!(x)) #endif -#endif /* mozilla_Likely_h_ */ +#endif /* mozilla_Likely_h */ diff --git a/external/spidermonkey/include/ios/mozilla/LinkedList.h b/external/spidermonkey/include/ios/mozilla/LinkedList.h index 5cfd60e4ac..c29760b3e7 100644 --- a/external/spidermonkey/include/ios/mozilla/LinkedList.h +++ b/external/spidermonkey/include/ios/mozilla/LinkedList.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -45,18 +46,19 @@ * } * * void notifyObservers(char* topic) { - * for (Observer* o = list.getFirst(); o != NULL; o = o->getNext()) - * o->Observe(topic); + * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) + * o->observe(topic); * } * }; * */ -#ifndef mozilla_LinkedList_h_ -#define mozilla_LinkedList_h_ +#ifndef mozilla_LinkedList_h +#define mozilla_LinkedList_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -69,10 +71,10 @@ template class LinkedListElement { /* - * It's convenient that we return NULL when getNext() or getPrevious() hits - * the end of the list, but doing so costs an extra word of storage in each - * linked list node (to keep track of whether |this| is the sentinel node) - * and a branch on this value in getNext/getPrevious. + * It's convenient that we return nullptr when getNext() or getPrevious() + * hits the end of the list, but doing so costs an extra word of storage in + * each linked list node (to keep track of whether |this| is the sentinel + * node) and a branch on this value in getNext/getPrevious. * * We could get rid of the extra word of storage by shoving the "is * sentinel" bit into one of the pointers, although this would, of course, @@ -107,12 +109,10 @@ class LinkedListElement LinkedListElement* prev; const bool isSentinel; - LinkedListElement* thisDuringConstruction() { return this; } - public: LinkedListElement() - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(false) { } @@ -122,8 +122,8 @@ class LinkedListElement } /* - * Get the next element in the list, or NULL if this is the last element in - * the list. + * Get the next element in the list, or nullptr if this is the last element + * in the list. */ T* getNext() { return next->asT(); @@ -133,8 +133,8 @@ class LinkedListElement } /* - * Get the previous element in the list, or NULL if this is the first element - * in the list. + * Get the previous element in the list, or nullptr if this is the first + * element in the list. */ T* getPrevious() { return prev->asT(); @@ -201,24 +201,24 @@ class LinkedListElement }; LinkedListElement(NodeKind nodeKind) - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(nodeKind == NODE_KIND_SENTINEL) { } /* - * Return |this| cast to T* if we're a normal node, or return NULL if we're - * a sentinel node. + * Return |this| cast to T* if we're a normal node, or return nullptr if + * we're a sentinel node. */ T* asT() { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } const T* asT() const { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } @@ -285,7 +285,7 @@ class LinkedList } /* - * Get the first element of the list, or NULL if the list is empty. + * Get the first element of the list, or nullptr if the list is empty. */ T* getFirst() { return sentinel.getNext(); @@ -295,7 +295,7 @@ class LinkedList } /* - * Get the last element of the list, or NULL if the list is empty. + * Get the last element of the list, or nullptr if the list is empty. */ T* getLast() { return sentinel.getPrevious(); @@ -306,7 +306,7 @@ class LinkedList /* * Get and remove the first element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popFirst() { T* ret = sentinel.getNext(); @@ -317,7 +317,7 @@ class LinkedList /* * Get and remove the last element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popLast() { T* ret = sentinel.getPrevious(); @@ -415,7 +415,7 @@ class LinkedList if (elem == t) return; } - MOZ_NOT_REACHED("element wasn't found in this list!"); + MOZ_CRASH("element wasn't found in this list!"); #endif } @@ -425,5 +425,6 @@ class LinkedList } /* namespace mozilla */ -#endif /* ifdef __cplusplus */ -#endif /* ifdef mozilla_LinkedList_h_ */ +#endif /* __cplusplus */ + +#endif /* mozilla_LinkedList_h */ diff --git a/external/spidermonkey/include/ios/mozilla/MSStdInt.h b/external/spidermonkey/include/ios/mozilla/MSStdInt.h deleted file mode 100644 index 0447f2f11b..0000000000 --- a/external/spidermonkey/include/ios/mozilla/MSStdInt.h +++ /dev/null @@ -1,247 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// Redistribution and use in source and binary forms, 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. -// -// 3. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 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 _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int32_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint32_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - - -#endif // _MSC_STDINT_H_ ] diff --git a/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h b/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h index 0a47810553..6d58691e06 100644 --- a/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h @@ -1,19 +1,20 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt maths algorithms. */ -#ifndef mozilla_MathAlgorithms_h_ -#define mozilla_MathAlgorithms_h_ +#ifndef mozilla_MathAlgorithms_h +#define mozilla_MathAlgorithms_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" #include #include +#include namespace mozilla { @@ -142,6 +143,288 @@ Abs(const long double d) return std::fabs(d); } +} // namespace mozilla + +#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) +# define MOZ_BITSCAN_WINDOWS + + extern "C" { + unsigned char _BitScanForward(unsigned long* Index, unsigned long mask); + unsigned char _BitScanReverse(unsigned long* Index, unsigned long mask); +# pragma intrinsic(_BitScanForward, _BitScanReverse) + +# if defined(_M_AMD64) || defined(_M_X64) +# define MOZ_BITSCAN_WINDOWS64 + unsigned char _BitScanForward64(unsigned long* index, unsigned __int64 mask); + unsigned char _BitScanReverse64(unsigned long* index, unsigned __int64 mask); +# pragma intrinsic(_BitScanForward64, _BitScanReverse64) +# endif + } // extern "C" + +#endif + +namespace mozilla { + +namespace detail { + +#if defined(MOZ_BITSCAN_WINDOWS) + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanReverse(&index, static_cast(u)); + return uint_fast8_t(31 - index); + } + + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanForward(&index, static_cast(u)); + return uint_fast8_t(index); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanReverse64(&index, static_cast(u)); + return uint_fast8_t(63 - index); +# else + uint32_t hi = uint32_t(u >> 32); + if (hi != 0) + return CountLeadingZeroes32(hi); + return 32 + CountLeadingZeroes32(uint32_t(u)); +# endif + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanForward64(&index, static_cast(u)); + return uint_fast8_t(index); +# else + uint32_t lo = uint32_t(u); + if (lo != 0) + return CountTrailingZeroes32(lo); + return 32 + CountTrailingZeroes32(uint32_t(u >> 32)); +# endif + } + +# ifdef MOZ_HAVE_BITSCAN64 +# undef MOZ_HAVE_BITSCAN64 +# endif + +#elif defined(__clang__) || defined(__GNUC__) + +# if defined(__clang__) +# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) +# error "A clang providing __builtin_c[lt]z is required to build" +# endif +# else + // gcc has had __builtin_clz and friends since 3.4: no need to check. +# endif + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + return __builtin_clz(u); + } + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + return __builtin_ctz(u); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { + return __builtin_clzll(u); + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { + return __builtin_ctzll(u); + } + +#else +# error "Implement these!" + inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; +#endif + +} // namespace detail + +/** + * Compute the number of high-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the highest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountLeadingZeroes32(0xF0FF1000) is 0; + * CountLeadingZeroes32(0x7F8F0001) is 1; + * CountLeadingZeroes32(0x3FFF0100) is 2; + * CountLeadingZeroes32(0x1FF50010) is 3; and so on. + */ +inline uint_fast8_t +CountLeadingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes32(u); +} + +/** + * Compute the number of low-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the lowest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountTrailingZeroes32(0x0100FFFF) is 0; + * CountTrailingZeroes32(0x7000FFFE) is 1; + * CountTrailingZeroes32(0x0080FFFC) is 2; + * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. + */ +inline uint_fast8_t +CountTrailingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes32(u); +} + +/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountLeadingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes64(u); +} + +/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountTrailingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes64(u); +} + +namespace detail { + +template +class CeilingLog2; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 32 - CountLeadingZeroes32(t - 1); + } +}; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 64 - CountLeadingZeroes64(t - 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the least power of 2 greater than or equal to |t|. + * + * CeilingLog2(0..1) is 0; + * CeilingLog2(2) is 1; + * CeilingLog2(3..4) is 2; + * CeilingLog2(5..8) is 3; + * CeilingLog2(9..16) is 4; and so on. + */ +template +inline uint_fast8_t +CeilingLog2(const T t) +{ + return detail::CeilingLog2::compute(t); +} + +/** A CeilingLog2 variant that accepts only size_t. */ +inline uint_fast8_t +CeilingLog2Size(size_t n) +{ + return CeilingLog2(n); +} + +namespace detail { + +template +class FloorLog2; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 31 - CountLeadingZeroes32(t | 1); + } +}; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 63 - CountLeadingZeroes64(t | 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the greatest power of 2 less than or equal to |t|. + * + * FloorLog2(0..1) is 0; + * FloorLog2(2..3) is 1; + * FloorLog2(4..7) is 2; + * FloorLog2(8..15) is 3; and so on. + */ +template +inline uint_fast8_t +FloorLog2(const T t) +{ + return detail::FloorLog2::compute(t); +} + +/** A FloorLog2 variant that accepts only size_t. */ +inline uint_fast8_t +FloorLog2Size(size_t n) +{ + return FloorLog2(n); +} + +/* + * Compute the smallest power of 2 greater than or equal to |x|. |x| must not + * be so great that the computed value would overflow |size_t|. + */ +inline size_t +RoundUpPow2(size_t x) +{ + MOZ_ASSERT(x <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), + "can't round up -- will overflow!"); + return size_t(1) << CeilingLog2(x); +} + } /* namespace mozilla */ -#endif /* mozilla_MathAlgorithms_h_ */ +#endif /* mozilla_MathAlgorithms_h */ diff --git a/external/spidermonkey/include/ios/mozilla/MemoryChecking.h b/external/spidermonkey/include/ios/mozilla/MemoryChecking.h index 3287e57ba1..2130990c6b 100644 --- a/external/spidermonkey/include/ios/mozilla/MemoryChecking.h +++ b/external/spidermonkey/include/ios/mozilla/MemoryChecking.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -19,8 +20,8 @@ * With no memory checker available, all macros expand to the empty statement. */ -#ifndef mozilla_MemoryChecking_h_ -#define mozilla_MemoryChecking_h_ +#ifndef mozilla_MemoryChecking_h +#define mozilla_MemoryChecking_h #if defined(MOZ_VALGRIND) #include "valgrind/memcheck.h" @@ -68,4 +69,4 @@ extern "C" { #endif -#endif /* mozilla_MemoryChecking_h_ */ +#endif /* mozilla_MemoryChecking_h */ diff --git a/external/spidermonkey/include/ios/mozilla/MemoryReporting.h b/external/spidermonkey/include/ios/mozilla/MemoryReporting.h new file mode 100644 index 0000000000..d2340ecf09 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/MemoryReporting.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Memory reporting infrastructure. */ + +#ifndef mozilla_MemoryReporting_h +#define mozilla_MemoryReporting_h + +#include + +#ifdef __cplusplus + +namespace mozilla { + +/* + * This is for functions that are like malloc_usable_size. Such functions are + * used for measuring the size of data structures. + */ +typedef size_t (*MallocSizeOf)(const void* p); + +} /* namespace mozilla */ + +#endif /* __cplusplus */ + +typedef size_t (*MozMallocSizeOf)(const void* p); + +#endif /* mozilla_MemoryReporting_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Move.h b/external/spidermonkey/include/ios/mozilla/Move.h new file mode 100644 index 0000000000..97178daaa6 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Move.h @@ -0,0 +1,166 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* C++11-style, but C++98-usable, "move references" implementation. */ + +#ifndef mozilla_Move_h +#define mozilla_Move_h + +namespace mozilla { + +/* + * "Move" References + * + * Some types can be copied much more efficiently if we know the original's + * value need not be preserved --- that is, if we are doing a "move", not a + * "copy". For example, if we have: + * + * Vector u; + * Vector v(u); + * + * the constructor for v must apply a copy constructor to each element of u --- + * taking time linear in the length of u. However, if we know we will not need u + * any more once v has been initialized, then we could initialize v very + * efficiently simply by stealing u's dynamically allocated buffer and giving it + * to v --- a constant-time operation, regardless of the size of u. + * + * Moves often appear in container implementations. For example, when we append + * to a vector, we may need to resize its buffer. This entails moving each of + * its extant elements from the old, smaller buffer to the new, larger buffer. + * But once the elements have been migrated, we're just going to throw away the + * old buffer; we don't care if they still have their values. So if the vector's + * element type can implement "move" more efficiently than "copy", the vector + * resizing should by all means use a "move" operation. Hash tables also need to + * be resized. + * + * The details of the optimization, and whether it's worth applying, vary from + * one type to the next. And while some constructor calls are moves, many really + * are copies, and can't be optimized this way. So we need: + * + * 1) a way for a particular invocation of a copy constructor to say that it's + * really a move, and that the value of the original isn't important + * afterwards (although it must still be safe to destroy); and + * + * 2) a way for a type (like Vector) to announce that it can be moved more + * efficiently than it can be copied, and provide an implementation of that + * move operation. + * + * The Move(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's 1). A MoveRef is simply a reference + * to a T, annotated to say that a copy constructor applied to it may move that + * T, instead of copying it. Finally, a constructor that accepts an MoveRef + * should perform a more efficient move, instead of a copy, providing 2). + * + * So, where we might define a copy constructor for a class C like this: + * + * C(const C& rhs) { ... copy rhs to this ... } + * + * we would declare a move constructor like this: + * + * C(MoveRef rhs) { ... move rhs to this ... } + * + * And where we might perform a copy like this: + * + * C c2(c1); + * + * we would perform a move like this: + * + * C c2(Move(c1)) + * + * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef + * to an ordinary copy constructor for a type that doesn't support a special + * move constructor, and you'll just get a copy. This means that templates can + * use Move whenever they know they won't use the original value any more, even + * if they're not sure whether the type at hand has a specialized move + * constructor. If it doesn't, the MoveRef will just convert to a T&, and + * the ordinary copy constructor will apply. + * + * A class with a move constructor can also provide a move assignment operator, + * which runs this's destructor, and then applies the move constructor to + * *this's memory. A typical definition: + * + * C& operator=(MoveRef rhs) { + * this->~C(); + * new(this) C(rhs); + * return *this; + * } + * + * With that in place, one can write move assignments like this: + * + * c2 = Move(c1); + * + * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but + * destructible state. + * + * This header file defines MoveRef and Move in the mozilla namespace. It's up + * to individual containers to annotate moves as such, by calling Move; and it's + * up to individual types to define move constructors. + * + * One hint: if you're writing a move constructor where the type has members + * that should be moved themselves, it's much nicer to write this: + * + * C(MoveRef c) : x(Move(c->x)), y(Move(c->y)) { } + * + * than the equivalent: + * + * C(MoveRef c) { new(&x) X(Move(c->x)); new(&y) Y(Move(c->y)); } + * + * especially since GNU C++ fails to notice that this does indeed initialize x + * and y, which may matter if they're const. + */ +template +class MoveRef +{ + T* pointer; + + public: + explicit MoveRef(T& t) : pointer(&t) { } + T& operator*() const { return *pointer; } + T* operator->() const { return pointer; } + operator T& () const { return *pointer; } +}; + +template +inline MoveRef +Move(T& t) +{ + return MoveRef(t); +} + +template +inline MoveRef +Move(const T& t) +{ + // With some versions of gcc, for a class C, there's an (incorrect) ambiguity + // between the C(const C&) constructor and the default C(C&&) C++11 move + // constructor, when the constructor is called with a const C& argument. + // + // This ambiguity manifests with the Move implementation above when Move is + // passed const U& for some class U. Calling Move(const U&) returns a + // MoveRef, which is then commonly passed to the U constructor, + // triggering an implicit conversion to const U&. gcc doesn't know whether to + // call U(const U&) or U(U&&), so it wrongly reports a compile error. + // + // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50442 has since been fixed, so + // this is no longer an issue for up-to-date compilers. But there's no harm + // in keeping it around for older compilers, so we might as well. See also + // bug 686280. + return MoveRef(const_cast(t)); +} + +/** Swap |t| and |u| using move-construction if possible. */ +template +inline void +Swap(T& t, T& u) +{ + T tmp(Move(t)); + t = Move(u); + u = Move(tmp); +} + +} // namespace mozilla + +#endif /* mozilla_Move_h */ diff --git a/external/spidermonkey/include/ios/mozilla/NullPtr.h b/external/spidermonkey/include/ios/mozilla/NullPtr.h index 7dcb03d734..14c0f07df2 100644 --- a/external/spidermonkey/include/ios/mozilla/NullPtr.h +++ b/external/spidermonkey/include/ios/mozilla/NullPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * constant. */ -#ifndef mozilla_NullPtr_h_ -#define mozilla_NullPtr_h_ +#ifndef mozilla_NullPtr_h +#define mozilla_NullPtr_h #include "mozilla/Compiler.h" @@ -45,4 +46,4 @@ # endif #endif -#endif /* mozilla_NullPtr_h_ */ +#endif /* mozilla_NullPtr_h */ diff --git a/external/spidermonkey/include/ios/mozilla/PodOperations.h b/external/spidermonkey/include/ios/mozilla/PodOperations.h index 6c6af27fc9..bec89fa928 100644 --- a/external/spidermonkey/include/ios/mozilla/PodOperations.h +++ b/external/spidermonkey/include/ios/mozilla/PodOperations.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -156,4 +157,4 @@ PodEqual(const T* one, const T* two, size_t len) } // namespace mozilla -#endif // mozilla_PodOperations_h_ +#endif /* mozilla_PodOperations_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Poison.h b/external/spidermonkey/include/ios/mozilla/Poison.h index c4adc23e71..75e0f081cd 100644 --- a/external/spidermonkey/include/ios/mozilla/Poison.h +++ b/external/spidermonkey/include/ios/mozilla/Poison.h @@ -9,13 +9,14 @@ * an address that leads to a safe crash when dereferenced. */ -#ifndef mozilla_Poison_h_ -#define mozilla_Poison_h_ +#ifndef mozilla_Poison_h +#define mozilla_Poison_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + MOZ_BEGIN_EXTERN_C extern MFBT_DATA uintptr_t gMozillaPoisonValue; @@ -36,11 +37,11 @@ inline uintptr_t mozPoisonValue() */ inline void mozWritePoison(void* aPtr, size_t aSize) { - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); const uintptr_t POISON = mozPoisonValue(); char* p = (char*)aPtr; char* limit = p + aSize; + MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); + MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); for (; p < limit; p += sizeof(uintptr_t)) { *((uintptr_t*)p) = POISON; } @@ -58,4 +59,4 @@ extern MFBT_DATA uintptr_t gMozillaPoisonSize; MOZ_END_EXTERN_C -#endif /* mozilla_Poison_h_ */ +#endif /* mozilla_Poison_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Range.h b/external/spidermonkey/include/ios/mozilla/Range.h index e14594d09d..4e02d962b5 100644 --- a/external/spidermonkey/include/ios/mozilla/Range.h +++ b/external/spidermonkey/include/ios/mozilla/Range.h @@ -1,12 +1,11 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef mozilla_Range_h_ -#define mozilla_Range_h_ +#ifndef mozilla_Range_h +#define mozilla_Range_h #include "mozilla/NullPtr.h" #include "mozilla/RangedPtr.h" @@ -40,10 +39,13 @@ class Range return mStart[offset]; } + const T& operator[](size_t offset) const { + return mStart[offset]; + } + operator ConvertibleToBool() const { return mStart ? &Range::nonNull : 0; } }; } // namespace mozilla -#endif // mozilla_Range_h_ - +#endif /* mozilla_Range_h */ diff --git a/external/spidermonkey/include/ios/mozilla/RangedPtr.h b/external/spidermonkey/include/ios/mozilla/RangedPtr.h index 7ce19d071f..493fcdbaee 100644 --- a/external/spidermonkey/include/ios/mozilla/RangedPtr.h +++ b/external/spidermonkey/include/ios/mozilla/RangedPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,11 +9,12 @@ * construction. */ -#ifndef mozilla_RangedPtr_h_ -#define mozilla_RangedPtr_h_ +#ifndef mozilla_RangedPtr_h +#define mozilla_RangedPtr_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #include "mozilla/Util.h" namespace mozilla { @@ -59,7 +61,7 @@ class RangedPtr #ifdef DEBUG return RangedPtr(p, rangeStart, rangeEnd); #else - return RangedPtr(p, NULL, size_t(0)); + return RangedPtr(p, nullptr, size_t(0)); #endif } @@ -251,4 +253,4 @@ class RangedPtr } /* namespace mozilla */ -#endif /* mozilla_RangedPtr_h_ */ +#endif /* mozilla_RangedPtr_h */ diff --git a/external/spidermonkey/include/ios/mozilla/ReentrancyGuard.h b/external/spidermonkey/include/ios/mozilla/ReentrancyGuard.h new file mode 100644 index 0000000000..d589f368a2 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/ReentrancyGuard.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Small helper class for asserting uses of a class are non-reentrant. */ + +#ifndef mozilla_ReentrancyGuard_h +#define mozilla_ReentrancyGuard_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/GuardObjects.h" + +namespace mozilla { + +/* Useful for implementing containers that assert non-reentrancy */ +class ReentrancyGuard +{ + MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER +#ifdef DEBUG + bool& entered; +#endif + + public: + template +#ifdef DEBUG + ReentrancyGuard(T& obj + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : entered(obj.entered) +#else + ReentrancyGuard(T& + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) +#endif + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; +#ifdef DEBUG + MOZ_ASSERT(!entered); + entered = true; +#endif + } + ~ReentrancyGuard() + { +#ifdef DEBUG + entered = false; +#endif + } + + private: + ReentrancyGuard(const ReentrancyGuard&) MOZ_DELETE; + void operator=(const ReentrancyGuard&) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_ReentrancyGuard_h */ diff --git a/external/spidermonkey/include/ios/mozilla/RefPtr.h b/external/spidermonkey/include/ios/mozilla/RefPtr.h index 9f4163a21a..3c275afdc7 100644 --- a/external/spidermonkey/include/ios/mozilla/RefPtr.h +++ b/external/spidermonkey/include/ios/mozilla/RefPtr.h @@ -1,14 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Helpers for defining and using refcounted objects. */ -#ifndef mozilla_RefPtr_h_ -#define mozilla_RefPtr_h_ +#ifndef mozilla_RefPtr_h +#define mozilla_RefPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/Attributes.h" #include "mozilla/TypeTraits.h" @@ -41,13 +43,19 @@ template OutParamRef byRef(RefPtr&); * state distinguishes use-before-ref (refcount==0) from * use-after-destroy (refcount==0xffffdead). */ -#ifdef DEBUG namespace detail { +#ifdef DEBUG static const int DEAD = 0xffffdead; -} #endif -template +// This is used WeakPtr.h as well as this file. +enum RefCountAtomicity +{ + AtomicRefCount, + NonAtomicRefCount +}; + +template class RefCounted { friend class RefPtr; @@ -56,8 +64,6 @@ class RefCounted RefCounted() : refCnt(0) { } ~RefCounted() { MOZ_ASSERT(refCnt == detail::DEAD); - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from RefCounted"); } public: @@ -87,7 +93,33 @@ class RefCounted } private: - int refCnt; + typename Conditional, int>::Type refCnt; +}; + +} + +template +class RefCounted : public detail::RefCounted +{ + public: + ~RefCounted() { + static_assert(IsBaseOf::value, + "T must derive from RefCounted"); + } +}; + +/** + * AtomicRefCounted is like RefCounted, with an atomically updated + * reference counter. + */ +template +class AtomicRefCounted : public detail::RefCounted +{ + public: + ~AtomicRefCounted() { + static_assert(IsBaseOf::value, + "T must derive from AtomicRefCounted"); + } }; /** @@ -259,9 +291,6 @@ byRef(RefPtr& ptr) } // namespace mozilla -#endif // mozilla_RefPtr_h_ - - #if 0 // Command line that builds these tests @@ -416,3 +445,5 @@ main(int argc, char** argv) } #endif + +#endif /* mozilla_RefPtr_h */ diff --git a/external/spidermonkey/include/ios/mozilla/SHA1.h b/external/spidermonkey/include/ios/mozilla/SHA1.h index a6604e699f..b167648540 100644 --- a/external/spidermonkey/include/ios/mozilla/SHA1.h +++ b/external/spidermonkey/include/ios/mozilla/SHA1.h @@ -1,17 +1,18 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Simple class for computing SHA1. */ -#ifndef mozilla_SHA1_h_ -#define mozilla_SHA1_h_ +#ifndef mozilla_SHA1_h +#define mozilla_SHA1_h -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" #include +#include namespace mozilla { @@ -58,4 +59,4 @@ class SHA1Sum } /* namespace mozilla */ -#endif /* mozilla_SHA1_h_ */ +#endif /* mozilla_SHA1_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Scoped.h b/external/spidermonkey/include/ios/mozilla/Scoped.h index 677a1a3797..fc48584b3e 100644 --- a/external/spidermonkey/include/ios/mozilla/Scoped.h +++ b/external/spidermonkey/include/ios/mozilla/Scoped.h @@ -1,11 +1,13 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A number of structures to simplify scope-based RAII management. */ -#ifndef mozilla_Scoped_h_ -#define mozilla_Scoped_h_ +#ifndef mozilla_Scoped_h +#define mozilla_Scoped_h /* * Resource Acquisition Is Initialization is a programming idiom used @@ -52,6 +54,7 @@ #include "mozilla/Attributes.h" #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -193,7 +196,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { free(ptr); } }; SCOPED_TEMPLATE(ScopedFreePtr, ScopedFreePtrTraits) @@ -256,7 +259,7 @@ template struct TypeSpecificScopedPointerTraits { typedef T* type; - const static type empty() { return NULL; } + const static type empty() { return nullptr; } const static void release(type value) { if (value) @@ -268,4 +271,4 @@ SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) } /* namespace mozilla */ -#endif // mozilla_Scoped_h_ +#endif /* mozilla_Scoped_h */ diff --git a/external/spidermonkey/include/ios/mozilla/SplayTree.h b/external/spidermonkey/include/ios/mozilla/SplayTree.h index f9a10d36dd..de0235aec9 100644 --- a/external/spidermonkey/include/ios/mozilla/SplayTree.h +++ b/external/spidermonkey/include/ios/mozilla/SplayTree.h @@ -1,7 +1,6 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=99 ft=cpp: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,8 +9,8 @@ * are faster to access again. */ -#ifndef mozilla_SplayTree_h_ -#define mozilla_SplayTree_h_ +#ifndef mozilla_SplayTree_h +#define mozilla_SplayTree_h #include "mozilla/Assertions.h" #include "mozilla/NullPtr.h" @@ -282,4 +281,4 @@ class SplayTree } /* namespace mozilla */ -#endif /* mozilla_SplayTree_h_ */ +#endif /* mozilla_SplayTree_h */ diff --git a/external/spidermonkey/include/ios/mozilla/StandardInteger.h b/external/spidermonkey/include/ios/mozilla/StandardInteger.h deleted file mode 100644 index 8e4c8578f1..0000000000 --- a/external/spidermonkey/include/ios/mozilla/StandardInteger.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface for C and C++ code. */ - -#ifndef mozilla_StandardInteger_h_ -#define mozilla_StandardInteger_h_ - -/* - * The C99 standard header exposes typedefs for common fixed-width - * integer types. It would be feasible to simply #include , but - * MSVC++ versions prior to 2010 don't provide . We could solve this - * by reimplementing for MSVC++ 2008 and earlier. But then we reach - * a second problem: our custom might conflict with a - * defined by an embedder already looking to work around the MSVC++ - * absence. - * - * We address these issues in this manner: - * - * 1. If the preprocessor macro MOZ_CUSTOM_STDINT_H is defined to a path to a - * custom implementation, we will #include it. Embedders using - * a custom must define this macro to an implementation that - * will work with their embedding. - * 2. Otherwise, if we are compiling with a an MSVC++ version without - * , #include our custom reimplementation. - * 3. Otherwise, #include the standard provided by the compiler. - * - * Note that we can't call this file "stdint.h" or something case-insensitively - * equal to "stdint.h" because then MSVC (and other compilers on - * case-insensitive file systems) will include this file, rather than the system - * stdint.h, when we ask for below. - */ -#if defined(MOZ_CUSTOM_STDINT_H) -# include MOZ_CUSTOM_STDINT_H -#elif defined(_MSC_VER) && _MSC_VER < 1600 -# include "mozilla/MSStdInt.h" -#else -# include -#endif - -#endif /* mozilla_StandardInteger_h_ */ diff --git a/external/spidermonkey/include/ios/mozilla/TemplateLib.h b/external/spidermonkey/include/ios/mozilla/TemplateLib.h new file mode 100644 index 0000000000..50275fdadb --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/TemplateLib.h @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Reusable template meta-functions on types and compile-time values. Meta- + * functions are placed inside the 'tl' namespace to avoid conflict with non- + * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. + * mozilla::FloorLog2). + * + * When constexpr support becomes universal, we should probably use that instead + * of some of these templates, for simplicity. + */ + +#ifndef mozilla_TemplateLib_h +#define mozilla_TemplateLib_h + +#include +#include + +namespace mozilla { + +namespace tl { + +/** Compute min/max. */ +template +struct Min +{ + static const size_t value = I < J ? I : J; +}; +template +struct Max +{ + static const size_t value = I > J ? I : J; +}; + +/** Compute floor(log2(i)). */ +template +struct FloorLog2 +{ + static const size_t value = 1 + FloorLog2::value; +}; +template<> struct FloorLog2<0> { /* Error */ }; +template<> struct FloorLog2<1> { static const size_t value = 0; }; + +/** Compute ceiling(log2(i)). */ +template +struct CeilingLog2 +{ + static const size_t value = FloorLog2<2 * I - 1>::value; +}; + +/** Round up to the nearest power of 2. */ +template +struct RoundUpPow2 +{ + static const size_t value = size_t(1) << CeilingLog2::value; +}; +template<> +struct RoundUpPow2<0> +{ + static const size_t value = 1; +}; + +/** Compute the number of bits in the given unsigned type. */ +template +struct BitSize +{ + static const size_t value = sizeof(T) * CHAR_BIT; +}; + +/** + * Produce an N-bit mask, where N <= BitSize::value. Handle the + * language-undefined edge case when N = BitSize::value. + */ +template +struct NBitMask +{ + // Assert the precondition. On success this evaluates to 0. Otherwise it + // triggers divide-by-zero at compile time: a guaranteed compile error in + // C++11, and usually one in C++98. Add this value to |value| to assure + // its computation. + static const size_t checkPrecondition = 0 / size_t(N < BitSize::value); + static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; +}; +template<> +struct NBitMask::value> +{ + static const size_t value = size_t(-1); +}; + +/** + * For the unsigned integral type size_t, compute a mask M for N such that + * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) + */ +template +struct MulOverflowMask +{ + static const size_t value = + ~NBitMask::value - CeilingLog2::value>::value; +}; +template<> struct MulOverflowMask<0> { /* Error */ }; +template<> struct MulOverflowMask<1> { static const size_t value = 0; }; + +} // namespace tl + +} // namespace mozilla + +#endif /* mozilla_TemplateLib_h */ diff --git a/external/spidermonkey/include/ios/mozilla/ThreadLocal.h b/external/spidermonkey/include/ios/mozilla/ThreadLocal.h index 2b4eb30207..6df109821f 100644 --- a/external/spidermonkey/include/ios/mozilla/ThreadLocal.h +++ b/external/spidermonkey/include/ios/mozilla/ThreadLocal.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cross-platform lightweight thread local data wrappers. */ -#ifndef mozilla_ThreadLocal_h_ -#define mozilla_ThreadLocal_h_ +#ifndef mozilla_ThreadLocal_h +#define mozilla_ThreadLocal_h #if defined(XP_WIN) // This file will get included in any file that wants to add a profiler mark. @@ -28,6 +29,7 @@ __declspec(dllimport) unsigned long __stdcall TlsAlloc(); #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -98,15 +100,15 @@ template inline bool ThreadLocal::init() { - MOZ_STATIC_ASSERT(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); + static_assert(sizeof(T) <= sizeof(void*), + "mozilla::ThreadLocal can't be used for types larger than " + "a pointer"); MOZ_ASSERT(!initialized()); #ifdef XP_WIN key = TlsAlloc(); inited = key != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES #else - inited = !pthread_key_create(&key, NULL); + inited = !pthread_key_create(&key, nullptr); #endif return inited; } @@ -144,4 +146,4 @@ ThreadLocal::set(const T value) } // namespace mozilla -#endif // mozilla_ThreadLocal_h_ +#endif /* mozilla_ThreadLocal_h */ diff --git a/external/spidermonkey/include/ios/mozilla/TypeTraits.h b/external/spidermonkey/include/ios/mozilla/TypeTraits.h index 656bc775f8..53c0b5c2f6 100644 --- a/external/spidermonkey/include/ios/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/ios/mozilla/TypeTraits.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Template-based metaprogramming and type-testing facilities. */ -#ifndef mozilla_TypeTraits_h_ -#define mozilla_TypeTraits_h_ +#ifndef mozilla_TypeTraits_h +#define mozilla_TypeTraits_h /* * These traits are approximate copies of the traits and semantics from C++11's @@ -126,6 +127,28 @@ struct IsPointer : FalseType {}; template struct IsPointer : TrueType {}; +namespace detail { + +// __is_enum is a supported extension across all of our supported compilers. +template +struct IsEnumHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsEnum determines whether a type is an enum type. + * + * mozilla::IsEnum::value is true; + * mozilla::IsEnum::value is false; + * mozilla::IsEnum::value is false; + */ +template +struct IsEnum + : detail::IsEnumHelper::Type> +{}; + /* 20.9.4.2 Composite type traits [meta.unary.comp] */ /** @@ -197,8 +220,24 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template struct IsPod : TrueType {}; +namespace detail { + +template::value> +struct IsSignedHelper; + +template +struct IsSignedHelper : TrueType {}; + +template +struct IsSignedHelper + : IntegralConstant::value && T(-1) < T(1)> +{}; + +} // namespace detail + /** - * IsSigned determines whether a type is a signed arithmetic type. + * IsSigned determines whether a type is a signed arithmetic type. |char| is + * considered a signed type if it has the same representation as |signed char|. * * Don't use this if the type might be user-defined! You might or might not get * a compile error, depending. @@ -209,10 +248,26 @@ template struct IsPod : TrueType {}; * mozilla::IsSigned::value is true. */ template -struct IsSigned - : IntegralConstant::value && T(-1) < T(0)> +struct IsSigned : detail::IsSignedHelper {}; + +namespace detail { + +template::value> +struct IsUnsignedHelper; + +template +struct IsUnsignedHelper : FalseType {}; + +template +struct IsUnsignedHelper + : IntegralConstant::value && + (IsSame::Type, bool>::value || + T(1) < T(-1))> {}; +} // namespace detail + /** * IsUnsigned determines whether a type is an unsigned arithmetic type. * @@ -225,9 +280,7 @@ struct IsSigned * mozilla::IsUnsigned::value is false. */ template -struct IsUnsigned - : IntegralConstant::value && T(0) < T(-1)> -{}; +struct IsUnsigned : detail::IsUnsignedHelper {}; /* 20.9.5 Type property queries [meta.unary.prop.query] */ @@ -427,6 +480,160 @@ struct RemoveCV /* 20.9.7.3 Sign modifications [meta.trans.sign] */ +template +struct EnableIf; + +template +struct Conditional; + +namespace detail { + +template +struct WithC : Conditional +{}; + +template +struct WithV : Conditional +{}; + + +template +struct WithCV : WithC::Type> +{}; + +template +struct CorrespondingSigned; + +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef short Type; }; +template<> +struct CorrespondingSigned { typedef int Type; }; +template<> +struct CorrespondingSigned { typedef long Type; }; +template<> +struct CorrespondingSigned { typedef long long Type; }; + +template::Type, + bool IsSignedIntegerType = IsSigned::value && + !IsSame::value> +struct MakeSigned; + +template +struct MakeSigned +{ + typedef T Type; +}; + +template +struct MakeSigned + : WithCV::value, IsVolatile::value, + typename CorrespondingSigned::Type> +{}; + +} // namespace detail + +/** + * MakeSigned produces the corresponding signed integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already a signed integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an unsigned integer type, the signed variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the integral type of the same size as T, with the lowest rank, + * with T's const/volatile qualifiers, is produced. (This basically only acts + * to produce signed char when T = char.) + * + * mozilla::MakeSigned::Type is signed long; + * mozilla::MakeSigned::Type is volatile int; + * mozilla::MakeSigned::Type is const signed short; + * mozilla::MakeSigned::Type is const signed char; + * mozilla::MakeSigned is an error; + * mozilla::MakeSigned is an error. + */ +template +struct MakeSigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeSigned + >::Type +{}; + +namespace detail { + +template +struct CorrespondingUnsigned; + +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned short Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned int Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long long Type; }; + + +template::Type, + bool IsUnsignedIntegerType = IsUnsigned::value && + !IsSame::value> +struct MakeUnsigned; + +template +struct MakeUnsigned +{ + typedef T Type; +}; + +template +struct MakeUnsigned + : WithCV::value, IsVolatile::value, + typename CorrespondingUnsigned::Type> +{}; + +} // namespace detail + +/** + * MakeUnsigned produces the corresponding unsigned integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already an unsigned integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an signed integer type, the unsigned variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the unsigned integral type of the same size as T, with the lowest + * rank, with T's const/volatile qualifiers, is produced. (This basically only + * acts to produce unsigned char when T = char.) + * + * mozilla::MakeUnsigned::Type is unsigned long; + * mozilla::MakeUnsigned::Type is volatile unsigned int; + * mozilla::MakeUnsigned::Type is const unsigned short; + * mozilla::MakeUnsigned::Type is const unsigned char; + * mozilla::MakeUnsigned is an error; + * mozilla::MakeUnsigned is an error. + */ +template +struct MakeUnsigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeUnsigned + >::Type +{}; + /* 20.9.7.4 Array modifications [meta.trans.arr] */ /* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ @@ -451,7 +658,7 @@ struct RemoveCV * ... * }; */ -template +template struct EnableIf {}; @@ -481,4 +688,4 @@ struct Conditional } /* namespace mozilla */ -#endif /* mozilla_TypeTraits_h_ */ +#endif /* mozilla_TypeTraits_h */ diff --git a/external/spidermonkey/include/ios/mozilla/TypedEnum.h b/external/spidermonkey/include/ios/mozilla/TypedEnum.h index 889960a32d..6f595cb4c5 100644 --- a/external/spidermonkey/include/ios/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/ios/mozilla/TypedEnum.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Macros to emulate C++11 typed enums and enum classes. */ -#ifndef mozilla_TypedEnum_h_ -#define mozilla_TypedEnum_h_ +#ifndef mozilla_TypedEnum_h +#define mozilla_TypedEnum_h #include "mozilla/Attributes.h" @@ -91,16 +92,33 @@ * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do * not support it. * - * Note that the workaround implemented here is not compatible with enums - * nested inside a class. + * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested + * inside classes. To define an enum class nested inside another class, use + * MOZ_{BEGIN,END}_NESTED_ENUM_CLASS, and place a MOZ_FINISH_NESTED_ENUM_CLASS + * in namespace scope to handle bits that can only be implemented with + * namespace-scoped code. For example: + * + * class FooBar { + * + * MOZ_BEGIN_NESTED_ENUM_CLASS(Enum, int32_t) + * A, + * B = 6 + * MOZ_END_NESTED_ENUM_CLASS(Enum) + * + * }; + * + * MOZ_FINISH_NESTED_ENUM_CLASS(FooBar::Enum) */ #if defined(MOZ_HAVE_CXX11_STRONG_ENUMS) /* * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) enum class Name : type { -# define MOZ_END_ENUM_CLASS(Name) }; +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + enum class Name : type { +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) /* nothing */ #else /** * We need Name to both name a type, and scope the provided enumerator @@ -136,14 +154,14 @@ * { * return Enum::A; * } - */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) \ + */\ +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ class Name \ { \ public: \ enum Enum MOZ_ENUM_TYPE(type) \ { -# define MOZ_END_ENUM_CLASS(Name) \ +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; \ Name() {} \ Name(Enum aEnum) : mEnum(aEnum) {} \ @@ -151,7 +169,8 @@ operator Enum() const { return mEnum; } \ private: \ Enum mEnum; \ - }; \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) \ inline int operator+(const int&, const Name::Enum&) MOZ_DELETE; \ inline int operator+(const Name::Enum&, const int&) MOZ_DELETE; \ inline int operator-(const int&, const Name::Enum&) MOZ_DELETE; \ @@ -207,7 +226,11 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif +# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) +# define MOZ_END_ENUM_CLASS(Name) \ + MOZ_END_NESTED_ENUM_CLASS(Name) \ + MOZ_FINISH_NESTED_ENUM_CLASS(Name) #endif /* __cplusplus */ -#endif /* mozilla_TypedEnum_h_ */ +#endif /* mozilla_TypedEnum_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Types.h b/external/spidermonkey/include/ios/mozilla/Types.h index 56e5cb82fb..5340b2b600 100644 --- a/external/spidermonkey/include/ios/mozilla/Types.h +++ b/external/spidermonkey/include/ios/mozilla/Types.h @@ -1,28 +1,22 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt foundational types and macros. */ -#ifndef mozilla_Types_h_ -#define mozilla_Types_h_ +#ifndef mozilla_Types_h +#define mozilla_Types_h /* * This header must be valid C and C++, includable by code embedding either * SpiderMonkey or Gecko. */ -/* - * Expose all the integer types defined in C99's (and the integer - * limit and constant macros, if compiling C code or if compiling C++ code and - * the right __STDC_*_MACRO has been defined for each). These are all usable - * throughout mfbt code, and throughout Mozilla code more generally. - */ -#include "mozilla/StandardInteger.h" - -/* Also expose size_t. */ +/* Expose all types and size_t. */ #include +#include /* Implement compiler and linker macros needed for APIs. */ @@ -133,4 +127,12 @@ # define MOZ_END_EXTERN_C #endif -#endif /* mozilla_Types_h_ */ +/* + * GCC's typeof is available when decltype is not. + */ +#if defined(__GNUC__) && defined(__cplusplus) && \ + !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +# define decltype __typeof__ +#endif + +#endif /* mozilla_Types_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Util.h b/external/spidermonkey/include/ios/mozilla/Util.h index 097c5478eb..4f1c634a59 100644 --- a/external/spidermonkey/include/ios/mozilla/Util.h +++ b/external/spidermonkey/include/ios/mozilla/Util.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * new headers, or to other appropriate existing headers, not here. */ -#ifndef mozilla_Util_h_ -#define mozilla_Util_h_ +#ifndef mozilla_Util_h +#define mozilla_Util_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -196,6 +197,58 @@ class Maybe constructed = true; } + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + T* addr() { MOZ_ASSERT(constructed); return &asT(); @@ -271,7 +324,7 @@ ArrayEnd(T (&arr)[N]) /* * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for MOZ_STATIC_ASSERT() calls that + * that can't use C++ template functions and for static_assert() calls that * can't call ArrayLength() when it is not a C++11 constexpr function. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR @@ -280,4 +333,4 @@ ArrayEnd(T (&arr)[N]) # define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) #endif -#endif /* mozilla_Util_h_ */ +#endif /* mozilla_Util_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Vector.h b/external/spidermonkey/include/ios/mozilla/Vector.h new file mode 100644 index 0000000000..8759df8c06 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Vector.h @@ -0,0 +1,1190 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A type/length-parametrized vector class. */ + +#ifndef mozilla_Vector_h +#define mozilla_Vector_h + +#include "mozilla/AllocPolicy.h" +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/MathAlgorithms.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" +#include "mozilla/NullPtr.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" +#include "mozilla/TypeTraits.h" +#include "mozilla/Util.h" + +#include // for placement new + +/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4345) +#endif + +namespace mozilla { + +template +class VectorBase; + +namespace detail { + +/* + * Check that the given capacity wastes the minimal amount of space if + * allocated on the heap. This means that cap*sizeof(T) is as close to a + * power-of-two as possible. growStorageBy() is responsible for ensuring + * this. + */ +template +static bool CapacityHasExcessSpace(size_t cap) +{ + size_t size = cap * sizeof(T); + return RoundUpPow2(size) - size >= sizeof(T); +} + +/* + * This template class provides a default implementation for vector operations + * when the element type is not known to be a POD, as judged by IsPod. + */ +template +struct VectorImpl +{ + /* Destroys constructed objects in the range [begin, end). */ + static inline void destroy(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + p->~T(); + } + + /* Constructs objects in the uninitialized range [begin, end). */ + static inline void initialize(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + /* + * Copy-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(*p); + } + + /* + * Move-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(Move(*p)); + } + + /* + * Copy-constructs objects in the uninitialized range [dst, dst+n) from the + * same object u. + */ + template + static inline void copyConstructN(T* dst, size_t n, const U& u) { + for (T* end = dst + n; dst < end; ++dst) + new(dst) T(u); + } + + /* + * Grows the given buffer to have capacity newCap, preserving the objects + * constructed in the range [begin, end) and updating v. Assumes that (1) + * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will + * not overflow. + */ + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + T* newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); + if (!newbuf) + return false; + T* dst = newbuf; + T* src = v.beginNoCheck(); + for (; src < v.endNoCheck(); ++dst, ++src) + new(dst) T(Move(*src)); + VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); + v.free_(v.mBegin); + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +/* + * This partial template specialization provides a default implementation for + * vector operations when the element type is known to be a POD, as judged by + * IsPod. + */ +template +struct VectorImpl +{ + static inline void destroy(T*, T*) {} + + static inline void initialize(T* begin, T* end) { + /* + * You would think that memset would be a big win (or even break even) + * when we know T is a POD. But currently it's not. This is probably + * because |append| tends to be given small ranges and memset requires + * a function call that doesn't get inlined. + * + * memset(begin, 0, sizeof(T) * (end-begin)); + */ + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + /* + * See above memset comment. Also, notice that copyConstruct is + * currently templated (T != U), so memcpy won't work without + * requiring T == U. + * + * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); + */ + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + *dst = *p; + } + + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + copyConstruct(dst, srcbeg, srcend); + } + + static inline void copyConstructN(T* dst, size_t n, const T& t) { + for (T* end = dst + n; dst < end; ++dst) + *dst = t; + } + + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + size_t oldSize = sizeof(T) * v.mCapacity; + size_t newSize = sizeof(T) * newCap; + T* newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); + if (!newbuf) + return false; + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +} // namespace detail + +/* + * A CRTP base class for vector-like classes. Unless you really really want + * your own vector class -- and you almost certainly don't -- you should use + * mozilla::Vector instead! + * + * See mozilla::Vector for interface requirements. + */ +template +class VectorBase : private AllocPolicy +{ + /* utilities */ + + static const bool sElemIsPod = IsPod::value; + typedef detail::VectorImpl Impl; + friend struct detail::VectorImpl; + + bool growStorageBy(size_t incr); + bool convertToHeapStorage(size_t newCap); + + /* magic constants */ + + static const int sMaxInlineBytes = 1024; + + /* compute constants */ + + /* + * Consider element size to be 1 for buffer sizing if there are 0 inline + * elements. This allows us to compile when the definition of the element + * type is not visible here. + * + * Explicit specialization is only allowed at namespace scope, so in order + * to keep everything here, we use a dummy template parameter with partial + * specialization. + */ + template + struct ElemSize + { + static const size_t value = sizeof(T); + }; + template + struct ElemSize<0, Dummy> + { + static const size_t value = 1; + }; + + static const size_t sInlineCapacity = + tl::Min::value>::value; + + /* Calculate inline buffer size; avoid 0-sized array. */ + static const size_t sInlineBytes = + tl::Max<1, sInlineCapacity * ElemSize::value>::value; + + /* member data */ + + /* + * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, + * mBegin + mLength) hold valid constructed T objects. The range [mBegin + + * mLength, mBegin + mCapacity) holds uninitialized memory. The range + * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory + * previously allocated by a call to reserve(). + */ + T* mBegin; + + /* Number of elements in the vector. */ + size_t mLength; + + /* Max number of elements storable in the vector without resizing. */ + size_t mCapacity; + +#ifdef DEBUG + /* Max elements of reserved or used space in this vector. */ + size_t mReserved; +#endif + + /* Memory used for inline storage. */ + AlignedStorage storage; + +#ifdef DEBUG + friend class ReentrancyGuard; + bool entered; +#endif + + /* private accessors */ + + bool usingInlineStorage() const { + return mBegin == const_cast(this)->inlineStorage(); + } + + T* inlineStorage() { + return static_cast(storage.addr()); + } + + T* beginNoCheck() const { + return mBegin; + } + + T* endNoCheck() { + return mBegin + mLength; + } + + const T* endNoCheck() const { + return mBegin + mLength; + } + +#ifdef DEBUG + size_t reserved() const { + MOZ_ASSERT(mReserved <= mCapacity); + MOZ_ASSERT(mLength <= mReserved); + return mReserved; + } +#endif + + /* Append operations guaranteed to succeed due to pre-reserved space. */ + template void internalAppend(const U& u); + template + void internalAppendAll(const VectorBase& u); + void internalAppendN(const T& t, size_t n); + template void internalAppend(const U* begin, size_t length); + + public: + static const size_t sMaxInlineStorage = N; + + typedef T ElementType; + + VectorBase(AllocPolicy = AllocPolicy()); + VectorBase(MoveRef); /* Move constructor. */ + ThisVector& operator=(MoveRef); /* Move assignment. */ + ~VectorBase(); + + /* accessors */ + + const AllocPolicy& allocPolicy() const { + return *this; + } + + AllocPolicy& allocPolicy() { + return *this; + } + + enum { InlineLength = N }; + + size_t length() const { + return mLength; + } + + bool empty() const { + return mLength == 0; + } + + size_t capacity() const { + return mCapacity; + } + + T* begin() { + MOZ_ASSERT(!entered); + return mBegin; + } + + const T* begin() const { + MOZ_ASSERT(!entered); + return mBegin; + } + + T* end() { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + const T* end() const { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + T& operator[](size_t i) { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + T& back() { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + const T& back() const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + class Range + { + friend class VectorBase; + T* cur_; + T* end_; + Range(T* cur, T* end) : cur_(cur), end_(end) {} + + public: + Range() {} + bool empty() const { return cur_ == end_; } + size_t remain() const { return end_ - cur_; } + T& front() const { return *cur_; } + void popFront() { MOZ_ASSERT(!empty()); ++cur_; } + T popCopyFront() { MOZ_ASSERT(!empty()); return *cur_++; } + }; + + Range all() { + return Range(begin(), end()); + } + + /* mutators */ + + /** + * Given that the vector is empty and has no inline storage, grow to + * |capacity|. + */ + bool initCapacity(size_t request); + + /** + * If reserve(length() + N) succeeds, the N next appends are guaranteed to + * succeed. + */ + bool reserve(size_t request); + + /** + * Destroy elements in the range [end() - incr, end()). Does not deallocate + * or unreserve storage for those elements. + */ + void shrinkBy(size_t incr); + + /** Grow the vector by incr elements. */ + bool growBy(size_t incr); + + /** Call shrinkBy or growBy based on whether newSize > length(). */ + bool resize(size_t newLength); + + /** + * Increase the length of the vector, but don't initialize the new elements + * -- leave them as uninitialized memory. + */ + bool growByUninitialized(size_t incr); + bool resizeUninitialized(size_t newLength); + + /** Shorthand for shrinkBy(length()). */ + void clear(); + + /** Clears and releases any heap-allocated storage. */ + void clearAndFree(); + + /** + * If true, appending |needed| elements won't reallocate elements storage. + * This *doesn't* mean that infallibleAppend may be used! You still must + * reserve the extra space, even if this method indicates that appends won't + * need to reallocate elements storage. + */ + bool canAppendWithoutRealloc(size_t needed) const; + + /** + * Potentially fallible append operations. + * + * The function templates that take an unspecified type U require a const T& + * or a MoveRef. The MoveRef variants move their operands into the + * vector, instead of copying them. If they fail, the operand is left + * unmoved. + */ + template bool append(const U& u); + template + bool appendAll(const VectorBase& u); + bool appendN(const T& t, size_t n); + template bool append(const U* begin, const U* end); + template bool append(const U* begin, size_t length); + + /* + * Guaranteed-infallible append operations for use upon vectors whose + * memory has been pre-reserved. Don't use this if you haven't reserved the + * memory! + */ + template void infallibleAppend(const U& u) { + internalAppend(u); + } + void infallibleAppendN(const T& t, size_t n) { + internalAppendN(t, n); + } + template void infallibleAppend(const U* aBegin, const U* aEnd) { + internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); + } + template void infallibleAppend(const U* aBegin, size_t aLength) { + internalAppend(aBegin, aLength); + } + + void popBack(); + + T popCopy(); + + /** + * Transfers ownership of the internal buffer used by this vector to the + * caller. (It's the caller's responsibility to properly deallocate this + * buffer, in accordance with this vector's AllocPolicy.) After this call, + * the vector is empty. Since the returned buffer may need to be allocated + * (if the elements are currently stored in-place), the call can fail, + * returning nullptr. + * + * N.B. Although a T*, only the range [0, length()) is constructed. + */ + T* extractRawBuffer(); + + /** + * Transfer ownership of an array of objects into the vector. The caller + * must have allocated the array in accordance with this vector's + * AllocPolicy. + * + * N.B. This call assumes that there are no uninitialized elements in the + * passed array. + */ + void replaceRawBuffer(T* p, size_t length); + + /** + * Places |val| at position |p|, shifting existing elements from |p| onward + * one position higher. On success, |p| should not be reused because it'll + * be a dangling pointer if reallocation of the vector storage occurred; the + * return value should be used instead. On failure, nullptr is returned. + * + * Example usage: + * + * if (!(p = vec.insert(p, val))) + * + * + * + * This is inherently a linear-time operation. Be careful! + */ + T* insert(T* p, const T& val); + + /** + * Removes the element |t|, which must fall in the bounds [begin, end), + * shifting existing elements from |t + 1| onward one position lower. + */ + void erase(T* t); + + /** + * Measure the size of the vector's heap-allocated storage. + */ + size_t sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const; + + /** + * Like sizeOfExcludingThis, but also measures the size of the vector + * object (which must be heap-allocated) itself. + */ + size_t sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const; + + void swap(ThisVector& other); + + private: + VectorBase(const ThisVector&) MOZ_DELETE; + void operator=(const ThisVector&) MOZ_DELETE; +}; + +/* This does the re-entrancy check plus several other sanity checks. */ +#define MOZ_REENTRANCY_GUARD_ET_AL \ + ReentrancyGuard g(*this); \ + MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ + MOZ_ASSERT(reserved() <= mCapacity); \ + MOZ_ASSERT(mLength <= reserved()); \ + MOZ_ASSERT(mLength <= mCapacity) + +/* Vector Implementation */ + +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(AP ap) + : AP(ap), + mBegin(static_cast(storage.addr())), + mLength(0), + mCapacity(sInlineCapacity) +#ifdef DEBUG + , mReserved(sInlineCapacity), + entered(false) +#endif +{} + +/* Move constructor. */ +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(MoveRef rhs) + : AllocPolicy(rhs) +#ifdef DEBUG + , entered(false) +#endif +{ + mLength = rhs->mLength; + mCapacity = rhs->mCapacity; +#ifdef DEBUG + mReserved = rhs->mReserved; +#endif + + if (rhs->usingInlineStorage()) { + /* We can't move the buffer over in this case, so copy elements. */ + mBegin = static_cast(storage.addr()); + Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); + /* + * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. + * The elements in its in-line storage still need to be destroyed. + */ + } else { + /* + * Take src's buffer, and turn src into an empty vector using + * in-line storage. + */ + mBegin = rhs->mBegin; + rhs->mBegin = static_cast(rhs->storage.addr()); + rhs->mCapacity = sInlineCapacity; + rhs->mLength = 0; +#ifdef DEBUG + rhs->mReserved = sInlineCapacity; +#endif + } +} + +/* Move assignment. */ +template +MOZ_ALWAYS_INLINE +TV& +VectorBase::operator=(MoveRef rhs) +{ + TV* tv = static_cast(this); + tv->~TV(); + new(tv) TV(rhs); + return *tv; +} + +template +MOZ_ALWAYS_INLINE +VectorBase::~VectorBase() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); +} + +/* + * This function will create a new heap buffer with capacity newCap, + * move all elements in the inline buffer to this new buffer, + * and fail on OOM. + */ +template +inline bool +VectorBase::convertToHeapStorage(size_t newCap) +{ + MOZ_ASSERT(usingInlineStorage()); + + /* Allocate buffer. */ + MOZ_ASSERT(!detail::CapacityHasExcessSpace(newCap)); + T* newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); + if (!newBuf) + return false; + + /* Copy inline elements into heap buffer. */ + Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + + /* Switch in heap buffer. */ + mBegin = newBuf; + /* mLength is unchanged. */ + mCapacity = newCap; + return true; +} + +template +MOZ_NEVER_INLINE bool +VectorBase::growStorageBy(size_t incr) +{ + MOZ_ASSERT(mLength + incr > mCapacity); + MOZ_ASSERT_IF(!usingInlineStorage(), + !detail::CapacityHasExcessSpace(mCapacity)); + + /* + * When choosing a new capacity, its size should is as close to 2**N bytes + * as possible. 2**N-sized requests are best because they are unlikely to + * be rounded up by the allocator. Asking for a 2**N number of elements + * isn't as good, because if sizeof(T) is not a power-of-two that would + * result in a non-2**N request size. + */ + + size_t newCap; + + if (incr == 1) { + if (usingInlineStorage()) { + /* This case occurs in ~70--80% of the calls to this function. */ + size_t newSize = + tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::value; + newCap = newSize / sizeof(T); + goto convert; + } + + if (mLength == 0) { + /* This case occurs in ~0--10% of the calls to this function. */ + newCap = 1; + goto grow; + } + + /* This case occurs in ~15--20% of the calls to this function. */ + + /* + * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector + * to 1GB of memory on a 32-bit system, which is a reasonable limit. It + * also ensures that + * + * static_cast(end()) - static_cast(begin()) + * + * doesn't overflow ptrdiff_t (see bug 510319). + */ + if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::value) { + this->reportAllocOverflow(); + return false; + } + + /* + * If we reach here, the existing capacity will have a size that is already + * as close to 2^N as sizeof(T) will allow. Just double the capacity, and + * then there might be space for one more element. + */ + newCap = mLength * 2; + if (detail::CapacityHasExcessSpace(newCap)) + newCap += 1; + } else { + /* This case occurs in ~2% of the calls to this function. */ + size_t newMinCap = mLength + incr; + + /* Did mLength + incr overflow? Will newCap * sizeof(T) overflow? */ + if (newMinCap < mLength || + newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value) + { + this->reportAllocOverflow(); + return false; + } + + size_t newMinSize = newMinCap * sizeof(T); + size_t newSize = RoundUpPow2(newMinSize); + newCap = newSize / sizeof(T); + } + + if (usingInlineStorage()) { + convert: + return convertToHeapStorage(newCap); + } + +grow: + return Impl::growTo(*this, newCap); +} + +template +inline bool +VectorBase::initCapacity(size_t request) +{ + MOZ_ASSERT(empty()); + MOZ_ASSERT(usingInlineStorage()); + if (request == 0) + return true; + T* newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); + if (!newbuf) + return false; + mBegin = newbuf; + mCapacity = request; +#ifdef DEBUG + mReserved = request; +#endif + return true; +} + +template +inline bool +VectorBase::reserve(size_t request) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (request > mCapacity && !growStorageBy(request - mLength)) + return false; + +#ifdef DEBUG + if (request > mReserved) + mReserved = request; + MOZ_ASSERT(mLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); +#endif + return true; +} + +template +inline void +VectorBase::shrinkBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(incr <= mLength); + Impl::destroy(endNoCheck() - incr, endNoCheck()); + mLength -= incr; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + T* newend = endNoCheck() + incr; + Impl::initialize(endNoCheck(), newend); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growByUninitialized(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +inline bool +VectorBase::resize(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growBy(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::resizeUninitialized(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growByUninitialized(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +inline void +VectorBase::clear() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + mLength = 0; +} + +template +inline void +VectorBase::clearAndFree() +{ + clear(); + + if (usingInlineStorage()) + return; + + this->free_(beginNoCheck()); + mBegin = static_cast(storage.addr()); + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif +} + +template +inline bool +VectorBase::canAppendWithoutRealloc(size_t needed) const +{ + return mLength + needed <= mCapacity; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendAll(const VectorBase& other) +{ + internalAppend(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U& u) +{ + MOZ_ASSERT(mLength + 1 <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + new(endNoCheck()) T(u); + ++mLength; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendN(const T& t, size_t needed) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppendN(t, needed); + return true; +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendN(const T& t, size_t needed) +{ + MOZ_ASSERT(mLength + needed <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstructN(endNoCheck(), needed, t); + mLength += needed; +} + +template +inline T* +VectorBase::insert(T* p, const T& val) +{ + MOZ_ASSERT(begin() <= p); + MOZ_ASSERT(p <= end()); + size_t pos = p - begin(); + MOZ_ASSERT(pos <= mLength); + size_t oldLength = mLength; + if (pos == oldLength) { + if (!append(val)) + return nullptr; + } else { + T oldBack = back(); + if (!append(oldBack)) /* Dup the last element. */ + return nullptr; + for (size_t i = oldLength; i > pos; --i) + (*this)[i] = (*this)[i - 1]; + (*this)[pos] = val; + } + return begin() + pos; +} + +template +inline void +VectorBase::erase(T* it) +{ + MOZ_ASSERT(begin() <= it); + MOZ_ASSERT(it < end()); + while (it + 1 < end()) { + *it = *(it + 1); + ++it; + } + popBack(); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U* insBegin, const U* insEnd) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + size_t needed = PointerRangeSize(insBegin, insEnd); + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppend(insBegin, needed); + return true; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U* insBegin, size_t insLength) +{ + MOZ_ASSERT(mLength + insLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); + mLength += insLength; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U& u) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength == mCapacity && !growStorageBy(1)) + return false; + +#ifdef DEBUG + if (mLength + 1 > mReserved) + mReserved = mLength + 1; +#endif + internalAppend(u); + return true; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendAll(const VectorBase& other) +{ + return append(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U *insBegin, size_t insLength) +{ + return append(insBegin, insBegin + insLength); +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::popBack() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(!empty()); + --mLength; + endNoCheck()->~T(); +} + +template +MOZ_ALWAYS_INLINE T +VectorBase::popCopy() +{ + T ret = back(); + popBack(); + return ret; +} + +template +inline T* +VectorBase::extractRawBuffer() +{ + T* ret; + if (usingInlineStorage()) { + ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); + if (!ret) + return nullptr; + Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + /* mBegin, mCapacity are unchanged. */ + mLength = 0; + } else { + ret = mBegin; + mBegin = static_cast(storage.addr()); + mLength = 0; + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif + } + return ret; +} + +template +inline void +VectorBase::replaceRawBuffer(T* p, size_t aLength) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + + /* Destroy what we have. */ + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); + + /* Take in the new buffer. */ + if (aLength <= sInlineCapacity) { + /* + * We convert to inline storage if possible, even though p might + * otherwise be acceptable. Maybe this behaviour should be + * specifiable with an argument to this function. + */ + mBegin = static_cast(storage.addr()); + mLength = aLength; + mCapacity = sInlineCapacity; + Impl::moveConstruct(mBegin, p, p + aLength); + Impl::destroy(p, p + aLength); + this->free_(p); + } else { + mBegin = p; + mLength = aLength; + mCapacity = aLength; + } +#ifdef DEBUG + mReserved = aLength; +#endif +} + +template +inline size_t +VectorBase::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const +{ + return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); +} + +template +inline size_t +VectorBase::sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const +{ + return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); +} + +template +inline void +VectorBase::swap(TV& other) +{ + static_assert(N == 0, + "still need to implement this for N != 0"); + + // This only works when inline storage is always empty. + if (!usingInlineStorage() && other.usingInlineStorage()) { + other.mBegin = mBegin; + mBegin = inlineStorage(); + } else if (usingInlineStorage() && !other.usingInlineStorage()) { + mBegin = other.mBegin; + other.mBegin = other.inlineStorage(); + } else if (!usingInlineStorage() && !other.usingInlineStorage()) { + Swap(mBegin, other.mBegin); + } else { + // This case is a no-op, since we'd set both to use their inline storage. + } + + Swap(mLength, other.mLength); + Swap(mCapacity, other.mCapacity); +#ifdef DEBUG + Swap(mReserved, other.mReserved); +#endif +} + +/* + * STL-like container providing a short-lived, dynamic buffer. Vector calls the + * constructors/destructors of all elements stored in its internal buffer, so + * non-PODs may be safely used. Additionally, Vector will store the first N + * elements in-place before resorting to dynamic allocation. + * + * T requirements: + * - default and copy constructible, assignable, destructible + * - operations do not throw + * N requirements: + * - any value, however, N is clamped to min/max values + * AllocPolicy: + * - see "Allocation policies" in AllocPolicy.h (defaults to + * mozilla::MallocAllocPolicy) + * + * Vector is not reentrant: T member functions called during Vector member + * functions must not call back into the same object! + */ +template +class Vector + : public VectorBase > +{ + typedef VectorBase Base; + + public: + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector& operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); + } +}; + +} // namespace mozilla + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif /* mozilla_Vector_h */ diff --git a/external/spidermonkey/include/ios/mozilla/WeakPtr.h b/external/spidermonkey/include/ios/mozilla/WeakPtr.h index d61b0b37d3..c714ebf565 100644 --- a/external/spidermonkey/include/ios/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/ios/mozilla/WeakPtr.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Weak pointer functionality, implemented as a mixin for use with any class. */ @@ -13,6 +14,9 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * + * AtomicSupportsWeakPtr can be used for a variant with an atomically updated + * reference counter. + * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -55,10 +59,11 @@ * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h */ -#ifndef mozilla_WeakPtr_h_ -#define mozilla_WeakPtr_h_ +#ifndef mozilla_WeakPtr_h +#define mozilla_WeakPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -71,8 +76,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted > +template +class WeakReference : public RefCounted, Atomicity> { public: explicit WeakReference(T* p) : ptr(p) {} @@ -81,8 +86,8 @@ class WeakReference : public RefCounted > } private: - friend class WeakPtrBase >; - friend class SupportsWeakPtrBase >; + friend class WeakPtrBase; + friend class SupportsWeakPtrBase; void detach() { ptr = nullptr; } @@ -103,8 +108,8 @@ class SupportsWeakPtrBase protected: ~SupportsWeakPtrBase() { - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from SupportsWeakPtrBase"); + static_assert(IsBaseOf, T>::value, + "T must derive from SupportsWeakPtrBase"); if (weakRef) weakRef->detach(); } @@ -116,10 +121,30 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr : public SupportsWeakPtrBase > +class SupportsWeakPtr + : public SupportsWeakPtrBase > { }; +template +class AtomicSupportsWeakPtr + : public SupportsWeakPtrBase > +{ +}; + +namespace detail { + +template +struct WeakReferenceCount +{ + static const RefCountAtomicity atomicity = + IsBaseOf, T>::value + ? AtomicRefCount + : NonAtomicRefCount; +}; + +} + template class WeakPtrBase { @@ -152,9 +177,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase > +class WeakPtr : public WeakPtrBase::atomicity> > { - typedef WeakPtrBase > Base; + typedef WeakPtrBase::atomicity> > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} @@ -163,4 +188,4 @@ class WeakPtr : public WeakPtrBase > } // namespace mozilla -#endif /* ifdef mozilla_WeakPtr_h_ */ +#endif /* mozilla_WeakPtr_h */ diff --git a/external/spidermonkey/include/mac/js-config.h b/external/spidermonkey/include/mac/js-config.h index 6a77e674d7..ae4f2abf71 100644 --- a/external/spidermonkey/include/mac/js-config.h +++ b/external/spidermonkey/include/mac/js-config.h @@ -38,8 +38,8 @@ JS_HAVE_STDINT_H. */ #define JS_BYTES_PER_WORD 8 -/* Some mozilla code uses JS-friend APIs that depend on JS_METHODJIT being - correct. */ -#define JS_METHODJIT 1 +/* MOZILLA JSAPI version number components */ +#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MINOR_VERSION 0 #endif /* js_config_h___ */ diff --git a/external/spidermonkey/include/mac/js.msg b/external/spidermonkey/include/mac/js.msg index 3e57bdf174..3f665d8d54 100644 --- a/external/spidermonkey/include/mac/js.msg +++ b/external/spidermonkey/include/mac/js.msg @@ -184,7 +184,7 @@ MSG_DEF(JSMSG_BAD_OPERAND, 130, 1, JSEXN_SYNTAXERR, "invalid {0} oper MSG_DEF(JSMSG_BAD_PROP_ID, 131, 0, JSEXN_SYNTAXERR, "invalid property id") MSG_DEF(JSMSG_RESERVED_ID, 132, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") MSG_DEF(JSMSG_SYNTAX_ERROR, 133, 0, JSEXN_SYNTAXERR, "syntax error") -MSG_DEF(JSMSG_UNUSED134, 134, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 134, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") MSG_DEF(JSMSG_BAD_PROTOTYPE, 135, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") MSG_DEF(JSMSG_MISSING_EXPONENT, 136, 0, JSEXN_SYNTAXERR, "missing exponent") MSG_DEF(JSMSG_OUT_OF_MEMORY, 137, 0, JSEXN_ERR, "out of memory") @@ -193,10 +193,10 @@ MSG_DEF(JSMSG_TOO_MANY_PARENS, 139, 0, JSEXN_INTERNALERR, "too many paren MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 140, 0, JSEXN_SYNTAXERR, "unterminated comment") MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 141, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 142, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_UNUSED143, 143, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 143, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 144, 0, JSEXN_SYNTAXERR, "illegal character") MSG_DEF(JSMSG_BAD_OCTAL, 145, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_UNUSED146, 146, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 146, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 147, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") MSG_DEF(JSMSG_INVALID_BACKREF, 148, 0, JSEXN_SYNTAXERR, "non-octal digit in an escape sequence that doesn't match a back-reference") MSG_DEF(JSMSG_BAD_BACKREF, 149, 0, JSEXN_SYNTAXERR, "back-reference exceeds number of capturing parentheses") @@ -220,7 +220,7 @@ MSG_DEF(JSMSG_RESERVED_SLOT_RANGE, 166, 0, JSEXN_RANGEERR, "reserved slot ind MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode JSPrincipals") MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_UNUSED170, 170, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") @@ -286,7 +286,7 @@ MSG_DEF(JSMSG_DEPRECATED_OCTAL, 232, 0, JSEXN_SYNTAXERR, "octal literals a MSG_DEF(JSMSG_STRICT_CODE_WITH, 233, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 234, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 235, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "assignment to {0} is deprecated") +MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "can't assign to {0} in strict mode") MSG_DEF(JSMSG_BAD_BINDING, 237, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 238, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 239, 1, JSEXN_TYPEERR, "{0} is not extensible") @@ -313,16 +313,16 @@ MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 259, 0, JSEXN_TYPEERR, "can't change ob MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 260, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 261, 0, JSEXN_TYPEERR, "unsupported type for structured data") MSG_DEF(JSMSG_SC_RECURSION, 262, 0, JSEXN_INTERNALERR, "recursive object") -MSG_DEF(JSMSG_UNUSED263, 263, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 263, 0, JSEXN_ERR, "passing non-debuggable global to addDebuggee") MSG_DEF(JSMSG_BAD_CLONE_VERSION, 264, 0, JSEXN_ERR, "unsupported structured clone version") MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 265, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_UNUSED266, 266, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 266, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") MSG_DEF(JSMSG_STRICT_FUNCTION_STATEMENT, 267, 0, JSEXN_SYNTAXERR, "in strict mode code, functions may be declared only at top level or immediately within another function") MSG_DEF(JSMSG_INVALID_FOR_IN_INIT, 268, 0, JSEXN_SYNTAXERR, "for-in loop let declaration may not have an initializer") MSG_DEF(JSMSG_CLEARED_SCOPE, 269, 0, JSEXN_TYPEERR, "attempt to run compile-and-go script on a cleared scope") MSG_DEF(JSMSG_MALFORMED_ESCAPE, 270, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") MSG_DEF(JSMSG_BAD_GENEXP_BODY, 271, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_UNUSED272, 272, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_YIELD_WITHOUT_OPERAND, 272, 0, JSEXN_SYNTAXERR, "yield without a value is deprecated, and illegal in ES6 (use 'yield undefined' instead)") MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 273, 0, JSEXN_SYNTAXERR, "function statement requires a name") MSG_DEF(JSMSG_CCW_REQUIRED, 274, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 275, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") @@ -391,12 +391,21 @@ MSG_DEF(JSMSG_DATE_NOT_FINITE, 337, 0, JSEXN_RANGEERR, "date value is not MSG_DEF(JSMSG_MODULE_STATEMENT, 338, 0, JSEXN_SYNTAXERR, "module declarations may only appear at the top level of a program or module body") MSG_DEF(JSMSG_CURLY_BEFORE_MODULE, 339, 0, JSEXN_SYNTAXERR, "missing { before module body") MSG_DEF(JSMSG_CURLY_AFTER_MODULE, 340, 0, JSEXN_SYNTAXERR, "missing } after module body") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "'use asm' directive only works on function code") +MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 342, 1, JSEXN_TYPEERR, "asm.js type error: {0}") MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 343, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 0, JSEXN_ERR, "successfully compiled asm.js code") +MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 1, JSEXN_ERR, "successfully compiled asm.js code ({0})") MSG_DEF(JSMSG_BAD_ARROW_ARGS, 345, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") +MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") +MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") diff --git a/external/spidermonkey/include/mac/js/Anchor.h b/external/spidermonkey/include/mac/js/Anchor.h index d0c2476cf7..0d458e6fb6 100644 --- a/external/spidermonkey/include/mac/js/Anchor.h +++ b/external/spidermonkey/include/mac/js/Anchor.h @@ -6,8 +6,8 @@ /* JS::Anchor implementation. */ -#ifndef js_Anchor_h___ -#define js_Anchor_h___ +#ifndef js_Anchor_h +#define js_Anchor_h #include "mozilla/Attributes.h" @@ -159,4 +159,4 @@ inline Anchor::~Anchor() } // namespace JS -#endif /* js_Anchor_h___ */ +#endif /* js_Anchor_h */ diff --git a/external/spidermonkey/include/mac/js/CallArgs.h b/external/spidermonkey/include/mac/js/CallArgs.h index af78fde0a0..8027ffc71a 100644 --- a/external/spidermonkey/include/mac/js/CallArgs.h +++ b/external/spidermonkey/include/mac/js/CallArgs.h @@ -26,11 +26,12 @@ * methods' implementations, potentially under time pressure. */ -#ifndef js_CallArgs_h___ -#define js_CallArgs_h___ +#ifndef js_CallArgs_h +#define js_CallArgs_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/TypeTraits.h" #include "jstypes.h" @@ -44,6 +45,29 @@ class JSObject; typedef JSBool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); +/* Typedef for native functions that may be called in parallel. */ +typedef js::ParallelResult +(* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + +/* + * Typedef for native functions that may be called either in parallel or + * sequential execution. + */ +typedef JSBool +(* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); + +/* + * Convenience wrappers for passing in ThreadSafeNative to places that expect + * a JSNative or a JSParallelNative. + */ +template +inline JSBool +JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); + +template +inline js::ParallelResult +JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + /* * Compute |this| for the |vp| inside a JSNative, either boxing primitives or * replacing with the global object as necessary. @@ -58,6 +82,8 @@ JS_ComputeThis(JSContext *cx, JS::Value *vp); namespace JS { +extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; + /* * JS::CallReceiver encapsulates access to the callee, |this|, and eventual * return value for a function call. The principal way to create a @@ -92,30 +118,55 @@ namespace JS { * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallReceiver + +namespace detail { + +#ifdef DEBUG +extern JS_PUBLIC_API(void) +CheckIsValidConstructible(Value v); +#endif + +enum UsedRval { IncludeUsedRval, NoUsedRval }; + +template +class MOZ_STACK_CLASS UsedRvalBase; + +template<> +class MOZ_STACK_CLASS UsedRvalBase { protected: -#ifdef DEBUG mutable bool usedRval_; void setUsedRval() const { usedRval_ = true; } void clearUsedRval() const { usedRval_ = false; } -#else +}; + +template<> +class MOZ_STACK_CLASS UsedRvalBase +{ + protected: void setUsedRval() const {} void clearUsedRval() const {} +}; + +template +class MOZ_STACK_CLASS CallReceiverBase : public UsedRvalBase< +#ifdef DEBUG + WantUsedRval +#else + NoUsedRval #endif - + > +{ + protected: Value *argv_; - friend CallReceiver CallReceiverFromVp(Value *vp); - friend CallReceiver CallReceiverFromArgv(Value *argv); - public: /* * Returns the function being called, as an object. Must not be called * after rval() has been used! */ JSObject &callee() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return argv_[-2].toObject(); } @@ -124,7 +175,7 @@ class MOZ_STACK_CLASS CallReceiver * rval() has been used! */ HandleValue calleev() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return HandleValue::fromMarkedLocation(&argv_[-2]); } @@ -148,6 +199,14 @@ class MOZ_STACK_CLASS CallReceiver return JS_ComputeThis(cx, base()); } + bool isConstructing() const { +#ifdef DEBUG + if (this->usedRval_) + CheckIsValidConstructible(calleev()); +#endif + return argv_[-1].isMagic(); + } + /* * Returns the currently-set return value. The initial contents of this * value are unspecified. Once this method has been called, callee() and @@ -160,7 +219,7 @@ class MOZ_STACK_CLASS CallReceiver * fails. */ MutableHandleValue rval() const { - setUsedRval(); + this->setUsedRval(); return MutableHandleValue::fromMarkedLocation(&argv_[-2]); } @@ -171,7 +230,7 @@ class MOZ_STACK_CLASS CallReceiver Value *base() const { return argv_ - 2; } Value *spAfterCall() const { - setUsedRval(); + this->setUsedRval(); return argv_ - 1; } @@ -181,7 +240,7 @@ class MOZ_STACK_CLASS CallReceiver // it. You probably don't want to use these! void setCallee(Value aCalleev) const { - clearUsedRval(); + this->clearUsedRval(); argv_[-2] = aCalleev; } @@ -194,6 +253,15 @@ class MOZ_STACK_CLASS CallReceiver } }; +} // namespace detail + +class MOZ_STACK_CLASS CallReceiver : public detail::CallReceiverBase +{ + private: + friend CallReceiver CallReceiverFromVp(Value *vp); + friend CallReceiver CallReceiverFromArgv(Value *argv); +}; + MOZ_ALWAYS_INLINE CallReceiver CallReceiverFromArgv(Value *argv) { @@ -233,11 +301,59 @@ CallReceiverFromVp(Value *vp) * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallArgs : public CallReceiver +namespace detail { + +template +class MOZ_STACK_CLASS CallArgsBase : + public mozilla::Conditional >::Type { protected: unsigned argc_; + public: + /* Returns the number of arguments. */ + unsigned length() const { return argc_; } + + /* Returns the i-th zero-indexed argument. */ + MutableHandleValue operator[](unsigned i) const { + MOZ_ASSERT(i < argc_); + return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); + } + + /* + * Returns the i-th zero-indexed argument, or |undefined| if there's no + * such argument. + */ + HandleValue get(unsigned i) const { + return i < length() + ? HandleValue::fromMarkedLocation(&this->argv_[i]) + : UndefinedHandleValue; + } + + /* + * Returns true if the i-th zero-indexed argument is present and is not + * |undefined|. + */ + bool hasDefined(unsigned i) const { + return i < argc_ && !this->argv_[i].isUndefined(); + } + + public: + // These methods are publicly exposed, but we're less sure of the interface + // here than we'd like (because they're hackish and drop assertions). Try + // to avoid using these if you can. + + Value *array() const { return this->argv_; } + Value *end() const { return this->argv_ + argc_; } +}; + +} // namespace detail + +class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase +{ + private: friend CallArgs CallArgsFromVp(unsigned argc, Value *vp); friend CallArgs CallArgsFromSp(unsigned argc, Value *sp); @@ -249,45 +365,6 @@ class MOZ_STACK_CLASS CallArgs : public CallReceiver return args; } - public: - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - Value &operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return argv_[i]; - } - - /* Returns a mutable handle for the i-th zero-indexed argument. */ - MutableHandleValue handleAt(unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - Value get(unsigned i) const { - return i < length() ? argv_[i] : UndefinedValue(); - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !argv_[i].isUndefined(); - } - - public: - // These methods are publicly exposed, but we're less sure of the interface - // here than we'd like (because they're hackish and drop assertions). Try - // to avoid using these if you can. - - Value *array() const { return argv_; } - Value *end() const { return argv_ + argc_; } }; MOZ_ALWAYS_INLINE CallArgs @@ -345,4 +422,4 @@ JS_THIS(JSContext *cx, JS::Value *vp) */ #define JS_THIS_VALUE(cx,vp) ((vp)[1]) -#endif /* js_CallArgs_h___ */ +#endif /* js_CallArgs_h */ diff --git a/external/spidermonkey/include/mac/js/CharacterEncoding.h b/external/spidermonkey/include/mac/js/CharacterEncoding.h index 63e5cc6650..e88e08e1be 100644 --- a/external/spidermonkey/include/mac/js/CharacterEncoding.h +++ b/external/spidermonkey/include/mac/js/CharacterEncoding.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_CharacterEncoding_h___ -#define js_CharacterEncoding_h___ +#ifndef js_CharacterEncoding_h +#define js_CharacterEncoding_h #include "mozilla/Range.h" @@ -58,6 +58,20 @@ class Latin1CharsZ : public mozilla::RangedPtr char *c_str() { return reinterpret_cast(get()); } }; +class UTF8Chars : public mozilla::Range +{ + typedef mozilla::Range Base; + + public: + UTF8Chars() : Base() {} + UTF8Chars(char *aBytes, size_t aLength) + : Base(reinterpret_cast(aBytes), aLength) + {} + UTF8Chars(const char *aBytes, size_t aLength) + : Base(reinterpret_cast(const_cast(aBytes)), aLength) + {} +}; + /* * SpiderMonkey also deals directly with UTF-8 encoded text in some places. */ @@ -124,10 +138,12 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: + TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) { - JS_ASSERT(chars[length] = '\0'); + JS_ASSERT(chars[length] == '\0'); } }; @@ -142,14 +158,34 @@ class TwoByteCharsZ : public mozilla::RangedPtr * This method cannot trigger GC. */ extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(JSContext *cx, TwoByteChars tbchars); +LossyTwoByteCharsToNewLatin1CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); extern UTF8CharsZ -TwoByteCharsToNewUTF8CharsZ(JSContext *cx, TwoByteChars tbchars); +TwoByteCharsToNewUTF8CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); + +uint32_t +Utf8ToOneUcs4Char(const uint8_t *utf8Buffer, int utf8Length); + +/* + * Inflate bytes in UTF-8 encoding to jschars. + * - On error, returns an empty TwoByteCharsZ. + * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold + * its length; the length value excludes the trailing null. + */ +extern TwoByteCharsZ +UTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); + +/* + * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters + * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 + * input. + */ +extern TwoByteCharsZ +LossyUTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); } // namespace JS inline void JS_free(JS::Latin1CharsZ &ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::UTF8CharsZ &ptr) { js_free((void*)ptr.get()); } -#endif // js_CharacterEncoding_h___ +#endif /* js_CharacterEncoding_h */ diff --git a/external/spidermonkey/include/mac/js/Date.h b/external/spidermonkey/include/mac/js/Date.h index 7ca961e30a..6199f9eca5 100644 --- a/external/spidermonkey/include/mac/js/Date.h +++ b/external/spidermonkey/include/mac/js/Date.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_Date_h___ -#define js_Date_h___ +#ifndef js_Date_h +#define js_Date_h #include "jstypes.h" @@ -32,4 +32,4 @@ DayFromTime(double time); } // namespace JS -#endif /* js_Date_h___ */ +#endif /* js_Date_h */ diff --git a/external/spidermonkey/include/mac/js/GCAPI.h b/external/spidermonkey/include/mac/js/GCAPI.h index 1b0036116c..a9bef77c09 100644 --- a/external/spidermonkey/include/mac/js/GCAPI.h +++ b/external/spidermonkey/include/mac/js/GCAPI.h @@ -4,10 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_gc_api_h___ -#define js_gc_api_h___ +#ifndef js_GCAPI_h +#define js_GCAPI_h -#include "HeapAPI.h" +#include "js/HeapAPI.h" namespace JS { @@ -181,6 +181,9 @@ DisableIncrementalGC(JSRuntime *rt); extern JS_FRIEND_API(void) DisableGenerationalGC(JSRuntime *rt); +extern JS_FRIEND_API(void) +EnableGenerationalGC(JSRuntime *rt); + extern JS_FRIEND_API(bool) IsIncrementalBarrierNeeded(JSRuntime *rt); @@ -205,7 +208,7 @@ WasIncrementalGC(JSRuntime *rt); class ObjectPtr { - JSObject *value; + Heap value; public: ObjectPtr() : value(NULL) {} @@ -240,7 +243,7 @@ class ObjectPtr } void trace(JSTracer *trc, const char *name) { - JS_CallObjectTracer(trc, &value, name); + JS_CallHeapObjectTracer(trc, &value, name); } JSObject &operator*() const { return *value; } @@ -291,4 +294,4 @@ ExposeValueToActiveJS(const Value &v) } /* namespace JS */ -#endif /* js_gc_api_h___ */ +#endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/mac/js/HashTable.h b/external/spidermonkey/include/mac/js/HashTable.h index 3402bfbff4..aa05b71472 100644 --- a/external/spidermonkey/include/mac/js/HashTable.h +++ b/external/spidermonkey/include/mac/js/HashTable.h @@ -4,17 +4,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_HashTable_h__ -#define js_HashTable_h__ +#ifndef js_HashTable_h +#define js_HashTable_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" #include "mozilla/PodOperations.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" #include "mozilla/Util.h" -#include "js/TemplateLib.h" #include "js/Utility.h" namespace js { @@ -68,15 +72,7 @@ class HashMap // HashMap construction is fallible (due to OOM); thus the user must call // init after constructing a HashMap and check the return value. - HashMap(AllocPolicy a = AllocPolicy()) - : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Key type must be relocatable"); - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Value type must be relocatable"); - } - + HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -142,18 +138,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, Move(e)); + return impl.relookupOrAdd(p, k, mozilla::Move(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -203,10 +199,10 @@ class HashMap // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -235,7 +231,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, Move(e)); + return impl.putNew(k, mozilla::Move(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -253,9 +249,17 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const Key &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashMap is movable - HashMap(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashMap is not copyable or assignable @@ -303,11 +307,7 @@ class HashSet // HashSet construction is fallible (due to OOM); thus the user must call // init after constructing a HashSet and check the return value. - HashSet(AllocPolicy a = AllocPolicy()) : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Set element type must be relocatable"); - } + HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -411,10 +411,10 @@ class HashSet // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -448,9 +448,17 @@ class HashSet remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const T &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashSet is movable - HashSet(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashSet is not copyable or assignable @@ -532,7 +540,7 @@ struct DefaultHasher // Specialize hashing policy for pointer types. It assumes that the type is // at least word-aligned. For types with smaller size use PointerHasher. template -struct DefaultHasher : PointerHasher::result> +struct DefaultHasher : PointerHasher::value> {}; // For doubles, we can xor the two uint32s. @@ -542,18 +550,11 @@ struct DefaultHasher typedef double Lookup; static HashNumber hash(double d) { JS_STATIC_ASSERT(sizeof(HashNumber) == 4); - union { - struct { - uint32_t lo; - uint32_t hi; - } s; - double d; - } u; - u.d = d; - return u.s.lo ^ u.s.hi; + uint64_t u = mozilla::BitwiseCast(d); + return HashNumber(u ^ (u >> 32)); } static bool match(double lhs, double rhs) { - return lhs == rhs; + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); } }; @@ -577,8 +578,8 @@ class HashMapEntry template HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} - HashMapEntry(MoveRef rhs) - : key(Move(rhs->key)), value(Move(rhs->value)) { } + HashMapEntry(mozilla::MoveRef rhs) + : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -647,8 +648,8 @@ class HashTableEntry } void swap(HashTableEntry *other) { - Swap(keyHash, other->keyHash); - Swap(mem, other->mem); + mozilla::Swap(keyHash, other->keyHash); + mozilla::Swap(mem, other->mem); } T &get() { JS_ASSERT(isLive()); return *mem.addr(); } @@ -807,10 +808,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - typename HashTableEntry::NonConstT t(Move(this->cur->get())); - HashPolicy::setKey(t, const_cast(k)); - table.remove(*this->cur); - table.putNewInfallible(l, Move(t)); + table.rekey(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -832,13 +830,13 @@ class HashTable : private AllocPolicy }; // HashTable is movable - HashTable(MoveRef rhs) + HashTable(mozilla::MoveRef rhs) : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); rhs->table = NULL; } - void operator=(MoveRef rhs) { + void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); @@ -882,7 +880,7 @@ class HashTable : private AllocPolicy # define METER(x) #endif - friend class js::ReentrancyGuard; + friend class mozilla::ReentrancyGuard; mutable mozilla::DebugOnly entered; mozilla::DebugOnly mutationCount; @@ -892,7 +890,7 @@ class HashTable : private AllocPolicy static const unsigned sMinCapacity = 1 << sMinCapacityLog2; static const unsigned sMaxInit = JS_BIT(23); static const unsigned sMaxCapacity = JS_BIT(24); - static const unsigned sHashBits = tl::BitSize::result; + static const unsigned sHashBits = mozilla::tl::BitSize::value; static const uint8_t sMinAlphaFrac = 64; // (0x100 * .25) static const uint8_t sMaxAlphaFrac = 192; // (0x100 * .75) static const uint8_t sInvMaxAlpha = 171; // (ceil(0x100 / .75) >> 1) @@ -1165,7 +1163,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); src->destroy(); } } @@ -1346,19 +1344,19 @@ class HashTable : private AllocPolicy return gen; } - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(table); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); } Ptr lookup(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); return Ptr(lookup(l, keyHash, 0)); } @@ -1371,7 +1369,7 @@ class HashTable : private AllocPolicy AddPtr lookupForAdd(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); Entry &entry = lookup(l, keyHash, sCollisionBit); AddPtr p(entry, keyHash); @@ -1382,7 +1380,7 @@ class HashTable : private AllocPolicy template bool add(AddPtr &p, const U &rhs) { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(mutationCount == p.mutationCount); JS_ASSERT(table); JS_ASSERT(!p.found()); @@ -1443,7 +1441,7 @@ class HashTable : private AllocPolicy { p.mutationCount = mutationCount; { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); p.entry_ = &lookup(l, p.keyHash, sCollisionBit); } return p.found() || add(p, u); @@ -1452,17 +1450,27 @@ class HashTable : private AllocPolicy void remove(Ptr p) { JS_ASSERT(table); - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); remove(*p.entry_); checkUnderloaded(); } + void rekey(Ptr p, const Lookup &l, const Key &k) + { + JS_ASSERT(table); + mozilla::ReentrancyGuard g(*this); + JS_ASSERT(p.found()); + typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + HashPolicy::setKey(t, const_cast(k)); + remove(*p.entry_); + putNewInfallible(l, mozilla::Move(t)); + } + #undef METER }; } // namespace detail } // namespace js -#endif // js_HashTable_h__ - +#endif /* js_HashTable_h */ diff --git a/external/spidermonkey/include/mac/js/HeapAPI.h b/external/spidermonkey/include/mac/js/HeapAPI.h index f0f4411ac9..4d739304bc 100644 --- a/external/spidermonkey/include/mac/js/HeapAPI.h +++ b/external/spidermonkey/include/mac/js/HeapAPI.h @@ -4,33 +4,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_heap_api_h___ -#define js_heap_api_h___ +#ifndef js_HeapAPI_h +#define js_HeapAPI_h #include "jspubtd.h" +#include "js/Utility.h" + /* These values are private to the JS engine. */ namespace js { namespace gc { -/* - * Page size must be static to support our arena pointer optimizations, so we - * are forced to support each platform with non-4096 pages as a special case. - * Note: The freelist supports a maximum arena shift of 15. - * Note: Do not use JS_CPU_SPARC here, this header is used outside JS. - */ -#if (defined(SOLARIS) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \ - (defined(__sparc) || defined(__sparcv9) || defined(__ia64)) -const size_t PageShift = 13; -const size_t ArenaShift = PageShift; -#elif defined(__powerpc64__) -const size_t PageShift = 16; const size_t ArenaShift = 12; -#else -const size_t PageShift = 12; -const size_t ArenaShift = PageShift; -#endif -const size_t PageSize = size_t(1) << PageShift; const size_t ArenaSize = size_t(1) << ArenaShift; const size_t ArenaMask = ArenaSize - 1; @@ -67,7 +52,7 @@ namespace shadow { struct ArenaHeader { - js::Zone *zone; + JS::Zone *zone; }; struct Zone @@ -153,10 +138,10 @@ IsIncrementalBarrierNeededOnGCThing(shadow::Runtime *rt, void *thing, JSGCTraceK { if (!rt->needsBarrier_) return false; - js::Zone *zone = GetGCThingZone(thing); + JS::Zone *zone = GetGCThingZone(thing); return reinterpret_cast(zone)->needsBarrier_; } } /* namespace JS */ -#endif /* js_heap_api_h___ */ +#endif /* js_HeapAPI_h */ diff --git a/external/spidermonkey/include/mac/js/LegacyIntTypes.h b/external/spidermonkey/include/mac/js/LegacyIntTypes.h index 387a68b9e9..2c8498c89e 100644 --- a/external/spidermonkey/include/mac/js/LegacyIntTypes.h +++ b/external/spidermonkey/include/mac/js/LegacyIntTypes.h @@ -17,13 +17,12 @@ * Indeed, if you use this header and third-party code defining these * types, *expect* to encounter either compile errors or link errors, * depending how these types are used and on the order of inclusion. - * It is safest to use only the JSAPI -style types, - * customizing those types using MOZ_CUSTOM_STDINT_H if necessary. + * It is safest to use only the types. */ -#ifndef PROTYPES_H -#define PROTYPES_H +#ifndef js_LegacyIntTypes_h +#define js_LegacyIntTypes_h -#include "mozilla/StandardInteger.h" +#include #include "js-config.h" @@ -57,4 +56,4 @@ typedef int16_t JSInt16; typedef int32_t JSInt32; typedef int64_t JSInt64; -#endif /* !defined(PROTYPES_H) */ +#endif /* js_LegacyIntTypes_h */ diff --git a/external/spidermonkey/include/mac/js/MemoryMetrics.h b/external/spidermonkey/include/mac/js/MemoryMetrics.h index 7e84f2ae11..ed61e1c427 100644 --- a/external/spidermonkey/include/mac/js/MemoryMetrics.h +++ b/external/spidermonkey/include/mac/js/MemoryMetrics.h @@ -10,6 +10,8 @@ // These declarations are not within jsapi.h because they are highly likely to // change in the future. Depend on them at your own risk. +#include "mozilla/MemoryReporting.h" + #include #include "jsalloc.h" @@ -91,7 +93,6 @@ struct TypeInferenceSizes // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t jaeger; size_t ion; size_t asmJS; size_t baseline; @@ -136,7 +137,7 @@ struct RuntimeSizes size_t dtoa; size_t temporary; size_t regexpData; - size_t stack; + size_t interpreterStack; size_t gcMarker; size_t mathCache; size_t scriptData; @@ -153,9 +154,11 @@ struct ZoneStats gcHeapUnusedGcThings(0), gcHeapStringsNormal(0), gcHeapStringsShort(0), + gcHeapLazyScripts(0), gcHeapTypeObjects(0), gcHeapIonCodes(0), stringCharsNonHuge(0), + lazyScripts(0), typeObjects(0), typePool(0), hugeStrings() @@ -167,14 +170,16 @@ struct ZoneStats gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), gcHeapStringsNormal(other.gcHeapStringsNormal), gcHeapStringsShort(other.gcHeapStringsShort), + gcHeapLazyScripts(other.gcHeapLazyScripts), gcHeapTypeObjects(other.gcHeapTypeObjects), gcHeapIonCodes(other.gcHeapIonCodes), stringCharsNonHuge(other.stringCharsNonHuge), + lazyScripts(other.lazyScripts), typeObjects(other.typeObjects), typePool(other.typePool), hugeStrings() { - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // Add other's numbers to this object's numbers. @@ -186,16 +191,18 @@ struct ZoneStats ADD(gcHeapStringsNormal); ADD(gcHeapStringsShort); + ADD(gcHeapLazyScripts); ADD(gcHeapTypeObjects); ADD(gcHeapIonCodes); ADD(stringCharsNonHuge); + ADD(lazyScripts); ADD(typeObjects); ADD(typePool); #undef ADD - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // This field can be used by embedders. @@ -207,10 +214,12 @@ struct ZoneStats size_t gcHeapStringsNormal; size_t gcHeapStringsShort; + size_t gcHeapLazyScripts; size_t gcHeapTypeObjects; size_t gcHeapIonCodes; size_t stringCharsNonHuge; + size_t lazyScripts; size_t typeObjects; size_t typePool; @@ -241,7 +250,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(0), shapesCompartmentTables(0), scriptData(0), - jaegerData(0), baselineData(0), baselineStubsFallback(0), baselineStubsOptimized(0), @@ -271,7 +279,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), shapesCompartmentTables(other.shapesCompartmentTables), scriptData(other.scriptData), - jaegerData(other.jaegerData), baselineData(other.baselineData), baselineStubsFallback(other.baselineStubsFallback), baselineStubsOptimized(other.baselineStubsOptimized), @@ -306,7 +313,6 @@ struct CompartmentStats size_t shapesExtraTreeShapeKids; size_t shapesCompartmentTables; size_t scriptData; - size_t jaegerData; size_t baselineData; size_t baselineStubsFallback; size_t baselineStubsOptimized; @@ -339,7 +345,6 @@ struct CompartmentStats ADD(shapesExtraTreeShapeKids); ADD(shapesCompartmentTables); ADD(scriptData); - ADD(jaegerData); ADD(baselineData); ADD(baselineStubsFallback); ADD(baselineStubsOptimized); @@ -360,7 +365,7 @@ struct CompartmentStats struct RuntimeStats { - RuntimeStats(JSMallocSizeOfFun mallocSizeOf) + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) : runtime(), gcHeapChunkTotal(0), gcHeapDecommittedArenas(0), @@ -417,7 +422,7 @@ struct RuntimeStats ZoneStats *currZoneStats; - JSMallocSizeOfFun mallocSizeOf_; + mozilla::MallocSizeOf mallocSizeOf_; virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; @@ -454,4 +459,4 @@ PeakSizeOfTemporary(const JSRuntime *rt); } // namespace JS -#endif // js_MemoryMetrics_h +#endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/mac/js/PropertyKey.h b/external/spidermonkey/include/mac/js/PropertyKey.h index 53158c26f3..c949db13a5 100644 --- a/external/spidermonkey/include/mac/js/PropertyKey.h +++ b/external/spidermonkey/include/mac/js/PropertyKey.h @@ -6,8 +6,8 @@ /* JS::PropertyKey implementation. */ -#ifndef js_PropertyKey_h___ -#define js_PropertyKey_h___ +#ifndef js_PropertyKey_h +#define js_PropertyKey_h #include "mozilla/Attributes.h" @@ -95,4 +95,4 @@ ToPropertyKey(JSContext *cx, HandleValue v, PropertyKey *key) } // namespace JS -#endif /* js_PropertyKey_h___ */ +#endif /* js_PropertyKey_h */ diff --git a/external/spidermonkey/include/mac/js/RequiredDefines.h b/external/spidermonkey/include/mac/js/RequiredDefines.h index 2be2efbf9a..6af9ca871b 100644 --- a/external/spidermonkey/include/mac/js/RequiredDefines.h +++ b/external/spidermonkey/include/mac/js/RequiredDefines.h @@ -10,8 +10,8 @@ * or SpiderMonkey public headers may not work correctly. */ -#ifndef js_RequiredDefines_h___ -#define js_RequiredDefines_h___ +#ifndef js_RequiredDefines_h +#define js_RequiredDefines_h /* * The c99 defining the limit macros (UINT32_MAX for example), says: @@ -20,4 +20,4 @@ */ #define __STDC_LIMIT_MACROS -#endif /* js_RequiredDefines_h___ */ +#endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/mac/js/RootingAPI.h b/external/spidermonkey/include/mac/js/RootingAPI.h index 3e2e0d2a7c..99295f1238 100644 --- a/external/spidermonkey/include/mac/js/RootingAPI.h +++ b/external/spidermonkey/include/mac/js/RootingAPI.h @@ -4,14 +4,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsgc_root_h__ -#define jsgc_root_h__ +#ifndef js_RootingAPI_h +#define js_RootingAPI_h #include "mozilla/GuardObjects.h" #include "mozilla/TypeTraits.h" #include "js/Utility.h" -#include "js/TemplateLib.h" #include "jspubtd.h" @@ -99,9 +98,10 @@ namespace js { class Module; +class ScriptSourceObject; template -struct RootMethods {}; +struct GCMethods {}; template class RootedBase {}; @@ -112,6 +112,9 @@ class HandleBase {}; template class MutableHandleBase {}; +template +class HeapBase {}; + /* * js::NullPtr acts like a NULL pointer in contexts that require a Handle. * @@ -130,6 +133,10 @@ struct NullPtr static void * const constNullValue; }; +namespace gc { +struct Cell; +} /* namespace gc */ + } /* namespace js */ namespace JS { @@ -161,6 +168,204 @@ struct JS_PUBLIC_API(NullPtr) static void * const constNullValue; }; +/* + * The Heap class is a C/C++ heap-stored reference to a JS GC thing. All + * members of heap classes that refer to GC thing should use Heap (or + * possibly TenuredHeap, described below). + * + * Heap wraps the complex mechanisms required to ensure GC safety for the + * contained reference into a C++ class that behaves similarly to a normal + * pointer. + * + * GC references stored on the C/C++ stack must use Rooted/Handle/MutableHandle + * instead. + * + * Requirements for type T: + * - Must be one of: Value, jsid, JSObject*, JSString*, JSScript* + */ +template +class Heap : public js::HeapBase +{ + public: + Heap() { + static_assert(sizeof(T) == sizeof(Heap), + "Heap must be binary compatible with T."); + init(js::GCMethods::initial()); + } + explicit Heap(T p) { init(p); } + explicit Heap(const Heap &p) { init(p.ptr); } + + ~Heap() { + if (js::GCMethods::needsPostBarrier(ptr)) + relocate(); + } + + bool operator==(const Heap &other) { return ptr == other.ptr; } + bool operator!=(const Heap &other) { return ptr != other.ptr; } + + bool operator==(const T &other) const { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + + operator T() const { return ptr; } + T operator->() const { return ptr; } + const T *address() const { return &ptr; } + const T &get() const { return ptr; } + + T *unsafeGet() { return &ptr; } + + Heap &operator=(T p) { + set(p); + return *this; + } + + void set(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (js::GCMethods::needsPostBarrier(newPtr)) { + ptr = newPtr; + post(); + } else if (js::GCMethods::needsPostBarrier(ptr)) { + relocate(); /* Called before overwriting ptr. */ + ptr = newPtr; + } else { + ptr = newPtr; + } + } + + private: + void init(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + ptr = newPtr; + if (js::GCMethods::needsPostBarrier(ptr)) + post(); + } + + void post() { +#ifdef JSGC_GENERATIONAL + JS_ASSERT(js::GCMethods::needsPostBarrier(ptr)); + js::GCMethods::postBarrier(&ptr); +#endif + } + + void relocate() { +#ifdef JSGC_GENERATIONAL + js::GCMethods::relocate(&ptr); +#endif + } + + T ptr; +}; + +#ifdef DEBUG +/* + * For generational GC, assert that an object is in the tenured generation as + * opposed to being in the nursery. + */ +extern JS_FRIEND_API(void) +AssertGCThingMustBeTenured(JSObject* obj); +#else +inline void +AssertGCThingMustBeTenured(JSObject *obj) {} +#endif + +/* + * The TenuredHeap class is similar to the Heap class above in that it + * encapsulates the GC concerns of an on-heap reference to a JS object. However, + * it has two important differences: + * + * 1) Pointers which are statically known to only reference "tenured" objects + * can avoid the extra overhead of SpiderMonkey's write barriers. + * + * 2) Objects in the "tenured" heap have stronger alignment restrictions than + * those in the "nursery", so it is possible to store flags in the lower + * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged + * pointer with a nice API for accessing the flag bits and adds various + * assertions to ensure that it is not mis-used. + * + * GC things are said to be "tenured" when they are located in the long-lived + * heap: e.g. they have gained tenure as an object by surviving past at least + * one GC. For performance, SpiderMonkey allocates some things which are known + * to normally be long lived directly into the tenured generation; for example, + * global objects. Additionally, SpiderMonkey does not visit individual objects + * when deleting non-tenured objects, so object with finalizers are also always + * tenured; for instance, this includes most DOM objects. + * + * The considerations to keep in mind when using a TenuredHeap vs a normal + * Heap are: + * + * - It is invalid for a TenuredHeap to refer to a non-tenured thing. + * - It is however valid for a Heap to refer to a tenured thing. + * - It is not possible to store flag bits in a Heap. + */ +template +class TenuredHeap : public js::HeapBase +{ + public: + TenuredHeap() : bits(0) { + static_assert(sizeof(T) == sizeof(TenuredHeap), + "TenuredHeap must be binary compatible with T."); + } + explicit TenuredHeap(T p) : bits(0) { setPtr(p); } + explicit TenuredHeap(const TenuredHeap &p) : bits(0) { setPtr(p.ptr); } + + bool operator==(const TenuredHeap &other) { return bits == other.bits; } + bool operator!=(const TenuredHeap &other) { return bits != other.bits; } + + void setPtr(T newPtr) { + JS_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (newPtr) + AssertGCThingMustBeTenured(newPtr); + bits = (bits & flagsMask) | reinterpret_cast(newPtr); + } + + void setFlags(uintptr_t flagsToSet) { + JS_ASSERT((flagsToSet & ~flagsMask) == 0); + bits |= flagsToSet; + } + + void unsetFlags(uintptr_t flagsToUnset) { + JS_ASSERT((flagsToUnset & ~flagsMask) == 0); + bits &= ~flagsToUnset; + } + + bool hasFlag(uintptr_t flag) const { + JS_ASSERT((flag & ~flagsMask) == 0); + return (bits & flag) != 0; + } + + T getPtr() const { return reinterpret_cast(bits & ~flagsMask); } + uintptr_t getFlags() const { return bits & flagsMask; } + + operator T() const { return getPtr(); } + T operator->() const { return getPtr(); } + + TenuredHeap &operator=(T p) { + setPtr(p); + return *this; + } + + /* + * Set the pointer to a value which will cause a crash if it is + * dereferenced. + */ + void setToCrashOnTouch() { + bits = (bits & flagsMask) | crashOnTouchPointer; + } + + bool isSetToCrashOnTouch() { + return (bits & ~flagsMask) == crashOnTouchPointer; + } + + private: + enum { + maskBits = 3, + flagsMask = (1 << maskBits) - 1, + crashOnTouchPointer = 1 << maskBits + }; + + uintptr_t bits; +}; + /* * Reference to a T that has been rooted elsewhere. This is most useful * as a parameter type, which guarantees that the T lvalue is properly @@ -170,7 +375,7 @@ struct JS_PUBLIC_API(NullPtr) * specialization, define a HandleBase specialization containing them. */ template -class MOZ_STACK_CLASS Handle : public js::HandleBase +class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { friend class MutableHandle; @@ -180,20 +385,22 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase Handle(Handle handle, typename mozilla::EnableIf::value, int>::Type dummy = 0) { + static_assert(sizeof(Handle) == sizeof(T *), + "Handle must be binary compatible with T*."); ptr = reinterpret_cast(handle.address()); } /* Create a handle for a NULL pointer. */ Handle(js::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "js::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } /* Create a handle for a NULL pointer. */ Handle(JS::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "JS::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "JS::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&JS::NullPtr::constNullValue); } @@ -202,11 +409,19 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase } /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. + * Take care when calling this method! * - * Create a Handle from a raw location of a T. + * This creates a Handle from the raw location of a T. + * + * It should be called only if the following conditions hold: + * + * 1) the location of the T is guaranteed to be marked (for some reason + * other than being a Rooted), e.g., if it is guaranteed to be reachable + * from an implicit root. + * + * 2) the contents of the location are immutable, or at least cannot change + * for the lifetime of the handle, as its users may not expect its value + * to change underneath them. */ static Handle fromMarkedLocation(const T *p) { Handle h; @@ -230,13 +445,17 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase typename mozilla::EnableIf::value, int>::Type dummy = 0); const T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a Handle to something that + * takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } - bool operator!=(const T &other) { return *ptr != other; } - bool operator==(const T &other) { return *ptr == other; } + bool operator!=(const T &other) const { return *ptr != other; } + bool operator==(const T &other) const { return *ptr == other; } private: Handle() {} @@ -247,13 +466,14 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase void operator=(S v) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; +typedef Handle HandleObject; +typedef Handle HandleModule; +typedef Handle HandleScriptSource; +typedef Handle HandleFunction; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleId; +typedef Handle HandleValue; /* * Similar to a handle, but the underlying storage can be changed. This is @@ -270,7 +490,7 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase inline MutableHandle(Rooted *root); void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -288,9 +508,13 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase } T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a MutableHandle to something that takes + * a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } private: @@ -298,8 +522,8 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S v) MOZ_DELETE; + void operator=(MutableHandle other) MOZ_DELETE; }; typedef MutableHandle MutableHandleObject; @@ -309,6 +533,11 @@ typedef MutableHandle MutableHandleString; typedef MutableHandle MutableHandleId; typedef MutableHandle MutableHandleValue; +#ifdef JSGC_GENERATIONAL +JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); +JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); +#endif + } /* namespace JS */ namespace js { @@ -383,13 +612,28 @@ struct RootKind }; template -struct RootMethods +struct GCMethods { static T *initial() { return NULL; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } + static bool needsPostBarrier(T *v) { return v; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(T **vp) { + JS::HeapCellPostBarrier(reinterpret_cast(vp)); + } + static void relocate(T **vp) { + JS::HeapCellRelocate(reinterpret_cast(vp)); + } +#endif }; +#if defined(DEBUG) +/* This helper allows us to assert that Rooted is scoped within a request. */ +extern JS_PUBLIC_API(bool) +IsInRequest(JSContext *cx); +#endif + } /* namespace js */ namespace JS { @@ -405,46 +649,63 @@ namespace JS { template class MOZ_STACK_CLASS Rooted : public js::RootedBase { - void init(JSContext *cxArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ContextFriendFields *cx = js::ContextFriendFields::get(cxArg); - commonInit(cx->thingGCRooters); -#endif - } + /* Note: CX is a subclass of either ContextFriendFields or PerThreadDataFriendFields. */ + template + void init(CX *cx) { +#ifdef JSGC_TRACK_EXACT_ROOTS + js::ThingRootKind kind = js::GCMethods::kind(); + this->stack = &cx->thingGCRooters[kind]; + this->prev = *stack; + *stack = reinterpret_cast*>(this); - void init(js::PerThreadData *ptArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::PerThreadDataFriendFields *pt = js::PerThreadDataFriendFields::get(ptArg); - commonInit(pt->thingGCRooters); + JS_ASSERT(!js::GCMethods::poisoned(ptr)); #endif } public: Rooted(JSContext *cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; - init(cx); + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); } Rooted(JSContext *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); + } + + Rooted(js::ContextFriendFields *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(cx); } - Rooted(js::PerThreadData *pt + Rooted(js::ContextFriendFields *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(cx); + } + + Rooted(js::PerThreadDataFriendFields *pt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(pt); } - Rooted(js::PerThreadData *pt, T initial + Rooted(js::PerThreadDataFriendFields *pt, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { @@ -452,18 +713,38 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(pt); } + Rooted(JSRuntime *rt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + + Rooted(JSRuntime *rt, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + ~Rooted() { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; #endif } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } #endif - operator T() const { return ptr; } + /* + * Important: Return a reference here so passing a Rooted to + * something that takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return ptr; } T operator->() const { return ptr; } T *address() { return &ptr; } const T *address() const { return &ptr; } @@ -471,7 +752,7 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!js::RootMethods::poisoned(value)); + JS_ASSERT(!js::GCMethods::poisoned(value)); ptr = value; return ptr; } @@ -481,28 +762,25 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } - - private: - void commonInit(Rooted **thingGCRooters) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ThingRootKind kind = js::RootMethods::kind(); - this->stack = &thingGCRooters[kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - - JS_ASSERT(!js::RootMethods::poisoned(ptr)); -#endif + void set(T value) { + JS_ASSERT(!js::GCMethods::poisoned(value)); + ptr = value; } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } + + private: +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted **stack, *prev; #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) /* Has the rooting analysis ever scanned this Rooted's stack location? */ friend void JS::CheckStackRoots(JSContext*); +#endif + +#ifdef JSGC_ROOT_ANALYSIS bool scanned; #endif @@ -523,13 +801,14 @@ template <> class Rooted; #endif -typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedId; -typedef Rooted RootedValue; +typedef Rooted RootedObject; +typedef Rooted RootedModule; +typedef Rooted RootedScriptSource; +typedef Rooted RootedFunction; +typedef Rooted RootedScript; +typedef Rooted RootedString; +typedef Rooted RootedId; +typedef Rooted RootedValue; } /* namespace JS */ @@ -549,8 +828,9 @@ class SkipRoot const uint8_t *start; const uint8_t *end; - template - void init(SkipRoot **head, const T *ptr, size_t count) { + template + void init(CX *cx, const T *ptr, size_t count) { + SkipRoot **head = &cx->skipGCRooters; this->stack = head; this->prev = *stack; *stack = this; @@ -559,23 +839,6 @@ class SkipRoot } public: - template - SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - init(&ContextFriendFields::get(cx)->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - template - SkipRoot(js::PerThreadData *ptd, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - PerThreadDataFriendFields *ptff = PerThreadDataFriendFields::get(ptd); - init(&ptff->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - ~SkipRoot() { JS_ASSERT(*stack == this); *stack = prev; @@ -589,22 +852,36 @@ class SkipRoot #else /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} + public: + +#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(ContextFriendFields::get(cx), ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } template - SkipRoot(PerThreadData *ptd, const T *ptr, size_t count = 1 + SkipRoot(ContextFriendFields *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(cx, ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } -#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + SkipRoot(PerThreadData *pt, const T *ptr, size_t count = 1 + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + { + init(PerThreadDataFriendFields::get(pt), ptr, count); + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + } MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; @@ -614,15 +891,17 @@ template class FakeRooted : public RootedBase { public: - FakeRooted(JSContext *cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(RootMethods::initial()) + template + FakeRooted(CX *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } - FakeRooted(JSContext *cx, T initial - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + template + FakeRooted(CX *cx, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; @@ -636,13 +915,13 @@ class FakeRooted : public RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!RootMethods::poisoned(value)); + JS_ASSERT(!GCMethods::poisoned(value)); ptr = value; return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } private: T ptr; @@ -666,7 +945,7 @@ class FakeMutableHandle : public js::MutableHandleBase } void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -727,13 +1006,11 @@ template class MaybeRooted typedef FakeMutableHandle MutableHandleType; static inline JS::Handle toHandle(HandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::Handle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::MutableHandle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } }; @@ -761,6 +1038,8 @@ template inline MutableHandle::MutableHandle(Rooted *root) { + static_assert(sizeof(MutableHandle) == sizeof(T *), + "MutableHandle must be binary compatible with T*."); ptr = root->address(); } @@ -779,10 +1058,6 @@ inline void MaybeCheckStackRoots(JSContext *cx) #endif } -namespace gc { -struct Cell; -} /* namespace gc */ - /* Base class for automatic read-only object rooting during compilation. */ class CompilerRootNode { @@ -801,4 +1076,4 @@ class CompilerRootNode } /* namespace js */ -#endif /* jsgc_root_h___ */ +#endif /* js_RootingAPI_h */ diff --git a/external/spidermonkey/include/mac/js/TemplateLib.h b/external/spidermonkey/include/mac/js/TemplateLib.h deleted file mode 100644 index a4ff682912..0000000000 --- a/external/spidermonkey/include/mac/js/TemplateLib.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_template_lib_h__ -#define js_template_lib_h__ - -#include "jstypes.h" - -/* - * Library of reusable template meta-functions (that is, functions on types and - * compile-time values). Meta-functions are placed inside the 'tl' namespace to - * avoid conflict with non-meta functions that logically have the same name - * (e.g., js::tl::Min vs. js::Min). - */ - -namespace js { -namespace tl { - -/* Compute min/max/clamp. */ -template struct Min { - static const size_t result = i < j ? i : j; -}; -template struct Max { - static const size_t result = i > j ? i : j; -}; -template struct Clamp { - static const size_t result = i < min ? min : (i > max ? max : i); -}; - -/* Compute x^y. */ -template struct Pow { - static const size_t result = x * Pow::result; -}; -template struct Pow { - static const size_t result = 1; -}; - -/* Compute floor(log2(i)). */ -template struct FloorLog2 { - static const size_t result = 1 + FloorLog2::result; -}; -template <> struct FloorLog2<0> { /* Error */ }; -template <> struct FloorLog2<1> { static const size_t result = 0; }; - -/* Compute ceiling(log2(i)). */ -template struct CeilingLog2 { - static const size_t result = FloorLog2<2 * i - 1>::result; -}; - -/* Round up to the nearest power of 2. */ -template struct RoundUpPow2 { - static const size_t result = size_t(1) << CeilingLog2::result; -}; -template <> struct RoundUpPow2<0> { - static const size_t result = 1; -}; - -/* Compute the number of bits in the given unsigned type. */ -template struct BitSize { - static const size_t result = sizeof(T) * JS_BITS_PER_BYTE; -}; - -/* - * Produce an N-bit mask, where N <= BitSize::result. Handle the - * language-undefined edge case when N = BitSize::result. - */ -template struct NBitMask { - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |result| to assure - // its computation. - static const size_t checkPrecondition = 0 / size_t(N < BitSize::result); - static const size_t result = (size_t(1) << N) - 1 + checkPrecondition; -}; -template <> struct NBitMask::result> { - static const size_t result = size_t(-1); -}; - -/* - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template struct MulOverflowMask { - static const size_t result = - ~NBitMask::result - CeilingLog2::result>::result; -}; -template <> struct MulOverflowMask<0> { /* Error */ }; -template <> struct MulOverflowMask<1> { static const size_t result = 0; }; - -/* - * Generate a mask for T such that if (X & sUnsafeRangeSizeMask), an X-sized - * array of T's is big enough to cause a ptrdiff_t overflow when subtracting - * a pointer to the end of the array from the beginning. - */ -template struct UnsafeRangeSizeMask { - /* - * The '2' factor means the top bit is clear, sizeof(T) converts from - * units of elements to bytes. - */ - static const size_t result = MulOverflowMask<2 * sizeof(T)>::result; -}; - -template struct If { static const T result = v1; }; -template struct If { static const T result = v2; }; - -/* - * Traits class for identifying types that are implicitly barriered. - */ -template struct IsRelocatableHeapType { static const bool result = true; }; - -} /* namespace tl */ -} /* namespace js */ - -#endif /* js_template_lib_h__ */ diff --git a/external/spidermonkey/include/mac/js/Utility.h b/external/spidermonkey/include/mac/js/Utility.h index c4ebf7ced6..9d391e5c8a 100644 --- a/external/spidermonkey/include/mac/js/Utility.h +++ b/external/spidermonkey/include/mac/js/Utility.h @@ -4,13 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_utility_h__ -#define js_utility_h__ +#ifndef js_Utility_h +#define js_Utility_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" +#include "mozilla/Move.h" #include "mozilla/Scoped.h" +#include "mozilla/TemplateLib.h" #include #include @@ -22,8 +24,6 @@ #include "jstypes.h" -#include "js/TemplateLib.h" - /* The public JS engine namespace. */ namespace JS {} @@ -41,7 +41,6 @@ namespace js {} #define JS_ASSERT(expr) MOZ_ASSERT(expr) #define JS_ASSERT_IF(cond, expr) MOZ_ASSERT_IF(cond, expr) -#define JS_NOT_REACHED(reason) MOZ_NOT_REACHED(reason) #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) @@ -63,7 +62,7 @@ namespace js {} # define JS_DIAGNOSTICS_ASSERT(expr) ((void) 0) #endif -#define JS_STATIC_ASSERT(cond) MOZ_STATIC_ASSERT(cond, "JS_STATIC_ASSERT") +#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") #define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") extern MOZ_NORETURN JS_PUBLIC_API(void) @@ -84,10 +83,11 @@ extern JS_PUBLIC_API(void) JS_Abort(void); #else # ifdef DEBUG /* - * In order to test OOM conditions, when the shell command-line option - * |-A NUM| is passed, we fail continuously after the NUM'th allocation. + * In order to test OOM conditions, when the testing function + * oomAfterAllocations COUNT is passed, we fail continuously after the NUM'th + * allocation from now. */ -extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set from shell/js.cpp */ +extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set in builtins/TestingFunctions.cpp */ extern JS_PUBLIC_DATA(uint32_t) OOM_counter; /* data race, who cares. */ #ifdef JS_OOM_DO_BACKTRACES @@ -157,6 +157,12 @@ static JS_INLINE void* js_calloc(size_t bytes) return calloc(bytes, 1); } +static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +{ + JS_OOM_POSSIBLY_FAIL(); + return calloc(nmemb, size); +} + static JS_INLINE void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); @@ -169,205 +175,6 @@ static JS_INLINE void js_free(void* p) } #endif/* JS_USE_CUSTOM_ALLOCATOR */ -JS_BEGIN_EXTERN_C - -/* - * Replace bit-scanning code sequences with CPU-specific instructions to - * speedup calculations of ceiling/floor log2. - * - * With GCC 3.4 or later we can use __builtin_clz for that, see bug 327129. - * - * SWS: Added MSVC intrinsic bitscan support. See bugs 349364 and 356856. - */ -#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) - -unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask); -unsigned char _BitScanReverse(unsigned long * Index, unsigned long Mask); -# pragma intrinsic(_BitScanForward,_BitScanReverse) - -__forceinline static int -__BitScanForward32(unsigned int val) -{ - unsigned long idx; - - _BitScanForward(&idx, (unsigned long)val); - return (int)idx; -} -__forceinline static int -__BitScanReverse32(unsigned int val) -{ - unsigned long idx; - - _BitScanReverse(&idx, (unsigned long)val); - return (int)(31-idx); -} -# define js_bitscan_ctz32(val) __BitScanForward32(val) -# define js_bitscan_clz32(val) __BitScanReverse32(val) -# define JS_HAS_BUILTIN_BITSCAN32 - -#if defined(_M_AMD64) || defined(_M_X64) -unsigned char _BitScanForward64(unsigned long * Index, unsigned __int64 Mask); -unsigned char _BitScanReverse64(unsigned long * Index, unsigned __int64 Mask); -# pragma intrinsic(_BitScanForward64,_BitScanReverse64) - -__forceinline static int -__BitScanForward64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanForward64(&idx, val); - return (int)idx; -} -__forceinline static int -__BitScanReverse64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanReverse64(&idx, val); - return (int)(63-idx); -} -# define js_bitscan_ctz64(val) __BitScanForward64(val) -# define js_bitscan_clz64(val) __BitScanReverse64(val) -# define JS_HAS_BUILTIN_BITSCAN64 -#endif -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(3, 4, 0) -# define USE_BUILTIN_CTZ -#endif - -#elif defined(__clang__) - -#if __has_builtin(__builtin_ctz) -# define USE_BUILTIN_CTZ -#endif - -#endif - -#if defined(USE_BUILTIN_CTZ) -# define js_bitscan_ctz32(val) __builtin_ctz(val) -# define js_bitscan_clz32(val) __builtin_clz(val) -# define JS_HAS_BUILTIN_BITSCAN32 -# if (JS_BYTES_PER_WORD == 8) -# define js_bitscan_ctz64(val) __builtin_ctzll(val) -# define js_bitscan_clz64(val) __builtin_clzll(val) -# define JS_HAS_BUILTIN_BITSCAN64 -# endif - -# undef USE_BUILTIN_CTZ - -#endif - -/* -** Macro version of JS_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use intrinsic function or count-leading-zeros to calculate ceil(log2(_n)). - * The macro checks for "n <= 1" and not "n != 0" as js_bitscan_clz32(0) is - * undefined. - */ -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - unsigned int j_ = (unsigned int)(_n); \ - (_log2) = (j_ <= 1 ? 0 : 32 - js_bitscan_clz32(j_ - 1)); \ - JS_END_MACRO -#else -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -/* -** Macro version of JS_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use js_bitscan_clz32 or count-leading-zeros to calculate floor(log2(_n)). - * Since js_bitscan_clz32(0) is undefined, the macro set the loweset bit to 1 - * to ensure 0 result when _n == 0. - */ -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - (_log2) = 31 - js_bitscan_clz32(((unsigned int)(_n)) | 1); \ - JS_END_MACRO -#else -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -#if JS_BYTES_PER_WORD == 4 -# ifdef JS_HAS_BUILTIN_BITSCAN32 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz32(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#elif JS_BYTES_PER_WORD == 8 -# ifdef JS_HAS_BUILTIN_BITSCAN64 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz64(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#else -# error "NOT SUPPORTED" -#endif - -JS_END_EXTERN_C - -/* - * Internal function. - * Compute the log of the least power of 2 greater than or equal to n. This is - * a version of JS_CeilingLog2 that operates on unsigned integers with - * CPU-dependant size. - */ -#define JS_CEILING_LOG2W(n) ((n) <= 1 ? 0 : 1 + JS_FLOOR_LOG2W((n) - 1)) - -/* - * Internal function. - * Compute the log of the greatest power of 2 less than or equal to n. - * This is a version of JS_FloorLog2 that operates on unsigned integers with - * CPU-dependant size and requires that n != 0. - */ -static MOZ_ALWAYS_INLINE size_t -JS_FLOOR_LOG2W(size_t n) -{ - JS_ASSERT(n != 0); - return js_FloorLog2wImpl(n); -} - /* * JS_ROTATE_LEFT32 * @@ -552,7 +359,7 @@ template static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_malloc(numElems * sizeof(T)); } @@ -561,7 +368,7 @@ template static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_calloc(numElems * sizeof(T)); } @@ -595,175 +402,6 @@ SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) namespace js { -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables also need to - * be resized. - * - * The details of the optimization, and whether it's worth applying, vary from - * one type to the next. And while some constructor calls are moves, many really - * are copies, and can't be optimized this way. So we need: - * - * 1) a way for a particular invocation of a copy constructor to say that it's - * really a move, and that the value of the original isn't important - * afterwards (althought it must still be safe to destroy); and - * - * 2) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation. - * - * The Move(T &) function takes a reference to a T, and returns an MoveRef - * referring to the same value; that's 1). An MoveRef is simply a reference - * to a T, annotated to say that a copy constructor applied to it may move that - * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). - * - * So, where we might define a copy constructor for a class C like this: - * - * C(const C &rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(MoveRef rhs) { ... move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)) - * - * Note that MoveRef implicitly converts to T &, so you can pass an - * MoveRef to an ordinary copy constructor for a type that doesn't support a - * special move constructor, and you'll just get a copy. This means that - * templates can use Move whenever they know they won't use the original value - * any more, even if they're not sure whether the type at hand has a specialized - * move constructor. If it doesn't, the MoveRef will just convert to a T &, - * and the ordinary copy constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator, - * which runs this's destructor, and then applies the move constructor to - * *this's memory. A typical definition: - * - * C &operator=(MoveRef rhs) { - * this->~C(); - * new(this) C(rhs); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * This header file defines MoveRef and Move in the js namespace. It's up to - * individual containers to annotate moves as such, by calling Move; and it's up - * to individual types to define move constructors. - * - * One hint: if you're writing a move constructor where the type has members - * that should be moved themselves, it's much nicer to write this: - * - * C(MoveRef c) : x(c->x), y(c->y) { } - * - * than the equivalent: - * - * C(MoveRef c) { new(&x) X(c->x); new(&y) Y(c->y); } - * - * especially since GNU C++ fails to notice that this does indeed initialize x - * and y, which may matter if they're const. - */ -template -class MoveRef { - public: - typedef T Referent; - explicit MoveRef(T &t) : pointer(&t) { } - T &operator*() const { return *pointer; } - T *operator->() const { return pointer; } - operator T& () const { return *pointer; } - private: - T *pointer; -}; - -template -MoveRef Move(T &t) { return MoveRef(t); } - -template -MoveRef Move(const T &t) { return MoveRef(const_cast(t)); } - -/* Useful for implementing containers that assert non-reentrancy */ -class ReentrancyGuard -{ - /* ReentrancyGuard is not copyable. */ - ReentrancyGuard(const ReentrancyGuard &); - void operator=(const ReentrancyGuard &); - -#ifdef DEBUG - bool &entered; -#endif - public: - template -#ifdef DEBUG - ReentrancyGuard(T &obj) - : entered(obj.entered) -#else - ReentrancyGuard(T &/*obj*/) -#endif - { -#ifdef DEBUG - JS_ASSERT(!entered); - entered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - entered = false; -#endif - } -}; - -template -JS_ALWAYS_INLINE static void -Swap(T &t, T &u) -{ - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); -} - -/* - * Round x up to the nearest power of 2. This function assumes that the most - * significant bit of x is not set, which would lead to overflow. - */ -JS_ALWAYS_INLINE size_t -RoundUpPow2(size_t x) -{ - return size_t(1) << JS_CEILING_LOG2W(x); -} - /* Integral types for all hash functions. */ typedef uint32_t HashNumber; const unsigned HashNumberSizeBits = 32; @@ -845,11 +483,6 @@ inline bool IsPoisonedPtr(T *v) } -/* - * This is SpiderMonkey's equivalent to |nsMallocSizeOfFun|. - */ -typedef size_t(*JSMallocSizeOfFun)(const void *p); - /* sixgill annotation defines */ #ifndef HAVE_STATIC_ANNOTATIONS # define HAVE_STATIC_ANNOTATIONS @@ -891,4 +524,4 @@ typedef size_t(*JSMallocSizeOfFun)(const void *p); # define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) #endif /* HAVE_STATIC_ANNOTATIONS */ -#endif /* js_utility_h__ */ +#endif /* js_Utility_h */ diff --git a/external/spidermonkey/include/mac/js/Value.h b/external/spidermonkey/include/mac/js/Value.h index 2c7fa1a600..9b2c5dd6f9 100644 --- a/external/spidermonkey/include/mac/js/Value.h +++ b/external/spidermonkey/include/mac/js/Value.h @@ -6,8 +6,8 @@ /* JS::Value implementation. */ -#ifndef js_Value_h___ -#define js_Value_h___ +#ifndef js_Value_h +#define js_Value_h #include "mozilla/Attributes.h" #include "mozilla/FloatingPoint.h" @@ -53,7 +53,7 @@ namespace JS { class Value; } * nice symbolic type tags, however we can only do this when we can force the * underlying type of the enum to be the desired size. */ -#if defined(__cplusplus) && !defined(__SUNPRO_CC) && !defined(__xlC__) +#if !defined(__SUNPRO_CC) && !defined(__xlC__) #if defined(_MSC_VER) # define JS_ENUM_HEADER(id, type) enum id : type @@ -132,7 +132,7 @@ JS_STATIC_ASSERT(sizeof(JSValueShiftedTag) == sizeof(uint64_t)); #endif -#else /* defined(__cplusplus) */ +#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ typedef uint8_t JSValueType; #define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) @@ -180,7 +180,7 @@ typedef uint64_t JSValueShiftedTag; #define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) #endif /* JS_BITS_PER_WORD */ -#endif /* defined(__cplusplus) && !defined(__SUNPRO_CC) */ +#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ #define JSVAL_LOWER_INCL_TYPE_OF_OBJ_OR_NULL_SET JSVAL_TYPE_NULL #define JSVAL_UPPER_EXCL_TYPE_OF_PRIMITIVE_SET JSVAL_TYPE_OBJECT @@ -265,7 +265,7 @@ typedef union jsval_layout typedef union jsval_layout { uint64_t asBits; -#if (!defined(_WIN64) && defined(__cplusplus)) +#if !defined(_WIN64) /* MSVC does not pack these correctly :-( */ struct { uint64_t payload47 : 47; @@ -321,7 +321,6 @@ typedef union jsval_layout int32_t i32; uint32_t u32; JSWhyMagic why; - uintptr_t word; } payload; } s; double asDouble; @@ -803,22 +802,31 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ -static inline double -JS_CANONICALIZE_NAN(double d) -{ - if (MOZ_UNLIKELY(d != d)) { - jsval_layout l; - l.asBits = 0x7FF8000000000000LL; - return l.asDouble; - } - return d; -} - static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +/** + * Returns a generic quiet NaN value, with all payload bits set to zero. + * + * Among other properties, this NaN's bit pattern conforms to JS::Value's + * bit pattern restrictions. + */ +static MOZ_ALWAYS_INLINE double +GenericNaN() +{ + return mozilla::SpecificNaN(0, 0x8000000000000ULL); +} + +static inline double +CanonicalizeNaN(double d) +{ + if (MOZ_UNLIKELY(mozilla::IsNaN(d))) + return GenericNaN(); + return d; +} + /* * JS::Value is the interface for a single JavaScript Engine value. A few * general notes on JS::Value: @@ -1393,22 +1401,35 @@ SameType(const Value &lhs, const Value &rhs) /************************************************************************/ +#ifdef JSGC_GENERATIONAL +namespace JS { +JS_PUBLIC_API(void) HeapValuePostBarrier(Value *valuep); +JS_PUBLIC_API(void) HeapValueRelocate(Value *valuep); +} +#endif + namespace js { -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } }; -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } + static bool needsPostBarrier(const JS::Value &v) { return v.isMarkable(); } +#ifdef JSGC_GENERATIONAL + static void postBarrier(JS::Value *v) { JS::HeapValuePostBarrier(v); } + static void relocate(JS::Value *v) { JS::HeapValueRelocate(v); } +#endif }; +template class UnbarrieredMutableValueOperations; template class MutableValueOperations; /* @@ -1420,7 +1441,9 @@ template class MutableValueOperations; template class ValueOperations { + friend class UnbarrieredMutableValueOperations; friend class MutableValueOperations; + const JS::Value * value() const { return static_cast(this)->extract(); } public: @@ -1453,19 +1476,22 @@ class ValueOperations void *toGCThing() const { return value()->toGCThing(); } JSValueType extractNonDoubleType() const { return value()->extractNonDoubleType(); } + uint32_t toPrivateUint32() const { return value()->toPrivateUint32(); } JSWhyMagic whyMagic() const { return value()->whyMagic(); } }; /* - * A class designed for CRTP use in implementing the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible extractMutable() and extract() - * methods returning the const Value* and Value* abstracted by Outer. + * A class designed for CRTP use in implementing the mutating parts of the Value + * interface in Value-like classes that don't need post barriers. Outer must be + * a class inheriting UnbarrieredMutableValueOperations with visible + * extractMutable() and extract() methods returning the const Value* and Value* + * abstracted by Outer. */ template -class MutableValueOperations : public ValueOperations +class UnbarrieredMutableValueOperations : public ValueOperations { + friend class MutableValueOperations; JS::Value * value() { return static_cast(this)->extractMutable(); } public: @@ -1473,14 +1499,66 @@ class MutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } - void setString(JSString *str) { value()->setString(str); } - void setString(const JS::Anchor &str) { value()->setString(str); } - void setObject(JSObject &obj) { value()->setObject(obj); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } bool setNumber(double d) { return value()->setNumber(d); } - void setObjectOrNull(JSObject *arg) { value()->setObjectOrNull(arg); } +}; + +/* + * A class designed for CRTP use in implementing all the mutating parts of the + * Value interface in Value-like classes. Outer must be a class inheriting + * MutableValueOperations with visible extractMutable() and extract() + * methods returning the const Value* and Value* abstracted by Outer. + */ +template +class MutableValueOperations : public UnbarrieredMutableValueOperations +{ + public: + void setString(JSString *str) { this->value()->setString(str); } + void setString(const JS::Anchor &str) { this->value()->setString(str); } + void setObject(JSObject &obj) { this->value()->setObject(obj); } + void setObjectOrNull(JSObject *arg) { this->value()->setObjectOrNull(arg); } +}; + +/* + * Augment the generic Heap interface when T = Value with + * type-querying, value-extracting, and mutating operations. + */ +template <> +class HeapBase : public UnbarrieredMutableValueOperations > +{ + typedef JS::Heap Outer; + + friend class ValueOperations; + friend class UnbarrieredMutableValueOperations; + + const JS::Value * extract() const { return static_cast(this)->address(); } + JS::Value * extractMutable() { return static_cast(this)->unsafeGet(); } + + /* + * Setters that potentially change the value to a GC thing from a non-GC + * thing must call JS::Heap::set() to trigger the post barrier. + * + * Changing from a GC thing to a non-GC thing value will leave the heap + * value in the store buffer, but it will be ingored so this is not a + * problem. + */ + void setBarriered(const JS::Value &v) { + static_cast *>(this)->set(v); + } + + public: + void setString(JSString *str) { setBarriered(JS::StringValue(str)); } + void setString(const JS::Anchor &str) { setBarriered(JS::StringValue(str.get())); } + void setObject(JSObject &obj) { setBarriered(JS::ObjectValue(obj)); } + + void setObjectOrNull(JSObject *arg) { + if (arg) + setObject(*arg); + else + setNull(); + } }; /* @@ -1508,6 +1586,7 @@ class MutableHandleBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1526,6 +1605,7 @@ class RootedBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1574,12 +1654,12 @@ inline Anchor::~Anchor() namespace detail { struct ValueAlignmentTester { char c; JS::Value v; }; -MOZ_STATIC_ASSERT(sizeof(ValueAlignmentTester) == 16, - "JS::Value must be 16-byte-aligned"); +static_assert(sizeof(ValueAlignmentTester) == 16, + "JS::Value must be 16-byte-aligned"); struct LayoutAlignmentTester { char c; jsval_layout l; }; -MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, - "jsval_layout must be 16-byte-aligned"); +static_assert(sizeof(LayoutAlignmentTester) == 16, + "jsval_layout must be 16-byte-aligned"); } // namespace detail #endif /* DEBUG */ @@ -1593,8 +1673,8 @@ MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, */ typedef JS::Value jsval; -MOZ_STATIC_ASSERT(sizeof(jsval_layout) == sizeof(JS::Value), - "jsval_layout and JS::Value must have identical layouts"); +static_assert(sizeof(jsval_layout) == sizeof(JS::Value), + "jsval_layout and JS::Value must have identical layouts"); /************************************************************************/ @@ -1762,4 +1842,4 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } -#endif /* js_Value_h___ */ +#endif /* js_Value_h */ diff --git a/external/spidermonkey/include/mac/js/Vector.h b/external/spidermonkey/include/mac/js/Vector.h index 5f40dd634b..b14d75c758 100644 --- a/external/spidermonkey/include/mac/js/Vector.h +++ b/external/spidermonkey/include/mac/js/Vector.h @@ -4,14 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsvector_h_ -#define jsvector_h_ +#ifndef js_Vector_h +#define js_Vector_h -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "TemplateLib.h" -#include "Utility.h" +#include "mozilla/Vector.h" /* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ #ifdef _MSC_VER @@ -23,1085 +19,48 @@ namespace js { class TempAllocPolicy; -template +// using Vector = mozilla::Vector; +// +// ...and get rid of all the CRTP madness in mozilla::Vector(Base). But we +// can't because compiler support's not up to snuff. (Template aliases are in +// gcc 4.7 and clang 3.0 and are expected to be in MSVC 2013.) Instead, have a +// completely separate class inheriting from mozilla::Vector, and throw CRTP at +// the problem til things work. +// +// This workaround presents a couple issues. First, because js::Vector is a +// distinct type from mozilla::Vector, overload resolution, method calls, etc. +// are affected. *Hopefully* this won't be too bad in practice. (A bunch of +// places had to be fixed when mozilla::Vector was introduced, but it wasn't a +// crazy number.) Second, mozilla::Vector's interface has to be made subclass- +// ready via CRTP -- or rather, via mozilla::VectorBase, which basically no one +// should use. :-) Third, we have to redefine the constructors and the non- +// inherited operators. Blech. Happily there aren't too many of these, so it +// isn't the end of the world. + +template -class Vector; - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that cap*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring - * this. - */ -template -static bool CapacityHasExcessSpace(size_t cap) +class Vector + : public mozilla::VectorBase > { - size_t size = cap * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* Destroys constructed objects in the range [begin, end). */ - static inline void destroy(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - p->~T(); - } - - /* Constructs objects in the uninitialized range [begin, end). */ - static inline void initialize(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - /* - * Copy-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(*p); - } - - /* - * Move-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(Move(*p)); - } - - /* - * Copy-constructs objects in the uninitialized range [dst, dst+n) from the - * same object u. - */ - template - static inline void copyConstructN(T *dst, size_t n, const U &u) { - for (T *end = dst + n; dst != end; ++dst) - new(dst) T(u); - } - - /* - * Grows the given buffer to have capacity newCap, preserving the objects - * constructed in the range [begin, end) and updating v. Assumes that (1) - * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will - * not overflow. - */ - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); - if (!newbuf) - return false; - for (T *dst = newbuf, *src = v.beginNoCheck(); src != v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); - VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); - v.free_(v.mBegin); - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - static inline void destroy(T *, T *) {} - - static inline void initialize(T *begin, T *end) { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(begin, 0, sizeof(T) * (end-begin)); - */ - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); - */ - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - *dst = *p; - } - - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - copyConstruct(dst, srcbeg, srcend); - } - - static inline void copyConstructN(T *dst, size_t n, const T &t) { - for (T *p = dst, *end = dst + n; p != end; ++p) - *p = t; - } - - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - size_t oldSize = sizeof(T) * v.mCapacity; - size_t newSize = sizeof(T) * newCap; - T *newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); - if (!newbuf) - return false; - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * JS-friendly, STL-like container providing a short-lived, dynamic buffer. - * Vector calls the constructors/destructors of all elements stored in - * its internal buffer, so non-PODs may be safely used. Additionally, - * Vector will store the first N elements in-place before resorting to - * dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * N requirements: - * - any value, however, N is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in jsalloc.h (default js::TempAllocPolicy) - * - * N.B: Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object. - */ -template -class Vector : private AllocPolicy -{ - // typedef typename tl::StaticAssert::result>::result _; - - /* utilities */ - - static const bool sElemIsPod = mozilla::IsPod::value; - typedef VectorImpl Impl; - friend struct VectorImpl; - - bool growStorageBy(size_t incr); - bool convertToHeapStorage(size_t newCap); - - template inline bool growByImpl(size_t inc); - - /* magic constants */ - - static const int sMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are - * 0 inline elements. This allows us to compile when the definition - * of the element type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so - * in order to keep everything here, we use a dummy template - * parameter with partial specialization. - */ - template - struct ElemSize { - static const size_t result = sizeof(T); - }; - template - struct ElemSize<0, Dummy> { - static const size_t result = 1; - }; - - static const size_t sInlineCapacity = - tl::Min::result>::result; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t sInlineBytes = - tl::Max<1, sInlineCapacity * ElemSize::result>::result; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T *mBegin; - size_t mLength; /* Number of elements in the Vector. */ - size_t mCapacity; /* Max number of elements storable in the Vector without resizing. */ -#ifdef DEBUG - size_t mReserved; /* Max elements of reserved or used space in this vector. */ -#endif - - mozilla::AlignedStorage storage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool entered; -#endif - - Vector(const Vector &) MOZ_DELETE; - Vector &operator=(const Vector &) MOZ_DELETE; - - /* private accessors */ - - bool usingInlineStorage() const { - return mBegin == inlineStorage(); - } - - T *inlineStorage() const { - return (T *)storage.addr(); - } - - T *beginNoCheck() const { - return mBegin; - } - - T *endNoCheck() { - return mBegin + mLength; - } - - const T *endNoCheck() const { - return mBegin + mLength; - } - -#ifdef DEBUG - size_t reserved() const { - JS_ASSERT(mReserved <= mCapacity); - JS_ASSERT(mLength <= mReserved); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U u); - void internalAppendN(const T &t, size_t n); - template void internalAppend(const U *begin, size_t length); - template void internalAppend(const Vector &other); + typedef typename mozilla::VectorBase Base; public: - static const size_t sMaxInlineStorage = N; - - typedef T ElementType; - - Vector(AllocPolicy = AllocPolicy()); - Vector(MoveRef); /* Move constructor. */ - Vector &operator=(MoveRef); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy &allocPolicy() const { - return *this; + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector &operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); } - - AllocPolicy &allocPolicy() { - return *this; - } - - enum { InlineLength = N }; - - size_t length() const { - return mLength; - } - - bool empty() const { - return mLength == 0; - } - - size_t capacity() const { - return mCapacity; - } - - T *begin() { - JS_ASSERT(!entered); - return mBegin; - } - - const T *begin() const { - JS_ASSERT(!entered); - return mBegin; - } - - T *end() { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - const T *end() const { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - T &operator[](size_t i) { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - const T &operator[](size_t i) const { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - T &back() { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - const T &back() const { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - class Range { - friend class Vector; - T *cur_, *end_; - Range(T *cur, T *end) : cur_(cur), end_(end) {} - public: - Range() {} - bool empty() const { return cur_ == end_; } - size_t remain() const { return end_ - cur_; } - T &front() const { return *cur_; } - void popFront() { JS_ASSERT(!empty()); ++cur_; } - T popCopyFront() { JS_ASSERT(!empty()); return *cur_++; } - }; - - Range all() { - return Range(begin(), end()); - } - - /* mutators */ - - /* Given that the Vector is empty and has no inline storage, grow to |capacity|. */ - bool initCapacity(size_t request); - - /* If reserve(length() + N) succeeds, the N next appends are guaranteed to succeed. */ - bool reserve(size_t request); - - /* - * Destroy elements in the range [end() - incr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t incr); - - /* Grow the vector by incr elements. */ - bool growBy(size_t incr); - - /* Call shrinkBy or growBy based on whether newSize > length(). */ - bool resize(size_t newLength); - - /* Leave new elements as uninitialized memory. */ - bool growByUninitialized(size_t incr); - bool resizeUninitialized(size_t newLength); - - /* Shorthand for shrinkBy(length()). */ - void clear(); - - /* Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /* If true, appending |needed| elements will not call realloc(). */ - bool canAppendWithoutRealloc(size_t needed) const; - - /* - * Potentially fallible append operations. - * - * The function templates that take an unspecified type U require a - * const T & or a MoveRef. The MoveRef variants move their - * operands into the vector, instead of copying them. If they fail, the - * operand is left unmoved. - */ - template bool append(U t); - bool appendN(const T &t, size_t n); - template bool append(const U *begin, const U *end); - template bool append(const U *begin, size_t length); - template bool append(const Vector &other); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. - */ - template void infallibleAppend(const U &u) { - internalAppend(u); - } - void infallibleAppendN(const T &t, size_t n) { - internalAppendN(t, n); - } - template void infallibleAppend(const U *aBegin, const U *aEnd) { - internalAppend(aBegin, mozilla::PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U *aBegin, size_t aLength) { - internalAppend(aBegin, aLength); - } - template void infallibleAppend(const Vector &other) { - internalAppend(other); - } - - void popBack(); - - T popCopy(); - - /* - * Transfers ownership of the internal buffer used by Vector to the caller. - * After this call, the Vector is empty. Since the returned buffer may need - * to be allocated (if the elements are currently stored in-place), the - * call can fail, returning NULL. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - T *extractRawBuffer(); - - /* - * Transfer ownership of an array of objects into the Vector. - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T *p, size_t length); - - /* - * Places |val| at position |p|, shifting existing elements from |p| - * onward one position higher. On success, |p| should not be reused - * because it will be a dangling pointer if reallocation of the vector - * storage occurred; the return value should be used instead. On failure, - * NULL is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) - * - * - */ - T *insert(T *p, const T &val); - - /* - * Removes the element |t|, which must fall in the bounds [begin, end), - * shifting existing elements from |t + 1| onward one position lower. - */ - void erase(T *t); - - /* - * Measure the size of the Vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - /* - * Like sizeOfExcludingThis, but also measures the size of the Vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - void swap(Vector &other); }; -/* This does the re-entrancy check plus several other sanity checks. */ -#define REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - JS_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ - JS_ASSERT(reserved() <= mCapacity); \ - JS_ASSERT(mLength <= reserved()); \ - JS_ASSERT(mLength <= mCapacity) +} // namespace js -/* Vector Implementation */ - -template -JS_ALWAYS_INLINE -Vector::Vector(AllocPolicy ap) - : AllocPolicy(ap), mBegin((T *)storage.addr()), mLength(0), - mCapacity(sInlineCapacity) -#ifdef DEBUG - , mReserved(sInlineCapacity), entered(false) -#endif -{} - -/* Move constructor. */ -template -JS_ALWAYS_INLINE -Vector::Vector(MoveRef rhs) - : AllocPolicy(rhs) -#ifdef DEBUG - , entered(false) -#endif -{ - mLength = rhs->mLength; - mCapacity = rhs->mCapacity; -#ifdef DEBUG - mReserved = rhs->mReserved; -#endif - - if (rhs->usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = (T *)storage.addr(); - Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); - /* - * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = rhs->mBegin; - rhs->mBegin = (T *) rhs->storage.addr(); - rhs->mCapacity = sInlineCapacity; - rhs->mLength = 0; -#ifdef DEBUG - rhs->mReserved = sInlineCapacity; -#endif - } -} - -/* Move assignment. */ -template -JS_ALWAYS_INLINE -Vector & -Vector::operator=(MoveRef rhs) -{ - this->~Vector(); - new(this) Vector(rhs); - return *this; -} - -template -JS_ALWAYS_INLINE -Vector::~Vector() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); -} - -/* - * This function will create a new heap buffer with capacity newCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t newCap) -{ - JS_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); - if (!newBuf) - return false; - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = newCap; - return true; -} - -template -JS_NEVER_INLINE bool -Vector::growStorageBy(size_t incr) -{ - JS_ASSERT(mLength + incr > mCapacity); - JS_ASSERT_IF(!usingInlineStorage(), !CapacityHasExcessSpace(mCapacity)); - - /* - * When choosing a new capacity, its size should is as close to 2^N bytes - * as possible. 2^N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2^N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2^N request size. - */ - - size_t newCap; - - if (incr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::result; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength*4*sizeof(T) overflow? This condition limits a Vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. - * It also ensures that the ((char *)end() - (char *)begin()) does not - * overflow ptrdiff_t (see Bug 510319). - */ - if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::result) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is - * already as close to 2^N as sizeof(T) will allow. Just double the - * capacity, and then there might be space for one more element. - */ - newCap = mLength * 2; - if (CapacityHasExcessSpace(newCap)) - newCap += 1; - - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + incr; - - /* Did mLength+incr overflow? Will newCap*sizeof(T) overflow? */ - if (newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::result) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { - convert: - return convertToHeapStorage(newCap); - } - - grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t request) -{ - JS_ASSERT(empty()); - JS_ASSERT(usingInlineStorage()); - if (request == 0) - return true; - T *newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); - if (!newbuf) - return false; - mBegin = newbuf; - mCapacity = request; -#ifdef DEBUG - mReserved = request; -#endif - return true; -} - -template -inline bool -Vector::reserve(size_t request) -{ - REENTRANCY_GUARD_ET_AL; - if (request > mCapacity && !growStorageBy(request - mLength)) - return false; - -#ifdef DEBUG - if (request > mReserved) - mReserved = request; - JS_ASSERT(mLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(incr <= mLength); - Impl::destroy(endNoCheck() - incr, endNoCheck()); - mLength -= incr; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::growByImpl(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - if (incr > mCapacity - mLength && !growStorageBy(incr)) - return false; - - JS_ASSERT(mLength + incr <= mCapacity); - T *newend = endNoCheck() + incr; - if (InitNewElems) - Impl::initialize(endNoCheck(), newend); - mLength += incr; -#ifdef DEBUG - if (mLength > mReserved) - mReserved = mLength; -#endif - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::growBy(size_t incr) -{ - return growByImpl(incr); -} - -template -JS_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t incr) -{ - return growByImpl(incr); -} - -template -STATIC_POSTCONDITION(!return || ubound(this->begin()) >= newLength) -inline bool -Vector::resize(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growBy(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growByUninitialized(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -inline void -Vector::clear() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) - return; - - this->free_(beginNoCheck()); - mBegin = (T *)storage.addr(); - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t needed) const -{ - return mLength + needed <= mCapacity; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(U t) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity && !growStorageBy(1)) - return false; - -#ifdef DEBUG - if (mLength + 1 > mReserved) - mReserved = mLength + 1; -#endif - internalAppend(t); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(U u) -{ - JS_ASSERT(mLength + 1 <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - new(endNoCheck()) T(u); - ++mLength; -} - -template -JS_ALWAYS_INLINE bool -Vector::appendN(const T &t, size_t needed) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppendN(t, needed); - return true; -} - -template -JS_ALWAYS_INLINE void -Vector::internalAppendN(const T &t, size_t needed) -{ - JS_ASSERT(mLength + needed <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), needed, t); - mLength += needed; -} - -template -inline T * -Vector::insert(T *p, const T &val) -{ - JS_ASSERT(begin() <= p && p <= end()); - size_t pos = p - begin(); - JS_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(val)) - return NULL; - } else { - T oldBack = back(); - if (!append(oldBack)) /* Dup the last element. */ - return NULL; - for (size_t i = oldLength; i > pos; --i) - (*this)[i] = (*this)[i - 1]; - (*this)[pos] = val; - } - return begin() + pos; -} - -template -inline void -Vector::erase(T *it) -{ - JS_ASSERT(begin() <= it && it < end()); - while (it + 1 != end()) { - *it = *(it + 1); - ++it; - } - popBack(); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, const U *insEnd) -{ - REENTRANCY_GUARD_ET_AL; - size_t needed = mozilla::PointerRangeSize(insBegin, insEnd); - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppend(insBegin, needed); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(const U *insBegin, size_t insLength) -{ - JS_ASSERT(mLength + insLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); - mLength += insLength; -} - -template -template -inline bool -Vector::append(const Vector &other) -{ - return append(other.begin(), other.end()); -} - -template -template -inline void -Vector::internalAppend(const Vector &other) -{ - internalAppend(other.begin(), other.length()); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, size_t insLength) -{ - return this->append(insBegin, insBegin + insLength); -} - -template -JS_ALWAYS_INLINE void -Vector::popBack() -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -JS_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T * -Vector::extractRawBuffer() -{ - T *ret; - if (usingInlineStorage()) { - ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); - if (!ret) - return NULL; - Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - /* mBegin, mCapacity are unchanged. */ - mLength = 0; - } else { - ret = mBegin; - mBegin = (T *)storage.addr(); - mLength = 0; - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif - } - return ret; -} - -template -inline void -Vector::replaceRawBuffer(T *p, size_t aLength) -{ - REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); - - /* Take in the new buffer. */ - if (aLength <= sInlineCapacity) { - /* - * We convert to inline storage if possible, even though p might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = (T *)storage.addr(); - mLength = aLength; - mCapacity = sInlineCapacity; - Impl::moveConstruct(mBegin, p, p + aLength); - Impl::destroy(p, p + aLength); - this->free_(p); - } else { - mBegin = p; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); -} - -template -inline void -Vector::swap(Vector &other) -{ - // TODO Implement N != 0 - JS_STATIC_ASSERT(N == 0); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && other.usingInlineStorage()) { - other.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !other.usingInlineStorage()) { - mBegin = other.mBegin; - other.mBegin = other.inlineStorage(); - } else if (!usingInlineStorage() && !other.usingInlineStorage()) { - Swap(mBegin, other.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, other.mLength); - Swap(mCapacity, other.mCapacity); -#ifdef DEBUG - Swap(mReserved, other.mReserved); -#endif -} - -} /* namespace js */ - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* jsvector_h_ */ +#endif /* js_Vector_h */ diff --git a/external/spidermonkey/include/mac/jsalloc.h b/external/spidermonkey/include/mac/jsalloc.h index e7e64fc540..3abc4966d1 100644 --- a/external/spidermonkey/include/mac/jsalloc.h +++ b/external/spidermonkey/include/mac/jsalloc.h @@ -4,32 +4,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsalloc_h_ -#define jsalloc_h_ +/* JS allocation policies. */ + +#ifndef jsalloc_h +#define jsalloc_h + +#include "mozilla/AllocPolicy.h" #include "js/Utility.h" -#include "jstypes.h" struct JSContext; namespace js { -/* - * Allocation policies. These model the concept: - * - public copy constructor, assignment, destructor - * - void *malloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *calloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *realloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * The *used* bytes of the previous buffer is passed in - * (rather than the old allocation size), in addition to - * the *new* allocation size requested. - * - void free_(void *) - * - reportAllocOverflow() - * Called on overflow before the container returns NULL. - */ +class ContextFriendFields; /* Policy for using system memory functions and doing no error reporting. */ class SystemAllocPolicy @@ -53,7 +41,7 @@ class SystemAllocPolicy */ class TempAllocPolicy { - JSContext *const cx_; + ContextFriendFields *const cx_; /* * Non-inline helper to call JSRuntime::onOutOfMemory with minimal @@ -62,11 +50,8 @@ class TempAllocPolicy JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes); public: - TempAllocPolicy(JSContext *cx) : cx_(cx) {} - - JSContext *context() const { - return cx_; - } + TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :( + TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {} void *malloc_(size_t bytes) { void *p = js_malloc(bytes); @@ -98,4 +83,4 @@ class TempAllocPolicy } /* namespace js */ -#endif /* jsalloc_h_ */ +#endif /* jsalloc_h */ diff --git a/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id index db9dbac6b4..27b6bbed78 100644 --- a/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -0ec74a6f5f2aa9bbaa6a8cbf6e2ae95ec7c4ee43 \ No newline at end of file +e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file diff --git a/external/spidermonkey/include/mac/jsclass.h b/external/spidermonkey/include/mac/jsclass.h index c9b53c7679..def641715d 100644 --- a/external/spidermonkey/include/mac/jsclass.h +++ b/external/spidermonkey/include/mac/jsclass.h @@ -4,14 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclass_h__ -#define jsclass_h__ +#ifndef jsclass_h +#define jsclass_h /* * A JSClass acts as a vtable for JS objects that allows JSAPI clients to * control various aspects of the behavior of an object like property lookup. * js::Class is an engine-private extension that allows more control over * object behavior and, e.g., allows custom slow layout. */ + #include "jsapi.h" #include "jsprvtd.h" @@ -21,6 +22,10 @@ class PropertyName; class SpecialId; class PropertyId; +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; + static JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); @@ -195,7 +200,7 @@ typedef void const char *name; \ uint32_t flags; \ \ - /* Mandatory non-null function pointer members. */ \ + /* Mandatory function pointer members. */ \ JSPropertyOp addProperty; \ JSDeletePropertyOp delProperty; \ JSPropertyOp getProperty; \ @@ -203,9 +208,9 @@ typedef void JSEnumerateOp enumerate; \ JSResolveOp resolve; \ JSConvertOp convert; \ - FinalizeOp finalize; \ \ - /* Optionally non-null members start here. */ \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ JSCheckAccessOp checkAccess; \ JSNative call; \ JSHasInstanceOp hasInstance; \ @@ -214,7 +219,7 @@ typedef void /* * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to padd js::Class to match the size of JSClass; + * we have to pad js::Class to match the size of JSClass. */ struct ClassSizeMeasurement { @@ -312,8 +317,9 @@ struct Class return flags & JSCLASS_EMULATES_UNDEFINED; } - /* Defined in jsfuninlines.h */ - inline bool isCallable() const; + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } static size_t offsetOfFlags() { return offsetof(Class, flags); } }; @@ -387,7 +393,7 @@ IsPoisonedSpecialId(js::SpecialId iden) return false; } -template <> struct RootMethods +template <> struct GCMethods { static SpecialId initial() { return SpecialId(); } static ThingRootKind kind() { return THING_ROOT_ID; } @@ -396,4 +402,4 @@ template <> struct RootMethods } /* namespace js */ -#endif /* jsclass_h__ */ +#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/mac/jsclist.h b/external/spidermonkey/include/mac/jsclist.h index 8782307fa4..23da9b8cd5 100644 --- a/external/spidermonkey/include/mac/jsclist.h +++ b/external/spidermonkey/include/mac/jsclist.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclist_h___ -#define jsclist_h___ +#ifndef jsclist_h +#define jsclist_h #include "jstypes.h" @@ -104,4 +104,4 @@ typedef struct JSCListStr { #define JS_INIT_STATIC_CLIST(_l) \ {(_l), (_l)} -#endif /* jsclist_h___ */ +#endif /* jsclist_h */ diff --git a/external/spidermonkey/include/mac/jscpucfg.h b/external/spidermonkey/include/mac/jscpucfg.h index 6bb62b420f..c79bd7ad14 100644 --- a/external/spidermonkey/include/mac/jscpucfg.h +++ b/external/spidermonkey/include/mac/jscpucfg.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_cpucfg___ -#define js_cpucfg___ +#ifndef jscpucfg_h +#define jscpucfg_h #define JS_HAVE_LONG_LONG @@ -114,4 +114,4 @@ # endif #endif -#endif /* js_cpucfg___ */ +#endif /* jscpucfg_h */ diff --git a/external/spidermonkey/include/mac/jsdbgapi.h b/external/spidermonkey/include/mac/jsdbgapi.h index 4907d913a0..0ce7101337 100644 --- a/external/spidermonkey/include/mac/jsdbgapi.h +++ b/external/spidermonkey/include/mac/jsdbgapi.h @@ -4,12 +4,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsdbgapi_h___ -#define jsdbgapi_h___ +#ifndef jsdbgapi_h +#define jsdbgapi_h /* * JS debugger API. */ -#include "jsapi.h" + #include "jsprvtd.h" namespace JS { @@ -111,7 +111,7 @@ JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, JSTrapHandler *handlerp, jsval *closurep); extern JS_PUBLIC_API(void) -JS_ClearScriptTraps(JSContext *cx, JSScript *script); +JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); @@ -224,12 +224,6 @@ JS_GetScriptLineExtent(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(JSVersion) JS_GetScriptVersion(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(bool) -JS_GetScriptUserBit(JSScript *script); - -extern JS_PUBLIC_API(void) -JS_SetScriptUserBit(JSScript *script, bool b); - extern JS_PUBLIC_API(bool) JS_GetScriptIsSelfHosted(JSScript *script); @@ -433,9 +427,6 @@ JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ -extern JS_FRIEND_API(void) -js_RevertVersion(JSContext *cx); - extern JS_PUBLIC_API(const JSDebugHooks *) JS_GetGlobalDebugHooks(JSRuntime *rt); @@ -465,4 +456,4 @@ JS_DumpCompartmentPCCounts(JSContext *cx); extern JS_FRIEND_API(JSBool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h___ */ +#endif /* jsdbgapi_h */ diff --git a/external/spidermonkey/include/mac/jsdhash.h b/external/spidermonkey/include/mac/jsdhash.h deleted file mode 100644 index 1f7830fd2b..0000000000 --- a/external/spidermonkey/include/mac/jsdhash.h +++ /dev/null @@ -1,612 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsdhash_h___ -#define jsdhash_h___ - -/* - * Double hashing, a la Knuth 6. - * - * Try to keep this file in sync with xpcom/glue/pldhash.h. - */ -#include "jstypes.h" -#include "jsutil.h" - -#if defined(__GNUC__) && defined(__i386__) && !defined(XP_OS2) -#define JS_DHASH_FASTCALL __attribute__ ((regparm (3),stdcall)) -#elif defined(XP_WIN) -#define JS_DHASH_FASTCALL __fastcall -#else -#define JS_DHASH_FASTCALL -#endif - -#ifdef DEBUG_XXXbrendan -#define JS_DHASHMETER 1 -#endif - -/* Table size limit, do not equal or exceed (see min&maxAlphaFrac, below). */ -#undef JS_DHASH_SIZE_LIMIT -#define JS_DHASH_SIZE_LIMIT JS_BIT(24) - -/* Minimum table size, or gross entry count (net is at most .75 loaded). */ -#ifndef JS_DHASH_MIN_SIZE -#define JS_DHASH_MIN_SIZE 16 -#elif (JS_DHASH_MIN_SIZE & (JS_DHASH_MIN_SIZE - 1)) != 0 -#error "JS_DHASH_MIN_SIZE must be a power of two!" -#endif - -/* - * Multiplicative hash uses an unsigned 32 bit integer and the golden ratio, - * expressed as a fixed-point 32-bit fraction. - */ -#define JS_DHASH_BITS 32 -#define JS_DHASH_GOLDEN_RATIO 0x9E3779B9U - -/* Primitive and forward-struct typedefs. */ -typedef uint32_t JSDHashNumber; -typedef struct JSDHashEntryHdr JSDHashEntryHdr; -typedef struct JSDHashEntryStub JSDHashEntryStub; -typedef struct JSDHashTable JSDHashTable; -typedef struct JSDHashTableOps JSDHashTableOps; - -/* - * Table entry header structure. - * - * In order to allow in-line allocation of key and value, we do not declare - * either here. Instead, the API uses const void *key as a formal parameter. - * The key need not be stored in the entry; it may be part of the value, but - * need not be stored at all. - * - * Callback types are defined below and grouped into the JSDHashTableOps - * structure, for single static initialization per hash table sub-type. - * - * Each hash table sub-type should nest the JSDHashEntryHdr structure at the - * front of its particular entry type. The keyHash member contains the result - * of multiplying the hash code returned from the hashKey callback (see below) - * by JS_DHASH_GOLDEN_RATIO, then constraining the result to avoid the magic 0 - * and 1 values. The stored keyHash value is table size invariant, and it is - * maintained automatically by JS_DHashTableOperate -- users should never set - * it, and its only uses should be via the entry macros below. - * - * The JS_DHASH_ENTRY_IS_LIVE macro tests whether entry is neither free nor - * removed. An entry may be either busy or free; if busy, it may be live or - * removed. Consumers of this API should not access members of entries that - * are not live. - * - * However, use JS_DHASH_ENTRY_IS_BUSY for faster liveness testing of entries - * returned by JS_DHashTableOperate, as JS_DHashTableOperate never returns a - * non-live, busy (i.e., removed) entry pointer to its caller. See below for - * more details on JS_DHashTableOperate's calling rules. - */ -struct JSDHashEntryHdr { - JSDHashNumber keyHash; /* every entry must begin like this */ -}; - -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_FREE(JSDHashEntryHdr* entry) -{ - return entry->keyHash == 0; -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_BUSY(JSDHashEntryHdr* entry) -{ - return !JS_DHASH_ENTRY_IS_FREE(entry); -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_LIVE(JSDHashEntryHdr* entry) -{ - return entry->keyHash >= 2; -} - -/* - * A JSDHashTable is currently 8 words (without the JS_DHASHMETER overhead) - * on most architectures, and may be allocated on the stack or within another - * structure or class (see below for the Init and Finish functions to use). - * - * To decide whether to use double hashing vs. chaining, we need to develop a - * trade-off relation, as follows: - * - * Let alpha be the load factor, esize the entry size in words, count the - * entry count, and pow2 the power-of-two table size in entries. - * - * (JSDHashTable overhead) > (JSHashTable overhead) - * (unused table entry space) > (malloc and .next overhead per entry) + - * (buckets overhead) - * (1 - alpha) * esize * pow2 > 2 * count + pow2 - * - * Notice that alpha is by definition (count / pow2): - * - * (1 - alpha) * esize * pow2 > 2 * alpha * pow2 + pow2 - * (1 - alpha) * esize > 2 * alpha + 1 - * - * esize > (1 + 2 * alpha) / (1 - alpha) - * - * This assumes both tables must keep keyHash, key, and value for each entry, - * where key and value point to separately allocated strings or structures. - * If key and value can be combined into one pointer, then the trade-off is: - * - * esize > (1 + 3 * alpha) / (1 - alpha) - * - * If the entry value can be a subtype of JSDHashEntryHdr, rather than a type - * that must be allocated separately and referenced by an entry.value pointer - * member, and provided key's allocation can be fused with its entry's, then - * k (the words wasted per entry with chaining) is 4. - * - * To see these curves, feed gnuplot input like so: - * - * gnuplot> f(x,k) = (1 + k * x) / (1 - x) - * gnuplot> plot [0:.75] f(x,2), f(x,3), f(x,4) - * - * For k of 2 and a well-loaded table (alpha > .5), esize must be more than 4 - * words for chaining to be more space-efficient than double hashing. - * - * Solving for alpha helps us decide when to shrink an underloaded table: - * - * esize > (1 + k * alpha) / (1 - alpha) - * esize - alpha * esize > 1 + k * alpha - * esize - 1 > (k + esize) * alpha - * (esize - 1) / (k + esize) > alpha - * - * alpha < (esize - 1) / (esize + k) - * - * Therefore double hashing should keep alpha >= (esize - 1) / (esize + k), - * assuming esize is not too large (in which case, chaining should probably be - * used for any alpha). For esize=2 and k=3, we want alpha >= .2; for esize=3 - * and k=2, we want alpha >= .4. For k=4, esize could be 6, and alpha >= .5 - * would still obtain. See the JS_DHASH_MIN_ALPHA macro further below. - * - * The current implementation uses a configurable lower bound on alpha, which - * defaults to .25, when deciding to shrink the table (while still respecting - * JS_DHASH_MIN_SIZE). - * - * Note a qualitative difference between chaining and double hashing: under - * chaining, entry addresses are stable across table shrinks and grows. With - * double hashing, you can't safely hold an entry pointer and use it after an - * ADD or REMOVE operation, unless you sample table->generation before adding - * or removing, and compare the sample after, dereferencing the entry pointer - * only if table->generation has not changed. - * - * The moral of this story: there is no one-size-fits-all hash table scheme, - * but for small table entry size, and assuming entry address stability is not - * required, double hashing wins. - */ -struct JSDHashTable { - const JSDHashTableOps *ops; /* virtual operations, see below */ - void *data; /* ops- and instance-specific data */ - int16_t hashShift; /* multiplicative hash shift */ - uint8_t maxAlphaFrac; /* 8-bit fixed point max alpha */ - uint8_t minAlphaFrac; /* 8-bit fixed point min alpha */ - uint32_t entrySize; /* number of bytes in an entry */ - uint32_t entryCount; /* number of entries in table */ - uint32_t removedCount; /* removed entry sentinels in table */ - uint32_t generation; /* entry storage generation number */ - char *entryStore; /* entry storage */ -#ifdef JS_DHASHMETER - struct JSDHashStats { - uint32_t searches; /* total number of table searches */ - uint32_t steps; /* hash chain links traversed */ - uint32_t hits; /* searches that found key */ - uint32_t misses; /* searches that didn't find key */ - uint32_t lookups; /* number of JS_DHASH_LOOKUPs */ - uint32_t addMisses; /* adds that miss, and do work */ - uint32_t addOverRemoved; /* adds that recycled a removed entry */ - uint32_t addHits; /* adds that hit an existing entry */ - uint32_t addFailures; /* out-of-memory during add growth */ - uint32_t removeHits; /* removes that hit, and do work */ - uint32_t removeMisses; /* useless removes that miss */ - uint32_t removeFrees; /* removes that freed entry directly */ - uint32_t removeEnums; /* removes done by Enumerate */ - uint32_t grows; /* table expansions */ - uint32_t shrinks; /* table contractions */ - uint32_t compresses; /* table compressions */ - uint32_t enumShrinks; /* contractions after Enumerate */ - } stats; -#endif -}; - -/* - * Size in entries (gross, not net of free and removed sentinels) for table. - * We store hashShift rather than sizeLog2 to optimize the collision-free case - * in SearchTable. - */ -#define JS_DHASH_TABLE_SIZE(table) JS_BIT(JS_DHASH_BITS - (table)->hashShift) - -/* - * Table space at entryStore is allocated and freed using these callbacks. - * The allocator should return null on error only (not if called with nbytes - * equal to 0; but note that jsdhash.c code will never call with 0 nbytes). - */ -typedef void * -(* JSDHashAllocTable)(JSDHashTable *table, uint32_t nbytes); - -typedef void -(* JSDHashFreeTable) (JSDHashTable *table, void *ptr); - -/* - * Compute the hash code for a given key to be looked up, added, or removed - * from table. A hash code may have any JSDHashNumber value. - */ -typedef JSDHashNumber -(* JSDHashHashKey) (JSDHashTable *table, const void *key); - -/* - * Compare the key identifying entry in table with the provided key parameter. - * Return JS_TRUE if keys match, JS_FALSE otherwise. - */ -typedef JSBool -(* JSDHashMatchEntry)(JSDHashTable *table, const JSDHashEntryHdr *entry, - const void *key); - -/* - * Copy the data starting at from to the new entry storage at to. Do not add - * reference counts for any strong references in the entry, however, as this - * is a "move" operation: the old entry storage at from will be freed without - * any reference-decrementing callback shortly. - */ -typedef void -(* JSDHashMoveEntry)(JSDHashTable *table, const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -/* - * Clear the entry and drop any strong references it holds. This callback is - * invoked during a JS_DHASH_REMOVE operation (see below for operation codes), - * but only if the given key is found in the table. - */ -typedef void -(* JSDHashClearEntry)(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Called when a table (whether allocated dynamically by itself, or nested in - * a larger structure, or allocated on the stack) is finished. This callback - * allows table->ops-specific code to finalize table->data. - */ -typedef void -(* JSDHashFinalize) (JSDHashTable *table); - -/* - * Initialize a new entry, apart from keyHash. This function is called when - * JS_DHashTableOperate's JS_DHASH_ADD case finds no existing entry for the - * given key, and must add a new one. At that point, entry->keyHash is not - * set yet, to avoid claiming the last free entry in a severely overloaded - * table. - */ -typedef JSBool -(* JSDHashInitEntry)(JSDHashTable *table, JSDHashEntryHdr *entry, - const void *key); - -/* - * Finally, the "vtable" structure for JSDHashTable. The first eight hooks - * must be provided by implementations; they're called unconditionally by the - * generic jsdhash.c code. Hooks after these may be null. - * - * Summary of allocation-related hook usage with C++ placement new emphasis: - * allocTable Allocate raw bytes with malloc, no ctors run. - * freeTable Free raw bytes with free, no dtors run. - * initEntry Call placement new using default key-based ctor. - * Return JS_TRUE on success, JS_FALSE on error. - * moveEntry Call placement new using copy ctor, run dtor on old - * entry storage. - * clearEntry Run dtor on entry. - * finalize Stub unless table->data was initialized and needs to - * be finalized. - * - * Note the reason why initEntry is optional: the default hooks (stubs) clear - * entry storage: On successful JS_DHashTableOperate(tbl, key, JS_DHASH_ADD), - * the returned entry pointer addresses an entry struct whose keyHash member - * has been set non-zero, but all other entry members are still clear (null). - * JS_DHASH_ADD callers can test such members to see whether the entry was - * newly created by the JS_DHASH_ADD call that just succeeded. If placement - * new or similar initialization is required, define an initEntry hook. Of - * course, the clearEntry hook must zero or null appropriately. - * - * XXX assumes 0 is null for pointer types. - */ -struct JSDHashTableOps { - /* Mandatory hooks. All implementations must provide these. */ - JSDHashAllocTable allocTable; - JSDHashFreeTable freeTable; - JSDHashHashKey hashKey; - JSDHashMatchEntry matchEntry; - JSDHashMoveEntry moveEntry; - JSDHashClearEntry clearEntry; - JSDHashFinalize finalize; - - /* Optional hooks start here. If null, these are not called. */ - JSDHashInitEntry initEntry; -}; - -/* - * Default implementations for the above ops. - */ -extern JS_PUBLIC_API(void *) -JS_DHashAllocTable(JSDHashTable *table, uint32_t nbytes); - -extern JS_PUBLIC_API(void) -JS_DHashFreeTable(JSDHashTable *table, void *ptr); - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashStringKey(JSDHashTable *table, const void *key); - -/* A minimal entry contains a keyHash header and a void key pointer. */ -struct JSDHashEntryStub { - JSDHashEntryHdr hdr; - const void *key; -}; - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashVoidPtrKeyStub(JSDHashTable *table, const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchStringKey(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(void) -JS_DHashMoveEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -extern JS_PUBLIC_API(void) -JS_DHashClearEntryStub(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFreeStringKey(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFinalizeStub(JSDHashTable *table); - -/* - * If you use JSDHashEntryStub or a subclass of it as your entry struct, and - * if your entries move via memcpy and clear via memset(0), you can use these - * stub operations. - */ -extern JS_PUBLIC_API(const JSDHashTableOps *) -JS_DHashGetStubOps(void); - -/* - * Dynamically allocate a new JSDHashTable using malloc, initialize it using - * JS_DHashTableInit, and return its address. Return null on malloc failure. - * Note that the entry storage at table->entryStore will be allocated using - * the ops->allocTable callback. - */ -extern JS_PUBLIC_API(JSDHashTable *) -JS_NewDHashTable(const JSDHashTableOps *ops, void *data, uint32_t entrySize, - uint32_t capacity); - -/* - * Finalize table's data, free its entry storage (via table->ops->freeTable), - * and return the memory starting at table to the malloc heap. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableDestroy(JSDHashTable *table); - -/* - * Initialize table with ops, data, entrySize, and capacity. Capacity is a - * guess for the smallest table size at which the table will usually be less - * than 75% loaded (the table will grow or shrink as needed; capacity serves - * only to avoid inevitable early growth from JS_DHASH_MIN_SIZE). - */ -extern JS_PUBLIC_API(JSBool) -JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data, - uint32_t entrySize, uint32_t capacity); - -/* - * Set maximum and minimum alpha for table. The defaults are 0.75 and .25. - * maxAlpha must be in [0.5, 0.9375] for the default JS_DHASH_MIN_SIZE; or if - * MinSize=JS_DHASH_MIN_SIZE <= 256, in [0.5, (float)(MinSize-1)/MinSize]; or - * else in [0.5, 255.0/256]. minAlpha must be in [0, maxAlpha / 2), so that - * we don't shrink on the very next remove after growing a table upon adding - * an entry that brings entryCount past maxAlpha * tableSize. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableSetAlphaBounds(JSDHashTable *table, - float maxAlpha, - float minAlpha); - -/* - * Call this macro with k, the number of pointer-sized words wasted per entry - * under chaining, to compute the minimum alpha at which double hashing still - * beats chaining. - */ -#define JS_DHASH_MIN_ALPHA(table, k) \ - ((float)((table)->entrySize / sizeof(void *) - 1) \ - / ((table)->entrySize / sizeof(void *) + (k))) - -/* - * Default max/min alpha, and macros to compute the value for the |capacity| - * parameter to JS_NewDHashTable and JS_DHashTableInit, given default or any - * max alpha, such that adding entryCount entries right after initializing the - * table will not require a reallocation (so JS_DHASH_ADD can't fail for those - * JS_DHashTableOperate calls). - * - * NB: JS_DHASH_CAP is a helper macro meant for use only in JS_DHASH_CAPACITY. - * Don't use it directly! - */ -#define JS_DHASH_DEFAULT_MAX_ALPHA 0.75 -#define JS_DHASH_DEFAULT_MIN_ALPHA 0.25 - -#define JS_DHASH_CAP(entryCount, maxAlpha) \ - ((uint32_t)((double)(entryCount) / (maxAlpha))) - -#define JS_DHASH_CAPACITY(entryCount, maxAlpha) \ - (JS_DHASH_CAP(entryCount, maxAlpha) + \ - (((JS_DHASH_CAP(entryCount, maxAlpha) * (uint8_t)(0x100 * (maxAlpha))) \ - >> 8) < (entryCount))) - -#define JS_DHASH_DEFAULT_CAPACITY(entryCount) \ - JS_DHASH_CAPACITY(entryCount, JS_DHASH_DEFAULT_MAX_ALPHA) - -/* - * Finalize table's data, free its entry storage using table->ops->freeTable, - * and leave its members unchanged from their last live values (which leaves - * pointers dangling). If you want to burn cycles clearing table, it's up to - * your code to call memset. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableFinish(JSDHashTable *table); - -/* - * To consolidate keyHash computation and table grow/shrink code, we use a - * single entry point for lookup, add, and remove operations. The operation - * codes are declared here, along with codes returned by JSDHashEnumerator - * functions, which control JS_DHashTableEnumerate's behavior. - */ -typedef enum JSDHashOperator { - JS_DHASH_LOOKUP = 0, /* lookup entry */ - JS_DHASH_ADD = 1, /* add entry */ - JS_DHASH_REMOVE = 2, /* remove entry, or enumerator says remove */ - JS_DHASH_NEXT = 0, /* enumerator says continue */ - JS_DHASH_STOP = 1 /* enumerator says stop */ -} JSDHashOperator; - -/* - * To lookup a key in table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_LOOKUP); - * - * If JS_DHASH_ENTRY_IS_BUSY(entry) is true, key was found and it identifies - * entry. If JS_DHASH_ENTRY_IS_FREE(entry) is true, key was not found. - * - * To add an entry identified by key to table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_ADD); - * - * If entry is null upon return, then either the table is severely overloaded, - * and memory can't be allocated for entry storage via table->ops->allocTable; - * Or if table->ops->initEntry is non-null, the table->ops->initEntry op may - * have returned false. - * - * Otherwise, entry->keyHash has been set so that JS_DHASH_ENTRY_IS_BUSY(entry) - * is true, and it is up to the caller to initialize the key and value parts - * of the entry sub-type, if they have not been set already (i.e. if entry was - * not already in the table, and if the optional initEntry hook was not used). - * - * To remove an entry identified by key from table, call: - * - * (void) JS_DHashTableOperate(table, key, JS_DHASH_REMOVE); - * - * If key's entry is found, it is cleared (via table->ops->clearEntry) and - * the entry is marked so that JS_DHASH_ENTRY_IS_FREE(entry). This operation - * returns null unconditionally; you should ignore its return value. - */ -extern JS_PUBLIC_API(JSDHashEntryHdr *) JS_DHASH_FASTCALL -JS_DHashTableOperate(JSDHashTable *table, const void *key, JSDHashOperator op); - -/* - * Remove an entry already accessed via LOOKUP or ADD. - * - * NB: this is a "raw" or low-level routine, intended to be used only where - * the inefficiency of a full JS_DHashTableOperate (which rehashes in order - * to find the entry given its key) is not tolerable. This function does not - * shrink the table if it is underloaded. It does not update stats #ifdef - * JS_DHASHMETER, either. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableRawRemove(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Enumerate entries in table using etor: - * - * count = JS_DHashTableEnumerate(table, etor, arg); - * - * JS_DHashTableEnumerate calls etor like so: - * - * op = etor(table, entry, number, arg); - * - * where number is a zero-based ordinal assigned to live entries according to - * their order in table->entryStore. - * - * The return value, op, is treated as a set of flags. If op is JS_DHASH_NEXT, - * then continue enumerating. If op contains JS_DHASH_REMOVE, then clear (via - * table->ops->clearEntry) and free entry. Then we check whether op contains - * JS_DHASH_STOP; if so, stop enumerating and return the number of live entries - * that were enumerated so far. Return the total number of live entries when - * enumeration completes normally. - * - * If etor calls JS_DHashTableOperate on table with op != JS_DHASH_LOOKUP, it - * must return JS_DHASH_STOP; otherwise undefined behavior results. - * - * If any enumerator returns JS_DHASH_REMOVE, table->entryStore may be shrunk - * or compressed after enumeration, but before JS_DHashTableEnumerate returns. - * Such an enumerator therefore can't safely set aside entry pointers, but an - * enumerator that never returns JS_DHASH_REMOVE can set pointers to entries - * aside, e.g., to avoid copying live entries into an array of the entry type. - * Copying entry pointers is cheaper, and safe so long as the caller of such a - * "stable" Enumerate doesn't use the set-aside pointers after any call either - * to PL_DHashTableOperate, or to an "unstable" form of Enumerate, which might - * grow or shrink entryStore. - * - * If your enumerator wants to remove certain entries, but set aside pointers - * to other entries that it retains, it can use JS_DHashTableRawRemove on the - * entries to be removed, returning JS_DHASH_NEXT to skip them. Likewise, if - * you want to remove entries, but for some reason you do not want entryStore - * to be shrunk or compressed, you can call JS_DHashTableRawRemove safely on - * the entry being enumerated, rather than returning JS_DHASH_REMOVE. - */ -typedef JSDHashOperator -(* JSDHashEnumerator)(JSDHashTable *table, JSDHashEntryHdr *hdr, uint32_t number, void *arg); - -extern JS_PUBLIC_API(uint32_t) -JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg); - -typedef size_t -(* JSDHashSizeOfEntryExcludingThisFun)(JSDHashEntryHdr *hdr, - JSMallocSizeOfFun mallocSizeOf, - void *arg); - -/** - * Measure the size of the table's entry storage, and if - * |sizeOfEntryExcludingThis| is non-NULL, measure the size of things pointed - * to by entries. Doesn't measure |ops| because it's often shared between - * tables, nor |data| because it's opaque. - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfExcludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -/** - * Like JS_DHashTableSizeOfExcludingThis, but includes sizeof(*this). - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfIncludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -#ifdef DEBUG -/** - * Mark a table as immutable for the remainder of its lifetime. This - * changes the implementation from ASSERTing one set of invariants to - * ASSERTing a different set. - * - * When a table is NOT marked as immutable, the table implementation - * asserts that the table is not mutated from its own callbacks. It - * assumes the caller protects the table from being accessed on multiple - * threads simultaneously. - * - * When the table is marked as immutable, the re-entry assertions will - * no longer trigger erroneously due to multi-threaded access. Instead, - * mutations will cause assertions. - */ -extern JS_PUBLIC_API(void) -JS_DHashMarkTableImmutable(JSDHashTable *table); -#endif - -#ifdef JS_DHASHMETER -#include - -extern JS_PUBLIC_API(void) -JS_DHashTableDumpMeter(JSDHashTable *table, JSDHashEnumerator dump, FILE *fp); -#endif - -#endif /* jsdhash_h___ */ diff --git a/external/spidermonkey/include/mac/jsfriendapi.h b/external/spidermonkey/include/mac/jsfriendapi.h index 848049ffe3..a1c3024fed 100644 --- a/external/spidermonkey/include/mac/jsfriendapi.h +++ b/external/spidermonkey/include/mac/jsfriendapi.h @@ -4,15 +4,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsfriendapi_h___ -#define jsfriendapi_h___ +#ifndef jsfriendapi_h +#define jsfriendapi_h -#include "mozilla/GuardObjects.h" +#include "mozilla/MemoryReporting.h" #include "jsclass.h" -#include "jscpucfg.h" -#include "jspubtd.h" #include "jsprvtd.h" +#include "jspubtd.h" + +#include "js/CallArgs.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -29,6 +30,11 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +namespace JS { +template +class Heap; +} /* namespace JS */ + extern JS_FRIEND_API(void) JS_SetGrayGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data); @@ -48,7 +54,7 @@ extern JS_FRIEND_API(JSObject *) JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JSHandleObject obj); +JS_ObjectCountDynamicSlots(JS::HandleObject obj); extern JS_FRIEND_API(size_t) JS_SetProtoCalled(JSContext *cx); @@ -118,14 +124,27 @@ extern JS_FRIEND_API(JSObject *) JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) -JS_BasicObjectToString(JSContext *cx, JSHandleObject obj); +JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp); +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, + JS::MutableHandleValue vp); JS_FRIEND_API(void) js_ReportOverRecursed(JSContext *maybecx); +JS_FRIEND_API(bool) +js_ObjectClassIs(JSContext *cx, JS::HandleObject obj, js::ESClassValue classValue); + +JS_FRIEND_API(const char *) +js_ObjectClassName(JSContext *cx, JS::HandleObject obj); + +JS_FRIEND_API(bool) +js_AddObjectRoot(JSRuntime *rt, JSObject **objp); + +JS_FRIEND_API(void) +js_RemoveObjectRoot(JSRuntime *rt, JSObject **objp); + #ifdef DEBUG /* @@ -157,7 +176,7 @@ extern JS_FRIEND_API(JSBool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); extern JS_FRIEND_API(JSBool) -JS_EnumerateState(JSContext *cx, JSHandleObject obj, JSIterateOp enum_op, +JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, js::MutableHandleValue statep, js::MutableHandleId idp); struct JSFunctionSpecWithHelp { @@ -177,25 +196,24 @@ struct JSFunctionSpecWithHelp { extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JSScript *script, jschar **src, uint32_t *length); +typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, + jschar **src, uint32_t *length); extern JS_FRIEND_API(void) JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); namespace js { -extern mozilla::ThreadLocal TlsPerThreadData; - inline JSRuntime * GetRuntime(const JSContext *cx) { - return ContextFriendFields::get(cx)->runtime; + return ContextFriendFields::get(cx)->runtime_; } inline JSCompartment * GetContextCompartment(const JSContext *cx) { - return ContextFriendFields::get(cx)->compartment; + return ContextFriendFields::get(cx)->compartment_; } inline JS::Zone * @@ -217,19 +235,6 @@ typedef bool extern JS_FRIEND_API(void) DumpHeapComplete(JSRuntime *rt, FILE *fp); -class JS_FRIEND_API(AutoSwitchCompartment) { - private: - JSContext *cx; - JSCompartment *oldCompartment; - public: - AutoSwitchCompartment(JSContext *cx, JSCompartment *newCompartment - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - AutoSwitchCompartment(JSContext *cx, JSHandleObject target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoSwitchCompartment(); - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - #ifdef OLD_GETTER_SETTER_METHODS JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); @@ -254,6 +259,15 @@ IsAtomsCompartment(JSCompartment *comp); extern JS_FRIEND_API(bool) ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +/* + * Returns whether we're in a non-strict property set (in that we're in a + * non-strict script and the bytecode we're on is a property set). The return + * value does NOT indicate any sort of exception was thrown: it's just a + * boolean. + */ +extern JS_FRIEND_API(bool) +IsInNonStrictPropertySet(JSContext *cx); + struct WeakMapTracer; /* @@ -301,7 +315,7 @@ IterateGrayObjects(JS::Zone *zone, GCThingCallback cellCallback, void *data); #ifdef JS_HAS_CTYPES extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(JSMallocSizeOfFun mallocSizeOf, JSObject *obj); +SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject *obj); #endif extern JS_FRIEND_API(JSCompartment *) @@ -321,8 +335,9 @@ struct TypeObject { }; struct BaseShape { - js::Class *clasp; - JSObject *parent; + js::Class *clasp; + JSObject *parent; + JSObject *_1; JSCompartment *compartment; }; @@ -365,19 +380,22 @@ struct Function { }; struct Atom { - size_t _; + static const size_t LENGTH_SHIFT = 4; + size_t lengthAndFlags; const jschar *chars; }; } /* namespace shadow */ -extern JS_FRIEND_DATA(js::Class) CallClass; -extern JS_FRIEND_DATA(js::Class) DeclEnvClass; -extern JS_FRIEND_DATA(js::Class) FunctionClass; -extern JS_FRIEND_DATA(js::Class) FunctionProxyClass; -extern JS_FRIEND_DATA(js::Class) OuterWindowProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectClass; +// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use +// them in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; + +// This is equal to |&JSObject::class_|. Use it in places where you don't want +// to #include jsobj.h. +extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; inline js::Class * GetObjectClass(JSObject *obj) @@ -401,9 +419,15 @@ IsOuterObject(JSObject *obj) { return !!GetObjectClass(obj)->ext.innerObject; } +JS_FRIEND_API(bool) +IsFunctionObject(JSObject *obj); + JS_FRIEND_API(bool) IsScopeObject(JSObject *obj); +JS_FRIEND_API(bool) +IsCallObject(JSObject *obj); + inline JSObject * GetObjectParent(JSObject *obj) { @@ -423,6 +447,13 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +// For legacy consumers only. This whole concept is going away soon. +JS_FRIEND_API(JSObject *) +DefaultObjectForContextOrNull(JSContext *cx); + +JS_FRIEND_API(void) +SetDefaultObjectForContext(JSContext *cx, JSObject *obj); + JS_FRIEND_API(void) NotifyAnimationActivity(JSObject *obj); @@ -469,11 +500,11 @@ inline bool GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) { js::Class *clasp = GetObjectClass(obj); - if (clasp == &js::ObjectProxyClass || - clasp == &js::OuterWindowProxyClass || - clasp == &js::FunctionProxyClass) + if (clasp == js::ObjectProxyClassPtr || + clasp == js::OuterWindowProxyClassPtr || + clasp == js::FunctionProxyClassPtr) { - return JS_GetPrototype(cx, obj, proto.address()); + return JS_GetPrototype(cx, obj, proto); } proto.set(reinterpret_cast(obj.get())->type->proto); @@ -535,6 +566,13 @@ GetAtomChars(JSAtom *atom) return reinterpret_cast(atom)->chars; } +inline size_t +GetAtomLength(JSAtom *atom) +{ + using shadow::Atom; + return reinterpret_cast(atom)->lengthAndFlags >> Atom::LENGTH_SHIFT; +} + inline JSLinearString * AtomToLinearString(JSAtom *atom) { @@ -589,6 +627,12 @@ GetNativeStackLimit(const JSRuntime *rt) return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; } +inline uintptr_t +GetNativeStackLimit(JSContext *cx) +{ + return GetNativeStackLimit(GetRuntime(cx)); +} + /* * These macros report a stack overflow and run |onerror| if we are close to * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a little @@ -598,18 +642,15 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), &stackDummy_)) { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), &stackDummy_)) { \ js_ReportOverRecursed(cx); \ onerror; \ } \ JS_END_MACRO -#define JS_CHECK_RECURSION_WITH_EXTRA_DONT_REPORT(cx, extra, onerror) \ +#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ JS_BEGIN_MACRO \ - uint8_t stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ - &stackDummy_ - (extra))) \ - { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ onerror; \ } \ JS_END_MACRO @@ -617,7 +658,7 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ + if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(cx), \ &stackDummy_, \ 1024 * sizeof(size_t))) \ { \ @@ -754,13 +795,13 @@ extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JSFlatString *desc); +(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); extern JS_FRIEND_API(AnalysisPurgeCallback) SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); typedef JSBool -(* DOMInstanceClassMatchesProto)(JSHandleObject protoObject, uint32_t protoID, +(* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { DOMInstanceClassMatchesProto instanceClassMatchesProto; @@ -851,10 +892,10 @@ NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& targetFilter, NukeReferencesToWindow nukeReferencesToWindow); -/* Specify information about ListBase proxies in the DOM, for use by ICs. */ +/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ /* - * The ListBaseShadowsCheck function will be called to check if the property for + * The DOMProxyShadowsCheck function will be called to check if the property for * id should be gotten from the prototype, or if there is an own property that * shadows it. * If DoesntShadow is returned then the slot at listBaseExpandoSlot should @@ -873,25 +914,31 @@ struct ExpandoAndGeneration { generation(0) {} - Value expando; + void Unlink() + { + ++generation; + expando.setUndefined(); + } + + JS::Heap expando; uint32_t generation; }; -typedef enum ListBaseShadowsResult { +typedef enum DOMProxyShadowsResult { ShadowCheckFailed, Shadows, DoesntShadow, DoesntShadowUnique -} ListBaseShadowsResult; -typedef ListBaseShadowsResult -(* ListBaseShadowsCheck)(JSContext* cx, JSHandleObject object, JSHandleId id); +} DOMProxyShadowsResult; +typedef DOMProxyShadowsResult +(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetListBaseInformation(void *listBaseHandlerFamily, uint32_t listBaseExpandoSlot, - ListBaseShadowsCheck listBaseShadowsCheck); +SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, + DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetListBaseHandlerFamily(); -uint32_t GetListBaseExpandoSlot(); -ListBaseShadowsCheck GetListBaseShadowsCheck(); +void *GetDOMProxyHandlerFamily(); +uint32_t GetDOMProxyExpandoSlot(); +DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); } /* namespace js */ @@ -960,6 +1007,137 @@ enum ViewType { }; } /* namespace ArrayBufferView */ + +/* + * A helper for building up an ArrayBuffer object's data + * before creating the ArrayBuffer itself. Will do doubling + * based reallocation, up to an optional maximum growth given. + * + * When all the data has been appended, call getArrayBuffer, + * passing in the JSContext* for which the ArrayBuffer object + * is to be created. This also implicitly resets the builder, + * or it can be reset explicitly at any point by calling reset(). + */ +class ArrayBufferBuilder +{ + void *rawcontents_; + uint8_t *dataptr_; + uint32_t capacity_; + uint32_t length_; + public: + ArrayBufferBuilder() + : rawcontents_(NULL), + dataptr_(NULL), + capacity_(0), + length_(0) + { + } + + ~ArrayBufferBuilder() { + reset(); + } + + void reset() { + if (rawcontents_) + JS_free(NULL, rawcontents_); + rawcontents_ = dataptr_ = NULL; + capacity_ = length_ = 0; + } + + // will truncate if newcap is < length() + bool setCapacity(uint32_t newcap) { + if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) + return false; + + capacity_ = newcap; + if (length_ > newcap) + length_ = newcap; + + return true; + } + + // Append datalen bytes from data to the current buffer. If we + // need to grow the buffer, grow by doubling the size up to a + // maximum of maxgrowth (if given). If datalen is greater than + // what the new capacity would end up as, then grow by datalen. + // + // The data parameter must not overlap with anything beyond the + // builder's current valid contents [0..length) + bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { + if (length_ + datalen > capacity_) { + uint32_t newcap; + // double while under maxgrowth or if not specified + if (!maxgrowth || capacity_ < maxgrowth) + newcap = capacity_ * 2; + else + newcap = capacity_ + maxgrowth; + + // but make sure there's always enough to satisfy our request + if (newcap < length_ + datalen) + newcap = length_ + datalen; + + // did we overflow? + if (newcap < capacity_) + return false; + + if (!setCapacity(newcap)) + return false; + } + + // assert that the region isn't overlapping so we can memcpy; + JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); + + memcpy(dataptr_ + length_, newdata, datalen); + length_ += datalen; + + return true; + } + + uint8_t *data() { + return dataptr_; + } + + uint32_t length() { + return length_; + } + + uint32_t capacity() { + return capacity_; + } + + JSObject* getArrayBuffer(JSContext *cx) { + // we need to check for length_ == 0, because nothing may have been + // added + if (capacity_ > length_ || length_ == 0) { + if (!setCapacity(length_)) + return NULL; + } + + JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); + if (!obj) + return NULL; + + rawcontents_ = dataptr_ = NULL; + length_ = capacity_ = 0; + + return obj; + } + +protected: + + static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, + const uint8_t *start2, uint32_t length2) + { + const uint8_t *end1 = start1 + length1; + const uint8_t *end2 = start2 + length2; + + const uint8_t *max_start = start1 > start2 ? start1 : start2; + const uint8_t *min_end = end1 < end2 ? end1 : end2; + + return max_start < min_end; + } +}; + } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1296,26 +1474,116 @@ JS_GetDataViewByteLength(JSObject *obj); JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitGetterOp. + */ +class JSJitGetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitGetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args.rval()) + {} + + explicit JSJitGetterCallArgs(JS::Rooted* rooted) + : JS::MutableHandleValue(rooted) + {} + + JS::MutableHandleValue rval() { + return *this; + } +}; + +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitSetterOp. + */ +class JSJitSetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitSetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args[0]) + {} + + JS::MutableHandleValue operator[](unsigned i) { + MOZ_ASSERT(i == 0); + return *this; + } + + unsigned length() const { return 1; } + + // Add get() or maybe hasDefined() as needed +}; + +struct JSJitMethodCallArgsTraits; + +/* + * A class, expected to be passed by reference, which represents the CallArgs + * for a JSJitMethodOp. + */ +class JSJitMethodCallArgs : protected JS::detail::CallArgsBase +{ + private: + typedef JS::detail::CallArgsBase Base; + friend struct JSJitMethodCallArgsTraits; + + public: + explicit JSJitMethodCallArgs(const JS::CallArgs& args) { + argv_ = args.array(); + argc_ = args.length(); + } + + JS::MutableHandleValue rval() const { + return Base::rval(); + } + + unsigned length() const { return Base::length(); } + + JS::MutableHandleValue operator[](unsigned i) const { + return Base::operator[](i); + } + + bool hasDefined(unsigned i) const { + return Base::hasDefined(i); + } + + // Add get() as needed +}; + +struct JSJitMethodCallArgsTraits +{ + static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); + static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); +}; + /* * This struct contains metadata passed from the DOM to the JS Engine for JIT * optimizations on DOM property accessors. Eventually, this should be made * available to general JSAPI users, but we are not currently ready to do so. */ typedef bool -(* JSJitPropertyOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, JS::Value *vp); +(* JSJitGetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitGetterCallArgs args); typedef bool -(* JSJitMethodOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, unsigned argc, JS::Value *vp); +(* JSJitSetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitSetterCallArgs args); +typedef bool +(* JSJitMethodOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, const JSJitMethodCallArgs& args); struct JSJitInfo { enum OpType { Getter, Setter, - Method + Method, + OpType_None }; - JSJitPropertyOp op; + union { + JSJitGetterOp getter; + JSJitSetterOp setter; + JSJitMethodOp method; + }; uint32_t protoID; uint32_t depth; OpType type; @@ -1325,12 +1593,18 @@ struct JSJitInfo { keep returning the same value for the given "this" object" */ JSValueType returnType; /* The return type tag. Might be JSVAL_TYPE_UNKNOWN */ + + /* An alternative native that's safe to call in parallel mode. */ + JSParallelNative parallelNative; }; +#define JS_JITINFO_NATIVE_PARALLEL(op) \ + {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) { - JS_ASSERT(js::GetObjectClass(&v.toObject()) == &js::FunctionClass); + JS_ASSERT(js::GetObjectClass(&v.toObject()) == js::FunctionClassPtr); return reinterpret_cast(&v.toObject())->jitinfo; } @@ -1482,9 +1756,46 @@ assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id); inline void assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id) {}; #endif +typedef bool +(* ObjectMetadataCallback)(JSContext *cx, JSObject **pmetadata); + +/* + * Specify a callback to invoke when creating each JS object in the current + * compartment, which may return a metadata object to associate with the + * object. Objects with different metadata have different shape hierarchies, + * so for efficiency, objects should generally try to share metadata objects. + */ +JS_FRIEND_API(void) +SetObjectMetadataCallback(JSContext *cx, ObjectMetadataCallback callback); + +/* Manipulate the metadata associated with an object. */ + +JS_FRIEND_API(bool) +SetObjectMetadata(JSContext *cx, JS::HandleObject obj, JS::HandleObject metadata); + +JS_FRIEND_API(JSObject *) +GetObjectMetadata(JSObject *obj); + /* ES5 8.12.8. */ extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); + +/* + * Helper function. To approximate a call to the [[DefineOwnProperty]] internal + * method described in ES5, first call this, then call JS_DefinePropertyById. + * + * JS_DefinePropertyById by itself does not enforce the invariants on + * non-configurable properties when obj->isNative(). This function performs the + * relevant checks (specified in ES5 8.12.9 [[DefineOwnProperty]] steps 1-11), + * but only if obj is native. + * + * The reason for the messiness here is that ES5 uses [[DefineOwnProperty]] as + * a sort of extension point, but there is no hook in js::Class, + * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. + */ +extern JS_FRIEND_API(bool) +CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, + PropertyOp getter, StrictPropertyOp setter, unsigned attrs); } /* namespace js */ @@ -1495,4 +1806,26 @@ js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, extern JS_FRIEND_API(JSBool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); -#endif /* jsfriendapi_h___ */ +#ifdef JSGC_GENERATIONAL +extern JS_FRIEND_API(void) +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data); + +extern JS_FRIEND_API(void) +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data); +#else +inline void +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data) {} + +inline void +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data) {} +#endif /* JSGC_GENERATIONAL */ + +#endif /* jsfriendapi_h */ diff --git a/external/spidermonkey/include/mac/jslock.h b/external/spidermonkey/include/mac/jslock.h index b4a28a9fa9..522034ad68 100644 --- a/external/spidermonkey/include/mac/jslock.h +++ b/external/spidermonkey/include/mac/jslock.h @@ -4,18 +4,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jslock_h__ -#define jslock_h__ - -#include "jsapi.h" +#ifndef jslock_h +#define jslock_h #ifdef JS_THREADSAFE +# include "jsapi.h" # include "pratom.h" -# include "prlock.h" # include "prcvar.h" -# include "prthread.h" # include "prinit.h" +# include "prlock.h" +# include "prthread.h" # define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) # define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) @@ -40,4 +39,4 @@ typedef struct PRLock PRLock; #endif /* JS_THREADSAFE */ -#endif /* jslock_h___ */ +#endif /* jslock_h */ diff --git a/external/spidermonkey/include/mac/json.h b/external/spidermonkey/include/mac/json.h deleted file mode 100644 index 7fa2c117c8..0000000000 --- a/external/spidermonkey/include/mac/json.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef json_h___ -#define json_h___ - -#include "jsprvtd.h" -#include "jspubtd.h" -#include "jsapi.h" - -#include "js/Vector.h" - -#define JSON_MAX_DEPTH 2048 -#define JSON_PARSER_BUFSIZE 1024 - -extern JSObject * -js_InitJSONClass(JSContext *cx, js::HandleObject obj); - -extern JSBool -js_Stringify(JSContext *cx, js::MutableHandleValue vp, - JSObject *replacer, js::Value space, - js::StringBuffer &sb); - -// Avoid build errors on certain platforms that define these names as constants -#undef STRICT -#undef LEGACY - -/* - * The type of JSON decoding to perform. Strict decoding is to-the-spec; - * legacy decoding accepts a few non-JSON syntaxes historically accepted by the - * implementation. (Full description of these deviations is deliberately - * omitted.) New users should use strict decoding rather than legacy decoding, - * as legacy decoding might be removed at a future time. - */ -enum DecodingMode { STRICT, LEGACY }; - -namespace js { - -extern JS_FRIEND_API(JSBool) -ParseJSONWithReviver(JSContext *cx, JS::StableCharPtr chars, size_t length, HandleValue filter, - MutableHandleValue vp, DecodingMode decodingMode = STRICT); - -} /* namespace js */ - -#endif /* json_h___ */ diff --git a/external/spidermonkey/include/mac/jsperf.h b/external/spidermonkey/include/mac/jsperf.h index a0287b4a57..468ce8609c 100644 --- a/external/spidermonkey/include/mac/jsperf.h +++ b/external/spidermonkey/include/mac/jsperf.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsperf_h___ -#define jsperf_h___ +#ifndef perf_jsperf_h +#define perf_jsperf_h #include "jsapi.h" @@ -127,4 +127,4 @@ extern JS_FRIEND_API(PerfMeasurement*) } // namespace JS -#endif // jsperf_h___ +#endif /* perf_jsperf_h */ diff --git a/external/spidermonkey/include/mac/jsprf.h b/external/spidermonkey/include/mac/jsprf.h index c0891f0e9e..ce159d8115 100644 --- a/external/spidermonkey/include/mac/jsprf.h +++ b/external/spidermonkey/include/mac/jsprf.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprf_h___ -#define jsprf_h___ +#ifndef jsprf_h +#define jsprf_h /* ** API for PR printf like routines. Supports the following formats @@ -24,9 +24,11 @@ ** %f - float ** %g - float */ -#include "jstypes.h" -#include + #include +#include + +#include "jstypes.h" /* ** sprintf into a fixed size buffer. Guarantees that a NUL is at the end @@ -75,4 +77,4 @@ extern JS_PUBLIC_API(char*) JS_vsmprintf(const char *fmt, va_list ap); extern JS_PUBLIC_API(char*) JS_vsprintf_append(char *last, const char *fmt, va_list ap); extern JS_PUBLIC_API(uint32_t) JS_vsxprintf(JSStuffFunc f, void *arg, const char *fmt, va_list ap); -#endif /* jsprf_h___ */ +#endif /* jsprf_h */ diff --git a/external/spidermonkey/include/mac/jsprototypes.h b/external/spidermonkey/include/mac/jsprototypes.h index 007d25d720..f9bacac409 100644 --- a/external/spidermonkey/include/mac/jsprototypes.h +++ b/external/spidermonkey/include/mac/jsprototypes.h @@ -6,8 +6,8 @@ /* A higher-order macro for enumerating all JSProtoKey values. */ -#ifndef jsprototypes_h___ -#define jsprototypes_h___ +#ifndef jsprototypes_h +#define jsprototypes_h #include "jsversion.h" @@ -56,5 +56,20 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ + macro(Type, 38, js_InitBinaryDataClasses) \ + macro(Data, 39, js_InitBinaryDataClasses) \ + macro(uint8, 40, js_InitBinaryDataClasses) \ + macro(uint16, 41, js_InitBinaryDataClasses) \ + macro(uint32, 42, js_InitBinaryDataClasses) \ + macro(uint64, 43, js_InitBinaryDataClasses) \ + macro(int8, 44, js_InitBinaryDataClasses) \ + macro(int16, 45, js_InitBinaryDataClasses) \ + macro(int32, 46, js_InitBinaryDataClasses) \ + macro(int64, 47, js_InitBinaryDataClasses) \ + macro(float32, 48, js_InitBinaryDataClasses) \ + macro(float64, 49, js_InitBinaryDataClasses) \ + macro(ArrayType, 50, js_InitBinaryDataClasses) \ + macro(StructType, 51, js_InitBinaryDataClasses) \ + macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ -#endif /* jsprototypes_h___ */ +#endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/mac/jsproxy.h b/external/spidermonkey/include/mac/jsproxy.h index 399490eddc..56868a05c3 100644 --- a/external/spidermonkey/include/mac/jsproxy.h +++ b/external/spidermonkey/include/mac/jsproxy.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsproxy_h___ -#define jsproxy_h___ +#ifndef jsproxy_h +#define jsproxy_h #include "jsapi.h" #include "jsfriendapi.h" @@ -129,7 +129,7 @@ class JS_FRIEND_API(BaseProxyHandler) MutableHandleValue vp); /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) = 0; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) = 0; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -190,7 +190,7 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -242,7 +242,7 @@ class Proxy static bool iterate(JSContext *cx, HandleObject proxy, unsigned flags, MutableHandleValue vp); /* Spidermonkey extensions. */ - static bool isExtensible(JSObject *proxy); + static bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible); static bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -259,12 +259,17 @@ class Proxy inline bool IsObjectProxyClass(const Class *clasp) { - return clasp == &js::ObjectProxyClass || clasp == &js::OuterWindowProxyClass; + return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; } inline bool IsFunctionProxyClass(const Class *clasp) { - return clasp == &js::FunctionProxyClass; + return clasp == js::FunctionProxyClassPtr; +} + +inline bool IsProxyClass(const Class *clasp) +{ + return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); } inline bool IsObjectProxy(JSObject *obj) @@ -279,36 +284,33 @@ inline bool IsFunctionProxy(JSObject *obj) inline bool IsProxy(JSObject *obj) { - Class *clasp = GetObjectClass(obj); - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); + return IsProxyClass(GetObjectClass(obj)); } -/* Shared between object and function proxies. */ /* - * NOTE: JSSLOT_PROXY_PRIVATE is 0, because that way slot 0 is usable by API + * These are part of the API. + * + * NOTE: PROXY_PRIVATE_SLOT is 0 because that way slot 0 is usable by API * clients for both proxy and non-proxy objects. So an API client that only * needs to store one slot's worth of data doesn't need to branch on what sort * of object it has. */ -const uint32_t JSSLOT_PROXY_PRIVATE = 0; -const uint32_t JSSLOT_PROXY_HANDLER = 1; -const uint32_t JSSLOT_PROXY_EXTRA = 2; -/* Function proxies only. */ -const uint32_t JSSLOT_PROXY_CALL = 4; -const uint32_t JSSLOT_PROXY_CONSTRUCT = 5; +const uint32_t PROXY_PRIVATE_SLOT = 0; +const uint32_t PROXY_HANDLER_SLOT = 1; +const uint32_t PROXY_EXTRA_SLOT = 2; inline BaseProxyHandler * GetProxyHandler(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return (BaseProxyHandler *) GetReservedSlot(obj, JSSLOT_PROXY_HANDLER).toPrivate(); + return (BaseProxyHandler *) GetReservedSlot(obj, PROXY_HANDLER_SLOT).toPrivate(); } inline const Value & GetProxyPrivate(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_PRIVATE); + return GetReservedSlot(obj, PROXY_PRIVATE_SLOT); } inline JSObject * @@ -322,14 +324,14 @@ inline const Value & GetProxyExtra(JSObject *obj, size_t n) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n); + return GetReservedSlot(obj, PROXY_EXTRA_SLOT + n); } inline void SetProxyHandler(JSObject *obj, BaseProxyHandler *handler) { JS_ASSERT(IsProxy(obj)); - SetReservedSlot(obj, JSSLOT_PROXY_HANDLER, PrivateValue(handler)); + SetReservedSlot(obj, PROXY_HANDLER_SLOT, PrivateValue(handler)); } inline void @@ -337,7 +339,7 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) { JS_ASSERT(IsProxy(obj)); JS_ASSERT(n <= 1); - SetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n, extra); + SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } enum ProxyCallable { @@ -346,7 +348,7 @@ enum ProxyCallable { }; JS_FRIEND_API(JSObject *) -NewProxyObject(JSContext *cx, BaseProxyHandler *handler, const Value &priv, +NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); JSObject * @@ -426,6 +428,6 @@ class JS_FRIEND_API(AutoWaivePolicy) { } /* namespace js */ extern JS_FRIEND_API(JSObject *) -js_InitProxyClass(JSContext *cx, JSHandleObject obj); +js_InitProxyClass(JSContext *cx, JS::HandleObject obj); -#endif +#endif /* jsproxy_h */ diff --git a/external/spidermonkey/include/mac/jsprvtd.h b/external/spidermonkey/include/mac/jsprvtd.h index 4db5ed8c36..1fbc086a7c 100644 --- a/external/spidermonkey/include/mac/jsprvtd.h +++ b/external/spidermonkey/include/mac/jsprvtd.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprvtd_h___ -#define jsprvtd_h___ +#ifndef jsprvtd_h +#define jsprvtd_h /* * JS private typename definitions. * @@ -56,13 +56,7 @@ typedef struct JSStackHeader JSStackHeader; typedef struct JSSubString JSSubString; typedef struct JSSpecializedNative JSSpecializedNative; -/* - * Template declarations. - * - * jsprvtd.h can be included in both C and C++ translation units. For C++, it - * may possibly be wrapped in an extern "C" block which does not agree with - * templates. - */ +/* String typedefs. */ class JSDependentString; class JSExtensibleString; class JSExternalString; @@ -76,6 +70,7 @@ namespace js { struct ArgumentsData; struct Class; +class AutoNameVector; class RegExpGuard; class RegExpObject; class RegExpObjectBuilder; @@ -83,6 +78,7 @@ class RegExpShared; class RegExpStatics; class MatchPairs; class PropertyName; +class LazyScript; enum RegExpFlag { @@ -95,19 +91,14 @@ enum RegExpFlag AllFlags = 0x0f }; -class ExecuteArgsGuard; -class InvokeFrameGuard; -class InvokeArgsGuard; class StringBuffer; class FrameRegs; class StackFrame; -class StackSegment; -class StackSpace; -class ContextStack; class ScriptFrameIter; class Proxy; +class JS_FRIEND_API(AutoEnterPolicy); class JS_FRIEND_API(BaseProxyHandler); class JS_FRIEND_API(Wrapper); class JS_FRIEND_API(CrossCompartmentWrapper); @@ -140,24 +131,29 @@ class WatchpointMap; typedef JSObject Env; typedef JSNative Native; +typedef JSParallelNative ParallelNative; +typedef JSThreadSafeNative ThreadSafeNative; typedef JSPropertyOp PropertyOp; typedef JSStrictPropertyOp StrictPropertyOp; typedef JSPropertyDescriptor PropertyDescriptor; +struct SourceCompressionToken; + namespace frontend { struct BytecodeEmitter; struct Definition; +class FullParseHandler; class FunctionBox; class ObjectBox; struct Token; struct TokenPos; class TokenStream; class ParseMapPool; -struct ParseNode; +class ParseNode; template -struct Parser; +class Parser; } /* namespace frontend */ @@ -284,18 +280,18 @@ typedef void * if an error or exception was thrown on cx. */ typedef JSObject * -(* JSObjectOp)(JSContext *cx, JSHandleObject obj); +(* JSObjectOp)(JSContext *cx, JS::Handle obj); /* Signature for class initialization ops. */ typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JSHandleObject obj); +(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); /* * Hook that creates an iterator object for a given object. Returns the * iterator object or null if an error or exception was thrown on cx. */ typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JSHandleObject obj, JSBool keysonly); +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); -#endif /* jsprvtd_h___ */ +#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/mac/jspubtd.h b/external/spidermonkey/include/mac/jspubtd.h index 6b7e63e6ba..96f5dd8297 100644 --- a/external/spidermonkey/include/mac/jspubtd.h +++ b/external/spidermonkey/include/mac/jspubtd.h @@ -4,16 +4,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jspubtd_h___ -#define jspubtd_h___ +#ifndef jspubtd_h +#define jspubtd_h /* * JS public API typedefs. */ +#include "mozilla/PodOperations.h" + #include "jsprototypes.h" #include "jstypes.h" +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) +# define JSGC_TRACK_EXACT_ROOTS +#endif + namespace JS { /* @@ -25,6 +31,8 @@ class Value; template class Rooted; +class JS_PUBLIC_API(AutoGCRooter); + struct Zone; } /* namespace JS */ @@ -44,10 +52,8 @@ struct Zone; * oblivious to the change. This feature can be explicitly disabled in debug * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. */ - // Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES - +#define JS_NO_JSVAL_JSID_STRUCT_TYPES # if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) # define JS_USE_JSID_STRUCT_TYPES # endif @@ -154,9 +160,10 @@ typedef enum { JSTRACE_SCRIPT, /* - * Trace kinds internal to the engine. The embedding can only them if it - * implements JSTraceCallback. + * Trace kinds internal to the engine. The embedding can only see them if + * it implements JSTraceCallback. */ + JSTRACE_LAZY_SCRIPT, JSTRACE_IONCODE, JSTRACE_SHAPE, JSTRACE_BASE_SHAPE, @@ -229,6 +236,18 @@ struct Runtime namespace js { +/* + * Parallel operations in general can have one of three states. They may + * succeed, fail, or "bail", where bail indicates that the code encountered an + * unexpected condition and should be re-run sequentially. Different + * subcategories of the "bail" state are encoded as variants of TP_RETRY_*. + */ +enum ParallelResult { TP_SUCCESS, TP_RETRY_SEQUENTIALLY, TP_RETRY_AFTER_GC, TP_FATAL }; + +struct ThreadSafeContext; +struct ForkJoinSlice; +class ExclusiveContext; + class Allocator; class SkipRoot; @@ -273,18 +292,28 @@ template <> struct RootKind : SpecificRootKind struct RootKind : SpecificRootKind {}; template <> struct RootKind : SpecificRootKind {}; -struct ContextFriendFields { - JSRuntime *const runtime; +struct ContextFriendFields +{ + protected: + JSRuntime *const runtime_; /* The current compartment. */ - JSCompartment *compartment; + JSCompartment *compartment_; /* The current zone. */ JS::Zone *zone_; + public: explicit ContextFriendFields(JSRuntime *rt) - : runtime(rt), compartment(NULL), zone_(NULL) - { } + : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + { +#ifdef JSGC_TRACK_EXACT_ROOTS + mozilla::PodArrayZero(thingGCRooters); +#endif +#if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) + skipGCRooters = NULL; +#endif + } static const ContextFriendFields *get(const JSContext *cx) { return reinterpret_cast(cx); @@ -294,7 +323,7 @@ struct ContextFriendFields { return reinterpret_cast(cx); } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -313,6 +342,13 @@ struct ContextFriendFields { */ SkipRoot *skipGCRooters; #endif + + /* Stack of thread-stack-allocated GC roots. */ + JS::AutoGCRooter *autoGCRooters; + + friend JSRuntime *GetRuntime(const JSContext *cx); + friend JSCompartment *GetContextCompartment(const JSContext *cx); + friend JS::Zone *GetContextZone(const JSContext *cx); }; class PerThreadData; @@ -338,7 +374,7 @@ struct PerThreadDataFriendFields PerThreadDataFriendFields(); -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -384,4 +420,4 @@ struct PerThreadDataFriendFields } /* namespace js */ -#endif /* jspubtd_h___ */ +#endif /* jspubtd_h */ diff --git a/external/spidermonkey/include/mac/jstypes.h b/external/spidermonkey/include/mac/jstypes.h index e4c02f8d8d..17f67f70e1 100644 --- a/external/spidermonkey/include/mac/jstypes.h +++ b/external/spidermonkey/include/mac/jstypes.h @@ -18,8 +18,8 @@ ** for all C files. **/ -#ifndef jstypes_h___ -#define jstypes_h___ +#ifndef jstypes_h +#define jstypes_h #include "mozilla/Attributes.h" #include "mozilla/Util.h" @@ -279,4 +279,4 @@ typedef int JSBool; # define JS_EXTENSION_(s) s #endif -#endif /* jstypes_h___ */ +#endif /* jstypes_h */ diff --git a/external/spidermonkey/include/mac/jsutil.h b/external/spidermonkey/include/mac/jsutil.h index 49e1641c61..4020822be1 100644 --- a/external/spidermonkey/include/mac/jsutil.h +++ b/external/spidermonkey/include/mac/jsutil.h @@ -8,19 +8,19 @@ * PR assertion checker. */ -#ifndef jsutil_h___ -#define jsutil_h___ +#ifndef jsutil_h +#define jsutil_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/GuardObjects.h" -#include "js/Utility.h" - #ifdef USE_ZLIB -#include "zlib.h" +#include #endif +#include "js/Utility.h" + /* Forward declarations. */ struct JSContext; @@ -204,15 +204,6 @@ UnsignedPtrDiff(const void *bigger, const void *smaller) return size_t(bigger) - size_t(smaller); } -/* - * Ordinarily, a function taking a JSContext* 'cx' parameter reports errors on - * the context. In some cases, functions optionally report and indicate this by - * taking a nullable 'maybecx' parameter. In some cases, though, a function - * always needs a 'cx', but optionally reports. This option is presented by the - * MaybeReportError. - */ -enum MaybeReportError { REPORT_ERROR = true, DONT_REPORT_ERROR = false }; - /*****************************************************************************/ /* A bit array is an array of bits represented by an array of words (size_t). */ @@ -391,4 +382,4 @@ typedef size_t jsbitmap; JS_END_MACRO #endif -#endif /* jsutil_h___ */ +#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/mac/jsversion.h b/external/spidermonkey/include/mac/jsversion.h index f3169fb5d1..1780616a32 100644 --- a/external/spidermonkey/include/mac/jsversion.h +++ b/external/spidermonkey/include/mac/jsversion.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsversion_h___ -#define jsversion_h___ +#ifndef jsversion_h +#define jsversion_h /* * Deprecated JS_VERSION handler. @@ -61,7 +61,7 @@ # define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else # define NEW_OBJECT_REPRESENTATION_ONLY() \ - MOZ_NOT_REACHED("don't call this! to be used in the new object representation") + MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif -#endif /* jsversion_h___ */ +#endif /* jsversion_h */ diff --git a/external/spidermonkey/include/mac/jswrapper.h b/external/spidermonkey/include/mac/jswrapper.h index d0c0fc625c..f78df7db60 100644 --- a/external/spidermonkey/include/mac/jswrapper.h +++ b/external/spidermonkey/include/mac/jswrapper.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jswrapper_h___ -#define jswrapper_h___ +#ifndef jswrapper_h +#define jswrapper_h #include "mozilla/Attributes.h" @@ -66,8 +66,6 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler static Wrapper singleton; static Wrapper singletonWithPrototype; - - static void *getWrapperFamily(); }; /* Base class for all cross compartment wrapper handlers. */ @@ -105,7 +103,7 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -139,7 +137,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base public: SecurityWrapper(unsigned flags); - virtual bool isExtensible(JSObject *wrapper) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool enter(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool *bp) MOZ_OVERRIDE; @@ -185,7 +183,7 @@ class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler virtual bool enumerate(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -297,4 +295,4 @@ struct JS_FRIEND_API(AutoMaybeTouchDeadZones) } /* namespace js */ -#endif +#endif /* jswrapper_h */ diff --git a/external/spidermonkey/include/mac/mozilla/AllocPolicy.h b/external/spidermonkey/include/mac/mozilla/AllocPolicy.h new file mode 100644 index 0000000000..20087e93bb --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/AllocPolicy.h @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * An allocation policy concept, usable for structures and algorithms to + * control how memory is allocated and how failures are handled. + */ + +#ifndef mozilla_AllocPolicy_h +#define mozilla_AllocPolicy_h + +#include +#include + +namespace mozilla { + +/* + * Allocation policies are used to implement the standard allocation behaviors + * in a customizable way. Additionally, custom behaviors may be added to these + * behaviors, such as additionally reporting an error through an out-of-band + * mechanism when OOM occurs. The concept modeled here is as follows: + * + * - public copy constructor, assignment, destructor + * - void* malloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* calloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* realloc_(void*, size_t, size_t) + * Responsible for OOM reporting when null is returned. The *used* bytes + * of the previous buffer is passed in (rather than the old allocation + * size), in addition to the *new* allocation size requested. + * - void free_(void*) + * - void reportAllocOverflow() const + * Called on allocation overflow (that is, an allocation implicitly tried + * to allocate more than the available memory space -- think allocating an + * array of large-size objects, where N * size overflows) before null is + * returned. + * + * mfbt provides (and typically uses by default) only MallocAllocPolicy, which + * does nothing more than delegate to the malloc/alloc/free functions. + */ + +/* + * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no + * extra behaviors. + */ +class MallocAllocPolicy +{ + public: + void* malloc_(size_t bytes) { return malloc(bytes); } + void* calloc_(size_t bytes) { return calloc(bytes, 1); } + void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } + void free_(void* p) { free(p); } + void reportAllocOverflow() const {} +}; + + +} // namespace mozilla + +#endif /* mozilla_AllocPolicy_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Array.h b/external/spidermonkey/include/mac/mozilla/Array.h new file mode 100644 index 0000000000..5af9aaa133 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Array.h @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A compile-time constant-length array with bounds-checking assertions. */ + +#ifndef mozilla_Array_h +#define mozilla_Array_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" + +#include + +namespace mozilla { + +template +class Array +{ + T arr[Length]; + + public: + T& operator[](size_t i) { + MOZ_ASSERT(i < Length); + return arr[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(i < Length); + return arr[i]; + } +}; + +template +class Array +{ + public: + T& operator[](size_t i) { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } + + const T& operator[](size_t i) const { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Array_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Assertions.h b/external/spidermonkey/include/mac/mozilla/Assertions.h index 5ead7f493e..00b7037802 100644 --- a/external/spidermonkey/include/mac/mozilla/Assertions.h +++ b/external/spidermonkey/include/mac/mozilla/Assertions.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of runtime and static assertion macros for C and C++. */ -#ifndef mozilla_Assertions_h_ -#define mozilla_Assertions_h_ +#ifndef mozilla_Assertions_h +#define mozilla_Assertions_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" @@ -39,44 +40,24 @@ #endif /* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This - * can be useful when you make certain assumptions about what must hold for + * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. + * In C++11, static_assert is provided by the compiler to the same effect. + * This can be useful when you make certain assumptions about what must hold for * optimal, or even correct, behavior. For example, you might assert that the * size of a struct is a multiple of the target architecture's word size: * * struct S { ... }; + * // C * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, * "S should be a multiple of word size for efficiency"); + * // C++11 + * static_assert(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); * * This macro can be used in any location where both an extern declaration and a * typedef could be used. - * - * Be aware of the gcc 4.2 concerns noted further down when writing patches that - * use this macro, particularly if a patch only bounces on OS X. */ -#ifdef __cplusplus -# if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__HP_aCC) -# if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# endif -#endif -#ifndef MOZ_STATIC_ASSERT +#ifndef __cplusplus /* * Some of the definitions below create an otherwise-unused typedef. This * triggers compiler warnings with some versions of gcc, so mark the typedefs @@ -124,78 +105,23 @@ # define MOZ_STATIC_ASSERT(cond, reason) \ extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE # endif -#endif #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) +#else +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) +#endif #ifdef __cplusplus extern "C" { #endif -/* - * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible - * way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. We use TerminateProcess - * with the exit code aborting would generate because we don't want to invoke - * atexit handlers, destructors, library unload handlers, and so on when our - * process might be in a compromised state. We don't use abort() because - * it'd cause Windows to annoyingly pop up the process error dialog multiple - * times. See bug 345118 and bug 426163. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - TerminateProcess(GetCurrentProcess(), 3); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - ::abort(); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - abort(); \ - } while (0) -# endif -#endif - /* * Prints |s| as an assertion failure (using file and ln as the location of the * assertion) to the standard debug-output channel. * - * Usually you should use MOZ_ASSERT instead of this method. This method is - * primarily for internal use in this header, and only secondarily for use in - * implementing release-build assertions. + * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This + * method is primarily for internal use in this header, and only secondarily + * for use in implementing release-build assertions. */ static MOZ_ALWAYS_INLINE void MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) @@ -209,6 +135,112 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif } +static MOZ_ALWAYS_INLINE void +MOZ_ReportCrash(const char* s, const char* file, int ln) +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", + "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); +#else + fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); + fflush(stderr); +#endif +} + +/** + * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should + * call MOZ_CRASH instead. + */ +#if defined(_MSC_VER) + /* + * On MSVC use the __debugbreak compiler intrinsic, which produces an inline + * (not nested in a system function) breakpoint. This distinctively invokes + * Breakpad without requiring system library symbols on all stack-processing + * machines, as a nested breakpoint would require. + * + * We use TerminateProcess with the exit code aborting would generate + * because we don't want to invoke atexit handlers, destructors, library + * unload handlers, and so on when our process might be in a compromised + * state. + * + * We don't use abort() because it'd cause Windows to annoyingly pop up the + * process error dialog multiple times. See bug 345118 and bug 426163. + * + * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the + * compiler doesn't hassle us to provide a return statement after a + * MOZ_REALLY_CRASH() call. + * + * (Technically these are Windows requirements, not MSVC requirements. But + * practically you need MSVC for debugging, and we only ship builds created + * by MSVC, so doing it this way reduces complexity.) + */ + +__declspec(noreturn) __inline void MOZ_NoReturn() {} + +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + ::TerminateProcess(::GetCurrentProcess(), 3); \ + ::MOZ_NoReturn(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + TerminateProcess(GetCurrentProcess(), 3); \ + MOZ_NoReturn(); \ + } while (0) +# endif +#else +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + ::abort(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + abort(); \ + } while (0) +# endif +#endif + +/* + * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a + * Breakpad-compatible way, in both debug and release builds. + * + * MOZ_CRASH is a good solution for "handling" failure cases when you're + * unwilling or unable to handle them more cleanly -- for OOM, for likely memory + * corruption, and so on. It's also a good solution if you need safe behavior + * in release builds as well as debug builds. But if the failure is one that + * should be debugged and fixed, MOZ_ASSERT is generally preferable. + * + * The optional explanation-string, if provided, must be a string literal + * explaining why we're crashing. This argument is intended for use with + * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's + * obvious why we're crashing. + * + * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an + * explanation-string, we print the string to stderr. Otherwise, we don't + * print anything; this is because we want MOZ_CRASH to be 100% safe in release + * builds, and it's hard to print to stderr safely when memory might have been + * corrupted. + */ +#ifndef DEBUG +# define MOZ_CRASH(...) MOZ_REALLY_CRASH() +#else +# define MOZ_CRASH(...) \ + do { \ + MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } while(0) +#endif + #ifdef __cplusplus } /* extern "C" */ #endif @@ -251,7 +283,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* Now the two-argument form. */ @@ -259,7 +291,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* And now, helper macrology up the wazoo. */ @@ -310,14 +342,14 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif /* - * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is + * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is * undefined behavior for execution to reach this point. No guarantees are made * about what will happen if this is reached at runtime. Most code should - * probably use the higher level MOZ_NOT_REACHED, which uses this when + * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when * appropriate. */ #if defined(__clang__) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() #elif defined(__GNUC__) /* * __builtin_unreachable() was implemented in gcc 4.5. If we don't have @@ -325,49 +357,71 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) * in C++ in case there's another abort() visible in local scope. */ # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() # else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif # endif #elif defined(_MSC_VER) -# define MOZ_NOT_REACHED_MARKER() __assume(0) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) #else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif #endif /* - * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached - * during execution: simply reaching that point in execution is a bug. It takes - * as an argument an error message indicating the reason why that point should - * not have been reachable. + * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that + * the macro call cannot be reached during execution. This lets the compiler + * generate better-optimized code under some circumstances, at the expense of + * the program's behavior being undefined if control reaches the + * MOZ_ASSUME_UNREACHABLE. * - * // ...in a language parser... - * void handle(BooleanLiteralNode node) + * In Gecko, you probably should not use this macro outside of performance- or + * size-critical code, because it's unsafe. If you don't care about code size + * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. + * + * SpiderMonkey is a different beast, and there it's acceptable to use + * MOZ_ASSUME_UNREACHABLE more widely. + * + * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a + * value following a MOZ_ASSUME_UNREACHABLE call. + * + * Example usage: + * + * enum ValueType { + * VALUE_STRING, + * VALUE_INT, + * VALUE_FLOAT + * }; + * + * int ptrToInt(ValueType type, void* value) { * { - * if (node.isTrue()) - * handleTrueLiteral(); - * else if (node.isFalse()) - * handleFalseLiteral(); - * else - * MOZ_NOT_REACHED("boolean literal that's not true or false?"); + * // We know for sure that type is either INT or FLOAT, and we want this + * // code to run as quickly as possible. + * switch (type) { + * case VALUE_INT: + * return *(int*) value; + * case VALUE_FLOAT: + * return (int) *(float*) value; + * default: + * MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT"); + * } * } */ #if defined(DEBUG) -# define MOZ_NOT_REACHED(reason) \ +# define MOZ_ASSUME_UNREACHABLE(...) \ do { \ - MOZ_ASSERT(false, reason); \ - MOZ_NOT_REACHED_MARKER(); \ + MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \ + MOZ_ASSUME_UNREACHABLE_MARKER(); \ } while (0) #else -# define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER() +# define MOZ_ASSUME_UNREACHABLE(reason) MOZ_ASSUME_UNREACHABLE_MARKER() #endif /* @@ -384,4 +438,4 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) # define MOZ_ALWAYS_FALSE(expr) ((void)(expr)) #endif -#endif /* mozilla_Assertions_h_ */ +#endif /* mozilla_Assertions_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Atomics.h b/external/spidermonkey/include/mac/mozilla/Atomics.h new file mode 100644 index 0000000000..f876683c3e --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Atomics.h @@ -0,0 +1,1014 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Implements (almost always) lock-free atomic operations. The operations here + * are a subset of that which can be found in C++11's header, with a + * different API to enforce consistent memory ordering constraints. + * + * Anyone caught using |volatile| for inter-thread memory safety needs to be + * sent a copy of this header and the C++11 standard. + */ + +#ifndef mozilla_Atomics_h +#define mozilla_Atomics_h + +#include "mozilla/Assertions.h" +#include "mozilla/TypeTraits.h" + +#include + +/* + * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK + * does not have . So be sure to check for support + * along with C++0x support. + */ +#if defined(__clang__) + /* + * clang doesn't like libstdc++'s version of before GCC 4.7, + * due to the loose typing of the __sync_* family of functions done by + * GCC. We do not have a particularly good way to detect this sort of + * case at this point, so just assume that if we're on a Linux system, + * we can't use the system's . + * + * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + */ +# if !defined(__linux__) && !defined(__OpenBSD__) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ + __has_include() +# define MOZ_HAVE_CXX11_ATOMICS +# endif +/* + * Android uses a different C++ standard library that does not provide + * support for . + * + * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include + * inline definitions for the functions declared therein. This oversight + * leads to linking errors when using atomic enums. We therefore require + * GCC 4.7 or higher. + */ +#elif defined(__GNUC__) && !defined(__ANDROID__) +# include "mozilla/Compiler.h" +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ + MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# define MOZ_HAVE_CXX11_ATOMICS +# endif +#elif defined(_MSC_VER) && _MSC_VER >= 1700 +# define MOZ_HAVE_CXX11_ATOMICS +#endif + +namespace mozilla { + +/** + * An enum of memory ordering possibilities for atomics. + * + * Memory ordering is the observable state of distinct values in memory. + * (It's a separate concept from atomicity, which concerns whether an + * operation can ever be observed in an intermediate state. Don't + * conflate the two!) Given a sequence of operations in source code on + * memory, it is *not* always the case that, at all times and on all + * cores, those operations will appear to have occurred in that exact + * sequence. First, the compiler might reorder that sequence, if it + * thinks another ordering will be more efficient. Second, the CPU may + * not expose so consistent a view of memory. CPUs will often perform + * their own instruction reordering, above and beyond that performed by + * the compiler. And each core has its own memory caches, and accesses + * (reads and writes both) to "memory" may only resolve to out-of-date + * cache entries -- not to the "most recently" performed operation in + * some global sense. Any access to a value that may be used by + * multiple threads, potentially across multiple cores, must therefore + * have a memory ordering imposed on it, for all code on all + * threads/cores to have a sufficiently coherent worldview. + * + * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and + * http://en.cppreference.com/w/cpp/atomic/memory_order go into more + * detail on all this, including examples of how each mode works. + * + * Note that for simplicity and practicality, not all of the modes in + * C++11 are supported. The missing C++11 modes are either subsumed by + * the modes we provide below, or not relevant for the CPUs we support + * in Gecko. These three modes are confusing enough as it is! + */ +enum MemoryOrdering { + /* + * Relaxed ordering is the simplest memory ordering: none at all. + * When the result of a write is observed, nothing may be inferred + * about other memory. Writes ostensibly performed "before" on the + * writing thread may not yet be visible. Writes performed "after" on + * the writing thread may already be visible, if the compiler or CPU + * reordered them. (The latter can happen if reads and/or writes get + * held up in per-processor caches.) Relaxed ordering means + * operations can always use cached values (as long as the actual + * updates to atomic values actually occur, correctly, eventually), so + * it's usually the fastest sort of atomic access. For this reason, + * *it's also the most dangerous kind of access*. + * + * Relaxed ordering is good for things like process-wide statistics + * counters that don't need to be consistent with anything else, so + * long as updates themselves are atomic. (And so long as any + * observations of that value can tolerate being out-of-date -- if you + * need some sort of up-to-date value, you need some sort of other + * synchronizing operation.) It's *not* good for locks, mutexes, + * reference counts, etc. that mediate access to other memory, or must + * be observably consistent with other memory. + * + * x86 architectures don't take advantage of the optimization + * opportunities that relaxed ordering permits. Thus it's possible + * that using relaxed ordering will "work" on x86 but fail elsewhere + * (ARM, say, which *does* implement non-sequentially-consistent + * relaxed ordering semantics). Be extra-careful using relaxed + * ordering if you can't easily test non-x86 architectures! + */ + Relaxed, + /* + * When an atomic value is updated with ReleaseAcquire ordering, and + * that new value is observed with ReleaseAcquire ordering, prior + * writes (atomic or not) are also observable. What ReleaseAcquire + * *doesn't* give you is any observable ordering guarantees for + * ReleaseAcquire-ordered operations on different objects. For + * example, if there are two cores that each perform ReleaseAcquire + * operations on separate objects, each core may or may not observe + * the operations made by the other core. The only way the cores can + * be synchronized with ReleaseAcquire is if they both + * ReleaseAcquire-access the same object. This implies that you can't + * necessarily describe some global total ordering of ReleaseAcquire + * operations. + * + * ReleaseAcquire ordering is good for (as the name implies) atomic + * operations on values controlling ownership of things: reference + * counts, mutexes, and the like. However, if you are thinking about + * using these to implement your own locks or mutexes, you should take + * a good, hard look at actual lock or mutex primitives first. + */ + ReleaseAcquire, + /* + * When an atomic value is updated with SequentiallyConsistent + * ordering, all writes observable when the update is observed, just + * as with ReleaseAcquire ordering. But, furthermore, a global total + * ordering of SequentiallyConsistent operations *can* be described. + * For example, if two cores perform SequentiallyConsistent operations + * on separate objects, one core will observably perform its update + * (and all previous operations will have completed), then the other + * core will observably perform its update (and all previous + * operations will have completed). (Although those previous + * operations aren't themselves ordered -- they could be intermixed, + * or ordered if they occur on atomic values with ordering + * requirements.) SequentiallyConsistent is the *simplest and safest* + * ordering of atomic operations -- it's always as if one operation + * happens, then another, then another, in some order -- and every + * core observes updates to happen in that single order. Because it + * has the most synchronization requirements, operations ordered this + * way also tend to be slowest. + * + * SequentiallyConsistent ordering can be desirable when multiple + * threads observe objects, and they all have to agree on the + * observable order of changes to them. People expect + * SequentiallyConsistent ordering, even if they shouldn't, when + * writing code, atomic or otherwise. SequentiallyConsistent is also + * the ordering of choice when designing lockless data structures. If + * you don't know what order to use, use this one. + */ + SequentiallyConsistent, +}; + +} // namespace mozilla + +// Build up the underlying intrinsics. +#ifdef MOZ_HAVE_CXX11_ATOMICS + +# include + +namespace mozilla { +namespace detail { + +/* + * We provide CompareExchangeFailureOrder to work around a bug in some + * versions of GCC's header. See bug 898491. + */ +template struct AtomicOrderConstraints; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; + static const std::memory_order LoadOrder = std::memory_order_relaxed; + static const std::memory_order StoreOrder = std::memory_order_relaxed; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_relaxed; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; + static const std::memory_order LoadOrder = std::memory_order_acquire; + static const std::memory_order StoreOrder = std::memory_order_release; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_acquire; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; + static const std::memory_order LoadOrder = std::memory_order_seq_cst; + static const std::memory_order StoreOrder = std::memory_order_seq_cst; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_seq_cst; +}; + +template +struct IntrinsicBase +{ + typedef std::atomic ValueType; + typedef AtomicOrderConstraints OrderedOp; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T load(const typename Base::ValueType& ptr) { + return ptr.load(Base::OrderedOp::LoadOrder); + } + static void store(typename Base::ValueType& ptr, T val) { + ptr.store(val, Base::OrderedOp::StoreOrder); + } + static T exchange(typename Base::ValueType& ptr, T val) { + return ptr.exchange(val, Base::OrderedOp::AtomicRMWOrder); + } + static bool compareExchange(typename Base::ValueType& ptr, T oldVal, T newVal) { + return ptr.compare_exchange_strong(oldVal, newVal, + Base::OrderedOp::AtomicRMWOrder, + Base::OrderedOp::CompareExchangeFailureOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T add(typename Base::ValueType& ptr, T val) { + return ptr.fetch_add(val, Base::OrderedOp::AtomicRMWOrder); + } + static T sub(typename Base::ValueType& ptr, T val) { + return ptr.fetch_sub(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T* add(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_add(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + static T* sub(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_sub(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + private: + /* + * GCC 4.6's header has a bug where adding X to an + * atomic is not the same as adding X to a T*. Hence the need + * for this function to provide the correct addend. + */ + static ptrdiff_t fixupAddend(ptrdiff_t val) { +#if defined(__clang__) || defined(_MSC_VER) + return val; +#elif defined(__GNUC__) && MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) && \ + !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) + return val * sizeof(T); +#else + return val; +#endif + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + typedef IntrinsicBase Base; + static T inc(typename Base::ValueType& ptr) { + return IntrinsicAddSub::add(ptr, 1); + } + static T dec(typename Base::ValueType& ptr) { + return IntrinsicAddSub::sub(ptr, 1); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + typedef IntrinsicBase Base; + static T or_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_or(val, Base::OrderedOp::AtomicRMWOrder); + } + static T xor_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_xor(val, Base::OrderedOp::AtomicRMWOrder); + } + static T and_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_and(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct AtomicIntrinsics + : public IntrinsicMemoryOps, public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(__GNUC__) + +namespace mozilla { +namespace detail { + +/* + * The __sync_* family of intrinsics is documented here: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html + * + * While these intrinsics are deprecated in favor of the newer __atomic_* + * family of intrincs: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html + * + * any GCC version that supports the __atomic_* intrinsics will also support + * the header and so will be handled above. We provide a version of + * atomics using the __sync_* intrinsics to support older versions of GCC. + * + * All __sync_* intrinsics that we use below act as full memory barriers, for + * both compiler and hardware reordering, except for __sync_lock_test_and_set, + * which is a only an acquire barrier. When we call __sync_lock_test_and_set, + * we add a barrier above it as appropriate. + */ + +template struct Barrier; + +/* + * Some processors (in particular, x86) don't require quite so many calls to + * __sync_sychronize as our specializations of Barrier produce. If + * performance turns out to be an issue, defining these specializations + * on a per-processor basis would be a good first tuning step. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() { __sync_synchronize(); } + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() { __sync_synchronize(); } +}; + +template +struct IntrinsicMemoryOps +{ + static T load(const T& ptr) { + Barrier::beforeLoad(); + T val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(T& ptr, T val) { + Barrier::beforeStore(); + ptr = val; + Barrier::afterStore(); + } + static T exchange(T& ptr, T val) { + // __sync_lock_test_and_set is only an acquire barrier; loads and stores + // can't be moved up from after to before it, but they can be moved down + // from before to after it. We may want a stricter ordering, so we need + // an explicit barrier. + + Barrier::beforeStore(); + return __sync_lock_test_and_set(&ptr, val); + } + static bool compareExchange(T& ptr, T oldVal, T newVal) { + return __sync_bool_compare_and_swap(&ptr, oldVal, newVal); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T ValueType; + static T add(T& ptr, T val) { + return __sync_fetch_and_add(&ptr, val); + } + static T sub(T& ptr, T val) { + return __sync_fetch_and_sub(&ptr, val); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T* ValueType; + /* + * The reinterpret_casts are needed so that + * __sync_fetch_and_{add,sub} will properly type-check. + * + * Also, these functions do not provide standard semantics for + * pointer types, so we need to adjust the addend. + */ + static ValueType add(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_add(&ptr, amount); + } + static ValueType sub(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_sub(&ptr, amount); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static T inc(T& ptr) { return IntrinsicAddSub::add(ptr, 1); } + static T dec(T& ptr) { return IntrinsicAddSub::sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static T or_(T& ptr, T val) { + return __sync_fetch_and_or(&ptr, val); + } + static T xor_(T& ptr, T val) { + return __sync_fetch_and_xor(&ptr, val); + } + static T and_(T& ptr, T val) { + return __sync_fetch_and_and(&ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(_MSC_VER) + +/* + * Windows comes with a full complement of atomic operations. + * Unfortunately, most of those aren't available for Windows XP (even if + * the compiler supports intrinsics for them), which is the oldest + * version of Windows we support. Therefore, we only provide operations + * on 32-bit datatypes for 32-bit Windows versions; for 64-bit Windows + * versions, we support 64-bit datatypes as well. + * + * To avoid namespace pollution issues, we declare whatever functions we + * need ourselves. + */ + +extern "C" { +long __cdecl _InterlockedExchangeAdd(long volatile* dst, long value); +long __cdecl _InterlockedOr(long volatile* dst, long value); +long __cdecl _InterlockedXor(long volatile* dst, long value); +long __cdecl _InterlockedAnd(long volatile* dst, long value); +long __cdecl _InterlockedExchange(long volatile *dst, long value); +long __cdecl _InterlockedCompareExchange(long volatile *dst, long newVal, long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd) +# pragma intrinsic(_InterlockedOr) +# pragma intrinsic(_InterlockedXor) +# pragma intrinsic(_InterlockedAnd) +# pragma intrinsic(_InterlockedExchange) +# pragma intrinsic(_InterlockedCompareExchange) + +namespace mozilla { +namespace detail { + +# if !defined(_M_IX86) && !defined(_M_X64) + /* + * The implementations below are optimized for x86ish systems. You + * will have to modify them if you are porting to Windows on a + * different architecture. + */ +# error "Unknown CPU type" +# endif + +/* + * The PrimitiveIntrinsics template should define |Type|, the datatype of size + * DataSize upon which we operate, and the following eight functions. + * + * static Type add(Type* ptr, Type val); + * static Type sub(Type* ptr, Type val); + * static Type or_(Type* ptr, Type val); + * static Type xor_(Type* ptr, Type val); + * static Type and_(Type* ptr, Type val); + * + * These functions perform the obvious operation on the value contained in + * |*ptr| combined with |val| and return the value previously stored in + * |*ptr|. + * + * static void store(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and must provide a full + * memory fence after the store to prevent compiler and hardware instruction + * reordering. It should also act as a compiler barrier to prevent reads and + * writes from moving to after the store. + * + * static Type exchange(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and returns the previous + * contents of *ptr; + * + * static bool compareExchange(Type* ptr, Type oldVal, Type newVal); + * + * This function atomically performs the following operation: + * + * if (*ptr == oldVal) { + * *ptr = newVal; + * return true; + * } else { + * return false; + * } + * + */ +template struct PrimitiveIntrinsics; + +template<> +struct PrimitiveIntrinsics<4> +{ + typedef long Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * _InterlockedExchangeSubtract isn't available before Windows 7, + * and we must support Windows XP. + */ + return _InterlockedExchangeAdd(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange(ptr, newVal, oldVal) == oldVal; + } +}; + +# if defined(_M_X64) + +extern "C" { +long long __cdecl _InterlockedExchangeAdd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedOr64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedXor64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedAnd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedExchange64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedCompareExchange64(long long volatile* dst, + long long newVal, + long long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd64) +# pragma intrinsic(_InterlockedOr64) +# pragma intrinsic(_InterlockedXor64) +# pragma intrinsic(_InterlockedAnd64) +# pragma intrinsic(_InterlockedExchange64) +# pragma intrinsic(_InterlockedCompareExchange64) + +template <> +struct PrimitiveIntrinsics<8> +{ + typedef __int64 Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd64(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * There is no _InterlockedExchangeSubtract64. + */ + return _InterlockedExchangeAdd64(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr64(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor64(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd64(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange64(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange64(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange64(ptr, newVal, oldVal) == oldVal; + } +}; + +# endif + +extern "C" { void _ReadWriteBarrier(); } + +# pragma intrinsic(_ReadWriteBarrier) + +template struct Barrier; + +/* + * We do not provide an afterStore method in Barrier, as Relaxed and + * ReleaseAcquire orderings do not require one, and the required barrier + * for SequentiallyConsistent is handled by PrimitiveIntrinsics. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template<> +struct Barrier +{ + static void beforeLoad() { _ReadWriteBarrier(); } + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T val) { return static_cast(val); } + static T fromPrimType(PrimType val) { return static_cast(val); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T* val) { return reinterpret_cast(val); } + static T* fromPrimType(PrimType val) { return reinterpret_cast(val); } +}; + +template +struct IntrinsicBase +{ + typedef T ValueType; + typedef PrimitiveIntrinsics Primitives; + typedef typename Primitives::Type PrimType; + static_assert(sizeof(PrimType) == sizeof(T), + "Selection of PrimitiveIntrinsics was wrong"); + typedef CastHelper Cast; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + static ValueType load(const ValueType& ptr) { + Barrier::beforeLoad(); + ValueType val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(ValueType& ptr, ValueType val) { + // For SequentiallyConsistent, Primitives::store() will generate the + // proper memory fence. Everything else just needs a barrier before + // the store. + if (Order == SequentiallyConsistent) { + Primitives::store(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + } else { + Barrier::beforeStore(); + ptr = val; + } + } + static ValueType exchange(ValueType& ptr, ValueType val) { + PrimType oldval = + Primitives::exchange(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + return Cast::fromPrimType(oldval); + } + static bool compareExchange(ValueType& ptr, ValueType oldVal, ValueType newVal) { + return Primitives::compareExchange(reinterpret_cast(&ptr), + Cast::toPrimType(oldVal), + Cast::toPrimType(newVal)); + } +}; + +template +struct IntrinsicApplyHelper : public IntrinsicBase +{ + typedef PrimType (*BinaryOp)(PrimType*, PrimType); + typedef PrimType (*UnaryOp)(PrimType*); + + static ValueType applyBinaryFunction(BinaryOp op, ValueType& ptr, + ValueType val) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + PrimType primTypeVal = Cast::toPrimType(val); + return Cast::fromPrimType(op(primTypePtr, primTypeVal)); + } + + static ValueType applyUnaryFunction(UnaryOp op, ValueType& ptr) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + return Cast::fromPrimType(op(primTypePtr)); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::add, ptr, val); + } + static ValueType sub(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::sub, ptr, val); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::add, ptr, + (ValueType)(amount * sizeof(ValueType))); + } + static ValueType sub(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::sub, ptr, + (ValueType)(amount * sizeof(ValueType))); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static ValueType inc(ValueType& ptr) { return add(ptr, 1); } + static ValueType dec(ValueType& ptr) { return sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static ValueType or_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::or_, ptr, val); + } + static ValueType xor_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::xor_, ptr, val); + } + static ValueType and_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::and_, ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#else +# error "Atomic compiler intrinsics are not supported on your platform" +#endif + +namespace mozilla { + +namespace detail { + +template +class AtomicBase +{ + // We only support 32-bit types on 32-bit Windows, which constrains our + // implementation elsewhere. But we support pointer-sized types everywhere. + static_assert(sizeof(T) == 4 || (sizeof(uintptr_t) == 8 && sizeof(T) == 8), + "mozilla/Atomics.h only supports 32-bit and pointer-sized types"); + + protected: + typedef typename detail::AtomicIntrinsics Intrinsics; + typename Intrinsics::ValueType mValue; + + public: + AtomicBase() : mValue() {} + AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + + operator T() const { return Intrinsics::load(mValue); } + + T operator=(T aValue) { + Intrinsics::store(mValue, aValue); + return aValue; + } + + /** + * Performs an atomic swap operation. aValue is stored and the previous + * value of this variable is returned. + */ + T exchange(T aValue) { + return Intrinsics::exchange(mValue, aValue); + } + + /** + * Performs an atomic compare-and-swap operation and returns true if it + * succeeded. This is equivalent to atomically doing + * + * if (mValue == aOldValue) { + * mValue = aNewValue; + * return true; + * } else { + * return false; + * } + */ + bool compareExchange(T aOldValue, T aNewValue) { + return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); + } + + private: + template + AtomicBase(const AtomicBase& aCopy) MOZ_DELETE; +}; + +template +class AtomicBaseIncDec : public AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + AtomicBaseIncDec() : Base() {} + AtomicBaseIncDec(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } + T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } + T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } + T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } + + private: + template + AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) MOZ_DELETE; +}; + +} // namespace detail + +/** + * A wrapper for a type that enforces that all memory accesses are atomic. + * + * In general, where a variable |T foo| exists, |Atomic foo| can be used in + * its place. Implementations for integral and pointer types are provided + * below. + * + * Atomic accesses are sequentially consistent by default. You should + * use the default unless you are tall enough to ride the + * memory-ordering roller coaster (if you're not sure, you aren't) and + * you have a compelling reason to do otherwise. + * + * There is one exception to the case of atomic memory accesses: providing an + * initial value of the atomic value is not guaranteed to be atomic. This is a + * deliberate design choice that enables static atomic variables to be declared + * without introducing extra static constructors. + */ +template +class Atomic; + +/** + * Atomic implementation for integral types. + * + * In addition to atomic store and load operations, compound assignment and + * increment/decrement operators are implemented which perform the + * corresponding read-modify-write operation atomically. Finally, an atomic + * swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator+=(T delta) { return Base::Intrinsics::add(Base::mValue, delta) + delta; } + T operator-=(T delta) { return Base::Intrinsics::sub(Base::mValue, delta) - delta; } + T operator|=(T val) { return Base::Intrinsics::or_(Base::mValue, val) | val; } + T operator^=(T val) { return Base::Intrinsics::xor_(Base::mValue, val) ^ val; } + T operator&=(T val) { return Base::Intrinsics::and_(Base::mValue, val) & val; } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for pointer types. + * + * An atomic compare-and-swap primitive for pointer variables is provided, as + * are atomic increment and decement operators. Also provided are the compound + * assignment operators for addition and subtraction. Atomic swap (via + * exchange()) is included as well. + */ +template +class Atomic : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T* aInit) : Base(aInit) {} + + using Base::operator=; + + T* operator+=(ptrdiff_t delta) { + return Base::Intrinsics::add(Base::mValue, delta) + delta; + } + T* operator-=(ptrdiff_t delta) { + return Base::Intrinsics::sub(Base::mValue, delta) - delta; + } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for enum types. + * + * The atomic store and load operations and the atomic swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Atomics_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Attributes.h b/external/spidermonkey/include/mac/mozilla/Attributes.h index 89f3641fc9..6ea9776fbf 100644 --- a/external/spidermonkey/include/mac/mozilla/Attributes.h +++ b/external/spidermonkey/include/mac/mozilla/Attributes.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of various class and method modifier attributes. */ -#ifndef mozilla_Attributes_h_ -#define mozilla_Attributes_h_ +#ifndef mozilla_Attributes_h +#define mozilla_Attributes_h #include "mozilla/Compiler.h" @@ -117,11 +118,18 @@ * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a * function at compile time. A constexpr function cannot examine any values * except its arguments and can have no side effects except its return value. + * The MOZ_CONSTEXPR_VAR specifier tells a C++11 compiler that a variable's + * value may be computed at compile time. It should be prefered to just + * marking variables as MOZ_CONSTEXPR because if the compiler does not support + * constexpr it will fall back to making the variable const, and some compilers + * do not accept variables being marked both const and constexpr. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR # define MOZ_CONSTEXPR constexpr +# define MOZ_CONSTEXPR_VAR constexpr #else # define MOZ_CONSTEXPR /* no support */ +# define MOZ_CONSTEXPR_VAR const #endif /* @@ -382,18 +390,42 @@ * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is * expected to live on the stack, so it is a compile-time error to use it, or * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). It may be a base or - * a member of another class only if both classes are marked with this - * annotation. + * a new expression (unless placement new is being used). If a member of + * another class uses this class, or if another class inherits from this + * class, then it is considered to be a stack class as well, although this + * attribute need not be provided in such cases. + * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack or in static storage, so it is a compile-time + * error to use it, or an array of such objects, as the type of a new + * expression (unless placement new is being used). If a member of another + * class uses this class, or if another class inherits from this class, then + * it is considered to be a non-heap class as well, although this attribute + * need not be provided in such cases. */ #ifdef MOZ_CLANG_PLUGIN # define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) # define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) +# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) #else # define MOZ_MUST_OVERRIDE /* nothing */ # define MOZ_STACK_CLASS /* nothing */ +# define MOZ_NONHEAP_CLASS /* nothing */ #endif /* MOZ_CLANG_PLUGIN */ +/* + * MOZ_THIS_IN_INITIALIZER_LIST is used to avoid a warning when we know that + * it's safe to use 'this' in an initializer list. + */ +#ifdef _MSC_VER +# define MOZ_THIS_IN_INITIALIZER_LIST() \ + __pragma(warning(push)) \ + __pragma(warning(disable:4355)) \ + this \ + __pragma(warning(pop)) +#else +# define MOZ_THIS_IN_INITIALIZER_LIST() this +#endif + #endif /* __cplusplus */ -#endif /* mozilla_Attributes_h_ */ +#endif /* mozilla_Attributes_h */ diff --git a/external/spidermonkey/include/mac/mozilla/BloomFilter.h b/external/spidermonkey/include/mac/mozilla/BloomFilter.h index 8680ef2907..afe4b72b80 100644 --- a/external/spidermonkey/include/mac/mozilla/BloomFilter.h +++ b/external/spidermonkey/include/mac/mozilla/BloomFilter.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * A counting Bloom filter implementation. This allows consumers to @@ -10,14 +11,14 @@ * incorrectly answer "yes" when the correct answer is "no"). */ -#ifndef mozilla_BloomFilter_h_ -#define mozilla_BloomFilter_h_ +#ifndef mozilla_BloomFilter_h +#define mozilla_BloomFilter_h #include "mozilla/Assertions.h" #include "mozilla/Likely.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Util.h" +#include #include namespace mozilla { @@ -105,7 +106,7 @@ class BloomFilter */ public: BloomFilter() { - MOZ_STATIC_ASSERT(KeySize <= keyShift, "KeySize too big"); + static_assert(KeySize <= keyShift, "KeySize too big"); // Should we have a custom operator new using calloc instead and // require that we're allocated via the operator? @@ -231,4 +232,4 @@ BloomFilter::mightContain(const T* t) const } // namespace mozilla -#endif /* mozilla_BloomFilter_h_ */ +#endif /* mozilla_BloomFilter_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Casting.h b/external/spidermonkey/include/mac/mozilla/Casting.h index b1e81c33fa..76df0ef27e 100644 --- a/external/spidermonkey/include/mac/mozilla/Casting.h +++ b/external/spidermonkey/include/mac/mozilla/Casting.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cast operations to supplement the built-in casting operations. */ -#ifndef mozilla_Casting_h_ -#define mozilla_Casting_h_ +#ifndef mozilla_Casting_h +#define mozilla_Casting_h #include "mozilla/Assertions.h" #include "mozilla/TypeTraits.h" @@ -15,6 +16,27 @@ namespace mozilla { +/** + * Return a value of type |To|, containing the underlying bit pattern of |from|. + * + * |To| and |From| must be types of the same size; be careful of cross-platform + * size differences, or this might fail to compile on some but not all + * platforms. + */ +template +inline To +BitwiseCast(const From from) +{ + static_assert(sizeof(From) == sizeof(To), + "To and From must have the same size"); + union { + From from; + To to; + } u; + u.from = from; + return u.to; +} + namespace detail { enum ToSignedness { ToIsSigned, ToIsUnsigned }; @@ -43,7 +65,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return from <= From(To(-1)); } }; @@ -52,7 +74,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -61,8 +83,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedUnsignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedUnsignedCheck::checkBounds(from); } }; @@ -72,7 +94,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (from < 0) return false; if (sizeof(To) >= sizeof(From)) @@ -93,7 +115,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -102,7 +124,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); return from <= From(MaxValue); } @@ -112,8 +134,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedSignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedSignedCheck::checkBounds(from); } }; @@ -123,7 +145,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (sizeof(From) <= sizeof(To)) return true; const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); @@ -141,15 +163,15 @@ template class BoundsChecker { public: - static bool check(const From from) { return true; } + static bool checkBounds(const From from) { return true; } }; template class BoundsChecker { public: - static bool check(const From from) { - return BoundsCheckImpl::check(from); + static bool checkBounds(const From from) { + return BoundsCheckImpl::checkBounds(from); } }; @@ -157,7 +179,7 @@ template inline bool IsInBounds(const From from) { - return BoundsChecker::check(from); + return BoundsChecker::checkBounds(from); } } // namespace detail @@ -177,4 +199,4 @@ SafeCast(const From from) } // namespace mozilla -#endif /* mozilla_Casting_h_ */ +#endif /* mozilla_Casting_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Char16.h b/external/spidermonkey/include/mac/mozilla/Char16.h index c6f9f87d44..e4b184f950 100644 --- a/external/spidermonkey/include/mac/mozilla/Char16.h +++ b/external/spidermonkey/include/mac/mozilla/Char16.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implements a UTF-16 character type. */ -#ifndef mozilla_Char16_h_ -#define mozilla_Char16_h_ +#ifndef mozilla_Char16_h +#define mozilla_Char16_h #include "mozilla/Assertions.h" @@ -49,8 +50,8 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) -MOZ_STATIC_ASSERT(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); +static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); -#endif /* mozilla_Char16_h_ */ +#endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/mac/mozilla/CheckedInt.h b/external/spidermonkey/include/mac/mozilla/CheckedInt.h index 1dc80b032b..050cef8ed8 100644 --- a/external/spidermonkey/include/mac/mozilla/CheckedInt.h +++ b/external/spidermonkey/include/mac/mozilla/CheckedInt.h @@ -1,23 +1,23 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Provides checked integers, detecting integer overflow and divide-by-0. */ -#ifndef mozilla_CheckedInt_h_ -#define mozilla_CheckedInt_h_ +#ifndef mozilla_CheckedInt_h +#define mozilla_CheckedInt_h // Enable relying of Mozilla's MFBT for possibly-available C++11 features #define MOZ_CHECKEDINT_USE_MFBT +#include + #ifdef MOZ_CHECKEDINT_USE_MFBT # include "mozilla/Assertions.h" -# include "mozilla/StandardInteger.h" #else # include -# include -# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_DELETE #endif @@ -450,6 +450,44 @@ IsDivValid(T x, T y) !(IsSigned::value && x == MinValue::value && y == T(-1)); } +template::value> +struct IsModValidImpl; + +template +inline bool +IsModValid(T x, T y) +{ + return IsModValidImpl::run(x, y); +} + +/* + * Mod is pretty simple. + * For now, let's just use the ANSI C definition: + * If x or y are negative, the results are implementation defined. + * Consider these invalid. + * Undefined for y=0. + * The result will never exceed either x or y. + * + * Checking that x>=0 is a warning when T is unsigned. + */ + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + return y >= 1; + } +}; + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + if (x < 0) + return false; + + return y >= 1; + } +}; + template::value> struct NegateImpl; @@ -528,7 +566,7 @@ struct NegateImpl CheckedInt x(-1); // 1000 is of type int16_t, is found not to be in range for int8_t, // x is invalid - CheckedInt x(int16_t(1000)); + CheckedInt x(int16_t(1000)); // 3123456789 is of type uint32_t, is found not to be in range for int32_t, // x is invalid CheckedInt x(uint32_t(3123456789)); @@ -561,12 +599,12 @@ class CheckedInt template CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); } - friend class detail::NegateImpl; + friend struct detail::NegateImpl; public: /** @@ -585,16 +623,27 @@ class CheckedInt : mValue(T(value)), mIsValid(detail::IsInRange(value)) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); + } + + template + friend class CheckedInt; + + template + CheckedInt toChecked() const + { + CheckedInt ret(mValue); + ret.mIsValid = ret.mIsValid && mIsValid; + return ret; } /** Constructs a valid checked integer with initial value 0 */ CheckedInt() : mValue(0), mIsValid(true) { - MOZ_STATIC_ASSERT(detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value, + "This type is not supported by CheckedInt"); } /** @returns the actual value */ @@ -619,22 +668,31 @@ class CheckedInt const CheckedInt& rhs); template CheckedInt& operator +=(U rhs); + template friend CheckedInt operator -(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator -=(U rhs); + template friend CheckedInt operator *(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator *=(U rhs); + template friend CheckedInt operator /(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator /=(U rhs); + template + friend CheckedInt operator %(const CheckedInt& lhs, + const CheckedInt& rhs); + template + CheckedInt& operator %=(U rhs); + CheckedInt operator -() const { return detail::NegateImpl::negate(*this); @@ -726,6 +784,7 @@ MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) +MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) #undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR @@ -757,9 +816,9 @@ template inline typename detail::CastToCheckedIntImpl::ReturnType castToCheckedInt(U u) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); return detail::CastToCheckedIntImpl::run(u); } @@ -786,6 +845,7 @@ MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) +MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) #undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS @@ -815,4 +875,4 @@ typedef CheckedInt CheckedUint64; } // namespace mozilla -#endif /* mozilla_CheckedInt_h_ */ +#endif /* mozilla_CheckedInt_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Compiler.h b/external/spidermonkey/include/mac/mozilla/Compiler.h index 58239b0e30..d1ef1e79aa 100644 --- a/external/spidermonkey/include/mac/mozilla/Compiler.h +++ b/external/spidermonkey/include/mac/mozilla/Compiler.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ -#ifndef mozilla_Compiler_h_ -#define mozilla_Compiler_h_ +#ifndef mozilla_Compiler_h +#define mozilla_Compiler_h #if !defined(__clang__) && defined(__GNUC__) @@ -28,4 +29,4 @@ #endif -#endif /* mozilla_Compiler_h_ */ +#endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Constants.h b/external/spidermonkey/include/mac/mozilla/Constants.h index 904b30145a..86bbb6b354 100644 --- a/external/spidermonkey/include/mac/mozilla/Constants.h +++ b/external/spidermonkey/include/mac/mozilla/Constants.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt math constants. */ -#ifndef mozilla_Constants_h_ -#define mozilla_Constants_h_ +#ifndef mozilla_Constants_h +#define mozilla_Constants_h #ifndef M_PI # define M_PI 3.14159265358979323846 #endif -#endif /* mozilla_Constants_h_ */ +#endif /* mozilla_Constants_h */ diff --git a/external/spidermonkey/include/mac/mozilla/DebugOnly.h b/external/spidermonkey/include/mac/mozilla/DebugOnly.h index 1f78ed7989..e5f0d729b5 100644 --- a/external/spidermonkey/include/mac/mozilla/DebugOnly.h +++ b/external/spidermonkey/include/mac/mozilla/DebugOnly.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * assertions). */ -#ifndef mozilla_DebugOnly_h_ -#define mozilla_DebugOnly_h_ +#ifndef mozilla_DebugOnly_h +#define mozilla_DebugOnly_h namespace mozilla { @@ -74,4 +75,4 @@ class DebugOnly } -#endif /* mozilla_DebugOnly_h_ */ +#endif /* mozilla_DebugOnly_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Decimal.h b/external/spidermonkey/include/mac/mozilla/Decimal.h index 8032fd6e23..3c67d784c9 100644 --- a/external/spidermonkey/include/mac/mozilla/Decimal.h +++ b/external/spidermonkey/include/mac/mozilla/Decimal.h @@ -38,7 +38,7 @@ #define Decimal_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" +#include #include "mozilla/Types.h" #include diff --git a/external/spidermonkey/include/mac/mozilla/Endian.h b/external/spidermonkey/include/mac/mozilla/Endian.h index 5d2f905b41..dc6d11d3ba 100644 --- a/external/spidermonkey/include/mac/mozilla/Endian.h +++ b/external/spidermonkey/include/mac/mozilla/Endian.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -59,16 +60,16 @@ * }; */ -#ifndef mozilla_Endian_h_ -#define mozilla_Endian_h_ +#ifndef mozilla_Endian_h +#define mozilla_Endian_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/DebugOnly.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" +#include #include #if defined(_MSC_VER) && _MSC_VER >= 1300 @@ -636,4 +637,4 @@ class NativeEndian MOZ_FINAL : public detail::Endian } /* namespace mozilla */ -#endif /* mozilla_Endian_h_ */ +#endif /* mozilla_Endian_h */ diff --git a/external/spidermonkey/include/mac/mozilla/EnumSet.h b/external/spidermonkey/include/mac/mozilla/EnumSet.h index b18b005669..95c5608cf4 100644 --- a/external/spidermonkey/include/mac/mozilla/EnumSet.h +++ b/external/spidermonkey/include/mac/mozilla/EnumSet.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,7 +10,8 @@ #define mozilla_EnumSet_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" + +#include namespace mozilla { @@ -172,4 +174,4 @@ class EnumSet } // namespace mozilla -#endif // mozilla_EnumSet_h_ +#endif /* mozilla_EnumSet_h_*/ diff --git a/external/spidermonkey/include/mac/mozilla/FloatingPoint.h b/external/spidermonkey/include/mac/mozilla/FloatingPoint.h index 30af2217b1..d80f6a7234 100644 --- a/external/spidermonkey/include/mac/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/mac/mozilla/FloatingPoint.h @@ -1,16 +1,19 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various predicates and operations on IEEE-754 floating point types. */ -#ifndef mozilla_FloatingPoint_h_ -#define mozilla_FloatingPoint_h_ +#ifndef mozilla_FloatingPoint_h +#define mozilla_FloatingPoint_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" +#include "mozilla/Casting.h" + +#include namespace mozilla { @@ -35,80 +38,58 @@ namespace mozilla { * the case. But we required this in implementations of these algorithms that * preceded this header, so we shouldn't break anything if we continue doing so. */ -MOZ_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); +static_assert(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); const unsigned DoubleExponentBias = 1023; const unsigned DoubleExponentShift = 52; -namespace detail { - const uint64_t DoubleSignBit = 0x8000000000000000ULL; const uint64_t DoubleExponentBits = 0x7ff0000000000000ULL; const uint64_t DoubleSignificandBits = 0x000fffffffffffffULL; -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleExponentBits) == 0, - "sign bit doesn't overlap exponent bits"); -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleSignificandBits) == 0, - "sign bit doesn't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleExponentBits & DoubleSignificandBits) == 0, - "exponent bits don't overlap significand bits"); +static_assert((DoubleSignBit & DoubleExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((DoubleSignBit & DoubleSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((DoubleExponentBits & DoubleSignificandBits) == 0, + "exponent bits don't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == - ~uint64_t(0), - "all bits accounted for"); - -union DoublePun -{ - /* - * Every way to pun the bits of a double introduces an additional layer of - * complexity, across a multitude of platforms, architectures, and ABIs. - * Use *only* uint64_t to reduce complexity. Don't add new punning here - * without discussion! - */ - uint64_t u; - double d; -}; - -} /* namespace detail */ +static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == + ~uint64_t(0), + "all bits accounted for"); /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * A double is NaN if all exponent bits are 1 and the significand contains at * least one non-zero bit. */ - return (pun.u & detail::DoubleExponentBits) == detail::DoubleExponentBits && - (pun.u & detail::DoubleSignificandBits) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) == DoubleExponentBits && + (bits & DoubleSignificandBits) != 0; } /** Determines whether a double is +Infinity or -Infinity. */ static MOZ_ALWAYS_INLINE bool IsInfinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - return (pun.u & ~detail::DoubleSignBit) == detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & ~DoubleSignBit) == DoubleExponentBits; } /** Determines whether a double is not NaN or infinite. */ static MOZ_ALWAYS_INLINE bool IsFinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * NaN and Infinities are the only non-finite doubles, and both have all * exponent bits set to 1. */ - return (pun.u & detail::DoubleExponentBits) != detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) != DoubleExponentBits; } /** @@ -120,36 +101,30 @@ IsNegative(double d) { MOZ_ASSERT(!IsNaN(d), "NaN does not have a sign"); - union detail::DoublePun pun; - pun.d = d; - /* The sign bit is set if the double is negative. */ - return (pun.u & detail::DoubleSignBit) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleSignBit) != 0; } /** Determines whether a double represents -0. */ static MOZ_ALWAYS_INLINE bool IsNegativeZero(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Only the sign bit is set if the double is -0. */ - return pun.u == detail::DoubleSignBit; + uint64_t bits = BitwiseCast(d); + return bits == DoubleSignBit; } /** Returns the exponent portion of the double. */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * The exponent component of a double is an unsigned number, biased from its * actual value. Subtract the bias to retrieve the actual exponent. */ - return int_fast16_t((pun.u & detail::DoubleExponentBits) >> DoubleExponentShift) - + uint64_t bits = BitwiseCast(d); + return int_fast16_t((bits & DoubleExponentBits) >> DoubleExponentShift) - int_fast16_t(DoubleExponentBias); } @@ -157,28 +132,22 @@ ExponentComponent(double d) static MOZ_ALWAYS_INLINE double PositiveInfinity() { - union detail::DoublePun pun; - /* * Positive infinity has all exponent bits set, sign bit set to 0, and no * significand. */ - pun.u = detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleExponentBits); } /** Returns -Infinity. */ static MOZ_ALWAYS_INLINE double NegativeInfinity() { - union detail::DoublePun pun; - /* * Negative infinity has all exponent bits set, sign bit set to 1, and no * significand. */ - pun.u = detail::DoubleSignBit | detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleSignBit | DoubleExponentBits); } /** Constructs a NaN value with the specified sign bit and significand bits. */ @@ -186,24 +155,21 @@ static MOZ_ALWAYS_INLINE double SpecificNaN(int signbit, uint64_t significand) { MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~detail::DoubleSignificandBits) == 0); - MOZ_ASSERT(significand & detail::DoubleSignificandBits); + MOZ_ASSERT((significand & ~DoubleSignificandBits) == 0); + MOZ_ASSERT(significand & DoubleSignificandBits); - union detail::DoublePun pun; - pun.u = (signbit ? detail::DoubleSignBit : 0) | - detail::DoubleExponentBits | - significand; - MOZ_ASSERT(IsNaN(pun.d)); - return pun.d; + double d = BitwiseCast((signbit ? DoubleSignBit : 0) | + DoubleExponentBits | + significand); + MOZ_ASSERT(IsNaN(d)); + return d; } /** Computes the smallest non-zero positive double value. */ static MOZ_ALWAYS_INLINE double MinDoubleValue() { - union detail::DoublePun pun; - pun.u = 1; - return pun.d; + return BitwiseCast(uint64_t(1)); } static MOZ_ALWAYS_INLINE bool @@ -224,9 +190,22 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return mozilla::SpecificNaN(0, 0xfffffffffffffULL); + return SpecificNaN(0, 0xfffffffffffffULL); +} + +/** + * Compare two doubles for equality, *without* equating -0 to +0, and equating + * any NaN value to any other NaN value. (The normal equality operators equate + * -0 with +0, and they equate NaN to no other value.) + */ +static inline bool +DoublesAreIdentical(double d1, double d2) +{ + if (IsNaN(d1)) + return IsNaN(d2); + return BitwiseCast(d1) == BitwiseCast(d2); } } /* namespace mozilla */ -#endif /* mozilla_FloatingPoint_h_ */ +#endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/mac/mozilla/GuardObjects.h b/external/spidermonkey/include/mac/mozilla/GuardObjects.h index 6c2058938c..aeae7dcbc0 100644 --- a/external/spidermonkey/include/mac/mozilla/GuardObjects.h +++ b/external/spidermonkey/include/mac/mozilla/GuardObjects.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,6 +10,7 @@ #define mozilla_GuardObjects_h #include "mozilla/Assertions.h" +#include "mozilla/NullPtr.h" #include "mozilla/Types.h" #ifdef __cplusplus @@ -72,7 +74,7 @@ class MOZ_EXPORT GuardObjectNotifier bool* statementDone; public: - GuardObjectNotifier() : statementDone(NULL) { } + GuardObjectNotifier() : statementDone(nullptr) { } ~GuardObjectNotifier() { *statementDone = true; diff --git a/external/spidermonkey/include/mac/mozilla/HashFunctions.h b/external/spidermonkey/include/mac/mozilla/HashFunctions.h index 96242b629a..6d0d24e7b1 100644 --- a/external/spidermonkey/include/mac/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/mac/mozilla/HashFunctions.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Utilities for hashing. */ @@ -39,17 +40,18 @@ * }; * * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKey.h. + * in nsHashKeys.h. */ -#ifndef mozilla_HashFunctions_h_ -#define mozilla_HashFunctions_h_ +#ifndef mozilla_HashFunctions_h +#define mozilla_HashFunctions_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + #ifdef __cplusplus namespace mozilla { @@ -173,8 +175,8 @@ AddToHash(uint32_t hash, A* a) * catch data pointers and couldn't handle function pointers. */ - MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t), - "Strange pointer!"); + static_assert(sizeof(a) == sizeof(uintptr_t), + "Strange pointer!"); return detail::AddUintptrToHash(hash, uintptr_t(a)); } @@ -356,4 +358,5 @@ HashBytes(const void* bytes, size_t length); } /* namespace mozilla */ #endif /* __cplusplus */ -#endif /* mozilla_HashFunctions_h_ */ + +#endif /* mozilla_HashFunctions_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Likely.h b/external/spidermonkey/include/mac/mozilla/Likely.h index 6412b4943b..4f21609295 100644 --- a/external/spidermonkey/include/mac/mozilla/Likely.h +++ b/external/spidermonkey/include/mac/mozilla/Likely.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a * boolean predicate should be branch-predicted. */ -#ifndef mozilla_Likely_h_ -#define mozilla_Likely_h_ +#ifndef mozilla_Likely_h +#define mozilla_Likely_h #if defined(__clang__) || defined(__GNUC__) # define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) @@ -19,4 +20,4 @@ # define MOZ_UNLIKELY(x) (!!(x)) #endif -#endif /* mozilla_Likely_h_ */ +#endif /* mozilla_Likely_h */ diff --git a/external/spidermonkey/include/mac/mozilla/LinkedList.h b/external/spidermonkey/include/mac/mozilla/LinkedList.h index 5cfd60e4ac..c29760b3e7 100644 --- a/external/spidermonkey/include/mac/mozilla/LinkedList.h +++ b/external/spidermonkey/include/mac/mozilla/LinkedList.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -45,18 +46,19 @@ * } * * void notifyObservers(char* topic) { - * for (Observer* o = list.getFirst(); o != NULL; o = o->getNext()) - * o->Observe(topic); + * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) + * o->observe(topic); * } * }; * */ -#ifndef mozilla_LinkedList_h_ -#define mozilla_LinkedList_h_ +#ifndef mozilla_LinkedList_h +#define mozilla_LinkedList_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -69,10 +71,10 @@ template class LinkedListElement { /* - * It's convenient that we return NULL when getNext() or getPrevious() hits - * the end of the list, but doing so costs an extra word of storage in each - * linked list node (to keep track of whether |this| is the sentinel node) - * and a branch on this value in getNext/getPrevious. + * It's convenient that we return nullptr when getNext() or getPrevious() + * hits the end of the list, but doing so costs an extra word of storage in + * each linked list node (to keep track of whether |this| is the sentinel + * node) and a branch on this value in getNext/getPrevious. * * We could get rid of the extra word of storage by shoving the "is * sentinel" bit into one of the pointers, although this would, of course, @@ -107,12 +109,10 @@ class LinkedListElement LinkedListElement* prev; const bool isSentinel; - LinkedListElement* thisDuringConstruction() { return this; } - public: LinkedListElement() - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(false) { } @@ -122,8 +122,8 @@ class LinkedListElement } /* - * Get the next element in the list, or NULL if this is the last element in - * the list. + * Get the next element in the list, or nullptr if this is the last element + * in the list. */ T* getNext() { return next->asT(); @@ -133,8 +133,8 @@ class LinkedListElement } /* - * Get the previous element in the list, or NULL if this is the first element - * in the list. + * Get the previous element in the list, or nullptr if this is the first + * element in the list. */ T* getPrevious() { return prev->asT(); @@ -201,24 +201,24 @@ class LinkedListElement }; LinkedListElement(NodeKind nodeKind) - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(nodeKind == NODE_KIND_SENTINEL) { } /* - * Return |this| cast to T* if we're a normal node, or return NULL if we're - * a sentinel node. + * Return |this| cast to T* if we're a normal node, or return nullptr if + * we're a sentinel node. */ T* asT() { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } const T* asT() const { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } @@ -285,7 +285,7 @@ class LinkedList } /* - * Get the first element of the list, or NULL if the list is empty. + * Get the first element of the list, or nullptr if the list is empty. */ T* getFirst() { return sentinel.getNext(); @@ -295,7 +295,7 @@ class LinkedList } /* - * Get the last element of the list, or NULL if the list is empty. + * Get the last element of the list, or nullptr if the list is empty. */ T* getLast() { return sentinel.getPrevious(); @@ -306,7 +306,7 @@ class LinkedList /* * Get and remove the first element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popFirst() { T* ret = sentinel.getNext(); @@ -317,7 +317,7 @@ class LinkedList /* * Get and remove the last element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popLast() { T* ret = sentinel.getPrevious(); @@ -415,7 +415,7 @@ class LinkedList if (elem == t) return; } - MOZ_NOT_REACHED("element wasn't found in this list!"); + MOZ_CRASH("element wasn't found in this list!"); #endif } @@ -425,5 +425,6 @@ class LinkedList } /* namespace mozilla */ -#endif /* ifdef __cplusplus */ -#endif /* ifdef mozilla_LinkedList_h_ */ +#endif /* __cplusplus */ + +#endif /* mozilla_LinkedList_h */ diff --git a/external/spidermonkey/include/mac/mozilla/MSStdInt.h b/external/spidermonkey/include/mac/mozilla/MSStdInt.h deleted file mode 100644 index 0447f2f11b..0000000000 --- a/external/spidermonkey/include/mac/mozilla/MSStdInt.h +++ /dev/null @@ -1,247 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// Redistribution and use in source and binary forms, 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. -// -// 3. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 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 _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int32_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint32_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - - -#endif // _MSC_STDINT_H_ ] diff --git a/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h b/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h index 0a47810553..6d58691e06 100644 --- a/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h @@ -1,19 +1,20 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt maths algorithms. */ -#ifndef mozilla_MathAlgorithms_h_ -#define mozilla_MathAlgorithms_h_ +#ifndef mozilla_MathAlgorithms_h +#define mozilla_MathAlgorithms_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" #include #include +#include namespace mozilla { @@ -142,6 +143,288 @@ Abs(const long double d) return std::fabs(d); } +} // namespace mozilla + +#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) +# define MOZ_BITSCAN_WINDOWS + + extern "C" { + unsigned char _BitScanForward(unsigned long* Index, unsigned long mask); + unsigned char _BitScanReverse(unsigned long* Index, unsigned long mask); +# pragma intrinsic(_BitScanForward, _BitScanReverse) + +# if defined(_M_AMD64) || defined(_M_X64) +# define MOZ_BITSCAN_WINDOWS64 + unsigned char _BitScanForward64(unsigned long* index, unsigned __int64 mask); + unsigned char _BitScanReverse64(unsigned long* index, unsigned __int64 mask); +# pragma intrinsic(_BitScanForward64, _BitScanReverse64) +# endif + } // extern "C" + +#endif + +namespace mozilla { + +namespace detail { + +#if defined(MOZ_BITSCAN_WINDOWS) + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanReverse(&index, static_cast(u)); + return uint_fast8_t(31 - index); + } + + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanForward(&index, static_cast(u)); + return uint_fast8_t(index); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanReverse64(&index, static_cast(u)); + return uint_fast8_t(63 - index); +# else + uint32_t hi = uint32_t(u >> 32); + if (hi != 0) + return CountLeadingZeroes32(hi); + return 32 + CountLeadingZeroes32(uint32_t(u)); +# endif + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanForward64(&index, static_cast(u)); + return uint_fast8_t(index); +# else + uint32_t lo = uint32_t(u); + if (lo != 0) + return CountTrailingZeroes32(lo); + return 32 + CountTrailingZeroes32(uint32_t(u >> 32)); +# endif + } + +# ifdef MOZ_HAVE_BITSCAN64 +# undef MOZ_HAVE_BITSCAN64 +# endif + +#elif defined(__clang__) || defined(__GNUC__) + +# if defined(__clang__) +# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) +# error "A clang providing __builtin_c[lt]z is required to build" +# endif +# else + // gcc has had __builtin_clz and friends since 3.4: no need to check. +# endif + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + return __builtin_clz(u); + } + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + return __builtin_ctz(u); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { + return __builtin_clzll(u); + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { + return __builtin_ctzll(u); + } + +#else +# error "Implement these!" + inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; +#endif + +} // namespace detail + +/** + * Compute the number of high-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the highest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountLeadingZeroes32(0xF0FF1000) is 0; + * CountLeadingZeroes32(0x7F8F0001) is 1; + * CountLeadingZeroes32(0x3FFF0100) is 2; + * CountLeadingZeroes32(0x1FF50010) is 3; and so on. + */ +inline uint_fast8_t +CountLeadingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes32(u); +} + +/** + * Compute the number of low-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the lowest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountTrailingZeroes32(0x0100FFFF) is 0; + * CountTrailingZeroes32(0x7000FFFE) is 1; + * CountTrailingZeroes32(0x0080FFFC) is 2; + * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. + */ +inline uint_fast8_t +CountTrailingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes32(u); +} + +/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountLeadingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes64(u); +} + +/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountTrailingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes64(u); +} + +namespace detail { + +template +class CeilingLog2; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 32 - CountLeadingZeroes32(t - 1); + } +}; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 64 - CountLeadingZeroes64(t - 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the least power of 2 greater than or equal to |t|. + * + * CeilingLog2(0..1) is 0; + * CeilingLog2(2) is 1; + * CeilingLog2(3..4) is 2; + * CeilingLog2(5..8) is 3; + * CeilingLog2(9..16) is 4; and so on. + */ +template +inline uint_fast8_t +CeilingLog2(const T t) +{ + return detail::CeilingLog2::compute(t); +} + +/** A CeilingLog2 variant that accepts only size_t. */ +inline uint_fast8_t +CeilingLog2Size(size_t n) +{ + return CeilingLog2(n); +} + +namespace detail { + +template +class FloorLog2; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 31 - CountLeadingZeroes32(t | 1); + } +}; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 63 - CountLeadingZeroes64(t | 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the greatest power of 2 less than or equal to |t|. + * + * FloorLog2(0..1) is 0; + * FloorLog2(2..3) is 1; + * FloorLog2(4..7) is 2; + * FloorLog2(8..15) is 3; and so on. + */ +template +inline uint_fast8_t +FloorLog2(const T t) +{ + return detail::FloorLog2::compute(t); +} + +/** A FloorLog2 variant that accepts only size_t. */ +inline uint_fast8_t +FloorLog2Size(size_t n) +{ + return FloorLog2(n); +} + +/* + * Compute the smallest power of 2 greater than or equal to |x|. |x| must not + * be so great that the computed value would overflow |size_t|. + */ +inline size_t +RoundUpPow2(size_t x) +{ + MOZ_ASSERT(x <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), + "can't round up -- will overflow!"); + return size_t(1) << CeilingLog2(x); +} + } /* namespace mozilla */ -#endif /* mozilla_MathAlgorithms_h_ */ +#endif /* mozilla_MathAlgorithms_h */ diff --git a/external/spidermonkey/include/mac/mozilla/MemoryChecking.h b/external/spidermonkey/include/mac/mozilla/MemoryChecking.h index 3287e57ba1..2130990c6b 100644 --- a/external/spidermonkey/include/mac/mozilla/MemoryChecking.h +++ b/external/spidermonkey/include/mac/mozilla/MemoryChecking.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -19,8 +20,8 @@ * With no memory checker available, all macros expand to the empty statement. */ -#ifndef mozilla_MemoryChecking_h_ -#define mozilla_MemoryChecking_h_ +#ifndef mozilla_MemoryChecking_h +#define mozilla_MemoryChecking_h #if defined(MOZ_VALGRIND) #include "valgrind/memcheck.h" @@ -68,4 +69,4 @@ extern "C" { #endif -#endif /* mozilla_MemoryChecking_h_ */ +#endif /* mozilla_MemoryChecking_h */ diff --git a/external/spidermonkey/include/mac/mozilla/MemoryReporting.h b/external/spidermonkey/include/mac/mozilla/MemoryReporting.h new file mode 100644 index 0000000000..d2340ecf09 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/MemoryReporting.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Memory reporting infrastructure. */ + +#ifndef mozilla_MemoryReporting_h +#define mozilla_MemoryReporting_h + +#include + +#ifdef __cplusplus + +namespace mozilla { + +/* + * This is for functions that are like malloc_usable_size. Such functions are + * used for measuring the size of data structures. + */ +typedef size_t (*MallocSizeOf)(const void* p); + +} /* namespace mozilla */ + +#endif /* __cplusplus */ + +typedef size_t (*MozMallocSizeOf)(const void* p); + +#endif /* mozilla_MemoryReporting_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Move.h b/external/spidermonkey/include/mac/mozilla/Move.h new file mode 100644 index 0000000000..97178daaa6 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Move.h @@ -0,0 +1,166 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* C++11-style, but C++98-usable, "move references" implementation. */ + +#ifndef mozilla_Move_h +#define mozilla_Move_h + +namespace mozilla { + +/* + * "Move" References + * + * Some types can be copied much more efficiently if we know the original's + * value need not be preserved --- that is, if we are doing a "move", not a + * "copy". For example, if we have: + * + * Vector u; + * Vector v(u); + * + * the constructor for v must apply a copy constructor to each element of u --- + * taking time linear in the length of u. However, if we know we will not need u + * any more once v has been initialized, then we could initialize v very + * efficiently simply by stealing u's dynamically allocated buffer and giving it + * to v --- a constant-time operation, regardless of the size of u. + * + * Moves often appear in container implementations. For example, when we append + * to a vector, we may need to resize its buffer. This entails moving each of + * its extant elements from the old, smaller buffer to the new, larger buffer. + * But once the elements have been migrated, we're just going to throw away the + * old buffer; we don't care if they still have their values. So if the vector's + * element type can implement "move" more efficiently than "copy", the vector + * resizing should by all means use a "move" operation. Hash tables also need to + * be resized. + * + * The details of the optimization, and whether it's worth applying, vary from + * one type to the next. And while some constructor calls are moves, many really + * are copies, and can't be optimized this way. So we need: + * + * 1) a way for a particular invocation of a copy constructor to say that it's + * really a move, and that the value of the original isn't important + * afterwards (although it must still be safe to destroy); and + * + * 2) a way for a type (like Vector) to announce that it can be moved more + * efficiently than it can be copied, and provide an implementation of that + * move operation. + * + * The Move(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's 1). A MoveRef is simply a reference + * to a T, annotated to say that a copy constructor applied to it may move that + * T, instead of copying it. Finally, a constructor that accepts an MoveRef + * should perform a more efficient move, instead of a copy, providing 2). + * + * So, where we might define a copy constructor for a class C like this: + * + * C(const C& rhs) { ... copy rhs to this ... } + * + * we would declare a move constructor like this: + * + * C(MoveRef rhs) { ... move rhs to this ... } + * + * And where we might perform a copy like this: + * + * C c2(c1); + * + * we would perform a move like this: + * + * C c2(Move(c1)) + * + * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef + * to an ordinary copy constructor for a type that doesn't support a special + * move constructor, and you'll just get a copy. This means that templates can + * use Move whenever they know they won't use the original value any more, even + * if they're not sure whether the type at hand has a specialized move + * constructor. If it doesn't, the MoveRef will just convert to a T&, and + * the ordinary copy constructor will apply. + * + * A class with a move constructor can also provide a move assignment operator, + * which runs this's destructor, and then applies the move constructor to + * *this's memory. A typical definition: + * + * C& operator=(MoveRef rhs) { + * this->~C(); + * new(this) C(rhs); + * return *this; + * } + * + * With that in place, one can write move assignments like this: + * + * c2 = Move(c1); + * + * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but + * destructible state. + * + * This header file defines MoveRef and Move in the mozilla namespace. It's up + * to individual containers to annotate moves as such, by calling Move; and it's + * up to individual types to define move constructors. + * + * One hint: if you're writing a move constructor where the type has members + * that should be moved themselves, it's much nicer to write this: + * + * C(MoveRef c) : x(Move(c->x)), y(Move(c->y)) { } + * + * than the equivalent: + * + * C(MoveRef c) { new(&x) X(Move(c->x)); new(&y) Y(Move(c->y)); } + * + * especially since GNU C++ fails to notice that this does indeed initialize x + * and y, which may matter if they're const. + */ +template +class MoveRef +{ + T* pointer; + + public: + explicit MoveRef(T& t) : pointer(&t) { } + T& operator*() const { return *pointer; } + T* operator->() const { return pointer; } + operator T& () const { return *pointer; } +}; + +template +inline MoveRef +Move(T& t) +{ + return MoveRef(t); +} + +template +inline MoveRef +Move(const T& t) +{ + // With some versions of gcc, for a class C, there's an (incorrect) ambiguity + // between the C(const C&) constructor and the default C(C&&) C++11 move + // constructor, when the constructor is called with a const C& argument. + // + // This ambiguity manifests with the Move implementation above when Move is + // passed const U& for some class U. Calling Move(const U&) returns a + // MoveRef, which is then commonly passed to the U constructor, + // triggering an implicit conversion to const U&. gcc doesn't know whether to + // call U(const U&) or U(U&&), so it wrongly reports a compile error. + // + // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50442 has since been fixed, so + // this is no longer an issue for up-to-date compilers. But there's no harm + // in keeping it around for older compilers, so we might as well. See also + // bug 686280. + return MoveRef(const_cast(t)); +} + +/** Swap |t| and |u| using move-construction if possible. */ +template +inline void +Swap(T& t, T& u) +{ + T tmp(Move(t)); + t = Move(u); + u = Move(tmp); +} + +} // namespace mozilla + +#endif /* mozilla_Move_h */ diff --git a/external/spidermonkey/include/mac/mozilla/NullPtr.h b/external/spidermonkey/include/mac/mozilla/NullPtr.h index 7dcb03d734..14c0f07df2 100644 --- a/external/spidermonkey/include/mac/mozilla/NullPtr.h +++ b/external/spidermonkey/include/mac/mozilla/NullPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * constant. */ -#ifndef mozilla_NullPtr_h_ -#define mozilla_NullPtr_h_ +#ifndef mozilla_NullPtr_h +#define mozilla_NullPtr_h #include "mozilla/Compiler.h" @@ -45,4 +46,4 @@ # endif #endif -#endif /* mozilla_NullPtr_h_ */ +#endif /* mozilla_NullPtr_h */ diff --git a/external/spidermonkey/include/mac/mozilla/PodOperations.h b/external/spidermonkey/include/mac/mozilla/PodOperations.h index 6c6af27fc9..bec89fa928 100644 --- a/external/spidermonkey/include/mac/mozilla/PodOperations.h +++ b/external/spidermonkey/include/mac/mozilla/PodOperations.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -156,4 +157,4 @@ PodEqual(const T* one, const T* two, size_t len) } // namespace mozilla -#endif // mozilla_PodOperations_h_ +#endif /* mozilla_PodOperations_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Poison.h b/external/spidermonkey/include/mac/mozilla/Poison.h index c4adc23e71..75e0f081cd 100644 --- a/external/spidermonkey/include/mac/mozilla/Poison.h +++ b/external/spidermonkey/include/mac/mozilla/Poison.h @@ -9,13 +9,14 @@ * an address that leads to a safe crash when dereferenced. */ -#ifndef mozilla_Poison_h_ -#define mozilla_Poison_h_ +#ifndef mozilla_Poison_h +#define mozilla_Poison_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + MOZ_BEGIN_EXTERN_C extern MFBT_DATA uintptr_t gMozillaPoisonValue; @@ -36,11 +37,11 @@ inline uintptr_t mozPoisonValue() */ inline void mozWritePoison(void* aPtr, size_t aSize) { - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); const uintptr_t POISON = mozPoisonValue(); char* p = (char*)aPtr; char* limit = p + aSize; + MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); + MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); for (; p < limit; p += sizeof(uintptr_t)) { *((uintptr_t*)p) = POISON; } @@ -58,4 +59,4 @@ extern MFBT_DATA uintptr_t gMozillaPoisonSize; MOZ_END_EXTERN_C -#endif /* mozilla_Poison_h_ */ +#endif /* mozilla_Poison_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Range.h b/external/spidermonkey/include/mac/mozilla/Range.h index e14594d09d..4e02d962b5 100644 --- a/external/spidermonkey/include/mac/mozilla/Range.h +++ b/external/spidermonkey/include/mac/mozilla/Range.h @@ -1,12 +1,11 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef mozilla_Range_h_ -#define mozilla_Range_h_ +#ifndef mozilla_Range_h +#define mozilla_Range_h #include "mozilla/NullPtr.h" #include "mozilla/RangedPtr.h" @@ -40,10 +39,13 @@ class Range return mStart[offset]; } + const T& operator[](size_t offset) const { + return mStart[offset]; + } + operator ConvertibleToBool() const { return mStart ? &Range::nonNull : 0; } }; } // namespace mozilla -#endif // mozilla_Range_h_ - +#endif /* mozilla_Range_h */ diff --git a/external/spidermonkey/include/mac/mozilla/RangedPtr.h b/external/spidermonkey/include/mac/mozilla/RangedPtr.h index 7ce19d071f..493fcdbaee 100644 --- a/external/spidermonkey/include/mac/mozilla/RangedPtr.h +++ b/external/spidermonkey/include/mac/mozilla/RangedPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,11 +9,12 @@ * construction. */ -#ifndef mozilla_RangedPtr_h_ -#define mozilla_RangedPtr_h_ +#ifndef mozilla_RangedPtr_h +#define mozilla_RangedPtr_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #include "mozilla/Util.h" namespace mozilla { @@ -59,7 +61,7 @@ class RangedPtr #ifdef DEBUG return RangedPtr(p, rangeStart, rangeEnd); #else - return RangedPtr(p, NULL, size_t(0)); + return RangedPtr(p, nullptr, size_t(0)); #endif } @@ -251,4 +253,4 @@ class RangedPtr } /* namespace mozilla */ -#endif /* mozilla_RangedPtr_h_ */ +#endif /* mozilla_RangedPtr_h */ diff --git a/external/spidermonkey/include/mac/mozilla/ReentrancyGuard.h b/external/spidermonkey/include/mac/mozilla/ReentrancyGuard.h new file mode 100644 index 0000000000..d589f368a2 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/ReentrancyGuard.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Small helper class for asserting uses of a class are non-reentrant. */ + +#ifndef mozilla_ReentrancyGuard_h +#define mozilla_ReentrancyGuard_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/GuardObjects.h" + +namespace mozilla { + +/* Useful for implementing containers that assert non-reentrancy */ +class ReentrancyGuard +{ + MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER +#ifdef DEBUG + bool& entered; +#endif + + public: + template +#ifdef DEBUG + ReentrancyGuard(T& obj + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : entered(obj.entered) +#else + ReentrancyGuard(T& + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) +#endif + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; +#ifdef DEBUG + MOZ_ASSERT(!entered); + entered = true; +#endif + } + ~ReentrancyGuard() + { +#ifdef DEBUG + entered = false; +#endif + } + + private: + ReentrancyGuard(const ReentrancyGuard&) MOZ_DELETE; + void operator=(const ReentrancyGuard&) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_ReentrancyGuard_h */ diff --git a/external/spidermonkey/include/mac/mozilla/RefPtr.h b/external/spidermonkey/include/mac/mozilla/RefPtr.h index 9f4163a21a..3c275afdc7 100644 --- a/external/spidermonkey/include/mac/mozilla/RefPtr.h +++ b/external/spidermonkey/include/mac/mozilla/RefPtr.h @@ -1,14 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Helpers for defining and using refcounted objects. */ -#ifndef mozilla_RefPtr_h_ -#define mozilla_RefPtr_h_ +#ifndef mozilla_RefPtr_h +#define mozilla_RefPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/Attributes.h" #include "mozilla/TypeTraits.h" @@ -41,13 +43,19 @@ template OutParamRef byRef(RefPtr&); * state distinguishes use-before-ref (refcount==0) from * use-after-destroy (refcount==0xffffdead). */ -#ifdef DEBUG namespace detail { +#ifdef DEBUG static const int DEAD = 0xffffdead; -} #endif -template +// This is used WeakPtr.h as well as this file. +enum RefCountAtomicity +{ + AtomicRefCount, + NonAtomicRefCount +}; + +template class RefCounted { friend class RefPtr; @@ -56,8 +64,6 @@ class RefCounted RefCounted() : refCnt(0) { } ~RefCounted() { MOZ_ASSERT(refCnt == detail::DEAD); - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from RefCounted"); } public: @@ -87,7 +93,33 @@ class RefCounted } private: - int refCnt; + typename Conditional, int>::Type refCnt; +}; + +} + +template +class RefCounted : public detail::RefCounted +{ + public: + ~RefCounted() { + static_assert(IsBaseOf::value, + "T must derive from RefCounted"); + } +}; + +/** + * AtomicRefCounted is like RefCounted, with an atomically updated + * reference counter. + */ +template +class AtomicRefCounted : public detail::RefCounted +{ + public: + ~AtomicRefCounted() { + static_assert(IsBaseOf::value, + "T must derive from AtomicRefCounted"); + } }; /** @@ -259,9 +291,6 @@ byRef(RefPtr& ptr) } // namespace mozilla -#endif // mozilla_RefPtr_h_ - - #if 0 // Command line that builds these tests @@ -416,3 +445,5 @@ main(int argc, char** argv) } #endif + +#endif /* mozilla_RefPtr_h */ diff --git a/external/spidermonkey/include/mac/mozilla/SHA1.h b/external/spidermonkey/include/mac/mozilla/SHA1.h index a6604e699f..b167648540 100644 --- a/external/spidermonkey/include/mac/mozilla/SHA1.h +++ b/external/spidermonkey/include/mac/mozilla/SHA1.h @@ -1,17 +1,18 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Simple class for computing SHA1. */ -#ifndef mozilla_SHA1_h_ -#define mozilla_SHA1_h_ +#ifndef mozilla_SHA1_h +#define mozilla_SHA1_h -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" #include +#include namespace mozilla { @@ -58,4 +59,4 @@ class SHA1Sum } /* namespace mozilla */ -#endif /* mozilla_SHA1_h_ */ +#endif /* mozilla_SHA1_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Scoped.h b/external/spidermonkey/include/mac/mozilla/Scoped.h index 677a1a3797..fc48584b3e 100644 --- a/external/spidermonkey/include/mac/mozilla/Scoped.h +++ b/external/spidermonkey/include/mac/mozilla/Scoped.h @@ -1,11 +1,13 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A number of structures to simplify scope-based RAII management. */ -#ifndef mozilla_Scoped_h_ -#define mozilla_Scoped_h_ +#ifndef mozilla_Scoped_h +#define mozilla_Scoped_h /* * Resource Acquisition Is Initialization is a programming idiom used @@ -52,6 +54,7 @@ #include "mozilla/Attributes.h" #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -193,7 +196,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { free(ptr); } }; SCOPED_TEMPLATE(ScopedFreePtr, ScopedFreePtrTraits) @@ -256,7 +259,7 @@ template struct TypeSpecificScopedPointerTraits { typedef T* type; - const static type empty() { return NULL; } + const static type empty() { return nullptr; } const static void release(type value) { if (value) @@ -268,4 +271,4 @@ SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) } /* namespace mozilla */ -#endif // mozilla_Scoped_h_ +#endif /* mozilla_Scoped_h */ diff --git a/external/spidermonkey/include/mac/mozilla/SplayTree.h b/external/spidermonkey/include/mac/mozilla/SplayTree.h index f9a10d36dd..de0235aec9 100644 --- a/external/spidermonkey/include/mac/mozilla/SplayTree.h +++ b/external/spidermonkey/include/mac/mozilla/SplayTree.h @@ -1,7 +1,6 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=99 ft=cpp: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,8 +9,8 @@ * are faster to access again. */ -#ifndef mozilla_SplayTree_h_ -#define mozilla_SplayTree_h_ +#ifndef mozilla_SplayTree_h +#define mozilla_SplayTree_h #include "mozilla/Assertions.h" #include "mozilla/NullPtr.h" @@ -282,4 +281,4 @@ class SplayTree } /* namespace mozilla */ -#endif /* mozilla_SplayTree_h_ */ +#endif /* mozilla_SplayTree_h */ diff --git a/external/spidermonkey/include/mac/mozilla/StandardInteger.h b/external/spidermonkey/include/mac/mozilla/StandardInteger.h deleted file mode 100644 index 8e4c8578f1..0000000000 --- a/external/spidermonkey/include/mac/mozilla/StandardInteger.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface for C and C++ code. */ - -#ifndef mozilla_StandardInteger_h_ -#define mozilla_StandardInteger_h_ - -/* - * The C99 standard header exposes typedefs for common fixed-width - * integer types. It would be feasible to simply #include , but - * MSVC++ versions prior to 2010 don't provide . We could solve this - * by reimplementing for MSVC++ 2008 and earlier. But then we reach - * a second problem: our custom might conflict with a - * defined by an embedder already looking to work around the MSVC++ - * absence. - * - * We address these issues in this manner: - * - * 1. If the preprocessor macro MOZ_CUSTOM_STDINT_H is defined to a path to a - * custom implementation, we will #include it. Embedders using - * a custom must define this macro to an implementation that - * will work with their embedding. - * 2. Otherwise, if we are compiling with a an MSVC++ version without - * , #include our custom reimplementation. - * 3. Otherwise, #include the standard provided by the compiler. - * - * Note that we can't call this file "stdint.h" or something case-insensitively - * equal to "stdint.h" because then MSVC (and other compilers on - * case-insensitive file systems) will include this file, rather than the system - * stdint.h, when we ask for below. - */ -#if defined(MOZ_CUSTOM_STDINT_H) -# include MOZ_CUSTOM_STDINT_H -#elif defined(_MSC_VER) && _MSC_VER < 1600 -# include "mozilla/MSStdInt.h" -#else -# include -#endif - -#endif /* mozilla_StandardInteger_h_ */ diff --git a/external/spidermonkey/include/mac/mozilla/TemplateLib.h b/external/spidermonkey/include/mac/mozilla/TemplateLib.h new file mode 100644 index 0000000000..50275fdadb --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/TemplateLib.h @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Reusable template meta-functions on types and compile-time values. Meta- + * functions are placed inside the 'tl' namespace to avoid conflict with non- + * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. + * mozilla::FloorLog2). + * + * When constexpr support becomes universal, we should probably use that instead + * of some of these templates, for simplicity. + */ + +#ifndef mozilla_TemplateLib_h +#define mozilla_TemplateLib_h + +#include +#include + +namespace mozilla { + +namespace tl { + +/** Compute min/max. */ +template +struct Min +{ + static const size_t value = I < J ? I : J; +}; +template +struct Max +{ + static const size_t value = I > J ? I : J; +}; + +/** Compute floor(log2(i)). */ +template +struct FloorLog2 +{ + static const size_t value = 1 + FloorLog2::value; +}; +template<> struct FloorLog2<0> { /* Error */ }; +template<> struct FloorLog2<1> { static const size_t value = 0; }; + +/** Compute ceiling(log2(i)). */ +template +struct CeilingLog2 +{ + static const size_t value = FloorLog2<2 * I - 1>::value; +}; + +/** Round up to the nearest power of 2. */ +template +struct RoundUpPow2 +{ + static const size_t value = size_t(1) << CeilingLog2::value; +}; +template<> +struct RoundUpPow2<0> +{ + static const size_t value = 1; +}; + +/** Compute the number of bits in the given unsigned type. */ +template +struct BitSize +{ + static const size_t value = sizeof(T) * CHAR_BIT; +}; + +/** + * Produce an N-bit mask, where N <= BitSize::value. Handle the + * language-undefined edge case when N = BitSize::value. + */ +template +struct NBitMask +{ + // Assert the precondition. On success this evaluates to 0. Otherwise it + // triggers divide-by-zero at compile time: a guaranteed compile error in + // C++11, and usually one in C++98. Add this value to |value| to assure + // its computation. + static const size_t checkPrecondition = 0 / size_t(N < BitSize::value); + static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; +}; +template<> +struct NBitMask::value> +{ + static const size_t value = size_t(-1); +}; + +/** + * For the unsigned integral type size_t, compute a mask M for N such that + * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) + */ +template +struct MulOverflowMask +{ + static const size_t value = + ~NBitMask::value - CeilingLog2::value>::value; +}; +template<> struct MulOverflowMask<0> { /* Error */ }; +template<> struct MulOverflowMask<1> { static const size_t value = 0; }; + +} // namespace tl + +} // namespace mozilla + +#endif /* mozilla_TemplateLib_h */ diff --git a/external/spidermonkey/include/mac/mozilla/ThreadLocal.h b/external/spidermonkey/include/mac/mozilla/ThreadLocal.h index 2b4eb30207..6df109821f 100644 --- a/external/spidermonkey/include/mac/mozilla/ThreadLocal.h +++ b/external/spidermonkey/include/mac/mozilla/ThreadLocal.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cross-platform lightweight thread local data wrappers. */ -#ifndef mozilla_ThreadLocal_h_ -#define mozilla_ThreadLocal_h_ +#ifndef mozilla_ThreadLocal_h +#define mozilla_ThreadLocal_h #if defined(XP_WIN) // This file will get included in any file that wants to add a profiler mark. @@ -28,6 +29,7 @@ __declspec(dllimport) unsigned long __stdcall TlsAlloc(); #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -98,15 +100,15 @@ template inline bool ThreadLocal::init() { - MOZ_STATIC_ASSERT(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); + static_assert(sizeof(T) <= sizeof(void*), + "mozilla::ThreadLocal can't be used for types larger than " + "a pointer"); MOZ_ASSERT(!initialized()); #ifdef XP_WIN key = TlsAlloc(); inited = key != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES #else - inited = !pthread_key_create(&key, NULL); + inited = !pthread_key_create(&key, nullptr); #endif return inited; } @@ -144,4 +146,4 @@ ThreadLocal::set(const T value) } // namespace mozilla -#endif // mozilla_ThreadLocal_h_ +#endif /* mozilla_ThreadLocal_h */ diff --git a/external/spidermonkey/include/mac/mozilla/TypeTraits.h b/external/spidermonkey/include/mac/mozilla/TypeTraits.h index 656bc775f8..53c0b5c2f6 100644 --- a/external/spidermonkey/include/mac/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/mac/mozilla/TypeTraits.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Template-based metaprogramming and type-testing facilities. */ -#ifndef mozilla_TypeTraits_h_ -#define mozilla_TypeTraits_h_ +#ifndef mozilla_TypeTraits_h +#define mozilla_TypeTraits_h /* * These traits are approximate copies of the traits and semantics from C++11's @@ -126,6 +127,28 @@ struct IsPointer : FalseType {}; template struct IsPointer : TrueType {}; +namespace detail { + +// __is_enum is a supported extension across all of our supported compilers. +template +struct IsEnumHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsEnum determines whether a type is an enum type. + * + * mozilla::IsEnum::value is true; + * mozilla::IsEnum::value is false; + * mozilla::IsEnum::value is false; + */ +template +struct IsEnum + : detail::IsEnumHelper::Type> +{}; + /* 20.9.4.2 Composite type traits [meta.unary.comp] */ /** @@ -197,8 +220,24 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template struct IsPod : TrueType {}; +namespace detail { + +template::value> +struct IsSignedHelper; + +template +struct IsSignedHelper : TrueType {}; + +template +struct IsSignedHelper + : IntegralConstant::value && T(-1) < T(1)> +{}; + +} // namespace detail + /** - * IsSigned determines whether a type is a signed arithmetic type. + * IsSigned determines whether a type is a signed arithmetic type. |char| is + * considered a signed type if it has the same representation as |signed char|. * * Don't use this if the type might be user-defined! You might or might not get * a compile error, depending. @@ -209,10 +248,26 @@ template struct IsPod : TrueType {}; * mozilla::IsSigned::value is true. */ template -struct IsSigned - : IntegralConstant::value && T(-1) < T(0)> +struct IsSigned : detail::IsSignedHelper {}; + +namespace detail { + +template::value> +struct IsUnsignedHelper; + +template +struct IsUnsignedHelper : FalseType {}; + +template +struct IsUnsignedHelper + : IntegralConstant::value && + (IsSame::Type, bool>::value || + T(1) < T(-1))> {}; +} // namespace detail + /** * IsUnsigned determines whether a type is an unsigned arithmetic type. * @@ -225,9 +280,7 @@ struct IsSigned * mozilla::IsUnsigned::value is false. */ template -struct IsUnsigned - : IntegralConstant::value && T(0) < T(-1)> -{}; +struct IsUnsigned : detail::IsUnsignedHelper {}; /* 20.9.5 Type property queries [meta.unary.prop.query] */ @@ -427,6 +480,160 @@ struct RemoveCV /* 20.9.7.3 Sign modifications [meta.trans.sign] */ +template +struct EnableIf; + +template +struct Conditional; + +namespace detail { + +template +struct WithC : Conditional +{}; + +template +struct WithV : Conditional +{}; + + +template +struct WithCV : WithC::Type> +{}; + +template +struct CorrespondingSigned; + +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef short Type; }; +template<> +struct CorrespondingSigned { typedef int Type; }; +template<> +struct CorrespondingSigned { typedef long Type; }; +template<> +struct CorrespondingSigned { typedef long long Type; }; + +template::Type, + bool IsSignedIntegerType = IsSigned::value && + !IsSame::value> +struct MakeSigned; + +template +struct MakeSigned +{ + typedef T Type; +}; + +template +struct MakeSigned + : WithCV::value, IsVolatile::value, + typename CorrespondingSigned::Type> +{}; + +} // namespace detail + +/** + * MakeSigned produces the corresponding signed integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already a signed integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an unsigned integer type, the signed variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the integral type of the same size as T, with the lowest rank, + * with T's const/volatile qualifiers, is produced. (This basically only acts + * to produce signed char when T = char.) + * + * mozilla::MakeSigned::Type is signed long; + * mozilla::MakeSigned::Type is volatile int; + * mozilla::MakeSigned::Type is const signed short; + * mozilla::MakeSigned::Type is const signed char; + * mozilla::MakeSigned is an error; + * mozilla::MakeSigned is an error. + */ +template +struct MakeSigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeSigned + >::Type +{}; + +namespace detail { + +template +struct CorrespondingUnsigned; + +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned short Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned int Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long long Type; }; + + +template::Type, + bool IsUnsignedIntegerType = IsUnsigned::value && + !IsSame::value> +struct MakeUnsigned; + +template +struct MakeUnsigned +{ + typedef T Type; +}; + +template +struct MakeUnsigned + : WithCV::value, IsVolatile::value, + typename CorrespondingUnsigned::Type> +{}; + +} // namespace detail + +/** + * MakeUnsigned produces the corresponding unsigned integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already an unsigned integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an signed integer type, the unsigned variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the unsigned integral type of the same size as T, with the lowest + * rank, with T's const/volatile qualifiers, is produced. (This basically only + * acts to produce unsigned char when T = char.) + * + * mozilla::MakeUnsigned::Type is unsigned long; + * mozilla::MakeUnsigned::Type is volatile unsigned int; + * mozilla::MakeUnsigned::Type is const unsigned short; + * mozilla::MakeUnsigned::Type is const unsigned char; + * mozilla::MakeUnsigned is an error; + * mozilla::MakeUnsigned is an error. + */ +template +struct MakeUnsigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeUnsigned + >::Type +{}; + /* 20.9.7.4 Array modifications [meta.trans.arr] */ /* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ @@ -451,7 +658,7 @@ struct RemoveCV * ... * }; */ -template +template struct EnableIf {}; @@ -481,4 +688,4 @@ struct Conditional } /* namespace mozilla */ -#endif /* mozilla_TypeTraits_h_ */ +#endif /* mozilla_TypeTraits_h */ diff --git a/external/spidermonkey/include/mac/mozilla/TypedEnum.h b/external/spidermonkey/include/mac/mozilla/TypedEnum.h index 889960a32d..6f595cb4c5 100644 --- a/external/spidermonkey/include/mac/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/mac/mozilla/TypedEnum.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Macros to emulate C++11 typed enums and enum classes. */ -#ifndef mozilla_TypedEnum_h_ -#define mozilla_TypedEnum_h_ +#ifndef mozilla_TypedEnum_h +#define mozilla_TypedEnum_h #include "mozilla/Attributes.h" @@ -91,16 +92,33 @@ * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do * not support it. * - * Note that the workaround implemented here is not compatible with enums - * nested inside a class. + * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested + * inside classes. To define an enum class nested inside another class, use + * MOZ_{BEGIN,END}_NESTED_ENUM_CLASS, and place a MOZ_FINISH_NESTED_ENUM_CLASS + * in namespace scope to handle bits that can only be implemented with + * namespace-scoped code. For example: + * + * class FooBar { + * + * MOZ_BEGIN_NESTED_ENUM_CLASS(Enum, int32_t) + * A, + * B = 6 + * MOZ_END_NESTED_ENUM_CLASS(Enum) + * + * }; + * + * MOZ_FINISH_NESTED_ENUM_CLASS(FooBar::Enum) */ #if defined(MOZ_HAVE_CXX11_STRONG_ENUMS) /* * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) enum class Name : type { -# define MOZ_END_ENUM_CLASS(Name) }; +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + enum class Name : type { +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) /* nothing */ #else /** * We need Name to both name a type, and scope the provided enumerator @@ -136,14 +154,14 @@ * { * return Enum::A; * } - */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) \ + */\ +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ class Name \ { \ public: \ enum Enum MOZ_ENUM_TYPE(type) \ { -# define MOZ_END_ENUM_CLASS(Name) \ +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; \ Name() {} \ Name(Enum aEnum) : mEnum(aEnum) {} \ @@ -151,7 +169,8 @@ operator Enum() const { return mEnum; } \ private: \ Enum mEnum; \ - }; \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) \ inline int operator+(const int&, const Name::Enum&) MOZ_DELETE; \ inline int operator+(const Name::Enum&, const int&) MOZ_DELETE; \ inline int operator-(const int&, const Name::Enum&) MOZ_DELETE; \ @@ -207,7 +226,11 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif +# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) +# define MOZ_END_ENUM_CLASS(Name) \ + MOZ_END_NESTED_ENUM_CLASS(Name) \ + MOZ_FINISH_NESTED_ENUM_CLASS(Name) #endif /* __cplusplus */ -#endif /* mozilla_TypedEnum_h_ */ +#endif /* mozilla_TypedEnum_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Types.h b/external/spidermonkey/include/mac/mozilla/Types.h index 56e5cb82fb..5340b2b600 100644 --- a/external/spidermonkey/include/mac/mozilla/Types.h +++ b/external/spidermonkey/include/mac/mozilla/Types.h @@ -1,28 +1,22 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt foundational types and macros. */ -#ifndef mozilla_Types_h_ -#define mozilla_Types_h_ +#ifndef mozilla_Types_h +#define mozilla_Types_h /* * This header must be valid C and C++, includable by code embedding either * SpiderMonkey or Gecko. */ -/* - * Expose all the integer types defined in C99's (and the integer - * limit and constant macros, if compiling C code or if compiling C++ code and - * the right __STDC_*_MACRO has been defined for each). These are all usable - * throughout mfbt code, and throughout Mozilla code more generally. - */ -#include "mozilla/StandardInteger.h" - -/* Also expose size_t. */ +/* Expose all types and size_t. */ #include +#include /* Implement compiler and linker macros needed for APIs. */ @@ -133,4 +127,12 @@ # define MOZ_END_EXTERN_C #endif -#endif /* mozilla_Types_h_ */ +/* + * GCC's typeof is available when decltype is not. + */ +#if defined(__GNUC__) && defined(__cplusplus) && \ + !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +# define decltype __typeof__ +#endif + +#endif /* mozilla_Types_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Util.h b/external/spidermonkey/include/mac/mozilla/Util.h index 097c5478eb..4f1c634a59 100644 --- a/external/spidermonkey/include/mac/mozilla/Util.h +++ b/external/spidermonkey/include/mac/mozilla/Util.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * new headers, or to other appropriate existing headers, not here. */ -#ifndef mozilla_Util_h_ -#define mozilla_Util_h_ +#ifndef mozilla_Util_h +#define mozilla_Util_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -196,6 +197,58 @@ class Maybe constructed = true; } + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + T* addr() { MOZ_ASSERT(constructed); return &asT(); @@ -271,7 +324,7 @@ ArrayEnd(T (&arr)[N]) /* * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for MOZ_STATIC_ASSERT() calls that + * that can't use C++ template functions and for static_assert() calls that * can't call ArrayLength() when it is not a C++11 constexpr function. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR @@ -280,4 +333,4 @@ ArrayEnd(T (&arr)[N]) # define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) #endif -#endif /* mozilla_Util_h_ */ +#endif /* mozilla_Util_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Vector.h b/external/spidermonkey/include/mac/mozilla/Vector.h new file mode 100644 index 0000000000..8759df8c06 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Vector.h @@ -0,0 +1,1190 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A type/length-parametrized vector class. */ + +#ifndef mozilla_Vector_h +#define mozilla_Vector_h + +#include "mozilla/AllocPolicy.h" +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/MathAlgorithms.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" +#include "mozilla/NullPtr.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" +#include "mozilla/TypeTraits.h" +#include "mozilla/Util.h" + +#include // for placement new + +/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4345) +#endif + +namespace mozilla { + +template +class VectorBase; + +namespace detail { + +/* + * Check that the given capacity wastes the minimal amount of space if + * allocated on the heap. This means that cap*sizeof(T) is as close to a + * power-of-two as possible. growStorageBy() is responsible for ensuring + * this. + */ +template +static bool CapacityHasExcessSpace(size_t cap) +{ + size_t size = cap * sizeof(T); + return RoundUpPow2(size) - size >= sizeof(T); +} + +/* + * This template class provides a default implementation for vector operations + * when the element type is not known to be a POD, as judged by IsPod. + */ +template +struct VectorImpl +{ + /* Destroys constructed objects in the range [begin, end). */ + static inline void destroy(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + p->~T(); + } + + /* Constructs objects in the uninitialized range [begin, end). */ + static inline void initialize(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + /* + * Copy-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(*p); + } + + /* + * Move-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(Move(*p)); + } + + /* + * Copy-constructs objects in the uninitialized range [dst, dst+n) from the + * same object u. + */ + template + static inline void copyConstructN(T* dst, size_t n, const U& u) { + for (T* end = dst + n; dst < end; ++dst) + new(dst) T(u); + } + + /* + * Grows the given buffer to have capacity newCap, preserving the objects + * constructed in the range [begin, end) and updating v. Assumes that (1) + * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will + * not overflow. + */ + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + T* newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); + if (!newbuf) + return false; + T* dst = newbuf; + T* src = v.beginNoCheck(); + for (; src < v.endNoCheck(); ++dst, ++src) + new(dst) T(Move(*src)); + VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); + v.free_(v.mBegin); + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +/* + * This partial template specialization provides a default implementation for + * vector operations when the element type is known to be a POD, as judged by + * IsPod. + */ +template +struct VectorImpl +{ + static inline void destroy(T*, T*) {} + + static inline void initialize(T* begin, T* end) { + /* + * You would think that memset would be a big win (or even break even) + * when we know T is a POD. But currently it's not. This is probably + * because |append| tends to be given small ranges and memset requires + * a function call that doesn't get inlined. + * + * memset(begin, 0, sizeof(T) * (end-begin)); + */ + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + /* + * See above memset comment. Also, notice that copyConstruct is + * currently templated (T != U), so memcpy won't work without + * requiring T == U. + * + * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); + */ + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + *dst = *p; + } + + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + copyConstruct(dst, srcbeg, srcend); + } + + static inline void copyConstructN(T* dst, size_t n, const T& t) { + for (T* end = dst + n; dst < end; ++dst) + *dst = t; + } + + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + size_t oldSize = sizeof(T) * v.mCapacity; + size_t newSize = sizeof(T) * newCap; + T* newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); + if (!newbuf) + return false; + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +} // namespace detail + +/* + * A CRTP base class for vector-like classes. Unless you really really want + * your own vector class -- and you almost certainly don't -- you should use + * mozilla::Vector instead! + * + * See mozilla::Vector for interface requirements. + */ +template +class VectorBase : private AllocPolicy +{ + /* utilities */ + + static const bool sElemIsPod = IsPod::value; + typedef detail::VectorImpl Impl; + friend struct detail::VectorImpl; + + bool growStorageBy(size_t incr); + bool convertToHeapStorage(size_t newCap); + + /* magic constants */ + + static const int sMaxInlineBytes = 1024; + + /* compute constants */ + + /* + * Consider element size to be 1 for buffer sizing if there are 0 inline + * elements. This allows us to compile when the definition of the element + * type is not visible here. + * + * Explicit specialization is only allowed at namespace scope, so in order + * to keep everything here, we use a dummy template parameter with partial + * specialization. + */ + template + struct ElemSize + { + static const size_t value = sizeof(T); + }; + template + struct ElemSize<0, Dummy> + { + static const size_t value = 1; + }; + + static const size_t sInlineCapacity = + tl::Min::value>::value; + + /* Calculate inline buffer size; avoid 0-sized array. */ + static const size_t sInlineBytes = + tl::Max<1, sInlineCapacity * ElemSize::value>::value; + + /* member data */ + + /* + * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, + * mBegin + mLength) hold valid constructed T objects. The range [mBegin + + * mLength, mBegin + mCapacity) holds uninitialized memory. The range + * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory + * previously allocated by a call to reserve(). + */ + T* mBegin; + + /* Number of elements in the vector. */ + size_t mLength; + + /* Max number of elements storable in the vector without resizing. */ + size_t mCapacity; + +#ifdef DEBUG + /* Max elements of reserved or used space in this vector. */ + size_t mReserved; +#endif + + /* Memory used for inline storage. */ + AlignedStorage storage; + +#ifdef DEBUG + friend class ReentrancyGuard; + bool entered; +#endif + + /* private accessors */ + + bool usingInlineStorage() const { + return mBegin == const_cast(this)->inlineStorage(); + } + + T* inlineStorage() { + return static_cast(storage.addr()); + } + + T* beginNoCheck() const { + return mBegin; + } + + T* endNoCheck() { + return mBegin + mLength; + } + + const T* endNoCheck() const { + return mBegin + mLength; + } + +#ifdef DEBUG + size_t reserved() const { + MOZ_ASSERT(mReserved <= mCapacity); + MOZ_ASSERT(mLength <= mReserved); + return mReserved; + } +#endif + + /* Append operations guaranteed to succeed due to pre-reserved space. */ + template void internalAppend(const U& u); + template + void internalAppendAll(const VectorBase& u); + void internalAppendN(const T& t, size_t n); + template void internalAppend(const U* begin, size_t length); + + public: + static const size_t sMaxInlineStorage = N; + + typedef T ElementType; + + VectorBase(AllocPolicy = AllocPolicy()); + VectorBase(MoveRef); /* Move constructor. */ + ThisVector& operator=(MoveRef); /* Move assignment. */ + ~VectorBase(); + + /* accessors */ + + const AllocPolicy& allocPolicy() const { + return *this; + } + + AllocPolicy& allocPolicy() { + return *this; + } + + enum { InlineLength = N }; + + size_t length() const { + return mLength; + } + + bool empty() const { + return mLength == 0; + } + + size_t capacity() const { + return mCapacity; + } + + T* begin() { + MOZ_ASSERT(!entered); + return mBegin; + } + + const T* begin() const { + MOZ_ASSERT(!entered); + return mBegin; + } + + T* end() { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + const T* end() const { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + T& operator[](size_t i) { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + T& back() { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + const T& back() const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + class Range + { + friend class VectorBase; + T* cur_; + T* end_; + Range(T* cur, T* end) : cur_(cur), end_(end) {} + + public: + Range() {} + bool empty() const { return cur_ == end_; } + size_t remain() const { return end_ - cur_; } + T& front() const { return *cur_; } + void popFront() { MOZ_ASSERT(!empty()); ++cur_; } + T popCopyFront() { MOZ_ASSERT(!empty()); return *cur_++; } + }; + + Range all() { + return Range(begin(), end()); + } + + /* mutators */ + + /** + * Given that the vector is empty and has no inline storage, grow to + * |capacity|. + */ + bool initCapacity(size_t request); + + /** + * If reserve(length() + N) succeeds, the N next appends are guaranteed to + * succeed. + */ + bool reserve(size_t request); + + /** + * Destroy elements in the range [end() - incr, end()). Does not deallocate + * or unreserve storage for those elements. + */ + void shrinkBy(size_t incr); + + /** Grow the vector by incr elements. */ + bool growBy(size_t incr); + + /** Call shrinkBy or growBy based on whether newSize > length(). */ + bool resize(size_t newLength); + + /** + * Increase the length of the vector, but don't initialize the new elements + * -- leave them as uninitialized memory. + */ + bool growByUninitialized(size_t incr); + bool resizeUninitialized(size_t newLength); + + /** Shorthand for shrinkBy(length()). */ + void clear(); + + /** Clears and releases any heap-allocated storage. */ + void clearAndFree(); + + /** + * If true, appending |needed| elements won't reallocate elements storage. + * This *doesn't* mean that infallibleAppend may be used! You still must + * reserve the extra space, even if this method indicates that appends won't + * need to reallocate elements storage. + */ + bool canAppendWithoutRealloc(size_t needed) const; + + /** + * Potentially fallible append operations. + * + * The function templates that take an unspecified type U require a const T& + * or a MoveRef. The MoveRef variants move their operands into the + * vector, instead of copying them. If they fail, the operand is left + * unmoved. + */ + template bool append(const U& u); + template + bool appendAll(const VectorBase& u); + bool appendN(const T& t, size_t n); + template bool append(const U* begin, const U* end); + template bool append(const U* begin, size_t length); + + /* + * Guaranteed-infallible append operations for use upon vectors whose + * memory has been pre-reserved. Don't use this if you haven't reserved the + * memory! + */ + template void infallibleAppend(const U& u) { + internalAppend(u); + } + void infallibleAppendN(const T& t, size_t n) { + internalAppendN(t, n); + } + template void infallibleAppend(const U* aBegin, const U* aEnd) { + internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); + } + template void infallibleAppend(const U* aBegin, size_t aLength) { + internalAppend(aBegin, aLength); + } + + void popBack(); + + T popCopy(); + + /** + * Transfers ownership of the internal buffer used by this vector to the + * caller. (It's the caller's responsibility to properly deallocate this + * buffer, in accordance with this vector's AllocPolicy.) After this call, + * the vector is empty. Since the returned buffer may need to be allocated + * (if the elements are currently stored in-place), the call can fail, + * returning nullptr. + * + * N.B. Although a T*, only the range [0, length()) is constructed. + */ + T* extractRawBuffer(); + + /** + * Transfer ownership of an array of objects into the vector. The caller + * must have allocated the array in accordance with this vector's + * AllocPolicy. + * + * N.B. This call assumes that there are no uninitialized elements in the + * passed array. + */ + void replaceRawBuffer(T* p, size_t length); + + /** + * Places |val| at position |p|, shifting existing elements from |p| onward + * one position higher. On success, |p| should not be reused because it'll + * be a dangling pointer if reallocation of the vector storage occurred; the + * return value should be used instead. On failure, nullptr is returned. + * + * Example usage: + * + * if (!(p = vec.insert(p, val))) + * + * + * + * This is inherently a linear-time operation. Be careful! + */ + T* insert(T* p, const T& val); + + /** + * Removes the element |t|, which must fall in the bounds [begin, end), + * shifting existing elements from |t + 1| onward one position lower. + */ + void erase(T* t); + + /** + * Measure the size of the vector's heap-allocated storage. + */ + size_t sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const; + + /** + * Like sizeOfExcludingThis, but also measures the size of the vector + * object (which must be heap-allocated) itself. + */ + size_t sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const; + + void swap(ThisVector& other); + + private: + VectorBase(const ThisVector&) MOZ_DELETE; + void operator=(const ThisVector&) MOZ_DELETE; +}; + +/* This does the re-entrancy check plus several other sanity checks. */ +#define MOZ_REENTRANCY_GUARD_ET_AL \ + ReentrancyGuard g(*this); \ + MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ + MOZ_ASSERT(reserved() <= mCapacity); \ + MOZ_ASSERT(mLength <= reserved()); \ + MOZ_ASSERT(mLength <= mCapacity) + +/* Vector Implementation */ + +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(AP ap) + : AP(ap), + mBegin(static_cast(storage.addr())), + mLength(0), + mCapacity(sInlineCapacity) +#ifdef DEBUG + , mReserved(sInlineCapacity), + entered(false) +#endif +{} + +/* Move constructor. */ +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(MoveRef rhs) + : AllocPolicy(rhs) +#ifdef DEBUG + , entered(false) +#endif +{ + mLength = rhs->mLength; + mCapacity = rhs->mCapacity; +#ifdef DEBUG + mReserved = rhs->mReserved; +#endif + + if (rhs->usingInlineStorage()) { + /* We can't move the buffer over in this case, so copy elements. */ + mBegin = static_cast(storage.addr()); + Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); + /* + * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. + * The elements in its in-line storage still need to be destroyed. + */ + } else { + /* + * Take src's buffer, and turn src into an empty vector using + * in-line storage. + */ + mBegin = rhs->mBegin; + rhs->mBegin = static_cast(rhs->storage.addr()); + rhs->mCapacity = sInlineCapacity; + rhs->mLength = 0; +#ifdef DEBUG + rhs->mReserved = sInlineCapacity; +#endif + } +} + +/* Move assignment. */ +template +MOZ_ALWAYS_INLINE +TV& +VectorBase::operator=(MoveRef rhs) +{ + TV* tv = static_cast(this); + tv->~TV(); + new(tv) TV(rhs); + return *tv; +} + +template +MOZ_ALWAYS_INLINE +VectorBase::~VectorBase() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); +} + +/* + * This function will create a new heap buffer with capacity newCap, + * move all elements in the inline buffer to this new buffer, + * and fail on OOM. + */ +template +inline bool +VectorBase::convertToHeapStorage(size_t newCap) +{ + MOZ_ASSERT(usingInlineStorage()); + + /* Allocate buffer. */ + MOZ_ASSERT(!detail::CapacityHasExcessSpace(newCap)); + T* newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); + if (!newBuf) + return false; + + /* Copy inline elements into heap buffer. */ + Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + + /* Switch in heap buffer. */ + mBegin = newBuf; + /* mLength is unchanged. */ + mCapacity = newCap; + return true; +} + +template +MOZ_NEVER_INLINE bool +VectorBase::growStorageBy(size_t incr) +{ + MOZ_ASSERT(mLength + incr > mCapacity); + MOZ_ASSERT_IF(!usingInlineStorage(), + !detail::CapacityHasExcessSpace(mCapacity)); + + /* + * When choosing a new capacity, its size should is as close to 2**N bytes + * as possible. 2**N-sized requests are best because they are unlikely to + * be rounded up by the allocator. Asking for a 2**N number of elements + * isn't as good, because if sizeof(T) is not a power-of-two that would + * result in a non-2**N request size. + */ + + size_t newCap; + + if (incr == 1) { + if (usingInlineStorage()) { + /* This case occurs in ~70--80% of the calls to this function. */ + size_t newSize = + tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::value; + newCap = newSize / sizeof(T); + goto convert; + } + + if (mLength == 0) { + /* This case occurs in ~0--10% of the calls to this function. */ + newCap = 1; + goto grow; + } + + /* This case occurs in ~15--20% of the calls to this function. */ + + /* + * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector + * to 1GB of memory on a 32-bit system, which is a reasonable limit. It + * also ensures that + * + * static_cast(end()) - static_cast(begin()) + * + * doesn't overflow ptrdiff_t (see bug 510319). + */ + if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::value) { + this->reportAllocOverflow(); + return false; + } + + /* + * If we reach here, the existing capacity will have a size that is already + * as close to 2^N as sizeof(T) will allow. Just double the capacity, and + * then there might be space for one more element. + */ + newCap = mLength * 2; + if (detail::CapacityHasExcessSpace(newCap)) + newCap += 1; + } else { + /* This case occurs in ~2% of the calls to this function. */ + size_t newMinCap = mLength + incr; + + /* Did mLength + incr overflow? Will newCap * sizeof(T) overflow? */ + if (newMinCap < mLength || + newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value) + { + this->reportAllocOverflow(); + return false; + } + + size_t newMinSize = newMinCap * sizeof(T); + size_t newSize = RoundUpPow2(newMinSize); + newCap = newSize / sizeof(T); + } + + if (usingInlineStorage()) { + convert: + return convertToHeapStorage(newCap); + } + +grow: + return Impl::growTo(*this, newCap); +} + +template +inline bool +VectorBase::initCapacity(size_t request) +{ + MOZ_ASSERT(empty()); + MOZ_ASSERT(usingInlineStorage()); + if (request == 0) + return true; + T* newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); + if (!newbuf) + return false; + mBegin = newbuf; + mCapacity = request; +#ifdef DEBUG + mReserved = request; +#endif + return true; +} + +template +inline bool +VectorBase::reserve(size_t request) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (request > mCapacity && !growStorageBy(request - mLength)) + return false; + +#ifdef DEBUG + if (request > mReserved) + mReserved = request; + MOZ_ASSERT(mLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); +#endif + return true; +} + +template +inline void +VectorBase::shrinkBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(incr <= mLength); + Impl::destroy(endNoCheck() - incr, endNoCheck()); + mLength -= incr; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + T* newend = endNoCheck() + incr; + Impl::initialize(endNoCheck(), newend); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growByUninitialized(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +inline bool +VectorBase::resize(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growBy(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::resizeUninitialized(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growByUninitialized(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +inline void +VectorBase::clear() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + mLength = 0; +} + +template +inline void +VectorBase::clearAndFree() +{ + clear(); + + if (usingInlineStorage()) + return; + + this->free_(beginNoCheck()); + mBegin = static_cast(storage.addr()); + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif +} + +template +inline bool +VectorBase::canAppendWithoutRealloc(size_t needed) const +{ + return mLength + needed <= mCapacity; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendAll(const VectorBase& other) +{ + internalAppend(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U& u) +{ + MOZ_ASSERT(mLength + 1 <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + new(endNoCheck()) T(u); + ++mLength; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendN(const T& t, size_t needed) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppendN(t, needed); + return true; +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendN(const T& t, size_t needed) +{ + MOZ_ASSERT(mLength + needed <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstructN(endNoCheck(), needed, t); + mLength += needed; +} + +template +inline T* +VectorBase::insert(T* p, const T& val) +{ + MOZ_ASSERT(begin() <= p); + MOZ_ASSERT(p <= end()); + size_t pos = p - begin(); + MOZ_ASSERT(pos <= mLength); + size_t oldLength = mLength; + if (pos == oldLength) { + if (!append(val)) + return nullptr; + } else { + T oldBack = back(); + if (!append(oldBack)) /* Dup the last element. */ + return nullptr; + for (size_t i = oldLength; i > pos; --i) + (*this)[i] = (*this)[i - 1]; + (*this)[pos] = val; + } + return begin() + pos; +} + +template +inline void +VectorBase::erase(T* it) +{ + MOZ_ASSERT(begin() <= it); + MOZ_ASSERT(it < end()); + while (it + 1 < end()) { + *it = *(it + 1); + ++it; + } + popBack(); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U* insBegin, const U* insEnd) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + size_t needed = PointerRangeSize(insBegin, insEnd); + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppend(insBegin, needed); + return true; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U* insBegin, size_t insLength) +{ + MOZ_ASSERT(mLength + insLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); + mLength += insLength; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U& u) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength == mCapacity && !growStorageBy(1)) + return false; + +#ifdef DEBUG + if (mLength + 1 > mReserved) + mReserved = mLength + 1; +#endif + internalAppend(u); + return true; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendAll(const VectorBase& other) +{ + return append(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U *insBegin, size_t insLength) +{ + return append(insBegin, insBegin + insLength); +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::popBack() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(!empty()); + --mLength; + endNoCheck()->~T(); +} + +template +MOZ_ALWAYS_INLINE T +VectorBase::popCopy() +{ + T ret = back(); + popBack(); + return ret; +} + +template +inline T* +VectorBase::extractRawBuffer() +{ + T* ret; + if (usingInlineStorage()) { + ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); + if (!ret) + return nullptr; + Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + /* mBegin, mCapacity are unchanged. */ + mLength = 0; + } else { + ret = mBegin; + mBegin = static_cast(storage.addr()); + mLength = 0; + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif + } + return ret; +} + +template +inline void +VectorBase::replaceRawBuffer(T* p, size_t aLength) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + + /* Destroy what we have. */ + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); + + /* Take in the new buffer. */ + if (aLength <= sInlineCapacity) { + /* + * We convert to inline storage if possible, even though p might + * otherwise be acceptable. Maybe this behaviour should be + * specifiable with an argument to this function. + */ + mBegin = static_cast(storage.addr()); + mLength = aLength; + mCapacity = sInlineCapacity; + Impl::moveConstruct(mBegin, p, p + aLength); + Impl::destroy(p, p + aLength); + this->free_(p); + } else { + mBegin = p; + mLength = aLength; + mCapacity = aLength; + } +#ifdef DEBUG + mReserved = aLength; +#endif +} + +template +inline size_t +VectorBase::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const +{ + return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); +} + +template +inline size_t +VectorBase::sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const +{ + return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); +} + +template +inline void +VectorBase::swap(TV& other) +{ + static_assert(N == 0, + "still need to implement this for N != 0"); + + // This only works when inline storage is always empty. + if (!usingInlineStorage() && other.usingInlineStorage()) { + other.mBegin = mBegin; + mBegin = inlineStorage(); + } else if (usingInlineStorage() && !other.usingInlineStorage()) { + mBegin = other.mBegin; + other.mBegin = other.inlineStorage(); + } else if (!usingInlineStorage() && !other.usingInlineStorage()) { + Swap(mBegin, other.mBegin); + } else { + // This case is a no-op, since we'd set both to use their inline storage. + } + + Swap(mLength, other.mLength); + Swap(mCapacity, other.mCapacity); +#ifdef DEBUG + Swap(mReserved, other.mReserved); +#endif +} + +/* + * STL-like container providing a short-lived, dynamic buffer. Vector calls the + * constructors/destructors of all elements stored in its internal buffer, so + * non-PODs may be safely used. Additionally, Vector will store the first N + * elements in-place before resorting to dynamic allocation. + * + * T requirements: + * - default and copy constructible, assignable, destructible + * - operations do not throw + * N requirements: + * - any value, however, N is clamped to min/max values + * AllocPolicy: + * - see "Allocation policies" in AllocPolicy.h (defaults to + * mozilla::MallocAllocPolicy) + * + * Vector is not reentrant: T member functions called during Vector member + * functions must not call back into the same object! + */ +template +class Vector + : public VectorBase > +{ + typedef VectorBase Base; + + public: + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector& operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); + } +}; + +} // namespace mozilla + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif /* mozilla_Vector_h */ diff --git a/external/spidermonkey/include/mac/mozilla/WeakPtr.h b/external/spidermonkey/include/mac/mozilla/WeakPtr.h index d61b0b37d3..c714ebf565 100644 --- a/external/spidermonkey/include/mac/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/mac/mozilla/WeakPtr.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Weak pointer functionality, implemented as a mixin for use with any class. */ @@ -13,6 +14,9 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * + * AtomicSupportsWeakPtr can be used for a variant with an atomically updated + * reference counter. + * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -55,10 +59,11 @@ * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h */ -#ifndef mozilla_WeakPtr_h_ -#define mozilla_WeakPtr_h_ +#ifndef mozilla_WeakPtr_h +#define mozilla_WeakPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -71,8 +76,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted > +template +class WeakReference : public RefCounted, Atomicity> { public: explicit WeakReference(T* p) : ptr(p) {} @@ -81,8 +86,8 @@ class WeakReference : public RefCounted > } private: - friend class WeakPtrBase >; - friend class SupportsWeakPtrBase >; + friend class WeakPtrBase; + friend class SupportsWeakPtrBase; void detach() { ptr = nullptr; } @@ -103,8 +108,8 @@ class SupportsWeakPtrBase protected: ~SupportsWeakPtrBase() { - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from SupportsWeakPtrBase"); + static_assert(IsBaseOf, T>::value, + "T must derive from SupportsWeakPtrBase"); if (weakRef) weakRef->detach(); } @@ -116,10 +121,30 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr : public SupportsWeakPtrBase > +class SupportsWeakPtr + : public SupportsWeakPtrBase > { }; +template +class AtomicSupportsWeakPtr + : public SupportsWeakPtrBase > +{ +}; + +namespace detail { + +template +struct WeakReferenceCount +{ + static const RefCountAtomicity atomicity = + IsBaseOf, T>::value + ? AtomicRefCount + : NonAtomicRefCount; +}; + +} + template class WeakPtrBase { @@ -152,9 +177,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase > +class WeakPtr : public WeakPtrBase::atomicity> > { - typedef WeakPtrBase > Base; + typedef WeakPtrBase::atomicity> > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} @@ -163,4 +188,4 @@ class WeakPtr : public WeakPtrBase > } // namespace mozilla -#endif /* ifdef mozilla_WeakPtr_h_ */ +#endif /* mozilla_WeakPtr_h */ diff --git a/external/spidermonkey/include/win32/js-config.h b/external/spidermonkey/include/win32/js-config.h index 38c5df91b4..a581835270 100644 --- a/external/spidermonkey/include/win32/js-config.h +++ b/external/spidermonkey/include/win32/js-config.h @@ -38,8 +38,8 @@ JS_HAVE_STDINT_H. */ /* #undef JS_BYTES_PER_WORD */ -/* Some mozilla code uses JS-friend APIs that depend on JS_METHODJIT being - correct. */ -#define JS_METHODJIT 1 +/* MOZILLA JSAPI version number components */ +#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MINOR_VERSION 0 #endif /* js_config_h___ */ diff --git a/external/spidermonkey/include/win32/js.msg b/external/spidermonkey/include/win32/js.msg index 3e57bdf174..3f665d8d54 100644 --- a/external/spidermonkey/include/win32/js.msg +++ b/external/spidermonkey/include/win32/js.msg @@ -184,7 +184,7 @@ MSG_DEF(JSMSG_BAD_OPERAND, 130, 1, JSEXN_SYNTAXERR, "invalid {0} oper MSG_DEF(JSMSG_BAD_PROP_ID, 131, 0, JSEXN_SYNTAXERR, "invalid property id") MSG_DEF(JSMSG_RESERVED_ID, 132, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") MSG_DEF(JSMSG_SYNTAX_ERROR, 133, 0, JSEXN_SYNTAXERR, "syntax error") -MSG_DEF(JSMSG_UNUSED134, 134, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 134, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") MSG_DEF(JSMSG_BAD_PROTOTYPE, 135, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") MSG_DEF(JSMSG_MISSING_EXPONENT, 136, 0, JSEXN_SYNTAXERR, "missing exponent") MSG_DEF(JSMSG_OUT_OF_MEMORY, 137, 0, JSEXN_ERR, "out of memory") @@ -193,10 +193,10 @@ MSG_DEF(JSMSG_TOO_MANY_PARENS, 139, 0, JSEXN_INTERNALERR, "too many paren MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 140, 0, JSEXN_SYNTAXERR, "unterminated comment") MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 141, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 142, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_UNUSED143, 143, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 143, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 144, 0, JSEXN_SYNTAXERR, "illegal character") MSG_DEF(JSMSG_BAD_OCTAL, 145, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_UNUSED146, 146, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 146, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 147, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") MSG_DEF(JSMSG_INVALID_BACKREF, 148, 0, JSEXN_SYNTAXERR, "non-octal digit in an escape sequence that doesn't match a back-reference") MSG_DEF(JSMSG_BAD_BACKREF, 149, 0, JSEXN_SYNTAXERR, "back-reference exceeds number of capturing parentheses") @@ -220,7 +220,7 @@ MSG_DEF(JSMSG_RESERVED_SLOT_RANGE, 166, 0, JSEXN_RANGEERR, "reserved slot ind MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode JSPrincipals") MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_UNUSED170, 170, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") @@ -286,7 +286,7 @@ MSG_DEF(JSMSG_DEPRECATED_OCTAL, 232, 0, JSEXN_SYNTAXERR, "octal literals a MSG_DEF(JSMSG_STRICT_CODE_WITH, 233, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 234, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 235, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "assignment to {0} is deprecated") +MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 236, 1, JSEXN_SYNTAXERR, "can't assign to {0} in strict mode") MSG_DEF(JSMSG_BAD_BINDING, 237, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 238, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 239, 1, JSEXN_TYPEERR, "{0} is not extensible") @@ -313,16 +313,16 @@ MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 259, 0, JSEXN_TYPEERR, "can't change ob MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 260, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 261, 0, JSEXN_TYPEERR, "unsupported type for structured data") MSG_DEF(JSMSG_SC_RECURSION, 262, 0, JSEXN_INTERNALERR, "recursive object") -MSG_DEF(JSMSG_UNUSED263, 263, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 263, 0, JSEXN_ERR, "passing non-debuggable global to addDebuggee") MSG_DEF(JSMSG_BAD_CLONE_VERSION, 264, 0, JSEXN_ERR, "unsupported structured clone version") MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 265, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_UNUSED266, 266, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 266, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") MSG_DEF(JSMSG_STRICT_FUNCTION_STATEMENT, 267, 0, JSEXN_SYNTAXERR, "in strict mode code, functions may be declared only at top level or immediately within another function") MSG_DEF(JSMSG_INVALID_FOR_IN_INIT, 268, 0, JSEXN_SYNTAXERR, "for-in loop let declaration may not have an initializer") MSG_DEF(JSMSG_CLEARED_SCOPE, 269, 0, JSEXN_TYPEERR, "attempt to run compile-and-go script on a cleared scope") MSG_DEF(JSMSG_MALFORMED_ESCAPE, 270, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") MSG_DEF(JSMSG_BAD_GENEXP_BODY, 271, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_UNUSED272, 272, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_YIELD_WITHOUT_OPERAND, 272, 0, JSEXN_SYNTAXERR, "yield without a value is deprecated, and illegal in ES6 (use 'yield undefined' instead)") MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 273, 0, JSEXN_SYNTAXERR, "function statement requires a name") MSG_DEF(JSMSG_CCW_REQUIRED, 274, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 275, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") @@ -391,12 +391,21 @@ MSG_DEF(JSMSG_DATE_NOT_FINITE, 337, 0, JSEXN_RANGEERR, "date value is not MSG_DEF(JSMSG_MODULE_STATEMENT, 338, 0, JSEXN_SYNTAXERR, "module declarations may only appear at the top level of a program or module body") MSG_DEF(JSMSG_CURLY_BEFORE_MODULE, 339, 0, JSEXN_SYNTAXERR, "missing { before module body") MSG_DEF(JSMSG_CURLY_AFTER_MODULE, 340, 0, JSEXN_SYNTAXERR, "missing } after module body") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "'use asm' directive only works on function code") +MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 341, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 342, 1, JSEXN_TYPEERR, "asm.js type error: {0}") MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 343, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 0, JSEXN_ERR, "successfully compiled asm.js code") +MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 344, 1, JSEXN_ERR, "successfully compiled asm.js code ({0})") MSG_DEF(JSMSG_BAD_ARROW_ARGS, 345, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") +MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") +MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") diff --git a/external/spidermonkey/include/win32/js/Anchor.h b/external/spidermonkey/include/win32/js/Anchor.h index d0c2476cf7..0d458e6fb6 100644 --- a/external/spidermonkey/include/win32/js/Anchor.h +++ b/external/spidermonkey/include/win32/js/Anchor.h @@ -6,8 +6,8 @@ /* JS::Anchor implementation. */ -#ifndef js_Anchor_h___ -#define js_Anchor_h___ +#ifndef js_Anchor_h +#define js_Anchor_h #include "mozilla/Attributes.h" @@ -159,4 +159,4 @@ inline Anchor::~Anchor() } // namespace JS -#endif /* js_Anchor_h___ */ +#endif /* js_Anchor_h */ diff --git a/external/spidermonkey/include/win32/js/CallArgs.h b/external/spidermonkey/include/win32/js/CallArgs.h index af78fde0a0..8027ffc71a 100644 --- a/external/spidermonkey/include/win32/js/CallArgs.h +++ b/external/spidermonkey/include/win32/js/CallArgs.h @@ -26,11 +26,12 @@ * methods' implementations, potentially under time pressure. */ -#ifndef js_CallArgs_h___ -#define js_CallArgs_h___ +#ifndef js_CallArgs_h +#define js_CallArgs_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/TypeTraits.h" #include "jstypes.h" @@ -44,6 +45,29 @@ class JSObject; typedef JSBool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); +/* Typedef for native functions that may be called in parallel. */ +typedef js::ParallelResult +(* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + +/* + * Typedef for native functions that may be called either in parallel or + * sequential execution. + */ +typedef JSBool +(* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); + +/* + * Convenience wrappers for passing in ThreadSafeNative to places that expect + * a JSNative or a JSParallelNative. + */ +template +inline JSBool +JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); + +template +inline js::ParallelResult +JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); + /* * Compute |this| for the |vp| inside a JSNative, either boxing primitives or * replacing with the global object as necessary. @@ -58,6 +82,8 @@ JS_ComputeThis(JSContext *cx, JS::Value *vp); namespace JS { +extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; + /* * JS::CallReceiver encapsulates access to the callee, |this|, and eventual * return value for a function call. The principal way to create a @@ -92,30 +118,55 @@ namespace JS { * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallReceiver + +namespace detail { + +#ifdef DEBUG +extern JS_PUBLIC_API(void) +CheckIsValidConstructible(Value v); +#endif + +enum UsedRval { IncludeUsedRval, NoUsedRval }; + +template +class MOZ_STACK_CLASS UsedRvalBase; + +template<> +class MOZ_STACK_CLASS UsedRvalBase { protected: -#ifdef DEBUG mutable bool usedRval_; void setUsedRval() const { usedRval_ = true; } void clearUsedRval() const { usedRval_ = false; } -#else +}; + +template<> +class MOZ_STACK_CLASS UsedRvalBase +{ + protected: void setUsedRval() const {} void clearUsedRval() const {} +}; + +template +class MOZ_STACK_CLASS CallReceiverBase : public UsedRvalBase< +#ifdef DEBUG + WantUsedRval +#else + NoUsedRval #endif - + > +{ + protected: Value *argv_; - friend CallReceiver CallReceiverFromVp(Value *vp); - friend CallReceiver CallReceiverFromArgv(Value *argv); - public: /* * Returns the function being called, as an object. Must not be called * after rval() has been used! */ JSObject &callee() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return argv_[-2].toObject(); } @@ -124,7 +175,7 @@ class MOZ_STACK_CLASS CallReceiver * rval() has been used! */ HandleValue calleev() const { - MOZ_ASSERT(!usedRval_); + MOZ_ASSERT(!this->usedRval_); return HandleValue::fromMarkedLocation(&argv_[-2]); } @@ -148,6 +199,14 @@ class MOZ_STACK_CLASS CallReceiver return JS_ComputeThis(cx, base()); } + bool isConstructing() const { +#ifdef DEBUG + if (this->usedRval_) + CheckIsValidConstructible(calleev()); +#endif + return argv_[-1].isMagic(); + } + /* * Returns the currently-set return value. The initial contents of this * value are unspecified. Once this method has been called, callee() and @@ -160,7 +219,7 @@ class MOZ_STACK_CLASS CallReceiver * fails. */ MutableHandleValue rval() const { - setUsedRval(); + this->setUsedRval(); return MutableHandleValue::fromMarkedLocation(&argv_[-2]); } @@ -171,7 +230,7 @@ class MOZ_STACK_CLASS CallReceiver Value *base() const { return argv_ - 2; } Value *spAfterCall() const { - setUsedRval(); + this->setUsedRval(); return argv_ - 1; } @@ -181,7 +240,7 @@ class MOZ_STACK_CLASS CallReceiver // it. You probably don't want to use these! void setCallee(Value aCalleev) const { - clearUsedRval(); + this->clearUsedRval(); argv_[-2] = aCalleev; } @@ -194,6 +253,15 @@ class MOZ_STACK_CLASS CallReceiver } }; +} // namespace detail + +class MOZ_STACK_CLASS CallReceiver : public detail::CallReceiverBase +{ + private: + friend CallReceiver CallReceiverFromVp(Value *vp); + friend CallReceiver CallReceiverFromArgv(Value *argv); +}; + MOZ_ALWAYS_INLINE CallReceiver CallReceiverFromArgv(Value *argv) { @@ -233,11 +301,59 @@ CallReceiverFromVp(Value *vp) * public interface are meant to be used by embedders! See inline comments to * for details. */ -class MOZ_STACK_CLASS CallArgs : public CallReceiver +namespace detail { + +template +class MOZ_STACK_CLASS CallArgsBase : + public mozilla::Conditional >::Type { protected: unsigned argc_; + public: + /* Returns the number of arguments. */ + unsigned length() const { return argc_; } + + /* Returns the i-th zero-indexed argument. */ + MutableHandleValue operator[](unsigned i) const { + MOZ_ASSERT(i < argc_); + return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); + } + + /* + * Returns the i-th zero-indexed argument, or |undefined| if there's no + * such argument. + */ + HandleValue get(unsigned i) const { + return i < length() + ? HandleValue::fromMarkedLocation(&this->argv_[i]) + : UndefinedHandleValue; + } + + /* + * Returns true if the i-th zero-indexed argument is present and is not + * |undefined|. + */ + bool hasDefined(unsigned i) const { + return i < argc_ && !this->argv_[i].isUndefined(); + } + + public: + // These methods are publicly exposed, but we're less sure of the interface + // here than we'd like (because they're hackish and drop assertions). Try + // to avoid using these if you can. + + Value *array() const { return this->argv_; } + Value *end() const { return this->argv_ + argc_; } +}; + +} // namespace detail + +class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase +{ + private: friend CallArgs CallArgsFromVp(unsigned argc, Value *vp); friend CallArgs CallArgsFromSp(unsigned argc, Value *sp); @@ -249,45 +365,6 @@ class MOZ_STACK_CLASS CallArgs : public CallReceiver return args; } - public: - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - Value &operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return argv_[i]; - } - - /* Returns a mutable handle for the i-th zero-indexed argument. */ - MutableHandleValue handleAt(unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - Value get(unsigned i) const { - return i < length() ? argv_[i] : UndefinedValue(); - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !argv_[i].isUndefined(); - } - - public: - // These methods are publicly exposed, but we're less sure of the interface - // here than we'd like (because they're hackish and drop assertions). Try - // to avoid using these if you can. - - Value *array() const { return argv_; } - Value *end() const { return argv_ + argc_; } }; MOZ_ALWAYS_INLINE CallArgs @@ -345,4 +422,4 @@ JS_THIS(JSContext *cx, JS::Value *vp) */ #define JS_THIS_VALUE(cx,vp) ((vp)[1]) -#endif /* js_CallArgs_h___ */ +#endif /* js_CallArgs_h */ diff --git a/external/spidermonkey/include/win32/js/CharacterEncoding.h b/external/spidermonkey/include/win32/js/CharacterEncoding.h index 63e5cc6650..e88e08e1be 100644 --- a/external/spidermonkey/include/win32/js/CharacterEncoding.h +++ b/external/spidermonkey/include/win32/js/CharacterEncoding.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_CharacterEncoding_h___ -#define js_CharacterEncoding_h___ +#ifndef js_CharacterEncoding_h +#define js_CharacterEncoding_h #include "mozilla/Range.h" @@ -58,6 +58,20 @@ class Latin1CharsZ : public mozilla::RangedPtr char *c_str() { return reinterpret_cast(get()); } }; +class UTF8Chars : public mozilla::Range +{ + typedef mozilla::Range Base; + + public: + UTF8Chars() : Base() {} + UTF8Chars(char *aBytes, size_t aLength) + : Base(reinterpret_cast(aBytes), aLength) + {} + UTF8Chars(const char *aBytes, size_t aLength) + : Base(reinterpret_cast(const_cast(aBytes)), aLength) + {} +}; + /* * SpiderMonkey also deals directly with UTF-8 encoded text in some places. */ @@ -124,10 +138,12 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: + TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) { - JS_ASSERT(chars[length] = '\0'); + JS_ASSERT(chars[length] == '\0'); } }; @@ -142,14 +158,34 @@ class TwoByteCharsZ : public mozilla::RangedPtr * This method cannot trigger GC. */ extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(JSContext *cx, TwoByteChars tbchars); +LossyTwoByteCharsToNewLatin1CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); extern UTF8CharsZ -TwoByteCharsToNewUTF8CharsZ(JSContext *cx, TwoByteChars tbchars); +TwoByteCharsToNewUTF8CharsZ(js::ThreadSafeContext *cx, TwoByteChars tbchars); + +uint32_t +Utf8ToOneUcs4Char(const uint8_t *utf8Buffer, int utf8Length); + +/* + * Inflate bytes in UTF-8 encoding to jschars. + * - On error, returns an empty TwoByteCharsZ. + * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold + * its length; the length value excludes the trailing null. + */ +extern TwoByteCharsZ +UTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); + +/* + * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters + * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 + * input. + */ +extern TwoByteCharsZ +LossyUTF8CharsToNewTwoByteCharsZ(JSContext *cx, const UTF8Chars utf8, size_t *outlen); } // namespace JS inline void JS_free(JS::Latin1CharsZ &ptr) { js_free((void*)ptr.get()); } inline void JS_free(JS::UTF8CharsZ &ptr) { js_free((void*)ptr.get()); } -#endif // js_CharacterEncoding_h___ +#endif /* js_CharacterEncoding_h */ diff --git a/external/spidermonkey/include/win32/js/Date.h b/external/spidermonkey/include/win32/js/Date.h index 7ca961e30a..6199f9eca5 100644 --- a/external/spidermonkey/include/win32/js/Date.h +++ b/external/spidermonkey/include/win32/js/Date.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_Date_h___ -#define js_Date_h___ +#ifndef js_Date_h +#define js_Date_h #include "jstypes.h" @@ -32,4 +32,4 @@ DayFromTime(double time); } // namespace JS -#endif /* js_Date_h___ */ +#endif /* js_Date_h */ diff --git a/external/spidermonkey/include/win32/js/GCAPI.h b/external/spidermonkey/include/win32/js/GCAPI.h index 1b0036116c..a9bef77c09 100644 --- a/external/spidermonkey/include/win32/js/GCAPI.h +++ b/external/spidermonkey/include/win32/js/GCAPI.h @@ -4,10 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_gc_api_h___ -#define js_gc_api_h___ +#ifndef js_GCAPI_h +#define js_GCAPI_h -#include "HeapAPI.h" +#include "js/HeapAPI.h" namespace JS { @@ -181,6 +181,9 @@ DisableIncrementalGC(JSRuntime *rt); extern JS_FRIEND_API(void) DisableGenerationalGC(JSRuntime *rt); +extern JS_FRIEND_API(void) +EnableGenerationalGC(JSRuntime *rt); + extern JS_FRIEND_API(bool) IsIncrementalBarrierNeeded(JSRuntime *rt); @@ -205,7 +208,7 @@ WasIncrementalGC(JSRuntime *rt); class ObjectPtr { - JSObject *value; + Heap value; public: ObjectPtr() : value(NULL) {} @@ -240,7 +243,7 @@ class ObjectPtr } void trace(JSTracer *trc, const char *name) { - JS_CallObjectTracer(trc, &value, name); + JS_CallHeapObjectTracer(trc, &value, name); } JSObject &operator*() const { return *value; } @@ -291,4 +294,4 @@ ExposeValueToActiveJS(const Value &v) } /* namespace JS */ -#endif /* js_gc_api_h___ */ +#endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/win32/js/HashTable.h b/external/spidermonkey/include/win32/js/HashTable.h index 3402bfbff4..aa05b71472 100644 --- a/external/spidermonkey/include/win32/js/HashTable.h +++ b/external/spidermonkey/include/win32/js/HashTable.h @@ -4,17 +4,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_HashTable_h__ -#define js_HashTable_h__ +#ifndef js_HashTable_h +#define js_HashTable_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" #include "mozilla/PodOperations.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" #include "mozilla/Util.h" -#include "js/TemplateLib.h" #include "js/Utility.h" namespace js { @@ -68,15 +72,7 @@ class HashMap // HashMap construction is fallible (due to OOM); thus the user must call // init after constructing a HashMap and check the return value. - HashMap(AllocPolicy a = AllocPolicy()) - : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Key type must be relocatable"); - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Value type must be relocatable"); - } - + HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -142,18 +138,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, Move(e)); + return impl.add(p, mozilla::Move(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, Move(e)); + return impl.relookupOrAdd(p, k, mozilla::Move(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -203,10 +199,10 @@ class HashMap // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -235,7 +231,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, Move(e)); + return impl.putNew(k, mozilla::Move(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -253,9 +249,17 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const Key &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashMap is movable - HashMap(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashMap is not copyable or assignable @@ -303,11 +307,7 @@ class HashSet // HashSet construction is fallible (due to OOM); thus the user must call // init after constructing a HashSet and check the return value. - HashSet(AllocPolicy a = AllocPolicy()) : impl(a) - { - MOZ_STATIC_ASSERT(tl::IsRelocatableHeapType::result, - "Set element type must be relocatable"); - } + HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} bool init(uint32_t len = 16) { return impl.init(len); } bool initialized() const { return impl.initialized(); } @@ -411,10 +411,10 @@ class HashSet // Don't just call |impl.sizeOfExcludingThis()| because there's no // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return impl.sizeOfExcludingThis(mallocSizeOf); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const { + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); } @@ -448,9 +448,17 @@ class HashSet remove(p); } + // Infallibly rekey one entry, if present. + void rekey(const Lookup &old_key, const T &new_key) { + if (old_key != new_key) { + if (Ptr p = lookup(old_key)) + impl.rekey(p, new_key, new_key); + } + } + // HashSet is movable - HashSet(MoveRef rhs) : impl(Move(rhs->impl)) {} - void operator=(MoveRef rhs) { impl = Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } private: // HashSet is not copyable or assignable @@ -532,7 +540,7 @@ struct DefaultHasher // Specialize hashing policy for pointer types. It assumes that the type is // at least word-aligned. For types with smaller size use PointerHasher. template -struct DefaultHasher : PointerHasher::result> +struct DefaultHasher : PointerHasher::value> {}; // For doubles, we can xor the two uint32s. @@ -542,18 +550,11 @@ struct DefaultHasher typedef double Lookup; static HashNumber hash(double d) { JS_STATIC_ASSERT(sizeof(HashNumber) == 4); - union { - struct { - uint32_t lo; - uint32_t hi; - } s; - double d; - } u; - u.d = d; - return u.s.lo ^ u.s.hi; + uint64_t u = mozilla::BitwiseCast(d); + return HashNumber(u ^ (u >> 32)); } static bool match(double lhs, double rhs) { - return lhs == rhs; + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); } }; @@ -577,8 +578,8 @@ class HashMapEntry template HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} - HashMapEntry(MoveRef rhs) - : key(Move(rhs->key)), value(Move(rhs->value)) { } + HashMapEntry(mozilla::MoveRef rhs) + : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -647,8 +648,8 @@ class HashTableEntry } void swap(HashTableEntry *other) { - Swap(keyHash, other->keyHash); - Swap(mem, other->mem); + mozilla::Swap(keyHash, other->keyHash); + mozilla::Swap(mem, other->mem); } T &get() { JS_ASSERT(isLive()); return *mem.addr(); } @@ -807,10 +808,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - typename HashTableEntry::NonConstT t(Move(this->cur->get())); - HashPolicy::setKey(t, const_cast(k)); - table.remove(*this->cur); - table.putNewInfallible(l, Move(t)); + table.rekey(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -832,13 +830,13 @@ class HashTable : private AllocPolicy }; // HashTable is movable - HashTable(MoveRef rhs) + HashTable(mozilla::MoveRef rhs) : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); rhs->table = NULL; } - void operator=(MoveRef rhs) { + void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); @@ -882,7 +880,7 @@ class HashTable : private AllocPolicy # define METER(x) #endif - friend class js::ReentrancyGuard; + friend class mozilla::ReentrancyGuard; mutable mozilla::DebugOnly entered; mozilla::DebugOnly mutationCount; @@ -892,7 +890,7 @@ class HashTable : private AllocPolicy static const unsigned sMinCapacity = 1 << sMinCapacityLog2; static const unsigned sMaxInit = JS_BIT(23); static const unsigned sMaxCapacity = JS_BIT(24); - static const unsigned sHashBits = tl::BitSize::result; + static const unsigned sHashBits = mozilla::tl::BitSize::value; static const uint8_t sMinAlphaFrac = 64; // (0x100 * .25) static const uint8_t sMaxAlphaFrac = 192; // (0x100 * .75) static const uint8_t sInvMaxAlpha = 171; // (ceil(0x100 / .75) >> 1) @@ -1165,7 +1163,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); src->destroy(); } } @@ -1346,19 +1344,19 @@ class HashTable : private AllocPolicy return gen; } - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(table); } - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const + size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); } Ptr lookup(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); return Ptr(lookup(l, keyHash, 0)); } @@ -1371,7 +1369,7 @@ class HashTable : private AllocPolicy AddPtr lookupForAdd(const Lookup &l) const { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); HashNumber keyHash = prepareHash(l); Entry &entry = lookup(l, keyHash, sCollisionBit); AddPtr p(entry, keyHash); @@ -1382,7 +1380,7 @@ class HashTable : private AllocPolicy template bool add(AddPtr &p, const U &rhs) { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(mutationCount == p.mutationCount); JS_ASSERT(table); JS_ASSERT(!p.found()); @@ -1443,7 +1441,7 @@ class HashTable : private AllocPolicy { p.mutationCount = mutationCount; { - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); p.entry_ = &lookup(l, p.keyHash, sCollisionBit); } return p.found() || add(p, u); @@ -1452,17 +1450,27 @@ class HashTable : private AllocPolicy void remove(Ptr p) { JS_ASSERT(table); - ReentrancyGuard g(*this); + mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); remove(*p.entry_); checkUnderloaded(); } + void rekey(Ptr p, const Lookup &l, const Key &k) + { + JS_ASSERT(table); + mozilla::ReentrancyGuard g(*this); + JS_ASSERT(p.found()); + typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + HashPolicy::setKey(t, const_cast(k)); + remove(*p.entry_); + putNewInfallible(l, mozilla::Move(t)); + } + #undef METER }; } // namespace detail } // namespace js -#endif // js_HashTable_h__ - +#endif /* js_HashTable_h */ diff --git a/external/spidermonkey/include/win32/js/HeapAPI.h b/external/spidermonkey/include/win32/js/HeapAPI.h index f0f4411ac9..4d739304bc 100644 --- a/external/spidermonkey/include/win32/js/HeapAPI.h +++ b/external/spidermonkey/include/win32/js/HeapAPI.h @@ -4,33 +4,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_heap_api_h___ -#define js_heap_api_h___ +#ifndef js_HeapAPI_h +#define js_HeapAPI_h #include "jspubtd.h" +#include "js/Utility.h" + /* These values are private to the JS engine. */ namespace js { namespace gc { -/* - * Page size must be static to support our arena pointer optimizations, so we - * are forced to support each platform with non-4096 pages as a special case. - * Note: The freelist supports a maximum arena shift of 15. - * Note: Do not use JS_CPU_SPARC here, this header is used outside JS. - */ -#if (defined(SOLARIS) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \ - (defined(__sparc) || defined(__sparcv9) || defined(__ia64)) -const size_t PageShift = 13; -const size_t ArenaShift = PageShift; -#elif defined(__powerpc64__) -const size_t PageShift = 16; const size_t ArenaShift = 12; -#else -const size_t PageShift = 12; -const size_t ArenaShift = PageShift; -#endif -const size_t PageSize = size_t(1) << PageShift; const size_t ArenaSize = size_t(1) << ArenaShift; const size_t ArenaMask = ArenaSize - 1; @@ -67,7 +52,7 @@ namespace shadow { struct ArenaHeader { - js::Zone *zone; + JS::Zone *zone; }; struct Zone @@ -153,10 +138,10 @@ IsIncrementalBarrierNeededOnGCThing(shadow::Runtime *rt, void *thing, JSGCTraceK { if (!rt->needsBarrier_) return false; - js::Zone *zone = GetGCThingZone(thing); + JS::Zone *zone = GetGCThingZone(thing); return reinterpret_cast(zone)->needsBarrier_; } } /* namespace JS */ -#endif /* js_heap_api_h___ */ +#endif /* js_HeapAPI_h */ diff --git a/external/spidermonkey/include/win32/js/LegacyIntTypes.h b/external/spidermonkey/include/win32/js/LegacyIntTypes.h index 387a68b9e9..2c8498c89e 100644 --- a/external/spidermonkey/include/win32/js/LegacyIntTypes.h +++ b/external/spidermonkey/include/win32/js/LegacyIntTypes.h @@ -17,13 +17,12 @@ * Indeed, if you use this header and third-party code defining these * types, *expect* to encounter either compile errors or link errors, * depending how these types are used and on the order of inclusion. - * It is safest to use only the JSAPI -style types, - * customizing those types using MOZ_CUSTOM_STDINT_H if necessary. + * It is safest to use only the types. */ -#ifndef PROTYPES_H -#define PROTYPES_H +#ifndef js_LegacyIntTypes_h +#define js_LegacyIntTypes_h -#include "mozilla/StandardInteger.h" +#include #include "js-config.h" @@ -57,4 +56,4 @@ typedef int16_t JSInt16; typedef int32_t JSInt32; typedef int64_t JSInt64; -#endif /* !defined(PROTYPES_H) */ +#endif /* js_LegacyIntTypes_h */ diff --git a/external/spidermonkey/include/win32/js/MemoryMetrics.h b/external/spidermonkey/include/win32/js/MemoryMetrics.h index 7e84f2ae11..ed61e1c427 100644 --- a/external/spidermonkey/include/win32/js/MemoryMetrics.h +++ b/external/spidermonkey/include/win32/js/MemoryMetrics.h @@ -10,6 +10,8 @@ // These declarations are not within jsapi.h because they are highly likely to // change in the future. Depend on them at your own risk. +#include "mozilla/MemoryReporting.h" + #include #include "jsalloc.h" @@ -91,7 +93,6 @@ struct TypeInferenceSizes // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t jaeger; size_t ion; size_t asmJS; size_t baseline; @@ -136,7 +137,7 @@ struct RuntimeSizes size_t dtoa; size_t temporary; size_t regexpData; - size_t stack; + size_t interpreterStack; size_t gcMarker; size_t mathCache; size_t scriptData; @@ -153,9 +154,11 @@ struct ZoneStats gcHeapUnusedGcThings(0), gcHeapStringsNormal(0), gcHeapStringsShort(0), + gcHeapLazyScripts(0), gcHeapTypeObjects(0), gcHeapIonCodes(0), stringCharsNonHuge(0), + lazyScripts(0), typeObjects(0), typePool(0), hugeStrings() @@ -167,14 +170,16 @@ struct ZoneStats gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), gcHeapStringsNormal(other.gcHeapStringsNormal), gcHeapStringsShort(other.gcHeapStringsShort), + gcHeapLazyScripts(other.gcHeapLazyScripts), gcHeapTypeObjects(other.gcHeapTypeObjects), gcHeapIonCodes(other.gcHeapIonCodes), stringCharsNonHuge(other.stringCharsNonHuge), + lazyScripts(other.lazyScripts), typeObjects(other.typeObjects), typePool(other.typePool), hugeStrings() { - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // Add other's numbers to this object's numbers. @@ -186,16 +191,18 @@ struct ZoneStats ADD(gcHeapStringsNormal); ADD(gcHeapStringsShort); + ADD(gcHeapLazyScripts); ADD(gcHeapTypeObjects); ADD(gcHeapIonCodes); ADD(stringCharsNonHuge); + ADD(lazyScripts); ADD(typeObjects); ADD(typePool); #undef ADD - hugeStrings.append(other.hugeStrings); + hugeStrings.appendAll(other.hugeStrings); } // This field can be used by embedders. @@ -207,10 +214,12 @@ struct ZoneStats size_t gcHeapStringsNormal; size_t gcHeapStringsShort; + size_t gcHeapLazyScripts; size_t gcHeapTypeObjects; size_t gcHeapIonCodes; size_t stringCharsNonHuge; + size_t lazyScripts; size_t typeObjects; size_t typePool; @@ -241,7 +250,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(0), shapesCompartmentTables(0), scriptData(0), - jaegerData(0), baselineData(0), baselineStubsFallback(0), baselineStubsOptimized(0), @@ -271,7 +279,6 @@ struct CompartmentStats shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), shapesCompartmentTables(other.shapesCompartmentTables), scriptData(other.scriptData), - jaegerData(other.jaegerData), baselineData(other.baselineData), baselineStubsFallback(other.baselineStubsFallback), baselineStubsOptimized(other.baselineStubsOptimized), @@ -306,7 +313,6 @@ struct CompartmentStats size_t shapesExtraTreeShapeKids; size_t shapesCompartmentTables; size_t scriptData; - size_t jaegerData; size_t baselineData; size_t baselineStubsFallback; size_t baselineStubsOptimized; @@ -339,7 +345,6 @@ struct CompartmentStats ADD(shapesExtraTreeShapeKids); ADD(shapesCompartmentTables); ADD(scriptData); - ADD(jaegerData); ADD(baselineData); ADD(baselineStubsFallback); ADD(baselineStubsOptimized); @@ -360,7 +365,7 @@ struct CompartmentStats struct RuntimeStats { - RuntimeStats(JSMallocSizeOfFun mallocSizeOf) + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) : runtime(), gcHeapChunkTotal(0), gcHeapDecommittedArenas(0), @@ -417,7 +422,7 @@ struct RuntimeStats ZoneStats *currZoneStats; - JSMallocSizeOfFun mallocSizeOf_; + mozilla::MallocSizeOf mallocSizeOf_; virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; @@ -454,4 +459,4 @@ PeakSizeOfTemporary(const JSRuntime *rt); } // namespace JS -#endif // js_MemoryMetrics_h +#endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/win32/js/PropertyKey.h b/external/spidermonkey/include/win32/js/PropertyKey.h index 53158c26f3..c949db13a5 100644 --- a/external/spidermonkey/include/win32/js/PropertyKey.h +++ b/external/spidermonkey/include/win32/js/PropertyKey.h @@ -6,8 +6,8 @@ /* JS::PropertyKey implementation. */ -#ifndef js_PropertyKey_h___ -#define js_PropertyKey_h___ +#ifndef js_PropertyKey_h +#define js_PropertyKey_h #include "mozilla/Attributes.h" @@ -95,4 +95,4 @@ ToPropertyKey(JSContext *cx, HandleValue v, PropertyKey *key) } // namespace JS -#endif /* js_PropertyKey_h___ */ +#endif /* js_PropertyKey_h */ diff --git a/external/spidermonkey/include/win32/js/RequiredDefines.h b/external/spidermonkey/include/win32/js/RequiredDefines.h index 2be2efbf9a..6af9ca871b 100644 --- a/external/spidermonkey/include/win32/js/RequiredDefines.h +++ b/external/spidermonkey/include/win32/js/RequiredDefines.h @@ -10,8 +10,8 @@ * or SpiderMonkey public headers may not work correctly. */ -#ifndef js_RequiredDefines_h___ -#define js_RequiredDefines_h___ +#ifndef js_RequiredDefines_h +#define js_RequiredDefines_h /* * The c99 defining the limit macros (UINT32_MAX for example), says: @@ -20,4 +20,4 @@ */ #define __STDC_LIMIT_MACROS -#endif /* js_RequiredDefines_h___ */ +#endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/win32/js/RootingAPI.h b/external/spidermonkey/include/win32/js/RootingAPI.h index 3e2e0d2a7c..99295f1238 100644 --- a/external/spidermonkey/include/win32/js/RootingAPI.h +++ b/external/spidermonkey/include/win32/js/RootingAPI.h @@ -4,14 +4,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsgc_root_h__ -#define jsgc_root_h__ +#ifndef js_RootingAPI_h +#define js_RootingAPI_h #include "mozilla/GuardObjects.h" #include "mozilla/TypeTraits.h" #include "js/Utility.h" -#include "js/TemplateLib.h" #include "jspubtd.h" @@ -99,9 +98,10 @@ namespace js { class Module; +class ScriptSourceObject; template -struct RootMethods {}; +struct GCMethods {}; template class RootedBase {}; @@ -112,6 +112,9 @@ class HandleBase {}; template class MutableHandleBase {}; +template +class HeapBase {}; + /* * js::NullPtr acts like a NULL pointer in contexts that require a Handle. * @@ -130,6 +133,10 @@ struct NullPtr static void * const constNullValue; }; +namespace gc { +struct Cell; +} /* namespace gc */ + } /* namespace js */ namespace JS { @@ -161,6 +168,204 @@ struct JS_PUBLIC_API(NullPtr) static void * const constNullValue; }; +/* + * The Heap class is a C/C++ heap-stored reference to a JS GC thing. All + * members of heap classes that refer to GC thing should use Heap (or + * possibly TenuredHeap, described below). + * + * Heap wraps the complex mechanisms required to ensure GC safety for the + * contained reference into a C++ class that behaves similarly to a normal + * pointer. + * + * GC references stored on the C/C++ stack must use Rooted/Handle/MutableHandle + * instead. + * + * Requirements for type T: + * - Must be one of: Value, jsid, JSObject*, JSString*, JSScript* + */ +template +class Heap : public js::HeapBase +{ + public: + Heap() { + static_assert(sizeof(T) == sizeof(Heap), + "Heap must be binary compatible with T."); + init(js::GCMethods::initial()); + } + explicit Heap(T p) { init(p); } + explicit Heap(const Heap &p) { init(p.ptr); } + + ~Heap() { + if (js::GCMethods::needsPostBarrier(ptr)) + relocate(); + } + + bool operator==(const Heap &other) { return ptr == other.ptr; } + bool operator!=(const Heap &other) { return ptr != other.ptr; } + + bool operator==(const T &other) const { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + + operator T() const { return ptr; } + T operator->() const { return ptr; } + const T *address() const { return &ptr; } + const T &get() const { return ptr; } + + T *unsafeGet() { return &ptr; } + + Heap &operator=(T p) { + set(p); + return *this; + } + + void set(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (js::GCMethods::needsPostBarrier(newPtr)) { + ptr = newPtr; + post(); + } else if (js::GCMethods::needsPostBarrier(ptr)) { + relocate(); /* Called before overwriting ptr. */ + ptr = newPtr; + } else { + ptr = newPtr; + } + } + + private: + void init(T newPtr) { + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + ptr = newPtr; + if (js::GCMethods::needsPostBarrier(ptr)) + post(); + } + + void post() { +#ifdef JSGC_GENERATIONAL + JS_ASSERT(js::GCMethods::needsPostBarrier(ptr)); + js::GCMethods::postBarrier(&ptr); +#endif + } + + void relocate() { +#ifdef JSGC_GENERATIONAL + js::GCMethods::relocate(&ptr); +#endif + } + + T ptr; +}; + +#ifdef DEBUG +/* + * For generational GC, assert that an object is in the tenured generation as + * opposed to being in the nursery. + */ +extern JS_FRIEND_API(void) +AssertGCThingMustBeTenured(JSObject* obj); +#else +inline void +AssertGCThingMustBeTenured(JSObject *obj) {} +#endif + +/* + * The TenuredHeap class is similar to the Heap class above in that it + * encapsulates the GC concerns of an on-heap reference to a JS object. However, + * it has two important differences: + * + * 1) Pointers which are statically known to only reference "tenured" objects + * can avoid the extra overhead of SpiderMonkey's write barriers. + * + * 2) Objects in the "tenured" heap have stronger alignment restrictions than + * those in the "nursery", so it is possible to store flags in the lower + * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged + * pointer with a nice API for accessing the flag bits and adds various + * assertions to ensure that it is not mis-used. + * + * GC things are said to be "tenured" when they are located in the long-lived + * heap: e.g. they have gained tenure as an object by surviving past at least + * one GC. For performance, SpiderMonkey allocates some things which are known + * to normally be long lived directly into the tenured generation; for example, + * global objects. Additionally, SpiderMonkey does not visit individual objects + * when deleting non-tenured objects, so object with finalizers are also always + * tenured; for instance, this includes most DOM objects. + * + * The considerations to keep in mind when using a TenuredHeap vs a normal + * Heap are: + * + * - It is invalid for a TenuredHeap to refer to a non-tenured thing. + * - It is however valid for a Heap to refer to a tenured thing. + * - It is not possible to store flag bits in a Heap. + */ +template +class TenuredHeap : public js::HeapBase +{ + public: + TenuredHeap() : bits(0) { + static_assert(sizeof(T) == sizeof(TenuredHeap), + "TenuredHeap must be binary compatible with T."); + } + explicit TenuredHeap(T p) : bits(0) { setPtr(p); } + explicit TenuredHeap(const TenuredHeap &p) : bits(0) { setPtr(p.ptr); } + + bool operator==(const TenuredHeap &other) { return bits == other.bits; } + bool operator!=(const TenuredHeap &other) { return bits != other.bits; } + + void setPtr(T newPtr) { + JS_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); + JS_ASSERT(!js::GCMethods::poisoned(newPtr)); + if (newPtr) + AssertGCThingMustBeTenured(newPtr); + bits = (bits & flagsMask) | reinterpret_cast(newPtr); + } + + void setFlags(uintptr_t flagsToSet) { + JS_ASSERT((flagsToSet & ~flagsMask) == 0); + bits |= flagsToSet; + } + + void unsetFlags(uintptr_t flagsToUnset) { + JS_ASSERT((flagsToUnset & ~flagsMask) == 0); + bits &= ~flagsToUnset; + } + + bool hasFlag(uintptr_t flag) const { + JS_ASSERT((flag & ~flagsMask) == 0); + return (bits & flag) != 0; + } + + T getPtr() const { return reinterpret_cast(bits & ~flagsMask); } + uintptr_t getFlags() const { return bits & flagsMask; } + + operator T() const { return getPtr(); } + T operator->() const { return getPtr(); } + + TenuredHeap &operator=(T p) { + setPtr(p); + return *this; + } + + /* + * Set the pointer to a value which will cause a crash if it is + * dereferenced. + */ + void setToCrashOnTouch() { + bits = (bits & flagsMask) | crashOnTouchPointer; + } + + bool isSetToCrashOnTouch() { + return (bits & ~flagsMask) == crashOnTouchPointer; + } + + private: + enum { + maskBits = 3, + flagsMask = (1 << maskBits) - 1, + crashOnTouchPointer = 1 << maskBits + }; + + uintptr_t bits; +}; + /* * Reference to a T that has been rooted elsewhere. This is most useful * as a parameter type, which guarantees that the T lvalue is properly @@ -170,7 +375,7 @@ struct JS_PUBLIC_API(NullPtr) * specialization, define a HandleBase specialization containing them. */ template -class MOZ_STACK_CLASS Handle : public js::HandleBase +class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { friend class MutableHandle; @@ -180,20 +385,22 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase Handle(Handle handle, typename mozilla::EnableIf::value, int>::Type dummy = 0) { + static_assert(sizeof(Handle) == sizeof(T *), + "Handle must be binary compatible with T*."); ptr = reinterpret_cast(handle.address()); } /* Create a handle for a NULL pointer. */ Handle(js::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "js::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } /* Create a handle for a NULL pointer. */ Handle(JS::NullPtr) { - MOZ_STATIC_ASSERT(mozilla::IsPointer::value, - "JS::NullPtr overload not valid for non-pointer types"); + static_assert(mozilla::IsPointer::value, + "JS::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&JS::NullPtr::constNullValue); } @@ -202,11 +409,19 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase } /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. + * Take care when calling this method! * - * Create a Handle from a raw location of a T. + * This creates a Handle from the raw location of a T. + * + * It should be called only if the following conditions hold: + * + * 1) the location of the T is guaranteed to be marked (for some reason + * other than being a Rooted), e.g., if it is guaranteed to be reachable + * from an implicit root. + * + * 2) the contents of the location are immutable, or at least cannot change + * for the lifetime of the handle, as its users may not expect its value + * to change underneath them. */ static Handle fromMarkedLocation(const T *p) { Handle h; @@ -230,13 +445,17 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase typename mozilla::EnableIf::value, int>::Type dummy = 0); const T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a Handle to something that + * takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } - bool operator!=(const T &other) { return *ptr != other; } - bool operator==(const T &other) { return *ptr == other; } + bool operator!=(const T &other) const { return *ptr != other; } + bool operator==(const T &other) const { return *ptr == other; } private: Handle() {} @@ -247,13 +466,14 @@ class MOZ_STACK_CLASS Handle : public js::HandleBase void operator=(S v) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; +typedef Handle HandleObject; +typedef Handle HandleModule; +typedef Handle HandleScriptSource; +typedef Handle HandleFunction; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleId; +typedef Handle HandleValue; /* * Similar to a handle, but the underlying storage can be changed. This is @@ -270,7 +490,7 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase inline MutableHandle(Rooted *root); void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -288,9 +508,13 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase } T *address() const { return ptr; } - T get() const { return *ptr; } + const T& get() const { return *ptr; } - operator T() const { return get(); } + /* + * Return a reference so passing a MutableHandle to something that takes + * a |const T&| is not a GC hazard. + */ + operator const T&() const { return get(); } T operator->() const { return get(); } private: @@ -298,8 +522,8 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S v) MOZ_DELETE; + void operator=(MutableHandle other) MOZ_DELETE; }; typedef MutableHandle MutableHandleObject; @@ -309,6 +533,11 @@ typedef MutableHandle MutableHandleString; typedef MutableHandle MutableHandleId; typedef MutableHandle MutableHandleValue; +#ifdef JSGC_GENERATIONAL +JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); +JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); +#endif + } /* namespace JS */ namespace js { @@ -383,13 +612,28 @@ struct RootKind }; template -struct RootMethods +struct GCMethods { static T *initial() { return NULL; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } + static bool needsPostBarrier(T *v) { return v; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(T **vp) { + JS::HeapCellPostBarrier(reinterpret_cast(vp)); + } + static void relocate(T **vp) { + JS::HeapCellRelocate(reinterpret_cast(vp)); + } +#endif }; +#if defined(DEBUG) +/* This helper allows us to assert that Rooted is scoped within a request. */ +extern JS_PUBLIC_API(bool) +IsInRequest(JSContext *cx); +#endif + } /* namespace js */ namespace JS { @@ -405,46 +649,63 @@ namespace JS { template class MOZ_STACK_CLASS Rooted : public js::RootedBase { - void init(JSContext *cxArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ContextFriendFields *cx = js::ContextFriendFields::get(cxArg); - commonInit(cx->thingGCRooters); -#endif - } + /* Note: CX is a subclass of either ContextFriendFields or PerThreadDataFriendFields. */ + template + void init(CX *cx) { +#ifdef JSGC_TRACK_EXACT_ROOTS + js::ThingRootKind kind = js::GCMethods::kind(); + this->stack = &cx->thingGCRooters[kind]; + this->prev = *stack; + *stack = reinterpret_cast*>(this); - void init(js::PerThreadData *ptArg) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::PerThreadDataFriendFields *pt = js::PerThreadDataFriendFields::get(ptArg); - commonInit(pt->thingGCRooters); + JS_ASSERT(!js::GCMethods::poisoned(ptr)); #endif } public: Rooted(JSContext *cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; - init(cx); + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); } Rooted(JSContext *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + MOZ_ASSERT(js::IsInRequest(cx)); + init(js::ContextFriendFields::get(cx)); + } + + Rooted(js::ContextFriendFields *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(cx); } - Rooted(js::PerThreadData *pt + Rooted(js::ContextFriendFields *cx, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(js::RootMethods::initial()) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(cx); + } + + Rooted(js::PerThreadDataFriendFields *pt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; init(pt); } - Rooted(js::PerThreadData *pt, T initial + Rooted(js::PerThreadDataFriendFields *pt, T initial MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { @@ -452,18 +713,38 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(pt); } + Rooted(JSRuntime *rt + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(js::GCMethods::initial()) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + + Rooted(JSRuntime *rt, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(initial) + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + init(js::PerThreadDataFriendFields::getMainThread(rt)); + } + ~Rooted() { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; #endif } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } #endif - operator T() const { return ptr; } + /* + * Important: Return a reference here so passing a Rooted to + * something that takes a |const T&| is not a GC hazard. + */ + operator const T&() const { return ptr; } T operator->() const { return ptr; } T *address() { return &ptr; } const T *address() const { return &ptr; } @@ -471,7 +752,7 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!js::RootMethods::poisoned(value)); + JS_ASSERT(!js::GCMethods::poisoned(value)); ptr = value; return ptr; } @@ -481,28 +762,25 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } - - private: - void commonInit(Rooted **thingGCRooters) { -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) - js::ThingRootKind kind = js::RootMethods::kind(); - this->stack = &thingGCRooters[kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - - JS_ASSERT(!js::RootMethods::poisoned(ptr)); -#endif + void set(T value) { + JS_ASSERT(!js::GCMethods::poisoned(value)); + ptr = value; } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } + + private: +#ifdef JSGC_TRACK_EXACT_ROOTS Rooted **stack, *prev; #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) /* Has the rooting analysis ever scanned this Rooted's stack location? */ friend void JS::CheckStackRoots(JSContext*); +#endif + +#ifdef JSGC_ROOT_ANALYSIS bool scanned; #endif @@ -523,13 +801,14 @@ template <> class Rooted; #endif -typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedId; -typedef Rooted RootedValue; +typedef Rooted RootedObject; +typedef Rooted RootedModule; +typedef Rooted RootedScriptSource; +typedef Rooted RootedFunction; +typedef Rooted RootedScript; +typedef Rooted RootedString; +typedef Rooted RootedId; +typedef Rooted RootedValue; } /* namespace JS */ @@ -549,8 +828,9 @@ class SkipRoot const uint8_t *start; const uint8_t *end; - template - void init(SkipRoot **head, const T *ptr, size_t count) { + template + void init(CX *cx, const T *ptr, size_t count) { + SkipRoot **head = &cx->skipGCRooters; this->stack = head; this->prev = *stack; *stack = this; @@ -559,23 +839,6 @@ class SkipRoot } public: - template - SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - init(&ContextFriendFields::get(cx)->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - template - SkipRoot(js::PerThreadData *ptd, const T *ptr, size_t count = 1 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - { - PerThreadDataFriendFields *ptff = PerThreadDataFriendFields::get(ptd); - init(&ptff->skipGCRooters, ptr, count); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - ~SkipRoot() { JS_ASSERT(*stack == this); *stack = prev; @@ -589,22 +852,36 @@ class SkipRoot #else /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} + public: + +#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template SkipRoot(JSContext *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(ContextFriendFields::get(cx), ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } template - SkipRoot(PerThreadData *ptd, const T *ptr, size_t count = 1 + SkipRoot(ContextFriendFields *cx, const T *ptr, size_t count = 1 MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { + init(cx, ptr, count); MOZ_GUARD_OBJECT_NOTIFIER_INIT; } -#endif /* DEBUG && JSGC_ROOT_ANALYSIS */ + template + SkipRoot(PerThreadData *pt, const T *ptr, size_t count = 1 + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + { + init(PerThreadDataFriendFields::get(pt), ptr, count); + MOZ_GUARD_OBJECT_NOTIFIER_INIT; + } MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; @@ -614,15 +891,17 @@ template class FakeRooted : public RootedBase { public: - FakeRooted(JSContext *cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : ptr(RootMethods::initial()) + template + FakeRooted(CX *cx + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : ptr(GCMethods::initial()) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } - FakeRooted(JSContext *cx, T initial - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + template + FakeRooted(CX *cx, T initial + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : ptr(initial) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; @@ -636,13 +915,13 @@ class FakeRooted : public RootedBase const T &get() const { return ptr; } T &operator=(T value) { - JS_ASSERT(!RootMethods::poisoned(value)); + JS_ASSERT(!GCMethods::poisoned(value)); ptr = value; return ptr; } - bool operator!=(const T &other) { return ptr != other; } - bool operator==(const T &other) { return ptr == other; } + bool operator!=(const T &other) const { return ptr != other; } + bool operator==(const T &other) const { return ptr == other; } private: T ptr; @@ -666,7 +945,7 @@ class FakeMutableHandle : public js::MutableHandleBase } void set(T v) { - JS_ASSERT(!js::RootMethods::poisoned(v)); + JS_ASSERT(!js::GCMethods::poisoned(v)); *ptr = v; } @@ -727,13 +1006,11 @@ template class MaybeRooted typedef FakeMutableHandle MutableHandleType; static inline JS::Handle toHandle(HandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::Handle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - JS_NOT_REACHED("Bad conversion"); - return JS::MutableHandle::fromMarkedLocation(NULL); + MOZ_ASSUME_UNREACHABLE("Bad conversion"); } }; @@ -761,6 +1038,8 @@ template inline MutableHandle::MutableHandle(Rooted *root) { + static_assert(sizeof(MutableHandle) == sizeof(T *), + "MutableHandle must be binary compatible with T*."); ptr = root->address(); } @@ -779,10 +1058,6 @@ inline void MaybeCheckStackRoots(JSContext *cx) #endif } -namespace gc { -struct Cell; -} /* namespace gc */ - /* Base class for automatic read-only object rooting during compilation. */ class CompilerRootNode { @@ -801,4 +1076,4 @@ class CompilerRootNode } /* namespace js */ -#endif /* jsgc_root_h___ */ +#endif /* js_RootingAPI_h */ diff --git a/external/spidermonkey/include/win32/js/TemplateLib.h b/external/spidermonkey/include/win32/js/TemplateLib.h deleted file mode 100644 index a4ff682912..0000000000 --- a/external/spidermonkey/include/win32/js/TemplateLib.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_template_lib_h__ -#define js_template_lib_h__ - -#include "jstypes.h" - -/* - * Library of reusable template meta-functions (that is, functions on types and - * compile-time values). Meta-functions are placed inside the 'tl' namespace to - * avoid conflict with non-meta functions that logically have the same name - * (e.g., js::tl::Min vs. js::Min). - */ - -namespace js { -namespace tl { - -/* Compute min/max/clamp. */ -template struct Min { - static const size_t result = i < j ? i : j; -}; -template struct Max { - static const size_t result = i > j ? i : j; -}; -template struct Clamp { - static const size_t result = i < min ? min : (i > max ? max : i); -}; - -/* Compute x^y. */ -template struct Pow { - static const size_t result = x * Pow::result; -}; -template struct Pow { - static const size_t result = 1; -}; - -/* Compute floor(log2(i)). */ -template struct FloorLog2 { - static const size_t result = 1 + FloorLog2::result; -}; -template <> struct FloorLog2<0> { /* Error */ }; -template <> struct FloorLog2<1> { static const size_t result = 0; }; - -/* Compute ceiling(log2(i)). */ -template struct CeilingLog2 { - static const size_t result = FloorLog2<2 * i - 1>::result; -}; - -/* Round up to the nearest power of 2. */ -template struct RoundUpPow2 { - static const size_t result = size_t(1) << CeilingLog2::result; -}; -template <> struct RoundUpPow2<0> { - static const size_t result = 1; -}; - -/* Compute the number of bits in the given unsigned type. */ -template struct BitSize { - static const size_t result = sizeof(T) * JS_BITS_PER_BYTE; -}; - -/* - * Produce an N-bit mask, where N <= BitSize::result. Handle the - * language-undefined edge case when N = BitSize::result. - */ -template struct NBitMask { - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |result| to assure - // its computation. - static const size_t checkPrecondition = 0 / size_t(N < BitSize::result); - static const size_t result = (size_t(1) << N) - 1 + checkPrecondition; -}; -template <> struct NBitMask::result> { - static const size_t result = size_t(-1); -}; - -/* - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template struct MulOverflowMask { - static const size_t result = - ~NBitMask::result - CeilingLog2::result>::result; -}; -template <> struct MulOverflowMask<0> { /* Error */ }; -template <> struct MulOverflowMask<1> { static const size_t result = 0; }; - -/* - * Generate a mask for T such that if (X & sUnsafeRangeSizeMask), an X-sized - * array of T's is big enough to cause a ptrdiff_t overflow when subtracting - * a pointer to the end of the array from the beginning. - */ -template struct UnsafeRangeSizeMask { - /* - * The '2' factor means the top bit is clear, sizeof(T) converts from - * units of elements to bytes. - */ - static const size_t result = MulOverflowMask<2 * sizeof(T)>::result; -}; - -template struct If { static const T result = v1; }; -template struct If { static const T result = v2; }; - -/* - * Traits class for identifying types that are implicitly barriered. - */ -template struct IsRelocatableHeapType { static const bool result = true; }; - -} /* namespace tl */ -} /* namespace js */ - -#endif /* js_template_lib_h__ */ diff --git a/external/spidermonkey/include/win32/js/Utility.h b/external/spidermonkey/include/win32/js/Utility.h index c4ebf7ced6..9d391e5c8a 100644 --- a/external/spidermonkey/include/win32/js/Utility.h +++ b/external/spidermonkey/include/win32/js/Utility.h @@ -4,13 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_utility_h__ -#define js_utility_h__ +#ifndef js_Utility_h +#define js_Utility_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" +#include "mozilla/Move.h" #include "mozilla/Scoped.h" +#include "mozilla/TemplateLib.h" #include #include @@ -22,8 +24,6 @@ #include "jstypes.h" -#include "js/TemplateLib.h" - /* The public JS engine namespace. */ namespace JS {} @@ -41,7 +41,6 @@ namespace js {} #define JS_ASSERT(expr) MOZ_ASSERT(expr) #define JS_ASSERT_IF(cond, expr) MOZ_ASSERT_IF(cond, expr) -#define JS_NOT_REACHED(reason) MOZ_NOT_REACHED(reason) #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) @@ -63,7 +62,7 @@ namespace js {} # define JS_DIAGNOSTICS_ASSERT(expr) ((void) 0) #endif -#define JS_STATIC_ASSERT(cond) MOZ_STATIC_ASSERT(cond, "JS_STATIC_ASSERT") +#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") #define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") extern MOZ_NORETURN JS_PUBLIC_API(void) @@ -84,10 +83,11 @@ extern JS_PUBLIC_API(void) JS_Abort(void); #else # ifdef DEBUG /* - * In order to test OOM conditions, when the shell command-line option - * |-A NUM| is passed, we fail continuously after the NUM'th allocation. + * In order to test OOM conditions, when the testing function + * oomAfterAllocations COUNT is passed, we fail continuously after the NUM'th + * allocation from now. */ -extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set from shell/js.cpp */ +extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set in builtins/TestingFunctions.cpp */ extern JS_PUBLIC_DATA(uint32_t) OOM_counter; /* data race, who cares. */ #ifdef JS_OOM_DO_BACKTRACES @@ -157,6 +157,12 @@ static JS_INLINE void* js_calloc(size_t bytes) return calloc(bytes, 1); } +static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +{ + JS_OOM_POSSIBLY_FAIL(); + return calloc(nmemb, size); +} + static JS_INLINE void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); @@ -169,205 +175,6 @@ static JS_INLINE void js_free(void* p) } #endif/* JS_USE_CUSTOM_ALLOCATOR */ -JS_BEGIN_EXTERN_C - -/* - * Replace bit-scanning code sequences with CPU-specific instructions to - * speedup calculations of ceiling/floor log2. - * - * With GCC 3.4 or later we can use __builtin_clz for that, see bug 327129. - * - * SWS: Added MSVC intrinsic bitscan support. See bugs 349364 and 356856. - */ -#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) - -unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask); -unsigned char _BitScanReverse(unsigned long * Index, unsigned long Mask); -# pragma intrinsic(_BitScanForward,_BitScanReverse) - -__forceinline static int -__BitScanForward32(unsigned int val) -{ - unsigned long idx; - - _BitScanForward(&idx, (unsigned long)val); - return (int)idx; -} -__forceinline static int -__BitScanReverse32(unsigned int val) -{ - unsigned long idx; - - _BitScanReverse(&idx, (unsigned long)val); - return (int)(31-idx); -} -# define js_bitscan_ctz32(val) __BitScanForward32(val) -# define js_bitscan_clz32(val) __BitScanReverse32(val) -# define JS_HAS_BUILTIN_BITSCAN32 - -#if defined(_M_AMD64) || defined(_M_X64) -unsigned char _BitScanForward64(unsigned long * Index, unsigned __int64 Mask); -unsigned char _BitScanReverse64(unsigned long * Index, unsigned __int64 Mask); -# pragma intrinsic(_BitScanForward64,_BitScanReverse64) - -__forceinline static int -__BitScanForward64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanForward64(&idx, val); - return (int)idx; -} -__forceinline static int -__BitScanReverse64(unsigned __int64 val) -{ - unsigned long idx; - - _BitScanReverse64(&idx, val); - return (int)(63-idx); -} -# define js_bitscan_ctz64(val) __BitScanForward64(val) -# define js_bitscan_clz64(val) __BitScanReverse64(val) -# define JS_HAS_BUILTIN_BITSCAN64 -#endif -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(3, 4, 0) -# define USE_BUILTIN_CTZ -#endif - -#elif defined(__clang__) - -#if __has_builtin(__builtin_ctz) -# define USE_BUILTIN_CTZ -#endif - -#endif - -#if defined(USE_BUILTIN_CTZ) -# define js_bitscan_ctz32(val) __builtin_ctz(val) -# define js_bitscan_clz32(val) __builtin_clz(val) -# define JS_HAS_BUILTIN_BITSCAN32 -# if (JS_BYTES_PER_WORD == 8) -# define js_bitscan_ctz64(val) __builtin_ctzll(val) -# define js_bitscan_clz64(val) __builtin_clzll(val) -# define JS_HAS_BUILTIN_BITSCAN64 -# endif - -# undef USE_BUILTIN_CTZ - -#endif - -/* -** Macro version of JS_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use intrinsic function or count-leading-zeros to calculate ceil(log2(_n)). - * The macro checks for "n <= 1" and not "n != 0" as js_bitscan_clz32(0) is - * undefined. - */ -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - unsigned int j_ = (unsigned int)(_n); \ - (_log2) = (j_ <= 1 ? 0 : 32 - js_bitscan_clz32(j_ - 1)); \ - JS_END_MACRO -#else -# define JS_CEILING_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -/* -** Macro version of JS_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#ifdef JS_HAS_BUILTIN_BITSCAN32 -/* - * Use js_bitscan_clz32 or count-leading-zeros to calculate floor(log2(_n)). - * Since js_bitscan_clz32(0) is undefined, the macro set the loweset bit to 1 - * to ensure 0 result when _n == 0. - */ -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - (_log2) = 31 - js_bitscan_clz32(((unsigned int)(_n)) | 1); \ - JS_END_MACRO -#else -# define JS_FLOOR_LOG2(_log2,_n) \ - JS_BEGIN_MACRO \ - uint32_t j_ = (uint32_t)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - JS_END_MACRO -#endif - -#if JS_BYTES_PER_WORD == 4 -# ifdef JS_HAS_BUILTIN_BITSCAN32 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz32(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#elif JS_BYTES_PER_WORD == 8 -# ifdef JS_HAS_BUILTIN_BITSCAN64 -# define js_FloorLog2wImpl(n) \ - ((size_t)(JS_BITS_PER_WORD - 1 - js_bitscan_clz64(n))) -# else -JS_PUBLIC_API(size_t) js_FloorLog2wImpl(size_t n); -# endif -#else -# error "NOT SUPPORTED" -#endif - -JS_END_EXTERN_C - -/* - * Internal function. - * Compute the log of the least power of 2 greater than or equal to n. This is - * a version of JS_CeilingLog2 that operates on unsigned integers with - * CPU-dependant size. - */ -#define JS_CEILING_LOG2W(n) ((n) <= 1 ? 0 : 1 + JS_FLOOR_LOG2W((n) - 1)) - -/* - * Internal function. - * Compute the log of the greatest power of 2 less than or equal to n. - * This is a version of JS_FloorLog2 that operates on unsigned integers with - * CPU-dependant size and requires that n != 0. - */ -static MOZ_ALWAYS_INLINE size_t -JS_FLOOR_LOG2W(size_t n) -{ - JS_ASSERT(n != 0); - return js_FloorLog2wImpl(n); -} - /* * JS_ROTATE_LEFT32 * @@ -552,7 +359,7 @@ template static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_malloc(numElems * sizeof(T)); } @@ -561,7 +368,7 @@ template static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { - if (numElems & js::tl::MulOverflowMask::result) + if (numElems & mozilla::tl::MulOverflowMask::value) return NULL; return (T *)js_calloc(numElems * sizeof(T)); } @@ -595,175 +402,6 @@ SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) namespace js { -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables also need to - * be resized. - * - * The details of the optimization, and whether it's worth applying, vary from - * one type to the next. And while some constructor calls are moves, many really - * are copies, and can't be optimized this way. So we need: - * - * 1) a way for a particular invocation of a copy constructor to say that it's - * really a move, and that the value of the original isn't important - * afterwards (althought it must still be safe to destroy); and - * - * 2) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation. - * - * The Move(T &) function takes a reference to a T, and returns an MoveRef - * referring to the same value; that's 1). An MoveRef is simply a reference - * to a T, annotated to say that a copy constructor applied to it may move that - * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). - * - * So, where we might define a copy constructor for a class C like this: - * - * C(const C &rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(MoveRef rhs) { ... move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)) - * - * Note that MoveRef implicitly converts to T &, so you can pass an - * MoveRef to an ordinary copy constructor for a type that doesn't support a - * special move constructor, and you'll just get a copy. This means that - * templates can use Move whenever they know they won't use the original value - * any more, even if they're not sure whether the type at hand has a specialized - * move constructor. If it doesn't, the MoveRef will just convert to a T &, - * and the ordinary copy constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator, - * which runs this's destructor, and then applies the move constructor to - * *this's memory. A typical definition: - * - * C &operator=(MoveRef rhs) { - * this->~C(); - * new(this) C(rhs); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * This header file defines MoveRef and Move in the js namespace. It's up to - * individual containers to annotate moves as such, by calling Move; and it's up - * to individual types to define move constructors. - * - * One hint: if you're writing a move constructor where the type has members - * that should be moved themselves, it's much nicer to write this: - * - * C(MoveRef c) : x(c->x), y(c->y) { } - * - * than the equivalent: - * - * C(MoveRef c) { new(&x) X(c->x); new(&y) Y(c->y); } - * - * especially since GNU C++ fails to notice that this does indeed initialize x - * and y, which may matter if they're const. - */ -template -class MoveRef { - public: - typedef T Referent; - explicit MoveRef(T &t) : pointer(&t) { } - T &operator*() const { return *pointer; } - T *operator->() const { return pointer; } - operator T& () const { return *pointer; } - private: - T *pointer; -}; - -template -MoveRef Move(T &t) { return MoveRef(t); } - -template -MoveRef Move(const T &t) { return MoveRef(const_cast(t)); } - -/* Useful for implementing containers that assert non-reentrancy */ -class ReentrancyGuard -{ - /* ReentrancyGuard is not copyable. */ - ReentrancyGuard(const ReentrancyGuard &); - void operator=(const ReentrancyGuard &); - -#ifdef DEBUG - bool &entered; -#endif - public: - template -#ifdef DEBUG - ReentrancyGuard(T &obj) - : entered(obj.entered) -#else - ReentrancyGuard(T &/*obj*/) -#endif - { -#ifdef DEBUG - JS_ASSERT(!entered); - entered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - entered = false; -#endif - } -}; - -template -JS_ALWAYS_INLINE static void -Swap(T &t, T &u) -{ - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); -} - -/* - * Round x up to the nearest power of 2. This function assumes that the most - * significant bit of x is not set, which would lead to overflow. - */ -JS_ALWAYS_INLINE size_t -RoundUpPow2(size_t x) -{ - return size_t(1) << JS_CEILING_LOG2W(x); -} - /* Integral types for all hash functions. */ typedef uint32_t HashNumber; const unsigned HashNumberSizeBits = 32; @@ -845,11 +483,6 @@ inline bool IsPoisonedPtr(T *v) } -/* - * This is SpiderMonkey's equivalent to |nsMallocSizeOfFun|. - */ -typedef size_t(*JSMallocSizeOfFun)(const void *p); - /* sixgill annotation defines */ #ifndef HAVE_STATIC_ANNOTATIONS # define HAVE_STATIC_ANNOTATIONS @@ -891,4 +524,4 @@ typedef size_t(*JSMallocSizeOfFun)(const void *p); # define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) #endif /* HAVE_STATIC_ANNOTATIONS */ -#endif /* js_utility_h__ */ +#endif /* js_Utility_h */ diff --git a/external/spidermonkey/include/win32/js/Value.h b/external/spidermonkey/include/win32/js/Value.h index 2c7fa1a600..9b2c5dd6f9 100644 --- a/external/spidermonkey/include/win32/js/Value.h +++ b/external/spidermonkey/include/win32/js/Value.h @@ -6,8 +6,8 @@ /* JS::Value implementation. */ -#ifndef js_Value_h___ -#define js_Value_h___ +#ifndef js_Value_h +#define js_Value_h #include "mozilla/Attributes.h" #include "mozilla/FloatingPoint.h" @@ -53,7 +53,7 @@ namespace JS { class Value; } * nice symbolic type tags, however we can only do this when we can force the * underlying type of the enum to be the desired size. */ -#if defined(__cplusplus) && !defined(__SUNPRO_CC) && !defined(__xlC__) +#if !defined(__SUNPRO_CC) && !defined(__xlC__) #if defined(_MSC_VER) # define JS_ENUM_HEADER(id, type) enum id : type @@ -132,7 +132,7 @@ JS_STATIC_ASSERT(sizeof(JSValueShiftedTag) == sizeof(uint64_t)); #endif -#else /* defined(__cplusplus) */ +#else /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ typedef uint8_t JSValueType; #define JSVAL_TYPE_DOUBLE ((uint8_t)0x00) @@ -180,7 +180,7 @@ typedef uint64_t JSValueShiftedTag; #define JSVAL_SHIFTED_TAG_OBJECT (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT) #endif /* JS_BITS_PER_WORD */ -#endif /* defined(__cplusplus) && !defined(__SUNPRO_CC) */ +#endif /* !defined(__SUNPRO_CC) && !defined(__xlC__) */ #define JSVAL_LOWER_INCL_TYPE_OF_OBJ_OR_NULL_SET JSVAL_TYPE_NULL #define JSVAL_UPPER_EXCL_TYPE_OF_PRIMITIVE_SET JSVAL_TYPE_OBJECT @@ -265,7 +265,7 @@ typedef union jsval_layout typedef union jsval_layout { uint64_t asBits; -#if (!defined(_WIN64) && defined(__cplusplus)) +#if !defined(_WIN64) /* MSVC does not pack these correctly :-( */ struct { uint64_t payload47 : 47; @@ -321,7 +321,6 @@ typedef union jsval_layout int32_t i32; uint32_t u32; JSWhyMagic why; - uintptr_t word; } payload; } s; double asDouble; @@ -803,22 +802,31 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ -static inline double -JS_CANONICALIZE_NAN(double d) -{ - if (MOZ_UNLIKELY(d != d)) { - jsval_layout l; - l.asBits = 0x7FF8000000000000LL; - return l.asDouble; - } - return d; -} - static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +/** + * Returns a generic quiet NaN value, with all payload bits set to zero. + * + * Among other properties, this NaN's bit pattern conforms to JS::Value's + * bit pattern restrictions. + */ +static MOZ_ALWAYS_INLINE double +GenericNaN() +{ + return mozilla::SpecificNaN(0, 0x8000000000000ULL); +} + +static inline double +CanonicalizeNaN(double d) +{ + if (MOZ_UNLIKELY(mozilla::IsNaN(d))) + return GenericNaN(); + return d; +} + /* * JS::Value is the interface for a single JavaScript Engine value. A few * general notes on JS::Value: @@ -1393,22 +1401,35 @@ SameType(const Value &lhs, const Value &rhs) /************************************************************************/ +#ifdef JSGC_GENERATIONAL +namespace JS { +JS_PUBLIC_API(void) HeapValuePostBarrier(Value *valuep); +JS_PUBLIC_API(void) HeapValueRelocate(Value *valuep); +} +#endif + namespace js { -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } }; -template <> struct RootMethods +template <> struct GCMethods { static JS::Value initial() { return JS::UndefinedValue(); } static ThingRootKind kind() { return THING_ROOT_VALUE; } static bool poisoned(const JS::Value &v) { return JS::IsPoisonedValue(v); } + static bool needsPostBarrier(const JS::Value &v) { return v.isMarkable(); } +#ifdef JSGC_GENERATIONAL + static void postBarrier(JS::Value *v) { JS::HeapValuePostBarrier(v); } + static void relocate(JS::Value *v) { JS::HeapValueRelocate(v); } +#endif }; +template class UnbarrieredMutableValueOperations; template class MutableValueOperations; /* @@ -1420,7 +1441,9 @@ template class MutableValueOperations; template class ValueOperations { + friend class UnbarrieredMutableValueOperations; friend class MutableValueOperations; + const JS::Value * value() const { return static_cast(this)->extract(); } public: @@ -1453,19 +1476,22 @@ class ValueOperations void *toGCThing() const { return value()->toGCThing(); } JSValueType extractNonDoubleType() const { return value()->extractNonDoubleType(); } + uint32_t toPrivateUint32() const { return value()->toPrivateUint32(); } JSWhyMagic whyMagic() const { return value()->whyMagic(); } }; /* - * A class designed for CRTP use in implementing the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible extractMutable() and extract() - * methods returning the const Value* and Value* abstracted by Outer. + * A class designed for CRTP use in implementing the mutating parts of the Value + * interface in Value-like classes that don't need post barriers. Outer must be + * a class inheriting UnbarrieredMutableValueOperations with visible + * extractMutable() and extract() methods returning the const Value* and Value* + * abstracted by Outer. */ template -class MutableValueOperations : public ValueOperations +class UnbarrieredMutableValueOperations : public ValueOperations { + friend class MutableValueOperations; JS::Value * value() { return static_cast(this)->extractMutable(); } public: @@ -1473,14 +1499,66 @@ class MutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } - void setString(JSString *str) { value()->setString(str); } - void setString(const JS::Anchor &str) { value()->setString(str); } - void setObject(JSObject &obj) { value()->setObject(obj); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } bool setNumber(double d) { return value()->setNumber(d); } - void setObjectOrNull(JSObject *arg) { value()->setObjectOrNull(arg); } +}; + +/* + * A class designed for CRTP use in implementing all the mutating parts of the + * Value interface in Value-like classes. Outer must be a class inheriting + * MutableValueOperations with visible extractMutable() and extract() + * methods returning the const Value* and Value* abstracted by Outer. + */ +template +class MutableValueOperations : public UnbarrieredMutableValueOperations +{ + public: + void setString(JSString *str) { this->value()->setString(str); } + void setString(const JS::Anchor &str) { this->value()->setString(str); } + void setObject(JSObject &obj) { this->value()->setObject(obj); } + void setObjectOrNull(JSObject *arg) { this->value()->setObjectOrNull(arg); } +}; + +/* + * Augment the generic Heap interface when T = Value with + * type-querying, value-extracting, and mutating operations. + */ +template <> +class HeapBase : public UnbarrieredMutableValueOperations > +{ + typedef JS::Heap Outer; + + friend class ValueOperations; + friend class UnbarrieredMutableValueOperations; + + const JS::Value * extract() const { return static_cast(this)->address(); } + JS::Value * extractMutable() { return static_cast(this)->unsafeGet(); } + + /* + * Setters that potentially change the value to a GC thing from a non-GC + * thing must call JS::Heap::set() to trigger the post barrier. + * + * Changing from a GC thing to a non-GC thing value will leave the heap + * value in the store buffer, but it will be ingored so this is not a + * problem. + */ + void setBarriered(const JS::Value &v) { + static_cast *>(this)->set(v); + } + + public: + void setString(JSString *str) { setBarriered(JS::StringValue(str)); } + void setString(const JS::Anchor &str) { setBarriered(JS::StringValue(str.get())); } + void setObject(JSObject &obj) { setBarriered(JS::ObjectValue(obj)); } + + void setObjectOrNull(JSObject *arg) { + if (arg) + setObject(*arg); + else + setNull(); + } }; /* @@ -1508,6 +1586,7 @@ class MutableHandleBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1526,6 +1605,7 @@ class RootedBase : public MutableValueOperations*>(this)->address(); } + friend class UnbarrieredMutableValueOperations >; friend class MutableValueOperations >; JS::Value * extractMutable() { return static_cast*>(this)->address(); @@ -1574,12 +1654,12 @@ inline Anchor::~Anchor() namespace detail { struct ValueAlignmentTester { char c; JS::Value v; }; -MOZ_STATIC_ASSERT(sizeof(ValueAlignmentTester) == 16, - "JS::Value must be 16-byte-aligned"); +static_assert(sizeof(ValueAlignmentTester) == 16, + "JS::Value must be 16-byte-aligned"); struct LayoutAlignmentTester { char c; jsval_layout l; }; -MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, - "jsval_layout must be 16-byte-aligned"); +static_assert(sizeof(LayoutAlignmentTester) == 16, + "jsval_layout must be 16-byte-aligned"); } // namespace detail #endif /* DEBUG */ @@ -1593,8 +1673,8 @@ MOZ_STATIC_ASSERT(sizeof(LayoutAlignmentTester) == 16, */ typedef JS::Value jsval; -MOZ_STATIC_ASSERT(sizeof(jsval_layout) == sizeof(JS::Value), - "jsval_layout and JS::Value must have identical layouts"); +static_assert(sizeof(jsval_layout) == sizeof(JS::Value), + "jsval_layout and JS::Value must have identical layouts"); /************************************************************************/ @@ -1762,4 +1842,4 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } -#endif /* js_Value_h___ */ +#endif /* js_Value_h */ diff --git a/external/spidermonkey/include/win32/js/Vector.h b/external/spidermonkey/include/win32/js/Vector.h index 5f40dd634b..b14d75c758 100644 --- a/external/spidermonkey/include/win32/js/Vector.h +++ b/external/spidermonkey/include/win32/js/Vector.h @@ -4,14 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsvector_h_ -#define jsvector_h_ +#ifndef js_Vector_h +#define js_Vector_h -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "TemplateLib.h" -#include "Utility.h" +#include "mozilla/Vector.h" /* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ #ifdef _MSC_VER @@ -23,1085 +19,48 @@ namespace js { class TempAllocPolicy; -template +// using Vector = mozilla::Vector; +// +// ...and get rid of all the CRTP madness in mozilla::Vector(Base). But we +// can't because compiler support's not up to snuff. (Template aliases are in +// gcc 4.7 and clang 3.0 and are expected to be in MSVC 2013.) Instead, have a +// completely separate class inheriting from mozilla::Vector, and throw CRTP at +// the problem til things work. +// +// This workaround presents a couple issues. First, because js::Vector is a +// distinct type from mozilla::Vector, overload resolution, method calls, etc. +// are affected. *Hopefully* this won't be too bad in practice. (A bunch of +// places had to be fixed when mozilla::Vector was introduced, but it wasn't a +// crazy number.) Second, mozilla::Vector's interface has to be made subclass- +// ready via CRTP -- or rather, via mozilla::VectorBase, which basically no one +// should use. :-) Third, we have to redefine the constructors and the non- +// inherited operators. Blech. Happily there aren't too many of these, so it +// isn't the end of the world. + +template -class Vector; - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that cap*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring - * this. - */ -template -static bool CapacityHasExcessSpace(size_t cap) +class Vector + : public mozilla::VectorBase > { - size_t size = cap * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* Destroys constructed objects in the range [begin, end). */ - static inline void destroy(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - p->~T(); - } - - /* Constructs objects in the uninitialized range [begin, end). */ - static inline void initialize(T *begin, T *end) { - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - /* - * Copy-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(*p); - } - - /* - * Move-constructs objects in the uninitialized range - * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). - */ - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - new(dst) T(Move(*p)); - } - - /* - * Copy-constructs objects in the uninitialized range [dst, dst+n) from the - * same object u. - */ - template - static inline void copyConstructN(T *dst, size_t n, const U &u) { - for (T *end = dst + n; dst != end; ++dst) - new(dst) T(u); - } - - /* - * Grows the given buffer to have capacity newCap, preserving the objects - * constructed in the range [begin, end) and updating v. Assumes that (1) - * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will - * not overflow. - */ - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); - if (!newbuf) - return false; - for (T *dst = newbuf, *src = v.beginNoCheck(); src != v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); - VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); - v.free_(v.mBegin); - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - static inline void destroy(T *, T *) {} - - static inline void initialize(T *begin, T *end) { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(begin, 0, sizeof(T) * (end-begin)); - */ - for (T *p = begin; p != end; ++p) - new(p) T(); - } - - template - static inline void copyConstruct(T *dst, const U *srcbeg, const U *srcend) { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); - */ - for (const U *p = srcbeg; p != srcend; ++p, ++dst) - *dst = *p; - } - - template - static inline void moveConstruct(T *dst, const U *srcbeg, const U *srcend) { - copyConstruct(dst, srcbeg, srcend); - } - - static inline void copyConstructN(T *dst, size_t n, const T &t) { - for (T *p = dst, *end = dst + n; p != end; ++p) - *p = t; - } - - static inline bool growTo(Vector &v, size_t newCap) { - JS_ASSERT(!v.usingInlineStorage()); - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - size_t oldSize = sizeof(T) * v.mCapacity; - size_t newSize = sizeof(T) * newCap; - T *newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); - if (!newbuf) - return false; - v.mBegin = newbuf; - /* v.mLength is unchanged. */ - v.mCapacity = newCap; - return true; - } -}; - -/* - * JS-friendly, STL-like container providing a short-lived, dynamic buffer. - * Vector calls the constructors/destructors of all elements stored in - * its internal buffer, so non-PODs may be safely used. Additionally, - * Vector will store the first N elements in-place before resorting to - * dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * N requirements: - * - any value, however, N is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in jsalloc.h (default js::TempAllocPolicy) - * - * N.B: Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object. - */ -template -class Vector : private AllocPolicy -{ - // typedef typename tl::StaticAssert::result>::result _; - - /* utilities */ - - static const bool sElemIsPod = mozilla::IsPod::value; - typedef VectorImpl Impl; - friend struct VectorImpl; - - bool growStorageBy(size_t incr); - bool convertToHeapStorage(size_t newCap); - - template inline bool growByImpl(size_t inc); - - /* magic constants */ - - static const int sMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are - * 0 inline elements. This allows us to compile when the definition - * of the element type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so - * in order to keep everything here, we use a dummy template - * parameter with partial specialization. - */ - template - struct ElemSize { - static const size_t result = sizeof(T); - }; - template - struct ElemSize<0, Dummy> { - static const size_t result = 1; - }; - - static const size_t sInlineCapacity = - tl::Min::result>::result; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t sInlineBytes = - tl::Max<1, sInlineCapacity * ElemSize::result>::result; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T *mBegin; - size_t mLength; /* Number of elements in the Vector. */ - size_t mCapacity; /* Max number of elements storable in the Vector without resizing. */ -#ifdef DEBUG - size_t mReserved; /* Max elements of reserved or used space in this vector. */ -#endif - - mozilla::AlignedStorage storage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool entered; -#endif - - Vector(const Vector &) MOZ_DELETE; - Vector &operator=(const Vector &) MOZ_DELETE; - - /* private accessors */ - - bool usingInlineStorage() const { - return mBegin == inlineStorage(); - } - - T *inlineStorage() const { - return (T *)storage.addr(); - } - - T *beginNoCheck() const { - return mBegin; - } - - T *endNoCheck() { - return mBegin + mLength; - } - - const T *endNoCheck() const { - return mBegin + mLength; - } - -#ifdef DEBUG - size_t reserved() const { - JS_ASSERT(mReserved <= mCapacity); - JS_ASSERT(mLength <= mReserved); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U u); - void internalAppendN(const T &t, size_t n); - template void internalAppend(const U *begin, size_t length); - template void internalAppend(const Vector &other); + typedef typename mozilla::VectorBase Base; public: - static const size_t sMaxInlineStorage = N; - - typedef T ElementType; - - Vector(AllocPolicy = AllocPolicy()); - Vector(MoveRef); /* Move constructor. */ - Vector &operator=(MoveRef); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy &allocPolicy() const { - return *this; + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector &operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); } - - AllocPolicy &allocPolicy() { - return *this; - } - - enum { InlineLength = N }; - - size_t length() const { - return mLength; - } - - bool empty() const { - return mLength == 0; - } - - size_t capacity() const { - return mCapacity; - } - - T *begin() { - JS_ASSERT(!entered); - return mBegin; - } - - const T *begin() const { - JS_ASSERT(!entered); - return mBegin; - } - - T *end() { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - const T *end() const { - JS_ASSERT(!entered); - return mBegin + mLength; - } - - T &operator[](size_t i) { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - const T &operator[](size_t i) const { - JS_ASSERT(!entered && i < mLength); - return begin()[i]; - } - - T &back() { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - const T &back() const { - JS_ASSERT(!entered && !empty()); - return *(end() - 1); - } - - class Range { - friend class Vector; - T *cur_, *end_; - Range(T *cur, T *end) : cur_(cur), end_(end) {} - public: - Range() {} - bool empty() const { return cur_ == end_; } - size_t remain() const { return end_ - cur_; } - T &front() const { return *cur_; } - void popFront() { JS_ASSERT(!empty()); ++cur_; } - T popCopyFront() { JS_ASSERT(!empty()); return *cur_++; } - }; - - Range all() { - return Range(begin(), end()); - } - - /* mutators */ - - /* Given that the Vector is empty and has no inline storage, grow to |capacity|. */ - bool initCapacity(size_t request); - - /* If reserve(length() + N) succeeds, the N next appends are guaranteed to succeed. */ - bool reserve(size_t request); - - /* - * Destroy elements in the range [end() - incr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t incr); - - /* Grow the vector by incr elements. */ - bool growBy(size_t incr); - - /* Call shrinkBy or growBy based on whether newSize > length(). */ - bool resize(size_t newLength); - - /* Leave new elements as uninitialized memory. */ - bool growByUninitialized(size_t incr); - bool resizeUninitialized(size_t newLength); - - /* Shorthand for shrinkBy(length()). */ - void clear(); - - /* Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /* If true, appending |needed| elements will not call realloc(). */ - bool canAppendWithoutRealloc(size_t needed) const; - - /* - * Potentially fallible append operations. - * - * The function templates that take an unspecified type U require a - * const T & or a MoveRef. The MoveRef variants move their - * operands into the vector, instead of copying them. If they fail, the - * operand is left unmoved. - */ - template bool append(U t); - bool appendN(const T &t, size_t n); - template bool append(const U *begin, const U *end); - template bool append(const U *begin, size_t length); - template bool append(const Vector &other); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. - */ - template void infallibleAppend(const U &u) { - internalAppend(u); - } - void infallibleAppendN(const T &t, size_t n) { - internalAppendN(t, n); - } - template void infallibleAppend(const U *aBegin, const U *aEnd) { - internalAppend(aBegin, mozilla::PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U *aBegin, size_t aLength) { - internalAppend(aBegin, aLength); - } - template void infallibleAppend(const Vector &other) { - internalAppend(other); - } - - void popBack(); - - T popCopy(); - - /* - * Transfers ownership of the internal buffer used by Vector to the caller. - * After this call, the Vector is empty. Since the returned buffer may need - * to be allocated (if the elements are currently stored in-place), the - * call can fail, returning NULL. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - T *extractRawBuffer(); - - /* - * Transfer ownership of an array of objects into the Vector. - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T *p, size_t length); - - /* - * Places |val| at position |p|, shifting existing elements from |p| - * onward one position higher. On success, |p| should not be reused - * because it will be a dangling pointer if reallocation of the vector - * storage occurred; the return value should be used instead. On failure, - * NULL is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) - * - * - */ - T *insert(T *p, const T &val); - - /* - * Removes the element |t|, which must fall in the bounds [begin, end), - * shifting existing elements from |t + 1| onward one position lower. - */ - void erase(T *t); - - /* - * Measure the size of the Vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - /* - * Like sizeOfExcludingThis, but also measures the size of the Vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const; - - void swap(Vector &other); }; -/* This does the re-entrancy check plus several other sanity checks. */ -#define REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - JS_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ - JS_ASSERT(reserved() <= mCapacity); \ - JS_ASSERT(mLength <= reserved()); \ - JS_ASSERT(mLength <= mCapacity) +} // namespace js -/* Vector Implementation */ - -template -JS_ALWAYS_INLINE -Vector::Vector(AllocPolicy ap) - : AllocPolicy(ap), mBegin((T *)storage.addr()), mLength(0), - mCapacity(sInlineCapacity) -#ifdef DEBUG - , mReserved(sInlineCapacity), entered(false) -#endif -{} - -/* Move constructor. */ -template -JS_ALWAYS_INLINE -Vector::Vector(MoveRef rhs) - : AllocPolicy(rhs) -#ifdef DEBUG - , entered(false) -#endif -{ - mLength = rhs->mLength; - mCapacity = rhs->mCapacity; -#ifdef DEBUG - mReserved = rhs->mReserved; -#endif - - if (rhs->usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = (T *)storage.addr(); - Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); - /* - * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = rhs->mBegin; - rhs->mBegin = (T *) rhs->storage.addr(); - rhs->mCapacity = sInlineCapacity; - rhs->mLength = 0; -#ifdef DEBUG - rhs->mReserved = sInlineCapacity; -#endif - } -} - -/* Move assignment. */ -template -JS_ALWAYS_INLINE -Vector & -Vector::operator=(MoveRef rhs) -{ - this->~Vector(); - new(this) Vector(rhs); - return *this; -} - -template -JS_ALWAYS_INLINE -Vector::~Vector() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); -} - -/* - * This function will create a new heap buffer with capacity newCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t newCap) -{ - JS_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - JS_ASSERT(!CapacityHasExcessSpace(newCap)); - T *newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); - if (!newBuf) - return false; - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = newCap; - return true; -} - -template -JS_NEVER_INLINE bool -Vector::growStorageBy(size_t incr) -{ - JS_ASSERT(mLength + incr > mCapacity); - JS_ASSERT_IF(!usingInlineStorage(), !CapacityHasExcessSpace(mCapacity)); - - /* - * When choosing a new capacity, its size should is as close to 2^N bytes - * as possible. 2^N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2^N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2^N request size. - */ - - size_t newCap; - - if (incr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::result; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength*4*sizeof(T) overflow? This condition limits a Vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. - * It also ensures that the ((char *)end() - (char *)begin()) does not - * overflow ptrdiff_t (see Bug 510319). - */ - if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::result) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is - * already as close to 2^N as sizeof(T) will allow. Just double the - * capacity, and then there might be space for one more element. - */ - newCap = mLength * 2; - if (CapacityHasExcessSpace(newCap)) - newCap += 1; - - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + incr; - - /* Did mLength+incr overflow? Will newCap*sizeof(T) overflow? */ - if (newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::result) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { - convert: - return convertToHeapStorage(newCap); - } - - grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t request) -{ - JS_ASSERT(empty()); - JS_ASSERT(usingInlineStorage()); - if (request == 0) - return true; - T *newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); - if (!newbuf) - return false; - mBegin = newbuf; - mCapacity = request; -#ifdef DEBUG - mReserved = request; -#endif - return true; -} - -template -inline bool -Vector::reserve(size_t request) -{ - REENTRANCY_GUARD_ET_AL; - if (request > mCapacity && !growStorageBy(request - mLength)) - return false; - -#ifdef DEBUG - if (request > mReserved) - mReserved = request; - JS_ASSERT(mLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(incr <= mLength); - Impl::destroy(endNoCheck() - incr, endNoCheck()); - mLength -= incr; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::growByImpl(size_t incr) -{ - REENTRANCY_GUARD_ET_AL; - if (incr > mCapacity - mLength && !growStorageBy(incr)) - return false; - - JS_ASSERT(mLength + incr <= mCapacity); - T *newend = endNoCheck() + incr; - if (InitNewElems) - Impl::initialize(endNoCheck(), newend); - mLength += incr; -#ifdef DEBUG - if (mLength > mReserved) - mReserved = mLength; -#endif - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::growBy(size_t incr) -{ - return growByImpl(incr); -} - -template -JS_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t incr) -{ - return growByImpl(incr); -} - -template -STATIC_POSTCONDITION(!return || ubound(this->begin()) >= newLength) -inline bool -Vector::resize(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growBy(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -JS_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t newLength) -{ - size_t curLength = mLength; - if (newLength > curLength) - return growByUninitialized(newLength - curLength); - shrinkBy(curLength - newLength); - return true; -} - -template -inline void -Vector::clear() -{ - REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) - return; - - this->free_(beginNoCheck()); - mBegin = (T *)storage.addr(); - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t needed) const -{ - return mLength + needed <= mCapacity; -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(U t) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity && !growStorageBy(1)) - return false; - -#ifdef DEBUG - if (mLength + 1 > mReserved) - mReserved = mLength + 1; -#endif - internalAppend(t); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(U u) -{ - JS_ASSERT(mLength + 1 <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - new(endNoCheck()) T(u); - ++mLength; -} - -template -JS_ALWAYS_INLINE bool -Vector::appendN(const T &t, size_t needed) -{ - REENTRANCY_GUARD_ET_AL; - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppendN(t, needed); - return true; -} - -template -JS_ALWAYS_INLINE void -Vector::internalAppendN(const T &t, size_t needed) -{ - JS_ASSERT(mLength + needed <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), needed, t); - mLength += needed; -} - -template -inline T * -Vector::insert(T *p, const T &val) -{ - JS_ASSERT(begin() <= p && p <= end()); - size_t pos = p - begin(); - JS_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(val)) - return NULL; - } else { - T oldBack = back(); - if (!append(oldBack)) /* Dup the last element. */ - return NULL; - for (size_t i = oldLength; i > pos; --i) - (*this)[i] = (*this)[i - 1]; - (*this)[pos] = val; - } - return begin() + pos; -} - -template -inline void -Vector::erase(T *it) -{ - JS_ASSERT(begin() <= it && it < end()); - while (it + 1 != end()) { - *it = *(it + 1); - ++it; - } - popBack(); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, const U *insEnd) -{ - REENTRANCY_GUARD_ET_AL; - size_t needed = mozilla::PointerRangeSize(insBegin, insEnd); - if (mLength + needed > mCapacity && !growStorageBy(needed)) - return false; - -#ifdef DEBUG - if (mLength + needed > mReserved) - mReserved = mLength + needed; -#endif - internalAppend(insBegin, needed); - return true; -} - -template -template -JS_ALWAYS_INLINE void -Vector::internalAppend(const U *insBegin, size_t insLength) -{ - JS_ASSERT(mLength + insLength <= mReserved); - JS_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); - mLength += insLength; -} - -template -template -inline bool -Vector::append(const Vector &other) -{ - return append(other.begin(), other.end()); -} - -template -template -inline void -Vector::internalAppend(const Vector &other) -{ - internalAppend(other.begin(), other.length()); -} - -template -template -JS_ALWAYS_INLINE bool -Vector::append(const U *insBegin, size_t insLength) -{ - return this->append(insBegin, insBegin + insLength); -} - -template -JS_ALWAYS_INLINE void -Vector::popBack() -{ - REENTRANCY_GUARD_ET_AL; - JS_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -JS_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T * -Vector::extractRawBuffer() -{ - T *ret; - if (usingInlineStorage()) { - ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); - if (!ret) - return NULL; - Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - /* mBegin, mCapacity are unchanged. */ - mLength = 0; - } else { - ret = mBegin; - mBegin = (T *)storage.addr(); - mLength = 0; - mCapacity = sInlineCapacity; -#ifdef DEBUG - mReserved = sInlineCapacity; -#endif - } - return ret; -} - -template -inline void -Vector::replaceRawBuffer(T *p, size_t aLength) -{ - REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) - this->free_(beginNoCheck()); - - /* Take in the new buffer. */ - if (aLength <= sInlineCapacity) { - /* - * We convert to inline storage if possible, even though p might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = (T *)storage.addr(); - mLength = aLength; - mCapacity = sInlineCapacity; - Impl::moveConstruct(mBegin, p, p + aLength); - Impl::destroy(p, p + aLength); - this->free_(p); - } else { - mBegin = p; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(JSMallocSizeOfFun mallocSizeOf) const -{ - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); -} - -template -inline void -Vector::swap(Vector &other) -{ - // TODO Implement N != 0 - JS_STATIC_ASSERT(N == 0); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && other.usingInlineStorage()) { - other.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !other.usingInlineStorage()) { - mBegin = other.mBegin; - other.mBegin = other.inlineStorage(); - } else if (!usingInlineStorage() && !other.usingInlineStorage()) { - Swap(mBegin, other.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, other.mLength); - Swap(mCapacity, other.mCapacity); -#ifdef DEBUG - Swap(mReserved, other.mReserved); -#endif -} - -} /* namespace js */ - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* jsvector_h_ */ +#endif /* js_Vector_h */ diff --git a/external/spidermonkey/include/win32/jsalloc.h b/external/spidermonkey/include/win32/jsalloc.h index e7e64fc540..3abc4966d1 100644 --- a/external/spidermonkey/include/win32/jsalloc.h +++ b/external/spidermonkey/include/win32/jsalloc.h @@ -4,32 +4,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsalloc_h_ -#define jsalloc_h_ +/* JS allocation policies. */ + +#ifndef jsalloc_h +#define jsalloc_h + +#include "mozilla/AllocPolicy.h" #include "js/Utility.h" -#include "jstypes.h" struct JSContext; namespace js { -/* - * Allocation policies. These model the concept: - * - public copy constructor, assignment, destructor - * - void *malloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *calloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * - void *realloc_(size_t) - * Responsible for OOM reporting on NULL return value. - * The *used* bytes of the previous buffer is passed in - * (rather than the old allocation size), in addition to - * the *new* allocation size requested. - * - void free_(void *) - * - reportAllocOverflow() - * Called on overflow before the container returns NULL. - */ +class ContextFriendFields; /* Policy for using system memory functions and doing no error reporting. */ class SystemAllocPolicy @@ -53,7 +41,7 @@ class SystemAllocPolicy */ class TempAllocPolicy { - JSContext *const cx_; + ContextFriendFields *const cx_; /* * Non-inline helper to call JSRuntime::onOutOfMemory with minimal @@ -62,11 +50,8 @@ class TempAllocPolicy JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes); public: - TempAllocPolicy(JSContext *cx) : cx_(cx) {} - - JSContext *context() const { - return cx_; - } + TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :( + TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {} void *malloc_(size_t bytes) { void *p = js_malloc(bytes); @@ -98,4 +83,4 @@ class TempAllocPolicy } /* namespace js */ -#endif /* jsalloc_h_ */ +#endif /* jsalloc_h */ diff --git a/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id index db9dbac6b4..27b6bbed78 100644 --- a/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -0ec74a6f5f2aa9bbaa6a8cbf6e2ae95ec7c4ee43 \ No newline at end of file +e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file diff --git a/external/spidermonkey/include/win32/jsclass.h b/external/spidermonkey/include/win32/jsclass.h index c9b53c7679..def641715d 100644 --- a/external/spidermonkey/include/win32/jsclass.h +++ b/external/spidermonkey/include/win32/jsclass.h @@ -4,14 +4,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclass_h__ -#define jsclass_h__ +#ifndef jsclass_h +#define jsclass_h /* * A JSClass acts as a vtable for JS objects that allows JSAPI clients to * control various aspects of the behavior of an object like property lookup. * js::Class is an engine-private extension that allows more control over * object behavior and, e.g., allows custom slow layout. */ + #include "jsapi.h" #include "jsprvtd.h" @@ -21,6 +22,10 @@ class PropertyName; class SpecialId; class PropertyId; +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; + static JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); @@ -195,7 +200,7 @@ typedef void const char *name; \ uint32_t flags; \ \ - /* Mandatory non-null function pointer members. */ \ + /* Mandatory function pointer members. */ \ JSPropertyOp addProperty; \ JSDeletePropertyOp delProperty; \ JSPropertyOp getProperty; \ @@ -203,9 +208,9 @@ typedef void JSEnumerateOp enumerate; \ JSResolveOp resolve; \ JSConvertOp convert; \ - FinalizeOp finalize; \ \ - /* Optionally non-null members start here. */ \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ JSCheckAccessOp checkAccess; \ JSNative call; \ JSHasInstanceOp hasInstance; \ @@ -214,7 +219,7 @@ typedef void /* * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to padd js::Class to match the size of JSClass; + * we have to pad js::Class to match the size of JSClass. */ struct ClassSizeMeasurement { @@ -312,8 +317,9 @@ struct Class return flags & JSCLASS_EMULATES_UNDEFINED; } - /* Defined in jsfuninlines.h */ - inline bool isCallable() const; + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } static size_t offsetOfFlags() { return offsetof(Class, flags); } }; @@ -387,7 +393,7 @@ IsPoisonedSpecialId(js::SpecialId iden) return false; } -template <> struct RootMethods +template <> struct GCMethods { static SpecialId initial() { return SpecialId(); } static ThingRootKind kind() { return THING_ROOT_ID; } @@ -396,4 +402,4 @@ template <> struct RootMethods } /* namespace js */ -#endif /* jsclass_h__ */ +#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/win32/jsclist.h b/external/spidermonkey/include/win32/jsclist.h index 8782307fa4..23da9b8cd5 100644 --- a/external/spidermonkey/include/win32/jsclist.h +++ b/external/spidermonkey/include/win32/jsclist.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsclist_h___ -#define jsclist_h___ +#ifndef jsclist_h +#define jsclist_h #include "jstypes.h" @@ -104,4 +104,4 @@ typedef struct JSCListStr { #define JS_INIT_STATIC_CLIST(_l) \ {(_l), (_l)} -#endif /* jsclist_h___ */ +#endif /* jsclist_h */ diff --git a/external/spidermonkey/include/win32/jscpucfg.h b/external/spidermonkey/include/win32/jscpucfg.h index 6bb62b420f..c79bd7ad14 100644 --- a/external/spidermonkey/include/win32/jscpucfg.h +++ b/external/spidermonkey/include/win32/jscpucfg.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef js_cpucfg___ -#define js_cpucfg___ +#ifndef jscpucfg_h +#define jscpucfg_h #define JS_HAVE_LONG_LONG @@ -114,4 +114,4 @@ # endif #endif -#endif /* js_cpucfg___ */ +#endif /* jscpucfg_h */ diff --git a/external/spidermonkey/include/win32/jsdbgapi.h b/external/spidermonkey/include/win32/jsdbgapi.h index 4907d913a0..0ce7101337 100644 --- a/external/spidermonkey/include/win32/jsdbgapi.h +++ b/external/spidermonkey/include/win32/jsdbgapi.h @@ -4,12 +4,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsdbgapi_h___ -#define jsdbgapi_h___ +#ifndef jsdbgapi_h +#define jsdbgapi_h /* * JS debugger API. */ -#include "jsapi.h" + #include "jsprvtd.h" namespace JS { @@ -111,7 +111,7 @@ JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, JSTrapHandler *handlerp, jsval *closurep); extern JS_PUBLIC_API(void) -JS_ClearScriptTraps(JSContext *cx, JSScript *script); +JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); @@ -224,12 +224,6 @@ JS_GetScriptLineExtent(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(JSVersion) JS_GetScriptVersion(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(bool) -JS_GetScriptUserBit(JSScript *script); - -extern JS_PUBLIC_API(void) -JS_SetScriptUserBit(JSScript *script, bool b); - extern JS_PUBLIC_API(bool) JS_GetScriptIsSelfHosted(JSScript *script); @@ -433,9 +427,6 @@ JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ -extern JS_FRIEND_API(void) -js_RevertVersion(JSContext *cx); - extern JS_PUBLIC_API(const JSDebugHooks *) JS_GetGlobalDebugHooks(JSRuntime *rt); @@ -465,4 +456,4 @@ JS_DumpCompartmentPCCounts(JSContext *cx); extern JS_FRIEND_API(JSBool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h___ */ +#endif /* jsdbgapi_h */ diff --git a/external/spidermonkey/include/win32/jsdhash.h b/external/spidermonkey/include/win32/jsdhash.h deleted file mode 100644 index 1f7830fd2b..0000000000 --- a/external/spidermonkey/include/win32/jsdhash.h +++ /dev/null @@ -1,612 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsdhash_h___ -#define jsdhash_h___ - -/* - * Double hashing, a la Knuth 6. - * - * Try to keep this file in sync with xpcom/glue/pldhash.h. - */ -#include "jstypes.h" -#include "jsutil.h" - -#if defined(__GNUC__) && defined(__i386__) && !defined(XP_OS2) -#define JS_DHASH_FASTCALL __attribute__ ((regparm (3),stdcall)) -#elif defined(XP_WIN) -#define JS_DHASH_FASTCALL __fastcall -#else -#define JS_DHASH_FASTCALL -#endif - -#ifdef DEBUG_XXXbrendan -#define JS_DHASHMETER 1 -#endif - -/* Table size limit, do not equal or exceed (see min&maxAlphaFrac, below). */ -#undef JS_DHASH_SIZE_LIMIT -#define JS_DHASH_SIZE_LIMIT JS_BIT(24) - -/* Minimum table size, or gross entry count (net is at most .75 loaded). */ -#ifndef JS_DHASH_MIN_SIZE -#define JS_DHASH_MIN_SIZE 16 -#elif (JS_DHASH_MIN_SIZE & (JS_DHASH_MIN_SIZE - 1)) != 0 -#error "JS_DHASH_MIN_SIZE must be a power of two!" -#endif - -/* - * Multiplicative hash uses an unsigned 32 bit integer and the golden ratio, - * expressed as a fixed-point 32-bit fraction. - */ -#define JS_DHASH_BITS 32 -#define JS_DHASH_GOLDEN_RATIO 0x9E3779B9U - -/* Primitive and forward-struct typedefs. */ -typedef uint32_t JSDHashNumber; -typedef struct JSDHashEntryHdr JSDHashEntryHdr; -typedef struct JSDHashEntryStub JSDHashEntryStub; -typedef struct JSDHashTable JSDHashTable; -typedef struct JSDHashTableOps JSDHashTableOps; - -/* - * Table entry header structure. - * - * In order to allow in-line allocation of key and value, we do not declare - * either here. Instead, the API uses const void *key as a formal parameter. - * The key need not be stored in the entry; it may be part of the value, but - * need not be stored at all. - * - * Callback types are defined below and grouped into the JSDHashTableOps - * structure, for single static initialization per hash table sub-type. - * - * Each hash table sub-type should nest the JSDHashEntryHdr structure at the - * front of its particular entry type. The keyHash member contains the result - * of multiplying the hash code returned from the hashKey callback (see below) - * by JS_DHASH_GOLDEN_RATIO, then constraining the result to avoid the magic 0 - * and 1 values. The stored keyHash value is table size invariant, and it is - * maintained automatically by JS_DHashTableOperate -- users should never set - * it, and its only uses should be via the entry macros below. - * - * The JS_DHASH_ENTRY_IS_LIVE macro tests whether entry is neither free nor - * removed. An entry may be either busy or free; if busy, it may be live or - * removed. Consumers of this API should not access members of entries that - * are not live. - * - * However, use JS_DHASH_ENTRY_IS_BUSY for faster liveness testing of entries - * returned by JS_DHashTableOperate, as JS_DHashTableOperate never returns a - * non-live, busy (i.e., removed) entry pointer to its caller. See below for - * more details on JS_DHashTableOperate's calling rules. - */ -struct JSDHashEntryHdr { - JSDHashNumber keyHash; /* every entry must begin like this */ -}; - -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_FREE(JSDHashEntryHdr* entry) -{ - return entry->keyHash == 0; -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_BUSY(JSDHashEntryHdr* entry) -{ - return !JS_DHASH_ENTRY_IS_FREE(entry); -} -MOZ_ALWAYS_INLINE bool -JS_DHASH_ENTRY_IS_LIVE(JSDHashEntryHdr* entry) -{ - return entry->keyHash >= 2; -} - -/* - * A JSDHashTable is currently 8 words (without the JS_DHASHMETER overhead) - * on most architectures, and may be allocated on the stack or within another - * structure or class (see below for the Init and Finish functions to use). - * - * To decide whether to use double hashing vs. chaining, we need to develop a - * trade-off relation, as follows: - * - * Let alpha be the load factor, esize the entry size in words, count the - * entry count, and pow2 the power-of-two table size in entries. - * - * (JSDHashTable overhead) > (JSHashTable overhead) - * (unused table entry space) > (malloc and .next overhead per entry) + - * (buckets overhead) - * (1 - alpha) * esize * pow2 > 2 * count + pow2 - * - * Notice that alpha is by definition (count / pow2): - * - * (1 - alpha) * esize * pow2 > 2 * alpha * pow2 + pow2 - * (1 - alpha) * esize > 2 * alpha + 1 - * - * esize > (1 + 2 * alpha) / (1 - alpha) - * - * This assumes both tables must keep keyHash, key, and value for each entry, - * where key and value point to separately allocated strings or structures. - * If key and value can be combined into one pointer, then the trade-off is: - * - * esize > (1 + 3 * alpha) / (1 - alpha) - * - * If the entry value can be a subtype of JSDHashEntryHdr, rather than a type - * that must be allocated separately and referenced by an entry.value pointer - * member, and provided key's allocation can be fused with its entry's, then - * k (the words wasted per entry with chaining) is 4. - * - * To see these curves, feed gnuplot input like so: - * - * gnuplot> f(x,k) = (1 + k * x) / (1 - x) - * gnuplot> plot [0:.75] f(x,2), f(x,3), f(x,4) - * - * For k of 2 and a well-loaded table (alpha > .5), esize must be more than 4 - * words for chaining to be more space-efficient than double hashing. - * - * Solving for alpha helps us decide when to shrink an underloaded table: - * - * esize > (1 + k * alpha) / (1 - alpha) - * esize - alpha * esize > 1 + k * alpha - * esize - 1 > (k + esize) * alpha - * (esize - 1) / (k + esize) > alpha - * - * alpha < (esize - 1) / (esize + k) - * - * Therefore double hashing should keep alpha >= (esize - 1) / (esize + k), - * assuming esize is not too large (in which case, chaining should probably be - * used for any alpha). For esize=2 and k=3, we want alpha >= .2; for esize=3 - * and k=2, we want alpha >= .4. For k=4, esize could be 6, and alpha >= .5 - * would still obtain. See the JS_DHASH_MIN_ALPHA macro further below. - * - * The current implementation uses a configurable lower bound on alpha, which - * defaults to .25, when deciding to shrink the table (while still respecting - * JS_DHASH_MIN_SIZE). - * - * Note a qualitative difference between chaining and double hashing: under - * chaining, entry addresses are stable across table shrinks and grows. With - * double hashing, you can't safely hold an entry pointer and use it after an - * ADD or REMOVE operation, unless you sample table->generation before adding - * or removing, and compare the sample after, dereferencing the entry pointer - * only if table->generation has not changed. - * - * The moral of this story: there is no one-size-fits-all hash table scheme, - * but for small table entry size, and assuming entry address stability is not - * required, double hashing wins. - */ -struct JSDHashTable { - const JSDHashTableOps *ops; /* virtual operations, see below */ - void *data; /* ops- and instance-specific data */ - int16_t hashShift; /* multiplicative hash shift */ - uint8_t maxAlphaFrac; /* 8-bit fixed point max alpha */ - uint8_t minAlphaFrac; /* 8-bit fixed point min alpha */ - uint32_t entrySize; /* number of bytes in an entry */ - uint32_t entryCount; /* number of entries in table */ - uint32_t removedCount; /* removed entry sentinels in table */ - uint32_t generation; /* entry storage generation number */ - char *entryStore; /* entry storage */ -#ifdef JS_DHASHMETER - struct JSDHashStats { - uint32_t searches; /* total number of table searches */ - uint32_t steps; /* hash chain links traversed */ - uint32_t hits; /* searches that found key */ - uint32_t misses; /* searches that didn't find key */ - uint32_t lookups; /* number of JS_DHASH_LOOKUPs */ - uint32_t addMisses; /* adds that miss, and do work */ - uint32_t addOverRemoved; /* adds that recycled a removed entry */ - uint32_t addHits; /* adds that hit an existing entry */ - uint32_t addFailures; /* out-of-memory during add growth */ - uint32_t removeHits; /* removes that hit, and do work */ - uint32_t removeMisses; /* useless removes that miss */ - uint32_t removeFrees; /* removes that freed entry directly */ - uint32_t removeEnums; /* removes done by Enumerate */ - uint32_t grows; /* table expansions */ - uint32_t shrinks; /* table contractions */ - uint32_t compresses; /* table compressions */ - uint32_t enumShrinks; /* contractions after Enumerate */ - } stats; -#endif -}; - -/* - * Size in entries (gross, not net of free and removed sentinels) for table. - * We store hashShift rather than sizeLog2 to optimize the collision-free case - * in SearchTable. - */ -#define JS_DHASH_TABLE_SIZE(table) JS_BIT(JS_DHASH_BITS - (table)->hashShift) - -/* - * Table space at entryStore is allocated and freed using these callbacks. - * The allocator should return null on error only (not if called with nbytes - * equal to 0; but note that jsdhash.c code will never call with 0 nbytes). - */ -typedef void * -(* JSDHashAllocTable)(JSDHashTable *table, uint32_t nbytes); - -typedef void -(* JSDHashFreeTable) (JSDHashTable *table, void *ptr); - -/* - * Compute the hash code for a given key to be looked up, added, or removed - * from table. A hash code may have any JSDHashNumber value. - */ -typedef JSDHashNumber -(* JSDHashHashKey) (JSDHashTable *table, const void *key); - -/* - * Compare the key identifying entry in table with the provided key parameter. - * Return JS_TRUE if keys match, JS_FALSE otherwise. - */ -typedef JSBool -(* JSDHashMatchEntry)(JSDHashTable *table, const JSDHashEntryHdr *entry, - const void *key); - -/* - * Copy the data starting at from to the new entry storage at to. Do not add - * reference counts for any strong references in the entry, however, as this - * is a "move" operation: the old entry storage at from will be freed without - * any reference-decrementing callback shortly. - */ -typedef void -(* JSDHashMoveEntry)(JSDHashTable *table, const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -/* - * Clear the entry and drop any strong references it holds. This callback is - * invoked during a JS_DHASH_REMOVE operation (see below for operation codes), - * but only if the given key is found in the table. - */ -typedef void -(* JSDHashClearEntry)(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Called when a table (whether allocated dynamically by itself, or nested in - * a larger structure, or allocated on the stack) is finished. This callback - * allows table->ops-specific code to finalize table->data. - */ -typedef void -(* JSDHashFinalize) (JSDHashTable *table); - -/* - * Initialize a new entry, apart from keyHash. This function is called when - * JS_DHashTableOperate's JS_DHASH_ADD case finds no existing entry for the - * given key, and must add a new one. At that point, entry->keyHash is not - * set yet, to avoid claiming the last free entry in a severely overloaded - * table. - */ -typedef JSBool -(* JSDHashInitEntry)(JSDHashTable *table, JSDHashEntryHdr *entry, - const void *key); - -/* - * Finally, the "vtable" structure for JSDHashTable. The first eight hooks - * must be provided by implementations; they're called unconditionally by the - * generic jsdhash.c code. Hooks after these may be null. - * - * Summary of allocation-related hook usage with C++ placement new emphasis: - * allocTable Allocate raw bytes with malloc, no ctors run. - * freeTable Free raw bytes with free, no dtors run. - * initEntry Call placement new using default key-based ctor. - * Return JS_TRUE on success, JS_FALSE on error. - * moveEntry Call placement new using copy ctor, run dtor on old - * entry storage. - * clearEntry Run dtor on entry. - * finalize Stub unless table->data was initialized and needs to - * be finalized. - * - * Note the reason why initEntry is optional: the default hooks (stubs) clear - * entry storage: On successful JS_DHashTableOperate(tbl, key, JS_DHASH_ADD), - * the returned entry pointer addresses an entry struct whose keyHash member - * has been set non-zero, but all other entry members are still clear (null). - * JS_DHASH_ADD callers can test such members to see whether the entry was - * newly created by the JS_DHASH_ADD call that just succeeded. If placement - * new or similar initialization is required, define an initEntry hook. Of - * course, the clearEntry hook must zero or null appropriately. - * - * XXX assumes 0 is null for pointer types. - */ -struct JSDHashTableOps { - /* Mandatory hooks. All implementations must provide these. */ - JSDHashAllocTable allocTable; - JSDHashFreeTable freeTable; - JSDHashHashKey hashKey; - JSDHashMatchEntry matchEntry; - JSDHashMoveEntry moveEntry; - JSDHashClearEntry clearEntry; - JSDHashFinalize finalize; - - /* Optional hooks start here. If null, these are not called. */ - JSDHashInitEntry initEntry; -}; - -/* - * Default implementations for the above ops. - */ -extern JS_PUBLIC_API(void *) -JS_DHashAllocTable(JSDHashTable *table, uint32_t nbytes); - -extern JS_PUBLIC_API(void) -JS_DHashFreeTable(JSDHashTable *table, void *ptr); - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashStringKey(JSDHashTable *table, const void *key); - -/* A minimal entry contains a keyHash header and a void key pointer. */ -struct JSDHashEntryStub { - JSDHashEntryHdr hdr; - const void *key; -}; - -extern JS_PUBLIC_API(JSDHashNumber) -JS_DHashVoidPtrKeyStub(JSDHashTable *table, const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(JSBool) -JS_DHashMatchStringKey(JSDHashTable *table, - const JSDHashEntryHdr *entry, - const void *key); - -extern JS_PUBLIC_API(void) -JS_DHashMoveEntryStub(JSDHashTable *table, - const JSDHashEntryHdr *from, - JSDHashEntryHdr *to); - -extern JS_PUBLIC_API(void) -JS_DHashClearEntryStub(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFreeStringKey(JSDHashTable *table, JSDHashEntryHdr *entry); - -extern JS_PUBLIC_API(void) -JS_DHashFinalizeStub(JSDHashTable *table); - -/* - * If you use JSDHashEntryStub or a subclass of it as your entry struct, and - * if your entries move via memcpy and clear via memset(0), you can use these - * stub operations. - */ -extern JS_PUBLIC_API(const JSDHashTableOps *) -JS_DHashGetStubOps(void); - -/* - * Dynamically allocate a new JSDHashTable using malloc, initialize it using - * JS_DHashTableInit, and return its address. Return null on malloc failure. - * Note that the entry storage at table->entryStore will be allocated using - * the ops->allocTable callback. - */ -extern JS_PUBLIC_API(JSDHashTable *) -JS_NewDHashTable(const JSDHashTableOps *ops, void *data, uint32_t entrySize, - uint32_t capacity); - -/* - * Finalize table's data, free its entry storage (via table->ops->freeTable), - * and return the memory starting at table to the malloc heap. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableDestroy(JSDHashTable *table); - -/* - * Initialize table with ops, data, entrySize, and capacity. Capacity is a - * guess for the smallest table size at which the table will usually be less - * than 75% loaded (the table will grow or shrink as needed; capacity serves - * only to avoid inevitable early growth from JS_DHASH_MIN_SIZE). - */ -extern JS_PUBLIC_API(JSBool) -JS_DHashTableInit(JSDHashTable *table, const JSDHashTableOps *ops, void *data, - uint32_t entrySize, uint32_t capacity); - -/* - * Set maximum and minimum alpha for table. The defaults are 0.75 and .25. - * maxAlpha must be in [0.5, 0.9375] for the default JS_DHASH_MIN_SIZE; or if - * MinSize=JS_DHASH_MIN_SIZE <= 256, in [0.5, (float)(MinSize-1)/MinSize]; or - * else in [0.5, 255.0/256]. minAlpha must be in [0, maxAlpha / 2), so that - * we don't shrink on the very next remove after growing a table upon adding - * an entry that brings entryCount past maxAlpha * tableSize. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableSetAlphaBounds(JSDHashTable *table, - float maxAlpha, - float minAlpha); - -/* - * Call this macro with k, the number of pointer-sized words wasted per entry - * under chaining, to compute the minimum alpha at which double hashing still - * beats chaining. - */ -#define JS_DHASH_MIN_ALPHA(table, k) \ - ((float)((table)->entrySize / sizeof(void *) - 1) \ - / ((table)->entrySize / sizeof(void *) + (k))) - -/* - * Default max/min alpha, and macros to compute the value for the |capacity| - * parameter to JS_NewDHashTable and JS_DHashTableInit, given default or any - * max alpha, such that adding entryCount entries right after initializing the - * table will not require a reallocation (so JS_DHASH_ADD can't fail for those - * JS_DHashTableOperate calls). - * - * NB: JS_DHASH_CAP is a helper macro meant for use only in JS_DHASH_CAPACITY. - * Don't use it directly! - */ -#define JS_DHASH_DEFAULT_MAX_ALPHA 0.75 -#define JS_DHASH_DEFAULT_MIN_ALPHA 0.25 - -#define JS_DHASH_CAP(entryCount, maxAlpha) \ - ((uint32_t)((double)(entryCount) / (maxAlpha))) - -#define JS_DHASH_CAPACITY(entryCount, maxAlpha) \ - (JS_DHASH_CAP(entryCount, maxAlpha) + \ - (((JS_DHASH_CAP(entryCount, maxAlpha) * (uint8_t)(0x100 * (maxAlpha))) \ - >> 8) < (entryCount))) - -#define JS_DHASH_DEFAULT_CAPACITY(entryCount) \ - JS_DHASH_CAPACITY(entryCount, JS_DHASH_DEFAULT_MAX_ALPHA) - -/* - * Finalize table's data, free its entry storage using table->ops->freeTable, - * and leave its members unchanged from their last live values (which leaves - * pointers dangling). If you want to burn cycles clearing table, it's up to - * your code to call memset. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableFinish(JSDHashTable *table); - -/* - * To consolidate keyHash computation and table grow/shrink code, we use a - * single entry point for lookup, add, and remove operations. The operation - * codes are declared here, along with codes returned by JSDHashEnumerator - * functions, which control JS_DHashTableEnumerate's behavior. - */ -typedef enum JSDHashOperator { - JS_DHASH_LOOKUP = 0, /* lookup entry */ - JS_DHASH_ADD = 1, /* add entry */ - JS_DHASH_REMOVE = 2, /* remove entry, or enumerator says remove */ - JS_DHASH_NEXT = 0, /* enumerator says continue */ - JS_DHASH_STOP = 1 /* enumerator says stop */ -} JSDHashOperator; - -/* - * To lookup a key in table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_LOOKUP); - * - * If JS_DHASH_ENTRY_IS_BUSY(entry) is true, key was found and it identifies - * entry. If JS_DHASH_ENTRY_IS_FREE(entry) is true, key was not found. - * - * To add an entry identified by key to table, call: - * - * entry = JS_DHashTableOperate(table, key, JS_DHASH_ADD); - * - * If entry is null upon return, then either the table is severely overloaded, - * and memory can't be allocated for entry storage via table->ops->allocTable; - * Or if table->ops->initEntry is non-null, the table->ops->initEntry op may - * have returned false. - * - * Otherwise, entry->keyHash has been set so that JS_DHASH_ENTRY_IS_BUSY(entry) - * is true, and it is up to the caller to initialize the key and value parts - * of the entry sub-type, if they have not been set already (i.e. if entry was - * not already in the table, and if the optional initEntry hook was not used). - * - * To remove an entry identified by key from table, call: - * - * (void) JS_DHashTableOperate(table, key, JS_DHASH_REMOVE); - * - * If key's entry is found, it is cleared (via table->ops->clearEntry) and - * the entry is marked so that JS_DHASH_ENTRY_IS_FREE(entry). This operation - * returns null unconditionally; you should ignore its return value. - */ -extern JS_PUBLIC_API(JSDHashEntryHdr *) JS_DHASH_FASTCALL -JS_DHashTableOperate(JSDHashTable *table, const void *key, JSDHashOperator op); - -/* - * Remove an entry already accessed via LOOKUP or ADD. - * - * NB: this is a "raw" or low-level routine, intended to be used only where - * the inefficiency of a full JS_DHashTableOperate (which rehashes in order - * to find the entry given its key) is not tolerable. This function does not - * shrink the table if it is underloaded. It does not update stats #ifdef - * JS_DHASHMETER, either. - */ -extern JS_PUBLIC_API(void) -JS_DHashTableRawRemove(JSDHashTable *table, JSDHashEntryHdr *entry); - -/* - * Enumerate entries in table using etor: - * - * count = JS_DHashTableEnumerate(table, etor, arg); - * - * JS_DHashTableEnumerate calls etor like so: - * - * op = etor(table, entry, number, arg); - * - * where number is a zero-based ordinal assigned to live entries according to - * their order in table->entryStore. - * - * The return value, op, is treated as a set of flags. If op is JS_DHASH_NEXT, - * then continue enumerating. If op contains JS_DHASH_REMOVE, then clear (via - * table->ops->clearEntry) and free entry. Then we check whether op contains - * JS_DHASH_STOP; if so, stop enumerating and return the number of live entries - * that were enumerated so far. Return the total number of live entries when - * enumeration completes normally. - * - * If etor calls JS_DHashTableOperate on table with op != JS_DHASH_LOOKUP, it - * must return JS_DHASH_STOP; otherwise undefined behavior results. - * - * If any enumerator returns JS_DHASH_REMOVE, table->entryStore may be shrunk - * or compressed after enumeration, but before JS_DHashTableEnumerate returns. - * Such an enumerator therefore can't safely set aside entry pointers, but an - * enumerator that never returns JS_DHASH_REMOVE can set pointers to entries - * aside, e.g., to avoid copying live entries into an array of the entry type. - * Copying entry pointers is cheaper, and safe so long as the caller of such a - * "stable" Enumerate doesn't use the set-aside pointers after any call either - * to PL_DHashTableOperate, or to an "unstable" form of Enumerate, which might - * grow or shrink entryStore. - * - * If your enumerator wants to remove certain entries, but set aside pointers - * to other entries that it retains, it can use JS_DHashTableRawRemove on the - * entries to be removed, returning JS_DHASH_NEXT to skip them. Likewise, if - * you want to remove entries, but for some reason you do not want entryStore - * to be shrunk or compressed, you can call JS_DHashTableRawRemove safely on - * the entry being enumerated, rather than returning JS_DHASH_REMOVE. - */ -typedef JSDHashOperator -(* JSDHashEnumerator)(JSDHashTable *table, JSDHashEntryHdr *hdr, uint32_t number, void *arg); - -extern JS_PUBLIC_API(uint32_t) -JS_DHashTableEnumerate(JSDHashTable *table, JSDHashEnumerator etor, void *arg); - -typedef size_t -(* JSDHashSizeOfEntryExcludingThisFun)(JSDHashEntryHdr *hdr, - JSMallocSizeOfFun mallocSizeOf, - void *arg); - -/** - * Measure the size of the table's entry storage, and if - * |sizeOfEntryExcludingThis| is non-NULL, measure the size of things pointed - * to by entries. Doesn't measure |ops| because it's often shared between - * tables, nor |data| because it's opaque. - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfExcludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -/** - * Like JS_DHashTableSizeOfExcludingThis, but includes sizeof(*this). - */ -extern JS_PUBLIC_API(size_t) -JS_DHashTableSizeOfIncludingThis(const JSDHashTable *table, - JSDHashSizeOfEntryExcludingThisFun sizeOfEntryExcludingThis, - JSMallocSizeOfFun mallocSizeOf, - void *arg = NULL); - -#ifdef DEBUG -/** - * Mark a table as immutable for the remainder of its lifetime. This - * changes the implementation from ASSERTing one set of invariants to - * ASSERTing a different set. - * - * When a table is NOT marked as immutable, the table implementation - * asserts that the table is not mutated from its own callbacks. It - * assumes the caller protects the table from being accessed on multiple - * threads simultaneously. - * - * When the table is marked as immutable, the re-entry assertions will - * no longer trigger erroneously due to multi-threaded access. Instead, - * mutations will cause assertions. - */ -extern JS_PUBLIC_API(void) -JS_DHashMarkTableImmutable(JSDHashTable *table); -#endif - -#ifdef JS_DHASHMETER -#include - -extern JS_PUBLIC_API(void) -JS_DHashTableDumpMeter(JSDHashTable *table, JSDHashEnumerator dump, FILE *fp); -#endif - -#endif /* jsdhash_h___ */ diff --git a/external/spidermonkey/include/win32/jsfriendapi.h b/external/spidermonkey/include/win32/jsfriendapi.h index 848049ffe3..a1c3024fed 100644 --- a/external/spidermonkey/include/win32/jsfriendapi.h +++ b/external/spidermonkey/include/win32/jsfriendapi.h @@ -4,15 +4,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsfriendapi_h___ -#define jsfriendapi_h___ +#ifndef jsfriendapi_h +#define jsfriendapi_h -#include "mozilla/GuardObjects.h" +#include "mozilla/MemoryReporting.h" #include "jsclass.h" -#include "jscpucfg.h" -#include "jspubtd.h" #include "jsprvtd.h" +#include "jspubtd.h" + +#include "js/CallArgs.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -29,6 +30,11 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +namespace JS { +template +class Heap; +} /* namespace JS */ + extern JS_FRIEND_API(void) JS_SetGrayGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data); @@ -48,7 +54,7 @@ extern JS_FRIEND_API(JSObject *) JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JSHandleObject obj); +JS_ObjectCountDynamicSlots(JS::HandleObject obj); extern JS_FRIEND_API(size_t) JS_SetProtoCalled(JSContext *cx); @@ -118,14 +124,27 @@ extern JS_FRIEND_API(JSObject *) JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) -JS_BasicObjectToString(JSContext *cx, JSHandleObject obj); +JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp); +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, + JS::MutableHandleValue vp); JS_FRIEND_API(void) js_ReportOverRecursed(JSContext *maybecx); +JS_FRIEND_API(bool) +js_ObjectClassIs(JSContext *cx, JS::HandleObject obj, js::ESClassValue classValue); + +JS_FRIEND_API(const char *) +js_ObjectClassName(JSContext *cx, JS::HandleObject obj); + +JS_FRIEND_API(bool) +js_AddObjectRoot(JSRuntime *rt, JSObject **objp); + +JS_FRIEND_API(void) +js_RemoveObjectRoot(JSRuntime *rt, JSObject **objp); + #ifdef DEBUG /* @@ -157,7 +176,7 @@ extern JS_FRIEND_API(JSBool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); extern JS_FRIEND_API(JSBool) -JS_EnumerateState(JSContext *cx, JSHandleObject obj, JSIterateOp enum_op, +JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, js::MutableHandleValue statep, js::MutableHandleId idp); struct JSFunctionSpecWithHelp { @@ -177,25 +196,24 @@ struct JSFunctionSpecWithHelp { extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JSScript *script, jschar **src, uint32_t *length); +typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, + jschar **src, uint32_t *length); extern JS_FRIEND_API(void) JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); namespace js { -extern mozilla::ThreadLocal TlsPerThreadData; - inline JSRuntime * GetRuntime(const JSContext *cx) { - return ContextFriendFields::get(cx)->runtime; + return ContextFriendFields::get(cx)->runtime_; } inline JSCompartment * GetContextCompartment(const JSContext *cx) { - return ContextFriendFields::get(cx)->compartment; + return ContextFriendFields::get(cx)->compartment_; } inline JS::Zone * @@ -217,19 +235,6 @@ typedef bool extern JS_FRIEND_API(void) DumpHeapComplete(JSRuntime *rt, FILE *fp); -class JS_FRIEND_API(AutoSwitchCompartment) { - private: - JSContext *cx; - JSCompartment *oldCompartment; - public: - AutoSwitchCompartment(JSContext *cx, JSCompartment *newCompartment - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - AutoSwitchCompartment(JSContext *cx, JSHandleObject target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoSwitchCompartment(); - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - #ifdef OLD_GETTER_SETTER_METHODS JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); @@ -254,6 +259,15 @@ IsAtomsCompartment(JSCompartment *comp); extern JS_FRIEND_API(bool) ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +/* + * Returns whether we're in a non-strict property set (in that we're in a + * non-strict script and the bytecode we're on is a property set). The return + * value does NOT indicate any sort of exception was thrown: it's just a + * boolean. + */ +extern JS_FRIEND_API(bool) +IsInNonStrictPropertySet(JSContext *cx); + struct WeakMapTracer; /* @@ -301,7 +315,7 @@ IterateGrayObjects(JS::Zone *zone, GCThingCallback cellCallback, void *data); #ifdef JS_HAS_CTYPES extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(JSMallocSizeOfFun mallocSizeOf, JSObject *obj); +SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject *obj); #endif extern JS_FRIEND_API(JSCompartment *) @@ -321,8 +335,9 @@ struct TypeObject { }; struct BaseShape { - js::Class *clasp; - JSObject *parent; + js::Class *clasp; + JSObject *parent; + JSObject *_1; JSCompartment *compartment; }; @@ -365,19 +380,22 @@ struct Function { }; struct Atom { - size_t _; + static const size_t LENGTH_SHIFT = 4; + size_t lengthAndFlags; const jschar *chars; }; } /* namespace shadow */ -extern JS_FRIEND_DATA(js::Class) CallClass; -extern JS_FRIEND_DATA(js::Class) DeclEnvClass; -extern JS_FRIEND_DATA(js::Class) FunctionClass; -extern JS_FRIEND_DATA(js::Class) FunctionProxyClass; -extern JS_FRIEND_DATA(js::Class) OuterWindowProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectProxyClass; -extern JS_FRIEND_DATA(js::Class) ObjectClass; +// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use +// them in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; +extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; + +// This is equal to |&JSObject::class_|. Use it in places where you don't want +// to #include jsobj.h. +extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; inline js::Class * GetObjectClass(JSObject *obj) @@ -401,9 +419,15 @@ IsOuterObject(JSObject *obj) { return !!GetObjectClass(obj)->ext.innerObject; } +JS_FRIEND_API(bool) +IsFunctionObject(JSObject *obj); + JS_FRIEND_API(bool) IsScopeObject(JSObject *obj); +JS_FRIEND_API(bool) +IsCallObject(JSObject *obj); + inline JSObject * GetObjectParent(JSObject *obj) { @@ -423,6 +447,13 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +// For legacy consumers only. This whole concept is going away soon. +JS_FRIEND_API(JSObject *) +DefaultObjectForContextOrNull(JSContext *cx); + +JS_FRIEND_API(void) +SetDefaultObjectForContext(JSContext *cx, JSObject *obj); + JS_FRIEND_API(void) NotifyAnimationActivity(JSObject *obj); @@ -469,11 +500,11 @@ inline bool GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) { js::Class *clasp = GetObjectClass(obj); - if (clasp == &js::ObjectProxyClass || - clasp == &js::OuterWindowProxyClass || - clasp == &js::FunctionProxyClass) + if (clasp == js::ObjectProxyClassPtr || + clasp == js::OuterWindowProxyClassPtr || + clasp == js::FunctionProxyClassPtr) { - return JS_GetPrototype(cx, obj, proto.address()); + return JS_GetPrototype(cx, obj, proto); } proto.set(reinterpret_cast(obj.get())->type->proto); @@ -535,6 +566,13 @@ GetAtomChars(JSAtom *atom) return reinterpret_cast(atom)->chars; } +inline size_t +GetAtomLength(JSAtom *atom) +{ + using shadow::Atom; + return reinterpret_cast(atom)->lengthAndFlags >> Atom::LENGTH_SHIFT; +} + inline JSLinearString * AtomToLinearString(JSAtom *atom) { @@ -589,6 +627,12 @@ GetNativeStackLimit(const JSRuntime *rt) return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; } +inline uintptr_t +GetNativeStackLimit(JSContext *cx) +{ + return GetNativeStackLimit(GetRuntime(cx)); +} + /* * These macros report a stack overflow and run |onerror| if we are close to * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a little @@ -598,18 +642,15 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), &stackDummy_)) { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), &stackDummy_)) { \ js_ReportOverRecursed(cx); \ onerror; \ } \ JS_END_MACRO -#define JS_CHECK_RECURSION_WITH_EXTRA_DONT_REPORT(cx, extra, onerror) \ +#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ JS_BEGIN_MACRO \ - uint8_t stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ - &stackDummy_ - (extra))) \ - { \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ onerror; \ } \ JS_END_MACRO @@ -617,7 +658,7 @@ GetNativeStackLimit(const JSRuntime *rt) #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(js::GetRuntime(cx)), \ + if (!JS_CHECK_STACK_SIZE_WITH_TOLERANCE(js::GetNativeStackLimit(cx), \ &stackDummy_, \ 1024 * sizeof(size_t))) \ { \ @@ -754,13 +795,13 @@ extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JSFlatString *desc); +(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); extern JS_FRIEND_API(AnalysisPurgeCallback) SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); typedef JSBool -(* DOMInstanceClassMatchesProto)(JSHandleObject protoObject, uint32_t protoID, +(* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { DOMInstanceClassMatchesProto instanceClassMatchesProto; @@ -851,10 +892,10 @@ NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& targetFilter, NukeReferencesToWindow nukeReferencesToWindow); -/* Specify information about ListBase proxies in the DOM, for use by ICs. */ +/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ /* - * The ListBaseShadowsCheck function will be called to check if the property for + * The DOMProxyShadowsCheck function will be called to check if the property for * id should be gotten from the prototype, or if there is an own property that * shadows it. * If DoesntShadow is returned then the slot at listBaseExpandoSlot should @@ -873,25 +914,31 @@ struct ExpandoAndGeneration { generation(0) {} - Value expando; + void Unlink() + { + ++generation; + expando.setUndefined(); + } + + JS::Heap expando; uint32_t generation; }; -typedef enum ListBaseShadowsResult { +typedef enum DOMProxyShadowsResult { ShadowCheckFailed, Shadows, DoesntShadow, DoesntShadowUnique -} ListBaseShadowsResult; -typedef ListBaseShadowsResult -(* ListBaseShadowsCheck)(JSContext* cx, JSHandleObject object, JSHandleId id); +} DOMProxyShadowsResult; +typedef DOMProxyShadowsResult +(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetListBaseInformation(void *listBaseHandlerFamily, uint32_t listBaseExpandoSlot, - ListBaseShadowsCheck listBaseShadowsCheck); +SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, + DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetListBaseHandlerFamily(); -uint32_t GetListBaseExpandoSlot(); -ListBaseShadowsCheck GetListBaseShadowsCheck(); +void *GetDOMProxyHandlerFamily(); +uint32_t GetDOMProxyExpandoSlot(); +DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); } /* namespace js */ @@ -960,6 +1007,137 @@ enum ViewType { }; } /* namespace ArrayBufferView */ + +/* + * A helper for building up an ArrayBuffer object's data + * before creating the ArrayBuffer itself. Will do doubling + * based reallocation, up to an optional maximum growth given. + * + * When all the data has been appended, call getArrayBuffer, + * passing in the JSContext* for which the ArrayBuffer object + * is to be created. This also implicitly resets the builder, + * or it can be reset explicitly at any point by calling reset(). + */ +class ArrayBufferBuilder +{ + void *rawcontents_; + uint8_t *dataptr_; + uint32_t capacity_; + uint32_t length_; + public: + ArrayBufferBuilder() + : rawcontents_(NULL), + dataptr_(NULL), + capacity_(0), + length_(0) + { + } + + ~ArrayBufferBuilder() { + reset(); + } + + void reset() { + if (rawcontents_) + JS_free(NULL, rawcontents_); + rawcontents_ = dataptr_ = NULL; + capacity_ = length_ = 0; + } + + // will truncate if newcap is < length() + bool setCapacity(uint32_t newcap) { + if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) + return false; + + capacity_ = newcap; + if (length_ > newcap) + length_ = newcap; + + return true; + } + + // Append datalen bytes from data to the current buffer. If we + // need to grow the buffer, grow by doubling the size up to a + // maximum of maxgrowth (if given). If datalen is greater than + // what the new capacity would end up as, then grow by datalen. + // + // The data parameter must not overlap with anything beyond the + // builder's current valid contents [0..length) + bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { + if (length_ + datalen > capacity_) { + uint32_t newcap; + // double while under maxgrowth or if not specified + if (!maxgrowth || capacity_ < maxgrowth) + newcap = capacity_ * 2; + else + newcap = capacity_ + maxgrowth; + + // but make sure there's always enough to satisfy our request + if (newcap < length_ + datalen) + newcap = length_ + datalen; + + // did we overflow? + if (newcap < capacity_) + return false; + + if (!setCapacity(newcap)) + return false; + } + + // assert that the region isn't overlapping so we can memcpy; + JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); + + memcpy(dataptr_ + length_, newdata, datalen); + length_ += datalen; + + return true; + } + + uint8_t *data() { + return dataptr_; + } + + uint32_t length() { + return length_; + } + + uint32_t capacity() { + return capacity_; + } + + JSObject* getArrayBuffer(JSContext *cx) { + // we need to check for length_ == 0, because nothing may have been + // added + if (capacity_ > length_ || length_ == 0) { + if (!setCapacity(length_)) + return NULL; + } + + JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); + if (!obj) + return NULL; + + rawcontents_ = dataptr_ = NULL; + length_ = capacity_ = 0; + + return obj; + } + +protected: + + static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, + const uint8_t *start2, uint32_t length2) + { + const uint8_t *end1 = start1 + length1; + const uint8_t *end2 = start2 + length2; + + const uint8_t *max_start = start1 > start2 ? start1 : start2; + const uint8_t *min_end = end1 < end2 ? end1 : end2; + + return max_start < min_end; + } +}; + } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1296,26 +1474,116 @@ JS_GetDataViewByteLength(JSObject *obj); JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitGetterOp. + */ +class JSJitGetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitGetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args.rval()) + {} + + explicit JSJitGetterCallArgs(JS::Rooted* rooted) + : JS::MutableHandleValue(rooted) + {} + + JS::MutableHandleValue rval() { + return *this; + } +}; + +/* + * A class, expected to be passed by value, which represents the CallArgs for a + * JSJitSetterOp. + */ +class JSJitSetterCallArgs : protected JS::MutableHandleValue +{ + public: + explicit JSJitSetterCallArgs(const JS::CallArgs& args) + : JS::MutableHandleValue(args[0]) + {} + + JS::MutableHandleValue operator[](unsigned i) { + MOZ_ASSERT(i == 0); + return *this; + } + + unsigned length() const { return 1; } + + // Add get() or maybe hasDefined() as needed +}; + +struct JSJitMethodCallArgsTraits; + +/* + * A class, expected to be passed by reference, which represents the CallArgs + * for a JSJitMethodOp. + */ +class JSJitMethodCallArgs : protected JS::detail::CallArgsBase +{ + private: + typedef JS::detail::CallArgsBase Base; + friend struct JSJitMethodCallArgsTraits; + + public: + explicit JSJitMethodCallArgs(const JS::CallArgs& args) { + argv_ = args.array(); + argc_ = args.length(); + } + + JS::MutableHandleValue rval() const { + return Base::rval(); + } + + unsigned length() const { return Base::length(); } + + JS::MutableHandleValue operator[](unsigned i) const { + return Base::operator[](i); + } + + bool hasDefined(unsigned i) const { + return Base::hasDefined(i); + } + + // Add get() as needed +}; + +struct JSJitMethodCallArgsTraits +{ + static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); + static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); +}; + /* * This struct contains metadata passed from the DOM to the JS Engine for JIT * optimizations on DOM property accessors. Eventually, this should be made * available to general JSAPI users, but we are not currently ready to do so. */ typedef bool -(* JSJitPropertyOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, JS::Value *vp); +(* JSJitGetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitGetterCallArgs args); typedef bool -(* JSJitMethodOp)(JSContext *cx, JSHandleObject thisObj, - void *specializedThis, unsigned argc, JS::Value *vp); +(* JSJitSetterOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, JSJitSetterCallArgs args); +typedef bool +(* JSJitMethodOp)(JSContext *cx, JS::HandleObject thisObj, + void *specializedThis, const JSJitMethodCallArgs& args); struct JSJitInfo { enum OpType { Getter, Setter, - Method + Method, + OpType_None }; - JSJitPropertyOp op; + union { + JSJitGetterOp getter; + JSJitSetterOp setter; + JSJitMethodOp method; + }; uint32_t protoID; uint32_t depth; OpType type; @@ -1325,12 +1593,18 @@ struct JSJitInfo { keep returning the same value for the given "this" object" */ JSValueType returnType; /* The return type tag. Might be JSVAL_TYPE_UNKNOWN */ + + /* An alternative native that's safe to call in parallel mode. */ + JSParallelNative parallelNative; }; +#define JS_JITINFO_NATIVE_PARALLEL(op) \ + {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) { - JS_ASSERT(js::GetObjectClass(&v.toObject()) == &js::FunctionClass); + JS_ASSERT(js::GetObjectClass(&v.toObject()) == js::FunctionClassPtr); return reinterpret_cast(&v.toObject())->jitinfo; } @@ -1482,9 +1756,46 @@ assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id); inline void assertEnteredPolicy(JSContext *cx, JSObject *obj, jsid id) {}; #endif +typedef bool +(* ObjectMetadataCallback)(JSContext *cx, JSObject **pmetadata); + +/* + * Specify a callback to invoke when creating each JS object in the current + * compartment, which may return a metadata object to associate with the + * object. Objects with different metadata have different shape hierarchies, + * so for efficiency, objects should generally try to share metadata objects. + */ +JS_FRIEND_API(void) +SetObjectMetadataCallback(JSContext *cx, ObjectMetadataCallback callback); + +/* Manipulate the metadata associated with an object. */ + +JS_FRIEND_API(bool) +SetObjectMetadata(JSContext *cx, JS::HandleObject obj, JS::HandleObject metadata); + +JS_FRIEND_API(JSObject *) +GetObjectMetadata(JSObject *obj); + /* ES5 8.12.8. */ extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); + +/* + * Helper function. To approximate a call to the [[DefineOwnProperty]] internal + * method described in ES5, first call this, then call JS_DefinePropertyById. + * + * JS_DefinePropertyById by itself does not enforce the invariants on + * non-configurable properties when obj->isNative(). This function performs the + * relevant checks (specified in ES5 8.12.9 [[DefineOwnProperty]] steps 1-11), + * but only if obj is native. + * + * The reason for the messiness here is that ES5 uses [[DefineOwnProperty]] as + * a sort of extension point, but there is no hook in js::Class, + * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. + */ +extern JS_FRIEND_API(bool) +CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, + PropertyOp getter, StrictPropertyOp setter, unsigned attrs); } /* namespace js */ @@ -1495,4 +1806,26 @@ js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, extern JS_FRIEND_API(JSBool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); -#endif /* jsfriendapi_h___ */ +#ifdef JSGC_GENERATIONAL +extern JS_FRIEND_API(void) +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data); + +extern JS_FRIEND_API(void) +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data); +#else +inline void +JS_StoreObjectPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSObject *key, void *data) {} + +inline void +JS_StoreStringPostBarrierCallback(JSContext* cx, + void (*callback)(JSTracer *trc, void *key, void *data), + JSString *key, void *data) {} +#endif /* JSGC_GENERATIONAL */ + +#endif /* jsfriendapi_h */ diff --git a/external/spidermonkey/include/win32/jslock.h b/external/spidermonkey/include/win32/jslock.h index b4a28a9fa9..522034ad68 100644 --- a/external/spidermonkey/include/win32/jslock.h +++ b/external/spidermonkey/include/win32/jslock.h @@ -4,18 +4,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jslock_h__ -#define jslock_h__ - -#include "jsapi.h" +#ifndef jslock_h +#define jslock_h #ifdef JS_THREADSAFE +# include "jsapi.h" # include "pratom.h" -# include "prlock.h" # include "prcvar.h" -# include "prthread.h" # include "prinit.h" +# include "prlock.h" +# include "prthread.h" # define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) # define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) @@ -40,4 +39,4 @@ typedef struct PRLock PRLock; #endif /* JS_THREADSAFE */ -#endif /* jslock_h___ */ +#endif /* jslock_h */ diff --git a/external/spidermonkey/include/win32/json.h b/external/spidermonkey/include/win32/json.h deleted file mode 100644 index 7fa2c117c8..0000000000 --- a/external/spidermonkey/include/win32/json.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef json_h___ -#define json_h___ - -#include "jsprvtd.h" -#include "jspubtd.h" -#include "jsapi.h" - -#include "js/Vector.h" - -#define JSON_MAX_DEPTH 2048 -#define JSON_PARSER_BUFSIZE 1024 - -extern JSObject * -js_InitJSONClass(JSContext *cx, js::HandleObject obj); - -extern JSBool -js_Stringify(JSContext *cx, js::MutableHandleValue vp, - JSObject *replacer, js::Value space, - js::StringBuffer &sb); - -// Avoid build errors on certain platforms that define these names as constants -#undef STRICT -#undef LEGACY - -/* - * The type of JSON decoding to perform. Strict decoding is to-the-spec; - * legacy decoding accepts a few non-JSON syntaxes historically accepted by the - * implementation. (Full description of these deviations is deliberately - * omitted.) New users should use strict decoding rather than legacy decoding, - * as legacy decoding might be removed at a future time. - */ -enum DecodingMode { STRICT, LEGACY }; - -namespace js { - -extern JS_FRIEND_API(JSBool) -ParseJSONWithReviver(JSContext *cx, JS::StableCharPtr chars, size_t length, HandleValue filter, - MutableHandleValue vp, DecodingMode decodingMode = STRICT); - -} /* namespace js */ - -#endif /* json_h___ */ diff --git a/external/spidermonkey/include/win32/jsperf.h b/external/spidermonkey/include/win32/jsperf.h index a0287b4a57..468ce8609c 100644 --- a/external/spidermonkey/include/win32/jsperf.h +++ b/external/spidermonkey/include/win32/jsperf.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsperf_h___ -#define jsperf_h___ +#ifndef perf_jsperf_h +#define perf_jsperf_h #include "jsapi.h" @@ -127,4 +127,4 @@ extern JS_FRIEND_API(PerfMeasurement*) } // namespace JS -#endif // jsperf_h___ +#endif /* perf_jsperf_h */ diff --git a/external/spidermonkey/include/win32/jsprf.h b/external/spidermonkey/include/win32/jsprf.h index c0891f0e9e..ce159d8115 100644 --- a/external/spidermonkey/include/win32/jsprf.h +++ b/external/spidermonkey/include/win32/jsprf.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprf_h___ -#define jsprf_h___ +#ifndef jsprf_h +#define jsprf_h /* ** API for PR printf like routines. Supports the following formats @@ -24,9 +24,11 @@ ** %f - float ** %g - float */ -#include "jstypes.h" -#include + #include +#include + +#include "jstypes.h" /* ** sprintf into a fixed size buffer. Guarantees that a NUL is at the end @@ -75,4 +77,4 @@ extern JS_PUBLIC_API(char*) JS_vsmprintf(const char *fmt, va_list ap); extern JS_PUBLIC_API(char*) JS_vsprintf_append(char *last, const char *fmt, va_list ap); extern JS_PUBLIC_API(uint32_t) JS_vsxprintf(JSStuffFunc f, void *arg, const char *fmt, va_list ap); -#endif /* jsprf_h___ */ +#endif /* jsprf_h */ diff --git a/external/spidermonkey/include/win32/jsprototypes.h b/external/spidermonkey/include/win32/jsprototypes.h index 007d25d720..f9bacac409 100644 --- a/external/spidermonkey/include/win32/jsprototypes.h +++ b/external/spidermonkey/include/win32/jsprototypes.h @@ -6,8 +6,8 @@ /* A higher-order macro for enumerating all JSProtoKey values. */ -#ifndef jsprototypes_h___ -#define jsprototypes_h___ +#ifndef jsprototypes_h +#define jsprototypes_h #include "jsversion.h" @@ -56,5 +56,20 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ + macro(Type, 38, js_InitBinaryDataClasses) \ + macro(Data, 39, js_InitBinaryDataClasses) \ + macro(uint8, 40, js_InitBinaryDataClasses) \ + macro(uint16, 41, js_InitBinaryDataClasses) \ + macro(uint32, 42, js_InitBinaryDataClasses) \ + macro(uint64, 43, js_InitBinaryDataClasses) \ + macro(int8, 44, js_InitBinaryDataClasses) \ + macro(int16, 45, js_InitBinaryDataClasses) \ + macro(int32, 46, js_InitBinaryDataClasses) \ + macro(int64, 47, js_InitBinaryDataClasses) \ + macro(float32, 48, js_InitBinaryDataClasses) \ + macro(float64, 49, js_InitBinaryDataClasses) \ + macro(ArrayType, 50, js_InitBinaryDataClasses) \ + macro(StructType, 51, js_InitBinaryDataClasses) \ + macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ -#endif /* jsprototypes_h___ */ +#endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/win32/jsproxy.h b/external/spidermonkey/include/win32/jsproxy.h index 399490eddc..56868a05c3 100644 --- a/external/spidermonkey/include/win32/jsproxy.h +++ b/external/spidermonkey/include/win32/jsproxy.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsproxy_h___ -#define jsproxy_h___ +#ifndef jsproxy_h +#define jsproxy_h #include "jsapi.h" #include "jsfriendapi.h" @@ -129,7 +129,7 @@ class JS_FRIEND_API(BaseProxyHandler) MutableHandleValue vp); /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) = 0; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) = 0; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -190,7 +190,7 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -242,7 +242,7 @@ class Proxy static bool iterate(JSContext *cx, HandleObject proxy, unsigned flags, MutableHandleValue vp); /* Spidermonkey extensions. */ - static bool isExtensible(JSObject *proxy); + static bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible); static bool call(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args); static bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); @@ -259,12 +259,17 @@ class Proxy inline bool IsObjectProxyClass(const Class *clasp) { - return clasp == &js::ObjectProxyClass || clasp == &js::OuterWindowProxyClass; + return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; } inline bool IsFunctionProxyClass(const Class *clasp) { - return clasp == &js::FunctionProxyClass; + return clasp == js::FunctionProxyClassPtr; +} + +inline bool IsProxyClass(const Class *clasp) +{ + return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); } inline bool IsObjectProxy(JSObject *obj) @@ -279,36 +284,33 @@ inline bool IsFunctionProxy(JSObject *obj) inline bool IsProxy(JSObject *obj) { - Class *clasp = GetObjectClass(obj); - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); + return IsProxyClass(GetObjectClass(obj)); } -/* Shared between object and function proxies. */ /* - * NOTE: JSSLOT_PROXY_PRIVATE is 0, because that way slot 0 is usable by API + * These are part of the API. + * + * NOTE: PROXY_PRIVATE_SLOT is 0 because that way slot 0 is usable by API * clients for both proxy and non-proxy objects. So an API client that only * needs to store one slot's worth of data doesn't need to branch on what sort * of object it has. */ -const uint32_t JSSLOT_PROXY_PRIVATE = 0; -const uint32_t JSSLOT_PROXY_HANDLER = 1; -const uint32_t JSSLOT_PROXY_EXTRA = 2; -/* Function proxies only. */ -const uint32_t JSSLOT_PROXY_CALL = 4; -const uint32_t JSSLOT_PROXY_CONSTRUCT = 5; +const uint32_t PROXY_PRIVATE_SLOT = 0; +const uint32_t PROXY_HANDLER_SLOT = 1; +const uint32_t PROXY_EXTRA_SLOT = 2; inline BaseProxyHandler * GetProxyHandler(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return (BaseProxyHandler *) GetReservedSlot(obj, JSSLOT_PROXY_HANDLER).toPrivate(); + return (BaseProxyHandler *) GetReservedSlot(obj, PROXY_HANDLER_SLOT).toPrivate(); } inline const Value & GetProxyPrivate(JSObject *obj) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_PRIVATE); + return GetReservedSlot(obj, PROXY_PRIVATE_SLOT); } inline JSObject * @@ -322,14 +324,14 @@ inline const Value & GetProxyExtra(JSObject *obj, size_t n) { JS_ASSERT(IsProxy(obj)); - return GetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n); + return GetReservedSlot(obj, PROXY_EXTRA_SLOT + n); } inline void SetProxyHandler(JSObject *obj, BaseProxyHandler *handler) { JS_ASSERT(IsProxy(obj)); - SetReservedSlot(obj, JSSLOT_PROXY_HANDLER, PrivateValue(handler)); + SetReservedSlot(obj, PROXY_HANDLER_SLOT, PrivateValue(handler)); } inline void @@ -337,7 +339,7 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) { JS_ASSERT(IsProxy(obj)); JS_ASSERT(n <= 1); - SetReservedSlot(obj, JSSLOT_PROXY_EXTRA + n, extra); + SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } enum ProxyCallable { @@ -346,7 +348,7 @@ enum ProxyCallable { }; JS_FRIEND_API(JSObject *) -NewProxyObject(JSContext *cx, BaseProxyHandler *handler, const Value &priv, +NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); JSObject * @@ -426,6 +428,6 @@ class JS_FRIEND_API(AutoWaivePolicy) { } /* namespace js */ extern JS_FRIEND_API(JSObject *) -js_InitProxyClass(JSContext *cx, JSHandleObject obj); +js_InitProxyClass(JSContext *cx, JS::HandleObject obj); -#endif +#endif /* jsproxy_h */ diff --git a/external/spidermonkey/include/win32/jsprvtd.h b/external/spidermonkey/include/win32/jsprvtd.h index 4db5ed8c36..1fbc086a7c 100644 --- a/external/spidermonkey/include/win32/jsprvtd.h +++ b/external/spidermonkey/include/win32/jsprvtd.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsprvtd_h___ -#define jsprvtd_h___ +#ifndef jsprvtd_h +#define jsprvtd_h /* * JS private typename definitions. * @@ -56,13 +56,7 @@ typedef struct JSStackHeader JSStackHeader; typedef struct JSSubString JSSubString; typedef struct JSSpecializedNative JSSpecializedNative; -/* - * Template declarations. - * - * jsprvtd.h can be included in both C and C++ translation units. For C++, it - * may possibly be wrapped in an extern "C" block which does not agree with - * templates. - */ +/* String typedefs. */ class JSDependentString; class JSExtensibleString; class JSExternalString; @@ -76,6 +70,7 @@ namespace js { struct ArgumentsData; struct Class; +class AutoNameVector; class RegExpGuard; class RegExpObject; class RegExpObjectBuilder; @@ -83,6 +78,7 @@ class RegExpShared; class RegExpStatics; class MatchPairs; class PropertyName; +class LazyScript; enum RegExpFlag { @@ -95,19 +91,14 @@ enum RegExpFlag AllFlags = 0x0f }; -class ExecuteArgsGuard; -class InvokeFrameGuard; -class InvokeArgsGuard; class StringBuffer; class FrameRegs; class StackFrame; -class StackSegment; -class StackSpace; -class ContextStack; class ScriptFrameIter; class Proxy; +class JS_FRIEND_API(AutoEnterPolicy); class JS_FRIEND_API(BaseProxyHandler); class JS_FRIEND_API(Wrapper); class JS_FRIEND_API(CrossCompartmentWrapper); @@ -140,24 +131,29 @@ class WatchpointMap; typedef JSObject Env; typedef JSNative Native; +typedef JSParallelNative ParallelNative; +typedef JSThreadSafeNative ThreadSafeNative; typedef JSPropertyOp PropertyOp; typedef JSStrictPropertyOp StrictPropertyOp; typedef JSPropertyDescriptor PropertyDescriptor; +struct SourceCompressionToken; + namespace frontend { struct BytecodeEmitter; struct Definition; +class FullParseHandler; class FunctionBox; class ObjectBox; struct Token; struct TokenPos; class TokenStream; class ParseMapPool; -struct ParseNode; +class ParseNode; template -struct Parser; +class Parser; } /* namespace frontend */ @@ -284,18 +280,18 @@ typedef void * if an error or exception was thrown on cx. */ typedef JSObject * -(* JSObjectOp)(JSContext *cx, JSHandleObject obj); +(* JSObjectOp)(JSContext *cx, JS::Handle obj); /* Signature for class initialization ops. */ typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JSHandleObject obj); +(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); /* * Hook that creates an iterator object for a given object. Returns the * iterator object or null if an error or exception was thrown on cx. */ typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JSHandleObject obj, JSBool keysonly); +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); -#endif /* jsprvtd_h___ */ +#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/win32/jspubtd.h b/external/spidermonkey/include/win32/jspubtd.h index 6b7e63e6ba..96f5dd8297 100644 --- a/external/spidermonkey/include/win32/jspubtd.h +++ b/external/spidermonkey/include/win32/jspubtd.h @@ -4,16 +4,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jspubtd_h___ -#define jspubtd_h___ +#ifndef jspubtd_h +#define jspubtd_h /* * JS public API typedefs. */ +#include "mozilla/PodOperations.h" + #include "jsprototypes.h" #include "jstypes.h" +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) +# define JSGC_TRACK_EXACT_ROOTS +#endif + namespace JS { /* @@ -25,6 +31,8 @@ class Value; template class Rooted; +class JS_PUBLIC_API(AutoGCRooter); + struct Zone; } /* namespace JS */ @@ -44,10 +52,8 @@ struct Zone; * oblivious to the change. This feature can be explicitly disabled in debug * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. */ - // Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES - +#define JS_NO_JSVAL_JSID_STRUCT_TYPES # if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) # define JS_USE_JSID_STRUCT_TYPES # endif @@ -154,9 +160,10 @@ typedef enum { JSTRACE_SCRIPT, /* - * Trace kinds internal to the engine. The embedding can only them if it - * implements JSTraceCallback. + * Trace kinds internal to the engine. The embedding can only see them if + * it implements JSTraceCallback. */ + JSTRACE_LAZY_SCRIPT, JSTRACE_IONCODE, JSTRACE_SHAPE, JSTRACE_BASE_SHAPE, @@ -229,6 +236,18 @@ struct Runtime namespace js { +/* + * Parallel operations in general can have one of three states. They may + * succeed, fail, or "bail", where bail indicates that the code encountered an + * unexpected condition and should be re-run sequentially. Different + * subcategories of the "bail" state are encoded as variants of TP_RETRY_*. + */ +enum ParallelResult { TP_SUCCESS, TP_RETRY_SEQUENTIALLY, TP_RETRY_AFTER_GC, TP_FATAL }; + +struct ThreadSafeContext; +struct ForkJoinSlice; +class ExclusiveContext; + class Allocator; class SkipRoot; @@ -273,18 +292,28 @@ template <> struct RootKind : SpecificRootKind struct RootKind : SpecificRootKind {}; template <> struct RootKind : SpecificRootKind {}; -struct ContextFriendFields { - JSRuntime *const runtime; +struct ContextFriendFields +{ + protected: + JSRuntime *const runtime_; /* The current compartment. */ - JSCompartment *compartment; + JSCompartment *compartment_; /* The current zone. */ JS::Zone *zone_; + public: explicit ContextFriendFields(JSRuntime *rt) - : runtime(rt), compartment(NULL), zone_(NULL) - { } + : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + { +#ifdef JSGC_TRACK_EXACT_ROOTS + mozilla::PodArrayZero(thingGCRooters); +#endif +#if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) + skipGCRooters = NULL; +#endif + } static const ContextFriendFields *get(const JSContext *cx) { return reinterpret_cast(cx); @@ -294,7 +323,7 @@ struct ContextFriendFields { return reinterpret_cast(cx); } -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -313,6 +342,13 @@ struct ContextFriendFields { */ SkipRoot *skipGCRooters; #endif + + /* Stack of thread-stack-allocated GC roots. */ + JS::AutoGCRooter *autoGCRooters; + + friend JSRuntime *GetRuntime(const JSContext *cx); + friend JSCompartment *GetContextCompartment(const JSContext *cx); + friend JS::Zone *GetContextZone(const JSContext *cx); }; class PerThreadData; @@ -338,7 +374,7 @@ struct PerThreadDataFriendFields PerThreadDataFriendFields(); -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) +#ifdef JSGC_TRACK_EXACT_ROOTS /* * Stack allocated GC roots for stack GC heap pointers, which may be * overwritten if moved during a GC. @@ -384,4 +420,4 @@ struct PerThreadDataFriendFields } /* namespace js */ -#endif /* jspubtd_h___ */ +#endif /* jspubtd_h */ diff --git a/external/spidermonkey/include/win32/jstypes.h b/external/spidermonkey/include/win32/jstypes.h index e4c02f8d8d..17f67f70e1 100644 --- a/external/spidermonkey/include/win32/jstypes.h +++ b/external/spidermonkey/include/win32/jstypes.h @@ -18,8 +18,8 @@ ** for all C files. **/ -#ifndef jstypes_h___ -#define jstypes_h___ +#ifndef jstypes_h +#define jstypes_h #include "mozilla/Attributes.h" #include "mozilla/Util.h" @@ -279,4 +279,4 @@ typedef int JSBool; # define JS_EXTENSION_(s) s #endif -#endif /* jstypes_h___ */ +#endif /* jstypes_h */ diff --git a/external/spidermonkey/include/win32/jsutil.h b/external/spidermonkey/include/win32/jsutil.h index 49e1641c61..4020822be1 100644 --- a/external/spidermonkey/include/win32/jsutil.h +++ b/external/spidermonkey/include/win32/jsutil.h @@ -8,19 +8,19 @@ * PR assertion checker. */ -#ifndef jsutil_h___ -#define jsutil_h___ +#ifndef jsutil_h +#define jsutil_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/GuardObjects.h" -#include "js/Utility.h" - #ifdef USE_ZLIB -#include "zlib.h" +#include #endif +#include "js/Utility.h" + /* Forward declarations. */ struct JSContext; @@ -204,15 +204,6 @@ UnsignedPtrDiff(const void *bigger, const void *smaller) return size_t(bigger) - size_t(smaller); } -/* - * Ordinarily, a function taking a JSContext* 'cx' parameter reports errors on - * the context. In some cases, functions optionally report and indicate this by - * taking a nullable 'maybecx' parameter. In some cases, though, a function - * always needs a 'cx', but optionally reports. This option is presented by the - * MaybeReportError. - */ -enum MaybeReportError { REPORT_ERROR = true, DONT_REPORT_ERROR = false }; - /*****************************************************************************/ /* A bit array is an array of bits represented by an array of words (size_t). */ @@ -391,4 +382,4 @@ typedef size_t jsbitmap; JS_END_MACRO #endif -#endif /* jsutil_h___ */ +#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/win32/jsversion.h b/external/spidermonkey/include/win32/jsversion.h index f3169fb5d1..1780616a32 100644 --- a/external/spidermonkey/include/win32/jsversion.h +++ b/external/spidermonkey/include/win32/jsversion.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jsversion_h___ -#define jsversion_h___ +#ifndef jsversion_h +#define jsversion_h /* * Deprecated JS_VERSION handler. @@ -61,7 +61,7 @@ # define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else # define NEW_OBJECT_REPRESENTATION_ONLY() \ - MOZ_NOT_REACHED("don't call this! to be used in the new object representation") + MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif -#endif /* jsversion_h___ */ +#endif /* jsversion_h */ diff --git a/external/spidermonkey/include/win32/jswrapper.h b/external/spidermonkey/include/win32/jswrapper.h index d0c0fc625c..f78df7db60 100644 --- a/external/spidermonkey/include/win32/jswrapper.h +++ b/external/spidermonkey/include/win32/jswrapper.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef jswrapper_h___ -#define jswrapper_h___ +#ifndef jswrapper_h +#define jswrapper_h #include "mozilla/Attributes.h" @@ -66,8 +66,6 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler static Wrapper singleton; static Wrapper singletonWithPrototype; - - static void *getWrapperFamily(); }; /* Base class for all cross compartment wrapper handlers. */ @@ -105,7 +103,7 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper MutableHandleValue vp) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject wrapper, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -139,7 +137,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base public: SecurityWrapper(unsigned flags); - virtual bool isExtensible(JSObject *wrapper) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject wrapper, bool *extensible) MOZ_OVERRIDE; virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool enter(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool *bp) MOZ_OVERRIDE; @@ -185,7 +183,7 @@ class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler virtual bool enumerate(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; /* Spidermonkey extensions. */ - virtual bool isExtensible(JSObject *proxy) MOZ_OVERRIDE; + virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE; virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE; virtual bool nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, @@ -297,4 +295,4 @@ struct JS_FRIEND_API(AutoMaybeTouchDeadZones) } /* namespace js */ -#endif +#endif /* jswrapper_h */ diff --git a/external/spidermonkey/include/win32/mozilla/AllocPolicy.h b/external/spidermonkey/include/win32/mozilla/AllocPolicy.h new file mode 100644 index 0000000000..20087e93bb --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/AllocPolicy.h @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * An allocation policy concept, usable for structures and algorithms to + * control how memory is allocated and how failures are handled. + */ + +#ifndef mozilla_AllocPolicy_h +#define mozilla_AllocPolicy_h + +#include +#include + +namespace mozilla { + +/* + * Allocation policies are used to implement the standard allocation behaviors + * in a customizable way. Additionally, custom behaviors may be added to these + * behaviors, such as additionally reporting an error through an out-of-band + * mechanism when OOM occurs. The concept modeled here is as follows: + * + * - public copy constructor, assignment, destructor + * - void* malloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* calloc_(size_t) + * Responsible for OOM reporting when null is returned. + * - void* realloc_(void*, size_t, size_t) + * Responsible for OOM reporting when null is returned. The *used* bytes + * of the previous buffer is passed in (rather than the old allocation + * size), in addition to the *new* allocation size requested. + * - void free_(void*) + * - void reportAllocOverflow() const + * Called on allocation overflow (that is, an allocation implicitly tried + * to allocate more than the available memory space -- think allocating an + * array of large-size objects, where N * size overflows) before null is + * returned. + * + * mfbt provides (and typically uses by default) only MallocAllocPolicy, which + * does nothing more than delegate to the malloc/alloc/free functions. + */ + +/* + * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no + * extra behaviors. + */ +class MallocAllocPolicy +{ + public: + void* malloc_(size_t bytes) { return malloc(bytes); } + void* calloc_(size_t bytes) { return calloc(bytes, 1); } + void* realloc_(void* p, size_t oldBytes, size_t bytes) { return realloc(p, bytes); } + void free_(void* p) { free(p); } + void reportAllocOverflow() const {} +}; + + +} // namespace mozilla + +#endif /* mozilla_AllocPolicy_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Array.h b/external/spidermonkey/include/win32/mozilla/Array.h new file mode 100644 index 0000000000..5af9aaa133 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Array.h @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A compile-time constant-length array with bounds-checking assertions. */ + +#ifndef mozilla_Array_h +#define mozilla_Array_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" + +#include + +namespace mozilla { + +template +class Array +{ + T arr[Length]; + + public: + T& operator[](size_t i) { + MOZ_ASSERT(i < Length); + return arr[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(i < Length); + return arr[i]; + } +}; + +template +class Array +{ + public: + T& operator[](size_t i) { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } + + const T& operator[](size_t i) const { + MOZ_ASSUME_UNREACHABLE("indexing into zero-length array"); + } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Array_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Assertions.h b/external/spidermonkey/include/win32/mozilla/Assertions.h index 5ead7f493e..00b7037802 100644 --- a/external/spidermonkey/include/win32/mozilla/Assertions.h +++ b/external/spidermonkey/include/win32/mozilla/Assertions.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of runtime and static assertion macros for C and C++. */ -#ifndef mozilla_Assertions_h_ -#define mozilla_Assertions_h_ +#ifndef mozilla_Assertions_h +#define mozilla_Assertions_h #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" @@ -39,44 +40,24 @@ #endif /* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This - * can be useful when you make certain assumptions about what must hold for + * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. + * In C++11, static_assert is provided by the compiler to the same effect. + * This can be useful when you make certain assumptions about what must hold for * optimal, or even correct, behavior. For example, you might assert that the * size of a struct is a multiple of the target architecture's word size: * * struct S { ... }; + * // C * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, * "S should be a multiple of word size for efficiency"); + * // C++11 + * static_assert(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); * * This macro can be used in any location where both an extern declaration and a * typedef could be used. - * - * Be aware of the gcc 4.2 concerns noted further down when writing patches that - * use this macro, particularly if a patch only bounces on OS X. */ -#ifdef __cplusplus -# if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# elif defined(__HP_aCC) -# if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE) -# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason) -# endif -# endif -#endif -#ifndef MOZ_STATIC_ASSERT +#ifndef __cplusplus /* * Some of the definitions below create an otherwise-unused typedef. This * triggers compiler warnings with some versions of gcc, so mark the typedefs @@ -124,78 +105,23 @@ # define MOZ_STATIC_ASSERT(cond, reason) \ extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE # endif -#endif #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) +#else +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) +#endif #ifdef __cplusplus extern "C" { #endif -/* - * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible - * way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. We use TerminateProcess - * with the exit code aborting would generate because we don't want to invoke - * atexit handlers, destructors, library unload handlers, and so on when our - * process might be in a compromised state. We don't use abort() because - * it'd cause Windows to annoyingly pop up the process error dialog multiple - * times. See bug 345118 and bug 426163. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = 123; \ - TerminateProcess(GetCurrentProcess(), 3); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - ::abort(); \ - } while (0) -# else -# define MOZ_CRASH() \ - do { \ - *((volatile int*) NULL) = 123; \ - abort(); \ - } while (0) -# endif -#endif - /* * Prints |s| as an assertion failure (using file and ln as the location of the * assertion) to the standard debug-output channel. * - * Usually you should use MOZ_ASSERT instead of this method. This method is - * primarily for internal use in this header, and only secondarily for use in - * implementing release-build assertions. + * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This + * method is primarily for internal use in this header, and only secondarily + * for use in implementing release-build assertions. */ static MOZ_ALWAYS_INLINE void MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) @@ -209,6 +135,112 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif } +static MOZ_ALWAYS_INLINE void +MOZ_ReportCrash(const char* s, const char* file, int ln) +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", + "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); +#else + fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln); + fflush(stderr); +#endif +} + +/** + * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should + * call MOZ_CRASH instead. + */ +#if defined(_MSC_VER) + /* + * On MSVC use the __debugbreak compiler intrinsic, which produces an inline + * (not nested in a system function) breakpoint. This distinctively invokes + * Breakpad without requiring system library symbols on all stack-processing + * machines, as a nested breakpoint would require. + * + * We use TerminateProcess with the exit code aborting would generate + * because we don't want to invoke atexit handlers, destructors, library + * unload handlers, and so on when our process might be in a compromised + * state. + * + * We don't use abort() because it'd cause Windows to annoyingly pop up the + * process error dialog multiple times. See bug 345118 and bug 426163. + * + * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the + * compiler doesn't hassle us to provide a return statement after a + * MOZ_REALLY_CRASH() call. + * + * (Technically these are Windows requirements, not MSVC requirements. But + * practically you need MSVC for debugging, and we only ship builds created + * by MSVC, so doing it this way reduces complexity.) + */ + +__declspec(noreturn) __inline void MOZ_NoReturn() {} + +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + ::TerminateProcess(::GetCurrentProcess(), 3); \ + ::MOZ_NoReturn(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = 123; \ + TerminateProcess(GetCurrentProcess(), 3); \ + MOZ_NoReturn(); \ + } while (0) +# endif +#else +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + ::abort(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = 123; \ + abort(); \ + } while (0) +# endif +#endif + +/* + * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a + * Breakpad-compatible way, in both debug and release builds. + * + * MOZ_CRASH is a good solution for "handling" failure cases when you're + * unwilling or unable to handle them more cleanly -- for OOM, for likely memory + * corruption, and so on. It's also a good solution if you need safe behavior + * in release builds as well as debug builds. But if the failure is one that + * should be debugged and fixed, MOZ_ASSERT is generally preferable. + * + * The optional explanation-string, if provided, must be a string literal + * explaining why we're crashing. This argument is intended for use with + * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's + * obvious why we're crashing. + * + * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an + * explanation-string, we print the string to stderr. Otherwise, we don't + * print anything; this is because we want MOZ_CRASH to be 100% safe in release + * builds, and it's hard to print to stderr safely when memory might have been + * corrupted. + */ +#ifndef DEBUG +# define MOZ_CRASH(...) MOZ_REALLY_CRASH() +#else +# define MOZ_CRASH(...) \ + do { \ + MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } while(0) +#endif + #ifdef __cplusplus } /* extern "C" */ #endif @@ -251,7 +283,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* Now the two-argument form. */ @@ -259,7 +291,7 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) do { \ if (MOZ_UNLIKELY(!(expr))) { \ MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH(); \ + MOZ_REALLY_CRASH(); \ } \ } while (0) /* And now, helper macrology up the wazoo. */ @@ -310,14 +342,14 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) #endif /* - * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is + * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is * undefined behavior for execution to reach this point. No guarantees are made * about what will happen if this is reached at runtime. Most code should - * probably use the higher level MOZ_NOT_REACHED, which uses this when + * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when * appropriate. */ #if defined(__clang__) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() #elif defined(__GNUC__) /* * __builtin_unreachable() was implemented in gcc 4.5. If we don't have @@ -325,49 +357,71 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) * in C++ in case there's another abort() visible in local scope. */ # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0) -# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable() +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() # else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif # endif #elif defined(_MSC_VER) -# define MOZ_NOT_REACHED_MARKER() __assume(0) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) #else # ifdef __cplusplus -# define MOZ_NOT_REACHED_MARKER() ::abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() # else -# define MOZ_NOT_REACHED_MARKER() abort() +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() # endif #endif /* - * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached - * during execution: simply reaching that point in execution is a bug. It takes - * as an argument an error message indicating the reason why that point should - * not have been reachable. + * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that + * the macro call cannot be reached during execution. This lets the compiler + * generate better-optimized code under some circumstances, at the expense of + * the program's behavior being undefined if control reaches the + * MOZ_ASSUME_UNREACHABLE. * - * // ...in a language parser... - * void handle(BooleanLiteralNode node) + * In Gecko, you probably should not use this macro outside of performance- or + * size-critical code, because it's unsafe. If you don't care about code size + * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. + * + * SpiderMonkey is a different beast, and there it's acceptable to use + * MOZ_ASSUME_UNREACHABLE more widely. + * + * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a + * value following a MOZ_ASSUME_UNREACHABLE call. + * + * Example usage: + * + * enum ValueType { + * VALUE_STRING, + * VALUE_INT, + * VALUE_FLOAT + * }; + * + * int ptrToInt(ValueType type, void* value) { * { - * if (node.isTrue()) - * handleTrueLiteral(); - * else if (node.isFalse()) - * handleFalseLiteral(); - * else - * MOZ_NOT_REACHED("boolean literal that's not true or false?"); + * // We know for sure that type is either INT or FLOAT, and we want this + * // code to run as quickly as possible. + * switch (type) { + * case VALUE_INT: + * return *(int*) value; + * case VALUE_FLOAT: + * return (int) *(float*) value; + * default: + * MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT"); + * } * } */ #if defined(DEBUG) -# define MOZ_NOT_REACHED(reason) \ +# define MOZ_ASSUME_UNREACHABLE(...) \ do { \ - MOZ_ASSERT(false, reason); \ - MOZ_NOT_REACHED_MARKER(); \ + MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \ + MOZ_ASSUME_UNREACHABLE_MARKER(); \ } while (0) #else -# define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER() +# define MOZ_ASSUME_UNREACHABLE(reason) MOZ_ASSUME_UNREACHABLE_MARKER() #endif /* @@ -384,4 +438,4 @@ MOZ_ReportAssertionFailure(const char* s, const char* file, int ln) # define MOZ_ALWAYS_FALSE(expr) ((void)(expr)) #endif -#endif /* mozilla_Assertions_h_ */ +#endif /* mozilla_Assertions_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Atomics.h b/external/spidermonkey/include/win32/mozilla/Atomics.h new file mode 100644 index 0000000000..f876683c3e --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Atomics.h @@ -0,0 +1,1014 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Implements (almost always) lock-free atomic operations. The operations here + * are a subset of that which can be found in C++11's header, with a + * different API to enforce consistent memory ordering constraints. + * + * Anyone caught using |volatile| for inter-thread memory safety needs to be + * sent a copy of this header and the C++11 standard. + */ + +#ifndef mozilla_Atomics_h +#define mozilla_Atomics_h + +#include "mozilla/Assertions.h" +#include "mozilla/TypeTraits.h" + +#include + +/* + * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK + * does not have . So be sure to check for support + * along with C++0x support. + */ +#if defined(__clang__) + /* + * clang doesn't like libstdc++'s version of before GCC 4.7, + * due to the loose typing of the __sync_* family of functions done by + * GCC. We do not have a particularly good way to detect this sort of + * case at this point, so just assume that if we're on a Linux system, + * we can't use the system's . + * + * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + */ +# if !defined(__linux__) && !defined(__OpenBSD__) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ + __has_include() +# define MOZ_HAVE_CXX11_ATOMICS +# endif +/* + * Android uses a different C++ standard library that does not provide + * support for . + * + * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include + * inline definitions for the functions declared therein. This oversight + * leads to linking errors when using atomic enums. We therefore require + * GCC 4.7 or higher. + */ +#elif defined(__GNUC__) && !defined(__ANDROID__) +# include "mozilla/Compiler.h" +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ + MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# define MOZ_HAVE_CXX11_ATOMICS +# endif +#elif defined(_MSC_VER) && _MSC_VER >= 1700 +# define MOZ_HAVE_CXX11_ATOMICS +#endif + +namespace mozilla { + +/** + * An enum of memory ordering possibilities for atomics. + * + * Memory ordering is the observable state of distinct values in memory. + * (It's a separate concept from atomicity, which concerns whether an + * operation can ever be observed in an intermediate state. Don't + * conflate the two!) Given a sequence of operations in source code on + * memory, it is *not* always the case that, at all times and on all + * cores, those operations will appear to have occurred in that exact + * sequence. First, the compiler might reorder that sequence, if it + * thinks another ordering will be more efficient. Second, the CPU may + * not expose so consistent a view of memory. CPUs will often perform + * their own instruction reordering, above and beyond that performed by + * the compiler. And each core has its own memory caches, and accesses + * (reads and writes both) to "memory" may only resolve to out-of-date + * cache entries -- not to the "most recently" performed operation in + * some global sense. Any access to a value that may be used by + * multiple threads, potentially across multiple cores, must therefore + * have a memory ordering imposed on it, for all code on all + * threads/cores to have a sufficiently coherent worldview. + * + * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and + * http://en.cppreference.com/w/cpp/atomic/memory_order go into more + * detail on all this, including examples of how each mode works. + * + * Note that for simplicity and practicality, not all of the modes in + * C++11 are supported. The missing C++11 modes are either subsumed by + * the modes we provide below, or not relevant for the CPUs we support + * in Gecko. These three modes are confusing enough as it is! + */ +enum MemoryOrdering { + /* + * Relaxed ordering is the simplest memory ordering: none at all. + * When the result of a write is observed, nothing may be inferred + * about other memory. Writes ostensibly performed "before" on the + * writing thread may not yet be visible. Writes performed "after" on + * the writing thread may already be visible, if the compiler or CPU + * reordered them. (The latter can happen if reads and/or writes get + * held up in per-processor caches.) Relaxed ordering means + * operations can always use cached values (as long as the actual + * updates to atomic values actually occur, correctly, eventually), so + * it's usually the fastest sort of atomic access. For this reason, + * *it's also the most dangerous kind of access*. + * + * Relaxed ordering is good for things like process-wide statistics + * counters that don't need to be consistent with anything else, so + * long as updates themselves are atomic. (And so long as any + * observations of that value can tolerate being out-of-date -- if you + * need some sort of up-to-date value, you need some sort of other + * synchronizing operation.) It's *not* good for locks, mutexes, + * reference counts, etc. that mediate access to other memory, or must + * be observably consistent with other memory. + * + * x86 architectures don't take advantage of the optimization + * opportunities that relaxed ordering permits. Thus it's possible + * that using relaxed ordering will "work" on x86 but fail elsewhere + * (ARM, say, which *does* implement non-sequentially-consistent + * relaxed ordering semantics). Be extra-careful using relaxed + * ordering if you can't easily test non-x86 architectures! + */ + Relaxed, + /* + * When an atomic value is updated with ReleaseAcquire ordering, and + * that new value is observed with ReleaseAcquire ordering, prior + * writes (atomic or not) are also observable. What ReleaseAcquire + * *doesn't* give you is any observable ordering guarantees for + * ReleaseAcquire-ordered operations on different objects. For + * example, if there are two cores that each perform ReleaseAcquire + * operations on separate objects, each core may or may not observe + * the operations made by the other core. The only way the cores can + * be synchronized with ReleaseAcquire is if they both + * ReleaseAcquire-access the same object. This implies that you can't + * necessarily describe some global total ordering of ReleaseAcquire + * operations. + * + * ReleaseAcquire ordering is good for (as the name implies) atomic + * operations on values controlling ownership of things: reference + * counts, mutexes, and the like. However, if you are thinking about + * using these to implement your own locks or mutexes, you should take + * a good, hard look at actual lock or mutex primitives first. + */ + ReleaseAcquire, + /* + * When an atomic value is updated with SequentiallyConsistent + * ordering, all writes observable when the update is observed, just + * as with ReleaseAcquire ordering. But, furthermore, a global total + * ordering of SequentiallyConsistent operations *can* be described. + * For example, if two cores perform SequentiallyConsistent operations + * on separate objects, one core will observably perform its update + * (and all previous operations will have completed), then the other + * core will observably perform its update (and all previous + * operations will have completed). (Although those previous + * operations aren't themselves ordered -- they could be intermixed, + * or ordered if they occur on atomic values with ordering + * requirements.) SequentiallyConsistent is the *simplest and safest* + * ordering of atomic operations -- it's always as if one operation + * happens, then another, then another, in some order -- and every + * core observes updates to happen in that single order. Because it + * has the most synchronization requirements, operations ordered this + * way also tend to be slowest. + * + * SequentiallyConsistent ordering can be desirable when multiple + * threads observe objects, and they all have to agree on the + * observable order of changes to them. People expect + * SequentiallyConsistent ordering, even if they shouldn't, when + * writing code, atomic or otherwise. SequentiallyConsistent is also + * the ordering of choice when designing lockless data structures. If + * you don't know what order to use, use this one. + */ + SequentiallyConsistent, +}; + +} // namespace mozilla + +// Build up the underlying intrinsics. +#ifdef MOZ_HAVE_CXX11_ATOMICS + +# include + +namespace mozilla { +namespace detail { + +/* + * We provide CompareExchangeFailureOrder to work around a bug in some + * versions of GCC's header. See bug 898491. + */ +template struct AtomicOrderConstraints; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; + static const std::memory_order LoadOrder = std::memory_order_relaxed; + static const std::memory_order StoreOrder = std::memory_order_relaxed; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_relaxed; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; + static const std::memory_order LoadOrder = std::memory_order_acquire; + static const std::memory_order StoreOrder = std::memory_order_release; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_acquire; +}; + +template<> +struct AtomicOrderConstraints +{ + static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; + static const std::memory_order LoadOrder = std::memory_order_seq_cst; + static const std::memory_order StoreOrder = std::memory_order_seq_cst; + static const std::memory_order CompareExchangeFailureOrder = + std::memory_order_seq_cst; +}; + +template +struct IntrinsicBase +{ + typedef std::atomic ValueType; + typedef AtomicOrderConstraints OrderedOp; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T load(const typename Base::ValueType& ptr) { + return ptr.load(Base::OrderedOp::LoadOrder); + } + static void store(typename Base::ValueType& ptr, T val) { + ptr.store(val, Base::OrderedOp::StoreOrder); + } + static T exchange(typename Base::ValueType& ptr, T val) { + return ptr.exchange(val, Base::OrderedOp::AtomicRMWOrder); + } + static bool compareExchange(typename Base::ValueType& ptr, T oldVal, T newVal) { + return ptr.compare_exchange_strong(oldVal, newVal, + Base::OrderedOp::AtomicRMWOrder, + Base::OrderedOp::CompareExchangeFailureOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T add(typename Base::ValueType& ptr, T val) { + return ptr.fetch_add(val, Base::OrderedOp::AtomicRMWOrder); + } + static T sub(typename Base::ValueType& ptr, T val) { + return ptr.fetch_sub(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicBase +{ + typedef IntrinsicBase Base; + static T* add(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_add(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + static T* sub(typename Base::ValueType& ptr, ptrdiff_t val) { + return ptr.fetch_sub(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder); + } + private: + /* + * GCC 4.6's header has a bug where adding X to an + * atomic is not the same as adding X to a T*. Hence the need + * for this function to provide the correct addend. + */ + static ptrdiff_t fixupAddend(ptrdiff_t val) { +#if defined(__clang__) || defined(_MSC_VER) + return val; +#elif defined(__GNUC__) && MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) && \ + !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) + return val * sizeof(T); +#else + return val; +#endif + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + typedef IntrinsicBase Base; + static T inc(typename Base::ValueType& ptr) { + return IntrinsicAddSub::add(ptr, 1); + } + static T dec(typename Base::ValueType& ptr) { + return IntrinsicAddSub::sub(ptr, 1); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + typedef IntrinsicBase Base; + static T or_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_or(val, Base::OrderedOp::AtomicRMWOrder); + } + static T xor_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_xor(val, Base::OrderedOp::AtomicRMWOrder); + } + static T and_(typename Base::ValueType& ptr, T val) { + return ptr.fetch_and(val, Base::OrderedOp::AtomicRMWOrder); + } +}; + +template +struct AtomicIntrinsics + : public IntrinsicMemoryOps, public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(__GNUC__) + +namespace mozilla { +namespace detail { + +/* + * The __sync_* family of intrinsics is documented here: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html + * + * While these intrinsics are deprecated in favor of the newer __atomic_* + * family of intrincs: + * + * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html + * + * any GCC version that supports the __atomic_* intrinsics will also support + * the header and so will be handled above. We provide a version of + * atomics using the __sync_* intrinsics to support older versions of GCC. + * + * All __sync_* intrinsics that we use below act as full memory barriers, for + * both compiler and hardware reordering, except for __sync_lock_test_and_set, + * which is a only an acquire barrier. When we call __sync_lock_test_and_set, + * we add a barrier above it as appropriate. + */ + +template struct Barrier; + +/* + * Some processors (in particular, x86) don't require quite so many calls to + * __sync_sychronize as our specializations of Barrier produce. If + * performance turns out to be an issue, defining these specializations + * on a per-processor basis would be a good first tuning step. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() { __sync_synchronize(); } + static void afterLoad() { __sync_synchronize(); } + static void beforeStore() { __sync_synchronize(); } + static void afterStore() { __sync_synchronize(); } +}; + +template +struct IntrinsicMemoryOps +{ + static T load(const T& ptr) { + Barrier::beforeLoad(); + T val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(T& ptr, T val) { + Barrier::beforeStore(); + ptr = val; + Barrier::afterStore(); + } + static T exchange(T& ptr, T val) { + // __sync_lock_test_and_set is only an acquire barrier; loads and stores + // can't be moved up from after to before it, but they can be moved down + // from before to after it. We may want a stricter ordering, so we need + // an explicit barrier. + + Barrier::beforeStore(); + return __sync_lock_test_and_set(&ptr, val); + } + static bool compareExchange(T& ptr, T oldVal, T newVal) { + return __sync_bool_compare_and_swap(&ptr, oldVal, newVal); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T ValueType; + static T add(T& ptr, T val) { + return __sync_fetch_and_add(&ptr, val); + } + static T sub(T& ptr, T val) { + return __sync_fetch_and_sub(&ptr, val); + } +}; + +template +struct IntrinsicAddSub +{ + typedef T* ValueType; + /* + * The reinterpret_casts are needed so that + * __sync_fetch_and_{add,sub} will properly type-check. + * + * Also, these functions do not provide standard semantics for + * pointer types, so we need to adjust the addend. + */ + static ValueType add(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_add(&ptr, amount); + } + static ValueType sub(ValueType& ptr, ptrdiff_t val) { + ValueType amount = reinterpret_cast(val * sizeof(T)); + return __sync_fetch_and_sub(&ptr, amount); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static T inc(T& ptr) { return IntrinsicAddSub::add(ptr, 1); } + static T dec(T& ptr) { return IntrinsicAddSub::sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static T or_(T& ptr, T val) { + return __sync_fetch_and_or(&ptr, val); + } + static T xor_(T& ptr, T val) { + return __sync_fetch_and_xor(&ptr, val); + } + static T and_(T& ptr, T val) { + return __sync_fetch_and_and(&ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#elif defined(_MSC_VER) + +/* + * Windows comes with a full complement of atomic operations. + * Unfortunately, most of those aren't available for Windows XP (even if + * the compiler supports intrinsics for them), which is the oldest + * version of Windows we support. Therefore, we only provide operations + * on 32-bit datatypes for 32-bit Windows versions; for 64-bit Windows + * versions, we support 64-bit datatypes as well. + * + * To avoid namespace pollution issues, we declare whatever functions we + * need ourselves. + */ + +extern "C" { +long __cdecl _InterlockedExchangeAdd(long volatile* dst, long value); +long __cdecl _InterlockedOr(long volatile* dst, long value); +long __cdecl _InterlockedXor(long volatile* dst, long value); +long __cdecl _InterlockedAnd(long volatile* dst, long value); +long __cdecl _InterlockedExchange(long volatile *dst, long value); +long __cdecl _InterlockedCompareExchange(long volatile *dst, long newVal, long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd) +# pragma intrinsic(_InterlockedOr) +# pragma intrinsic(_InterlockedXor) +# pragma intrinsic(_InterlockedAnd) +# pragma intrinsic(_InterlockedExchange) +# pragma intrinsic(_InterlockedCompareExchange) + +namespace mozilla { +namespace detail { + +# if !defined(_M_IX86) && !defined(_M_X64) + /* + * The implementations below are optimized for x86ish systems. You + * will have to modify them if you are porting to Windows on a + * different architecture. + */ +# error "Unknown CPU type" +# endif + +/* + * The PrimitiveIntrinsics template should define |Type|, the datatype of size + * DataSize upon which we operate, and the following eight functions. + * + * static Type add(Type* ptr, Type val); + * static Type sub(Type* ptr, Type val); + * static Type or_(Type* ptr, Type val); + * static Type xor_(Type* ptr, Type val); + * static Type and_(Type* ptr, Type val); + * + * These functions perform the obvious operation on the value contained in + * |*ptr| combined with |val| and return the value previously stored in + * |*ptr|. + * + * static void store(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and must provide a full + * memory fence after the store to prevent compiler and hardware instruction + * reordering. It should also act as a compiler barrier to prevent reads and + * writes from moving to after the store. + * + * static Type exchange(Type* ptr, Type val); + * + * This function atomically stores |val| into |*ptr| and returns the previous + * contents of *ptr; + * + * static bool compareExchange(Type* ptr, Type oldVal, Type newVal); + * + * This function atomically performs the following operation: + * + * if (*ptr == oldVal) { + * *ptr = newVal; + * return true; + * } else { + * return false; + * } + * + */ +template struct PrimitiveIntrinsics; + +template<> +struct PrimitiveIntrinsics<4> +{ + typedef long Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * _InterlockedExchangeSubtract isn't available before Windows 7, + * and we must support Windows XP. + */ + return _InterlockedExchangeAdd(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange(ptr, newVal, oldVal) == oldVal; + } +}; + +# if defined(_M_X64) + +extern "C" { +long long __cdecl _InterlockedExchangeAdd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedOr64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedXor64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedAnd64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedExchange64(long long volatile* dst, + long long value); +long long __cdecl _InterlockedCompareExchange64(long long volatile* dst, + long long newVal, + long long oldVal); +} + +# pragma intrinsic(_InterlockedExchangeAdd64) +# pragma intrinsic(_InterlockedOr64) +# pragma intrinsic(_InterlockedXor64) +# pragma intrinsic(_InterlockedAnd64) +# pragma intrinsic(_InterlockedExchange64) +# pragma intrinsic(_InterlockedCompareExchange64) + +template <> +struct PrimitiveIntrinsics<8> +{ + typedef __int64 Type; + + static Type add(Type* ptr, Type val) { + return _InterlockedExchangeAdd64(ptr, val); + } + static Type sub(Type* ptr, Type val) { + /* + * There is no _InterlockedExchangeSubtract64. + */ + return _InterlockedExchangeAdd64(ptr, -val); + } + static Type or_(Type* ptr, Type val) { + return _InterlockedOr64(ptr, val); + } + static Type xor_(Type* ptr, Type val) { + return _InterlockedXor64(ptr, val); + } + static Type and_(Type* ptr, Type val) { + return _InterlockedAnd64(ptr, val); + } + static void store(Type* ptr, Type val) { + _InterlockedExchange64(ptr, val); + } + static Type exchange(Type* ptr, Type val) { + return _InterlockedExchange64(ptr, val); + } + static bool compareExchange(Type* ptr, Type oldVal, Type newVal) { + return _InterlockedCompareExchange64(ptr, newVal, oldVal) == oldVal; + } +}; + +# endif + +extern "C" { void _ReadWriteBarrier(); } + +# pragma intrinsic(_ReadWriteBarrier) + +template struct Barrier; + +/* + * We do not provide an afterStore method in Barrier, as Relaxed and + * ReleaseAcquire orderings do not require one, and the required barrier + * for SequentiallyConsistent is handled by PrimitiveIntrinsics. + */ + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() {} + static void beforeStore() {} +}; + +template<> +struct Barrier +{ + static void beforeLoad() {} + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template<> +struct Barrier +{ + static void beforeLoad() { _ReadWriteBarrier(); } + static void afterLoad() { _ReadWriteBarrier(); } + static void beforeStore() { _ReadWriteBarrier(); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T val) { return static_cast(val); } + static T fromPrimType(PrimType val) { return static_cast(val); } +}; + +template +struct CastHelper +{ + static PrimType toPrimType(T* val) { return reinterpret_cast(val); } + static T* fromPrimType(PrimType val) { return reinterpret_cast(val); } +}; + +template +struct IntrinsicBase +{ + typedef T ValueType; + typedef PrimitiveIntrinsics Primitives; + typedef typename Primitives::Type PrimType; + static_assert(sizeof(PrimType) == sizeof(T), + "Selection of PrimitiveIntrinsics was wrong"); + typedef CastHelper Cast; +}; + +template +struct IntrinsicMemoryOps : public IntrinsicBase +{ + static ValueType load(const ValueType& ptr) { + Barrier::beforeLoad(); + ValueType val = ptr; + Barrier::afterLoad(); + return val; + } + static void store(ValueType& ptr, ValueType val) { + // For SequentiallyConsistent, Primitives::store() will generate the + // proper memory fence. Everything else just needs a barrier before + // the store. + if (Order == SequentiallyConsistent) { + Primitives::store(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + } else { + Barrier::beforeStore(); + ptr = val; + } + } + static ValueType exchange(ValueType& ptr, ValueType val) { + PrimType oldval = + Primitives::exchange(reinterpret_cast(&ptr), + Cast::toPrimType(val)); + return Cast::fromPrimType(oldval); + } + static bool compareExchange(ValueType& ptr, ValueType oldVal, ValueType newVal) { + return Primitives::compareExchange(reinterpret_cast(&ptr), + Cast::toPrimType(oldVal), + Cast::toPrimType(newVal)); + } +}; + +template +struct IntrinsicApplyHelper : public IntrinsicBase +{ + typedef PrimType (*BinaryOp)(PrimType*, PrimType); + typedef PrimType (*UnaryOp)(PrimType*); + + static ValueType applyBinaryFunction(BinaryOp op, ValueType& ptr, + ValueType val) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + PrimType primTypeVal = Cast::toPrimType(val); + return Cast::fromPrimType(op(primTypePtr, primTypeVal)); + } + + static ValueType applyUnaryFunction(UnaryOp op, ValueType& ptr) { + PrimType* primTypePtr = reinterpret_cast(&ptr); + return Cast::fromPrimType(op(primTypePtr)); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::add, ptr, val); + } + static ValueType sub(ValueType& ptr, ValueType val) { + return applyBinaryFunction(&Primitives::sub, ptr, val); + } +}; + +template +struct IntrinsicAddSub : public IntrinsicApplyHelper +{ + static ValueType add(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::add, ptr, + (ValueType)(amount * sizeof(ValueType))); + } + static ValueType sub(ValueType& ptr, ptrdiff_t amount) { + return applyBinaryFunction(&Primitives::sub, ptr, + (ValueType)(amount * sizeof(ValueType))); + } +}; + +template +struct IntrinsicIncDec : public IntrinsicAddSub +{ + static ValueType inc(ValueType& ptr) { return add(ptr, 1); } + static ValueType dec(ValueType& ptr) { return sub(ptr, 1); } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ + static ValueType or_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::or_, ptr, val); + } + static ValueType xor_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::xor_, ptr, val); + } + static ValueType and_(ValueType& ptr, T val) { + return applyBinaryFunction(&Primitives::and_, ptr, val); + } +}; + +template +struct AtomicIntrinsics : public IntrinsicMemoryOps, + public IntrinsicIncDec +{ +}; + +} // namespace detail +} // namespace mozilla + +#else +# error "Atomic compiler intrinsics are not supported on your platform" +#endif + +namespace mozilla { + +namespace detail { + +template +class AtomicBase +{ + // We only support 32-bit types on 32-bit Windows, which constrains our + // implementation elsewhere. But we support pointer-sized types everywhere. + static_assert(sizeof(T) == 4 || (sizeof(uintptr_t) == 8 && sizeof(T) == 8), + "mozilla/Atomics.h only supports 32-bit and pointer-sized types"); + + protected: + typedef typename detail::AtomicIntrinsics Intrinsics; + typename Intrinsics::ValueType mValue; + + public: + AtomicBase() : mValue() {} + AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + + operator T() const { return Intrinsics::load(mValue); } + + T operator=(T aValue) { + Intrinsics::store(mValue, aValue); + return aValue; + } + + /** + * Performs an atomic swap operation. aValue is stored and the previous + * value of this variable is returned. + */ + T exchange(T aValue) { + return Intrinsics::exchange(mValue, aValue); + } + + /** + * Performs an atomic compare-and-swap operation and returns true if it + * succeeded. This is equivalent to atomically doing + * + * if (mValue == aOldValue) { + * mValue = aNewValue; + * return true; + * } else { + * return false; + * } + */ + bool compareExchange(T aOldValue, T aNewValue) { + return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); + } + + private: + template + AtomicBase(const AtomicBase& aCopy) MOZ_DELETE; +}; + +template +class AtomicBaseIncDec : public AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + AtomicBaseIncDec() : Base() {} + AtomicBaseIncDec(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } + T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } + T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } + T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } + + private: + template + AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) MOZ_DELETE; +}; + +} // namespace detail + +/** + * A wrapper for a type that enforces that all memory accesses are atomic. + * + * In general, where a variable |T foo| exists, |Atomic foo| can be used in + * its place. Implementations for integral and pointer types are provided + * below. + * + * Atomic accesses are sequentially consistent by default. You should + * use the default unless you are tall enough to ride the + * memory-ordering roller coaster (if you're not sure, you aren't) and + * you have a compelling reason to do otherwise. + * + * There is one exception to the case of atomic memory accesses: providing an + * initial value of the atomic value is not guaranteed to be atomic. This is a + * deliberate design choice that enables static atomic variables to be declared + * without introducing extra static constructors. + */ +template +class Atomic; + +/** + * Atomic implementation for integral types. + * + * In addition to atomic store and load operations, compound assignment and + * increment/decrement operators are implemented which perform the + * corresponding read-modify-write operation atomically. Finally, an atomic + * swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + T operator+=(T delta) { return Base::Intrinsics::add(Base::mValue, delta) + delta; } + T operator-=(T delta) { return Base::Intrinsics::sub(Base::mValue, delta) - delta; } + T operator|=(T val) { return Base::Intrinsics::or_(Base::mValue, val) | val; } + T operator^=(T val) { return Base::Intrinsics::xor_(Base::mValue, val) ^ val; } + T operator&=(T val) { return Base::Intrinsics::and_(Base::mValue, val) & val; } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for pointer types. + * + * An atomic compare-and-swap primitive for pointer variables is provided, as + * are atomic increment and decement operators. Also provided are the compound + * assignment operators for addition and subtraction. Atomic swap (via + * exchange()) is included as well. + */ +template +class Atomic : public detail::AtomicBaseIncDec +{ + typedef typename detail::AtomicBaseIncDec Base; + + public: + Atomic() : Base() {} + Atomic(T* aInit) : Base(aInit) {} + + using Base::operator=; + + T* operator+=(ptrdiff_t delta) { + return Base::Intrinsics::add(Base::mValue, delta) + delta; + } + T* operator-=(ptrdiff_t delta) { + return Base::Intrinsics::sub(Base::mValue, delta) - delta; + } + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +/** + * Atomic implementation for enum types. + * + * The atomic store and load operations and the atomic swap method is provided. + */ +template +class Atomic::value>::Type> + : public detail::AtomicBase +{ + typedef typename detail::AtomicBase Base; + + public: + Atomic() : Base() {} + Atomic(T aInit) : Base(aInit) {} + + using Base::operator=; + + private: + Atomic(Atomic& aOther) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Atomics_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Attributes.h b/external/spidermonkey/include/win32/mozilla/Attributes.h index 89f3641fc9..6ea9776fbf 100644 --- a/external/spidermonkey/include/win32/mozilla/Attributes.h +++ b/external/spidermonkey/include/win32/mozilla/Attributes.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implementations of various class and method modifier attributes. */ -#ifndef mozilla_Attributes_h_ -#define mozilla_Attributes_h_ +#ifndef mozilla_Attributes_h +#define mozilla_Attributes_h #include "mozilla/Compiler.h" @@ -117,11 +118,18 @@ * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a * function at compile time. A constexpr function cannot examine any values * except its arguments and can have no side effects except its return value. + * The MOZ_CONSTEXPR_VAR specifier tells a C++11 compiler that a variable's + * value may be computed at compile time. It should be prefered to just + * marking variables as MOZ_CONSTEXPR because if the compiler does not support + * constexpr it will fall back to making the variable const, and some compilers + * do not accept variables being marked both const and constexpr. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR # define MOZ_CONSTEXPR constexpr +# define MOZ_CONSTEXPR_VAR constexpr #else # define MOZ_CONSTEXPR /* no support */ +# define MOZ_CONSTEXPR_VAR const #endif /* @@ -382,18 +390,42 @@ * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is * expected to live on the stack, so it is a compile-time error to use it, or * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). It may be a base or - * a member of another class only if both classes are marked with this - * annotation. + * a new expression (unless placement new is being used). If a member of + * another class uses this class, or if another class inherits from this + * class, then it is considered to be a stack class as well, although this + * attribute need not be provided in such cases. + * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack or in static storage, so it is a compile-time + * error to use it, or an array of such objects, as the type of a new + * expression (unless placement new is being used). If a member of another + * class uses this class, or if another class inherits from this class, then + * it is considered to be a non-heap class as well, although this attribute + * need not be provided in such cases. */ #ifdef MOZ_CLANG_PLUGIN # define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) # define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) +# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) #else # define MOZ_MUST_OVERRIDE /* nothing */ # define MOZ_STACK_CLASS /* nothing */ +# define MOZ_NONHEAP_CLASS /* nothing */ #endif /* MOZ_CLANG_PLUGIN */ +/* + * MOZ_THIS_IN_INITIALIZER_LIST is used to avoid a warning when we know that + * it's safe to use 'this' in an initializer list. + */ +#ifdef _MSC_VER +# define MOZ_THIS_IN_INITIALIZER_LIST() \ + __pragma(warning(push)) \ + __pragma(warning(disable:4355)) \ + this \ + __pragma(warning(pop)) +#else +# define MOZ_THIS_IN_INITIALIZER_LIST() this +#endif + #endif /* __cplusplus */ -#endif /* mozilla_Attributes_h_ */ +#endif /* mozilla_Attributes_h */ diff --git a/external/spidermonkey/include/win32/mozilla/BloomFilter.h b/external/spidermonkey/include/win32/mozilla/BloomFilter.h index 8680ef2907..afe4b72b80 100644 --- a/external/spidermonkey/include/win32/mozilla/BloomFilter.h +++ b/external/spidermonkey/include/win32/mozilla/BloomFilter.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * A counting Bloom filter implementation. This allows consumers to @@ -10,14 +11,14 @@ * incorrectly answer "yes" when the correct answer is "no"). */ -#ifndef mozilla_BloomFilter_h_ -#define mozilla_BloomFilter_h_ +#ifndef mozilla_BloomFilter_h +#define mozilla_BloomFilter_h #include "mozilla/Assertions.h" #include "mozilla/Likely.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Util.h" +#include #include namespace mozilla { @@ -105,7 +106,7 @@ class BloomFilter */ public: BloomFilter() { - MOZ_STATIC_ASSERT(KeySize <= keyShift, "KeySize too big"); + static_assert(KeySize <= keyShift, "KeySize too big"); // Should we have a custom operator new using calloc instead and // require that we're allocated via the operator? @@ -231,4 +232,4 @@ BloomFilter::mightContain(const T* t) const } // namespace mozilla -#endif /* mozilla_BloomFilter_h_ */ +#endif /* mozilla_BloomFilter_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Casting.h b/external/spidermonkey/include/win32/mozilla/Casting.h index b1e81c33fa..76df0ef27e 100644 --- a/external/spidermonkey/include/win32/mozilla/Casting.h +++ b/external/spidermonkey/include/win32/mozilla/Casting.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cast operations to supplement the built-in casting operations. */ -#ifndef mozilla_Casting_h_ -#define mozilla_Casting_h_ +#ifndef mozilla_Casting_h +#define mozilla_Casting_h #include "mozilla/Assertions.h" #include "mozilla/TypeTraits.h" @@ -15,6 +16,27 @@ namespace mozilla { +/** + * Return a value of type |To|, containing the underlying bit pattern of |from|. + * + * |To| and |From| must be types of the same size; be careful of cross-platform + * size differences, or this might fail to compile on some but not all + * platforms. + */ +template +inline To +BitwiseCast(const From from) +{ + static_assert(sizeof(From) == sizeof(To), + "To and From must have the same size"); + union { + From from; + To to; + } u; + u.from = from; + return u.to; +} + namespace detail { enum ToSignedness { ToIsSigned, ToIsUnsigned }; @@ -43,7 +65,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return from <= From(To(-1)); } }; @@ -52,7 +74,7 @@ template struct UnsignedUnsignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -61,8 +83,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedUnsignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedUnsignedCheck::checkBounds(from); } }; @@ -72,7 +94,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (from < 0) return false; if (sizeof(To) >= sizeof(From)) @@ -93,7 +115,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { return true; } }; @@ -102,7 +124,7 @@ template struct UnsignedSignedCheck { public: - static bool check(const From from) { + static bool checkBounds(const From from) { const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); return from <= From(MaxValue); } @@ -112,8 +134,8 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { - return UnsignedSignedCheck::check(from); + static bool checkBounds(const From from) { + return UnsignedSignedCheck::checkBounds(from); } }; @@ -123,7 +145,7 @@ template struct BoundsCheckImpl { public: - static bool check(const From from) { + static bool checkBounds(const From from) { if (sizeof(From) <= sizeof(To)) return true; const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); @@ -141,15 +163,15 @@ template class BoundsChecker { public: - static bool check(const From from) { return true; } + static bool checkBounds(const From from) { return true; } }; template class BoundsChecker { public: - static bool check(const From from) { - return BoundsCheckImpl::check(from); + static bool checkBounds(const From from) { + return BoundsCheckImpl::checkBounds(from); } }; @@ -157,7 +179,7 @@ template inline bool IsInBounds(const From from) { - return BoundsChecker::check(from); + return BoundsChecker::checkBounds(from); } } // namespace detail @@ -177,4 +199,4 @@ SafeCast(const From from) } // namespace mozilla -#endif /* mozilla_Casting_h_ */ +#endif /* mozilla_Casting_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Char16.h b/external/spidermonkey/include/win32/mozilla/Char16.h index c6f9f87d44..e4b184f950 100644 --- a/external/spidermonkey/include/win32/mozilla/Char16.h +++ b/external/spidermonkey/include/win32/mozilla/Char16.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implements a UTF-16 character type. */ -#ifndef mozilla_Char16_h_ -#define mozilla_Char16_h_ +#ifndef mozilla_Char16_h +#define mozilla_Char16_h #include "mozilla/Assertions.h" @@ -49,8 +50,8 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) -MOZ_STATIC_ASSERT(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); -MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); +static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); -#endif /* mozilla_Char16_h_ */ +#endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/win32/mozilla/CheckedInt.h b/external/spidermonkey/include/win32/mozilla/CheckedInt.h index 1dc80b032b..050cef8ed8 100644 --- a/external/spidermonkey/include/win32/mozilla/CheckedInt.h +++ b/external/spidermonkey/include/win32/mozilla/CheckedInt.h @@ -1,23 +1,23 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Provides checked integers, detecting integer overflow and divide-by-0. */ -#ifndef mozilla_CheckedInt_h_ -#define mozilla_CheckedInt_h_ +#ifndef mozilla_CheckedInt_h +#define mozilla_CheckedInt_h // Enable relying of Mozilla's MFBT for possibly-available C++11 features #define MOZ_CHECKEDINT_USE_MFBT +#include + #ifdef MOZ_CHECKEDINT_USE_MFBT # include "mozilla/Assertions.h" -# include "mozilla/StandardInteger.h" #else # include -# include -# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_ASSERT(cond, reason) assert((cond) && reason) # define MOZ_DELETE #endif @@ -450,6 +450,44 @@ IsDivValid(T x, T y) !(IsSigned::value && x == MinValue::value && y == T(-1)); } +template::value> +struct IsModValidImpl; + +template +inline bool +IsModValid(T x, T y) +{ + return IsModValidImpl::run(x, y); +} + +/* + * Mod is pretty simple. + * For now, let's just use the ANSI C definition: + * If x or y are negative, the results are implementation defined. + * Consider these invalid. + * Undefined for y=0. + * The result will never exceed either x or y. + * + * Checking that x>=0 is a warning when T is unsigned. + */ + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + return y >= 1; + } +}; + +template +struct IsModValidImpl { + static inline bool run(T x, T y) { + if (x < 0) + return false; + + return y >= 1; + } +}; + template::value> struct NegateImpl; @@ -528,7 +566,7 @@ struct NegateImpl CheckedInt x(-1); // 1000 is of type int16_t, is found not to be in range for int8_t, // x is invalid - CheckedInt x(int16_t(1000)); + CheckedInt x(int16_t(1000)); // 3123456789 is of type uint32_t, is found not to be in range for int32_t, // x is invalid CheckedInt x(uint32_t(3123456789)); @@ -561,12 +599,12 @@ class CheckedInt template CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); } - friend class detail::NegateImpl; + friend struct detail::NegateImpl; public: /** @@ -585,16 +623,27 @@ class CheckedInt : mValue(T(value)), mIsValid(detail::IsInRange(value)) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); + } + + template + friend class CheckedInt; + + template + CheckedInt toChecked() const + { + CheckedInt ret(mValue); + ret.mIsValid = ret.mIsValid && mIsValid; + return ret; } /** Constructs a valid checked integer with initial value 0 */ CheckedInt() : mValue(0), mIsValid(true) { - MOZ_STATIC_ASSERT(detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value, + "This type is not supported by CheckedInt"); } /** @returns the actual value */ @@ -619,22 +668,31 @@ class CheckedInt const CheckedInt& rhs); template CheckedInt& operator +=(U rhs); + template friend CheckedInt operator -(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator -=(U rhs); + template friend CheckedInt operator *(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator *=(U rhs); + template friend CheckedInt operator /(const CheckedInt& lhs, - const CheckedInt &rhs); + const CheckedInt& rhs); template CheckedInt& operator /=(U rhs); + template + friend CheckedInt operator %(const CheckedInt& lhs, + const CheckedInt& rhs); + template + CheckedInt& operator %=(U rhs); + CheckedInt operator -() const { return detail::NegateImpl::negate(*this); @@ -726,6 +784,7 @@ MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) +MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) #undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR @@ -757,9 +816,9 @@ template inline typename detail::CastToCheckedIntImpl::ReturnType castToCheckedInt(U u) { - MOZ_STATIC_ASSERT(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); + static_assert(detail::IsSupported::value && + detail::IsSupported::value, + "This type is not supported by CheckedInt"); return detail::CastToCheckedIntImpl::run(u); } @@ -786,6 +845,7 @@ MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) +MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) #undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS @@ -815,4 +875,4 @@ typedef CheckedInt CheckedUint64; } // namespace mozilla -#endif /* mozilla_CheckedInt_h_ */ +#endif /* mozilla_CheckedInt_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Compiler.h b/external/spidermonkey/include/win32/mozilla/Compiler.h index 58239b0e30..d1ef1e79aa 100644 --- a/external/spidermonkey/include/win32/mozilla/Compiler.h +++ b/external/spidermonkey/include/win32/mozilla/Compiler.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ -#ifndef mozilla_Compiler_h_ -#define mozilla_Compiler_h_ +#ifndef mozilla_Compiler_h +#define mozilla_Compiler_h #if !defined(__clang__) && defined(__GNUC__) @@ -28,4 +29,4 @@ #endif -#endif /* mozilla_Compiler_h_ */ +#endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Constants.h b/external/spidermonkey/include/win32/mozilla/Constants.h index 904b30145a..86bbb6b354 100644 --- a/external/spidermonkey/include/win32/mozilla/Constants.h +++ b/external/spidermonkey/include/win32/mozilla/Constants.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt math constants. */ -#ifndef mozilla_Constants_h_ -#define mozilla_Constants_h_ +#ifndef mozilla_Constants_h +#define mozilla_Constants_h #ifndef M_PI # define M_PI 3.14159265358979323846 #endif -#endif /* mozilla_Constants_h_ */ +#endif /* mozilla_Constants_h */ diff --git a/external/spidermonkey/include/win32/mozilla/DebugOnly.h b/external/spidermonkey/include/win32/mozilla/DebugOnly.h index 1f78ed7989..e5f0d729b5 100644 --- a/external/spidermonkey/include/win32/mozilla/DebugOnly.h +++ b/external/spidermonkey/include/win32/mozilla/DebugOnly.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * assertions). */ -#ifndef mozilla_DebugOnly_h_ -#define mozilla_DebugOnly_h_ +#ifndef mozilla_DebugOnly_h +#define mozilla_DebugOnly_h namespace mozilla { @@ -74,4 +75,4 @@ class DebugOnly } -#endif /* mozilla_DebugOnly_h_ */ +#endif /* mozilla_DebugOnly_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Decimal.h b/external/spidermonkey/include/win32/mozilla/Decimal.h index 8032fd6e23..3c67d784c9 100644 --- a/external/spidermonkey/include/win32/mozilla/Decimal.h +++ b/external/spidermonkey/include/win32/mozilla/Decimal.h @@ -38,7 +38,7 @@ #define Decimal_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" +#include #include "mozilla/Types.h" #include diff --git a/external/spidermonkey/include/win32/mozilla/Endian.h b/external/spidermonkey/include/win32/mozilla/Endian.h index 5d2f905b41..dc6d11d3ba 100644 --- a/external/spidermonkey/include/win32/mozilla/Endian.h +++ b/external/spidermonkey/include/win32/mozilla/Endian.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -59,16 +60,16 @@ * }; */ -#ifndef mozilla_Endian_h_ -#define mozilla_Endian_h_ +#ifndef mozilla_Endian_h +#define mozilla_Endian_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/DebugOnly.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" +#include #include #if defined(_MSC_VER) && _MSC_VER >= 1300 @@ -636,4 +637,4 @@ class NativeEndian MOZ_FINAL : public detail::Endian } /* namespace mozilla */ -#endif /* mozilla_Endian_h_ */ +#endif /* mozilla_Endian_h */ diff --git a/external/spidermonkey/include/win32/mozilla/EnumSet.h b/external/spidermonkey/include/win32/mozilla/EnumSet.h index b18b005669..95c5608cf4 100644 --- a/external/spidermonkey/include/win32/mozilla/EnumSet.h +++ b/external/spidermonkey/include/win32/mozilla/EnumSet.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,7 +10,8 @@ #define mozilla_EnumSet_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" + +#include namespace mozilla { @@ -172,4 +174,4 @@ class EnumSet } // namespace mozilla -#endif // mozilla_EnumSet_h_ +#endif /* mozilla_EnumSet_h_*/ diff --git a/external/spidermonkey/include/win32/mozilla/FloatingPoint.h b/external/spidermonkey/include/win32/mozilla/FloatingPoint.h index 30af2217b1..d80f6a7234 100644 --- a/external/spidermonkey/include/win32/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/win32/mozilla/FloatingPoint.h @@ -1,16 +1,19 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various predicates and operations on IEEE-754 floating point types. */ -#ifndef mozilla_FloatingPoint_h_ -#define mozilla_FloatingPoint_h_ +#ifndef mozilla_FloatingPoint_h +#define mozilla_FloatingPoint_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" +#include "mozilla/Casting.h" + +#include namespace mozilla { @@ -35,80 +38,58 @@ namespace mozilla { * the case. But we required this in implementations of these algorithms that * preceded this header, so we shouldn't break anything if we continue doing so. */ -MOZ_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); +static_assert(sizeof(double) == sizeof(uint64_t), "double must be 64 bits"); const unsigned DoubleExponentBias = 1023; const unsigned DoubleExponentShift = 52; -namespace detail { - const uint64_t DoubleSignBit = 0x8000000000000000ULL; const uint64_t DoubleExponentBits = 0x7ff0000000000000ULL; const uint64_t DoubleSignificandBits = 0x000fffffffffffffULL; -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleExponentBits) == 0, - "sign bit doesn't overlap exponent bits"); -MOZ_STATIC_ASSERT((DoubleSignBit & DoubleSignificandBits) == 0, - "sign bit doesn't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleExponentBits & DoubleSignificandBits) == 0, - "exponent bits don't overlap significand bits"); +static_assert((DoubleSignBit & DoubleExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((DoubleSignBit & DoubleSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((DoubleExponentBits & DoubleSignificandBits) == 0, + "exponent bits don't overlap significand bits"); -MOZ_STATIC_ASSERT((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == - ~uint64_t(0), - "all bits accounted for"); - -union DoublePun -{ - /* - * Every way to pun the bits of a double introduces an additional layer of - * complexity, across a multitude of platforms, architectures, and ABIs. - * Use *only* uint64_t to reduce complexity. Don't add new punning here - * without discussion! - */ - uint64_t u; - double d; -}; - -} /* namespace detail */ +static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == + ~uint64_t(0), + "all bits accounted for"); /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * A double is NaN if all exponent bits are 1 and the significand contains at * least one non-zero bit. */ - return (pun.u & detail::DoubleExponentBits) == detail::DoubleExponentBits && - (pun.u & detail::DoubleSignificandBits) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) == DoubleExponentBits && + (bits & DoubleSignificandBits) != 0; } /** Determines whether a double is +Infinity or -Infinity. */ static MOZ_ALWAYS_INLINE bool IsInfinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - return (pun.u & ~detail::DoubleSignBit) == detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & ~DoubleSignBit) == DoubleExponentBits; } /** Determines whether a double is not NaN or infinite. */ static MOZ_ALWAYS_INLINE bool IsFinite(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * NaN and Infinities are the only non-finite doubles, and both have all * exponent bits set to 1. */ - return (pun.u & detail::DoubleExponentBits) != detail::DoubleExponentBits; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleExponentBits) != DoubleExponentBits; } /** @@ -120,36 +101,30 @@ IsNegative(double d) { MOZ_ASSERT(!IsNaN(d), "NaN does not have a sign"); - union detail::DoublePun pun; - pun.d = d; - /* The sign bit is set if the double is negative. */ - return (pun.u & detail::DoubleSignBit) != 0; + uint64_t bits = BitwiseCast(d); + return (bits & DoubleSignBit) != 0; } /** Determines whether a double represents -0. */ static MOZ_ALWAYS_INLINE bool IsNegativeZero(double d) { - union detail::DoublePun pun; - pun.d = d; - /* Only the sign bit is set if the double is -0. */ - return pun.u == detail::DoubleSignBit; + uint64_t bits = BitwiseCast(d); + return bits == DoubleSignBit; } /** Returns the exponent portion of the double. */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { - union detail::DoublePun pun; - pun.d = d; - /* * The exponent component of a double is an unsigned number, biased from its * actual value. Subtract the bias to retrieve the actual exponent. */ - return int_fast16_t((pun.u & detail::DoubleExponentBits) >> DoubleExponentShift) - + uint64_t bits = BitwiseCast(d); + return int_fast16_t((bits & DoubleExponentBits) >> DoubleExponentShift) - int_fast16_t(DoubleExponentBias); } @@ -157,28 +132,22 @@ ExponentComponent(double d) static MOZ_ALWAYS_INLINE double PositiveInfinity() { - union detail::DoublePun pun; - /* * Positive infinity has all exponent bits set, sign bit set to 0, and no * significand. */ - pun.u = detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleExponentBits); } /** Returns -Infinity. */ static MOZ_ALWAYS_INLINE double NegativeInfinity() { - union detail::DoublePun pun; - /* * Negative infinity has all exponent bits set, sign bit set to 1, and no * significand. */ - pun.u = detail::DoubleSignBit | detail::DoubleExponentBits; - return pun.d; + return BitwiseCast(DoubleSignBit | DoubleExponentBits); } /** Constructs a NaN value with the specified sign bit and significand bits. */ @@ -186,24 +155,21 @@ static MOZ_ALWAYS_INLINE double SpecificNaN(int signbit, uint64_t significand) { MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~detail::DoubleSignificandBits) == 0); - MOZ_ASSERT(significand & detail::DoubleSignificandBits); + MOZ_ASSERT((significand & ~DoubleSignificandBits) == 0); + MOZ_ASSERT(significand & DoubleSignificandBits); - union detail::DoublePun pun; - pun.u = (signbit ? detail::DoubleSignBit : 0) | - detail::DoubleExponentBits | - significand; - MOZ_ASSERT(IsNaN(pun.d)); - return pun.d; + double d = BitwiseCast((signbit ? DoubleSignBit : 0) | + DoubleExponentBits | + significand); + MOZ_ASSERT(IsNaN(d)); + return d; } /** Computes the smallest non-zero positive double value. */ static MOZ_ALWAYS_INLINE double MinDoubleValue() { - union detail::DoublePun pun; - pun.u = 1; - return pun.d; + return BitwiseCast(uint64_t(1)); } static MOZ_ALWAYS_INLINE bool @@ -224,9 +190,22 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return mozilla::SpecificNaN(0, 0xfffffffffffffULL); + return SpecificNaN(0, 0xfffffffffffffULL); +} + +/** + * Compare two doubles for equality, *without* equating -0 to +0, and equating + * any NaN value to any other NaN value. (The normal equality operators equate + * -0 with +0, and they equate NaN to no other value.) + */ +static inline bool +DoublesAreIdentical(double d1, double d2) +{ + if (IsNaN(d1)) + return IsNaN(d2); + return BitwiseCast(d1) == BitwiseCast(d2); } } /* namespace mozilla */ -#endif /* mozilla_FloatingPoint_h_ */ +#endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/win32/mozilla/GuardObjects.h b/external/spidermonkey/include/win32/mozilla/GuardObjects.h index 6c2058938c..aeae7dcbc0 100644 --- a/external/spidermonkey/include/win32/mozilla/GuardObjects.h +++ b/external/spidermonkey/include/win32/mozilla/GuardObjects.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,6 +10,7 @@ #define mozilla_GuardObjects_h #include "mozilla/Assertions.h" +#include "mozilla/NullPtr.h" #include "mozilla/Types.h" #ifdef __cplusplus @@ -72,7 +74,7 @@ class MOZ_EXPORT GuardObjectNotifier bool* statementDone; public: - GuardObjectNotifier() : statementDone(NULL) { } + GuardObjectNotifier() : statementDone(nullptr) { } ~GuardObjectNotifier() { *statementDone = true; diff --git a/external/spidermonkey/include/win32/mozilla/HashFunctions.h b/external/spidermonkey/include/win32/mozilla/HashFunctions.h index 96242b629a..6d0d24e7b1 100644 --- a/external/spidermonkey/include/win32/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/win32/mozilla/HashFunctions.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Utilities for hashing. */ @@ -39,17 +40,18 @@ * }; * * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKey.h. + * in nsHashKeys.h. */ -#ifndef mozilla_HashFunctions_h_ -#define mozilla_HashFunctions_h_ +#ifndef mozilla_HashFunctions_h +#define mozilla_HashFunctions_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + #ifdef __cplusplus namespace mozilla { @@ -173,8 +175,8 @@ AddToHash(uint32_t hash, A* a) * catch data pointers and couldn't handle function pointers. */ - MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t), - "Strange pointer!"); + static_assert(sizeof(a) == sizeof(uintptr_t), + "Strange pointer!"); return detail::AddUintptrToHash(hash, uintptr_t(a)); } @@ -356,4 +358,5 @@ HashBytes(const void* bytes, size_t length); } /* namespace mozilla */ #endif /* __cplusplus */ -#endif /* mozilla_HashFunctions_h_ */ + +#endif /* mozilla_HashFunctions_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Likely.h b/external/spidermonkey/include/win32/mozilla/Likely.h index 6412b4943b..4f21609295 100644 --- a/external/spidermonkey/include/win32/mozilla/Likely.h +++ b/external/spidermonkey/include/win32/mozilla/Likely.h @@ -1,15 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a * boolean predicate should be branch-predicted. */ -#ifndef mozilla_Likely_h_ -#define mozilla_Likely_h_ +#ifndef mozilla_Likely_h +#define mozilla_Likely_h #if defined(__clang__) || defined(__GNUC__) # define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) @@ -19,4 +20,4 @@ # define MOZ_UNLIKELY(x) (!!(x)) #endif -#endif /* mozilla_Likely_h_ */ +#endif /* mozilla_Likely_h */ diff --git a/external/spidermonkey/include/win32/mozilla/LinkedList.h b/external/spidermonkey/include/win32/mozilla/LinkedList.h index 5cfd60e4ac..c29760b3e7 100644 --- a/external/spidermonkey/include/win32/mozilla/LinkedList.h +++ b/external/spidermonkey/include/win32/mozilla/LinkedList.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -45,18 +46,19 @@ * } * * void notifyObservers(char* topic) { - * for (Observer* o = list.getFirst(); o != NULL; o = o->getNext()) - * o->Observe(topic); + * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) + * o->observe(topic); * } * }; * */ -#ifndef mozilla_LinkedList_h_ -#define mozilla_LinkedList_h_ +#ifndef mozilla_LinkedList_h +#define mozilla_LinkedList_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -69,10 +71,10 @@ template class LinkedListElement { /* - * It's convenient that we return NULL when getNext() or getPrevious() hits - * the end of the list, but doing so costs an extra word of storage in each - * linked list node (to keep track of whether |this| is the sentinel node) - * and a branch on this value in getNext/getPrevious. + * It's convenient that we return nullptr when getNext() or getPrevious() + * hits the end of the list, but doing so costs an extra word of storage in + * each linked list node (to keep track of whether |this| is the sentinel + * node) and a branch on this value in getNext/getPrevious. * * We could get rid of the extra word of storage by shoving the "is * sentinel" bit into one of the pointers, although this would, of course, @@ -107,12 +109,10 @@ class LinkedListElement LinkedListElement* prev; const bool isSentinel; - LinkedListElement* thisDuringConstruction() { return this; } - public: LinkedListElement() - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(false) { } @@ -122,8 +122,8 @@ class LinkedListElement } /* - * Get the next element in the list, or NULL if this is the last element in - * the list. + * Get the next element in the list, or nullptr if this is the last element + * in the list. */ T* getNext() { return next->asT(); @@ -133,8 +133,8 @@ class LinkedListElement } /* - * Get the previous element in the list, or NULL if this is the first element - * in the list. + * Get the previous element in the list, or nullptr if this is the first + * element in the list. */ T* getPrevious() { return prev->asT(); @@ -201,24 +201,24 @@ class LinkedListElement }; LinkedListElement(NodeKind nodeKind) - : next(thisDuringConstruction()), - prev(thisDuringConstruction()), + : next(MOZ_THIS_IN_INITIALIZER_LIST()), + prev(MOZ_THIS_IN_INITIALIZER_LIST()), isSentinel(nodeKind == NODE_KIND_SENTINEL) { } /* - * Return |this| cast to T* if we're a normal node, or return NULL if we're - * a sentinel node. + * Return |this| cast to T* if we're a normal node, or return nullptr if + * we're a sentinel node. */ T* asT() { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } const T* asT() const { if (isSentinel) - return NULL; + return nullptr; return static_cast(this); } @@ -285,7 +285,7 @@ class LinkedList } /* - * Get the first element of the list, or NULL if the list is empty. + * Get the first element of the list, or nullptr if the list is empty. */ T* getFirst() { return sentinel.getNext(); @@ -295,7 +295,7 @@ class LinkedList } /* - * Get the last element of the list, or NULL if the list is empty. + * Get the last element of the list, or nullptr if the list is empty. */ T* getLast() { return sentinel.getPrevious(); @@ -306,7 +306,7 @@ class LinkedList /* * Get and remove the first element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popFirst() { T* ret = sentinel.getNext(); @@ -317,7 +317,7 @@ class LinkedList /* * Get and remove the last element of the list. If the list is empty, - * return NULL. + * return nullptr. */ T* popLast() { T* ret = sentinel.getPrevious(); @@ -415,7 +415,7 @@ class LinkedList if (elem == t) return; } - MOZ_NOT_REACHED("element wasn't found in this list!"); + MOZ_CRASH("element wasn't found in this list!"); #endif } @@ -425,5 +425,6 @@ class LinkedList } /* namespace mozilla */ -#endif /* ifdef __cplusplus */ -#endif /* ifdef mozilla_LinkedList_h_ */ +#endif /* __cplusplus */ + +#endif /* mozilla_LinkedList_h */ diff --git a/external/spidermonkey/include/win32/mozilla/MSStdInt.h b/external/spidermonkey/include/win32/mozilla/MSStdInt.h deleted file mode 100644 index 0447f2f11b..0000000000 --- a/external/spidermonkey/include/win32/mozilla/MSStdInt.h +++ /dev/null @@ -1,247 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// Redistribution and use in source and binary forms, 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. -// -// 3. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 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 _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int32_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint32_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - - -#endif // _MSC_STDINT_H_ ] diff --git a/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h b/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h index 0a47810553..6d58691e06 100644 --- a/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h @@ -1,19 +1,20 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt maths algorithms. */ -#ifndef mozilla_MathAlgorithms_h_ -#define mozilla_MathAlgorithms_h_ +#ifndef mozilla_MathAlgorithms_h +#define mozilla_MathAlgorithms_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/TypeTraits.h" #include #include +#include namespace mozilla { @@ -142,6 +143,288 @@ Abs(const long double d) return std::fabs(d); } +} // namespace mozilla + +#if defined(_WIN32) && (_MSC_VER >= 1300) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) +# define MOZ_BITSCAN_WINDOWS + + extern "C" { + unsigned char _BitScanForward(unsigned long* Index, unsigned long mask); + unsigned char _BitScanReverse(unsigned long* Index, unsigned long mask); +# pragma intrinsic(_BitScanForward, _BitScanReverse) + +# if defined(_M_AMD64) || defined(_M_X64) +# define MOZ_BITSCAN_WINDOWS64 + unsigned char _BitScanForward64(unsigned long* index, unsigned __int64 mask); + unsigned char _BitScanReverse64(unsigned long* index, unsigned __int64 mask); +# pragma intrinsic(_BitScanForward64, _BitScanReverse64) +# endif + } // extern "C" + +#endif + +namespace mozilla { + +namespace detail { + +#if defined(MOZ_BITSCAN_WINDOWS) + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanReverse(&index, static_cast(u)); + return uint_fast8_t(31 - index); + } + + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + unsigned long index; + _BitScanForward(&index, static_cast(u)); + return uint_fast8_t(index); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanReverse64(&index, static_cast(u)); + return uint_fast8_t(63 - index); +# else + uint32_t hi = uint32_t(u >> 32); + if (hi != 0) + return CountLeadingZeroes32(hi); + return 32 + CountLeadingZeroes32(uint32_t(u)); +# endif + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { +# if defined(MOZ_BITSCAN_WINDOWS64) + unsigned long index; + _BitScanForward64(&index, static_cast(u)); + return uint_fast8_t(index); +# else + uint32_t lo = uint32_t(u); + if (lo != 0) + return CountTrailingZeroes32(lo); + return 32 + CountTrailingZeroes32(uint32_t(u >> 32)); +# endif + } + +# ifdef MOZ_HAVE_BITSCAN64 +# undef MOZ_HAVE_BITSCAN64 +# endif + +#elif defined(__clang__) || defined(__GNUC__) + +# if defined(__clang__) +# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) +# error "A clang providing __builtin_c[lt]z is required to build" +# endif +# else + // gcc has had __builtin_clz and friends since 3.4: no need to check. +# endif + + inline uint_fast8_t + CountLeadingZeroes32(uint32_t u) + { + return __builtin_clz(u); + } + + inline uint_fast8_t + CountTrailingZeroes32(uint32_t u) + { + return __builtin_ctz(u); + } + + inline uint_fast8_t + CountLeadingZeroes64(uint64_t u) + { + return __builtin_clzll(u); + } + + inline uint_fast8_t + CountTrailingZeroes64(uint64_t u) + { + return __builtin_ctzll(u); + } + +#else +# error "Implement these!" + inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; + inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; +#endif + +} // namespace detail + +/** + * Compute the number of high-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the highest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountLeadingZeroes32(0xF0FF1000) is 0; + * CountLeadingZeroes32(0x7F8F0001) is 1; + * CountLeadingZeroes32(0x3FFF0100) is 2; + * CountLeadingZeroes32(0x1FF50010) is 3; and so on. + */ +inline uint_fast8_t +CountLeadingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes32(u); +} + +/** + * Compute the number of low-order zero bits in the NON-ZERO number |u|. That + * is, looking at the bitwise representation of the number, with the lowest- + * valued bits at the start, return the number of zeroes before the first one + * is observed. + * + * CountTrailingZeroes32(0x0100FFFF) is 0; + * CountTrailingZeroes32(0x7000FFFE) is 1; + * CountTrailingZeroes32(0x0080FFFC) is 2; + * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. + */ +inline uint_fast8_t +CountTrailingZeroes32(uint32_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes32(u); +} + +/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountLeadingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountLeadingZeroes64(u); +} + +/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ +inline uint_fast8_t +CountTrailingZeroes64(uint64_t u) +{ + MOZ_ASSERT(u != 0); + return detail::CountTrailingZeroes64(u); +} + +namespace detail { + +template +class CeilingLog2; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 32 - CountLeadingZeroes32(t - 1); + } +}; + +template +class CeilingLog2 +{ + public: + static uint_fast8_t compute(const T t) { + // Check for <= 1 to avoid the == 0 undefined case. + return t <= 1 ? 0 : 64 - CountLeadingZeroes64(t - 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the least power of 2 greater than or equal to |t|. + * + * CeilingLog2(0..1) is 0; + * CeilingLog2(2) is 1; + * CeilingLog2(3..4) is 2; + * CeilingLog2(5..8) is 3; + * CeilingLog2(9..16) is 4; and so on. + */ +template +inline uint_fast8_t +CeilingLog2(const T t) +{ + return detail::CeilingLog2::compute(t); +} + +/** A CeilingLog2 variant that accepts only size_t. */ +inline uint_fast8_t +CeilingLog2Size(size_t n) +{ + return CeilingLog2(n); +} + +namespace detail { + +template +class FloorLog2; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 31 - CountLeadingZeroes32(t | 1); + } +}; + +template +class FloorLog2 +{ + public: + static uint_fast8_t compute(const T t) { + return 63 - CountLeadingZeroes64(t | 1); + } +}; + +} // namespace detail + +/** + * Compute the log of the greatest power of 2 less than or equal to |t|. + * + * FloorLog2(0..1) is 0; + * FloorLog2(2..3) is 1; + * FloorLog2(4..7) is 2; + * FloorLog2(8..15) is 3; and so on. + */ +template +inline uint_fast8_t +FloorLog2(const T t) +{ + return detail::FloorLog2::compute(t); +} + +/** A FloorLog2 variant that accepts only size_t. */ +inline uint_fast8_t +FloorLog2Size(size_t n) +{ + return FloorLog2(n); +} + +/* + * Compute the smallest power of 2 greater than or equal to |x|. |x| must not + * be so great that the computed value would overflow |size_t|. + */ +inline size_t +RoundUpPow2(size_t x) +{ + MOZ_ASSERT(x <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), + "can't round up -- will overflow!"); + return size_t(1) << CeilingLog2(x); +} + } /* namespace mozilla */ -#endif /* mozilla_MathAlgorithms_h_ */ +#endif /* mozilla_MathAlgorithms_h */ diff --git a/external/spidermonkey/include/win32/mozilla/MemoryChecking.h b/external/spidermonkey/include/win32/mozilla/MemoryChecking.h index 3287e57ba1..2130990c6b 100644 --- a/external/spidermonkey/include/win32/mozilla/MemoryChecking.h +++ b/external/spidermonkey/include/win32/mozilla/MemoryChecking.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -19,8 +20,8 @@ * With no memory checker available, all macros expand to the empty statement. */ -#ifndef mozilla_MemoryChecking_h_ -#define mozilla_MemoryChecking_h_ +#ifndef mozilla_MemoryChecking_h +#define mozilla_MemoryChecking_h #if defined(MOZ_VALGRIND) #include "valgrind/memcheck.h" @@ -68,4 +69,4 @@ extern "C" { #endif -#endif /* mozilla_MemoryChecking_h_ */ +#endif /* mozilla_MemoryChecking_h */ diff --git a/external/spidermonkey/include/win32/mozilla/MemoryReporting.h b/external/spidermonkey/include/win32/mozilla/MemoryReporting.h new file mode 100644 index 0000000000..d2340ecf09 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/MemoryReporting.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Memory reporting infrastructure. */ + +#ifndef mozilla_MemoryReporting_h +#define mozilla_MemoryReporting_h + +#include + +#ifdef __cplusplus + +namespace mozilla { + +/* + * This is for functions that are like malloc_usable_size. Such functions are + * used for measuring the size of data structures. + */ +typedef size_t (*MallocSizeOf)(const void* p); + +} /* namespace mozilla */ + +#endif /* __cplusplus */ + +typedef size_t (*MozMallocSizeOf)(const void* p); + +#endif /* mozilla_MemoryReporting_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Move.h b/external/spidermonkey/include/win32/mozilla/Move.h new file mode 100644 index 0000000000..97178daaa6 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Move.h @@ -0,0 +1,166 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* C++11-style, but C++98-usable, "move references" implementation. */ + +#ifndef mozilla_Move_h +#define mozilla_Move_h + +namespace mozilla { + +/* + * "Move" References + * + * Some types can be copied much more efficiently if we know the original's + * value need not be preserved --- that is, if we are doing a "move", not a + * "copy". For example, if we have: + * + * Vector u; + * Vector v(u); + * + * the constructor for v must apply a copy constructor to each element of u --- + * taking time linear in the length of u. However, if we know we will not need u + * any more once v has been initialized, then we could initialize v very + * efficiently simply by stealing u's dynamically allocated buffer and giving it + * to v --- a constant-time operation, regardless of the size of u. + * + * Moves often appear in container implementations. For example, when we append + * to a vector, we may need to resize its buffer. This entails moving each of + * its extant elements from the old, smaller buffer to the new, larger buffer. + * But once the elements have been migrated, we're just going to throw away the + * old buffer; we don't care if they still have their values. So if the vector's + * element type can implement "move" more efficiently than "copy", the vector + * resizing should by all means use a "move" operation. Hash tables also need to + * be resized. + * + * The details of the optimization, and whether it's worth applying, vary from + * one type to the next. And while some constructor calls are moves, many really + * are copies, and can't be optimized this way. So we need: + * + * 1) a way for a particular invocation of a copy constructor to say that it's + * really a move, and that the value of the original isn't important + * afterwards (although it must still be safe to destroy); and + * + * 2) a way for a type (like Vector) to announce that it can be moved more + * efficiently than it can be copied, and provide an implementation of that + * move operation. + * + * The Move(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's 1). A MoveRef is simply a reference + * to a T, annotated to say that a copy constructor applied to it may move that + * T, instead of copying it. Finally, a constructor that accepts an MoveRef + * should perform a more efficient move, instead of a copy, providing 2). + * + * So, where we might define a copy constructor for a class C like this: + * + * C(const C& rhs) { ... copy rhs to this ... } + * + * we would declare a move constructor like this: + * + * C(MoveRef rhs) { ... move rhs to this ... } + * + * And where we might perform a copy like this: + * + * C c2(c1); + * + * we would perform a move like this: + * + * C c2(Move(c1)) + * + * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef + * to an ordinary copy constructor for a type that doesn't support a special + * move constructor, and you'll just get a copy. This means that templates can + * use Move whenever they know they won't use the original value any more, even + * if they're not sure whether the type at hand has a specialized move + * constructor. If it doesn't, the MoveRef will just convert to a T&, and + * the ordinary copy constructor will apply. + * + * A class with a move constructor can also provide a move assignment operator, + * which runs this's destructor, and then applies the move constructor to + * *this's memory. A typical definition: + * + * C& operator=(MoveRef rhs) { + * this->~C(); + * new(this) C(rhs); + * return *this; + * } + * + * With that in place, one can write move assignments like this: + * + * c2 = Move(c1); + * + * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but + * destructible state. + * + * This header file defines MoveRef and Move in the mozilla namespace. It's up + * to individual containers to annotate moves as such, by calling Move; and it's + * up to individual types to define move constructors. + * + * One hint: if you're writing a move constructor where the type has members + * that should be moved themselves, it's much nicer to write this: + * + * C(MoveRef c) : x(Move(c->x)), y(Move(c->y)) { } + * + * than the equivalent: + * + * C(MoveRef c) { new(&x) X(Move(c->x)); new(&y) Y(Move(c->y)); } + * + * especially since GNU C++ fails to notice that this does indeed initialize x + * and y, which may matter if they're const. + */ +template +class MoveRef +{ + T* pointer; + + public: + explicit MoveRef(T& t) : pointer(&t) { } + T& operator*() const { return *pointer; } + T* operator->() const { return pointer; } + operator T& () const { return *pointer; } +}; + +template +inline MoveRef +Move(T& t) +{ + return MoveRef(t); +} + +template +inline MoveRef +Move(const T& t) +{ + // With some versions of gcc, for a class C, there's an (incorrect) ambiguity + // between the C(const C&) constructor and the default C(C&&) C++11 move + // constructor, when the constructor is called with a const C& argument. + // + // This ambiguity manifests with the Move implementation above when Move is + // passed const U& for some class U. Calling Move(const U&) returns a + // MoveRef, which is then commonly passed to the U constructor, + // triggering an implicit conversion to const U&. gcc doesn't know whether to + // call U(const U&) or U(U&&), so it wrongly reports a compile error. + // + // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50442 has since been fixed, so + // this is no longer an issue for up-to-date compilers. But there's no harm + // in keeping it around for older compilers, so we might as well. See also + // bug 686280. + return MoveRef(const_cast(t)); +} + +/** Swap |t| and |u| using move-construction if possible. */ +template +inline void +Swap(T& t, T& u) +{ + T tmp(Move(t)); + t = Move(u); + u = Move(tmp); +} + +} // namespace mozilla + +#endif /* mozilla_Move_h */ diff --git a/external/spidermonkey/include/win32/mozilla/NullPtr.h b/external/spidermonkey/include/win32/mozilla/NullPtr.h index 7dcb03d734..14c0f07df2 100644 --- a/external/spidermonkey/include/win32/mozilla/NullPtr.h +++ b/external/spidermonkey/include/win32/mozilla/NullPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * constant. */ -#ifndef mozilla_NullPtr_h_ -#define mozilla_NullPtr_h_ +#ifndef mozilla_NullPtr_h +#define mozilla_NullPtr_h #include "mozilla/Compiler.h" @@ -45,4 +46,4 @@ # endif #endif -#endif /* mozilla_NullPtr_h_ */ +#endif /* mozilla_NullPtr_h */ diff --git a/external/spidermonkey/include/win32/mozilla/PodOperations.h b/external/spidermonkey/include/win32/mozilla/PodOperations.h index 6c6af27fc9..bec89fa928 100644 --- a/external/spidermonkey/include/win32/mozilla/PodOperations.h +++ b/external/spidermonkey/include/win32/mozilla/PodOperations.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -156,4 +157,4 @@ PodEqual(const T* one, const T* two, size_t len) } // namespace mozilla -#endif // mozilla_PodOperations_h_ +#endif /* mozilla_PodOperations_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Poison.h b/external/spidermonkey/include/win32/mozilla/Poison.h index c4adc23e71..75e0f081cd 100644 --- a/external/spidermonkey/include/win32/mozilla/Poison.h +++ b/external/spidermonkey/include/win32/mozilla/Poison.h @@ -9,13 +9,14 @@ * an address that leads to a safe crash when dereferenced. */ -#ifndef mozilla_Poison_h_ -#define mozilla_Poison_h_ +#ifndef mozilla_Poison_h +#define mozilla_Poison_h #include "mozilla/Assertions.h" -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" +#include + MOZ_BEGIN_EXTERN_C extern MFBT_DATA uintptr_t gMozillaPoisonValue; @@ -36,11 +37,11 @@ inline uintptr_t mozPoisonValue() */ inline void mozWritePoison(void* aPtr, size_t aSize) { - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); const uintptr_t POISON = mozPoisonValue(); char* p = (char*)aPtr; char* limit = p + aSize; + MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); + MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); for (; p < limit; p += sizeof(uintptr_t)) { *((uintptr_t*)p) = POISON; } @@ -58,4 +59,4 @@ extern MFBT_DATA uintptr_t gMozillaPoisonSize; MOZ_END_EXTERN_C -#endif /* mozilla_Poison_h_ */ +#endif /* mozilla_Poison_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Range.h b/external/spidermonkey/include/win32/mozilla/Range.h index e14594d09d..4e02d962b5 100644 --- a/external/spidermonkey/include/win32/mozilla/Range.h +++ b/external/spidermonkey/include/win32/mozilla/Range.h @@ -1,12 +1,11 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef mozilla_Range_h_ -#define mozilla_Range_h_ +#ifndef mozilla_Range_h +#define mozilla_Range_h #include "mozilla/NullPtr.h" #include "mozilla/RangedPtr.h" @@ -40,10 +39,13 @@ class Range return mStart[offset]; } + const T& operator[](size_t offset) const { + return mStart[offset]; + } + operator ConvertibleToBool() const { return mStart ? &Range::nonNull : 0; } }; } // namespace mozilla -#endif // mozilla_Range_h_ - +#endif /* mozilla_Range_h */ diff --git a/external/spidermonkey/include/win32/mozilla/RangedPtr.h b/external/spidermonkey/include/win32/mozilla/RangedPtr.h index 7ce19d071f..493fcdbaee 100644 --- a/external/spidermonkey/include/win32/mozilla/RangedPtr.h +++ b/external/spidermonkey/include/win32/mozilla/RangedPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,11 +9,12 @@ * construction. */ -#ifndef mozilla_RangedPtr_h_ -#define mozilla_RangedPtr_h_ +#ifndef mozilla_RangedPtr_h +#define mozilla_RangedPtr_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" #include "mozilla/Util.h" namespace mozilla { @@ -59,7 +61,7 @@ class RangedPtr #ifdef DEBUG return RangedPtr(p, rangeStart, rangeEnd); #else - return RangedPtr(p, NULL, size_t(0)); + return RangedPtr(p, nullptr, size_t(0)); #endif } @@ -251,4 +253,4 @@ class RangedPtr } /* namespace mozilla */ -#endif /* mozilla_RangedPtr_h_ */ +#endif /* mozilla_RangedPtr_h */ diff --git a/external/spidermonkey/include/win32/mozilla/ReentrancyGuard.h b/external/spidermonkey/include/win32/mozilla/ReentrancyGuard.h new file mode 100644 index 0000000000..d589f368a2 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/ReentrancyGuard.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Small helper class for asserting uses of a class are non-reentrant. */ + +#ifndef mozilla_ReentrancyGuard_h +#define mozilla_ReentrancyGuard_h + +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/GuardObjects.h" + +namespace mozilla { + +/* Useful for implementing containers that assert non-reentrancy */ +class ReentrancyGuard +{ + MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER +#ifdef DEBUG + bool& entered; +#endif + + public: + template +#ifdef DEBUG + ReentrancyGuard(T& obj + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + : entered(obj.entered) +#else + ReentrancyGuard(T& + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) +#endif + { + MOZ_GUARD_OBJECT_NOTIFIER_INIT; +#ifdef DEBUG + MOZ_ASSERT(!entered); + entered = true; +#endif + } + ~ReentrancyGuard() + { +#ifdef DEBUG + entered = false; +#endif + } + + private: + ReentrancyGuard(const ReentrancyGuard&) MOZ_DELETE; + void operator=(const ReentrancyGuard&) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_ReentrancyGuard_h */ diff --git a/external/spidermonkey/include/win32/mozilla/RefPtr.h b/external/spidermonkey/include/win32/mozilla/RefPtr.h index 9f4163a21a..3c275afdc7 100644 --- a/external/spidermonkey/include/win32/mozilla/RefPtr.h +++ b/external/spidermonkey/include/win32/mozilla/RefPtr.h @@ -1,14 +1,16 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Helpers for defining and using refcounted objects. */ -#ifndef mozilla_RefPtr_h_ -#define mozilla_RefPtr_h_ +#ifndef mozilla_RefPtr_h +#define mozilla_RefPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/Attributes.h" #include "mozilla/TypeTraits.h" @@ -41,13 +43,19 @@ template OutParamRef byRef(RefPtr&); * state distinguishes use-before-ref (refcount==0) from * use-after-destroy (refcount==0xffffdead). */ -#ifdef DEBUG namespace detail { +#ifdef DEBUG static const int DEAD = 0xffffdead; -} #endif -template +// This is used WeakPtr.h as well as this file. +enum RefCountAtomicity +{ + AtomicRefCount, + NonAtomicRefCount +}; + +template class RefCounted { friend class RefPtr; @@ -56,8 +64,6 @@ class RefCounted RefCounted() : refCnt(0) { } ~RefCounted() { MOZ_ASSERT(refCnt == detail::DEAD); - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from RefCounted"); } public: @@ -87,7 +93,33 @@ class RefCounted } private: - int refCnt; + typename Conditional, int>::Type refCnt; +}; + +} + +template +class RefCounted : public detail::RefCounted +{ + public: + ~RefCounted() { + static_assert(IsBaseOf::value, + "T must derive from RefCounted"); + } +}; + +/** + * AtomicRefCounted is like RefCounted, with an atomically updated + * reference counter. + */ +template +class AtomicRefCounted : public detail::RefCounted +{ + public: + ~AtomicRefCounted() { + static_assert(IsBaseOf::value, + "T must derive from AtomicRefCounted"); + } }; /** @@ -259,9 +291,6 @@ byRef(RefPtr& ptr) } // namespace mozilla -#endif // mozilla_RefPtr_h_ - - #if 0 // Command line that builds these tests @@ -416,3 +445,5 @@ main(int argc, char** argv) } #endif + +#endif /* mozilla_RefPtr_h */ diff --git a/external/spidermonkey/include/win32/mozilla/SHA1.h b/external/spidermonkey/include/win32/mozilla/SHA1.h index a6604e699f..b167648540 100644 --- a/external/spidermonkey/include/win32/mozilla/SHA1.h +++ b/external/spidermonkey/include/win32/mozilla/SHA1.h @@ -1,17 +1,18 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Simple class for computing SHA1. */ -#ifndef mozilla_SHA1_h_ -#define mozilla_SHA1_h_ +#ifndef mozilla_SHA1_h +#define mozilla_SHA1_h -#include "mozilla/StandardInteger.h" #include "mozilla/Types.h" #include +#include namespace mozilla { @@ -58,4 +59,4 @@ class SHA1Sum } /* namespace mozilla */ -#endif /* mozilla_SHA1_h_ */ +#endif /* mozilla_SHA1_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Scoped.h b/external/spidermonkey/include/win32/mozilla/Scoped.h index 677a1a3797..fc48584b3e 100644 --- a/external/spidermonkey/include/win32/mozilla/Scoped.h +++ b/external/spidermonkey/include/win32/mozilla/Scoped.h @@ -1,11 +1,13 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A number of structures to simplify scope-based RAII management. */ -#ifndef mozilla_Scoped_h_ -#define mozilla_Scoped_h_ +#ifndef mozilla_Scoped_h +#define mozilla_Scoped_h /* * Resource Acquisition Is Initialization is a programming idiom used @@ -52,6 +54,7 @@ #include "mozilla/Attributes.h" #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -193,7 +196,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { free(ptr); } }; SCOPED_TEMPLATE(ScopedFreePtr, ScopedFreePtrTraits) @@ -256,7 +259,7 @@ template struct TypeSpecificScopedPointerTraits { typedef T* type; - const static type empty() { return NULL; } + const static type empty() { return nullptr; } const static void release(type value) { if (value) @@ -268,4 +271,4 @@ SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) } /* namespace mozilla */ -#endif // mozilla_Scoped_h_ +#endif /* mozilla_Scoped_h */ diff --git a/external/spidermonkey/include/win32/mozilla/SplayTree.h b/external/spidermonkey/include/win32/mozilla/SplayTree.h index f9a10d36dd..de0235aec9 100644 --- a/external/spidermonkey/include/win32/mozilla/SplayTree.h +++ b/external/spidermonkey/include/win32/mozilla/SplayTree.h @@ -1,7 +1,6 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=99 ft=cpp: - * - * This Source Code Form is subject to the terms of the Mozilla Public +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,8 +9,8 @@ * are faster to access again. */ -#ifndef mozilla_SplayTree_h_ -#define mozilla_SplayTree_h_ +#ifndef mozilla_SplayTree_h +#define mozilla_SplayTree_h #include "mozilla/Assertions.h" #include "mozilla/NullPtr.h" @@ -282,4 +281,4 @@ class SplayTree } /* namespace mozilla */ -#endif /* mozilla_SplayTree_h_ */ +#endif /* mozilla_SplayTree_h */ diff --git a/external/spidermonkey/include/win32/mozilla/StandardInteger.h b/external/spidermonkey/include/win32/mozilla/StandardInteger.h deleted file mode 100644 index 8e4c8578f1..0000000000 --- a/external/spidermonkey/include/win32/mozilla/StandardInteger.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface for C and C++ code. */ - -#ifndef mozilla_StandardInteger_h_ -#define mozilla_StandardInteger_h_ - -/* - * The C99 standard header exposes typedefs for common fixed-width - * integer types. It would be feasible to simply #include , but - * MSVC++ versions prior to 2010 don't provide . We could solve this - * by reimplementing for MSVC++ 2008 and earlier. But then we reach - * a second problem: our custom might conflict with a - * defined by an embedder already looking to work around the MSVC++ - * absence. - * - * We address these issues in this manner: - * - * 1. If the preprocessor macro MOZ_CUSTOM_STDINT_H is defined to a path to a - * custom implementation, we will #include it. Embedders using - * a custom must define this macro to an implementation that - * will work with their embedding. - * 2. Otherwise, if we are compiling with a an MSVC++ version without - * , #include our custom reimplementation. - * 3. Otherwise, #include the standard provided by the compiler. - * - * Note that we can't call this file "stdint.h" or something case-insensitively - * equal to "stdint.h" because then MSVC (and other compilers on - * case-insensitive file systems) will include this file, rather than the system - * stdint.h, when we ask for below. - */ -#if defined(MOZ_CUSTOM_STDINT_H) -# include MOZ_CUSTOM_STDINT_H -#elif defined(_MSC_VER) && _MSC_VER < 1600 -# include "mozilla/MSStdInt.h" -#else -# include -#endif - -#endif /* mozilla_StandardInteger_h_ */ diff --git a/external/spidermonkey/include/win32/mozilla/TemplateLib.h b/external/spidermonkey/include/win32/mozilla/TemplateLib.h new file mode 100644 index 0000000000..50275fdadb --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/TemplateLib.h @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Reusable template meta-functions on types and compile-time values. Meta- + * functions are placed inside the 'tl' namespace to avoid conflict with non- + * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. + * mozilla::FloorLog2). + * + * When constexpr support becomes universal, we should probably use that instead + * of some of these templates, for simplicity. + */ + +#ifndef mozilla_TemplateLib_h +#define mozilla_TemplateLib_h + +#include +#include + +namespace mozilla { + +namespace tl { + +/** Compute min/max. */ +template +struct Min +{ + static const size_t value = I < J ? I : J; +}; +template +struct Max +{ + static const size_t value = I > J ? I : J; +}; + +/** Compute floor(log2(i)). */ +template +struct FloorLog2 +{ + static const size_t value = 1 + FloorLog2::value; +}; +template<> struct FloorLog2<0> { /* Error */ }; +template<> struct FloorLog2<1> { static const size_t value = 0; }; + +/** Compute ceiling(log2(i)). */ +template +struct CeilingLog2 +{ + static const size_t value = FloorLog2<2 * I - 1>::value; +}; + +/** Round up to the nearest power of 2. */ +template +struct RoundUpPow2 +{ + static const size_t value = size_t(1) << CeilingLog2::value; +}; +template<> +struct RoundUpPow2<0> +{ + static const size_t value = 1; +}; + +/** Compute the number of bits in the given unsigned type. */ +template +struct BitSize +{ + static const size_t value = sizeof(T) * CHAR_BIT; +}; + +/** + * Produce an N-bit mask, where N <= BitSize::value. Handle the + * language-undefined edge case when N = BitSize::value. + */ +template +struct NBitMask +{ + // Assert the precondition. On success this evaluates to 0. Otherwise it + // triggers divide-by-zero at compile time: a guaranteed compile error in + // C++11, and usually one in C++98. Add this value to |value| to assure + // its computation. + static const size_t checkPrecondition = 0 / size_t(N < BitSize::value); + static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; +}; +template<> +struct NBitMask::value> +{ + static const size_t value = size_t(-1); +}; + +/** + * For the unsigned integral type size_t, compute a mask M for N such that + * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) + */ +template +struct MulOverflowMask +{ + static const size_t value = + ~NBitMask::value - CeilingLog2::value>::value; +}; +template<> struct MulOverflowMask<0> { /* Error */ }; +template<> struct MulOverflowMask<1> { static const size_t value = 0; }; + +} // namespace tl + +} // namespace mozilla + +#endif /* mozilla_TemplateLib_h */ diff --git a/external/spidermonkey/include/win32/mozilla/ThreadLocal.h b/external/spidermonkey/include/win32/mozilla/ThreadLocal.h index 2b4eb30207..6df109821f 100644 --- a/external/spidermonkey/include/win32/mozilla/ThreadLocal.h +++ b/external/spidermonkey/include/win32/mozilla/ThreadLocal.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Cross-platform lightweight thread local data wrappers. */ -#ifndef mozilla_ThreadLocal_h_ -#define mozilla_ThreadLocal_h_ +#ifndef mozilla_ThreadLocal_h +#define mozilla_ThreadLocal_h #if defined(XP_WIN) // This file will get included in any file that wants to add a profiler mark. @@ -28,6 +29,7 @@ __declspec(dllimport) unsigned long __stdcall TlsAlloc(); #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/NullPtr.h" namespace mozilla { @@ -98,15 +100,15 @@ template inline bool ThreadLocal::init() { - MOZ_STATIC_ASSERT(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); + static_assert(sizeof(T) <= sizeof(void*), + "mozilla::ThreadLocal can't be used for types larger than " + "a pointer"); MOZ_ASSERT(!initialized()); #ifdef XP_WIN key = TlsAlloc(); inited = key != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES #else - inited = !pthread_key_create(&key, NULL); + inited = !pthread_key_create(&key, nullptr); #endif return inited; } @@ -144,4 +146,4 @@ ThreadLocal::set(const T value) } // namespace mozilla -#endif // mozilla_ThreadLocal_h_ +#endif /* mozilla_ThreadLocal_h */ diff --git a/external/spidermonkey/include/win32/mozilla/TypeTraits.h b/external/spidermonkey/include/win32/mozilla/TypeTraits.h index 656bc775f8..53c0b5c2f6 100644 --- a/external/spidermonkey/include/win32/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/win32/mozilla/TypeTraits.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Template-based metaprogramming and type-testing facilities. */ -#ifndef mozilla_TypeTraits_h_ -#define mozilla_TypeTraits_h_ +#ifndef mozilla_TypeTraits_h +#define mozilla_TypeTraits_h /* * These traits are approximate copies of the traits and semantics from C++11's @@ -126,6 +127,28 @@ struct IsPointer : FalseType {}; template struct IsPointer : TrueType {}; +namespace detail { + +// __is_enum is a supported extension across all of our supported compilers. +template +struct IsEnumHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsEnum determines whether a type is an enum type. + * + * mozilla::IsEnum::value is true; + * mozilla::IsEnum::value is false; + * mozilla::IsEnum::value is false; + */ +template +struct IsEnum + : detail::IsEnumHelper::Type> +{}; + /* 20.9.4.2 Composite type traits [meta.unary.comp] */ /** @@ -197,8 +220,24 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template struct IsPod : TrueType {}; +namespace detail { + +template::value> +struct IsSignedHelper; + +template +struct IsSignedHelper : TrueType {}; + +template +struct IsSignedHelper + : IntegralConstant::value && T(-1) < T(1)> +{}; + +} // namespace detail + /** - * IsSigned determines whether a type is a signed arithmetic type. + * IsSigned determines whether a type is a signed arithmetic type. |char| is + * considered a signed type if it has the same representation as |signed char|. * * Don't use this if the type might be user-defined! You might or might not get * a compile error, depending. @@ -209,10 +248,26 @@ template struct IsPod : TrueType {}; * mozilla::IsSigned::value is true. */ template -struct IsSigned - : IntegralConstant::value && T(-1) < T(0)> +struct IsSigned : detail::IsSignedHelper {}; + +namespace detail { + +template::value> +struct IsUnsignedHelper; + +template +struct IsUnsignedHelper : FalseType {}; + +template +struct IsUnsignedHelper + : IntegralConstant::value && + (IsSame::Type, bool>::value || + T(1) < T(-1))> {}; +} // namespace detail + /** * IsUnsigned determines whether a type is an unsigned arithmetic type. * @@ -225,9 +280,7 @@ struct IsSigned * mozilla::IsUnsigned::value is false. */ template -struct IsUnsigned - : IntegralConstant::value && T(0) < T(-1)> -{}; +struct IsUnsigned : detail::IsUnsignedHelper {}; /* 20.9.5 Type property queries [meta.unary.prop.query] */ @@ -427,6 +480,160 @@ struct RemoveCV /* 20.9.7.3 Sign modifications [meta.trans.sign] */ +template +struct EnableIf; + +template +struct Conditional; + +namespace detail { + +template +struct WithC : Conditional +{}; + +template +struct WithV : Conditional +{}; + + +template +struct WithCV : WithC::Type> +{}; + +template +struct CorrespondingSigned; + +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef short Type; }; +template<> +struct CorrespondingSigned { typedef int Type; }; +template<> +struct CorrespondingSigned { typedef long Type; }; +template<> +struct CorrespondingSigned { typedef long long Type; }; + +template::Type, + bool IsSignedIntegerType = IsSigned::value && + !IsSame::value> +struct MakeSigned; + +template +struct MakeSigned +{ + typedef T Type; +}; + +template +struct MakeSigned + : WithCV::value, IsVolatile::value, + typename CorrespondingSigned::Type> +{}; + +} // namespace detail + +/** + * MakeSigned produces the corresponding signed integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already a signed integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an unsigned integer type, the signed variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the integral type of the same size as T, with the lowest rank, + * with T's const/volatile qualifiers, is produced. (This basically only acts + * to produce signed char when T = char.) + * + * mozilla::MakeSigned::Type is signed long; + * mozilla::MakeSigned::Type is volatile int; + * mozilla::MakeSigned::Type is const signed short; + * mozilla::MakeSigned::Type is const signed char; + * mozilla::MakeSigned is an error; + * mozilla::MakeSigned is an error. + */ +template +struct MakeSigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeSigned + >::Type +{}; + +namespace detail { + +template +struct CorrespondingUnsigned; + +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned short Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned int Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long long Type; }; + + +template::Type, + bool IsUnsignedIntegerType = IsUnsigned::value && + !IsSame::value> +struct MakeUnsigned; + +template +struct MakeUnsigned +{ + typedef T Type; +}; + +template +struct MakeUnsigned + : WithCV::value, IsVolatile::value, + typename CorrespondingUnsigned::Type> +{}; + +} // namespace detail + +/** + * MakeUnsigned produces the corresponding unsigned integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already an unsigned integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an signed integer type, the unsigned variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the unsigned integral type of the same size as T, with the lowest + * rank, with T's const/volatile qualifiers, is produced. (This basically only + * acts to produce unsigned char when T = char.) + * + * mozilla::MakeUnsigned::Type is unsigned long; + * mozilla::MakeUnsigned::Type is volatile unsigned int; + * mozilla::MakeUnsigned::Type is const unsigned short; + * mozilla::MakeUnsigned::Type is const unsigned char; + * mozilla::MakeUnsigned is an error; + * mozilla::MakeUnsigned is an error. + */ +template +struct MakeUnsigned + : EnableIf::value && !IsSame::Type>::value, + typename detail::MakeUnsigned + >::Type +{}; + /* 20.9.7.4 Array modifications [meta.trans.arr] */ /* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ @@ -451,7 +658,7 @@ struct RemoveCV * ... * }; */ -template +template struct EnableIf {}; @@ -481,4 +688,4 @@ struct Conditional } /* namespace mozilla */ -#endif /* mozilla_TypeTraits_h_ */ +#endif /* mozilla_TypeTraits_h */ diff --git a/external/spidermonkey/include/win32/mozilla/TypedEnum.h b/external/spidermonkey/include/win32/mozilla/TypedEnum.h index 889960a32d..6f595cb4c5 100644 --- a/external/spidermonkey/include/win32/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/win32/mozilla/TypedEnum.h @@ -1,12 +1,13 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Macros to emulate C++11 typed enums and enum classes. */ -#ifndef mozilla_TypedEnum_h_ -#define mozilla_TypedEnum_h_ +#ifndef mozilla_TypedEnum_h +#define mozilla_TypedEnum_h #include "mozilla/Attributes.h" @@ -91,16 +92,33 @@ * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do * not support it. * - * Note that the workaround implemented here is not compatible with enums - * nested inside a class. + * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested + * inside classes. To define an enum class nested inside another class, use + * MOZ_{BEGIN,END}_NESTED_ENUM_CLASS, and place a MOZ_FINISH_NESTED_ENUM_CLASS + * in namespace scope to handle bits that can only be implemented with + * namespace-scoped code. For example: + * + * class FooBar { + * + * MOZ_BEGIN_NESTED_ENUM_CLASS(Enum, int32_t) + * A, + * B = 6 + * MOZ_END_NESTED_ENUM_CLASS(Enum) + * + * }; + * + * MOZ_FINISH_NESTED_ENUM_CLASS(FooBar::Enum) */ #if defined(MOZ_HAVE_CXX11_STRONG_ENUMS) /* * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) enum class Name : type { -# define MOZ_END_ENUM_CLASS(Name) }; +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + enum class Name : type { +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) /* nothing */ #else /** * We need Name to both name a type, and scope the provided enumerator @@ -136,14 +154,14 @@ * { * return Enum::A; * } - */ -# define MOZ_BEGIN_ENUM_CLASS(Name, type) \ + */\ +# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ class Name \ { \ public: \ enum Enum MOZ_ENUM_TYPE(type) \ { -# define MOZ_END_ENUM_CLASS(Name) \ +# define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; \ Name() {} \ Name(Enum aEnum) : mEnum(aEnum) {} \ @@ -151,7 +169,8 @@ operator Enum() const { return mEnum; } \ private: \ Enum mEnum; \ - }; \ + }; +# define MOZ_FINISH_NESTED_ENUM_CLASS(Name) \ inline int operator+(const int&, const Name::Enum&) MOZ_DELETE; \ inline int operator+(const Name::Enum&, const int&) MOZ_DELETE; \ inline int operator-(const int&, const Name::Enum&) MOZ_DELETE; \ @@ -207,7 +226,11 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif +# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) +# define MOZ_END_ENUM_CLASS(Name) \ + MOZ_END_NESTED_ENUM_CLASS(Name) \ + MOZ_FINISH_NESTED_ENUM_CLASS(Name) #endif /* __cplusplus */ -#endif /* mozilla_TypedEnum_h_ */ +#endif /* mozilla_TypedEnum_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Types.h b/external/spidermonkey/include/win32/mozilla/Types.h index 56e5cb82fb..5340b2b600 100644 --- a/external/spidermonkey/include/win32/mozilla/Types.h +++ b/external/spidermonkey/include/win32/mozilla/Types.h @@ -1,28 +1,22 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* mfbt foundational types and macros. */ -#ifndef mozilla_Types_h_ -#define mozilla_Types_h_ +#ifndef mozilla_Types_h +#define mozilla_Types_h /* * This header must be valid C and C++, includable by code embedding either * SpiderMonkey or Gecko. */ -/* - * Expose all the integer types defined in C99's (and the integer - * limit and constant macros, if compiling C code or if compiling C++ code and - * the right __STDC_*_MACRO has been defined for each). These are all usable - * throughout mfbt code, and throughout Mozilla code more generally. - */ -#include "mozilla/StandardInteger.h" - -/* Also expose size_t. */ +/* Expose all types and size_t. */ #include +#include /* Implement compiler and linker macros needed for APIs. */ @@ -133,4 +127,12 @@ # define MOZ_END_EXTERN_C #endif -#endif /* mozilla_Types_h_ */ +/* + * GCC's typeof is available when decltype is not. + */ +#if defined(__GNUC__) && defined(__cplusplus) && \ + !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +# define decltype __typeof__ +#endif + +#endif /* mozilla_Types_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Util.h b/external/spidermonkey/include/win32/mozilla/Util.h index 097c5478eb..4f1c634a59 100644 --- a/external/spidermonkey/include/win32/mozilla/Util.h +++ b/external/spidermonkey/include/win32/mozilla/Util.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -8,8 +9,8 @@ * new headers, or to other appropriate existing headers, not here. */ -#ifndef mozilla_Util_h_ -#define mozilla_Util_h_ +#ifndef mozilla_Util_h +#define mozilla_Util_h #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -196,6 +197,58 @@ class Maybe constructed = true; } + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + T* addr() { MOZ_ASSERT(constructed); return &asT(); @@ -271,7 +324,7 @@ ArrayEnd(T (&arr)[N]) /* * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for MOZ_STATIC_ASSERT() calls that + * that can't use C++ template functions and for static_assert() calls that * can't call ArrayLength() when it is not a C++11 constexpr function. */ #ifdef MOZ_HAVE_CXX11_CONSTEXPR @@ -280,4 +333,4 @@ ArrayEnd(T (&arr)[N]) # define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) #endif -#endif /* mozilla_Util_h_ */ +#endif /* mozilla_Util_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Vector.h b/external/spidermonkey/include/win32/mozilla/Vector.h new file mode 100644 index 0000000000..8759df8c06 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Vector.h @@ -0,0 +1,1190 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* A type/length-parametrized vector class. */ + +#ifndef mozilla_Vector_h +#define mozilla_Vector_h + +#include "mozilla/AllocPolicy.h" +#include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/MathAlgorithms.h" +#include "mozilla/MemoryReporting.h" +#include "mozilla/Move.h" +#include "mozilla/NullPtr.h" +#include "mozilla/ReentrancyGuard.h" +#include "mozilla/TemplateLib.h" +#include "mozilla/TypeTraits.h" +#include "mozilla/Util.h" + +#include // for placement new + +/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4345) +#endif + +namespace mozilla { + +template +class VectorBase; + +namespace detail { + +/* + * Check that the given capacity wastes the minimal amount of space if + * allocated on the heap. This means that cap*sizeof(T) is as close to a + * power-of-two as possible. growStorageBy() is responsible for ensuring + * this. + */ +template +static bool CapacityHasExcessSpace(size_t cap) +{ + size_t size = cap * sizeof(T); + return RoundUpPow2(size) - size >= sizeof(T); +} + +/* + * This template class provides a default implementation for vector operations + * when the element type is not known to be a POD, as judged by IsPod. + */ +template +struct VectorImpl +{ + /* Destroys constructed objects in the range [begin, end). */ + static inline void destroy(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + p->~T(); + } + + /* Constructs objects in the uninitialized range [begin, end). */ + static inline void initialize(T* begin, T* end) { + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + /* + * Copy-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(*p); + } + + /* + * Move-constructs objects in the uninitialized range + * [dst, dst+(srcend-srcbeg)) from the range [srcbeg, srcend). + */ + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + new(dst) T(Move(*p)); + } + + /* + * Copy-constructs objects in the uninitialized range [dst, dst+n) from the + * same object u. + */ + template + static inline void copyConstructN(T* dst, size_t n, const U& u) { + for (T* end = dst + n; dst < end; ++dst) + new(dst) T(u); + } + + /* + * Grows the given buffer to have capacity newCap, preserving the objects + * constructed in the range [begin, end) and updating v. Assumes that (1) + * newCap has not overflowed, and (2) multiplying newCap by sizeof(T) will + * not overflow. + */ + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + T* newbuf = reinterpret_cast(v.malloc_(newCap * sizeof(T))); + if (!newbuf) + return false; + T* dst = newbuf; + T* src = v.beginNoCheck(); + for (; src < v.endNoCheck(); ++dst, ++src) + new(dst) T(Move(*src)); + VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); + v.free_(v.mBegin); + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +/* + * This partial template specialization provides a default implementation for + * vector operations when the element type is known to be a POD, as judged by + * IsPod. + */ +template +struct VectorImpl +{ + static inline void destroy(T*, T*) {} + + static inline void initialize(T* begin, T* end) { + /* + * You would think that memset would be a big win (or even break even) + * when we know T is a POD. But currently it's not. This is probably + * because |append| tends to be given small ranges and memset requires + * a function call that doesn't get inlined. + * + * memset(begin, 0, sizeof(T) * (end-begin)); + */ + for (T* p = begin; p < end; ++p) + new(p) T(); + } + + template + static inline void copyConstruct(T* dst, const U* srcbeg, const U* srcend) { + /* + * See above memset comment. Also, notice that copyConstruct is + * currently templated (T != U), so memcpy won't work without + * requiring T == U. + * + * memcpy(dst, srcbeg, sizeof(T) * (srcend - srcbeg)); + */ + for (const U* p = srcbeg; p < srcend; ++p, ++dst) + *dst = *p; + } + + template + static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { + copyConstruct(dst, srcbeg, srcend); + } + + static inline void copyConstructN(T* dst, size_t n, const T& t) { + for (T* end = dst + n; dst < end; ++dst) + *dst = t; + } + + static inline bool + growTo(VectorBase& v, size_t newCap) { + MOZ_ASSERT(!v.usingInlineStorage()); + MOZ_ASSERT(!CapacityHasExcessSpace(newCap)); + size_t oldSize = sizeof(T) * v.mCapacity; + size_t newSize = sizeof(T) * newCap; + T* newbuf = reinterpret_cast(v.realloc_(v.mBegin, oldSize, newSize)); + if (!newbuf) + return false; + v.mBegin = newbuf; + /* v.mLength is unchanged. */ + v.mCapacity = newCap; + return true; + } +}; + +} // namespace detail + +/* + * A CRTP base class for vector-like classes. Unless you really really want + * your own vector class -- and you almost certainly don't -- you should use + * mozilla::Vector instead! + * + * See mozilla::Vector for interface requirements. + */ +template +class VectorBase : private AllocPolicy +{ + /* utilities */ + + static const bool sElemIsPod = IsPod::value; + typedef detail::VectorImpl Impl; + friend struct detail::VectorImpl; + + bool growStorageBy(size_t incr); + bool convertToHeapStorage(size_t newCap); + + /* magic constants */ + + static const int sMaxInlineBytes = 1024; + + /* compute constants */ + + /* + * Consider element size to be 1 for buffer sizing if there are 0 inline + * elements. This allows us to compile when the definition of the element + * type is not visible here. + * + * Explicit specialization is only allowed at namespace scope, so in order + * to keep everything here, we use a dummy template parameter with partial + * specialization. + */ + template + struct ElemSize + { + static const size_t value = sizeof(T); + }; + template + struct ElemSize<0, Dummy> + { + static const size_t value = 1; + }; + + static const size_t sInlineCapacity = + tl::Min::value>::value; + + /* Calculate inline buffer size; avoid 0-sized array. */ + static const size_t sInlineBytes = + tl::Max<1, sInlineCapacity * ElemSize::value>::value; + + /* member data */ + + /* + * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, + * mBegin + mLength) hold valid constructed T objects. The range [mBegin + + * mLength, mBegin + mCapacity) holds uninitialized memory. The range + * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory + * previously allocated by a call to reserve(). + */ + T* mBegin; + + /* Number of elements in the vector. */ + size_t mLength; + + /* Max number of elements storable in the vector without resizing. */ + size_t mCapacity; + +#ifdef DEBUG + /* Max elements of reserved or used space in this vector. */ + size_t mReserved; +#endif + + /* Memory used for inline storage. */ + AlignedStorage storage; + +#ifdef DEBUG + friend class ReentrancyGuard; + bool entered; +#endif + + /* private accessors */ + + bool usingInlineStorage() const { + return mBegin == const_cast(this)->inlineStorage(); + } + + T* inlineStorage() { + return static_cast(storage.addr()); + } + + T* beginNoCheck() const { + return mBegin; + } + + T* endNoCheck() { + return mBegin + mLength; + } + + const T* endNoCheck() const { + return mBegin + mLength; + } + +#ifdef DEBUG + size_t reserved() const { + MOZ_ASSERT(mReserved <= mCapacity); + MOZ_ASSERT(mLength <= mReserved); + return mReserved; + } +#endif + + /* Append operations guaranteed to succeed due to pre-reserved space. */ + template void internalAppend(const U& u); + template + void internalAppendAll(const VectorBase& u); + void internalAppendN(const T& t, size_t n); + template void internalAppend(const U* begin, size_t length); + + public: + static const size_t sMaxInlineStorage = N; + + typedef T ElementType; + + VectorBase(AllocPolicy = AllocPolicy()); + VectorBase(MoveRef); /* Move constructor. */ + ThisVector& operator=(MoveRef); /* Move assignment. */ + ~VectorBase(); + + /* accessors */ + + const AllocPolicy& allocPolicy() const { + return *this; + } + + AllocPolicy& allocPolicy() { + return *this; + } + + enum { InlineLength = N }; + + size_t length() const { + return mLength; + } + + bool empty() const { + return mLength == 0; + } + + size_t capacity() const { + return mCapacity; + } + + T* begin() { + MOZ_ASSERT(!entered); + return mBegin; + } + + const T* begin() const { + MOZ_ASSERT(!entered); + return mBegin; + } + + T* end() { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + const T* end() const { + MOZ_ASSERT(!entered); + return mBegin + mLength; + } + + T& operator[](size_t i) { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + const T& operator[](size_t i) const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(i < mLength); + return begin()[i]; + } + + T& back() { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + const T& back() const { + MOZ_ASSERT(!entered); + MOZ_ASSERT(!empty()); + return *(end() - 1); + } + + class Range + { + friend class VectorBase; + T* cur_; + T* end_; + Range(T* cur, T* end) : cur_(cur), end_(end) {} + + public: + Range() {} + bool empty() const { return cur_ == end_; } + size_t remain() const { return end_ - cur_; } + T& front() const { return *cur_; } + void popFront() { MOZ_ASSERT(!empty()); ++cur_; } + T popCopyFront() { MOZ_ASSERT(!empty()); return *cur_++; } + }; + + Range all() { + return Range(begin(), end()); + } + + /* mutators */ + + /** + * Given that the vector is empty and has no inline storage, grow to + * |capacity|. + */ + bool initCapacity(size_t request); + + /** + * If reserve(length() + N) succeeds, the N next appends are guaranteed to + * succeed. + */ + bool reserve(size_t request); + + /** + * Destroy elements in the range [end() - incr, end()). Does not deallocate + * or unreserve storage for those elements. + */ + void shrinkBy(size_t incr); + + /** Grow the vector by incr elements. */ + bool growBy(size_t incr); + + /** Call shrinkBy or growBy based on whether newSize > length(). */ + bool resize(size_t newLength); + + /** + * Increase the length of the vector, but don't initialize the new elements + * -- leave them as uninitialized memory. + */ + bool growByUninitialized(size_t incr); + bool resizeUninitialized(size_t newLength); + + /** Shorthand for shrinkBy(length()). */ + void clear(); + + /** Clears and releases any heap-allocated storage. */ + void clearAndFree(); + + /** + * If true, appending |needed| elements won't reallocate elements storage. + * This *doesn't* mean that infallibleAppend may be used! You still must + * reserve the extra space, even if this method indicates that appends won't + * need to reallocate elements storage. + */ + bool canAppendWithoutRealloc(size_t needed) const; + + /** + * Potentially fallible append operations. + * + * The function templates that take an unspecified type U require a const T& + * or a MoveRef. The MoveRef variants move their operands into the + * vector, instead of copying them. If they fail, the operand is left + * unmoved. + */ + template bool append(const U& u); + template + bool appendAll(const VectorBase& u); + bool appendN(const T& t, size_t n); + template bool append(const U* begin, const U* end); + template bool append(const U* begin, size_t length); + + /* + * Guaranteed-infallible append operations for use upon vectors whose + * memory has been pre-reserved. Don't use this if you haven't reserved the + * memory! + */ + template void infallibleAppend(const U& u) { + internalAppend(u); + } + void infallibleAppendN(const T& t, size_t n) { + internalAppendN(t, n); + } + template void infallibleAppend(const U* aBegin, const U* aEnd) { + internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); + } + template void infallibleAppend(const U* aBegin, size_t aLength) { + internalAppend(aBegin, aLength); + } + + void popBack(); + + T popCopy(); + + /** + * Transfers ownership of the internal buffer used by this vector to the + * caller. (It's the caller's responsibility to properly deallocate this + * buffer, in accordance with this vector's AllocPolicy.) After this call, + * the vector is empty. Since the returned buffer may need to be allocated + * (if the elements are currently stored in-place), the call can fail, + * returning nullptr. + * + * N.B. Although a T*, only the range [0, length()) is constructed. + */ + T* extractRawBuffer(); + + /** + * Transfer ownership of an array of objects into the vector. The caller + * must have allocated the array in accordance with this vector's + * AllocPolicy. + * + * N.B. This call assumes that there are no uninitialized elements in the + * passed array. + */ + void replaceRawBuffer(T* p, size_t length); + + /** + * Places |val| at position |p|, shifting existing elements from |p| onward + * one position higher. On success, |p| should not be reused because it'll + * be a dangling pointer if reallocation of the vector storage occurred; the + * return value should be used instead. On failure, nullptr is returned. + * + * Example usage: + * + * if (!(p = vec.insert(p, val))) + * + * + * + * This is inherently a linear-time operation. Be careful! + */ + T* insert(T* p, const T& val); + + /** + * Removes the element |t|, which must fall in the bounds [begin, end), + * shifting existing elements from |t + 1| onward one position lower. + */ + void erase(T* t); + + /** + * Measure the size of the vector's heap-allocated storage. + */ + size_t sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const; + + /** + * Like sizeOfExcludingThis, but also measures the size of the vector + * object (which must be heap-allocated) itself. + */ + size_t sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const; + + void swap(ThisVector& other); + + private: + VectorBase(const ThisVector&) MOZ_DELETE; + void operator=(const ThisVector&) MOZ_DELETE; +}; + +/* This does the re-entrancy check plus several other sanity checks. */ +#define MOZ_REENTRANCY_GUARD_ET_AL \ + ReentrancyGuard g(*this); \ + MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == sInlineCapacity); \ + MOZ_ASSERT(reserved() <= mCapacity); \ + MOZ_ASSERT(mLength <= reserved()); \ + MOZ_ASSERT(mLength <= mCapacity) + +/* Vector Implementation */ + +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(AP ap) + : AP(ap), + mBegin(static_cast(storage.addr())), + mLength(0), + mCapacity(sInlineCapacity) +#ifdef DEBUG + , mReserved(sInlineCapacity), + entered(false) +#endif +{} + +/* Move constructor. */ +template +MOZ_ALWAYS_INLINE +VectorBase::VectorBase(MoveRef rhs) + : AllocPolicy(rhs) +#ifdef DEBUG + , entered(false) +#endif +{ + mLength = rhs->mLength; + mCapacity = rhs->mCapacity; +#ifdef DEBUG + mReserved = rhs->mReserved; +#endif + + if (rhs->usingInlineStorage()) { + /* We can't move the buffer over in this case, so copy elements. */ + mBegin = static_cast(storage.addr()); + Impl::moveConstruct(mBegin, rhs->beginNoCheck(), rhs->endNoCheck()); + /* + * Leave rhs's mLength, mBegin, mCapacity, and mReserved as they are. + * The elements in its in-line storage still need to be destroyed. + */ + } else { + /* + * Take src's buffer, and turn src into an empty vector using + * in-line storage. + */ + mBegin = rhs->mBegin; + rhs->mBegin = static_cast(rhs->storage.addr()); + rhs->mCapacity = sInlineCapacity; + rhs->mLength = 0; +#ifdef DEBUG + rhs->mReserved = sInlineCapacity; +#endif + } +} + +/* Move assignment. */ +template +MOZ_ALWAYS_INLINE +TV& +VectorBase::operator=(MoveRef rhs) +{ + TV* tv = static_cast(this); + tv->~TV(); + new(tv) TV(rhs); + return *tv; +} + +template +MOZ_ALWAYS_INLINE +VectorBase::~VectorBase() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); +} + +/* + * This function will create a new heap buffer with capacity newCap, + * move all elements in the inline buffer to this new buffer, + * and fail on OOM. + */ +template +inline bool +VectorBase::convertToHeapStorage(size_t newCap) +{ + MOZ_ASSERT(usingInlineStorage()); + + /* Allocate buffer. */ + MOZ_ASSERT(!detail::CapacityHasExcessSpace(newCap)); + T* newBuf = reinterpret_cast(this->malloc_(newCap * sizeof(T))); + if (!newBuf) + return false; + + /* Copy inline elements into heap buffer. */ + Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + + /* Switch in heap buffer. */ + mBegin = newBuf; + /* mLength is unchanged. */ + mCapacity = newCap; + return true; +} + +template +MOZ_NEVER_INLINE bool +VectorBase::growStorageBy(size_t incr) +{ + MOZ_ASSERT(mLength + incr > mCapacity); + MOZ_ASSERT_IF(!usingInlineStorage(), + !detail::CapacityHasExcessSpace(mCapacity)); + + /* + * When choosing a new capacity, its size should is as close to 2**N bytes + * as possible. 2**N-sized requests are best because they are unlikely to + * be rounded up by the allocator. Asking for a 2**N number of elements + * isn't as good, because if sizeof(T) is not a power-of-two that would + * result in a non-2**N request size. + */ + + size_t newCap; + + if (incr == 1) { + if (usingInlineStorage()) { + /* This case occurs in ~70--80% of the calls to this function. */ + size_t newSize = + tl::RoundUpPow2<(sInlineCapacity + 1) * sizeof(T)>::value; + newCap = newSize / sizeof(T); + goto convert; + } + + if (mLength == 0) { + /* This case occurs in ~0--10% of the calls to this function. */ + newCap = 1; + goto grow; + } + + /* This case occurs in ~15--20% of the calls to this function. */ + + /* + * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector + * to 1GB of memory on a 32-bit system, which is a reasonable limit. It + * also ensures that + * + * static_cast(end()) - static_cast(begin()) + * + * doesn't overflow ptrdiff_t (see bug 510319). + */ + if (mLength & tl::MulOverflowMask<4 * sizeof(T)>::value) { + this->reportAllocOverflow(); + return false; + } + + /* + * If we reach here, the existing capacity will have a size that is already + * as close to 2^N as sizeof(T) will allow. Just double the capacity, and + * then there might be space for one more element. + */ + newCap = mLength * 2; + if (detail::CapacityHasExcessSpace(newCap)) + newCap += 1; + } else { + /* This case occurs in ~2% of the calls to this function. */ + size_t newMinCap = mLength + incr; + + /* Did mLength + incr overflow? Will newCap * sizeof(T) overflow? */ + if (newMinCap < mLength || + newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value) + { + this->reportAllocOverflow(); + return false; + } + + size_t newMinSize = newMinCap * sizeof(T); + size_t newSize = RoundUpPow2(newMinSize); + newCap = newSize / sizeof(T); + } + + if (usingInlineStorage()) { + convert: + return convertToHeapStorage(newCap); + } + +grow: + return Impl::growTo(*this, newCap); +} + +template +inline bool +VectorBase::initCapacity(size_t request) +{ + MOZ_ASSERT(empty()); + MOZ_ASSERT(usingInlineStorage()); + if (request == 0) + return true; + T* newbuf = reinterpret_cast(this->malloc_(request * sizeof(T))); + if (!newbuf) + return false; + mBegin = newbuf; + mCapacity = request; +#ifdef DEBUG + mReserved = request; +#endif + return true; +} + +template +inline bool +VectorBase::reserve(size_t request) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (request > mCapacity && !growStorageBy(request - mLength)) + return false; + +#ifdef DEBUG + if (request > mReserved) + mReserved = request; + MOZ_ASSERT(mLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); +#endif + return true; +} + +template +inline void +VectorBase::shrinkBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(incr <= mLength); + Impl::destroy(endNoCheck() - incr, endNoCheck()); + mLength -= incr; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growBy(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + T* newend = endNoCheck() + incr; + Impl::initialize(endNoCheck(), newend); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::growByUninitialized(size_t incr) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (incr > mCapacity - mLength && !growStorageBy(incr)) + return false; + + MOZ_ASSERT(mLength + incr <= mCapacity); + mLength += incr; +#ifdef DEBUG + if (mLength > mReserved) + mReserved = mLength; +#endif + return true; +} + +template +inline bool +VectorBase::resize(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growBy(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::resizeUninitialized(size_t newLength) +{ + size_t curLength = mLength; + if (newLength > curLength) + return growByUninitialized(newLength - curLength); + shrinkBy(curLength - newLength); + return true; +} + +template +inline void +VectorBase::clear() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + Impl::destroy(beginNoCheck(), endNoCheck()); + mLength = 0; +} + +template +inline void +VectorBase::clearAndFree() +{ + clear(); + + if (usingInlineStorage()) + return; + + this->free_(beginNoCheck()); + mBegin = static_cast(storage.addr()); + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif +} + +template +inline bool +VectorBase::canAppendWithoutRealloc(size_t needed) const +{ + return mLength + needed <= mCapacity; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendAll(const VectorBase& other) +{ + internalAppend(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U& u) +{ + MOZ_ASSERT(mLength + 1 <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + new(endNoCheck()) T(u); + ++mLength; +} + +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendN(const T& t, size_t needed) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppendN(t, needed); + return true; +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppendN(const T& t, size_t needed) +{ + MOZ_ASSERT(mLength + needed <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstructN(endNoCheck(), needed, t); + mLength += needed; +} + +template +inline T* +VectorBase::insert(T* p, const T& val) +{ + MOZ_ASSERT(begin() <= p); + MOZ_ASSERT(p <= end()); + size_t pos = p - begin(); + MOZ_ASSERT(pos <= mLength); + size_t oldLength = mLength; + if (pos == oldLength) { + if (!append(val)) + return nullptr; + } else { + T oldBack = back(); + if (!append(oldBack)) /* Dup the last element. */ + return nullptr; + for (size_t i = oldLength; i > pos; --i) + (*this)[i] = (*this)[i - 1]; + (*this)[pos] = val; + } + return begin() + pos; +} + +template +inline void +VectorBase::erase(T* it) +{ + MOZ_ASSERT(begin() <= it); + MOZ_ASSERT(it < end()); + while (it + 1 < end()) { + *it = *(it + 1); + ++it; + } + popBack(); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U* insBegin, const U* insEnd) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + size_t needed = PointerRangeSize(insBegin, insEnd); + if (mLength + needed > mCapacity && !growStorageBy(needed)) + return false; + +#ifdef DEBUG + if (mLength + needed > mReserved) + mReserved = mLength + needed; +#endif + internalAppend(insBegin, needed); + return true; +} + +template +template +MOZ_ALWAYS_INLINE void +VectorBase::internalAppend(const U* insBegin, size_t insLength) +{ + MOZ_ASSERT(mLength + insLength <= mReserved); + MOZ_ASSERT(mReserved <= mCapacity); + Impl::copyConstruct(endNoCheck(), insBegin, insBegin + insLength); + mLength += insLength; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U& u) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + if (mLength == mCapacity && !growStorageBy(1)) + return false; + +#ifdef DEBUG + if (mLength + 1 > mReserved) + mReserved = mLength + 1; +#endif + internalAppend(u); + return true; +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::appendAll(const VectorBase& other) +{ + return append(other.begin(), other.length()); +} + +template +template +MOZ_ALWAYS_INLINE bool +VectorBase::append(const U *insBegin, size_t insLength) +{ + return append(insBegin, insBegin + insLength); +} + +template +MOZ_ALWAYS_INLINE void +VectorBase::popBack() +{ + MOZ_REENTRANCY_GUARD_ET_AL; + MOZ_ASSERT(!empty()); + --mLength; + endNoCheck()->~T(); +} + +template +MOZ_ALWAYS_INLINE T +VectorBase::popCopy() +{ + T ret = back(); + popBack(); + return ret; +} + +template +inline T* +VectorBase::extractRawBuffer() +{ + T* ret; + if (usingInlineStorage()) { + ret = reinterpret_cast(this->malloc_(mLength * sizeof(T))); + if (!ret) + return nullptr; + Impl::copyConstruct(ret, beginNoCheck(), endNoCheck()); + Impl::destroy(beginNoCheck(), endNoCheck()); + /* mBegin, mCapacity are unchanged. */ + mLength = 0; + } else { + ret = mBegin; + mBegin = static_cast(storage.addr()); + mLength = 0; + mCapacity = sInlineCapacity; +#ifdef DEBUG + mReserved = sInlineCapacity; +#endif + } + return ret; +} + +template +inline void +VectorBase::replaceRawBuffer(T* p, size_t aLength) +{ + MOZ_REENTRANCY_GUARD_ET_AL; + + /* Destroy what we have. */ + Impl::destroy(beginNoCheck(), endNoCheck()); + if (!usingInlineStorage()) + this->free_(beginNoCheck()); + + /* Take in the new buffer. */ + if (aLength <= sInlineCapacity) { + /* + * We convert to inline storage if possible, even though p might + * otherwise be acceptable. Maybe this behaviour should be + * specifiable with an argument to this function. + */ + mBegin = static_cast(storage.addr()); + mLength = aLength; + mCapacity = sInlineCapacity; + Impl::moveConstruct(mBegin, p, p + aLength); + Impl::destroy(p, p + aLength); + this->free_(p); + } else { + mBegin = p; + mLength = aLength; + mCapacity = aLength; + } +#ifdef DEBUG + mReserved = aLength; +#endif +} + +template +inline size_t +VectorBase::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const +{ + return usingInlineStorage() ? 0 : mallocSizeOf(beginNoCheck()); +} + +template +inline size_t +VectorBase::sizeOfIncludingThis(MallocSizeOf mallocSizeOf) const +{ + return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); +} + +template +inline void +VectorBase::swap(TV& other) +{ + static_assert(N == 0, + "still need to implement this for N != 0"); + + // This only works when inline storage is always empty. + if (!usingInlineStorage() && other.usingInlineStorage()) { + other.mBegin = mBegin; + mBegin = inlineStorage(); + } else if (usingInlineStorage() && !other.usingInlineStorage()) { + mBegin = other.mBegin; + other.mBegin = other.inlineStorage(); + } else if (!usingInlineStorage() && !other.usingInlineStorage()) { + Swap(mBegin, other.mBegin); + } else { + // This case is a no-op, since we'd set both to use their inline storage. + } + + Swap(mLength, other.mLength); + Swap(mCapacity, other.mCapacity); +#ifdef DEBUG + Swap(mReserved, other.mReserved); +#endif +} + +/* + * STL-like container providing a short-lived, dynamic buffer. Vector calls the + * constructors/destructors of all elements stored in its internal buffer, so + * non-PODs may be safely used. Additionally, Vector will store the first N + * elements in-place before resorting to dynamic allocation. + * + * T requirements: + * - default and copy constructible, assignable, destructible + * - operations do not throw + * N requirements: + * - any value, however, N is clamped to min/max values + * AllocPolicy: + * - see "Allocation policies" in AllocPolicy.h (defaults to + * mozilla::MallocAllocPolicy) + * + * Vector is not reentrant: T member functions called during Vector member + * functions must not call back into the same object! + */ +template +class Vector + : public VectorBase > +{ + typedef VectorBase Base; + + public: + Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} + Vector(mozilla::MoveRef vec) : Base(vec) {} + Vector& operator=(mozilla::MoveRef vec) { + return Base::operator=(vec); + } +}; + +} // namespace mozilla + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif /* mozilla_Vector_h */ diff --git a/external/spidermonkey/include/win32/mozilla/WeakPtr.h b/external/spidermonkey/include/win32/mozilla/WeakPtr.h index d61b0b37d3..c714ebf565 100644 --- a/external/spidermonkey/include/win32/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/win32/mozilla/WeakPtr.h @@ -1,7 +1,8 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Weak pointer functionality, implemented as a mixin for use with any class. */ @@ -13,6 +14,9 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * + * AtomicSupportsWeakPtr can be used for a variant with an atomically updated + * reference counter. + * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -55,10 +59,11 @@ * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h */ -#ifndef mozilla_WeakPtr_h_ -#define mozilla_WeakPtr_h_ +#ifndef mozilla_WeakPtr_h +#define mozilla_WeakPtr_h #include "mozilla/Assertions.h" +#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -71,8 +76,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted > +template +class WeakReference : public RefCounted, Atomicity> { public: explicit WeakReference(T* p) : ptr(p) {} @@ -81,8 +86,8 @@ class WeakReference : public RefCounted > } private: - friend class WeakPtrBase >; - friend class SupportsWeakPtrBase >; + friend class WeakPtrBase; + friend class SupportsWeakPtrBase; void detach() { ptr = nullptr; } @@ -103,8 +108,8 @@ class SupportsWeakPtrBase protected: ~SupportsWeakPtrBase() { - MOZ_STATIC_ASSERT((IsBaseOf, T>::value), - "T must derive from SupportsWeakPtrBase"); + static_assert(IsBaseOf, T>::value, + "T must derive from SupportsWeakPtrBase"); if (weakRef) weakRef->detach(); } @@ -116,10 +121,30 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr : public SupportsWeakPtrBase > +class SupportsWeakPtr + : public SupportsWeakPtrBase > { }; +template +class AtomicSupportsWeakPtr + : public SupportsWeakPtrBase > +{ +}; + +namespace detail { + +template +struct WeakReferenceCount +{ + static const RefCountAtomicity atomicity = + IsBaseOf, T>::value + ? AtomicRefCount + : NonAtomicRefCount; +}; + +} + template class WeakPtrBase { @@ -152,9 +177,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase > +class WeakPtr : public WeakPtrBase::atomicity> > { - typedef WeakPtrBase > Base; + typedef WeakPtrBase::atomicity> > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} @@ -163,4 +188,4 @@ class WeakPtr : public WeakPtrBase > } // namespace mozilla -#endif /* ifdef mozilla_WeakPtr_h_ */ +#endif /* mozilla_WeakPtr_h */ diff --git a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id index 34db1e4f01..8362daf11f 100644 --- a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -ab3b6f2938d78c25531e3afcac0dbc1e2ae234ac \ No newline at end of file +faf19f806c33a8c42138cd4ada1c76d04f9510f4 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id index d808087a7d..8da98b5613 100644 --- a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -be12c5e66dcb793cb02c542083565cc569d9cf43 \ No newline at end of file +9c5b123f113fb3b0b6846b4f1123ec5a40004944 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id index fd7cdf9335..74e8973064 100644 --- a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -916f323784cc5896ba7fe056ee2a6be4cc75507f \ No newline at end of file +3e18fa7933f481d605147b1d46dd7afee105fa2c \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id index 62d0642dea..a263aa1a15 100644 --- a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -de60414ce2fd3a5d2d446568baf6a5b1f268dace \ No newline at end of file +62ff11f15f6f4dae163513e336bc3e4671b91a90 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id index 904a424da5..609f8680c6 100644 --- a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -97a549a55dd578b65863f083b4aa76a4c0a521b7 \ No newline at end of file +591cdbb9304d6f7b5682542b7a50e0b5ae4d6a4d \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-23.0.dll.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-23.0.dll.REMOVED.git-id deleted file mode 100644 index a57db13141..0000000000 --- a/external/spidermonkey/prebuilt/win32/mozjs-23.0.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -83c05fbd090f7df8dda9789f7201534375ebb993 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-23.0.lib.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-23.0.lib.REMOVED.git-id deleted file mode 100644 index c727112da9..0000000000 --- a/external/spidermonkey/prebuilt/win32/mozjs-23.0.lib.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c4ea49d145a5b6898bd7c5c00c8e78413a6894b1 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id new file mode 100644 index 0000000000..7e9dc81732 --- /dev/null +++ b/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id @@ -0,0 +1 @@ +c1212ee7de1da38ee10b27e327120205ab2cac7c \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id new file mode 100644 index 0000000000..ae3f274acc --- /dev/null +++ b/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id @@ -0,0 +1 @@ +5991d26d951ae7b8398cd037bb22422ec33ab949 \ No newline at end of file From 3b86d6398f7af675b883319ef422dab955ebb1c9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 30 Oct 2013 21:56:07 +0800 Subject: [PATCH 291/557] [sp v25] Fixing complication errors after updating Spidermonkey to v25. --- .../javascript/bindings/ScriptingCore.cpp | 101 +++- ...dings_chipmunk_auto_classes_registration.h | 36 +- ...bindings_chipmunk_functions_registration.h | 546 +++++++++--------- .../chipmunk/js_bindings_chipmunk_manual.cpp | 13 +- .../js_bindings_chipmunk_registration.cpp | 36 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../cocosbuilder/js_bindings_ccbreader.cpp | 4 +- .../bindings/cocosjs_manual_conversions.cpp | 6 +- .../jsb_cocos2dx_extension_manual.cpp | 14 +- .../bindings/js_bindings_opengl.cpp | 11 +- .../javascript/bindings/jsb_helper.h | 12 +- .../bindings/jsb_opengl_registration.cpp | 10 +- .../js_bindings_system_registration.cpp | 10 +- .../bindings/network/XMLHTTPRequest.cpp | 7 +- .../bindings/network/jsb_websocket.cpp | 32 +- 15 files changed, 452 insertions(+), 388 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index c4603fc8c0..6a8ac7dd98 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -300,13 +300,13 @@ JSBool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) void registerDefaultClasses(JSContext* cx, JSObject* global) { // first, try to get the ns - jsval nsval; + JS::RootedValue nsval(cx); JSObject *ns; JS_GetProperty(cx, global, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, global, "cc", &nsval); + JS_SetProperty(cx, global, "cc", nsval); } else { JS_ValueToObject(cx, nsval, &ns); } @@ -315,8 +315,9 @@ void registerDefaultClasses(JSContext* cx, JSObject* global) { // Javascript controller (__jsc__) // JSObject *jsc = JS_NewObject(cx, NULL, NULL, NULL); - jsval jscVal = OBJECT_TO_JSVAL(jsc); - JS_SetProperty(cx, global, "__jsc__", &jscVal); + JS::RootedValue jscVal(cx); + jscVal = OBJECT_TO_JSVAL(jsc); + JS_SetProperty(cx, global, "__jsc__", jscVal); JS_DefineFunction(cx, jsc, "garbageCollect", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, jsc, "dumpRoot", ScriptingCore::dumpRoot, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); @@ -451,6 +452,11 @@ void ScriptingCore::createGlobalContext() { this->_cx = NULL; this->_rt = NULL; } + + // Start the engine. Added in SpiderMonkey v25 + if (!JS_Init()) + return; + // Removed from Spidermonkey 19. //JS_SetCStringsAreUTF8(); this->_rt = JS_NewRuntime(8L * 1024L * 1024L, JS_USE_HELPER_THREADS); @@ -461,13 +467,15 @@ void ScriptingCore::createGlobalContext() { JS_SetNativeStackQuota(_rt, JSB_MAX_STACK_QUOTA); this->_cx = JS_NewContext(_rt, 8192); + JS_SetOptions(this->_cx, JSOPTION_TYPE_INFERENCE); - JS_SetVersion(this->_cx, JSVERSION_LATEST); + +// JS_SetVersion(this->_cx, JSVERSION_LATEST); // Only disable METHODJIT on iOS. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - JS_SetOptions(this->_cx, JS_GetOptions(this->_cx) & ~JSOPTION_METHODJIT); - JS_SetOptions(this->_cx, JS_GetOptions(this->_cx) & ~JSOPTION_METHODJIT_ALWAYS); +// JS_SetOptions(this->_cx, JS_GetOptions(this->_cx) & ~JSOPTION_METHODJIT); +// JS_SetOptions(this->_cx, JS_GetOptions(this->_cx) & ~JSOPTION_METHODJIT_ALWAYS); #endif JS_SetErrorReporter(this->_cx, ScriptingCore::reportError); @@ -475,7 +483,10 @@ void ScriptingCore::createGlobalContext() { //JS_SetGCZeal(this->_cx, 2, JS_DEFAULT_ZEAL_FREQ); #endif this->_global = NewGlobalObject(_cx); - + JS_AddObjectRoot(_cx, &_global); + JSAutoCompartment ac(_cx, _global); + js::SetDefaultObjectForContext(_cx, _global); + for (std::vector::iterator it = registrationList.begin(); it != registrationList.end(); it++) { sc_register_sth callback = *it; callback(this->_cx, this->_global); @@ -507,8 +518,12 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c if (cx == NULL) { cx = _cx; } - JSScript *script = NULL; + + JSAutoCompartment ac(cx, global); + + js::RootedScript script(cx); js::RootedObject obj(cx, global); + JS::CompileOptions options(cx); options.setUTF8(true).setFileAndLine(fullPath.c_str(), 1); @@ -659,7 +674,7 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) return JS_FALSE; } } else { - JSObject* glob = JS_GetGlobalForScopeChain(cx); + JSObject* glob = JS::CurrentGlobalOrNull(cx); res = ScriptingCore::getInstance()->runScript(path, glob); } return res; @@ -925,8 +940,8 @@ JSBool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, ui { JSBool bRet = JS_FALSE; JSBool hasAction; - jsval temp_retval; JSContext* cx = this->_cx; + JS::RootedValue temp_retval(cx); JSObject* obj = JSVAL_TO_OBJECT(owner); do @@ -1213,7 +1228,8 @@ JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { JSObject *tmp; - jsval jsx, jsy; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); double x, y; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1231,7 +1247,11 @@ JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { JSObject *tmp; - jsval jsx, jsy, jsz, jstimestamp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jsz(cx); + JS::RootedValue jstimestamp(cx); + double x, y, timestamp, z; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1292,7 +1312,11 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { JSObject *tmp; - jsval jsx, jsy, jswidth, jsheight; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jswidth(cx); + JS::RootedValue jsheight(cx); + double x, y, width, height; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1316,7 +1340,8 @@ JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { JSObject *tmp; - jsval jsw, jsh; + JS::RootedValue jsw(cx); + JS::RootedValue jsh(cx); double w, h; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1333,7 +1358,11 @@ JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { JSObject *tmp; - jsval jsr, jsg, jsb, jsa; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + double r, g, b, a; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1357,7 +1386,10 @@ JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { JSObject *tmp; - jsval jsr, jsg, jsb, jsa; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); double r, g, b, a; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1380,7 +1412,9 @@ JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { JSObject *tmp; - jsval jsr, jsg, jsb; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); double r, g, b; JSBool ok = v.isObject() && JS_ValueToObject(cx, v, &tmp) && @@ -1554,7 +1588,7 @@ jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) DictElement* pElement = NULL; CCDICT_FOREACH(dict, pElement) { - jsval dictElement; + JS::RootedValue dictElement(cx); Object* obj = pElement->getObject(); //First, check whether object is associated with js object. js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); @@ -1591,7 +1625,7 @@ jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) const char* key = pElement->getStrKey(); if (key && strlen(key) > 0) { - JS_SetProperty(cx, jsRet, key, &dictElement); + JS_SetProperty(cx, jsRet, key, dictElement); } } return OBJECT_TO_JSVAL(jsRet); @@ -1635,7 +1669,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { dict = Dictionary::create(); } - jsval value; + JS::RootedValue value(cx); JS_GetPropertyById(cx, tmp, idp, &value); if (value.isObject()) { @@ -1699,7 +1733,12 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) { JSObject *tmp; - jsval jsa, jsb, jsc, jsd, jstx, jsty; + JS::RootedValue jsa(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsc(cx); + JS::RootedValue jsd(cx); + JS::RootedValue jstx(cx); + JS::RootedValue jsty(cx); double a, b, c, d, tx, ty; JSBool ok = JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "a", &jsa) && @@ -2145,11 +2184,12 @@ JSBool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) void ScriptingCore::enableDebugger() { - JS_SetDebugMode(_cx, JS_TRUE); - if (_debugGlobal == NULL) { JSAutoCompartment ac0(_cx, _global); + + JS_SetDebugMode(_cx, JS_TRUE); + _debugGlobal = NewGlobalObject(_cx, true); JS_WrapObject(_cx, &_debugGlobal); JSAutoCompartment ac(_cx, _debugGlobal); @@ -2182,7 +2222,10 @@ void ScriptingCore::enableDebugger() JSObject* NewGlobalObject(JSContext* cx, bool debug) { - JSObject* glob = JS_NewGlobalObject(cx, &global_class, NULL); + JS::CompartmentOptions options; + options.setVersion(JSVERSION_LATEST); + + JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, NULL, JS::DontFireOnNewGlobalHook, options)); if (!glob) { return NULL; } @@ -2196,6 +2239,8 @@ JSObject* NewGlobalObject(JSContext* cx, bool debug) if (!ok) return NULL; + JS_FireOnNewGlobalObject(cx, glob); + return glob; } @@ -2251,7 +2296,7 @@ void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) { - jsval jsr; + JS::RootedValue jsr(cx); Color3B out; JS_GetProperty(cx, colorObject, "r", &jsr); double fontR = 0.0; @@ -2275,7 +2320,7 @@ static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) { - jsval jsr; + JS::RootedValue jsr(cx); Size out; JS_GetProperty(cx, sizeObject, "width", &jsr); double width = 0.0; @@ -2316,7 +2361,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) out->_fontFillColor = Color3B::WHITE; // font name - jsval jsr; + JS::RootedValue jsr(cx); JS_GetProperty(cx, jsobj, "fontName", &jsr); JS_ValueToString(cx, jsr); JSStringWrapper wrapper(jsr); diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h index da26c49bb3..6435be96f6 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes_registration.h @@ -6,24 +6,24 @@ #include "js_bindings_config.h" #ifdef JSB_INCLUDE_CHIPMUNK -JSB_cpConstraint_createClass(_cx, chipmunk, "Constraint"); -JSB_cpGrooveJoint_createClass(_cx, chipmunk, "GrooveJoint"); -JSB_cpSimpleMotor_createClass(_cx, chipmunk, "SimpleMotor"); -JSB_cpPivotJoint_createClass(_cx, chipmunk, "PivotJoint"); -JSB_cpPinJoint_createClass(_cx, chipmunk, "PinJoint"); -JSB_cpSlideJoint_createClass(_cx, chipmunk, "SlideJoint"); -JSB_cpGearJoint_createClass(_cx, chipmunk, "GearJoint"); -JSB_cpDampedRotarySpring_createClass(_cx, chipmunk, "DampedRotarySpring"); -JSB_cpDampedSpring_createClass(_cx, chipmunk, "DampedSpring"); -JSB_cpRatchetJoint_createClass(_cx, chipmunk, "RatchetJoint"); -JSB_cpRotaryLimitJoint_createClass(_cx, chipmunk, "RotaryLimitJoint"); -JSB_cpArbiter_createClass(_cx, chipmunk, "Arbiter"); -JSB_cpSpace_createClass(_cx, chipmunk, "Space"); -JSB_cpBody_createClass(_cx, chipmunk, "Body"); -JSB_cpShape_createClass(_cx, chipmunk, "Shape"); -JSB_cpCircleShape_createClass(_cx, chipmunk, "CircleShape"); -JSB_cpSegmentShape_createClass(_cx, chipmunk, "SegmentShape"); -JSB_cpPolyShape_createClass(_cx, chipmunk, "PolyShape"); +JSB_cpConstraint_createClass(cx, chipmunk, "Constraint"); +JSB_cpGrooveJoint_createClass(cx, chipmunk, "GrooveJoint"); +JSB_cpSimpleMotor_createClass(cx, chipmunk, "SimpleMotor"); +JSB_cpPivotJoint_createClass(cx, chipmunk, "PivotJoint"); +JSB_cpPinJoint_createClass(cx, chipmunk, "PinJoint"); +JSB_cpSlideJoint_createClass(cx, chipmunk, "SlideJoint"); +JSB_cpGearJoint_createClass(cx, chipmunk, "GearJoint"); +JSB_cpDampedRotarySpring_createClass(cx, chipmunk, "DampedRotarySpring"); +JSB_cpDampedSpring_createClass(cx, chipmunk, "DampedSpring"); +JSB_cpRatchetJoint_createClass(cx, chipmunk, "RatchetJoint"); +JSB_cpRotaryLimitJoint_createClass(cx, chipmunk, "RotaryLimitJoint"); +JSB_cpArbiter_createClass(cx, chipmunk, "Arbiter"); +JSB_cpSpace_createClass(cx, chipmunk, "Space"); +JSB_cpBody_createClass(cx, chipmunk, "Body"); +JSB_cpShape_createClass(cx, chipmunk, "Shape"); +JSB_cpCircleShape_createClass(cx, chipmunk, "CircleShape"); +JSB_cpSegmentShape_createClass(cx, chipmunk, "SegmentShape"); +JSB_cpPolyShape_createClass(cx, chipmunk, "PolyShape"); #endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h index 2d84087c28..20e87592f9 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h @@ -7,279 +7,279 @@ #ifdef JSB_INCLUDE_CHIPMUNK #include "js_bindings_chipmunk_manual.h" -JS_DefineFunction(_cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(_cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); #endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 14a88c87bb..197a270e91 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -473,13 +473,13 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { - jsval nsval; + JS::RootedValue nsval(cx); JSObject *ns; JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); + JS_SetProperty(cx, obj, "cc", nsval); } else { JS_ValueToObject(cx, nsval, &ns); } @@ -488,13 +488,13 @@ void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { } void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj) { - jsval nsval; + JS::RootedValue nsval(cx); JSObject *ns; JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); + JS_SetProperty(cx, obj, "cc", nsval); } else { JS_ValueToObject(cx, nsval, &ns); } @@ -509,7 +509,10 @@ JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) JSB_PRECONDITION( ok, "Error converting value to object"); JSB_PRECONDITION( jsobj, "Not a valid JS object"); - jsval vall, valb, valr, valt; + JS::RootedValue vall(cx); + JS::RootedValue valb(cx); + JS::RootedValue valr(cx); + JS::RootedValue valt(cx); ok = JS_TRUE; ok &= JS_GetProperty(cx, jsobj, "l", &vall); ok &= JS_GetProperty(cx, jsobj, "b", &valb); diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp index a96434eace..6a31f800e6 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp @@ -36,32 +36,34 @@ #include "js_bindings_chipmunk_manual.h" -void jsb_register_chipmunk(JSContext *_cx, JSObject *object) +void jsb_register_chipmunk(JSContext* cx, JSObject *object) { // // Chipmunk // - JSObject *chipmunk = JS_NewObject(_cx, NULL, NULL, NULL); - jsval chipmunkVal = OBJECT_TO_JSVAL(chipmunk); - JS_SetProperty(_cx, object, "cp", &chipmunkVal); + JSObject *chipmunk = JS_NewObject(cx, NULL, NULL, NULL); + JS::RootedValue chipmunkVal(cx); + + chipmunkVal = OBJECT_TO_JSVAL(chipmunk); + JS_SetProperty(cx, object, "cp", chipmunkVal); - JSB_cpBase_createClass(_cx, chipmunk, "Base"); // manual base class registration + JSB_cpBase_createClass(cx, chipmunk, "Base"); // manual base class registration #include "js_bindings_chipmunk_auto_classes_registration.h" #include "js_bindings_chipmunk_functions_registration.h" // manual - JS_DefineFunction(_cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(_cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - register_CCPhysicsSprite(_cx, object); - register_CCPhysicsDebugNode(_cx, object); + JS_DefineFunction(cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + register_CCPhysicsSprite(cx, object); + register_CCPhysicsDebugNode(cx, object); } diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 3237461ed0..4308bf2a80 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -d88cc721a9477ddfd6f690121991a620cbd260e6 \ No newline at end of file +8a34b565b95d3bdd2cf1dad5b70729544004a35d \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp index 733ac47b45..66f6819df3 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp +++ b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp @@ -303,13 +303,13 @@ extern JSObject* jsb_CCBReader_prototype; extern JSObject* jsb_CCBAnimationManager_prototype; void register_CCBuilderReader(JSContext *cx, JSObject *obj) { - jsval nsval; + JS::RootedValue nsval(cx); JSObject *ns; JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ns); - JS_SetProperty(cx, obj, "cc", &nsval); + JS_SetProperty(cx, obj, "cc", nsval); } else { JS_ValueToObject(cx, nsval, &ns); } diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp index 22e075684c..56bd017069 100644 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp @@ -18,7 +18,8 @@ JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) JSB_PRECONDITION( jsobj, "Not a valid JS object"); - jsval valx, valy; + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); JSBool ok = JS_TRUE; ok &= JS_GetProperty(cx, jsobj, "x", &valx); ok &= JS_GetProperty(cx, jsobj, "y", &valy); @@ -65,7 +66,8 @@ JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) JSB_PRECONDITION( jsobj, "Not a valid JS object"); - jsval valx, valy; + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); JSBool ok = JS_TRUE; ok &= JS_GetProperty(cx, jsobj, "x", &valx); ok &= JS_GetProperty(cx, jsobj, "y", &valy); diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp index 9f2ab82470..e46bc688f8 100644 --- a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp @@ -322,12 +322,14 @@ private: js_proxy_t * p = jsb_get_native_proxy(table); if (!p) return false; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JSBool hasAction; - jsval temp_retval; + JS::RootedValue temp_retval(cx); jsval dataVal = OBJECT_TO_JSVAL(p->obj); - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* obj = _JSTableViewDataSource; + JSAutoCompartment ac(cx, obj); if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) { @@ -340,7 +342,6 @@ private: return false; } - JSAutoCompartment ac(cx, obj); JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), 1, &dataVal, &retVal); return true; @@ -353,15 +354,15 @@ private: js_proxy_t * p = jsb_get_native_proxy(table); if (!p) return false; - + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSBool hasAction; - jsval temp_retval; + JS::RootedValue temp_retval(cx); jsval dataVal[2]; dataVal[0] = OBJECT_TO_JSVAL(p->obj); dataVal[1] = INT_TO_JSVAL(idx); - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* obj = _JSTableViewDataSource; + JSAutoCompartment ac(cx, obj); if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) { @@ -375,7 +376,6 @@ private: return false; } - JSAutoCompartment ac(cx, obj); JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), 2, dataVal, &retVal); return true; diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index dfde6ba278..6b08243875 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -13,11 +13,12 @@ void GLNode::draw() { JSB_ENSURE_AUTOCOMPARTMENT(cx, jsObj); JS_HasProperty(cx, jsObj, "draw", &found); if (found == JS_TRUE) { - jsval rval, fval; - jsval *argv = NULL; unsigned argc=0; - - JS_GetProperty(cx, jsObj, "draw", &fval); - JS_CallFunctionValue(cx, jsObj, fval, argc, argv, &rval); + JS::RootedValue rval(cx); + JS::RootedValue fval(cx); + jsval *argv = NULL; unsigned argc=0; + + JS_GetProperty(cx, jsObj, "draw", &fval); + JS_CallFunctionValue(cx, jsObj, fval, argc, argv, rval.address()); } } } diff --git a/cocos/scripting/javascript/bindings/jsb_helper.h b/cocos/scripting/javascript/bindings/jsb_helper.h index 4ffa7c3d4c..664d7f4f28 100644 --- a/cocos/scripting/javascript/bindings/jsb_helper.h +++ b/cocos/scripting/javascript/bindings/jsb_helper.h @@ -53,10 +53,10 @@ out = OBJECT_TO_JSVAL(obj); \ JS_FN(#name, klass##_func_##name, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT) #define JS_BINDED_PROP_GET(klass, propName) \ -JSBool _js_get_##propName(JSContext *cx, JSHandleId id, JSMutableHandleValue vp) +JSBool _js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) #define JS_BINDED_PROP_GET_IMPL(klass, propName) \ -static JSBool _js_get_##klass##_##propName(JSContext *cx, JSHandleObject obj, JSHandleId id, JSMutableHandleValue vp) { \ +static JSBool _js_get_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) { \ klass* cobj = (klass*)JS_GetPrivate(obj); \ if (cobj) { \ return cobj->_js_get_##propName(cx, id, vp); \ @@ -64,13 +64,13 @@ return cobj->_js_get_##propName(cx, id, vp); \ JS_ReportError(cx, "Invalid getter call for property %s", #propName); \ return JS_FALSE; \ } \ -JSBool klass::_js_get_##propName(JSContext *cx, JSHandleId id, JSMutableHandleValue vp) +JSBool klass::_js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) #define JS_BINDED_PROP_SET(klass, propName) \ -JSBool _js_set_##propName(JSContext *cx, JSHandleId id, JSBool strict, JSMutableHandleValue vp) +JSBool _js_set_##propName(JSContext *cx, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) #define JS_BINDED_PROP_SET_IMPL(klass, propName) \ -static JSBool _js_set_##klass##_##propName(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp) { \ +static JSBool _js_set_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) { \ klass* cobj = (klass*)JS_GetPrivate(obj); \ if (cobj) { \ return cobj->_js_set_##propName(cx, id, strict, vp); \ @@ -78,7 +78,7 @@ return cobj->_js_set_##propName(cx, id, strict, vp); \ JS_ReportError(cx, "Invalid setter call for property %s", #propName); \ return JS_FALSE; \ } \ -JSBool klass::_js_set_##propName(JSContext *cx, JSHandleId id, JSBool strict, JSMutableHandleValue vp) +JSBool klass::_js_set_##propName(JSContext *cx, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) #define JS_BINDED_PROP_ACCESSOR(klass, propName) \ JS_BINDED_PROP_GET(klass, propName); \ diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp index 434737f24b..ad3fee9a24 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp @@ -39,16 +39,18 @@ void JSB_register_opengl(JSContext *_cx, JSObject *object) // gl // JSObject *opengl = JS_NewObject(_cx, NULL, NULL, NULL); - jsval openglVal = OBJECT_TO_JSVAL(opengl); - JS_SetProperty(_cx, object, "gl", &openglVal); + + JS::RootedValue openglVal(_cx); + openglVal = OBJECT_TO_JSVAL(opengl); + JS_SetProperty(_cx, object, "gl", openglVal); - jsval nsval; + JS::RootedValue nsval(_cx); JSObject *ccns; JS_GetProperty(_cx, object, "cc", &nsval); if (nsval == JSVAL_VOID) { ccns = JS_NewObject(_cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ccns); - JS_SetProperty(_cx, object, "cc", &nsval); + JS_SetProperty(_cx, object, "cc", nsval); } else { JS_ValueToObject(_cx, nsval, &ccns); } diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp index bf55e188f0..785b869e39 100644 --- a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_registration.cpp @@ -37,14 +37,16 @@ void jsb_register_system( JSContext *_cx, JSObject *object) // sys // JSObject *sys = JS_NewObject(_cx, NULL, NULL, NULL); - jsval systemVal = OBJECT_TO_JSVAL(sys); - JS_SetProperty(_cx, object, "sys", &systemVal); + JS::RootedValue systemVal(_cx); + systemVal = OBJECT_TO_JSVAL(sys); + JS_SetProperty(_cx, object, "sys", systemVal); // sys.localStorage JSObject *ls = JS_NewObject(_cx, NULL, NULL, NULL); - jsval lsVal = OBJECT_TO_JSVAL(ls); - JS_SetProperty(_cx, sys, "localStorage", &lsVal); + JS::RootedValue lsVal(_cx); + lsVal = OBJECT_TO_JSVAL(ls); + JS_SetProperty(_cx, sys, "localStorage", lsVal); // sys.localStorage functions JSObject *system = ls; diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index cc7b72c586..1879b5417d 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -327,8 +327,9 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) if (_onreadystateCallback) { JSString *tmpstr = JS_NewStringCopyZ(cx, "1"); - jsval tmpval = STRING_TO_JSVAL(tmpstr); - JS_SetProperty(cx, _onreadystateCallback, "readyState", &tmpval); + JS::RootedValue tmpval(cx); + tmpval = STRING_TO_JSVAL(tmpstr); + JS_SetProperty(cx, _onreadystateCallback, "readyState", tmpval); jsval out = OBJECT_TO_JSVAL(_onreadystateCallback); vp.set(out); @@ -563,7 +564,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) if (_responseType == ResponseType::JSON) { - jsval outVal; + JS::RootedValue outVal(cx); jsval strVal = std_string_to_jsval(cx, _data.str()); if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) diff --git a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp index b5083ad268..8497cd35e3 100644 --- a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp +++ b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp @@ -69,8 +69,9 @@ public: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "open"); - JS_SetProperty(cx, jsobj, "type", &vp); + JS::RootedValue vp(cx); + vp = c_string_to_jsval(cx, "open"); + JS_SetProperty(cx, jsobj, "type", vp); jsval args = OBJECT_TO_JSVAL(jsobj); @@ -84,8 +85,9 @@ public: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "message"); - JS_SetProperty(cx, jsobj, "type", &vp); + JS::RootedValue vp(cx); + vp = c_string_to_jsval(cx, "message"); + JS_SetProperty(cx, jsobj, "type", vp); jsval args = OBJECT_TO_JSVAL(jsobj); @@ -94,13 +96,15 @@ public: JSObject* buffer = JS_NewArrayBuffer(cx, data.len); uint8_t* bufdata = JS_GetArrayBufferData(buffer); memcpy((void*)bufdata, (void*)data.bytes, data.len); - jsval dataVal = OBJECT_TO_JSVAL(buffer); - JS_SetProperty(cx, jsobj, "data", &dataVal); + JS::RootedValue dataVal(cx); + dataVal = OBJECT_TO_JSVAL(buffer); + JS_SetProperty(cx, jsobj, "data", dataVal); } else {// data is string - jsval dataVal = c_string_to_jsval(cx, data.bytes); - JS_SetProperty(cx, jsobj, "data", &dataVal); + JS::RootedValue dataVal(cx); + dataVal = c_string_to_jsval(cx, data.bytes); + JS_SetProperty(cx, jsobj, "data", dataVal); } ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onmessage", 1, &args); @@ -113,8 +117,9 @@ public: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "close"); - JS_SetProperty(cx, jsobj, "type", &vp); + JS::RootedValue vp(cx); + vp = c_string_to_jsval(cx, "close"); + JS_SetProperty(cx, jsobj, "type", vp); jsval args = OBJECT_TO_JSVAL(jsobj); ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(_JSDelegate), "onclose", 1, &args); @@ -132,8 +137,9 @@ public: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); - jsval vp = c_string_to_jsval(cx, "error"); - JS_SetProperty(cx, jsobj, "type", &vp); + JS::RootedValue vp(cx); + vp = c_string_to_jsval(cx, "error"); + JS_SetProperty(cx, jsobj, "type", vp); jsval args = OBJECT_TO_JSVAL(jsobj); @@ -308,7 +314,7 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, return JS_FALSE; } -static JSBool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JSHandleObject obj, JSHandleId id, JSMutableHandleValue vp) +static JSBool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) { JSObject* jsobj = obj.get(); js_proxy_t *proxy = jsb_get_js_proxy(jsobj); From d1b88b0a7877c0349689d0b024b961267499ab92 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 30 Oct 2013 22:08:28 +0800 Subject: [PATCH 292/557] [sp v25] Updating auto-generated and bindings-generated submodules. --- cocos/scripting/auto-generated | 2 +- tools/bindings-generator | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 4fd4e14912..c1da46eabb 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 4fd4e14912165a2c8a5a6faacda2626035af6f36 +Subproject commit c1da46eabb46727a66daa4d64d9841b09fa6d63c diff --git a/tools/bindings-generator b/tools/bindings-generator index 0c5ff684fb..b6f97d9fc2 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 0c5ff684fb8176f4da5313dbb9d35e112f99cd39 +Subproject commit b6f97d9fc2d3450426423583c7a6aaf4a366a99d From a81998ccf6fed3fc36b3d93d259c49e778ee5aa5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 10:20:45 +0800 Subject: [PATCH 293/557] [sp v25] Debugger script, loading file is ok. --- .../javascript/script/debugger/actors/root.js | 29 +- .../script/debugger/actors/script.js | 2948 ----------------- .../debugger/actors/script.js.REMOVED.git-id | 1 + .../javascript/script/debugger/main.js | 213 +- .../javascript/script/debugger/transport.js | 68 +- 5 files changed, 249 insertions(+), 3010 deletions(-) delete mode 100644 cocos/scripting/javascript/script/debugger/actors/script.js create mode 100644 cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id diff --git a/cocos/scripting/javascript/script/debugger/actors/root.js b/cocos/scripting/javascript/script/debugger/actors/root.js index aa0d85342b..93fc857c0b 100644 --- a/cocos/scripting/javascript/script/debugger/actors/root.js +++ b/cocos/scripting/javascript/script/debugger/actors/root.js @@ -164,7 +164,7 @@ RootActor.prototype = { */ sayHello: function() { return { - from: "root", + from: this.actorID, applicationType: this.applicationType, /* This is not in the spec, but it's used by tests. */ testConnectionPrefix: this.conn.prefix, @@ -174,6 +174,16 @@ RootActor.prototype = { }; }, + /** + * This is true for the root actor only, used by some child actors + */ + get isRootActor() true, + + /** + * The (chrome) window, for use by child actors + */ + get window() Services.wm.getMostRecentWindow(DebuggerServer.chromeWindowType), + /** * Disconnects the actor from the browser window. */ @@ -195,10 +205,9 @@ RootActor.prototype = { * the next listTabs request. */ onListTabs: function() { - let tabList = this._parameters.tabList; if (!tabList) { - return { from: "root", error: "noTabs", + return { from: this.actorID, error: "noTabs", message: "This root actor has no browser tabs." }; } @@ -235,9 +244,9 @@ RootActor.prototype = { this.conn.addActorPool(this._tabActorPool); let reply = { - "from": "root", + "from": this.actorID, "selected": selected || 0, - "tabs": [actor.grip() for (actor of tabActorList)] + "tabs": [actor.grip() for (actor of tabActorList)], }; /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ @@ -254,13 +263,19 @@ RootActor.prototype = { }, onTabListChanged: function () { - this.conn.send({ from:"root", type:"tabListChanged" }); + this.conn.send({ from: this.actorID, type:"tabListChanged" }); /* It's a one-shot notification; no need to watch any more. */ this._parameters.tabList.onListChanged = null; }, /* This is not in the spec, but it's used by tests. */ - onEcho: (aRequest) => aRequest, + onEcho: function (aRequest) { + /* + * Request packets are frozen. Copy aRequest, so that + * DebuggerServerConnection.onPacket can attach a 'from' property. + */ + return JSON.parse(JSON.stringify(aRequest)); + }, /* Support for DebuggerServer.addGlobalActor. */ _createExtraActors: CommonCreateExtraActors, diff --git a/cocos/scripting/javascript/script/debugger/actors/script.js b/cocos/scripting/javascript/script/debugger/actors/script.js deleted file mode 100644 index 7ddade2b54..0000000000 --- a/cocos/scripting/javascript/script/debugger/actors/script.js +++ /dev/null @@ -1,2948 +0,0 @@ -/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -/** - * JSD2 actors. - */ -/** - * Creates a ThreadActor. - * - * ThreadActors manage a JSInspector object and manage execution/inspection - * of debuggees. - * - * @param aHooks object - * An object with preNest and postNest methods for calling when entering - * and exiting a nested event loop, addToParentPool and - * removeFromParentPool methods for handling the lifetime of actors that - * will outlive the thread, like breakpoints. - * @param aGlobal object [optional] - * An optional (for content debugging only) reference to the content - * window. - */ -function ThreadActor(aHooks, aGlobal) -{ - this._state = "detached"; - this._frameActors = []; - this._environmentActors = []; - this._hooks = aHooks; - this.global = aGlobal; - - this.findGlobals = this.globalManager.findGlobals.bind(this); - this.onNewGlobal = this.globalManager.onNewGlobal.bind(this); - this.onNewSource = this.onNewSource.bind(this); - - this._options = { - useSourceMaps: false - }; -} - -/** - * The breakpoint store must be shared across instances of ThreadActor so that - * page reloads don't blow away all of our breakpoints. - */ -ThreadActor._breakpointStore = {}; - -ThreadActor.prototype = { - actorPrefix: "context", - - get state() { return this._state; }, - get attached() this.state == "attached" || - this.state == "running" || - this.state == "paused", - - get _breakpointStore() { return ThreadActor._breakpointStore; }, - - get threadLifetimePool() { - if (!this._threadLifetimePool) { - this._threadLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._threadLifetimePool); - this._threadLifetimePool.objectActors = new WeakMap(); - } - return this._threadLifetimePool; - }, - - get sources() { - if (!this._sources) { - this._sources = new ThreadSources(this, this._options.useSourceMaps, - this._allowSource, this.onNewSource); - } - return this._sources; - }, - - clearDebuggees: function TA_clearDebuggees() { - if (this.dbg) { - this.dbg.removeAllDebuggees(); - } - this.conn.removeActorPool(this._threadLifetimePool || undefined); - this._threadLifetimePool = null; - this._sources = null; - }, - - /** - * Add a debuggee global to the Debugger object. - */ - addDebuggee: function TA_addDebuggee(aGlobal) { - try { - this.dbg.addDebuggee(aGlobal); - } catch (e) { - // Ignore attempts to add the debugger's compartment as a debuggee. - dumpn("Ignoring request to add the debugger's compartment as a debuggee"); - } - }, - - /** - * Initialize the Debugger. - */ - _initDebugger: function TA__initDebugger() { - this.dbg = new Debugger(); - this.dbg.uncaughtExceptionHook = this.uncaughtExceptionHook.bind(this); - this.dbg.onDebuggerStatement = this.onDebuggerStatement.bind(this); - this.dbg.onNewScript = this.onNewScript.bind(this); - this.dbg.onNewGlobalObject = this.globalManager.onNewGlobal.bind(this); - // Keep the debugger disabled until a client attaches. - this.dbg.enabled = this._state != "detached"; - }, - - /** - * Remove a debuggee global from the JSInspector. - */ - removeDebugee: function TA_removeDebuggee(aGlobal) { - try { - this.dbg.removeDebuggee(aGlobal); - } catch(ex) { - // XXX: This debuggee has code currently executing on the stack, - // we need to save this for later. - } - }, - - /** - * Add the provided window and all windows in its frame tree as debuggees. - */ - _addDebuggees: function TA__addDebuggees(aWindow) { - this.addDebuggee(aWindow); - let frames = aWindow.frames; - if (frames) { - for (let i = 0; i < frames.length; i++) { - this._addDebuggees(frames[i]); - } - } - }, - - /** - * An object that will be used by ThreadActors to tailor their behavior - * depending on the debugging context being required (chrome or content). - */ - globalManager: { - findGlobals: function TA_findGlobals() { - this._addDebuggees(this.global); - }, - - /** - * A function that the engine calls when a new global object has been - * created. - * - * @param aGlobal Debugger.Object - * The new global object that was created. - */ - onNewGlobal: function TA_onNewGlobal(aGlobal) { - // Content debugging only cares about new globals in the contant window, - // like iframe children. - if (aGlobal.hostAnnotations && - aGlobal.hostAnnotations.type == "document" && - aGlobal.hostAnnotations.element === this.global) { - this.addDebuggee(aGlobal); - // Notify the client. - this.conn.send({ - from: this.actorID, - type: "newGlobal", - // TODO: after bug 801084 lands see if we need to JSONify this. - hostAnnotations: aGlobal.hostAnnotations - }); - } - } - }, - - disconnect: function TA_disconnect() { - dumpn("in ThreadActor.prototype.disconnect"); - if (this._state == "paused") { - this.onResume(); - } - - this._state = "exited"; - - this.clearDebuggees(); - - if (!this.dbg) { - return; - } - this.dbg.enabled = false; - this.dbg = null; - }, - - /** - * Disconnect the debugger and put the actor in the exited state. - */ - exit: function TA_exit() { - this.disconnect(); - }, - - // Request handlers - onAttach: function TA_onAttach(aRequest) { - if (this.state === "exited") { - return { type: "exited" }; - } - - if (this.state !== "detached") { - return { error: "wrongState" }; - } - - this._state = "attached"; - - update(this._options, aRequest.options || {}); - - if (!this.dbg) { - this._initDebugger(); - } - this.findGlobals(); - this.dbg.enabled = true; - try { - // Put ourselves in the paused state. - let packet = this._paused(); - if (!packet) { - return { error: "notAttached" }; - } - packet.why = { type: "attached" }; - - this._restoreBreakpoints(); - - // Send the response to the attach request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._nest(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notAttached", message: e.toString() }; - } - }, - - onDetach: function TA_onDetach(aRequest) { - this.disconnect(); - dumpn("ThreadActor.prototype.onDetach: returning 'detached' packet"); - return { - type: "detached" - }; - }, - - onReconfigure: function TA_onReconfigure(aRequest) { - if (this.state == "exited") { - return { error: "wrongState" }; - } - - update(this._options, aRequest.options || {}); - // Clear existing sources, so they can be recreated on next access. - this._sources = null; - - return {}; - }, - - /** - * Pause the debuggee, by entering a nested event loop, and return a 'paused' - * packet to the client. - * - * @param Debugger.Frame aFrame - * The newest debuggee frame in the stack. - * @param object aReason - * An object with a 'type' property containing the reason for the pause. - * @param function onPacket - * Hook to modify the packet before it is sent. Feel free to return a - * promise. - */ - _pauseAndRespond: function TA__pauseAndRespond(aFrame, aReason, - onPacket=function (k) k) { - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - packet.why = aReason; - resolve(onPacket(packet)).then(this.conn.send.bind(this.conn)); - return this._nest(); - } catch(e) { - let msg = "Got an exception during TA__pauseAndRespond: " + e + - ": " + e.stack; - // Cu.reportError(msg); - dumpn(msg); - return undefined; - } - }, - - /** - * Handle a protocol request to resume execution of the debuggee. - */ - onResume: function TA_onResume(aRequest) { - if (this._state !== "paused") { - return { - error: "wrongState", - message: "Can't resume when debuggee isn't paused. Current state is '" - + this._state + "'" - }; - } - - // In case of multiple nested event loops (due to multiple debuggers open in - // different tabs or multiple debugger clients connected to the same tab) - // only allow resumption in a LIFO order. - if (DebuggerServer.xpcInspector.eventLoopNestLevel() > 1) { - log("DebuggerServer.xpcInspector.eventLoopNestLevel: "+DebuggerServer.xpcInspector.eventLoopNestLevel()); - // let lastNestRequestor = DebuggerServer.xpcInspector.lastNestRequestor; - // if (lastNestRequestor.connection != this.conn) { - // return { error: "wrongOrder", - // message: "trying to resume in the wrong order.", - // lastPausedUrl: lastNestRequestor.url }; - // } - } - - if (aRequest && aRequest.forceCompletion) { - // TODO: remove this when Debugger.Frame.prototype.pop is implemented in - // bug 736733. - if (typeof this.frame.pop != "function") { - return { error: "notImplemented", - message: "forced completion is not yet implemented." }; - } - - this.dbg.getNewestFrame().pop(aRequest.completionValue); - let packet = this._resumed(); - DebuggerServer.xpcInspector.exitNestedEventLoop(); - return { type: "resumeLimit", frameFinished: aRequest.forceCompletion }; - } - - if (aRequest && aRequest.resumeLimit) { - log("resumeLimit..."); - // Bind these methods because some of the hooks are called with 'this' - // set to the current frame. - let pauseAndRespond = (aFrame, onPacket=function (k) k) => { - this._pauseAndRespond(aFrame, { type: "resumeLimit" }, onPacket); - }; - let createValueGrip = this.createValueGrip.bind(this); - - let startFrame = this.youngestFrame; - let startLine; - if (this.youngestFrame.script) { - let offset = this.youngestFrame.offset; - startLine = this.youngestFrame.script.getOffsetLine(offset); - } - - // Define the JS hook functions for stepping. - - let onEnterFrame = aFrame => { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - return pauseAndRespond(aFrame); - }; - - let thread = this; - - let onPop = function TA_onPop(aCompletion) { - // onPop is called with 'this' set to the current frame. - if (thread.sources.isBlackBoxed(this.script.url)) { - return undefined; - } - - // Note that we're popping this frame; we need to watch for - // subsequent step events on its caller. - this.reportedPop = true; - - return pauseAndRespond(this, (aPacket) => { - aPacket.why.frameFinished = {}; - if (!aCompletion) { - aPacket.why.frameFinished.terminated = true; - } else if (aCompletion.hasOwnProperty("return")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.return); - } else if (aCompletion.hasOwnProperty("yield")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.yield); - } else { - aPacket.why.frameFinished.throw = createValueGrip(aCompletion.throw); - } - return aPacket; - }); - }; - - let onStep = function TA_onStep() { - // onStep is called with 'this' set to the current frame. - - if (thread.sources.isBlackBoxed(this.script.url)) { - return undefined; - } - - // If we've changed frame or line, then report that. - if (this !== startFrame || - (this.script && - this.script.getOffsetLine(this.offset) != startLine)) { - return pauseAndRespond(this); - } - - // Otherwise, let execution continue. - return undefined; - }; - - let steppingType = aRequest.resumeLimit.type; - if (["step", "next", "finish"].indexOf(steppingType) == -1) { - return { error: "badParameterType", - message: "Unknown resumeLimit type" }; - } - // Make sure there is still a frame on the stack if we are to continue - // stepping. - let stepFrame = this._getNextStepFrame(startFrame); - if (stepFrame) { - switch (steppingType) { - case "step": - log("--> step..."); - this.dbg.onEnterFrame = onEnterFrame; - // Fall through. - case "next": - log("--> next..."); - stepFrame.onStep = onStep; - stepFrame.onPop = onPop; - break; - case "finish": - log("--> finish..."); - stepFrame.onPop = onPop; - } - } - - } - - if (aRequest && aRequest.pauseOnExceptions) { - this.dbg.onExceptionUnwind = this.onExceptionUnwind.bind(this); - } - let packet = this._resumed(); - DebuggerServer.xpcInspector.exitNestedEventLoop(); - return packet; - }, - - /** - * Helper method that returns the next frame when stepping. - */ - _getNextStepFrame: function TA__getNextStepFrame(aFrame) { - let stepFrame = aFrame.reportedPop ? aFrame.older : aFrame; - if (!stepFrame || !stepFrame.script) { - stepFrame = null; - } - return stepFrame; - }, - - onClientEvaluate: function TA_onClientEvaluate(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Debuggee must be paused to evaluate code." }; - }; - - let frame = this._requestFrame(aRequest.frame); - if (!frame) { - return { error: "unknownFrame", - message: "Evaluation frame not found" }; - } - - if (!frame.environment) { - return { error: "notDebuggee", - message: "cannot access the environment of this frame." }; - }; - - // We'll clobber the youngest frame if the eval causes a pause, so - // save our frame now to be restored after eval returns. - // XXX: or we could just start using dbg.getNewestFrame() now that it - // works as expected. - let youngest = this.youngestFrame; - - // Put ourselves back in the running state and inform the client. - let resumedPacket = this._resumed(); - this.conn.send(resumedPacket); - - // Run the expression. - // XXX: test syntax errors - let completion = frame.eval(aRequest.expression); - - // Put ourselves back in the pause state. - let packet = this._paused(youngest); - packet.why = { type: "clientEvaluated", - frameFinished: this.createProtocolCompletionValue(completion) }; - - // Return back to our previous pause's event loop. - return packet; - }, - - onFrames: function TA_onFrames(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Stack frames are only available while the debuggee is paused."}; - } - - let start = aRequest.start ? aRequest.start : 0; - let count = aRequest.count; - - // Find the starting frame... - let frame = this.youngestFrame; - let i = 0; - while (frame && (i < start)) { - frame = frame.older; - i++; - } - - // Return request.count frames, or all remaining - // frames if count is not defined. - let frames = []; - let promises = []; - for (; frame && (!count || i < (start + count)); i++, frame=frame.older) { - let form = this._createFrameActor(frame).form(); - form.depth = i; - frames.push(form); - - let promise = this.sources.getOriginalLocation(form.where.url, - form.where.line) - .then(function (aOrigLocation) { - form.where = aOrigLocation; - }); - promises.push(promise); - } - - return all(promises).then(function () { - return { frames: frames }; - }); - }, - - onReleaseMany: function TA_onReleaseMany(aRequest) { - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - let res; - for each (let actorID in aRequest.actors) { - let actor = this.threadLifetimePool.get(actorID); - if (!actor) { - if (!res) { - res = { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - continue; - } - actor.onRelease(); - } - return res ? res : {}; - }, - - /** - * Handle a protocol request to set a breakpoint. - */ - onSetBreakpoint: function TA_onSetBreakpoint(aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Breakpoints can only be set while the debuggee is paused."}; - } - - // XXX: `originalColumn` is never used. See bug 827639. - let { url: originalSource, - line: originalLine, - column: originalColumn } = aRequest.location; - - let locationPromise = this.sources.getGeneratedLocation(originalSource, - originalLine) - return locationPromise.then((aLocation) => { - let line = aLocation.line; - if (this.dbg.findScripts({ url: aLocation.url }).length == 0 || - line < 0 || - line == null) { - return { error: "noScript" }; - } - - // Add the breakpoint to the store for later reuse, in case it belongs to a - // script that hasn't appeared yet. - if (!this._breakpointStore[aLocation.url]) { - this._breakpointStore[aLocation.url] = []; - } - let scriptBreakpoints = this._breakpointStore[aLocation.url]; - scriptBreakpoints[line] = { - url: aLocation.url, - line: line, - column: aLocation.column - }; - - let response = this._setBreakpoint(aLocation); - // If the original location of our generated location is different from - // the original location we attempted to set the breakpoint on, we will - // need to know so that we can set actualLocation on the response. - let originalLocation = this.sources.getOriginalLocation(aLocation.url, - aLocation.line); - - return all([response, originalLocation]) - .then(([aResponse, {url, line}]) => { - if (aResponse.actualLocation) { - let actualOrigLocation = this.sources.getOriginalLocation( - aResponse.actualLocation.url, aResponse.actualLocation.line); - return actualOrigLocation.then(function ({ url, line }) { - if (url !== originalSource || line !== originalLine) { - aResponse.actualLocation = { url: url, line: line }; - } - return aResponse; - }); - } - - if (url !== originalSource || line !== originalLine) { - aResponse.actualLocation = { url: url, line: line }; - } - - return aResponse; - }); - }); - }, - - /** - * Set a breakpoint using the jsdbg2 API. If the line on which the breakpoint - * is being set contains no code, then the breakpoint will slide down to the - * next line that has runnable code. In this case the server breakpoint cache - * will be updated, so callers that iterate over the breakpoint cache should - * take that into account. - * - * @param object aLocation - * The location of the breakpoint as specified in the protocol. - */ - _setBreakpoint: function TA__setBreakpoint(aLocation) { - let breakpoints = this._breakpointStore[aLocation.url]; - - // Get or create the breakpoint actor for the given location - let actor; - if (breakpoints[aLocation.line].actor) { - actor = breakpoints[aLocation.line].actor; - } else { - actor = breakpoints[aLocation.line].actor = new BreakpointActor(this, { - url: aLocation.url, - line: aLocation.line - }); - this._hooks.addToParentPool(actor); - } - - // Find all scripts matching the given location - let scripts = this.dbg.findScripts(aLocation); - if (scripts.length == 0) { - return { - error: "noScript", - actor: actor.actorID - }; - } - - /** - * For each script, if the given line has at least one entry point, set - * breakpoint on the bytecode offet for each of them. - */ - let found = false; - for (let script of scripts) { - let offsets = script.getLineOffsets(aLocation.line); - if (offsets.length > 0) { - for (let offset of offsets) { - script.setBreakpoint(offset, actor); - } - actor.addScript(script, this); - found = true; - } - } - if (found) { - return { - actor: actor.actorID - }; - } - - /** - * If we get here, no breakpoint was set. This is because the given line - * has no entry points, for example because it is empty. As a fallback - * strategy, we try to set the breakpoint on the smallest line greater - * than or equal to the given line that as at least one entry point. - */ - - // Find all innermost scripts matching the given location - let scripts = this.dbg.findScripts({ - url: aLocation.url, - line: aLocation.line, - innermost: true - }); - - /** - * For each innermost script, look for the smallest line greater than or - * equal to the given line that has one or more entry points. If found, set - * a breakpoint on the bytecode offset for each of its entry points. - */ - let actualLocation; - let found = false; - for (let script of scripts) { - let offsets = script.getAllOffsets(); - for (let line = aLocation.line; line < offsets.length; ++line) { - if (offsets[line]) { - for (let offset of offsets[line]) { - script.setBreakpoint(offset, actor); - } - actor.addScript(script, this); - if (!actualLocation) { - actualLocation = { - url: aLocation.url, - line: line, - column: 0 - }; - } - found = true; - break; - } - } - } - if (found) { - if (breakpoints[actualLocation.line] && - breakpoints[actualLocation.line].actor) { - /** - * We already have a breakpoint actor for the actual location, so - * actor we created earlier is now redundant. Delete it, update the - * breakpoint store, and return the actor for the actual location. - */ - actor.onDelete(); - delete breakpoints[aLocation.line]; - return { - actor: breakpoints[actualLocation.line].actor.actorID, - actualLocation: actualLocation - }; - } else { - /** - * We don't have a breakpoint actor for the actual location yet. - * Instead or creating a new actor, reuse the actor we created earlier, - * and update the breakpoint store. - */ - actor.location = actualLocation; - breakpoints[actualLocation.line] = breakpoints[aLocation.line]; - delete breakpoints[aLocation.line]; - // WARNING: This overwrites aLocation.line - breakpoints[actualLocation.line].line = actualLocation.line; - return { - actor: actor.actorID, - actualLocation: actualLocation - }; - } - } - - /** - * If we get here, no line matching the given line was found, so just - * epically. - */ - return { - error: "noCodeAtLineColumn", - actor: actor.actorID - }; - }, - - /** - * Get the script and source lists from the debugger. - * - * TODO bug 637572: we should be dealing with sources directly, not inferring - * them through scripts. - */ - _discoverSources: function TA__discoverSources() { - // Only get one script per url. - let scriptsByUrl = {}; - for (let s of this.dbg.findScripts()) { - scriptsByUrl[s.url] = s; - } - - return all([this.sources.sourcesForScript(scriptsByUrl[s]) - for (s of Object.keys(scriptsByUrl))]); - }, - - onSources: function TA_onSources(aRequest) { - return this._discoverSources().then(() => { - return { - sources: [s.form() for (s of this.sources.iter())] - }; - }); - }, - - /** - * Disassociate all breakpoint actors from their scripts and clear the - * breakpoint handlers. This method can be used when the thread actor intends - * to keep the breakpoint store, but needs to clear any actual breakpoints, - * e.g. due to a page navigation. This way the breakpoint actors' script - * caches won't hold on to the Debugger.Script objects leaking memory. - */ - disableAllBreakpoints: function () { - for (let url in this._breakpointStore) { - for (let line in this._breakpointStore[url]) { - let bp = this._breakpointStore[url][line]; - bp.actor.removeScripts(); - } - } - }, - - /** - * Handle a protocol request to pause the debuggee. - */ - onInterrupt: function TA_onInterrupt(aRequest) { - if (this.state == "exited") { - return { type: "exited" }; - } else if (this.state == "paused") { - // TODO: return the actual reason for the existing pause. - return { type: "paused", why: { type: "alreadyPaused" } }; - } else if (this.state != "running") { - return { error: "wrongState", - message: "Received interrupt request in " + this.state + - " state." }; - } - - try { - // Put ourselves in the paused state. - let packet = this._paused(); - if (!packet) { - return { error: "notInterrupted" }; - } - packet.why = { type: "interrupted" }; - - // Send the response to the interrupt request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._nest(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notInterrupted", message: e.toString() }; - } - }, - - /** - * Return the Debug.Frame for a frame mentioned by the protocol. - */ - _requestFrame: function TA_requestFrame(aFrameID) { - if (!aFrameID) { - return this.youngestFrame; - } - - if (this._framePool.has(aFrameID)) { - return this._framePool.get(aFrameID).frame; - } - - return undefined; - }, - - _paused: function TA_paused(aFrame) { - // We don't handle nested pauses correctly. Don't try - if we're - // paused, just continue running whatever code triggered the pause. - // We don't want to actually have nested pauses (although we - // have nested event loops). If code runs in the debuggee during - // a pause, it should cause the actor to resume (dropping - // pause-lifetime actors etc) and then repause when complete. - - if (this.state === "paused") { - return undefined; - } - - // Clear stepping hooks. - this.dbg.onEnterFrame = undefined; - this.dbg.onExceptionUnwind = undefined; - if (aFrame) { - aFrame.onStep = undefined; - aFrame.onPop = undefined; - } - - this._state = "paused"; - - // Save the pause frame (if any) as the youngest frame for - // stack viewing. - this.youngestFrame = aFrame; - - // Create the actor pool that will hold the pause actor and its - // children. - dbg_assert(!this._pausePool); - this._pausePool = new ActorPool(this.conn); - this.conn.addActorPool(this._pausePool); - - // Give children of the pause pool a quick link back to the - // thread... - this._pausePool.threadActor = this; - - // Create the pause actor itself... - dbg_assert(!this._pauseActor); - this._pauseActor = new PauseActor(this._pausePool); - this._pausePool.addActor(this._pauseActor); - - // Update the list of frames. - let poppedFrames = this._updateFrames(); - - // Send off the paused packet and spin an event loop. - let packet = { from: this.actorID, - type: "paused", - actor: this._pauseActor.actorID }; - if (aFrame) { - packet.frame = this._createFrameActor(aFrame).form(); - } - - if (poppedFrames) { - packet.poppedFrames = poppedFrames; - } - - return packet; - }, - - _nest: function TA_nest() { - if (this._hooks.preNest) { - var nestData = this._hooks.preNest(); - } - - let requestor = Object.create(null); - requestor.url = this._hooks.url; - requestor.connection = this.conn; - DebuggerServer.xpcInspector.enterNestedEventLoop(requestor); - - dbg_assert(this.state === "running"); - - if (this._hooks.postNest) { - this._hooks.postNest(nestData) - } - - // "continue" resumption value. - return undefined; - }, - - _resumed: function TA_resumed() { - this._state = "running"; - - // Drop the actors in the pause actor pool. - this.conn.removeActorPool(this._pausePool); - - this._pausePool = null; - this._pauseActor = null; - this.youngestFrame = null; - - return { from: this.actorID, type: "resumed" }; - }, - - /** - * Expire frame actors for frames that have been popped. - * - * @returns A list of actor IDs whose frames have been popped. - */ - _updateFrames: function TA_updateFrames() { - let popped = []; - - // Create the actor pool that will hold the still-living frames. - let framePool = new ActorPool(this.conn); - let frameList = []; - - for each (let frameActor in this._frameActors) { - if (frameActor.frame.live) { - framePool.addActor(frameActor); - frameList.push(frameActor); - } else { - popped.push(frameActor.actorID); - } - } - - // Remove the old frame actor pool, this will expire - // any actors that weren't added to the new pool. - if (this._framePool) { - this.conn.removeActorPool(this._framePool); - } - - this._frameActors = frameList; - this._framePool = framePool; - this.conn.addActorPool(framePool); - - return popped; - }, - - _createFrameActor: function TA_createFrameActor(aFrame) { - if (aFrame.actor) { - return aFrame.actor; - } - - let actor = new FrameActor(aFrame, this); - this._frameActors.push(actor); - this._framePool.addActor(actor); - aFrame.actor = actor; - - return actor; - }, - - /** - * Create and return an environment actor that corresponds to the provided - * Debugger.Environment. - * @param Debugger.Environment aEnvironment - * The lexical environment we want to extract. - * @param object aPool - * The pool where the newly-created actor will be placed. - * @return The EnvironmentActor for aEnvironment or undefined for host - * functions or functions scoped to a non-debuggee global. - */ - createEnvironmentActor: - function TA_createEnvironmentActor(aEnvironment, aPool) { - if (!aEnvironment) { - return undefined; - } - - if (aEnvironment.actor) { - return aEnvironment.actor; - } - - let actor = new EnvironmentActor(aEnvironment, this); - this._environmentActors.push(actor); - aPool.addActor(actor); - aEnvironment.actor = actor; - - return actor; - }, - - /** - * Create a grip for the given debuggee value. If the value is an - * object, will create an actor with the given lifetime. - */ - createValueGrip: function TA_createValueGrip(aValue, aPool=false) { - if (!aPool) { - aPool = this._pausePool; - } - let type = typeof(aValue); - - if (type === "string" && this._stringIsLong(aValue)) { - return this.longStringGrip(aValue, aPool); - } - - if (type === "boolean" || type === "string" || type === "number") { - return aValue; - } - - if (aValue === null) { - return { type: "null" }; - } - - if (aValue === undefined) { - return { type: "undefined" } - } - - if (typeof(aValue) === "object") { - return this.objectGrip(aValue, aPool); - } - - dbg_assert(false, "Failed to provide a grip for: " + aValue); - return null; - }, - - /** - * Return a protocol completion value representing the given - * Debugger-provided completion value. - */ - createProtocolCompletionValue: - function TA_createProtocolCompletionValue(aCompletion) { - let protoValue = {}; - if ("return" in aCompletion) { - protoValue.return = this.createValueGrip(aCompletion.return); - } else if ("yield" in aCompletion) { - protoValue.return = this.createValueGrip(aCompletion.yield); - } else if ("throw" in aCompletion) { - protoValue.throw = this.createValueGrip(aCompletion.throw); - } else { - protoValue.terminated = true; - } - return protoValue; - }, - - /** - * Create a grip for the given debuggee object. - * - * @param aValue Debugger.Object - * The debuggee object value. - * @param aPool ActorPool - * The actor pool where the new object actor will be added. - */ - objectGrip: function TA_objectGrip(aValue, aPool) { - if (!aPool.objectActors) { - aPool.objectActors = new WeakMap(); - } - - if (aPool.objectActors.has(aValue)) { - return aPool.objectActors.get(aValue).grip(); - } else if (this.threadLifetimePool.objectActors.has(aValue)) { - return this.threadLifetimePool.objectActors.get(aValue).grip(); - } - - let actor = new PauseScopedObjectActor(aValue, this); - aPool.addActor(actor); - aPool.objectActors.set(aValue, actor); - return actor.grip(); - }, - - /** - * Create a grip for the given debuggee object with a pause lifetime. - * - * @param aValue Debugger.Object - * The debuggee object value. - */ - pauseObjectGrip: function TA_pauseObjectGrip(aValue) { - if (!this._pausePool) { - throw "Object grip requested while not paused."; - } - - return this.objectGrip(aValue, this._pausePool); - }, - - /** - * Extend the lifetime of the provided object actor to thread lifetime. - * - * @param aActor object - * The object actor. - */ - threadObjectGrip: function TA_threadObjectGrip(aActor) { - // We want to reuse the existing actor ID, so we just remove it from the - // current pool's weak map and then let pool.addActor do the rest. - aActor.registeredPool.objectActors.delete(aActor.obj); - this.threadLifetimePool.addActor(aActor); - this.threadLifetimePool.objectActors.set(aActor.obj, aActor); - }, - - /** - * Handle a protocol request to promote multiple pause-lifetime grips to - * thread-lifetime grips. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrips: function OA_onThreadGrips(aRequest) { - if (this.state != "paused") { - return { error: "wrongState" }; - } - - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - for (let actorID of aRequest.actors) { - let actor = this._pausePool.get(actorID); - if (actor) { - this.threadObjectGrip(actor); - } - } - return {}; - }, - - /** - * Create a grip for the given string. - * - * @param aString String - * The string we are creating a grip for. - * @param aPool ActorPool - * The actor pool where the new actor will be added. - */ - longStringGrip: function TA_longStringGrip(aString, aPool) { - if (!aPool.longStringActors) { - aPool.longStringActors = {}; - } - - if (aPool.longStringActors.hasOwnProperty(aString)) { - return aPool.longStringActors[aString].grip(); - } - - let actor = new LongStringActor(aString, this); - aPool.addActor(actor); - aPool.longStringActors[aString] = actor; - return actor.grip(); - }, - - /** - * Create a long string grip that is scoped to a pause. - * - * @param aString String - * The string we are creating a grip for. - */ - pauseLongStringGrip: function TA_pauseLongStringGrip (aString) { - return this.longStringGrip(aString, this._pausePool); - }, - - /** - * Create a long string grip that is scoped to a thread. - * - * @param aString String - * The string we are creating a grip for. - */ - threadLongStringGrip: function TA_pauseLongStringGrip (aString) { - return this.longStringGrip(aString, this._threadLifetimePool); - }, - - /** - * Returns true if the string is long enough to use a LongStringActor instead - * of passing the value directly over the protocol. - * - * @param aString String - * The string we are checking the length of. - */ - _stringIsLong: function TA__stringIsLong(aString) { - return aString.length >= DebuggerServer.LONG_STRING_LENGTH; - }, - - // JS Debugger API hooks. - - /** - * A function that the engine calls when a call to a debug event hook, - * breakpoint handler, watchpoint handler, or similar function throws some - * exception. - * - * @param aException exception - * The exception that was thrown in the debugger code. - */ - uncaughtExceptionHook: function TA_uncaughtExceptionHook(aException) { - dumpn("Got an exception: " + aException.message + "\n" + aException.stack); - }, - - /** - * A function that the engine calls when a debugger statement has been - * executed in the specified frame. - * - * @param aFrame Debugger.Frame - * The stack frame that contained the debugger statement. - */ - onDebuggerStatement: function TA_onDebuggerStatement(aFrame) { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - return this._pauseAndRespond(aFrame, { type: "debuggerStatement" }); - }, - - /** - * A function that the engine calls when an exception has been thrown and has - * propagated to the specified frame. - * - * @param aFrame Debugger.Frame - * The youngest remaining stack frame. - * @param aValue object - * The exception that was thrown. - */ - onExceptionUnwind: function TA_onExceptionUnwind(aFrame, aValue) { - if (this.sources.isBlackBoxed(aFrame.script.url)) { - return undefined; - } - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - - packet.why = { type: "exception", - exception: this.createValueGrip(aValue) }; - this.conn.send(packet); - return this._nest(); - } catch(e) { - log("Got an exception during TA_onExceptionUnwind: " + e + - ": " + e.stack); - return undefined; - } - }, - - /** - * A function that the engine calls when a new script has been loaded into the - * scope of the specified debuggee global. - * - * @param aScript Debugger.Script - * The source script that has been loaded into a debuggee compartment. - * @param aGlobal Debugger.Object - * A Debugger.Object instance whose referent is the global object. - */ - onNewScript: function TA_onNewScript(aScript, aGlobal) { - this._addScript(aScript); - this.sources.sourcesForScript(aScript); - }, - - onNewSource: function TA_onNewSource(aSource) { - this.conn.send({ - from: this.actorID, - type: "newSource", - source: aSource.form() - }); - }, - - /** - * Check if scripts from the provided source URL are allowed to be stored in - * the cache. - * - * @param aSourceUrl String - * The url of the script's source that will be stored. - * @returns true, if the script can be added, false otherwise. - */ - _allowSource: function TA__allowSource(aSourceUrl) { - // Ignore anything we don't have a URL for (eval scripts, for example). - if (!aSourceUrl) - return false; - // Ignore XBL bindings for content debugging. - if (aSourceUrl.indexOf("chrome://") == 0) { - return false; - } - // Ignore about:* pages for content debugging. - if (aSourceUrl.indexOf("about:") == 0) { - return false; - } - return true; - }, - - /** - * Restore any pre-existing breakpoints to the scripts that we have access to. - */ - _restoreBreakpoints: function TA__restoreBreakpoints() { - for (let s of this.dbg.findScripts()) { - this._addScript(s); - } - }, - - /** - * Add the provided script to the server cache. - * - * @param aScript Debugger.Script - * The source script that will be stored. - * @returns true, if the script was added; false otherwise. - */ - _addScript: function TA__addScript(aScript) { - if (!this._allowSource(aScript.url)) { - return false; - } - - // Set any stored breakpoints. - let existing = this._breakpointStore[aScript.url]; - if (existing) { - let endLine = aScript.startLine + aScript.lineCount - 1; - // Iterate over the lines backwards, so that sliding breakpoints don't - // affect the loop. - for (let line = existing.length - 1; line >= aScript.startLine; line--) { - let bp = existing[line]; - // Only consider breakpoints that are not already associated with - // scripts, and limit search to the line numbers contained in the new - // script. - if (bp && !bp.actor.scripts.length && line <= endLine) { - this._setBreakpoint(bp); - } - } - } - return true; - }, - -}; - -ThreadActor.prototype.requestTypes = { - "attach": ThreadActor.prototype.onAttach, - "detach": ThreadActor.prototype.onDetach, - "reconfigure": ThreadActor.prototype.onReconfigure, - "resume": ThreadActor.prototype.onResume, - "clientEvaluate": ThreadActor.prototype.onClientEvaluate, - "frames": ThreadActor.prototype.onFrames, - "interrupt": ThreadActor.prototype.onInterrupt, - "releaseMany": ThreadActor.prototype.onReleaseMany, - "setBreakpoint": ThreadActor.prototype.onSetBreakpoint, - "sources": ThreadActor.prototype.onSources, - "threadGrips": ThreadActor.prototype.onThreadGrips -}; - - -/** - * Creates a PauseActor. - * - * PauseActors exist for the lifetime of a given debuggee pause. Used to - * scope pause-lifetime grips. - * - * @param ActorPool aPool - * The actor pool created for this pause. - */ -function PauseActor(aPool) -{ - this.pool = aPool; -} - -PauseActor.prototype = { - actorPrefix: "pause" -}; - - -/** - * A base actor for any actors that should only respond receive messages in the - * paused state. Subclasses may expose a `threadActor` which is used to help - * determine when we are in a paused state. Subclasses should set their own - * "constructor" property if they want better error messages. You should never - * instantiate a PauseScopedActor directly, only through subclasses. - */ -function PauseScopedActor() -{ -} - -/** - * A function decorator for creating methods to handle protocol messages that - * should only be received while in the paused state. - * - * @param aMethod Function - * The function we are decorating. - */ -PauseScopedActor.withPaused = function PSA_withPaused(aMethod) { - return function () { - if (this.isPaused()) { - return aMethod.apply(this, arguments); - } else { - return this._wrongState(); - } - }; -}; - -PauseScopedActor.prototype = { - - /** - * Returns true if we are in the paused state. - */ - isPaused: function PSA_isPaused() { - // When there is not a ThreadActor available (like in the webconsole) we - // have to be optimistic and assume that we are paused so that we can - // respond to requests. - return this.threadActor ? this.threadActor.state === "paused" : true; - }, - - /** - * Returns the wrongState response packet for this actor. - */ - _wrongState: function PSA_wrongState() { - return { - error: "wrongState", - message: this.constructor.name + - " actors can only be accessed while the thread is paused." - }; - } -}; - - -/** - * A SourceActor provides information about the source of a script. - * - * @param aUrl String - * The url of the source we are representing. - * @param aThreadActor ThreadActor - * The current thread actor. - * @param aSourceMap SourceMapConsumer - * Optional. The source map that introduced this source, if available. - */ -function SourceActor(aUrl, aThreadActor, aSourceMap=null) { - this._threadActor = aThreadActor; - this._url = aUrl; - this._sourceMap = aSourceMap; -} - -SourceActor.prototype = { - constructor: SourceActor, - actorPrefix: "source", - - get threadActor() this._threadActor, - get url() this._url, - - form: function SA_form() { - return { - actor: this.actorID, - url: this._url, - isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url) - // TODO bug 637572: introductionScript - }; - }, - - disconnect: function LSA_disconnect() { - if (this.registeredPool && this.registeredPool.sourceActors) { - delete this.registeredPool.sourceActors[this.actorID]; - } - }, - - /** - * Handler for the "source" packet. - */ - onSource: function SA_onSource(aRequest) { - let sourceContent = null; - if (this._sourceMap) { - sourceContent = this._sourceMap.sourceContentFor(this._url); - } - - if (sourceContent) { - return { - from: this.actorID, - source: this.threadActor.createValueGrip( - sourceContent, this.threadActor.threadLifetimePool) - }; - } - - // XXX bug 865252: Don't load from the cache if this is a source mapped - // source because we can't guarantee that the cache has the most up to date - // content for this source like we can if it isn't source mapped. - return fetch(this._url, { loadFromCache: !this._sourceMap }) - .then((aSource) => { - return this.threadActor.createValueGrip( - aSource, this.threadActor.threadLifetimePool); - }) - .then((aSourceGrip) => { - return { - from: this.actorID, - source: aSourceGrip - }; - }, (aError) => { - let msg = "Got an exception during SA_onSource: " + aError + - "\n" + aError.stack; - // Cu.reportError(msg); - dumpn(msg); - return { - "from": this.actorID, - "error": "loadSourceError", - "message": "Could not load the source for " + this._url + "." - }; - }); - }, - - /** - * Handler for the "blackbox" packet. - */ - onBlackBox: function SA_onBlackBox(aRequest) { - this.threadActor.sources.blackBox(this.url); - let packet = { - from: this.actorID - }; - if (this.threadActor.state == "paused" - && this.threadActor.youngestFrame - && this.threadActor.youngestFrame.script.url == this.url) { - packet.pausedInSource = true; - } - return packet; - }, - - /** - * Handler for the "unblackbox" packet. - */ - onUnblackBox: function SA_onUnblackBox(aRequest) { - this.threadActor.sources.unblackBox(this.url); - return { - from: this.actorID - }; - } -}; - -SourceActor.prototype.requestTypes = { - "source": SourceActor.prototype.onSource, - "blackbox": SourceActor.prototype.onBlackBox, - "unblackbox": SourceActor.prototype.onUnblackBox -}; - - -/** - * Creates an actor for the specified object. - * - * @param aObj Debugger.Object - * The debuggee object. - * @param aThreadActor ThreadActor - * The parent thread actor for this object. - */ -function ObjectActor(aObj, aThreadActor) -{ - this.obj = aObj; - this.threadActor = aThreadActor; -} - -ObjectActor.prototype = { - actorPrefix: "obj", - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function OA_grip() { - let g = { - "type": "object", - "class": this.obj.class, - "actor": this.actorID, - "extensible": this.obj.isExtensible(), - "frozen": this.obj.isFrozen(), - "sealed": this.obj.isSealed() - }; - - // Add additional properties for functions. - if (this.obj.class === "Function") { - if (this.obj.name) { - g.name = this.obj.name; - } else if (this.obj.displayName) { - g.displayName = this.obj.displayName; - } - - // Check if the developer has added a de-facto standard displayName - // property for us to use. - let desc = this.obj.getOwnPropertyDescriptor("displayName"); - if (desc && desc.value && typeof desc.value == "string") { - g.userDisplayName = this.threadActor.createValueGrip(desc.value); - } - } - - return g; - }, - - /** - * Releases this actor from the pool. - */ - release: function OA_release() { - if (this.registeredPool.objectActors) { - this.registeredPool.objectActors.delete(this.obj); - } - this.registeredPool.removeActor(this); - }, - - /** - * Handle a protocol request to provide the names of the properties defined on - * the object and not its prototype. - * - * @param aRequest object - * The protocol request object. - */ - onOwnPropertyNames: function OA_onOwnPropertyNames(aRequest) { - return { from: this.actorID, - ownPropertyNames: this.obj.getOwnPropertyNames() }; - }, - - /** - * Handle a protocol request to provide the prototype and own properties of - * the object. - * - * @param aRequest object - * The protocol request object. - */ - onPrototypeAndProperties: function OA_onPrototypeAndProperties(aRequest) { - let ownProperties = Object.create(null); - let names; - try { - names = this.obj.getOwnPropertyNames(); - } catch (ex) { - // The above can throw if this.obj points to a dead object. - // TODO: we should use Cu.isDeadWrapper() - see bug 885800. - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(null), - ownProperties: ownProperties, - safeGetterValues: Object.create(null) }; - } - for (let name of names) { - ownProperties[name] = this._propertyDescriptor(name); - } - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(this.obj.proto), - ownProperties: ownProperties, - safeGetterValues: this._findSafeGetterValues(ownProperties) }; - }, - - /** - * Find the safe getter values for the current Debugger.Object, |this.obj|. - * - * @private - * @param object aOwnProperties - * The object that holds the list of known ownProperties for - * |this.obj|. - * @return object - * An object that maps property names to safe getter descriptors as - * defined by the remote debugging protocol. - */ - _findSafeGetterValues: function OA__findSafeGetterValues(aOwnProperties) - { - let safeGetterValues = Object.create(null); - let obj = this.obj; - let level = 0; - - while (obj) { - let getters = this._findSafeGetters(obj); - for (let name of getters) { - // Avoid overwriting properties from prototypes closer to this.obj. Also - // avoid providing safeGetterValues from prototypes if property |name| - // is already defined as an own property. - if (name in safeGetterValues || - (obj != this.obj && name in aOwnProperties)) { - continue; - } - - let desc = null, getter = null; - try { - desc = obj.getOwnPropertyDescriptor(name); - getter = desc.get; - } catch (ex) { - // The above can throw if the cache becomes stale. - } - if (!getter) { - obj._safeGetters = null; - continue; - } - - let result = getter.call(this.obj); - if (result && !("throw" in result)) { - let getterValue = undefined; - if ("return" in result) { - getterValue = result.return; - } else if ("yield" in result) { - getterValue = result.yield; - } - // WebIDL attributes specified with the LenientThis extended attribute - // return undefined and should be ignored. - if (getterValue !== undefined) { - safeGetterValues[name] = { - getterValue: this.threadActor.createValueGrip(getterValue), - getterPrototypeLevel: level, - enumerable: desc.enumerable, - writable: level == 0 ? desc.writable : true, - }; - } - } - } - - obj = obj.proto; - level++; - } - - return safeGetterValues; - }, - - /** - * Find the safe getters for a given Debugger.Object. Safe getters are native - * getters which are safe to execute. - * - * @private - * @param Debugger.Object aObject - * The Debugger.Object where you want to find safe getters. - * @return Set - * A Set of names of safe getters. This result is cached for each - * Debugger.Object. - */ - _findSafeGetters: function OA__findSafeGetters(aObject) - { - if (aObject._safeGetters) { - return aObject._safeGetters; - } - - let getters = new Set(); - for (let name of aObject.getOwnPropertyNames()) { - let desc = null; - try { - desc = aObject.getOwnPropertyDescriptor(name); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). - } - if (!desc || desc.value !== undefined || !("get" in desc)) { - continue; - } - - let fn = desc.get; - if (fn && fn.callable && fn.class == "Function" && - fn.script === undefined) { - getters.add(name); - } - } - - aObject._safeGetters = getters; - return getters; - }, - - /** - * Handle a protocol request to provide the prototype of the object. - * - * @param aRequest object - * The protocol request object. - */ - onPrototype: function OA_onPrototype(aRequest) { - return { from: this.actorID, - prototype: this.threadActor.createValueGrip(this.obj.proto) }; - }, - - /** - * Handle a protocol request to provide the property descriptor of the - * object's specified property. - * - * @param aRequest object - * The protocol request object. - */ - onProperty: function OA_onProperty(aRequest) { - if (!aRequest.name) { - return { error: "missingParameter", - message: "no property name was specified" }; - } - - return { from: this.actorID, - descriptor: this._propertyDescriptor(aRequest.name) }; - }, - - /** - * A helper method that creates a property descriptor for the provided object, - * properly formatted for sending in a protocol response. - * - * @param string aName - * The property that the descriptor is generated for. - */ - _propertyDescriptor: function OA_propertyDescriptor(aName) { - let desc; - try { - desc = this.obj.getOwnPropertyDescriptor(aName); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). Inform the user with a bogus, but hopefully - // explanatory, descriptor. - return { - configurable: false, - writable: false, - enumerable: false, - value: e.name - }; - } - - let retval = { - configurable: desc.configurable, - enumerable: desc.enumerable - }; - - if ("value" in desc) { - retval.writable = desc.writable; - retval.value = this.threadActor.createValueGrip(desc.value); - } else { - if ("get" in desc) { - retval.get = this.threadActor.createValueGrip(desc.get); - } - if ("set" in desc) { - retval.set = this.threadActor.createValueGrip(desc.set); - } - } - return retval; - }, - - /** - * Handle a protocol request to provide the source code of a function. - * - * @param aRequest object - * The protocol request object. - */ - onDecompile: function OA_onDecompile(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "decompile request is only valid for object grips " + - "with a 'Function' class." }; - } - - return { from: this.actorID, - decompiledCode: this.obj.decompile(!!aRequest.pretty) }; - }, - - /** - * Handle a protocol request to provide the parameters of a function. - * - * @param aRequest object - * The protocol request object. - */ - onParameterNames: function OA_onParameterNames(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "'parameterNames' request is only valid for object " + - "grips with a 'Function' class." }; - } - - return { parameterNames: this.obj.parameterNames }; - }, - - /** - * Handle a protocol request to release a thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onRelease: function OA_onRelease(aRequest) { - this.release(); - return {}; - }, -}; - -ObjectActor.prototype.requestTypes = { - "parameterNames": ObjectActor.prototype.onParameterNames, - "prototypeAndProperties": ObjectActor.prototype.onPrototypeAndProperties, - "prototype": ObjectActor.prototype.onPrototype, - "property": ObjectActor.prototype.onProperty, - "ownPropertyNames": ObjectActor.prototype.onOwnPropertyNames, - "decompile": ObjectActor.prototype.onDecompile, - "release": ObjectActor.prototype.onRelease, -}; - - -/** - * Creates a pause-scoped actor for the specified object. - * @see ObjectActor - */ -function PauseScopedObjectActor() -{ - ObjectActor.apply(this, arguments); -} - -PauseScopedObjectActor.prototype = Object.create(PauseScopedActor.prototype); - -update(PauseScopedObjectActor.prototype, ObjectActor.prototype); - -update(PauseScopedObjectActor.prototype, { - constructor: PauseScopedObjectActor, - - onOwnPropertyNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onOwnPropertyNames), - - onPrototypeAndProperties: - PauseScopedActor.withPaused(ObjectActor.prototype.onPrototypeAndProperties), - - onPrototype: PauseScopedActor.withPaused(ObjectActor.prototype.onPrototype), - onProperty: PauseScopedActor.withPaused(ObjectActor.prototype.onProperty), - onDecompile: PauseScopedActor.withPaused(ObjectActor.prototype.onDecompile), - - onParameterNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onParameterNames), - - /** - * Handle a protocol request to provide the lexical scope of a function. - * - * @param aRequest object - * The protocol request object. - */ - onScope: PauseScopedActor.withPaused(function OA_onScope(aRequest) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "scope request is only valid for object grips with a" + - " 'Function' class." }; - } - - let envActor = this.threadActor.createEnvironmentActor(this.obj.environment, - this.registeredPool); - if (!envActor) { - return { error: "notDebuggee", - message: "cannot access the environment of this function." }; - } - - return { from: this.actorID, scope: envActor.form() }; - }), - - /** - * Handle a protocol request to promote a pause-lifetime grip to a - * thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrip: PauseScopedActor.withPaused(function OA_onThreadGrip(aRequest) { - this.threadActor.threadObjectGrip(this); - return {}; - }), - - /** - * Handle a protocol request to release a thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onRelease: PauseScopedActor.withPaused(function OA_onRelease(aRequest) { - if (this.registeredPool !== this.threadActor.threadLifetimePool) { - return { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - - this.release(); - return {}; - }), -}); - -update(PauseScopedObjectActor.prototype.requestTypes, { - "scope": PauseScopedObjectActor.prototype.onScope, - "threadGrip": PauseScopedObjectActor.prototype.onThreadGrip, -}); - - -/** - * Creates an actor for the specied "very long" string. "Very long" is specified - * at the server's discretion. - * - * @param aString String - * The string. - */ -function LongStringActor(aString) -{ - this.string = aString; - this.stringLength = aString.length; -} - -LongStringActor.prototype = { - - actorPrefix: "longString", - - disconnect: function LSA_disconnect() { - // Because longStringActors is not a weak map, we won't automatically leave - // it so we need to manually leave on disconnect so that we don't leak - // memory. - if (this.registeredPool && this.registeredPool.longStringActors) { - delete this.registeredPool.longStringActors[this.actorID]; - } - }, - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function LSA_grip() { - return { - "type": "longString", - "initial": this.string.substring( - 0, DebuggerServer.LONG_STRING_INITIAL_LENGTH), - "length": this.stringLength, - "actor": this.actorID - }; - }, - - /** - * Handle a request to extract part of this actor's string. - * - * @param aRequest object - * The protocol request object. - */ - onSubstring: function LSA_onSubString(aRequest) { - return { - "from": this.actorID, - "substring": this.string.substring(aRequest.start, aRequest.end) - }; - }, - - /** - * Handle a request to release this LongStringActor instance. - */ - onRelease: function LSA_onRelease() { - // TODO: also check if registeredPool === threadActor.threadLifetimePool - // when the web console moves aray from manually releasing pause-scoped - // actors. - if (this.registeredPool.longStringActors) { - delete this.registeredPool.longStringActors[this.actorID]; - } - this.registeredPool.removeActor(this); - return {}; - }, -}; - -LongStringActor.prototype.requestTypes = { - "substring": LongStringActor.prototype.onSubstring, - "release": LongStringActor.prototype.onRelease -}; - - -/** - * Creates an actor for the specified stack frame. - * - * @param aFrame Debugger.Frame - * The debuggee frame. - * @param aThreadActor ThreadActor - * The parent thread actor for this frame. - */ -function FrameActor(aFrame, aThreadActor) -{ - this.frame = aFrame; - this.threadActor = aThreadActor; -} - -FrameActor.prototype = { - actorPrefix: "frame", - - /** - * A pool that contains frame-lifetime objects, like the environment. - */ - _frameLifetimePool: null, - get frameLifetimePool() { - if (!this._frameLifetimePool) { - this._frameLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._frameLifetimePool); - } - return this._frameLifetimePool; - }, - - /** - * Finalization handler that is called when the actor is being evicted from - * the pool. - */ - disconnect: function FA_disconnect() { - this.conn.removeActorPool(this._frameLifetimePool); - this._frameLifetimePool = null; - }, - - /** - * Returns a frame form for use in a protocol message. - */ - form: function FA_form() { - let form = { actor: this.actorID, - type: this.frame.type }; - if (this.frame.type === "call") { - form.callee = this.threadActor.createValueGrip(this.frame.callee); - } - - if (this.frame.environment) { - let envActor = this.threadActor - .createEnvironmentActor(this.frame.environment, - this.frameLifetimePool); - form.environment = envActor.form(); - } - form.this = this.threadActor.createValueGrip(this.frame.this); - form.arguments = this._args(); - if (this.frame.script) { - form.where = { url: this.frame.script.url, - line: this.frame.script.getOffsetLine(this.frame.offset) }; - form.isBlackBoxed = this.threadActor.sources.isBlackBoxed(this.frame.script.url) - } - - if (!this.frame.older) { - form.oldest = true; - } - - return form; - }, - - _args: function FA__args() { - if (!this.frame.arguments) { - return []; - } - - return [this.threadActor.createValueGrip(arg) - for each (arg in this.frame.arguments)]; - }, - - /** - * Handle a protocol request to pop this frame from the stack. - * - * @param aRequest object - * The protocol request object. - */ - onPop: function FA_onPop(aRequest) { - // TODO: remove this when Debugger.Frame.prototype.pop is implemented - if (typeof this.frame.pop != "function") { - return { error: "notImplemented", - message: "Popping frames is not yet implemented." }; - } - - while (this.frame != this.threadActor.dbg.getNewestFrame()) { - this.threadActor.dbg.getNewestFrame().pop(); - } - this.frame.pop(aRequest.completionValue); - - // TODO: return the watches property when frame pop watch actors are - // implemented. - return { from: this.actorID }; - } -}; - -FrameActor.prototype.requestTypes = { - "pop": FrameActor.prototype.onPop, -}; - - -/** - * Creates a BreakpointActor. BreakpointActors exist for the lifetime of their - * containing thread and are responsible for deleting breakpoints, handling - * breakpoint hits and associating breakpoints with scripts. - * - * @param ThreadActor aThreadActor - * The parent thread actor that contains this breakpoint. - * @param object aLocation - * The location of the breakpoint as specified in the protocol. - */ -function BreakpointActor(aThreadActor, aLocation) -{ - this.scripts = []; - this.threadActor = aThreadActor; - this.location = aLocation; -} - -BreakpointActor.prototype = { - actorPrefix: "breakpoint", - - /** - * Called when this same breakpoint is added to another Debugger.Script - * instance, in the case of a page reload. - * - * @param aScript Debugger.Script - * The new source script on which the breakpoint has been set. - * @param ThreadActor aThreadActor - * The parent thread actor that contains this breakpoint. - */ - addScript: function BA_addScript(aScript, aThreadActor) { - this.threadActor = aThreadActor; - this.scripts.push(aScript); - }, - - /** - * Remove the breakpoints from associated scripts and clear the script cache. - */ - removeScripts: function () { - for (let script of this.scripts) { - script.clearBreakpoint(this); - } - this.scripts = []; - }, - - /** - * A function that the engine calls when a breakpoint has been hit. - * - * @param aFrame Debugger.Frame - * The stack frame that contained the breakpoint. - */ - hit: function BA_hit(aFrame) { - if (this.threadActor.sources.isBlackBoxed(this.location.url)) { - return undefined; - } - - // TODO: add the rest of the breakpoints on that line (bug 676602). - let reason = { type: "breakpoint", actors: [ this.actorID ] }; - return this.threadActor._pauseAndRespond(aFrame, reason, (aPacket) => { - log("pause callback ..."); - - let { url, line } = aPacket.frame.where; - return this.threadActor.sources.getOriginalLocation(url, line) - .then(function (aOrigPosition) { - aPacket.frame.where = aOrigPosition; - return aPacket; - }); - }); - }, - - /** - * Handle a protocol request to remove this breakpoint. - * - * @param aRequest object - * The protocol request object. - */ - onDelete: function BA_onDelete(aRequest) { - // Remove from the breakpoint store. - let scriptBreakpoints = this.threadActor._breakpointStore[this.location.url]; - delete scriptBreakpoints[this.location.line]; - this.threadActor._hooks.removeFromParentPool(this); - // Remove the actual breakpoint from the associated scripts. - this.removeScripts(); - - return { from: this.actorID }; - } -}; - -BreakpointActor.prototype.requestTypes = { - "delete": BreakpointActor.prototype.onDelete -}; - - -/** - * Creates an EnvironmentActor. EnvironmentActors are responsible for listing - * the bindings introduced by a lexical environment and assigning new values to - * those identifier bindings. - * - * @param Debugger.Environment aEnvironment - * The lexical environment that will be used to create the actor. - * @param ThreadActor aThreadActor - * The parent thread actor that contains this environment. - */ -function EnvironmentActor(aEnvironment, aThreadActor) -{ - this.obj = aEnvironment; - this.threadActor = aThreadActor; -} - -EnvironmentActor.prototype = { - actorPrefix: "environment", - - /** - * Return an environment form for use in a protocol message. - */ - form: function EA_form() { - let form = { actor: this.actorID }; - - // What is this environment's type? - if (this.obj.type == "declarative") { - form.type = this.obj.callee ? "function" : "block"; - } else { - form.type = this.obj.type; - } - - // Does this environment have a parent? - if (this.obj.parent) { - form.parent = (this.threadActor - .createEnvironmentActor(this.obj.parent, - this.registeredPool) - .form()); - } - - // Does this environment reflect the properties of an object as variables? - if (this.obj.type == "object" || this.obj.type == "with") { - form.object = this.threadActor.createValueGrip(this.obj.object); - } - - // Is this the environment created for a function call? - if (this.obj.callee) { - form.function = this.threadActor.createValueGrip(this.obj.callee); - } - - // Shall we list this environment's bindings? - if (this.obj.type == "declarative") { - form.bindings = this._bindings(); - } - - return form; - }, - - /** - * Return the identifier bindings object as required by the remote protocol - * specification. - */ - _bindings: function EA_bindings() { - let bindings = { arguments: [], variables: {} }; - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - if (typeof this.obj.getVariable != "function") { - //if (typeof this.obj.getVariableDescriptor != "function") { - return bindings; - } - - let parameterNames; - if (this.obj.callee) { - parameterNames = this.obj.callee.parameterNames; - } - for each (let name in parameterNames) { - let arg = {}; - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - let desc = { - value: this.obj.getVariable(name), - configurable: false, - writable: true, - enumerable: true - }; - - // let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = this.threadActor.createValueGrip(desc.value); - descForm.writable = desc.writable; - } else { - descForm.get = this.threadActor.createValueGrip(desc.get); - descForm.set = this.threadActor.createValueGrip(desc.set); - } - arg[name] = descForm; - bindings.arguments.push(arg); - } - - for each (let name in this.obj.names()) { - if (bindings.arguments.some(function exists(element) { - return !!element[name]; - })) { - continue; - } - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands. - let desc = { - configurable: false, - writable: true, - enumerable: true - }; - try { - desc.value = this.obj.getVariable(name); - } catch (e) { - // Avoid "Debugger scope is not live" errors for |arguments|, introduced - // in bug 746601. - if (name != "arguments") { - throw e; - } - } - //let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = this.threadActor.createValueGrip(desc.value); - descForm.writable = desc.writable; - } else { - descForm.get = this.threadActor.createValueGrip(desc.get); - descForm.set = this.threadActor.createValueGrip(desc.set); - } - bindings.variables[name] = descForm; - } - - return bindings; - }, - - /** - * Handle a protocol request to change the value of a variable bound in this - * lexical environment. - * - * @param aRequest object - * The protocol request object. - */ - onAssign: function EA_onAssign(aRequest) { - // TODO: enable the commented-out part when getVariableDescriptor lands - // (bug 725815). - /*let desc = this.obj.getVariableDescriptor(aRequest.name); - - if (!desc.writable) { - return { error: "immutableBinding", - message: "Changing the value of an immutable binding is not " + - "allowed" }; - }*/ - - try { - this.obj.setVariable(aRequest.name, aRequest.value); - } catch (e) { - if (e instanceof Debugger.DebuggeeWouldRun) { - return { error: "threadWouldRun", - cause: e.cause ? e.cause : "setter", - message: "Assigning a value would cause the debuggee to run" }; - } - // This should never happen, so let it complain loudly if it does. - throw e; - } - return { from: this.actorID }; - }, - - /** - * Handle a protocol request to fully enumerate the bindings introduced by the - * lexical environment. - * - * @param aRequest object - * The protocol request object. - */ - onBindings: function EA_onBindings(aRequest) { - return { from: this.actorID, - bindings: this._bindings() }; - } -}; - -EnvironmentActor.prototype.requestTypes = { - "assign": EnvironmentActor.prototype.onAssign, - "bindings": EnvironmentActor.prototype.onBindings -}; - -/** - * Override the toString method in order to get more meaningful script output - * for debugging the debugger. - */ -Debugger.Script.prototype.toString = function() { - let output = ""; - if (this.url) { - output += this.url; - } - if (typeof this.startLine != "undefined") { - output += ":" + this.startLine; - if (this.lineCount && this.lineCount > 1) { - output += "-" + (this.startLine + this.lineCount - 1); - } - } - if (this.strictMode) { - output += ":strict"; - } - return output; -}; - -/** - * Helper property for quickly getting to the line number a stack frame is - * currently paused at. - */ -Object.defineProperty(Debugger.Frame.prototype, "line", { - configurable: true, - get: function() { - if (this.script) { - return this.script.getOffsetLine(this.offset); - } else { - return null; - } - } -}); - - -/** - * Creates an actor for handling chrome debugging. ChromeDebuggerActor is a - * thin wrapper over ThreadActor, slightly changing some of its behavior. - * - * @param aConnection object - * The DebuggerServerConnection with which this ChromeDebuggerActor - * is associated. (Currently unused, but required to make this - * constructor usable with addGlobalActor.) - * - * @param aHooks object - * An object with preNest and postNest methods for calling when entering - * and exiting a nested event loop and also addToParentPool and - * removeFromParentPool methods for handling the lifetime of actors that - * will outlive the thread, like breakpoints. - */ -function ChromeDebuggerActor(aConnection, aHooks) -{ - ThreadActor.call(this, aHooks); -} - -ChromeDebuggerActor.prototype = Object.create(ThreadActor.prototype); - -update(ChromeDebuggerActor.prototype, { - constructor: ChromeDebuggerActor, - - // A constant prefix that will be used to form the actor ID by the server. - actorPrefix: "chromeDebugger", - - /** - * Override the eligibility check for scripts and sources to make sure every - * script and source with a URL is stored when debugging chrome. - */ - _allowSource: function(aSourceURL) !!aSourceURL, - - /** - * An object that will be used by ThreadActors to tailor their behavior - * depending on the debugging context being required (chrome or content). - * The methods that this object provides must be bound to the ThreadActor - * before use. - */ - globalManager: { - findGlobals: function CDA_findGlobals() { - // Add every global known to the debugger as debuggee. - this.dbg.addAllGlobalsAsDebuggees(); - }, - - /** - * A function that the engine calls when a new global object has been - * created. - * - * @param aGlobal Debugger.Object - * The new global object that was created. - */ - onNewGlobal: function CDA_onNewGlobal(aGlobal) { - this.addDebuggee(aGlobal); - // Notify the client. - this.conn.send({ - from: this.actorID, - type: "newGlobal", - // TODO: after bug 801084 lands see if we need to JSONify this. - hostAnnotations: aGlobal.hostAnnotations - }); - } - } -}); - - -/** - * Manages the sources for a thread. Handles source maps, locations in the - * sources, etc for ThreadActors. - */ -function ThreadSources(aThreadActor, aUseSourceMaps, aAllowPredicate, - aOnNewSource) { - this._thread = aThreadActor; - this._useSourceMaps = aUseSourceMaps; - this._allow = aAllowPredicate; - this._onNewSource = aOnNewSource; - - // source map URL --> promise of SourceMapConsumer - this._sourceMaps = Object.create(null); - // generated source url --> promise of SourceMapConsumer - this._sourceMapsByGeneratedSource = Object.create(null); - // original source url --> promise of SourceMapConsumer - this._sourceMapsByOriginalSource = Object.create(null); - // source url --> SourceActor - this._sourceActors = Object.create(null); - // original url --> generated url - this._generatedUrlsByOriginalUrl = Object.create(null); -} - -/** - * Must be a class property because it needs to persist across reloads, same as - * the breakpoint store. - */ -ThreadSources._blackBoxedSources = new Set(); - -ThreadSources.prototype = { - /** - * Return the source actor representing |aURL|, creating one if none - * exists already. Returns null if |aURL| is not allowed by the 'allow' - * predicate. - * - * Right now this takes a URL, but in the future it should - * take a Debugger.Source. See bug 637572. - * - * @param String aURL - * The source URL. - * @param optional SourceMapConsumer aSourceMap - * The source map that introduced this source, if any. - * @returns a SourceActor representing the source at aURL or null. - */ - source: function TS_source(aURL, aSourceMap=null) { - if (!this._allow(aURL)) { - return null; - } - - if (aURL in this._sourceActors) { - return this._sourceActors[aURL]; - } - - let actor = new SourceActor(aURL, this._thread, aSourceMap); - this._thread.threadLifetimePool.addActor(actor); - this._sourceActors[aURL] = actor; - try { - this._onNewSource(actor); - } catch (e) { - reportError(e); - } - return actor; - }, - - /** - * Return a promise of an array of source actors representing all the - * sources of |aScript|. - * - * If source map handling is enabled and |aScript| has a source map, then - * use it to find all of |aScript|'s *original* sources; return a promise - * of an array of source actors for those. - */ - sourcesForScript: function TS_sourcesForScript(aScript) { - if (!this._useSourceMaps || !aScript.sourceMapURL) { - return resolve([this.source(aScript.url)].filter(isNotNull)); - } - - return this.sourceMap(aScript) - .then((aSourceMap) => { - return [ - this.source(s, aSourceMap) for (s of aSourceMap.sources) - ]; - }) - .then(null, (e) => { - reportError(e); - delete this._sourceMaps[this._normalize(aScript.sourceMapURL, aScript.url)]; - delete this._sourceMapsByGeneratedSource[aScript.url]; - return [this.source(aScript.url)]; - }) - .then(function (aSources) { - return aSources.filter(isNotNull); - }); - }, - - /** - * Return a promise of a SourceMapConsumer for the source map for - * |aScript|; if we already have such a promise extant, return that. - * |aScript| must have a non-null sourceMapURL. - */ - sourceMap: function TS_sourceMap(aScript) { - if (aScript.url in this._sourceMapsByGeneratedSource) { - return this._sourceMapsByGeneratedSource[aScript.url]; - } - dbg_assert(aScript.sourceMapURL); - let sourceMapURL = this._normalize(aScript.sourceMapURL, aScript.url); - let map = this._fetchSourceMap(sourceMapURL) - .then((aSourceMap) => { - for (let s of aSourceMap.sources) { - this._generatedUrlsByOriginalUrl[s] = aScript.url; - this._sourceMapsByOriginalSource[s] = resolve(aSourceMap); - } - return aSourceMap; - }); - this._sourceMapsByGeneratedSource[aScript.url] = map; - return map; - }, - - /** - * Return a promise of a SourceMapConsumer for the source map located at - * |aAbsSourceMapURL|, which must be absolute. If there is already such a - * promise extant, return it. - */ - _fetchSourceMap: function TS__fetchSourceMap(aAbsSourceMapURL) { - if (aAbsSourceMapURL in this._sourceMaps) { - return this._sourceMaps[aAbsSourceMapURL]; - } else { - let promise = fetch(aAbsSourceMapURL).then((rawSourceMap) => { - let map = new SourceMapConsumer(rawSourceMap); - let base = aAbsSourceMapURL.replace(/\/[^\/]+$/, '/'); - if (base.indexOf("data:") !== 0) { - map.sourceRoot = map.sourceRoot - ? this._normalize(map.sourceRoot, base) - : base; - } - return map; - }); - this._sourceMaps[aAbsSourceMapURL] = promise; - return promise; - } - }, - - /** - * Returns a promise of the location in the original source if the source is - * source mapped, otherwise a promise of the same location. - * - * TODO bug 637572: take/return a column - */ - getOriginalLocation: function TS_getOriginalLocation(aSourceUrl, aLine) { - if (aSourceUrl in this._sourceMapsByGeneratedSource) { - return this._sourceMapsByGeneratedSource[aSourceUrl] - .then(function (aSourceMap) { - let { source, line } = aSourceMap.originalPositionFor({ - source: aSourceUrl, - line: aLine, - column: Infinity - }); - return { - url: source, - line: line - }; - }); - } - - // No source map - return resolve({ - url: aSourceUrl, - line: aLine - }); - }, - - /** - * Returns a promise of the location in the generated source corresponding to - * the original source and line given. - * - * When we pass a script S representing generated code to |sourceMap|, - * above, that returns a promise P. The process of resolving P populates - * the tables this function uses; thus, it won't know that S's original - * source URLs map to S until P is resolved. - * - * TODO bug 637572: take/return a column - */ - getGeneratedLocation: function TS_getGeneratedLocation(aSourceUrl, aLine) { - if (aSourceUrl in this._sourceMapsByOriginalSource) { - return this._sourceMapsByOriginalSource[aSourceUrl] - .then((aSourceMap) => { - let { line } = aSourceMap.generatedPositionFor({ - source: aSourceUrl, - line: aLine, - column: Infinity - }); - return { - url: this._generatedUrlsByOriginalUrl[aSourceUrl], - line: line - }; - }); - } - - // No source map - return resolve({ - url: aSourceUrl, - line: aLine - }); - }, - - /** - * Returns true if URL for the given source is black boxed. - * - * @param aURL String - * The URL of the source which we are checking whether it is black - * boxed or not. - */ - isBlackBoxed: function TS_isBlackBoxed(aURL) { - return ThreadSources._blackBoxedSources.has(aURL); - }, - - /** - * Add the given source URL to the set of sources that are black boxed. If the - * thread is currently paused and we are black boxing the yougest frame's - * source, this will force a step. - * - * @param aURL String - * The URL of the source which we are black boxing. - */ - blackBox: function TS_blackBox(aURL) { - ThreadSources._blackBoxedSources.add(aURL); - }, - - /** - * Remove the given source URL to the set of sources that are black boxed. - * - * @param aURL String - * The URL of the source which we are no longer black boxing. - */ - unblackBox: function TS_unblackBox(aURL) { - ThreadSources._blackBoxedSources.delete(aURL); - }, - - /** - * Normalize multiple relative paths towards the base paths on the right. - */ - _normalize: function TS__normalize(...aURLs) { - dbg_assert(aURLs.length > 1); - let base = Services.io.newURI(aURLs.pop(), null, null); - let url; - while ((url = aURLs.pop())) { - base = Services.io.newURI(url, null, base); - } - return base.spec; - }, - - iter: function TS_iter() { - for (let url in this._sourceActors) { - yield this._sourceActors[url]; - } - } -}; - -// Utility functions. - -/** - * Utility function for updating an object with the properties of another - * object. - * - * @param aTarget Object - * The object being updated. - * @param aNewAttrs Object - * The new attributes being set on the target. - */ -function update(aTarget, aNewAttrs) { - for (let key in aNewAttrs) { - let desc = Object.getOwnPropertyDescriptor(aNewAttrs, key); - - if (desc) { - Object.defineProperty(aTarget, key, desc); - } - } -} - -/** - * Returns true if its argument is not null. - */ -function isNotNull(aThing) { - return aThing !== null; -} - -/** - * Performs a request to load the desired URL and returns a promise. - * - * @param aURL String - * The URL we will request. - * @returns Promise - * A promise of the document at that URL, as a string. - * - * XXX: It may be better to use nsITraceableChannel to get to the sources - * without relying on caching when we can (not for eval, etc.): - * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ - */ -function fetch(aURL, aOptions={ loadFromCache: true }) { - let deferred = defer(); - let scheme; - let url = aURL.split(" -> ").pop(); - let charset; - let filePath = url; - // try { - // scheme = Services.io.extractScheme(url); - // } catch (e) { - // In the xpcshell tests, the script url is the absolute path of the test - // file, which will make a malformed URI error be thrown. Add the file - // scheme prefix ourselves. - url = "file://" + url; - // scheme = Services.io.extractScheme(url); - // } - scheme = "file"; - - switch (scheme) { - case "file": - case "chrome": - case "resource": - try { - // NetUtil.asyncFetch(url, function onFetch(aStream, aStatus) { - // if (!Components.isSuccessCode(aStatus)) { - // deferred.reject("Request failed: " + url); - // return; - // } - let cc = globalDebuggee.cc; - let fileUtils = cc.FileUtils.getInstance(); - let source = fileUtils.getStringFromFile(filePath);//NetUtil.readInputStreamToString(aStream, aStream.available()); - if (!source) - { - deferred.reject("Request failed: " + url); - } - else - { - deferred.resolve(source); - } - // aStream.close(); - // }); - } catch (ex) { - deferred.reject("Request failed: " + url); - } - break; - - default: - let channel; - try { - channel = Services.io.newChannel(url, null, null); - } catch (e if e.name == "NS_ERROR_UNKNOWN_PROTOCOL") { - // On Windows xpcshell tests, c:/foo/bar can pass as a valid URL, but - // newChannel won't be able to handle it. - url = "file:///" + url; - channel = Services.io.newChannel(url, null, null); - } - let chunks = []; - let streamListener = { - onStartRequest: function(aRequest, aContext, aStatusCode) { - if (!Components.isSuccessCode(aStatusCode)) { - deferred.reject("Request failed: " + url); - } - }, - onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount) { - chunks.push(NetUtil.readInputStreamToString(aStream, aCount)); - }, - onStopRequest: function(aRequest, aContext, aStatusCode) { - if (!Components.isSuccessCode(aStatusCode)) { - deferred.reject("Request failed: " + url); - return; - } - - charset = channel.contentCharset; - deferred.resolve(chunks.join("")); - } - }; - - channel.loadFlags = aOptions.loadFromCache - ? channel.LOAD_FROM_CACHE - : channel.LOAD_BYPASS_CACHE; - channel.asyncOpen(streamListener, null); - break; - } - - return deferred.promise.then(function (source) { - return convertToUnicode(source, charset); - }); -} - -/** - * Convert a given string, encoded in a given character set, to unicode. - * - * @param string aString - * A string. - * @param string aCharset - * A character set. - */ -function convertToUnicode(aString, aCharset=null) { - // Decoding primitives. - // let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - // .createInstance(Ci.nsIScriptableUnicodeConverter); - // try { - // converter.charset = aCharset || "UTF-8"; - // return converter.ConvertToUnicode(aString); - // } catch(e) { - return aString; - // } -} - -/** - * Report the given error in the error console and to stdout. - */ -function reportError(aError) { - // Cu.reportError(aError); - dumpn(aError.message + ":\n" + aError.stack); -} diff --git a/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id new file mode 100644 index 0000000000..8f144050f7 --- /dev/null +++ b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id @@ -0,0 +1 @@ +c318c72ef4ee9c141e846d261e63250a0328bca4 \ No newline at end of file diff --git a/cocos/scripting/javascript/script/debugger/main.js b/cocos/scripting/javascript/script/debugger/main.js index f08009ade6..c6437e7922 100644 --- a/cocos/scripting/javascript/script/debugger/main.js +++ b/cocos/scripting/javascript/script/debugger/main.js @@ -10,26 +10,27 @@ * debugging global. */ -//const Ci = Components.interfaces; -//const Cc = Components.classes; -//const CC = Components.Constructor; -//const Cu = Components.utils; -//const Cr = Components.results; -//const DBG_STRINGS_URI = "chrome://global/locale/devtools/debugger.properties"; -// -//Cu.import("resource://gre/modules/Services.jsm"); -//Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -//let wantLogging = Services.prefs.getBoolPref("devtools.debugger.log"); -// -//Cu.import("resource://gre/modules/jsdebugger.jsm"); -//addDebuggerToGlobal(this); -// -//Cu.import("resource://gre/modules/commonjs/sdk/core/promise.js"); -//const { defer, resolve, reject, all } = Promise; -// -//Cu.import("resource://gre/modules/devtools/SourceMap.jsm"); -// -//loadSubScript.call(this, "resource://gre/modules/devtools/DevToolsUtils.js"); +/* +const Ci = Components.interfaces; +const Cc = Components.classes; +const CC = Components.Constructor; +const Cu = Components.utils; +const Cr = Components.results; +const DBG_STRINGS_URI = "chrome://global/locale/devtools/debugger.properties"; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +let wantLogging = Services.prefs.getBoolPref("devtools.debugger.log"); + +Cu.import("resource://gre/modules/jsdebugger.jsm"); +addDebuggerToGlobal(this); + +loadSubScript.call(this, "resource://gre/modules/commonjs/sdk/core/promise.js"); + +Cu.import("resource://gre/modules/devtools/SourceMap.jsm"); + +loadSubScript.call(this, "resource://gre/modules/devtools/DevToolsUtils.js"); +*/ let wantLogging = true; let debuggerServer = null; @@ -127,7 +128,7 @@ var DebuggerServer = { _initialized: false, _transportInitialized: false, xpcInspector: null, - _transport: null, + _transport: null, // James added // Number of currently open TCP connections. _socketConnections: 0, // Map of global actor names to actor constructors provided by extensions. @@ -145,6 +146,13 @@ var DebuggerServer = { */ _allowConnection: null, + /** + * The windowtype of the chrome window to use for actors that use the global + * window (i.e the global style editor). Set this to your main window type, + * for example "navigator:browser". + */ + chromeWindowType: null, + /** * Prompt the user to accept or decline the incoming connection. This is the * default implementation that products embedding the debugger server may @@ -217,11 +225,11 @@ var DebuggerServer = { get initialized() this._initialized, /** - * Performs cleanup tasks before shutting down the debugger server, if no - * connections are currently open. Such tasks include clearing any actor - * constructors added at runtime. This method should be called whenever a - * debugger server is no longer useful, to avoid memory leaks. After this - * method returns, the debugger server must be initialized again before use. + * Performs cleanup tasks before shutting down the debugger server. Such tasks + * include clearing any actor constructors added at runtime. This method + * should be called whenever a debugger server is no longer useful, to avoid + * memory leaks. After this method returns, the debugger server must be + * initialized again before use. */ destroy: function DS_destroy() { if (!this._initialized) { @@ -302,6 +310,7 @@ var DebuggerServer = { * Install Firefox-specific actors. */ addBrowserActors: function DS_addBrowserActors() { + this.chromeWindowType = "navigator:browser"; this.addActors("resource://gre/modules/devtools/server/actors/webbrowser.js"); this.addActors("resource://gre/modules/devtools/server/actors/script.js"); this.addGlobalActor(this.ChromeDebuggerActor, "chromeDebugger"); @@ -313,6 +322,27 @@ var DebuggerServer = { this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); this.addActors("resource://gre/modules/devtools/server/actors/webapps.js"); this.registerModule("devtools/server/actors/inspector"); + this.registerModule("devtools/server/actors/tracer"); + }, + + /** + * Install tab actors in documents loaded in content childs + */ + addChildActors: function () { + // In case of apps being loaded in parent process, DebuggerServer is already + // initialized and browser actors are already loaded, + // but childtab.js hasn't been loaded yet. + if (!("BrowserTabActor" in this)) { + this.addActors("resource://gre/modules/devtools/server/actors/webbrowser.js"); + this.addActors("resource://gre/modules/devtools/server/actors/script.js"); + this.addActors("resource://gre/modules/devtools/server/actors/webconsole.js"); + this.addActors("resource://gre/modules/devtools/server/actors/gcli.js"); + this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); + this.registerModule("devtools/server/actors/inspector"); + } + if (!("ContentTabActor" in DebuggerServer)) { + this.addActors("resource://gre/modules/devtools/server/actors/childtab.js"); + } }, /** @@ -339,7 +369,6 @@ var DebuggerServer = { // } let flags = 0; - try { let socket = new ServerSocket(aPort, flags, 4); socket.asyncListen(this); @@ -381,16 +410,19 @@ var DebuggerServer = { * transport. This connection results in straightforward calls to the onPacket * handlers of each side. * + * @param aPrefix string [optional] + * If given, all actors in this connection will have names starting + * with |aPrefix + ':'|. * @returns a client-side DebuggerTransport for communicating with - * the newly-created connection. + * the newly-created connection. */ - connectPipe: function DS_connectPipe() { + connectPipe: function DS_connectPipe(aPrefix) { this._checkInit(); let serverTransport = new LocalDebuggerTransport; let clientTransport = new LocalDebuggerTransport(serverTransport); serverTransport.other = clientTransport; - let connection = this._onConnection(serverTransport); + let connection = this._onConnection(serverTransport, aPrefix); // I'm putting this here because I trust you. // @@ -412,6 +444,22 @@ var DebuggerServer = { return clientTransport; }, + /** + * In a content child process, create a new connection that exchanges + * nsIMessageSender messages with our parent process. + * + * @param aPrefix + * The prefix we should use in our nsIMessageSender message names and + * actor names. This connection will use messages named + * "debug::packet", and all its actors will have names + * beginning with ":". + */ + connectToParent: function(aPrefix, aMessageManager) { + this._checkInit(); + + let transport = new ChildDebuggerTransport(aMessageManager, aPrefix); + return this._onConnection(transport, aPrefix, true); + }, // nsIServerSocketListener implementation @@ -446,23 +494,36 @@ var DebuggerServer = { }, /** - * Create a new debugger connection for the given transport. Called - * after connectPipe() or after an incoming socket connection. + * Create a new debugger connection for the given transport. Called after + * connectPipe(), from connectToParent, or from an incoming socket + * connection handler. + * + * If present, |aForwardingPrefix| is a forwarding prefix that a parent + * server is using to recognizes messages intended for this server. Ensure + * that all our actors have names beginning with |aForwardingPrefix + ':'|. + * In particular, the root actor's name will be |aForwardingPrefix + ':root'|. */ - _onConnection: function DS_onConnection(aTransport) { - log("DebuggerServer._onConnection...."); - + _onConnection: function DS_onConnection(aTransport, aForwardingPrefix, aNoRootActor = false) { + let connID; this._transport = aTransport; - - let connID = "conn" + this._nextConnID++ + '.'; + if (aForwardingPrefix) { + connID = aForwardingPrefix + ":"; + } else { + connID = "conn" + this._nextConnID++ + '.'; + } let conn = new DebuggerServerConnection(connID, aTransport); this._connections[connID] = conn; // Create a root actor for the connection and send the hello packet. - conn.rootActor = this.createRootActor(conn); - conn.addActor(conn.rootActor); - - aTransport.send(conn.rootActor.sayHello()); + if (!aNoRootActor) { + conn.rootActor = this.createRootActor(conn); + if (aForwardingPrefix) + conn.rootActor.actorID = aForwardingPrefix + ":root"; + else + conn.rootActor.actorID = "root"; + conn.addActor(conn.rootActor); + aTransport.send(conn.rootActor.sayHello()); + } aTransport.ready(); return conn; @@ -676,6 +737,14 @@ function DebuggerServerConnection(aPrefix, aTransport) this._actorPool = new ActorPool(this); this._extraPools = []; + + /* + * We can forward packets to other servers, if the actors on that server + * all use a distinct prefix on their names. This is a map from prefixes + * to transports: it maps a prefix P to a transport T if T conveys + * packets to the server whose actors' names all begin with P + ":". + */ + this._forwardingPrefixes = new Map; } DebuggerServerConnection.prototype = { @@ -788,6 +857,35 @@ DebuggerServerConnection.prototype = { }; }, + /* Forwarding packets to other transports based on actor name prefixes. */ + + /* + * Arrange to forward packets to another server. This is how we + * forward debugging connections to child processes. + * + * If we receive a packet for an actor whose name begins with |aPrefix| + * followed by ':', then we will forward that packet to |aTransport|. + * + * This overrides any prior forwarding for |aPrefix|. + * + * @param aPrefix string + * The actor name prefix, not including the ':'. + * @param aTransport object + * A packet transport to which we should forward packets to actors + * whose names begin with |(aPrefix + ':').| + */ + setForwarding: function(aPrefix, aTransport) { + this._forwardingPrefixes.set(aPrefix, aTransport); + }, + + /* + * Stop forwarding messages to actors whose names begin with + * |aPrefix+':'|. Such messages will now elicit 'noSuchActor' errors. + */ + cancelForwarding: function(aPrefix) { + this._forwardingPrefixes.delete(aPrefix); + }, + // Transport hooks. /** @@ -797,6 +895,26 @@ DebuggerServerConnection.prototype = { * The incoming packet. */ onPacket: function DSC_onPacket(aPacket) { + // If the actor's name begins with a prefix we've been asked to + // forward, do so. + // + // Note that the presence of a prefix alone doesn't indicate that + // forwarding is needed: in DebuggerServerConnection instances in child + // processes, every actor has a prefixed name. + + log("aPacket: " + aPacket); + + if (this._forwardingPrefixes.size > 0) { + let colon = aPacket.to.indexOf(':'); + if (colon >= 0) { + let forwardTo = this._forwardingPrefixes.get(aPacket.to.substring(0, colon)); + if (forwardTo) { + forwardTo.send(aPacket); + return; + } + } + } + let actor = this.getActor(aPacket.to); if (!actor) { this.transport.send({ from: aPacket.to ? aPacket.to : "root", @@ -824,7 +942,6 @@ DebuggerServerConnection.prototype = { } var ret = null; - // log("actor.requestTypes: "+actor.requestTypes+", cb: "+actor.requestTypes[aPacket.type]); // Dispatch the request to the actor. if (actor.requestTypes && actor.requestTypes[aPacket.type]) { try { @@ -851,18 +968,18 @@ DebuggerServerConnection.prototype = { } resolve(ret) - .then(null, (e) => { - return this._unknownError( - "error occurred while processing '" + aPacket.type, - e); - }) .then(function (aResponse) { if (!aResponse.from) { aResponse.from = aPacket.to; } return aResponse; }) - .then(this.transport.send.bind(this.transport)); + .then(this.transport.send.bind(this.transport)) + .then(null, (e) => { + return this._unknownError( + "error occurred while processing '" + aPacket.type, + e); + }); }, /** diff --git a/cocos/scripting/javascript/script/debugger/transport.js b/cocos/scripting/javascript/script/debugger/transport.js index 8676e367a8..b5de443a06 100644 --- a/cocos/scripting/javascript/script/debugger/transport.js +++ b/cocos/scripting/javascript/script/debugger/transport.js @@ -11,6 +11,8 @@ * An adapter that handles data transfers between the debugger client and * server. It can work with both nsIPipe and nsIServerSocket transports so * long as the properly created input and output streams are specified. + * (However, for intra-process connections, LocalDebuggerTransport, below, + * is more efficient than using an nsIPipe pair with DebuggerTransport.) * * @param aInput nsIInputStream * The input stream. @@ -20,12 +22,12 @@ * Given a DebuggerTransport instance dt: * 1) Set dt.hooks to a packet handler object (described below). * 2) Call dt.ready() to begin watching for input packets. - * 3) Send packets as you please, and handle incoming packets passed to - * hook.onPacket. + * 3) Call dt.send() to send packets as you please, and handle incoming + * packets passed to hook.onPacket. * 4) Call dt.close() to close the connection, and disengage from the event * loop. * - * A packet handler object is an object with two methods: + * A packet handler is an object with two methods: * * - onPacket(packet) - called when we have received a complete packet. * |Packet| is the parsed form of the packet --- a JavaScript value, not @@ -226,10 +228,11 @@ LocalDebuggerTransport.prototype = { send: function LDT_send(aPacket) { let serial = this._serial.count++; if (wantLogging) { - if (aPacket.to) { - dumpn("Packet " + serial + " sent to " + uneval(aPacket.to)); - } else if (aPacket.from) { + /* Check 'from' first, as 'echo' packets have both. */ + if (aPacket.from) { dumpn("Packet " + serial + " sent from " + uneval(aPacket.from)); + } else if (aPacket.to) { + dumpn("Packet " + serial + " sent to " + uneval(aPacket.to)); } } this._deepFreeze(aPacket); @@ -259,7 +262,11 @@ LocalDebuggerTransport.prototype = { other.close(); } if (this.hooks) { - this.hooks.onClosed(); + try { + this.hooks.onClosed(); + } catch(ex) { + Components.utils.reportError(ex); + } this.hooks = null; } }, @@ -286,3 +293,50 @@ LocalDebuggerTransport.prototype = { } } }; + +/** + * A transport for the debugging protocol that uses nsIMessageSenders to + * exchange packets with servers running in child processes. + * + * In the parent process, |aSender| should be the nsIMessageSender for the + * child process. In a child process, |aSender| should be the child process + * message manager, which sends packets to the parent. + * + * aPrefix is a string included in the message names, to distinguish + * multiple servers running in the same child process. + * + * This transport exchanges messages named 'debug::packet', where + * is |aPrefix|, whose data is the protocol packet. + */ +function ChildDebuggerTransport(aSender, aPrefix) { + this._sender = aSender.QueryInterface(Components.interfaces.nsIMessageSender); + this._messageName = "debug:" + aPrefix + ":packet"; +} + +/* + * To avoid confusion, we use 'message' to mean something that + * nsIMessageSender conveys, and 'packet' to mean a remote debugging + * protocol packet. + */ +ChildDebuggerTransport.prototype = { + constructor: ChildDebuggerTransport, + + hooks: null, + + ready: function () { + this._sender.addMessageListener(this._messageName, this); + }, + + close: function () { + this._sender.removeMessageListener(this._messageName, this); + this.hooks.onClosed(); + }, + + receiveMessage: function ({data}) { + this.hooks.onPacket(data); + }, + + send: function (packet) { + this._sender.sendAsyncMessage(this._messageName, packet); + } +}; From d2fc29dbfad3ba3d602949df816c8f3f23f2692e Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 10:29:20 +0800 Subject: [PATCH 294/557] [sp v25] Updating Debugger script. --- .../javascript/script/debugger/actors/script.js.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id index 8f144050f7..802edb4902 100644 --- a/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id +++ b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id @@ -1 +1 @@ -c318c72ef4ee9c141e846d261e63250a0328bca4 \ No newline at end of file +85c713e3bdd74f54afb60036b9c11f754c55e267 \ No newline at end of file From 541a0478acbdc9a7574a2b5d27e32b0a0ac9cdfa Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 10:29:49 +0800 Subject: [PATCH 295/557] [sp v25] Removing unused comments in main.js --- cocos/scripting/javascript/script/debugger/main.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/cocos/scripting/javascript/script/debugger/main.js b/cocos/scripting/javascript/script/debugger/main.js index c6437e7922..2c57735dbf 100644 --- a/cocos/scripting/javascript/script/debugger/main.js +++ b/cocos/scripting/javascript/script/debugger/main.js @@ -902,8 +902,6 @@ DebuggerServerConnection.prototype = { // forwarding is needed: in DebuggerServerConnection instances in child // processes, every actor has a prefixed name. - log("aPacket: " + aPacket); - if (this._forwardingPrefixes.size > 0) { let colon = aPacket.to.indexOf(':'); if (colon >= 0) { From 0f7a99f8986c7e7d3961aab6f4c057c79dcec0b7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 11:07:33 +0800 Subject: [PATCH 296/557] [sp v25] Don't use 'using namespace std;' to make android build happy. --- .../javascript/bindings/ScriptingCore.cpp | 20 +++++++++---------- .../javascript/bindings/ScriptingCore.h | 5 ++--- .../bindings/network/XMLHTTPRequest.h | 4 ++-- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 6a8ac7dd98..9756be492a 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -54,9 +54,9 @@ #define BYTE_CODE_FILE_EXT ".jsc" -static string inData; -static string outData; -static vector g_queue; +static std::string inData; +static std::string outData; +static std::vector g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; @@ -1964,8 +1964,8 @@ void SimpleRunLoop::update(float dt) while (size > 0) { g_qMutex.lock(); - vector::iterator first = g_queue.begin(); - string str = *first; + auto first = g_queue.begin(); + std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); @@ -1974,7 +1974,7 @@ void SimpleRunLoop::update(float dt) } } -void ScriptingCore::debugProcessInput(string str) +void ScriptingCore::debugProcessInput(const std::string& str) { JSAutoCompartment ac(_cx, _debugGlobal); @@ -1994,8 +1994,8 @@ static bool NS_ProcessNextEvent() while (size > 0) { g_qMutex.lock(); - vector::iterator first = g_queue.begin(); - string str = *first; + auto first = g_queue.begin(); + std::string str = *first; g_queue.erase(first); size = g_queue.size(); g_qMutex.unlock(); @@ -2060,7 +2060,7 @@ static void _clientSocketWriteAndClearString(std::string& s) s.clear(); } -static void processInput(string data) { +static void processInput(const std::string& data) { std::lock_guard lk(g_qMutex); g_queue.push_back(data); } @@ -2087,7 +2087,7 @@ static void serverEntryPoint(void) hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me - stringstream portstr; + std::stringstream portstr; portstr << JSB_DEBUGGER_PORT; int err = 0; diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 769be86cfa..8df12fddc6 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -21,7 +21,6 @@ void js_log(const char *format, ...); using namespace cocos2d; -using namespace std; typedef void (*sc_register_sth)(JSContext* cx, JSObject* global); @@ -189,7 +188,7 @@ public: /** * enable the debug environment */ - void debugProcessInput(string str); + void debugProcessInput(const std::string& str); void enableDebugger(); JSObject* getDebugGlobal() { return _debugGlobal; } JSObject* getGlobalObject() { return _global; } @@ -230,7 +229,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition* ret ); jsval int32_to_jsval( JSContext *cx, int32_t l); jsval uint32_to_jsval( JSContext *cx, uint32_t number ); jsval long_long_to_jsval(JSContext* cx, long long v); -jsval std_string_to_jsval(JSContext* cx, const string& v); +jsval std_string_to_jsval(JSContext* cx, const std::string& v); jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); jsval ccpoint_to_jsval(JSContext* cx, const Point& v); jsval ccrect_to_jsval(JSContext* cx, const Rect& v); diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h index 861e0a2536..93951313f4 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -105,8 +105,8 @@ private: network::HttpRequest* _httpRequest; bool _isNetwork; bool _withCredentialsValue; - std::map _httpHeader; - std::map _requestHeader; + std::map _httpHeader; + std::map _requestHeader; }; #endif From 69b02060187e5b51240484751bd77c0864053372 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 11:24:43 +0800 Subject: [PATCH 297/557] issue #2826: Updating vs project to link mozjs-25.lib --- .../AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj | 4 ++-- .../Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj | 4 ++-- .../Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj | 4 ++-- .../Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj | 4 ++-- .../TestJavascript/proj.win32/TestJavascript.vcxproj | 4 ++-- .../WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj | 4 ++-- template/multi-platform-js/proj.win32/HelloJavascript.vcxproj | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj index b46bf264ae..7851565229 100644 --- a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj +++ b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) + mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) + mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj index 8483cb7237..2e7cc9a5d5 100644 --- a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj +++ b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj index 6194bc0354..36fd882002 100644 --- a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj +++ b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj index 08efa5fdba..d0dfa15e88 100644 --- a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj +++ b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -155,7 +155,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj b/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj index 1af52eccb0..f6e517fc8f 100644 --- a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj +++ b/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj @@ -103,7 +103,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -159,7 +159,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj index 48f07febfb..0f76fa0e57 100644 --- a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj +++ b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj index 26bab7731b..35da6b1ee0 100644 --- a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj +++ b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj @@ -102,7 +102,7 @@ xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-23.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 From c116d070d30aeaea499dd97fb81a4b9a6ad722d5 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 31 Oct 2013 14:16:42 +0800 Subject: [PATCH 298/557] Closed #3048: cc.rect can receiving different type parameters now --- cocos/scripting/javascript/script/jsb_cocos2d.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index 684eb386d9..3362e78650 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -235,7 +235,19 @@ cc.sizeEqualToSize = function (size1, size2) // cc.rect = function(x,y,w,h) { - return {x:x, y:y, width:w, height:h}; + if (arguments.length === 0) + return { x: 0, y: 0, width: 0, height: 0 }; + + if (arguments.length === 1) + return { x: x.x, y: x.y, width: x.width, height: x.height }; + + if (arguments.length === 2) + return { x: x.x, y: x.y, width: y.width, height: y.height }; + + if (arguments.length === 4) + return { x: x, y: y, width: w, height: h }; + + throw "unknown argument type"; }; cc._rect = function(x,y,w,h) { From f172abbc1418b726f0f627047d9bf4db8c335635 Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 31 Oct 2013 14:31:25 +0800 Subject: [PATCH 299/557] fixed #3048: add some comments for cc.rect --- cocos/scripting/javascript/script/jsb_cocos2d.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index 3362e78650..a5dd86d282 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -230,9 +230,14 @@ cc.sizeEqualToSize = function (size1, size2) return ((size1.width == size2.width) && (size1.height == size2.height)); }; -// -// Rect -// +/** + * create a rect object + * @param {Number|cc.Point|cc.Rect} [x1] a Number value as x or a cc.Point object as origin or a cc.Rect clone object + * @param {Number|cc.Size} [y1] x1 a Number value as y or a cc.Size object as size + * @param {Number} [width1] + * @param {Number} [height1] + * @return {Object} a Rect object + */ cc.rect = function(x,y,w,h) { if (arguments.length === 0) From 7e8faed7aff38136491ee18387b453e26b22a93c Mon Sep 17 00:00:00 2001 From: dingpinglv Date: Thu, 31 Oct 2013 14:36:17 +0800 Subject: [PATCH 300/557] fixed #3048: rename some comments --- .../javascript/script/jsb_cocos2d.js | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index a5dd86d282..5689a7a51e 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -231,25 +231,26 @@ cc.sizeEqualToSize = function (size1, size2) }; /** - * create a rect object - * @param {Number|cc.Point|cc.Rect} [x1] a Number value as x or a cc.Point object as origin or a cc.Rect clone object - * @param {Number|cc.Size} [y1] x1 a Number value as y or a cc.Size object as size - * @param {Number} [width1] - * @param {Number} [height1] - * @return {Object} a Rect object + * create a cc.rect object + * @param {Number|cc.point|cc.rect} [x] a Number value as x or a cc.point object as origin or a cc.rect clone object + * @param {Number|cc.size} [y] x1 a Number value as y or a cc.size object as size + * @param {Number} [w] + * @param {Number} [h] + * @return {Object} a cc.rect object */ cc.rect = function(x,y,w,h) { - if (arguments.length === 0) + var argLen = arguments.length; + if (argLen === 0) return { x: 0, y: 0, width: 0, height: 0 }; - if (arguments.length === 1) + if (argLen === 1) return { x: x.x, y: x.y, width: x.width, height: x.height }; - if (arguments.length === 2) + if (argLen === 2) return { x: x.x, y: x.y, width: y.width, height: y.height }; - if (arguments.length === 4) + if (argLen === 4) return { x: x, y: y, width: w, height: h }; throw "unknown argument type"; From a27975763ff00c41eed76b2c3348d1da03dbdc08 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Thu, 31 Oct 2013 00:04:39 -0700 Subject: [PATCH 301/557] Add MouseEvent to win32 build --- cocos/2d/cocos2d.vcxproj | 4 ++++ cocos/2d/cocos2d.vcxproj.filters | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index a7f030bb9f..a59611bc90 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -243,7 +243,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + + @@ -414,7 +416,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 2028e708c8..493e1dc747 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -572,6 +572,12 @@ support + + event_dispatcher + + + event_dispatcher + @@ -1152,5 +1158,11 @@ base + + event_dispatcher + + + event_dispatcher + \ No newline at end of file From 6f978c5cbd823fdcb87fcb1f5e5016cfc6dd5f87 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 15:13:49 +0800 Subject: [PATCH 302/557] issue #2826: Bug fixes after using Spidermonkey v25. Adding JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET macro. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 9 ++++++++- .../bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/extension/jsb_cocos2dx_extension_manual.cpp | 1 + cocos/scripting/javascript/bindings/js_bindings_config.h | 3 +++ .../scripting/javascript/bindings/js_bindings_opengl.cpp | 3 +-- .../javascript/bindings/network/XMLHTTPRequest.cpp | 1 + .../javascript/bindings/network/jsb_websocket.cpp | 8 ++++++++ 7 files changed, 23 insertions(+), 4 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 9756be492a..03c140036c 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -176,6 +176,8 @@ void ScriptingCore::executeJSFunctionWithThisObj(jsval thisObj, { if (callback != JSVAL_VOID || thisObj != JSVAL_VOID) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + // 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'. @@ -1076,6 +1078,8 @@ int ScriptingCore::executeCustomTouchesEvent(EventTouch::EventCode eventType, int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, Touch *pTouch, JSObject *obj) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + jsval retval; std::string funcName; getTouchFuncName(eventType, funcName); @@ -1096,7 +1100,8 @@ int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, Touch *pTouch, JSObject *obj, jsval &retval) { - + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + std::string funcName; getTouchFuncName(eventType, funcName); @@ -1791,6 +1796,8 @@ jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) return JSVAL_NULL; } + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + if (0 == length) { auto emptyStr = JS_NewStringCopyZ(cx, ""); diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 4308bf2a80..39e01fd1ef 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -8a34b565b95d3bdd2cf1dad5b70729544004a35d \ No newline at end of file +c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp index e46bc688f8..5980940918 100644 --- a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp @@ -258,6 +258,7 @@ public: } if (ok) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); Size size; JSBool isSucceed = jsval_to_ccsize(cx, ret, &size); diff --git a/cocos/scripting/javascript/bindings/js_bindings_config.h b/cocos/scripting/javascript/bindings/js_bindings_config.h index 98d5feb954..b4a5702029 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_config.h +++ b/cocos/scripting/javascript/bindings/js_bindings_config.h @@ -144,6 +144,9 @@ JSAutoCompartment ac(cx, obj) #define JSB_ENSURE_AUTOCOMPARTMENT(cx, obj) #endif +#define JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET \ +JSAutoCompartment __jsb_ac(ScriptingCore::getInstance()->getGlobalContext(), ScriptingCore::getInstance()->getGlobalObject()); + /** * @def JSB_DEBUGGER_PORT * The port number, where the client will be listening on diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index 6b08243875..9fbf145647 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -5,12 +5,11 @@ void GLNode::draw() { JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); proxy = js_get_or_create_proxy(cx, this); - //JSB_CCNode *proxy = objc_getAssociatedObject(self, &JSB_association_proxy_key); if( proxy ) { JSObject *jsObj = proxy->obj; if (jsObj) { JSBool found; - JSB_ENSURE_AUTOCOMPARTMENT(cx, jsObj); + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JS_HasProperty(cx, jsObj, "draw", &found); if (found == JS_TRUE) { JS::RootedValue rval(cx); diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index 1879b5417d..e3a0ba5b18 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -231,6 +231,7 @@ void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, netw if (_onreadystateCallback) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx); jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback); jsval out; diff --git a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp index 8497cd35e3..ae3b1c64ce 100644 --- a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp +++ b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp @@ -67,6 +67,8 @@ public: js_proxy_t * p = jsb_get_native_proxy(ws); if (!p) return; + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); JS::RootedValue vp(cx); @@ -83,6 +85,8 @@ public: js_proxy_t * p = jsb_get_native_proxy(ws); if (!p) return; + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); JS::RootedValue vp(cx); @@ -115,6 +119,8 @@ public: js_proxy_t * p = jsb_get_native_proxy(ws); if (!p) return; + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); JS::RootedValue vp(cx); @@ -135,6 +141,8 @@ public: js_proxy_t * p = jsb_get_native_proxy(ws); if (!p) return; + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* jsobj = JS_NewObject(cx, NULL, NULL, NULL); JS::RootedValue vp(cx); From f478e2d2a5ddb2c73db181841bbf382ab5e31151 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 15:15:52 +0800 Subject: [PATCH 303/557] issue #2826: Bug fixes for win32. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 8 ++++++++ external/spidermonkey/include/win32/jspubtd.h | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 03c140036c..59fe928dde 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -79,6 +79,14 @@ static std::map ports_sockets; // name ~> globals static std::map globals; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +namespace js { +bool IsInRequest(JSContext* cx) +{ + return true; +} +} +#endif static void ReportException(JSContext *cx) { diff --git a/external/spidermonkey/include/win32/jspubtd.h b/external/spidermonkey/include/win32/jspubtd.h index 96f5dd8297..3ff5b3428c 100644 --- a/external/spidermonkey/include/win32/jspubtd.h +++ b/external/spidermonkey/include/win32/jspubtd.h @@ -16,7 +16,7 @@ #include "jsprototypes.h" #include "jstypes.h" -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || (defined(DEBUG) && !defined(_WIN32)) # define JSGC_TRACK_EXACT_ROOTS #endif From faf3b30e9bfa35daa1db109c83e7d9f5e23373c2 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 15:20:53 +0800 Subject: [PATCH 304/557] issue #3069:Add LuaObjectCBridge and related test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../bindings/platform/ios/CCLuaObjcBridge.mm | 2 +- cocos/scripting/lua/script/luaoc.lua | 28 +++++++ .../luaScript/LuaBridgeTest/LuaBridgeTest.lua | 30 ++++++- .../TestLua/Resources/luaScript/mainMenu.lua | 4 +- .../TestLua/proj.ios/LuaObjectCBridgeTest.h | 20 +++++ .../TestLua/proj.ios/LuaObjectCBridgeTest.mm | 81 +++++++++++++++++++ .../TestLua/proj.mac/LuaObjectCBridgeTest.h | 20 +++++ .../TestLua/proj.mac/LuaObjectCBridgeTest.mm | 81 +++++++++++++++++++ 10 files changed, 264 insertions(+), 6 deletions(-) create mode 100644 cocos/scripting/lua/script/luaoc.lua create mode 100644 samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h create mode 100644 samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm create mode 100644 samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h create mode 100644 samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 17e0cee1da..4b66f8ecfe 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b695026fc3d856d540590ff09112696f66379c22 \ No newline at end of file +2fc86c9b16a099b711aabd5d29f835c45a1690a4 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 70bb169acc..3a1978b2ff 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -83265c81797ca614f19372a96adf326aeb21b396 \ No newline at end of file +3cdc74655a14f57ae21036886ccf31e32aaadce4 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm b/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm index 421b85c5b7..74487cee44 100644 --- a/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm +++ b/cocos/scripting/lua/bindings/platform/ios/CCLuaObjcBridge.mm @@ -10,7 +10,7 @@ void LuaObjcBridge::luaopen_luaoc(lua_State *L) lua_pushstring(L, "callStaticMethod"); lua_pushcfunction(L, LuaObjcBridge::callObjcStaticMethod); lua_rawset(L, -3); - lua_setglobal(L, "CCLuaObjcBridge"); + lua_setglobal(L, "LuaObjcBridge"); } /** diff --git a/cocos/scripting/lua/script/luaoc.lua b/cocos/scripting/lua/script/luaoc.lua new file mode 100644 index 0000000000..ff6d157c3b --- /dev/null +++ b/cocos/scripting/lua/script/luaoc.lua @@ -0,0 +1,28 @@ + +local luaoc = {} + +local callStaticMethod = LuaObjcBridge.callStaticMethod + +function luaoc.callStaticMethod(className, methodName, args) + local ok, ret = callStaticMethod(className, methodName, args) + if not ok then + local msg = string.format("luaoc.callStaticMethod(\"%s\", \"%s\", \"%s\") - error: [%s] ", + className, methodName, tostring(args), tostring(ret)) + if ret == -1 then + print(msg .. "INVALID PARAMETERS") + elseif ret == -2 then + print(msg .. "CLASS NOT FOUND") + elseif ret == -3 then + print(msg .. "METHOD NOT FOUND") + elseif ret == -4 then + print(msg .. "EXCEPTION OCCURRED") + elseif ret == -5 then + print(msg .. "INVALID METHOD SIGNATURE") + else + print(msg .. "UNKNOWN") + end + end + return ok, ret +end + +return luaoc diff --git a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua b/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua index 2cc9b17568..dd149a00d5 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua @@ -66,7 +66,7 @@ local function LuaBridgeLayer() if not ok then print("luaj error:", ret) else - print("luaj ret:", ret) + print("The ret is:", ret) end local function callbackLua(param) @@ -86,6 +86,34 @@ local function LuaBridgeLayer() local function newLuaObjectCBridge() local newScene = cc.Scene:create() + local titleLabel = cc.LabelTTF:create("", "Arial", 28) + newScene:addChild(titleLabel, 1) + titleLabel:setPosition(s.width / 2, s.height - 50) + titleLabel:setString("LuaObjectCBridge Test") + + subtitleLabel = cc.LabelTTF:create("", "Thonburi", 16) + newScene:addChild(subtitleLabel, 1) + subtitleLabel:setPosition(s.width / 2, s.height - 80) + subtitleLabel:setString("See the console.") + if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_MAC == targetPlatform) then + local args = { num1 = 2 , num2 = 3 } + local luaoc = require "luaoc" + local className = "LuaObjectCBridgeTest" + local ok,ret = luaoc.callStaticMethod(className,"addTwoNumbers",args) + if not ok then + Director:getInstance():resume() + else + print("The ret is:", ret) + end + + local function callback(param) + if "success" == param then + print("object c call back success") + end + end + luaoc.callStaticMethod(className,"registerScriptHandler", {scriptHandler = callback } ) + luaoc.callStaticMethod(className,"callbackScriptHandler") + end return newScene end diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua index 73d79855d6..c1c5088530 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua @@ -75,6 +75,7 @@ local _allTests = { { isSupported = true, name = "KeypadTest" , create_func= KeypadTestMain }, { isSupported = true, name = "LabelTest" , create_func = LabelTest }, { isSupported = true, name = "LayerTest" , create_func = LayerTestMain }, + { isSupported = true, name = "LuaBridgeTest" , create_func = LuaBridgeMainTest }, { isSupported = true, name = "MenuTest" , create_func = MenuTestMain }, { isSupported = true, name = "MotionStreakTest" , create_func = MotionStreakTest }, { isSupported = false, name = "MutiTouchTest" , create_func= MutiTouchTestMain }, @@ -96,8 +97,7 @@ local _allTests = { { isSupported = true, name = "TouchesTest" , create_func = TouchesTest }, { isSupported = true, name = "TransitionsTest" , create_func = TransitionsTest }, { isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain }, - { isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain }, - { isSupported = true, name = "LuaBridgeTest" , create_func = LuaBridgeMainTest } + { isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain } } local TESTS_COUNT = table.getn(_allTests) diff --git a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h new file mode 100644 index 0000000000..882dab3ed7 --- /dev/null +++ b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h @@ -0,0 +1,20 @@ +#ifndef COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H +#define COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H +#import + +@interface LuaObjectCBridgeTest : NSObject { + int _scriptHandler; +} ++ (LuaObjectCBridgeTest*) getInstance; ++ (void) destroyInstance; + ++ (void) registerScriptHandler:(NSDictionary *)dict; ++ (void) unregisterScriptHandler; + ++ (int) addTwoNumbers:(NSDictionary *)dict; ++ (void) callbackScriptHandler; + +- (void) init; +@end + +#endif // COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H diff --git a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm new file mode 100644 index 0000000000..efed273add --- /dev/null +++ b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm @@ -0,0 +1,81 @@ +#import "LuaObjectCBridgeTest.h" + +#include "cocos2d.h" +#include "CCLuaEngine.h" +#include "CCLuaBridge.h" + +using namespace cocos2d; + +@implementation LuaObjectCBridgeTest + +static LuaObjectCBridgeTest* s_instance = nil; + ++ (LuaObjectCBridgeTest*) getInstance +{ + if (!s_instance) + { + s_instance = [LuaObjectCBridgeTest alloc]; + [s_instance init]; + } + + return s_instance; +} + ++ (void) destroyInstance +{ + [s_instance release]; +} + +- (void) setScriptHandler:(int)scriptHandler +{ + if (_scriptHandler) + { + LuaBridge::releaseLuaFunctionById(_scriptHandler); + _scriptHandler = 0; + } + _scriptHandler = scriptHandler; +} + +- (int) getScriptHandler +{ + return _scriptHandler; +} + + ++(void) registerScriptHandler:(NSDictionary *)dict +{ + [[LuaObjectCBridgeTest getInstance] setScriptHandler:[[dict objectForKey:@"scriptHandler"] intValue]]; +} + + ++ (void) unregisterScriptHandler +{ + [[LuaObjectCBridgeTest getInstance] setScriptHandler:0]; +} + ++ (int) addTwoNumbers:(NSDictionary *)dict +{ + int num1 = [[dict objectForKey:@"num1"] intValue]; + int num2 = [[dict objectForKey:@"num2"] intValue]; + + return num1 + num2; +} + ++ (void) callbackScriptHandler +{ + int scriptHandler = [[LuaObjectCBridgeTest getInstance] getScriptHandler]; + if (scriptHandler) + { + LuaBridge::pushLuaFunctionById(scriptHandler); + LuaStack *stack = LuaBridge::getStack(); + stack->pushString("success"); + stack->executeFunction(1); + } +} + +- (void)init +{ + _scriptHandler = 0; +} + +@end \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h new file mode 100644 index 0000000000..882dab3ed7 --- /dev/null +++ b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h @@ -0,0 +1,20 @@ +#ifndef COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H +#define COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H +#import + +@interface LuaObjectCBridgeTest : NSObject { + int _scriptHandler; +} ++ (LuaObjectCBridgeTest*) getInstance; ++ (void) destroyInstance; + ++ (void) registerScriptHandler:(NSDictionary *)dict; ++ (void) unregisterScriptHandler; + ++ (int) addTwoNumbers:(NSDictionary *)dict; ++ (void) callbackScriptHandler; + +- (void) init; +@end + +#endif // COCOS2DX_SAMPLES_TESTLUA_PROJ_IOS_LUAOBJECTCBRIDGETEST_H diff --git a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm new file mode 100644 index 0000000000..efed273add --- /dev/null +++ b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm @@ -0,0 +1,81 @@ +#import "LuaObjectCBridgeTest.h" + +#include "cocos2d.h" +#include "CCLuaEngine.h" +#include "CCLuaBridge.h" + +using namespace cocos2d; + +@implementation LuaObjectCBridgeTest + +static LuaObjectCBridgeTest* s_instance = nil; + ++ (LuaObjectCBridgeTest*) getInstance +{ + if (!s_instance) + { + s_instance = [LuaObjectCBridgeTest alloc]; + [s_instance init]; + } + + return s_instance; +} + ++ (void) destroyInstance +{ + [s_instance release]; +} + +- (void) setScriptHandler:(int)scriptHandler +{ + if (_scriptHandler) + { + LuaBridge::releaseLuaFunctionById(_scriptHandler); + _scriptHandler = 0; + } + _scriptHandler = scriptHandler; +} + +- (int) getScriptHandler +{ + return _scriptHandler; +} + + ++(void) registerScriptHandler:(NSDictionary *)dict +{ + [[LuaObjectCBridgeTest getInstance] setScriptHandler:[[dict objectForKey:@"scriptHandler"] intValue]]; +} + + ++ (void) unregisterScriptHandler +{ + [[LuaObjectCBridgeTest getInstance] setScriptHandler:0]; +} + ++ (int) addTwoNumbers:(NSDictionary *)dict +{ + int num1 = [[dict objectForKey:@"num1"] intValue]; + int num2 = [[dict objectForKey:@"num2"] intValue]; + + return num1 + num2; +} + ++ (void) callbackScriptHandler +{ + int scriptHandler = [[LuaObjectCBridgeTest getInstance] getScriptHandler]; + if (scriptHandler) + { + LuaBridge::pushLuaFunctionById(scriptHandler); + LuaStack *stack = LuaBridge::getStack(); + stack->pushString("success"); + stack->executeFunction(1); + } +} + +- (void)init +{ + _scriptHandler = 0; +} + +@end \ No newline at end of file From 705da20ee729dc7b8a8d4ea061ad7380522e56c8 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 15:26:38 +0800 Subject: [PATCH 305/557] issue #2794:Add LuaObjectCBridge and related test sample --- samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm | 2 +- samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm index efed273add..624e338206 100644 --- a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm +++ b/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm @@ -78,4 +78,4 @@ static LuaObjectCBridgeTest* s_instance = nil; _scriptHandler = 0; } -@end \ No newline at end of file +@end diff --git a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm index efed273add..624e338206 100644 --- a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm +++ b/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm @@ -78,4 +78,4 @@ static LuaObjectCBridgeTest* s_instance = nil; _scriptHandler = 0; } -@end \ No newline at end of file +@end From 771844fc58420fbfbed09a2ad6c7cb9c6b3b6265 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Thu, 31 Oct 2013 00:40:38 -0700 Subject: [PATCH 306/557] Fix android build after adding MouseEvent and MouseTest --- cocos/2d/Android.mk | 2 ++ samples/Cpp/TestCpp/Android.mk | 1 + 2 files changed, 3 insertions(+) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 6a25764f44..75ff000786 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -39,6 +39,8 @@ CCEventAcceleration.cpp \ CCEventCustom.cpp \ CCEventDispatcher.cpp \ CCEventKeyboard.cpp \ +CCEventMouse.cpp \ +CCEventListenerMouse.cpp \ CCEventListener.cpp \ CCEventListenerAcceleration.cpp \ CCEventListenerCustom.cpp \ diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index c848586fbb..4fd63763d1 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -99,6 +99,7 @@ Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ Classes/FileUtilsTest/FileUtilsTest.cpp \ Classes/FontTest/FontTest.cpp \ Classes/IntervalTest/IntervalTest.cpp \ +Classes/InputTest/MouseTest.cpp \ Classes/KeyboardTest/KeyboardTest.cpp \ Classes/KeypadTest/KeypadTest.cpp \ Classes/LabelTest/LabelTest.cpp \ From 4b2429186c73969d61e3de731160e8fb693e11fe Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 16:25:06 +0800 Subject: [PATCH 307/557] closed #3093: The last test of OpenglTest crashes on Windows. --- .../javascript/bindings/jsb_opengl_manual.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp index e7aac467ee..38a168b935 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp @@ -437,8 +437,8 @@ JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) JSB_PRECONDITION2(ok, cx, JS_FALSE, "JSB_glGetUniformfv: Error processing arguments"); GLsizei length; - glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length); - GLchar* namebuffer = new GLchar[length]; + glGetProgramiv(arg0, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length); + GLchar* namebuffer = new GLchar[length+1]; GLint size = -1; GLenum type = -1; @@ -503,7 +503,10 @@ JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) JSObject *typedArray = NULL; if( utype == GL_FLOAT) { - GLfloat* param = new GLfloat[usize]; + // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv. + // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in. + // For temporary solution, we allocate 4x array. + GLfloat* param = new GLfloat[usize*4]; glGetUniformfv(arg0, arg1, param); typedArray = JS_NewFloat32Array(cx, usize); @@ -511,7 +514,10 @@ JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) memcpy( buffer, param, sizeof(float) * usize); CC_SAFE_DELETE_ARRAY(param); } else if( utype == GL_INT ) { - GLint* param = new GLint[usize]; + // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv. + // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in. + // For temporary solution, we allocate 4x array. + GLint* param = new GLint[usize*4]; glGetUniformiv(arg0, arg1, param); typedArray = JS_NewInt32Array(cx, usize); From 15cf5197573b852e07c0a64bc8f3446b8401309b Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 16:59:55 +0800 Subject: [PATCH 308/557] issue #2970:crash for CCLabelTTF when setting dimension width less than the font height --- cocos/2d/platform/android/CCImage.cpp | 10 +- .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 210 ++++++++++-------- 2 files changed, 123 insertions(+), 97 deletions(-) diff --git a/cocos/2d/platform/android/CCImage.cpp b/cocos/2d/platform/android/CCImage.cpp index 0fdfe6445e..ba722d7fad 100644 --- a/cocos/2d/platform/android/CCImage.cpp +++ b/cocos/2d/platform/android/CCImage.cpp @@ -81,7 +81,7 @@ public: { JniMethodInfo methodInfo; if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmapShadowStroke", - "(Ljava/lang/String;Ljava/lang/String;IFFFIIIZFFFFZFFFF)V")) + "(Ljava/lang/String;Ljava/lang/String;IFFFIIIZFFFFZFFFF)Z")) { CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__); return false; @@ -109,8 +109,12 @@ public: jstring jstrText = methodInfo.env->NewStringUTF(text); jstring jstrFont = methodInfo.env->NewStringUTF(fullPathOrFontName.c_str()); - methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, jstrText, - jstrFont, (int)fontSize, textTintR, textTintG, textTintB, eAlignMask, nWidth, nHeight, shadow, shadowDeltaX, -shadowDeltaY, shadowBlur, shadowOpacity, stroke, strokeColorR, strokeColorG, strokeColorB, strokeSize); + if(!methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID, jstrText, + jstrFont, (int)fontSize, textTintR, textTintG, textTintB, eAlignMask, nWidth, nHeight, shadow, shadowDeltaX, -shadowDeltaY, shadowBlur, shadowOpacity, stroke, strokeColorR, strokeColorG, strokeColorB, strokeSize)) + { + return false; + } + methodInfo.env->DeleteLocalRef(jstrText); methodInfo.env->DeleteLocalRef(jstrFont); diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index 2660097a45..ef0ba4074e 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -58,7 +58,7 @@ public class Cocos2dxBitmap { // Fields // =========================================================== - private static Context sContext; + private static Context _context; // =========================================================== // Constructors @@ -68,8 +68,8 @@ public class Cocos2dxBitmap { // Getter & Setter // =========================================================== - public static void setContext(final Context pContext) { - Cocos2dxBitmap.sContext = pContext; + public static void setContext(final Context context) { + Cocos2dxBitmap._context = context; } // =========================================================== @@ -80,8 +80,8 @@ public class Cocos2dxBitmap { // Methods // =========================================================== - private static native void nativeInitBitmapDC(final int pWidth, - final int pHeight, final byte[] pPixels); + private static native void nativeInitBitmapDC(final int width, + final int height, final byte[] pixels); /** * @param pWidth @@ -89,36 +89,49 @@ public class Cocos2dxBitmap { * @param pHeight * the height to draw, it can be 0 */ - public static void createTextBitmap(String pString, final String pFontName, - final int pFontSize, final int pAlignment, final int pWidth, - final int pHeight) { + public static void createTextBitmap(String string, final String fontName, + final int fontSize, final int alignment, final int width, + final int height) { // - createTextBitmapShadowStroke( pString, pFontName, pFontSize, 1.0f, 1.0f, 1.0f, // text font and color - pAlignment, pWidth, pHeight, // alignment and size + createTextBitmapShadowStroke( string, fontName, fontSize, 1.0f, 1.0f, 1.0f, // text font and color + alignment, width, height, // alignment and size false, 0.0f, 0.0f, 0.0f, 0.0f, // no shadow false, 1.0f, 1.0f, 1.0f, 1.0f); // no stroke } - public static void createTextBitmapShadowStroke(String pString, final String pFontName, final int pFontSize, + public static boolean createTextBitmapShadowStroke(String string, final String fontName, final int fontSize, final float fontTintR, final float fontTintG, final float fontTintB, - final int pAlignment, final int pWidth, final int pHeight, final boolean shadow, + final int alignment, final int width, final int height, final boolean shadow, final float shadowDX, final float shadowDY, final float shadowBlur, final float shadowOpacity, final boolean stroke, final float strokeR, final float strokeG, final float strokeB, final float strokeSize) { - final int horizontalAlignment = pAlignment & 0x0F; - final int verticalAlignment = (pAlignment >> 4) & 0x0F; + final int horizontalAlignment = alignment & 0x0F; + final int verticalAlignment = (alignment >> 4) & 0x0F; + + string = Cocos2dxBitmap.refactorString(string); + final Paint paint = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); + /** + * if the first word width less than designed width,It means no words to show + */ + if(0 != width) + { + final int firstWordWidth = (int) FloatMath.ceil(paint.measureText(string, 0,1)); + if ( firstWordWidth > width) + { + Log.w("createTextBitmapShadowStroke warning:","the input width is less than the width of the pString's first word\n"); + return false; + } + } - pString = Cocos2dxBitmap.refactorString(pString); - final Paint paint = Cocos2dxBitmap.newPaint(pFontName, pFontSize, horizontalAlignment); // set the paint color paint.setARGB(255, (int)(255.0 * fontTintR), (int)(255.0 * fontTintG), (int)(255.0 * fontTintB)); - final TextProperty textProperty = Cocos2dxBitmap.computeTextProperty(pString, pWidth, pHeight, paint); - final int bitmapTotalHeight = (pHeight == 0 ? textProperty.mTotalHeight: pHeight); + final TextProperty textProperty = Cocos2dxBitmap.computeTextProperty(string, width, height, paint); + final int bitmapTotalHeight = (height == 0 ? textProperty.mTotalHeight: height); // padding needed when using shadows (not used otherwise) float bitmapPaddingX = 0.0f; @@ -144,6 +157,13 @@ public class Cocos2dxBitmap { renderTextDeltaY = bitmapPaddingY; } } + + if (0 == textProperty.mMaxWidth || 0 == bitmapTotalHeight) + { + Log.w("createTextBitmapShadowStroke warning:","textProperty MaxWidth is 0 or bitMapTotalHeight is 0\n"); + return false; + } + final Bitmap bitmap = Bitmap.createBitmap(textProperty.mMaxWidth + (int)bitmapPaddingX, bitmapTotalHeight + (int)bitmapPaddingY, Bitmap.Config.ARGB_8888); @@ -154,7 +174,7 @@ public class Cocos2dxBitmap { final FontMetricsInt fontMetricsInt = paint.getFontMetricsInt(); int x = 0; - int y = Cocos2dxBitmap.computeY(fontMetricsInt, pHeight, textProperty.mTotalHeight, verticalAlignment); + int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); final String[] lines = textProperty.mLines; @@ -169,13 +189,13 @@ public class Cocos2dxBitmap { // draw again with stroke on if needed if ( stroke ) { - final Paint paintStroke = Cocos2dxBitmap.newPaint(pFontName, pFontSize, horizontalAlignment); + final Paint paintStroke = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); paintStroke.setStyle(Paint.Style.STROKE); paintStroke.setStrokeWidth(strokeSize * 0.5f); paintStroke.setARGB(255, (int) (strokeR * 255), (int) (strokeG * 255), (int) (strokeB * 255)); x = 0; - y = Cocos2dxBitmap.computeY(fontMetricsInt, pHeight, textProperty.mTotalHeight, verticalAlignment); + y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); final String[] lines2 = textProperty.mLines; for (final String line : lines2) { @@ -189,33 +209,35 @@ public class Cocos2dxBitmap { } Cocos2dxBitmap.initNativeObject(bitmap); + + return true; } - private static Paint newPaint(final String pFontName, final int pFontSize, - final int pHorizontalAlignment) { + private static Paint newPaint(final String fontName, final int fontSize, + final int horizontalAlignment) { final Paint paint = new Paint(); paint.setColor(Color.WHITE); - paint.setTextSize(pFontSize); + paint.setTextSize(fontSize); paint.setAntiAlias(true); /* Set type face for paint, now it support .ttf file. */ - if (pFontName.endsWith(".ttf")) { + if (fontName.endsWith(".ttf")) { try { final Typeface typeFace = Cocos2dxTypefaces.get( - Cocos2dxBitmap.sContext, pFontName); + Cocos2dxBitmap._context, fontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("Cocos2dxBitmap", "error to create ttf type face: " - + pFontName); + + fontName); /* The file may not find, use system font. */ - paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); } } else { - paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); } - switch (pHorizontalAlignment) { + switch (horizontalAlignment) { case HORIZONTALALIGN_CENTER: paint.setTextAlign(Align.CENTER); break; @@ -231,22 +253,22 @@ public class Cocos2dxBitmap { return paint; } - private static TextProperty computeTextProperty(final String pString, - final int pWidth, final int pHeight, final Paint pPaint) { - final FontMetricsInt fm = pPaint.getFontMetricsInt(); + private static TextProperty computeTextProperty(final String string, + final int width, final int height, final Paint paint) { + final FontMetricsInt fm = paint.getFontMetricsInt(); final int h = (int) Math.ceil(fm.bottom - fm.top); int maxContentWidth = 0; - final String[] lines = Cocos2dxBitmap.splitString(pString, pWidth, - pHeight, pPaint); + final String[] lines = Cocos2dxBitmap.splitString(string, width, + height, paint); - if (pWidth != 0) { - maxContentWidth = pWidth; + if (width != 0) { + maxContentWidth = width; } else { /* Compute the max width. */ int temp = 0; for (final String line : lines) { - temp = (int) FloatMath.ceil(pPaint.measureText(line, 0, + temp = (int) FloatMath.ceil(paint.measureText(line, 0, line.length())); if (temp > maxContentWidth) { maxContentWidth = temp; @@ -257,16 +279,16 @@ public class Cocos2dxBitmap { return new TextProperty(maxContentWidth, h, lines); } - private static int computeX(final String pText, final int pMaxWidth, - final int pHorizontalAlignment) { + private static int computeX(final String text, final int maxWidth, + final int horizontalAlignment) { int ret = 0; - switch (pHorizontalAlignment) { + switch (horizontalAlignment) { case HORIZONTALALIGN_CENTER: - ret = pMaxWidth / 2; + ret = maxWidth / 2; break; case HORIZONTALALIGN_RIGHT: - ret = pMaxWidth; + ret = maxWidth; break; case HORIZONTALALIGN_LEFT: default: @@ -276,22 +298,22 @@ public class Cocos2dxBitmap { return ret; } - private static int computeY(final FontMetricsInt pFontMetricsInt, - final int pConstrainHeight, final int pTotalHeight, - final int pVerticalAlignment) { - int y = -pFontMetricsInt.top; + private static int computeY(final FontMetricsInt fontMetricsInt, + final int constrainHeight, final int totalHeight, + final int verticalAlignment) { + int y = -fontMetricsInt.top; - if (pConstrainHeight > pTotalHeight) { - switch (pVerticalAlignment) { + if (constrainHeight > totalHeight) { + switch (verticalAlignment) { case VERTICALALIGN_TOP: - y = -pFontMetricsInt.top; + y = -fontMetricsInt.top; break; case VERTICALALIGN_CENTER: - y = -pFontMetricsInt.top + (pConstrainHeight - pTotalHeight) + y = -fontMetricsInt.top + (constrainHeight - totalHeight) / 2; break; case VERTICALALIGN_BOTTOM: - y = -pFontMetricsInt.top + (pConstrainHeight - pTotalHeight); + y = -fontMetricsInt.top + (constrainHeight - totalHeight); break; default: break; @@ -305,26 +327,26 @@ public class Cocos2dxBitmap { * If maxWidth or maxHeight is not 0, split the string to fix the maxWidth * and maxHeight. */ - private static String[] splitString(final String pString, - final int pMaxWidth, final int pMaxHeight, final Paint pPaint) { - final String[] lines = pString.split("\\n"); + private static String[] splitString(final String string, + final int maxWidth, final int maxHeight, final Paint paint) { + final String[] lines = string.split("\\n"); String[] ret = null; - final FontMetricsInt fm = pPaint.getFontMetricsInt(); + final FontMetricsInt fm = paint.getFontMetricsInt(); final int heightPerLine = (int) Math.ceil(fm.bottom - fm.top); - final int maxLines = pMaxHeight / heightPerLine; + final int maxLines = maxHeight / heightPerLine; - if (pMaxWidth != 0) { + if (maxWidth != 0) { final LinkedList strList = new LinkedList(); for (final String line : lines) { /* * The width of line is exceed maxWidth, should divide it into * two or more lines. */ - final int lineWidth = (int) FloatMath.ceil(pPaint + final int lineWidth = (int) FloatMath.ceil(paint .measureText(line)); - if (lineWidth > pMaxWidth) { + if (lineWidth > maxWidth) { strList.addAll(Cocos2dxBitmap.divideStringWithMaxWidth( - line, pMaxWidth, pPaint)); + line, maxWidth, paint)); } else { strList.add(line); } @@ -344,7 +366,7 @@ public class Cocos2dxBitmap { ret = new String[strList.size()]; strList.toArray(ret); - } else if (pMaxHeight != 0 && lines.length > maxLines) { + } else if (maxHeight != 0 && lines.length > maxLines) { /* Remove exceeding lines. */ final LinkedList strList = new LinkedList(); for (int i = 0; i < maxLines; i++) { @@ -360,37 +382,37 @@ public class Cocos2dxBitmap { } private static LinkedList divideStringWithMaxWidth( - final String pString, final int pMaxWidth, final Paint pPaint) { - final int charLength = pString.length(); + final String string, final int maxWidth, final Paint paint) { + final int charLength = string.length(); int start = 0; int tempWidth = 0; final LinkedList strList = new LinkedList(); /* Break a String into String[] by the width & should wrap the word. */ for (int i = 1; i <= charLength; ++i) { - tempWidth = (int) FloatMath.ceil(pPaint.measureText(pString, start, + tempWidth = (int) FloatMath.ceil(paint.measureText(string, start, i)); - if (tempWidth >= pMaxWidth) { - final int lastIndexOfSpace = pString.substring(0, i) + if (tempWidth >= maxWidth) { + final int lastIndexOfSpace = string.substring(0, i) .lastIndexOf(" "); if (lastIndexOfSpace != -1 && lastIndexOfSpace > start) { /* Should wrap the word. */ - strList.add(pString.substring(start, lastIndexOfSpace)); + strList.add(string.substring(start, lastIndexOfSpace)); i = lastIndexOfSpace + 1; // skip space } else { /* Should not exceed the width. */ - if (tempWidth > pMaxWidth) { - strList.add(pString.substring(start, i - 1)); + if (tempWidth > maxWidth) { + strList.add(string.substring(start, i - 1)); /* Compute from previous char. */ --i; } else { - strList.add(pString.substring(start, i)); + strList.add(string.substring(start, i)); } } /* Remove spaces at the beginning of a new line. */ - while (i < charLength && pString.charAt(i) == ' ') { + while (i < charLength && string.charAt(i) == ' ') { ++i; } @@ -400,15 +422,15 @@ public class Cocos2dxBitmap { /* Add the last chars. */ if (start < charLength) { - strList.add(pString.substring(start)); + strList.add(string.substring(start)); } return strList; } - private static String refactorString(final String pString) { + private static String refactorString(final String string) { /* Avoid error when content is "". */ - if (pString.compareTo("") == 0) { + if (string.compareTo("") == 0) { return " "; } @@ -416,7 +438,7 @@ public class Cocos2dxBitmap { * If the font of "\n" is "" or "\n", insert " " in front of it. For * example: "\nabc" -> " \nabc" "\nabc\n\n" -> " \nabc\n \n". */ - final StringBuilder strBuilder = new StringBuilder(pString); + final StringBuilder strBuilder = new StringBuilder(string); int start = 0; int index = strBuilder.indexOf("\n"); while (index != -1) { @@ -437,23 +459,23 @@ public class Cocos2dxBitmap { return strBuilder.toString(); } - private static void initNativeObject(final Bitmap pBitmap) { - final byte[] pixels = Cocos2dxBitmap.getPixels(pBitmap); + private static void initNativeObject(final Bitmap bitmap) { + final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap); if (pixels == null) { return; } - Cocos2dxBitmap.nativeInitBitmapDC(pBitmap.getWidth(), - pBitmap.getHeight(), pixels); + Cocos2dxBitmap.nativeInitBitmapDC(bitmap.getWidth(), + bitmap.getHeight(), pixels); } - private static byte[] getPixels(final Bitmap pBitmap) { - if (pBitmap != null) { - final byte[] pixels = new byte[pBitmap.getWidth() - * pBitmap.getHeight() * 4]; + private static byte[] getPixels(final Bitmap bitmap) { + if (bitmap != null) { + final byte[] pixels = new byte[bitmap.getWidth() + * bitmap.getHeight() * 4]; final ByteBuffer buf = ByteBuffer.wrap(pixels); buf.order(ByteOrder.nativeOrder()); - pBitmap.copyPixelsToBuffer(buf); + bitmap.copyPixelsToBuffer(buf); return pixels; } @@ -484,9 +506,9 @@ public class Cocos2dxBitmap { return incr_text_size; } - private static String getStringWithEllipsis(String pString, float width, + private static String getStringWithEllipsis(String string, float width, float fontSize) { - if (TextUtils.isEmpty(pString)) { + if (TextUtils.isEmpty(string)) { return ""; } @@ -494,7 +516,7 @@ public class Cocos2dxBitmap { paint.setTypeface(Typeface.DEFAULT); paint.setTextSize(fontSize); - return TextUtils.ellipsize(pString, paint, width, + return TextUtils.ellipsize(string, paint, width, TextUtils.TruncateAt.END).toString(); } @@ -510,12 +532,12 @@ public class Cocos2dxBitmap { private final int mHeightPerLine; private final String[] mLines; - TextProperty(final int pMaxWidth, final int pHeightPerLine, - final String[] pLines) { - this.mMaxWidth = pMaxWidth; - this.mHeightPerLine = pHeightPerLine; - this.mTotalHeight = pHeightPerLine * pLines.length; - this.mLines = pLines; + TextProperty(final int maxWidth, final int heightPerLine, + final String[] lines) { + this.mMaxWidth = maxWidth; + this.mHeightPerLine = heightPerLine; + this.mTotalHeight = heightPerLine * lines.length; + this.mLines = lines; } } } From 005d3c012103ddb31a2867251ae24276695825c4 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Thu, 31 Oct 2013 17:28:14 +0800 Subject: [PATCH 309/557] 1. fix if frame event is at the last frame, it may emit event several times 2. add method for removing single data info 3. add test TEST_DIRECT_LOADING 4. add test TEST_FRAME_EVENT 5. add method for getting calculated collider vertex --- .../cocostudio/CCArmatureDataManager.cpp | 113 ++++++++++++++---- .../cocostudio/CCArmatureDataManager.h | 27 +++-- .../cocostudio/CCArmatureDefine.h | 4 + .../cocostudio/CCColliderDetector.cpp | 36 ++++++ .../cocostudio/CCColliderDetector.h | 4 + .../cocostudio/CCDataReaderHelper.cpp | 102 +++++++++------- .../cocostudio/CCDataReaderHelper.h | 5 +- cocos/editor-support/cocostudio/CCTween.cpp | 18 ++- cocos/editor-support/cocostudio/CCTween.h | 19 +-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 80 ++++++++++++- .../CocoStudioArmatureTest/ArmatureScene.h | 21 ++++ 11 files changed, 339 insertions(+), 90 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 13ca184768..ca1945b418 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -65,7 +65,21 @@ ArmatureDataManager::ArmatureDataManager(void) ArmatureDataManager::~ArmatureDataManager(void) { - removeAll(); + if( _animationDatas ) + { + _animationDatas->removeAllObjects(); + } + if( _armarureDatas ) + { + _armarureDatas->removeAllObjects(); + } + + if( _textureDatas ) + { + _textureDatas->removeAllObjects(); + } + + _relativeDatas.clear(); CC_SAFE_DELETE(_animationDatas); CC_SAFE_DELETE(_armarureDatas); @@ -97,10 +111,45 @@ bool ArmatureDataManager::init() return bRet; } -void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData) +void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) +{ + if (RelativeData *data = getRelativeData(configFilePath)) + { + for (std::vector::iterator i = data->armatures.begin(); i != data->armatures.end(); i++) + { + removeArmatureData(i->c_str()); + } + + for (std::vector::iterator i = data->animations.begin(); i != data->animations.end(); i++) + { + removeAnimationData(i->c_str()); + } + + for (std::vector::iterator i = data->textures.begin(); i != data->textures.end(); i++) + { + removeTextureData(i->c_str()); + } + + for (std::vector::iterator i = data->plistFiles.begin(); i != data->plistFiles.end(); i++) + { + SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(i->c_str()); + } + + _relativeDatas.erase(configFilePath); + DataReaderHelper::sharedDataReaderHelper()->removeConfigFile(configFilePath); + } +} + + +void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath) { if(_armarureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->armatures.push_back(id); + } + _armarureDatas->setObject(armatureData, id); } } @@ -123,10 +172,15 @@ void ArmatureDataManager::removeArmatureData(const char *id) } } -void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData) +void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath) { if(_animationDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->animations.push_back(id); + } + _animationDatas->setObject(animationData, id); } } @@ -149,10 +203,15 @@ void ArmatureDataManager::removeAnimationData(const char *id) } } -void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData) +void ArmatureDataManager::addTextureData(const char *id, TextureData *textureData, const char *configFilePath) { if(_textureDatas) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->textures.push_back(id); + } + _textureDatas->setObject(textureData, id); } } @@ -179,18 +238,24 @@ void ArmatureDataManager::removeTextureData(const char *id) void ArmatureDataManager::addArmatureFileInfo(const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); } void ArmatureDataManager::addArmatureFileInfoAsync(const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = true; DataReaderHelper::getInstance()->addDataFromFileAsync("", "", configFilePath, target, selector); } void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; DataReaderHelper::getInstance()->addDataFromFile(configFilePath); addSpriteFrameFromFile(plistPath, imagePath); @@ -198,36 +263,23 @@ void ArmatureDataManager::addArmatureFileInfo(const char *imagePath, const char void ArmatureDataManager::addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, Object *target, SEL_SCHEDULE selector) { + addRelativeData(configFilePath); + _autoLoadSpriteFile = false; DataReaderHelper::getInstance()->addDataFromFileAsync(imagePath, plistPath, configFilePath, target, selector); addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) +void ArmatureDataManager::addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath) { + if (RelativeData *data = getRelativeData(configFilePath)) + { + data->plistFiles.push_back(plistPath); + } SpriteFrameCacheHelper::getInstance()->addSpriteFrameFromFile(plistPath, imagePath); } -void ArmatureDataManager::removeAll() -{ - if( _animationDatas ) - { - _animationDatas->removeAllObjects(); - } - if( _armarureDatas ) - { - _armarureDatas->removeAllObjects(); - } - - if( _textureDatas ) - { - _textureDatas->removeAllObjects(); - } - - DataReaderHelper::clear(); -} - bool ArmatureDataManager::isAutoLoadSpriteFile() { return _autoLoadSpriteFile; @@ -246,4 +298,17 @@ Dictionary *ArmatureDataManager::getTextureDatas() const return _textureDatas; } +void CCArmatureDataManager::addRelativeData(const char *configFilePath) +{ + if (_relativeDatas.find(configFilePath) == _relativeDatas.end()) + { + _relativeDatas[configFilePath] = RelativeData(); + } +} + +RelativeData *CCArmatureDataManager::getRelativeData(const char* configFilePath) +{ + return &_relativeDatas[configFilePath]; +} + } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.h b/cocos/editor-support/cocostudio/CCArmatureDataManager.h index 1bd426784d..b73dc99ef9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.h +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.h @@ -31,6 +31,14 @@ THE SOFTWARE. namespace cocostudio { +struct RelativeData +{ + std::vector plistFiles; + std::vector armatures; + std::vector animations; + std::vector textures; +}; + /** * @brief format and manage armature configuration and armature animation */ @@ -69,7 +77,7 @@ public: * @param id The id of the armature data * @param armatureData ArmatureData * */ - void addArmatureData(const char *id, ArmatureData *armatureData); + void addArmatureData(const char *id, ArmatureData *armatureData, const char *configFilePath = ""); /** * @brief get armature data @@ -89,7 +97,7 @@ public: * @param id the id of the animation data * @return AnimationData * */ - void addAnimationData(const char *id, AnimationData *animationData); + void addAnimationData(const char *id, AnimationData *animationData, const char *configFilePath = ""); /** * @brief get animation data from _animationDatas(Dictionary) @@ -109,7 +117,7 @@ public: * @param id the id of the texture data * @return TextureData * */ - void addTextureData(const char *id, TextureData *textureData); + void addTextureData(const char *id, TextureData *textureData, const char *configFilePath = ""); /** * @brief get texture data @@ -149,13 +157,10 @@ public: /** * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name */ - void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); + void addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath = ""); + virtual void removeArmatureFileInfo(const char *configFilePath); - /** - * @brief Clear the data in the _armarureDatas and _animationDatas, and set _armarureDatas and _animationDatas to NULL - */ - void removeAll(); /** * @brief Juge whether or not need auto load sprite file @@ -166,6 +171,10 @@ public: cocos2d::Dictionary *getArmatureDatas() const; cocos2d::Dictionary *getAnimationDatas() const; cocos2d::Dictionary *getTextureDatas() const; + +protected: + void addRelativeData(const char* configFilePath); + RelativeData *getRelativeData(const char* configFilePath); private: /** * @brief save amature datas @@ -189,6 +198,8 @@ private: cocos2d::Dictionary *_textureDatas; bool _autoLoadSpriteFile; + + std::map _relativeDatas; }; diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 8b7cb42312..b3fca84e01 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -44,6 +44,10 @@ THE SOFTWARE. #define ENABLE_PHYSICS_CHIPMUNK_DETECT 1 #endif +#ifndef ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#endif + #define CS_RETURN_IF(cond) if (cond) return #define CS_RETURN_NULL_IF(cond) if (cond) return NULL; diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 341bf503e6..8857832c99 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -44,6 +44,11 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT @@ -52,6 +57,11 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + _calculatedVertexList = Array::create(); + CC_SAFE_RETAIN(_calculatedVertexList); +#endif } #endif @@ -59,6 +69,10 @@ ColliderBody::~ColliderBody() { CC_SAFE_RELEASE(_contourData); +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SAFE_RELEASE(_calculatedVertexList); +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT CC_SAFE_DELETE(_filter); #endif @@ -125,6 +139,19 @@ void ColliderDetector::addContourData(ContourData *contourData) ColliderBody *colliderBody = new ColliderBody(contourData); _colliderBodyList->addObject(colliderBody); colliderBody->release(); + + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CCArray *calculatedVertexList = colliderBody->getCalculatedVertexList(); + + int num = contourData->vertexList.count(); + for (int i = 0; i < num; i++) + { + ContourVertex2 *newVertex = new ContourVertex2(0, 0); + calculatedVertexList->addObject(newVertex); + newVertex->release(); + } +#endif } void ColliderDetector::addContourDataList(Array *contourDataList) @@ -262,12 +289,21 @@ void ColliderDetector::updateTransform(AffineTransform &t) int num = contourData->vertexList.count(); ContourVertex2 **vs = (ContourVertex2 **)contourData->vertexList.data->arr; +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + ContourVertex2 **cvs = (ContourVertex2 **)colliderBody->getCalculatedVertexList()->data->arr; +#endif + for (int i = 0; i < num; i++) { helpPoint.setPoint( vs[i]->x, vs[i]->y); helpPoint = PointApplyAffineTransform(helpPoint, t); +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + cvs[i]->x = helpPoint.x; + cvs[i]->y = helpPoint.y; +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT if (shape != NULL) { diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 4f6fbeebfe..9e8b7246c6 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -65,6 +65,10 @@ public: } private: ContourData *_contourData; + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); +#endif }; /* diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 3fb1b69fb8..c64a469c71 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -138,13 +138,14 @@ static const char *CONTENT_SCALE = "content_scale"; namespace cocostudio { -std::vector s_arrConfigFileList; + float s_PositionReadScale = 1; float s_ContentScale = 1; static float s_FlashToolVersion = VERSION_2_0; static float s_CocoStudioVersion = VERSION_COMBINED; -static std::string s_BasefilePath = ""; +std::vector DataReaderHelper::_configFileList; +std::string DataReaderHelper::_basefilePath = ""; DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; @@ -184,7 +185,7 @@ void DataReaderHelper::loadData() _asyncStructQueueMutex.unlock(); } - // generate image info + // generate data info DataInfo *pDataInfo = new DataInfo(); pDataInfo->asyncStruct = pAsyncStruct; @@ -236,14 +237,10 @@ float DataReaderHelper::getPositionReadScale() void DataReaderHelper::purge() { - DataReaderHelper::clear(); + _configFileList.clear(); CC_SAFE_RELEASE_NULL(_dataReaderHelper); } -void DataReaderHelper::clear() -{ - s_arrConfigFileList.clear(); -} DataReaderHelper::DataReaderHelper() : _loadingThread(nullptr) @@ -272,26 +269,26 @@ void DataReaderHelper::addDataFromFile(const char *filePath) /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); + _basefilePath = filePath; + size_t pos = _basefilePath.find_last_of("/"); if (pos != std::string::npos) { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); + _basefilePath = _basefilePath.substr(0, pos + 1); } else { - s_BasefilePath = ""; + _basefilePath = ""; } @@ -303,13 +300,17 @@ void DataReaderHelper::addDataFromFile(const char *filePath) std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); + DataInfo dataInfo; + dataInfo.filename = filePathStr; + dataInfo.asyncStruct = NULL; + if (str.compare(".xml") == 0) { - DataReaderHelper::addDataFromCache(pFileContent); + DataReaderHelper::addDataFromCache(pFileContent, &dataInfo); } else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) { - DataReaderHelper::addDataFromJsonCache(pFileContent); + DataReaderHelper::addDataFromJsonCache(pFileContent, &dataInfo); } } @@ -318,9 +319,9 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p /* * Check if file is already added to ArmatureDataManager, if then return. */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) + for(unsigned int i = 0; i < _configFileList.size(); i++) { - if (s_arrConfigFileList[i].compare(filePath) == 0) + if (_configFileList[i].compare(filePath) == 0) { if (target && selector) { @@ -336,7 +337,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p return; } } - s_arrConfigFileList.push_back(filePath); + _configFileList.push_back(filePath); //! find the base file path std::string basefilePath = filePath; @@ -474,7 +475,22 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) } +void DataReaderHelper::removeConfigFile(const char *configFile) +{ + std::vector::iterator it = _configFileList.end(); + for (std::vector::iterator i = _configFileList.begin(); i != _configFileList.end(); i++) + { + if (*i == configFile) + { + it = i; + } + } + if (it != _configFileList.end()) + { + _configFileList.erase(it); + } +} @@ -498,13 +514,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data { ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); + ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData, dataInfo->filename.c_str()); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -521,13 +537,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data while(animationXML) { AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); + ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData, dataInfo->filename.c_str()); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -544,13 +560,13 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data { TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); + ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData, dataInfo->filename.c_str()); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1137,7 +1153,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); - if (dataInfo) + if (dataInfo->asyncStruct) { dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); } @@ -1153,13 +1169,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); ArmatureData *armatureData = decodeArmature(*armatureDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); armatureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1173,13 +1189,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); AnimationData *animationData = decodeAnimation(*animationDic, dataInfo); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); animationData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1193,13 +1209,13 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); TextureData *textureData = decodeTexture(*textureDic); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); } ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); textureData->release(); - if (dataInfo) + if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.unlock(); } @@ -1207,7 +1223,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } // Auto load sprite file - bool autoLoad = dataInfo == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; + bool autoLoad = dataInfo->asyncStruct == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; if (autoLoad) { length = json.getArrayItemCount(CONFIG_FILE_PATH); @@ -1223,7 +1239,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string filePath = path; filePath = filePath.erase(filePath.find_last_of(".")); - if (dataInfo != NULL) + if (dataInfo->asyncStruct) { dataInfo->configFileQueue.push(filePath); } @@ -1232,7 +1248,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string plistPath = filePath + ".plist"; std::string pngPath = filePath + ".png"; - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((s_BasefilePath + plistPath).c_str(), (s_BasefilePath + pngPath).c_str()); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile((_basefilePath + plistPath).c_str(), (_basefilePath + pngPath).c_str()); } } } @@ -1328,7 +1344,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - if (dataInfo) + if (dataInfo->asyncStruct) { sdd->skinData.x *= dataInfo->contentScale; sdd->skinData.y *= dataInfo->contentScale; @@ -1362,13 +1378,13 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo const char *plist = json.getItemStringValue(A_PLIST); if(plist != NULL) { - if (dataInfo != NULL) + if (dataInfo->asyncStruct) { static_cast(displayData)->plist = dataInfo->asyncStruct->baseFilePath + plist; } else { - static_cast(displayData)->plist = s_BasefilePath + plist; + static_cast(displayData)->plist = _basefilePath + plist; } } } @@ -1601,7 +1617,7 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - if (dataInfo) + if (dataInfo->asyncStruct) { node->x *= dataInfo->contentScale; node->y *= dataInfo->contentScale; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index a9159ef39e..c2df44b512 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -73,6 +73,7 @@ protected: AsyncStruct *asyncStruct; std::queue configFileQueue; float contentScale; + std::string filename; } DataInfo; public: @@ -90,7 +91,6 @@ public: static float getPositionReadScale(); static void purge(); - static void clear(); public: /** * @js ctor @@ -107,6 +107,7 @@ public: void addDataAsyncCallBack(float dt); + void removeConfigFile(const char *configFile); public: /** @@ -192,6 +193,8 @@ protected: std::queue *_asyncStructQueue; std::queue *_dataQueue; + static std::string _basefilePath; + static std::vector _configFileList; static DataReaderHelper *_dataReaderHelper; }; diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 5704867a61..77f9a3b2ff 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -61,6 +61,7 @@ Tween::Tween() , _fromIndex(0) , _toIndex(0) , _animation(NULL) + , _passLastFrame(false) { } @@ -408,7 +409,6 @@ float Tween::updateFrameData(float currentPercent) FrameData *from = NULL; FrameData *to = NULL; - bool passLastFrame = false; if (playedTime < frames[0]->frameID) { @@ -416,9 +416,19 @@ float Tween::updateFrameData(float currentPercent) setBetween(from, to); return currentPercent; } - else if(playedTime >= frames[length - 1]->frameID) + + if(playedTime >= frames[length - 1]->frameID) { - passLastFrame = true; + // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. + if (_passLastFrame) + { + return _currentPercent; + } + _passLastFrame = true; + } + else + { + _passLastFrame = false; } @@ -442,7 +452,7 @@ float Tween::updateFrameData(float currentPercent) _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } - if (playedTime == from->frameID || (passLastFrame && _fromIndex == length-1)) + if (playedTime == from->frameID || (_passLastFrame && _fromIndex == length-1)) { break; } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 5e5bea6356..61213371e8 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -123,25 +123,26 @@ protected: //! A weak reference to the current MovementBoneData. The data is in the data pool CC_SYNTHESIZE(MovementBoneData *, _movementBoneData, MovementBoneData) - FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData - FrameData *_from; //! From frame data, used for calculate between value - FrameData *_to; //! To frame data, used for calculate between value - FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value + FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData + FrameData *_from; //! From frame data, used for calculate between value + FrameData *_to; //! To frame data, used for calculate between value + FrameData *_between; //! Between frame data, used for calculate current FrameData(m_pNode) value - Bone *_bone; //! A weak reference to the Bone + Bone *_bone; //! A weak reference to the Bone - CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use + CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use - int _betweenDuration; //! Current key frame will last _betweenDuration frames + int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; - int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex - int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _fromIndex; //! The current frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex + int _toIndex; //! The next frame index in FrameList of MovementBoneData, it's different from m_iFrameIndex ArmatureAnimation *_animation; + bool _passLastFrame; //! If current frame index is more than the last frame's index }; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 625308dd01..35db4c129b 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -21,6 +21,9 @@ Layer *CreateLayer(int index) case TEST_ASYNCHRONOUS_LOADING: pLayer = new TestAsynchronousLoading(); break; + case TEST_DIRECT_LOADING: + pLayer = new TestDirectLoading(); + break; case TEST_DRAGON_BONES_2_0: pLayer = new TestDragonBones20(); break; @@ -39,6 +42,9 @@ Layer *CreateLayer(int index) case TEST_ANIMATION_EVENT: pLayer = new TestAnimationEvent(); break; + case TEST_FRAME_EVENT: + pLayer = new TestFrameEvent(); + break; case TEST_PARTICLE_DISPLAY: pLayer = new TestParticleDisplay(); break; @@ -244,6 +250,7 @@ void TestAsynchronousLoading::onEnter() ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/hero.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/horse.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/bear.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); + ArmatureDataManager::getInstance()->addArmatureFileInfoAsync("armature/HeroAnimation.ExportJson", this, schedule_selector(TestAsynchronousLoading::dataLoaded)); //! load data directly // ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml"); @@ -263,6 +270,12 @@ std::string TestAsynchronousLoading::subtitle() { return "current percent : "; } + +void TestAsynchronousLoading::restartCallback(CCObject* pSender) +{ + ArmatureDataManager::getInstance()->purge(); + ArmatureTestLayer::restartCallback(pSender); +} void TestAsynchronousLoading::dataLoaded(float percent) { LabelTTF *label = (LabelTTF *)getChildByTag(10001); @@ -282,6 +295,26 @@ void TestAsynchronousLoading::dataLoaded(float percent) } +void TestDirectLoading::onEnter() +{ + ArmatureTestLayer::onEnter(); + + // remove sigle resource + ArmatureDataManager::getInstance()->removeArmatureFileInfo("armature/bear.ExportJson"); + + // load resource directly + ArmatureDataManager::getInstance()->addArmatureFileInfo("armature/bear.ExportJson"); + + Armature *armature = Armature::create("bear"); + armature->getAnimation()->playByIndex(0); + armature->setPosition(ccp(VisibleRect::center().x, VisibleRect::center().y)); + addChild(armature); +} +std::string TestDirectLoading::title() +{ + return "Test Direct Loading"; +} + void TestCSWithSkeleton::onEnter() { @@ -535,6 +568,51 @@ void TestAnimationEvent::callback2() +#define FRAME_EVENT_ACTION_TAG 10000 + +void TestFrameEvent::onEnter() +{ + ArmatureTestLayer::onEnter(); + Armature *armature = Armature::create("HeroAnimation"); + armature->getAnimation()->play("attack"); + armature->getAnimation()->setSpeedScale(0.5); + armature->setPosition(Point(VisibleRect::center().x - 50, VisibleRect::center().y -100)); + + /* + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + */ + armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestFrameEvent::onFrameEvent)); + + addChild(armature); + + schedule( schedule_selector(TestFrameEvent::checkAction) ); +} +std::string TestFrameEvent::title() +{ + return "Test Frame Event"; +} +void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex) +{ + CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt, currentFrameIndex); + + + if (!this->getActionByTag(FRAME_EVENT_ACTION_TAG) || this->getActionByTag(FRAME_EVENT_ACTION_TAG)->isDone()) + { + this->stopAllActions(); + + ActionInterval *action = ShatteredTiles3D::create(0.2f, Size(16,12), 5, false); + action->setTag(FRAME_EVENT_ACTION_TAG); + this->runAction(action); + } +} +void TestFrameEvent::checkAction(float dt) +{ + if ( this->numberOfRunningActions() == 0 && this->getGrid() != NULL) + this->setGrid(NULL); +} + + void TestParticleDisplay::onEnter() { @@ -926,7 +1004,7 @@ void TestColliderDetector::initWorld() bullet->setCPBody(body); - body = cpBodyNew(INFINITY, INFINITY); + body = cpBodyNew(1.0f, INFINITY); cpSpaceAddBody(space, body); armature2->setBody(body); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index f5a7787168..f8429fc595 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -27,12 +27,14 @@ public: enum { TEST_ASYNCHRONOUS_LOADING = 0, + TEST_DIRECT_LOADING, TEST_COCOSTUDIO_WITH_SKELETON, TEST_DRAGON_BONES_2_0, TEST_PERFORMANCE, TEST_PERFORMANCE_BATCHNODE, TEST_CHANGE_ZORDER, TEST_ANIMATION_EVENT, + TEST_FRAME_EVENT, TEST_PARTICLE_DISPLAY, TEST_USE_DIFFERENT_PICTURE, TEST_BCOLLIDER_DETECTOR, @@ -72,10 +74,18 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); + virtual void restartCallback(CCObject* pSender); void dataLoaded(float percent); }; +class TestDirectLoading : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); +}; + class TestCSWithSkeleton : public ArmatureTestLayer { virtual void onEnter(); @@ -147,6 +157,17 @@ public: cocostudio::Armature *armature; }; + +class TestFrameEvent : public ArmatureTestLayer +{ +public: + virtual void onEnter(); + virtual std::string title(); + void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); + void checkAction(float dt); +}; + + class TestUseMutiplePicture : public ArmatureTestLayer { virtual void onEnter(); From 4eaaaddc3405cef7d3274a8af7b530abd1b52193 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Thu, 31 Oct 2013 17:29:03 +0800 Subject: [PATCH 310/557] upload resource --- .../Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id | 1 + .../Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id | 1 + 2 files changed, 2 insertions(+) create mode 100644 samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id create mode 100644 samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id new file mode 100644 index 0000000000..43ba518703 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id @@ -0,0 +1 @@ +d73c3774258671e491d1579a4991bba7c4b4c24c \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id new file mode 100644 index 0000000000..f92a9b8f72 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id @@ -0,0 +1 @@ +ac19b290421fc75a284f603891442ab9796c132a \ No newline at end of file From b8faaeba59c1e89a42fbab17dd985a8240c565fe Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 31 Oct 2013 17:52:22 +0800 Subject: [PATCH 311/557] issus #2893:improve new label --- cocos/2d/CCFontAtlas.cpp | 25 ++++++------- cocos/2d/CCFontAtlas.h | 4 +-- cocos/2d/CCFontAtlasFactory.cpp | 2 ++ cocos/2d/CCFontDefinition.cpp | 1 + cocos/2d/CCFontFNT.cpp | 6 +--- cocos/2d/CCFontFreeType.cpp | 8 ++--- cocos/2d/CCFontFreeType.h | 7 ++-- cocos/2d/CCLabel.cpp | 58 +++++++++++++------------------ cocos/2d/CCLabel.h | 6 ++-- cocos/2d/CCLabelTextFormatter.cpp | 2 -- 10 files changed, 52 insertions(+), 67 deletions(-) diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 2879ac72de..24b56bd448 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -14,15 +14,15 @@ NS_CC_BEGIN FontAtlas::FontAtlas(Font &theFont) : -_font(theFont), +_font(&theFont), _currentPageData(nullptr) { - _font.retain(); + _font->retain(); - FontFreeType* fontTTf = dynamic_cast(&_font); + FontFreeType* fontTTf = dynamic_cast(_font); if (fontTTf && fontTTf->isDynamicGlyphCollection()) { - _currentPageLineHeight = _font.getFontMaxHeight(); + _currentPageLineHeight = _font->getFontMaxHeight(); _commonLineHeight = _currentPageLineHeight * 0.8f; Texture2D * tex = new Texture2D; _currentPage = 0; @@ -34,16 +34,16 @@ _currentPageData(nullptr) _currentPageData = new unsigned char[_currentPageDataSize]; memset(_currentPageData, 0, _currentPageDataSize); addTexture(*tex,0); + tex->release(); } } FontAtlas::~FontAtlas() { - _font.release(); + _font->release(); relaseTextures(); - if(_currentPageData) - delete []_currentPageData; + delete []_currentPageData; } void FontAtlas::relaseTextures() @@ -79,7 +79,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) if(_currentPageData == nullptr) return false; - FontFreeType* fontTTf = (FontFreeType*)&_font; + FontFreeType* fontTTf = (FontFreeType*)_font; std::vector fontDefs; int length = cc_wcslen(utf16String); @@ -100,7 +100,6 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect)) { - //log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[i], _fontName.c_str()); tempDef.validDefinition = false; tempDef.letteCharUTF16 = utf16String[i]; tempDef.commonLineHeight = 0; @@ -150,7 +149,9 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) return false; memset(_currentPageData, 0, _currentPageDataSize); _currentPage++; - addTexture(*(new Texture2D),_currentPage); + Texture2D* tex = new Texture2D; + addTexture(*tex,_currentPage); + tex->release(); } } renderCharAt(fontDefs[i].letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,1024); @@ -182,7 +183,7 @@ bool FontAtlas::renderCharAt(unsigned short int charToRender, int posX, int posY int sourceHeight = 0; // get the glyph's bitmap - sourceBitmap = _font.getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight); if (!sourceBitmap) return false; @@ -234,7 +235,7 @@ void FontAtlas::setCommonLineHeight(float newHeight) _commonLineHeight = newHeight; } -Font & FontAtlas::getFont() const +const Font * FontAtlas::getFont() const { return _font; } diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index b1b6eaa9b4..a388a5b987 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -70,7 +70,7 @@ public: void setCommonLineHeight(float newHeight); Texture2D & getTexture(int slot); - Font & getFont() const; + const Font * getFont() const; private: bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); @@ -79,7 +79,7 @@ private: std::map _atlasTextures; std::map _fontLetterDefinitions; float _commonLineHeight; - Font & _font; + Font * _font; // Dynamic GlyphCollection related stuff int _currentPage; diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index 2b8e0b4ca4..aeb0b6154e 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -35,7 +35,9 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) return atlas; } else + { return nullptr; + } } NS_CC_END diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index 7852d56d84..938204f3b0 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -49,6 +49,7 @@ FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) if (ret->initDefinition(font, glyph, textureSize)) { + ret->autorelease(); return ret; } else diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index cd1e586e62..7a1ca6f200 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -38,11 +38,7 @@ FontFNT * FontFNT::create(const char* fntFilePath) FontFNT::~FontFNT() { - //_configuration release when execute LabelBMFont::purgeCachedData(); - /*if (_configuration) - { - _configuration->release(); - }*/ + } Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 3fbac58b5b..0e4e49d96f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -88,8 +88,8 @@ FT_Library FontFreeType::getFTLibrary() } FontFreeType::FontFreeType(bool dynamicGlyphCollection) - : _letterPadding(5) - ,_ttfData(nullptr), + : _letterPadding(5), + _ttfData(nullptr), _dynamicGlyphCollection(dynamicGlyphCollection), _fontRef(nullptr) { @@ -130,8 +130,6 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) FontFreeType::~FontFreeType() { - // release the font - // TO DO if (_fontRef) { FT_Done_Face(_fontRef); @@ -160,8 +158,6 @@ FontAtlas * FontFreeType::createFontAtlas() FontAtlas *atlas = def->createFontAtlas(); - // release the font definition, we don't need it anymore - def->release(); return atlas; } } diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index cdf3d1a1ac..a305b2253e 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -39,7 +39,9 @@ class CC_DLL FontFreeType : public Font public: static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - + + static void shutdownFreeType(); + virtual FontAtlas * createFontAtlas() override; virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const override; @@ -49,8 +51,7 @@ public: bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; - inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} - static void shutdownFreeType(); + inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} protected: diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index a7ed8e2978..ce928825bc 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -112,12 +112,9 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment) Label::~Label() { - if (_currentUTF16String) - delete [] _currentUTF16String; - if (_originalUTF16String) - delete [] _originalUTF16String; - if (_advances) - delete [] _advances; + delete [] _currentUTF16String; + delete [] _originalUTF16String; + delete [] _advances; if (_fontAtlas) FontAtlasCache::releaseFontAtlas(_fontAtlas); @@ -254,8 +251,7 @@ void Label::alignText() int strLen = cc_wcslen(_currentUTF16String); if (_children && _children->count() != 0) { - Object* child; - CCARRAY_FOREACH(_children, child) + for (auto child: *_children) { Node* pNode = static_cast( child ); if (pNode) @@ -275,7 +271,7 @@ void Label::alignText() { if (_lettersInfo[ctr].def.validDefinition) { - child = (Sprite*)this->getChildByTag(ctr); + child = static_cast( this->getChildByTag(ctr) ); if (child) { uvRect.size.height = _lettersInfo[ctr].def.height; @@ -302,10 +298,8 @@ bool Label::computeAdvancesForString(unsigned short int *stringToRender) _advances = 0; } - Font &theFont = _fontAtlas->getFont(); - int letterCount = 0; - _advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount); + _advances = _fontAtlas->getFont()->getAdvancesForTextUTF16(stringToRender, letterCount); if(!_advances) return false; @@ -519,7 +513,7 @@ int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const Rect Label::getRectForChar(unsigned short c) const { - return _fontAtlas->getFont().getRectForChar(c); + return _fontAtlas->getFont()->getRectForChar(c); } // string related stuff @@ -649,31 +643,27 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity) { _displayedOpacity = _realOpacity * parentOpacity/255.0; - Object* pObj; - CCARRAY_FOREACH(_children, pObj) + for (auto child: *_children) { - Sprite *item = static_cast( pObj ); + Sprite *item = static_cast( child ); item->updateDisplayedOpacity(_displayedOpacity); } - //if (_cascadeOpacityEnabled) + V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); + int count = _textureAtlas->getTotalQuads(); + Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); + if (_isOpacityModifyRGB) { - V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); - int count = _textureAtlas->getTotalQuads(); - Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); - if (_isOpacityModifyRGB) - { - color4.r *= _displayedOpacity/255.0f; - color4.g *= _displayedOpacity/255.0f; - color4.b *= _displayedOpacity/255.0f; - } - for (int index=0; indexupdateQuad(&quads[index], index); - } + color4.r *= _displayedOpacity/255.0f; + color4.g *= _displayedOpacity/255.0f; + color4.b *= _displayedOpacity/255.0f; + } + for (int index = 0; index < count; ++index) + { + quads[index].bl.colors = color4; + quads[index].br.colors = color4; + quads[index].tl.colors = color4; + quads[index].tr.colors = color4; + _textureAtlas->updateQuad(&quads[index], index); } } diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index e9e56e31ca..b59850632b 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -82,9 +82,9 @@ public: virtual unsigned char getDisplayedOpacity() const override; // CCLabelTextFormat protocol implementation - virtual std::vector *getLettersInfo(){ return &_lettersInfo; }; - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex); - virtual bool recordPlaceholderInfo(int spriteIndex); + virtual std::vector *getLettersInfo() override { return &_lettersInfo; }; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; + virtual bool recordPlaceholderInfo(int spriteIndex) override; virtual float getLetterPosXLeft( int index ) const override; virtual float getLetterPosXRight( int index ) const override; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index dc3bc82020..87dd3cf7cd 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -71,8 +71,6 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) } skip += justSkipped; tIndex = j + skip; - //if (!info->visible) - // continue; if (i >= stringLength) break; From 2efef34144afd5435e0ad5070e04a6e2ef95986c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 31 Oct 2013 18:18:02 +0800 Subject: [PATCH 312/557] issue #2771: fix vs compile errors --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/Android.mk | 20 +-- cocos/2d/Makefile | 20 +-- cocos/2d/cocos2d.vcxproj | 44 +++--- cocos/2d/cocos2d.vcxproj.filters | 132 +++++++++--------- cocos/physics/CCPhysicsBody.cpp | 22 +-- cocos/physics/CCPhysicsContact.cpp | 8 +- cocos/physics/CCPhysicsJoint.cpp | 16 +-- cocos/physics/CCPhysicsShape.cpp | 10 +- cocos/physics/CCPhysicsWorld.cpp | 22 +-- ...dyInfo.cpp => CCPhysicsBodyInfo_box2d.cpp} | 2 +- ...csBodyInfo.h => CCPhysicsBodyInfo_box2d.h} | 2 + ...nfo.cpp => CCPhysicsContactInfo_box2d.cpp} | 2 +- ...actInfo.h => CCPhysicsContactInfo_box2d.h} | 1 + ...hysicsHelper.h => CCPhysicsHelper_box2d.h} | 1 - ...tInfo.cpp => CCPhysicsJointInfo_box2d.cpp} | 2 +- ...JointInfo.h => CCPhysicsJointInfo_box2d.h} | 1 + ...eInfo.cpp => CCPhysicsShapeInfo_box2d.cpp} | 2 +- ...ShapeInfo.h => CCPhysicsShapeInfo_box2d.h} | 1 + ...dInfo.cpp => CCPhysicsWorldInfo_box2d.cpp} | 2 +- ...WorldInfo.h => CCPhysicsWorldInfo_box2d.h} | 1 + ...nfo.cpp => CCPhysicsBodyInfo_chipmunk.cpp} | 2 +- ...odyInfo.h => CCPhysicsBodyInfo_chipmunk.h} | 5 +- ....cpp => CCPhysicsContactInfo_chipmunk.cpp} | 2 +- ...Info.h => CCPhysicsContactInfo_chipmunk.h} | 5 +- ...icsHelper.h => CCPhysicsHelper_chipmunk.h} | 6 +- ...fo.cpp => CCPhysicsJointInfo_chipmunk.cpp} | 2 +- ...ntInfo.h => CCPhysicsJointInfo_chipmunk.h} | 5 +- ...fo.cpp => CCPhysicsShapeInfo_chipmunk.cpp} | 2 +- ...peInfo.h => CCPhysicsShapeInfo_chipmunk.h} | 6 +- ...fo.cpp => CCPhysicsWorldInfo_chipmunk.cpp} | 2 +- ...ldInfo.h => CCPhysicsWorldInfo_chipmunk.h} | 5 +- 32 files changed, 182 insertions(+), 173 deletions(-) rename cocos/physics/box2d/{CCPhysicsBodyInfo.cpp => CCPhysicsBodyInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsBodyInfo.h => CCPhysicsBodyInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsContactInfo.cpp => CCPhysicsContactInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsContactInfo.h => CCPhysicsContactInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsHelper.h => CCPhysicsHelper_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsJointInfo.cpp => CCPhysicsJointInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsJointInfo.h => CCPhysicsJointInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsShapeInfo.cpp => CCPhysicsShapeInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsShapeInfo.h => CCPhysicsShapeInfo_box2d.h} (99%) rename cocos/physics/box2d/{CCPhysicsWorldInfo.cpp => CCPhysicsWorldInfo_box2d.cpp} (97%) rename cocos/physics/box2d/{CCPhysicsWorldInfo.h => CCPhysicsWorldInfo_box2d.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsBodyInfo.cpp => CCPhysicsBodyInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsBodyInfo.h => CCPhysicsBodyInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsContactInfo.cpp => CCPhysicsContactInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsContactInfo.h => CCPhysicsContactInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsHelper.h => CCPhysicsHelper_chipmunk.h} (100%) rename cocos/physics/chipmunk/{CCPhysicsJointInfo.cpp => CCPhysicsJointInfo_chipmunk.cpp} (98%) rename cocos/physics/chipmunk/{CCPhysicsJointInfo.h => CCPhysicsJointInfo_chipmunk.h} (99%) rename cocos/physics/chipmunk/{CCPhysicsShapeInfo.cpp => CCPhysicsShapeInfo_chipmunk.cpp} (98%) rename cocos/physics/chipmunk/{CCPhysicsShapeInfo.h => CCPhysicsShapeInfo_chipmunk.h} (100%) rename cocos/physics/chipmunk/{CCPhysicsWorldInfo.cpp => CCPhysicsWorldInfo_chipmunk.cpp} (97%) rename cocos/physics/chipmunk/{CCPhysicsWorldInfo.h => CCPhysicsWorldInfo_chipmunk.h} (99%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 17e0cee1da..3084c15190 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b695026fc3d856d540590ff09112696f66379c22 \ No newline at end of file +a9f1e2dab211d674c7a17bb7c268d613af6d5797 \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 6a25764f44..52009a4638 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -147,16 +147,16 @@ platform/CCThread.cpp \ ../physics/CCPhysicsJoint.cpp \ ../physics/CCPhysicsShape.cpp \ ../physics/CCPhysicsWorld.cpp \ -../physics/box2d/CCPhysicsBodyInfo.cpp \ -../physics/box2d/CCPhysicsContactInfo.cpp \ -../physics/box2d/CCPhysicsJointInfo.cpp \ -../physics/box2d/CCPhysicsShapeInfo.cpp \ -../physics/box2d/CCPhysicsWorldInfo.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -../physics/chipmunk/CCPhysicsContactInfo.cpp \ -../physics/chipmunk/CCPhysicsJointInfo.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ +../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ +../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ +../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ +../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../../external/tinyxml2/tinyxml2.cpp \ ../../external/unzip/ioapi.cpp \ ../../external/unzip/unzip.cpp diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile index d88604b130..d84d5ed6d1 100644 --- a/cocos/2d/Makefile +++ b/cocos/2d/Makefile @@ -73,16 +73,16 @@ CCParticleExamples.cpp \ CCParticleSystem.cpp \ CCParticleSystemQuad.cpp \ CCParticleBatchNode.cpp \ -../physics/box2d/CCPhysicsContactInfo.cpp \ -../physics/box2d/CCPhysicsJointInfo.cpp \ -../physics/box2d/CCPhysicsShapeInfo.cpp \ -../physics/box2d/CCPhysicsBodyInfo.cpp \ -../physics/box2d/CCPhysicsWorldInfo.cpp \ -../physics/chipmunk/CCPhysicsContactInfo.cpp \ -../physics/chipmunk/CCPhysicsJointInfo.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo.cpp \ +../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ +../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ +../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ +../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ +../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ +../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ +../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../physics/CCPhysicsBody.cpp \ ../physics/CCPhysicsContact.cpp \ ../physics/CCPhysicsShape.cpp \ diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index a7f030bb9f..21150abf4a 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -192,21 +192,21 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - + + + + + - - - - - + + + + + @@ -359,24 +359,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - - + + + + + + - - - - - - + + + + + + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 2028e708c8..29fad13db6 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -129,36 +129,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -572,6 +542,36 @@ support + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + @@ -592,42 +592,6 @@ physics - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\chipmunk - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - base_nodes @@ -1152,5 +1116,41 @@ base + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\Box2D + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + + + physics\chipmunk + \ No newline at end of file diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index a4393c4435..70bfe275b8 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -25,6 +25,7 @@ #ifdef CC_USE_PHYSICS #include +#include #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" @@ -36,17 +37,16 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" - -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 7c3c609ebc..6f08fc6b24 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -30,10 +30,10 @@ #include "Box2D.h" #endif -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 1268ac2460..e35b8d241c 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -33,14 +33,14 @@ #include "CCPhysicsBody.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" -#include "box2d/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" +#include "box2d/CCPhysicsHelper_box2d.h" #include "CCNode.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 6b166da351..bb17c54501 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -34,11 +34,11 @@ #include "CCPhysicsBody.h" #include "CCPhysicsWorld.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 459261f896..a8d3d962c7 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -37,17 +37,17 @@ #include "CCPhysicsJoint.h" #include "CCPhysicsContact.h" -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "box2d/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "box2d/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "box2d/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsContactInfo.h" -#include "box2d/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "box2d/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsHelper.h" +#include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" +#include "box2d/CCPhysicsWorldInfo_box2d.h" +#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" +#include "box2d/CCPhysicsBodyInfo_box2d.h" +#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" +#include "box2d/CCPhysicsShapeInfo_box2d.h" +#include "chipmunk/CCPhysicsContactInfo_chipmunk.h" +#include "box2d/CCPhysicsContactInfo_box2d.h" +#include "chipmunk/CCPhysicsJointInfo_chipmunk.h" +#include "box2d/CCPhysicsJointInfo_box2d.h" +#include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "CCDrawNode.h" #include "CCArray.h" diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsBodyInfo.cpp rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp index bfa20b616a..059619a264 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsBodyInfo.h rename to cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index 5c89ac5f19..ed5135bf36 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -27,7 +27,9 @@ #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ + #include "CCPlatformMacros.h" + NS_CC_BEGIN class PhysicsBodyInfo diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.cpp b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsContactInfo.cpp rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp index 41eaa4f831..4edb6ce3a2 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsContactInfo.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsContactInfo.h rename to cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index f1e41ef572..c8d4a262d5 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsHelper.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsHelper.h rename to cocos/physics/box2d/CCPhysicsHelper_box2d.h index 61dd2b6e4c..01f156628d 100644 --- a/cocos/physics/box2d/CCPhysicsHelper.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -27,7 +27,6 @@ #ifndef __CCPHYSICS_HELPER_H__ #define __CCPHYSICS_HELPER_H__ - #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.cpp b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsJointInfo.cpp rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp index 753ba41534..a0b6363cde 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsJointInfo.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsJointInfo.h rename to cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index a60ecdb97e..c8223b6f8c 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsShapeInfo.cpp rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp index a89ba7dae7..fc3aa61491 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsShapeInfo.h rename to cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index 8608f0bad1..cd1fc6abcc 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_SHAPE_INFO_H__ #define __CCPHYSICS_SHAPE_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp similarity index 97% rename from cocos/physics/box2d/CCPhysicsWorldInfo.cpp rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp index 0de6c00d82..fbe3be06d4 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) NS_CC_BEGIN diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h similarity index 99% rename from cocos/physics/box2d/CCPhysicsWorldInfo.h rename to cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index 662fa19843..9df3ec46cd 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -27,6 +27,7 @@ #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ + #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 5fd8ceb171..42ce5cc7ec 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsBodyInfo.h" +#include "CCPhysicsBodyInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsBodyInfo.h rename to cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 54e4313b38..19e43c23fb 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_BODY_INFO_H__ #define __CCPHYSICS_BODY_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 53b4f29b14..283a4998ab 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsContactInfo.h" +#include "CCPhysicsContactInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsContactInfo.h rename to cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index fb455cdfc5..7dc6561fec 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_CONTACT_INFO_H__ #define __CCPHYSICS_CONTACT_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsHelper.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h similarity index 100% rename from cocos/physics/chipmunk/CCPhysicsHelper.h rename to cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 8ad6fa29bd..bf6f6d14db 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifndef __CCPHYSICS_HELPER_H__ +#define __CCPHYSICS_HELPER_H__ + #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp similarity index 98% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index b3fc376710..82053ce4b1 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsJointInfo.h" +#include "CCPhysicsJointInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsJointInfo.h rename to cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 5033e4aaba..8116c48eae 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_JOINT_INFO_H__ #define __CCPHYSICS_JOINT_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" #include diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp similarity index 98% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 07e5c2f932..74abfc75f1 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsShapeInfo.h" +#include "CCPhysicsShapeInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h similarity index 100% rename from cocos/physics/chipmunk/CCPhysicsShapeInfo.h rename to cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 9229ba6d7f..83be655b02 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifndef __CCPHYSICS_SHAPE_INFO_H__ +#define __CCPHYSICS_SHAPE_INFO_H__ + #include #include #include "chipmunk.h" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp similarity index 97% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index 57f601ead7..f58eebadf2 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsWorldInfo.h" +#include "CCPhysicsWorldInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h similarity index 99% rename from cocos/physics/chipmunk/CCPhysicsWorldInfo.h rename to cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 8c60cde415..158f074c77 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -22,11 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include "../CCPhysicsSetting.h" +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + #ifndef __CCPHYSICS_WORLD_INFO_H__ #define __CCPHYSICS_WORLD_INFO_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN From 150f1aeaab06902d711b98a874f624c57aad051a Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 31 Oct 2013 20:17:30 +0800 Subject: [PATCH 313/557] issue #2893:improve new label --- cocos/2d/CCFontAtlasFactory.cpp | 1 - cocos/2d/CCFontFNT.cpp | 2 +- cocos/2d/CCLabel.cpp | 10 ++++------ cocos/2d/CCLabel.h | 2 +- cocos/2d/CCLabelTextFormatProtocol.h | 2 +- samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp | 8 ++++---- 6 files changed, 11 insertions(+), 14 deletions(-) diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index aeb0b6154e..f5e4f60802 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -31,7 +31,6 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) if(font) { FontAtlas * atlas = font->createFontAtlas(); - font->release(); return atlas; } else diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 7a1ca6f200..e655236a1b 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -32,7 +32,7 @@ FontFNT * FontFNT::create(const char* fntFilePath) delete newConf; return nullptr; } - + tempFont->autorelease(); return tempFont; } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index ce928825bc..09192c0e89 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -420,7 +420,7 @@ void Label::addChild(Node * child, int zOrder/* =0 */, int tag/* =0 */) ///// PROTOCOL STUFF -Sprite * Label::getLetterAt(int ID) +Sprite * Label::getLetter(int ID) { if (ID < getStringLenght()) { @@ -598,8 +598,7 @@ void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) _isOpacityModifyRGB = isOpacityModifyRGB; if (_children && _children->count() != 0) { - Object* child; - CCARRAY_FOREACH(_children, child) + for (auto child: *_children) { Node* pNode = static_cast( child ); if (pNode) @@ -709,10 +708,9 @@ void Label::updateDisplayedColor(const Color3B& parentColor) _displayedColor.g = _realColor.g * parentColor.g/255.0; _displayedColor.b = _realColor.b * parentColor.b/255.0; - Object* pObj; - CCARRAY_FOREACH(_children, pObj) + for (auto child: *_children) { - Sprite *item = static_cast( pObj ); + Sprite *item = static_cast( child ); item->updateDisplayedColor(_displayedColor); } diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index b59850632b..0d668256f2 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -88,7 +88,7 @@ public: virtual float getLetterPosXLeft( int index ) const override; virtual float getLetterPosXRight( int index ) const override; - virtual Sprite * getLetterAt(int ID) override; + virtual Sprite * getLetter(int ID) override; // font related stuff virtual int getCommonLineHeight() const override; diff --git a/cocos/2d/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h index c2027350fc..8e1530fb3e 100644 --- a/cocos/2d/CCLabelTextFormatProtocol.h +++ b/cocos/2d/CCLabelTextFormatProtocol.h @@ -48,7 +48,7 @@ public: virtual float getLetterPosXLeft(int index) const = 0; virtual float getLetterPosXRight(int index) const = 0; // sprite related stuff - virtual cocos2d::Sprite *getLetterAt(int ID) = 0; + virtual cocos2d::Sprite *getLetter(int ID) = 0; // font related stuff virtual int getCommonLineHeight() const = 0; diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 9aa5d20947..e329dafcbe 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -264,9 +264,9 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() label->setAnchorPoint( Point(0.5f, 0.5f) ); - auto BChar = (Sprite*) label->getLetterAt(0); - auto FChar = (Sprite*) label->getLetterAt(7); - auto AChar = (Sprite*) label->getLetterAt(12); + auto BChar = (Sprite*) label->getLetter(0); + auto FChar = (Sprite*) label->getLetter(7); + auto AChar = (Sprite*) label->getLetter(12); auto rotate = RotateBy::create(2, 360); @@ -296,7 +296,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() addChild(label2, 0, kTagBitmapAtlas2); label2->setPosition( Point(s.width/2.0f, 80) ); - auto lastChar = (Sprite*) label2->getLetterAt(3); + auto lastChar = (Sprite*) label2->getLetter(3); lastChar->runAction( rot_4ever->clone() ); schedule( schedule_selector(LabelFNTSpriteActions::step), 0.1f); From 8884c58ac1a5de5352e9d6a82326dae1f30cc519 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 31 Oct 2013 21:03:06 +0800 Subject: [PATCH 314/557] issue #2826: Updating ScriptingCore.cpp. runScript small fix. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 59fe928dde..65c136da87 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -493,7 +493,7 @@ void ScriptingCore::createGlobalContext() { //JS_SetGCZeal(this->_cx, 2, JS_DEFAULT_ZEAL_FREQ); #endif this->_global = NewGlobalObject(_cx); - JS_AddObjectRoot(_cx, &_global); + JSAutoCompartment ac(_cx, _global); js::SetDefaultObjectForContext(_cx, _global); @@ -521,7 +521,7 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c cocos2d::FileUtils *futil = cocos2d::FileUtils::getInstance(); - std::string fullPath = futil->fullPathForFilename(path); + if (global == NULL) { global = _global; } @@ -534,9 +534,6 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c js::RootedScript script(cx); js::RootedObject obj(cx, global); - JS::CompileOptions options(cx); - options.setUTF8(true).setFileAndLine(fullPath.c_str(), 1); - // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; unsigned long length = 0; @@ -554,6 +551,10 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c /* Clear any pending exception from previous failed decoding. */ ReportException(cx); + std::string fullPath = futil->fullPathForFilename(path); + JS::CompileOptions options(cx); + options.setUTF8(true).setFileAndLine(fullPath.c_str(), 1); + #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) String* content = String::createWithContentsOfFile(path); if (content) { From 5891f009672bc0b81a4e7eaea38e641f9e0be11d Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 21:52:28 +0800 Subject: [PATCH 315/557] issue #3037:Add assetsmananger lua binding and a releated test sample --- .../project.pbxproj.REMOVED.git-id | 2 +- external/lua/luajit/build_mac.sh | 4 ++-- .../TestLua/Classes}/lua_assetsmanager_test_sample.cpp | 0 .../Lua/TestLua/Classes}/lua_assetsmanager_test_sample.h | 0 samples/Lua/TestLua/proj.android/jni/Android.mk | 8 ++++++-- 5 files changed, 9 insertions(+), 5 deletions(-) rename {cocos/scripting/lua/bindings => samples/Lua/TestLua/Classes}/lua_assetsmanager_test_sample.cpp (100%) rename {cocos/scripting/lua/bindings => samples/Lua/TestLua/Classes}/lua_assetsmanager_test_sample.h (100%) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 3a1978b2ff..da0402247e 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3cdc74655a14f57ae21036886ccf31e32aaadce4 \ No newline at end of file +8d8d7ea290e8626153fe3dd955b85757a7bb6e05 \ No newline at end of file diff --git a/external/lua/luajit/build_mac.sh b/external/lua/luajit/build_mac.sh index d3b43e2d4b..35e88665f8 100755 --- a/external/lua/luajit/build_mac.sh +++ b/external/lua/luajit/build_mac.sh @@ -1,7 +1,7 @@ #!/bin/sh DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -SRCDIR=$DIR/LuaJit-2.0.1 -DESTDIR=$DIR/mac +SRCDIR=$DIR/src +DESTDIR=$DIR/prebuilt/mac MACOSX_DEPLOYMENT_TARGET="10.6" rm "$DESTDIR"/*.a diff --git a/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp similarity index 100% rename from cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.cpp rename to samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp diff --git a/cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.h similarity index 100% rename from cocos/scripting/lua/bindings/lua_assetsmanager_test_sample.h rename to samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.h diff --git a/samples/Lua/TestLua/proj.android/jni/Android.mk b/samples/Lua/TestLua/proj.android/jni/Android.mk index daadaf2a3a..5dc5404354 100644 --- a/samples/Lua/TestLua/proj.android/jni/Android.mk +++ b/samples/Lua/TestLua/proj.android/jni/Android.mk @@ -7,10 +7,14 @@ LOCAL_MODULE := testlua_shared LOCAL_MODULE_FILENAME := libtestlua LOCAL_SRC_FILES := testlua/main.cpp \ - ../../Classes/AppDelegate.cpp + ../../Classes/AppDelegate.cpp \ + ../../Classes/lua_assetsmanager_test_sample.cpp -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \ + $(LOCAL_PATH)/../../../../external/lua/tolua \ + $(LOCAL_PATH)/../../../../cocos/scripting/lua/bindings + LOCAL_STATIC_LIBRARIES := curl_static_prebuilt From de4aaeda2d232f72f3d02695456898a29e456bcd Mon Sep 17 00:00:00 2001 From: samuelhu Date: Thu, 31 Oct 2013 22:06:34 +0800 Subject: [PATCH 316/557] issue #3049:Add XMLHttpRequest lua binding and corresponding test sample --- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- samples/Lua/TestLua/Resources/luaScript/mainMenu.lua | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 3a1978b2ff..9bd7c96932 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3cdc74655a14f57ae21036886ccf31e32aaadce4 \ No newline at end of file +99dcbba48124bf51788735fe775650f659d7302c \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua index c1c5088530..9c4640be8e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua @@ -44,6 +44,7 @@ require "luaScript/TransitionsTest/TransitionsTest" require "luaScript/UserDefaultTest/UserDefaultTest" require "luaScript/ZwoptexTest/ZwoptexTest" require "luaScript/LuaBridgeTest/LuaBridgeTest" +require "luaScript/XMLHttpRequestTest/XMLHttpRequestTest" local LINE_SPACE = 40 @@ -97,6 +98,7 @@ local _allTests = { { isSupported = true, name = "TouchesTest" , create_func = TouchesTest }, { isSupported = true, name = "TransitionsTest" , create_func = TransitionsTest }, { isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain }, + { isSupported = true, name = "XMLHttpRequestTest" , create_func = XMLHttpRequestTestMain }, { isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain } } From 17af5b6850dda462c2eb85d9102e8a185078f512 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 31 Oct 2013 17:56:15 -0700 Subject: [PATCH 317/557] Adds flags in GLProgram to prevent sending uneeded uniforms --- cocos/2d/CCGLProgram.cpp | 61 ++++++++++++++++++++++------------------ cocos/2d/CCGLProgram.h | 11 +++++++- 2 files changed, 43 insertions(+), 29 deletions(-) diff --git a/cocos/2d/CCGLProgram.cpp b/cocos/2d/CCGLProgram.cpp index 83da8f9bdc..61fd7aaa66 100644 --- a/cocos/2d/CCGLProgram.cpp +++ b/cocos/2d/CCGLProgram.cpp @@ -75,7 +75,7 @@ GLProgram::GLProgram() , _vertShader(0) , _fragShader(0) , _hashForUniforms(NULL) -, _usesTime(false) +, _flags() { memset(_uniforms, 0, sizeof(_uniforms)); } @@ -223,27 +223,30 @@ void GLProgram::addAttribute(const char* attributeName, GLuint index) void GLProgram::updateUniforms() { _uniforms[UNIFORM_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_P_MATRIX); - _uniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_MV_MATRIX); - _uniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_MVP_MATRIX); + _uniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MV_MATRIX); + _uniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MVP_MATRIX); - _uniforms[GLProgram::UNIFORM_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_TIME); - _uniforms[GLProgram::UNIFORM_SIN_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_SIN_TIME); - _uniforms[GLProgram::UNIFORM_COS_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_COS_TIME); - - _usesTime = ( - _uniforms[GLProgram::UNIFORM_TIME] != -1 || - _uniforms[GLProgram::UNIFORM_SIN_TIME] != -1 || - _uniforms[GLProgram::UNIFORM_COS_TIME] != -1 - ); - - _uniforms[UNIFORM_RANDOM01] = glGetUniformLocation(_program, UNIFORM_NAME_RANDOM01); + _uniforms[UNIFORM_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_TIME); + _uniforms[UNIFORM_SIN_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_SIN_TIME); + _uniforms[UNIFORM_COS_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_COS_TIME); + + _uniforms[UNIFORM_RANDOM01] = glGetUniformLocation(_program, UNIFORM_NAME_RANDOM01); _uniforms[UNIFORM_SAMPLER] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER); + _flags.usesMVP = _uniforms[UNIFORM_MVP_MATRIX] != -1; + _flags.usesMV = (_uniforms[UNIFORM_MV_MATRIX] != -1 && _uniforms[UNIFORM_P_MATRIX] != -1 ); + _flags.usesTime = ( + _uniforms[UNIFORM_TIME] != -1 || + _uniforms[UNIFORM_SIN_TIME] != -1 || + _uniforms[UNIFORM_COS_TIME] != -1 + ); + _flags.usesRandom = _uniforms[UNIFORM_RANDOM01] != -1; + this->use(); // Since sample most probably won't change, set it to 0 now. - this->setUniformLocationWith1i(_uniforms[GLProgram::UNIFORM_SAMPLER], 0); + this->setUniformLocationWith1i(_uniforms[UNIFORM_SAMPLER], 0); } bool GLProgram::link() @@ -527,19 +530,23 @@ void GLProgram::setUniformsForBuiltins() { kmMat4 matrixP; kmMat4 matrixMV; - kmMat4 matrixMVP; - + kmGLGetMatrix(KM_GL_PROJECTION, &matrixP); kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV); - kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); - - setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1); - setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1); - setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1); - - if(_usesTime) - { + + if(_flags.usesMVP) { + kmMat4 matrixMVP; + kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); + setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1); + } + + if(_flags.usesMV) { + setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1); + setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1); + } + + if(_flags.usesTime) { Director *director = Director::getInstance(); // This doesn't give the most accurate global time value. // Cocos2D doesn't store a high precision time value, so this will have to do. @@ -551,10 +558,8 @@ void GLProgram::setUniformsForBuiltins() setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_COS_TIME], time/8.0, time/4.0, time/2.0, cosf(time)); } - if (_uniforms[GLProgram::UNIFORM_RANDOM01] != -1) - { + if(_flags.usesRandom) setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_RANDOM01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1()); - } } void GLProgram::reset() diff --git a/cocos/2d/CCGLProgram.h b/cocos/2d/CCGLProgram.h index cea1add0b2..f218f7181e 100644 --- a/cocos/2d/CCGLProgram.h +++ b/cocos/2d/CCGLProgram.h @@ -244,7 +244,16 @@ private: GLuint _fragShader; GLint _uniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; - bool _usesTime; + + struct flag_struct { + unsigned int usesTime:1; + unsigned int usesMVP:1; + unsigned int usesMV:1; + unsigned int usesRandom:1; + + // handy way to initialize the bitfield + flag_struct() { memset(this, 0, sizeof(*this)); } + } _flags; }; // end of shaders group From 0c6748b5777c836ac4629a49d1ab110d91bc70b5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 10:44:15 +0800 Subject: [PATCH 318/557] issue #2826: Bug fix of 'js::IsInRequest' --- external/spidermonkey/include/android/js/RootingAPI.h | 5 +++-- external/spidermonkey/include/ios/js/RootingAPI.h | 5 +++-- external/spidermonkey/include/mac/js/RootingAPI.h | 5 +++-- external/spidermonkey/include/win32/js/RootingAPI.h | 5 +++-- .../android/armeabi-v7a/libjs_static.a.REMOVED.git-id | 2 +- .../prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id | 2 +- .../prebuilt/android/x86/libjs_static.a.REMOVED.git-id | 2 +- .../spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id | 2 +- .../spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id | 2 +- .../prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id | 2 +- .../prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id | 2 +- 11 files changed, 19 insertions(+), 15 deletions(-) diff --git a/external/spidermonkey/include/android/js/RootingAPI.h b/external/spidermonkey/include/android/js/RootingAPI.h index 99295f1238..c4a5925ae7 100644 --- a/external/spidermonkey/include/android/js/RootingAPI.h +++ b/external/spidermonkey/include/android/js/RootingAPI.h @@ -628,11 +628,12 @@ struct GCMethods #endif }; -#if defined(DEBUG) +// XXX: Needed for cocos2d JS Bindings +//#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -#endif +//#endif } /* namespace js */ diff --git a/external/spidermonkey/include/ios/js/RootingAPI.h b/external/spidermonkey/include/ios/js/RootingAPI.h index 99295f1238..c4a5925ae7 100644 --- a/external/spidermonkey/include/ios/js/RootingAPI.h +++ b/external/spidermonkey/include/ios/js/RootingAPI.h @@ -628,11 +628,12 @@ struct GCMethods #endif }; -#if defined(DEBUG) +// XXX: Needed for cocos2d JS Bindings +//#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -#endif +//#endif } /* namespace js */ diff --git a/external/spidermonkey/include/mac/js/RootingAPI.h b/external/spidermonkey/include/mac/js/RootingAPI.h index 99295f1238..c4a5925ae7 100644 --- a/external/spidermonkey/include/mac/js/RootingAPI.h +++ b/external/spidermonkey/include/mac/js/RootingAPI.h @@ -628,11 +628,12 @@ struct GCMethods #endif }; -#if defined(DEBUG) +// XXX: Needed for cocos2d JS Bindings +//#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -#endif +//#endif } /* namespace js */ diff --git a/external/spidermonkey/include/win32/js/RootingAPI.h b/external/spidermonkey/include/win32/js/RootingAPI.h index 99295f1238..c4a5925ae7 100644 --- a/external/spidermonkey/include/win32/js/RootingAPI.h +++ b/external/spidermonkey/include/win32/js/RootingAPI.h @@ -628,11 +628,12 @@ struct GCMethods #endif }; -#if defined(DEBUG) +// XXX: Needed for cocos2d JS Bindings +//#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -#endif +//#endif } /* namespace js */ diff --git a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id index 8362daf11f..66d2ff3161 100644 --- a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -faf19f806c33a8c42138cd4ada1c76d04f9510f4 \ No newline at end of file +0e1091b9f67b4d348d01b69e998be70c9e0b2dad \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id index 8da98b5613..8a8f30faca 100644 --- a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -9c5b123f113fb3b0b6846b4f1123ec5a40004944 \ No newline at end of file +23bfd06f14371832fa99b4efb76133ade10887ec \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id index 74e8973064..fbdaca36eb 100644 --- a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -3e18fa7933f481d605147b1d46dd7afee105fa2c \ No newline at end of file +1eb9de4a5ab182f329be479e736c06ac8ab83a00 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id index a263aa1a15..3aa7da9b21 100644 --- a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -62ff11f15f6f4dae163513e336bc3e4671b91a90 \ No newline at end of file +1267f1437ae315da4c23e0fc5e7e3f70b4b3c8e2 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id index 609f8680c6..e3f35605ac 100644 --- a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -591cdbb9304d6f7b5682542b7a50e0b5ae4d6a4d \ No newline at end of file +2385a209e3aa59896599e079658d761fd2985c9a \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id index 7e9dc81732..e9a69561f8 100644 --- a/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id @@ -1 +1 @@ -c1212ee7de1da38ee10b27e327120205ab2cac7c \ No newline at end of file +66328744e55deaa5397a58a7e0a49b34a602697b \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id index ae3f274acc..729e48a68d 100644 --- a/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id @@ -1 +1 @@ -5991d26d951ae7b8398cd037bb22422ec33ab949 \ No newline at end of file +746eb762bc48a27219221c08bd8ada90727f3921 \ No newline at end of file From baccf828f32de6a628facc0a248bcf1388bea36c Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 10:45:01 +0800 Subject: [PATCH 319/557] closed #2826: Removing js::IsInRequest in ScriptingCore.cpp for win32. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 65c136da87..5d902c1c23 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -79,15 +79,6 @@ static std::map ports_sockets; // name ~> globals static std::map globals; -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) -namespace js { -bool IsInRequest(JSContext* cx) -{ - return true; -} -} -#endif - static void ReportException(JSContext *cx) { if (JS_IsExceptionPending(cx)) { From 0298c338a6198de180bb287ead1d496a7675ccf5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 10:46:06 +0800 Subject: [PATCH 320/557] issue #2826: Updating cocos2d-console submodule. --- tools/cocos2d-console | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cocos2d-console b/tools/cocos2d-console index 37a695d46c..3556d41429 160000 --- a/tools/cocos2d-console +++ b/tools/cocos2d-console @@ -1 +1 @@ -Subproject commit 37a695d46c0a7386a261733f9f76583895681702 +Subproject commit 3556d41429e487e88fbbd5222df95fdd4c2ddf7b From f3ff7955a8fc94a9033efd4b89f056e6c25fa57d Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 1 Nov 2013 11:18:02 +0800 Subject: [PATCH 321/557] issue #3037:Modify platform build config --- .../project.pbxproj.REMOVED.git-id | 2 +- samples/Lua/TestLua/Classes/AppDelegate.cpp | 2 +- .../luaScript/AssetsManagerTest/AssetsManagerTest.lua | 7 ++++--- samples/Lua/TestLua/proj.android/jni/Android.mk | 9 +++++---- samples/Lua/TestLua/proj.linux/Makefile | 7 +++++-- 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index da0402247e..56fa5cef1e 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -8d8d7ea290e8626153fe3dd955b85757a7bb6e05 \ No newline at end of file +ec80e8e2bcdb07b161a4ba7fcdee13bfec8cf347 \ No newline at end of file diff --git a/samples/Lua/TestLua/Classes/AppDelegate.cpp b/samples/Lua/TestLua/Classes/AppDelegate.cpp index 025f938b6b..deefa14f40 100644 --- a/samples/Lua/TestLua/Classes/AppDelegate.cpp +++ b/samples/Lua/TestLua/Classes/AppDelegate.cpp @@ -51,7 +51,7 @@ bool AppDelegate::applicationDidFinishLaunching() LuaEngine* pEngine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(pEngine); -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ||CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ||CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) LuaStack* stack = pEngine->getLuaStack(); register_assetsmanager_test_sample(stack->getLuaState()); #endif diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua index 853342a706..67be1499eb 100644 --- a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua @@ -12,23 +12,24 @@ local menuItemNames = local winSize = cc.Director:getInstance():getWinSize() local function updateLayer() + local layer = cc.Layer:create() local support = false if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) - or (cc.PLATFORM_OS_IPHONE == targetPlatform) then + or (cc.PLATFORM_OS_MAC == targetPlatform) then support = true end if not support then - return nil + print("Platform is not supported!") + return layer end local isUpdateItemClicked = false local assetsManager = nil local pathToSave = "" - local layer = cc.Layer:create() local menu = cc.Menu:create() menu:setPosition(cc.p(0, 0)) cc.MenuItemFont:setFontName("Arial") diff --git a/samples/Lua/TestLua/proj.android/jni/Android.mk b/samples/Lua/TestLua/proj.android/jni/Android.mk index 5dc5404354..4bc4ceafb3 100644 --- a/samples/Lua/TestLua/proj.android/jni/Android.mk +++ b/samples/Lua/TestLua/proj.android/jni/Android.mk @@ -6,14 +6,15 @@ LOCAL_MODULE := testlua_shared LOCAL_MODULE_FILENAME := libtestlua -LOCAL_SRC_FILES := testlua/main.cpp \ +LOCAL_SRC_FILES += testlua/main.cpp \ ../../Classes/AppDelegate.cpp \ ../../Classes/lua_assetsmanager_test_sample.cpp -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \ - $(LOCAL_PATH)/../../../../external/lua/tolua \ - $(LOCAL_PATH)/../../../../cocos/scripting/lua/bindings +LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../Classes \ + $(LOCAL_PATH)/../../../../../external/lua/tolua \ + $(LOCAL_PATH)/../../../../../extensions \ + $(LOCAL_PATH)/../../../../../cocos/scripting/lua/bindings LOCAL_STATIC_LIBRARIES := curl_static_prebuilt diff --git a/samples/Lua/TestLua/proj.linux/Makefile b/samples/Lua/TestLua/proj.linux/Makefile index 5151716394..8e9246c6ee 100644 --- a/samples/Lua/TestLua/proj.linux/Makefile +++ b/samples/Lua/TestLua/proj.linux/Makefile @@ -4,10 +4,13 @@ COCOS_ROOT = ../../../.. INCLUDES = -I../Classes \ -I$(COCOS_ROOT)/audio/include \ -I$(COCOS_ROOT)/cocos/scripting/lua/bindings \ - -I$(COCOS_ROOT)/external/lua/lua + -I$(COCOS_ROOT)/external/lua/lua \ + -I$(COCOS_ROOT)/external/lua/tolua \ + -I$(COCOS_ROOT)/extensions SOURCES = main.cpp \ -../Classes/AppDelegate.cpp +../Classes/AppDelegate.cpp \ +../Classes/lua_assetsmanager_test_sample.cpp SHAREDLIBS += -lcocos2d -lcocosdenshion -llua From 5010779e39242f9b0ff40cbee5b1fcb247ad2e86 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 1 Nov 2013 11:36:06 +0800 Subject: [PATCH 322/557] issue #3049:Reset .project file in pro.android. --- samples/Lua/TestLua/proj.android/.project | 52 +++++++++++++++++++++-- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/samples/Lua/TestLua/proj.android/.project b/samples/Lua/TestLua/proj.android/.project index 8703060095..3c1261c623 100644 --- a/samples/Lua/TestLua/proj.android/.project +++ b/samples/Lua/TestLua/proj.android/.project @@ -6,12 +6,56 @@ - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.buildArguments + ${ProjDirPath}/build_native.sh + + + org.eclipse.cdt.make.core.buildCommand + bash + + + org.eclipse.cdt.make.core.buildLocation + ${ProjDirPath} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + false From 1d932ae95f5a04df83895934ed63f40dd8016f0d Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 11:46:02 +0800 Subject: [PATCH 323/557] Updating travic-ci scripts. --- tools/travis-scripts/before-install.sh | 4 +-- tools/travis-scripts/generate-jsbindings.sh | 8 ++--- tools/travis-scripts/run-script.sh | 39 ++++++--------------- 3 files changed, 17 insertions(+), 34 deletions(-) diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh index 4353b026a8..93cdb195fe 100755 --- a/tools/travis-scripts/before-install.sh +++ b/tools/travis-scripts/before-install.sh @@ -102,8 +102,8 @@ elif [ "$PLATFORM"x = "linux"x ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 90 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7 g++ --version - bash $COCOS2DX_ROOT/install-deps-linux.sh - bash $DIR/install_glfw.sh + bash $COCOS2DX_ROOT/build/install-deps-linux.sh + bash $COCOS2DX_ROOT/build/install_glfw.sh install_android_ndk install_llvm elif [ "$PLATFORM"x = "nacl"x ]; then diff --git a/tools/travis-scripts/generate-jsbindings.sh b/tools/travis-scripts/generate-jsbindings.sh index 2a1dd3b69a..dcb2b9bd0f 100755 --- a/tools/travis-scripts/generate-jsbindings.sh +++ b/tools/travis-scripts/generate-jsbindings.sh @@ -20,7 +20,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR"/../.. TOJS_ROOT=$COCOS2DX_ROOT/tools/tojs TOLUA_ROOT=$COCOS2DX_ROOT/tools/tolua -GENERATED_WORKTREE="$COCOS2DX_ROOT"/scripting/auto-generated +GENERATED_WORKTREE="$COCOS2DX_ROOT"/cocos/scripting/auto-generated COMMITTAG="[AUTO]" # Exit on error @@ -75,10 +75,10 @@ echo "Set git user for the submodule of ${GENERATED_WORKTREE}" git config user.email ${GH_EMAIL} git config user.name ${GH_USER} #Set remotes -git remote add upstream https://${GH_USER}:${GH_PASSWORD}@github.com/folecr/cocos2dx-autogen-bindings.git 2> /dev/null > /dev/null +git remote add upstream https://${GH_USER}:${GH_PASSWORD}@github.com/cocos2d-x/bindings-auto-generated.git 2> /dev/null > /dev/null -echo "Delete all directories and files except '.git' and 'README'." -ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README$ | xargs -I{} rm -rf {} +echo "Delete all directories and files except '.git' and 'README.md'." +ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README.md$ | xargs -I{} rm -rf {} echo "Show files in ${GENERATED_WORKTREE} folder." ls -a popd diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 79c063dc0e..7e86b00319 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -5,15 +5,6 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR"/../.. -build_android() -{ - echo "Current dir: `pwd`" - pushd $1/proj.android - ln -s $COCOS2DX_ROOT/android_build_objs obj - ./build_native.sh - popd -} - if [ "$GEN_JSB"x = "YES"x ]; then # Re-generation of the javascript bindings can perform push of the new # version back to github. We don't do this for pull requests, or if @@ -51,23 +42,15 @@ elif [ "$PLATFORM"x = "android"x ]; then # Create a directory for temporary objects mkdir android_build_objs - # Build samples - echo "Building samples ..." - cd $COCOS2DX_ROOT/samples/Cpp - build_android HelloCpp - build_android TestCpp - build_android AssetsManagerTest + PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") + for i in ${PROJECTS[*]}; do + ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/samples/$i/proj.android/obj + done - cd $COCOS2DX_ROOT/samples/Javascript - build_android TestJavascript - build_android CocosDragonJS - build_android CrystalCraze - build_android MoonWarriors - build_android WatermelonWithMe - - cd $COCOS2DX_ROOT/samples/Lua - build_android HelloLua - build_android TestLua + # Build all samples + echo "Building all samples ..." + cd $COCOS2DX_ROOT/build + ./android-build.py all # Build template # echo "Building template ..." @@ -80,7 +63,7 @@ elif [ "$PLATFORM"x = "nacl"x ]; then export NACL_SDK_ROOT=$HOME/bin/nacl_sdk/pepper_canary export PATH=$PATH:$NACL_SDK_ROOT/toolchain/linux_x86_newlib/bin export PATH=$PATH:$NACL_SDK_ROOT/toolchain/linux_arm_newlib/bin - cd $COCOS2DX_ROOT + cd $COCOS2DX_ROOT/build make -j4 elif [ "$PLATFORM"x = "linux"x ]; then # Generate binding glue codes @@ -88,7 +71,7 @@ elif [ "$PLATFORM"x = "linux"x ]; then cd $COCOS2DX_ROOT/tools/travis-scripts ./generate-jsbindings.sh - cd $COCOS2DX_ROOT + cd $COCOS2DX_ROOT/build make -j4 elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes @@ -96,7 +79,7 @@ elif [ "$PLATFORM"x = "emscripten"x ]; then cd $COCOS2DX_ROOT/tools/travis-scripts ./generate-jsbindings.sh - cd $COCOS2DX_ROOT + cd $COCOS2DX_ROOT/build export PYTHON=/usr/bin/python export LLVM=$HOME/bin/clang+llvm-3.2/bin export LLVM_ROOT=$LLVM From 72d6f8650b3d06ae67332cdfb6f933ec54c50978 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 11:50:43 +0800 Subject: [PATCH 324/557] Regular expression fix for generate-jsbindings.sh. --- tools/travis-scripts/generate-jsbindings.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/generate-jsbindings.sh b/tools/travis-scripts/generate-jsbindings.sh index dcb2b9bd0f..cd7f897e20 100755 --- a/tools/travis-scripts/generate-jsbindings.sh +++ b/tools/travis-scripts/generate-jsbindings.sh @@ -78,7 +78,7 @@ git config user.name ${GH_USER} git remote add upstream https://${GH_USER}:${GH_PASSWORD}@github.com/cocos2d-x/bindings-auto-generated.git 2> /dev/null > /dev/null echo "Delete all directories and files except '.git' and 'README.md'." -ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README.md$ | xargs -I{} rm -rf {} +ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README\.md$ | xargs -I{} rm -rf {} echo "Show files in ${GENERATED_WORKTREE} folder." ls -a popd From d98c6f8de60a1e5449ca7ba9ae817d07b01792ea Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 1 Nov 2013 14:27:29 +0800 Subject: [PATCH 325/557] can run build-android.python in any path --- build/android-build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/android-build.py b/build/android-build.py index 62bc226e77..e59ee61bf1 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -164,7 +164,7 @@ def build_samples(target,ndk_build_param): select_toolchain_version() build_targets = caculate_built_samples(target) - current_dir = os.getcwd() + current_dir = os.path.dirname(os.path.realpath(__file__)) cocos_root = os.path.join(current_dir, "..") app_android_root = '' From a9054ba14abd41c836d3f8de177ede612e2d0fb7 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Fri, 1 Nov 2013 14:36:44 +0800 Subject: [PATCH 326/557] 1.add method to set collider filter --- .../editor-support/cocostudio/CCArmature.cpp | 10 ++ cocos/editor-support/cocostudio/CCArmature.h | 2 + cocos/editor-support/cocostudio/CCBone.cpp | 27 +++++ cocos/editor-support/cocostudio/CCBone.h | 2 + .../cocostudio/CCColliderDetector.cpp | 98 +++++++++++++++---- .../cocostudio/CCColliderDetector.h | 47 +++++++-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 8 +- 7 files changed, 161 insertions(+), 33 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index ac04de1af5..baa56ddfb7 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -728,6 +728,16 @@ Bone *Armature::getParentBone() return _parentBone; } +void CCArmature::setColliderFilter(ColliderFilter *filter) +{ + DictElement *element = NULL; + CCDICT_FOREACH(_boneDic, element) + { + Bone *bone = static_cast(element->getObject()); + bone->setColliderFilter(filter); + } +} + #if ENABLE_PHYSICS_BOX2D_DETECT b2Body *Armature::getBody() { diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 15abe96079..bf11841f7e 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -175,6 +175,8 @@ public: virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual void setColliderFilter(ColliderFilter *filter); + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 804ea5d65a..3132acec79 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -441,4 +441,31 @@ Array *Bone::getColliderBodyList() } + +void Bone::setColliderFilter(ColliderFilter *filter) +{ + Array *array = _displayManager->getDecorativeDisplayList(); + Object *object = NULL; + CCARRAY_FOREACH(array, object) + { + DecorativeDisplay *decoDisplay = static_cast(object); + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + detector->setColliderFilter(filter); + } + } +} +ColliderFilter *Bone::getColliderFilter() +{ + if (DecorativeDisplay *decoDisplay = _displayManager->getCurrentDecorativeDisplay()) + { + if (ColliderDetector *detector = decoDisplay->getColliderDetector()) + { + return detector->getColliderFilter(); + } + } + return NULL; +} + + } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 1a1d3c26d6..6edd3fe8cb 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -159,6 +159,8 @@ public: */ virtual cocos2d::Array *getColliderBodyList(); + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); public: /* * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 8857832c99..cceb1a9b72 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -37,13 +37,44 @@ using namespace cocos2d; namespace cocostudio { +#if ENABLE_PHYSICS_BOX2D_DETECT +ColliderFilter::ColliderFilter(unsigned short categoryBits, unsigned short maskBits, signed short groupIndex) + : _categoryBits(categoryBits) + , _maskBits(maskBits) + , _groupIndex(groupIndex) +{ +} + +void ColliderFilter::updateShape(b2Fixture *fixture) +{ + b2Filter filter; + filter.categoryBits = _categoryBits; + filter.groupIndex = _groupIndex; + filter.maskBits = _maskBits; + + fixture->SetFilterData(filter); +} + +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +ColliderFilter::ColliderFilter(cpCollisionType collisionType, cpGroup group) + : _collisionType(collisionType) + , _group(group) +{ +} +void ColliderFilter::updateShape(cpShape *shape) +{ + shape->collision_type = _collisionType; + shape->group = _group; +} +#endif + #if ENABLE_PHYSICS_BOX2D_DETECT ColliderBody::ColliderBody(ContourData *contourData) : _fixture(NULL) - , _filter(NULL) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX _calculatedVertexList = Array::create(); @@ -57,6 +88,7 @@ ColliderBody::ColliderBody(ContourData *contourData) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); + _filter = new ColliderFilter(); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX _calculatedVertexList = Array::create(); @@ -68,14 +100,20 @@ ColliderBody::ColliderBody(ContourData *contourData) ColliderBody::~ColliderBody() { CC_SAFE_RELEASE(_contourData); + CC_SAFE_DELETE(_filter); #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX CC_SAFE_RELEASE(_calculatedVertexList); #endif +} -#if ENABLE_PHYSICS_BOX2D_DETECT - CC_SAFE_DELETE(_filter); -#endif +void ColliderBody::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; +} +ColliderFilter *ColliderBody::getColliderFilter() +{ + return _filter; } @@ -106,6 +144,7 @@ ColliderDetector *ColliderDetector::create(Bone *bone) ColliderDetector::ColliderDetector() : _colliderBodyList(NULL) + , _filter(NULL) , _active(false) { _body = NULL; @@ -115,6 +154,7 @@ ColliderDetector::~ColliderDetector() { _colliderBodyList->removeAllObjects(); CC_SAFE_DELETE(_colliderBodyList); + CC_SAFE_DELETE(_filter); } bool ColliderDetector::init() @@ -123,6 +163,8 @@ bool ColliderDetector::init() CCASSERT(_colliderBodyList, "create _colliderBodyList failed!"); _colliderBodyList->retain(); + _filter = new ColliderFilter(); + return true; } @@ -206,9 +248,6 @@ void ColliderDetector::setActive(bool active) ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); - b2Filter *filter = colliderBody->getB2Filter(); - *filter = fixture->GetFilterData(); - _body->DestroyFixture(fixture); colliderBody->setB2Fixture(NULL); } @@ -256,6 +295,34 @@ Array *ColliderDetector::getColliderBodyList() return _colliderBodyList; } +void ColliderDetector::setColliderFilter(ColliderFilter *filter) +{ + *_filter = *filter; + + Object *object = NULL; + CCARRAY_FOREACH(_colliderBodyList, object) + { + ColliderBody *colliderBody = (ColliderBody *)object; + colliderBody->setColliderFilter(filter); + +#if ENABLE_PHYSICS_BOX2D_DETECT + if (colliderBody->getB2Fixture()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getB2Fixture()); + } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + if (colliderBody->getShape()) + { + colliderBody->getColliderFilter()->updateShape(colliderBody->getShape()); + } +#endif + } +} +ColliderFilter *ColliderDetector::getColliderFilter() +{ + return _filter; +} + Point helpPoint; @@ -378,15 +445,7 @@ void ColliderDetector::setBody(b2Body *pBody) } colliderBody->setB2Fixture(fixture); - if (colliderBody->getB2Filter() == NULL) - { - b2Filter *filter = new b2Filter; - colliderBody->setB2Filter(filter); - } - else - { - fixture->SetFilterData(*colliderBody->getB2Filter()); - } + colliderBody->getColliderFilter()->updateShape(fixture); } } @@ -420,9 +479,14 @@ void ColliderDetector::setBody(cpBody *pBody) shape->sensor = true; shape->data = _bone; - cpSpaceAddShape(_body->space_private, shape); + + if (_active) + { + cpSpaceAddShape(_body->space_private, shape); + } colliderBody->setShape(shape); + colliderBody->getColliderFilter()->updateShape(shape); delete []verts; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 9e8b7246c6..e2da724c80 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -33,24 +33,48 @@ THE SOFTWARE. #endif +#if ENABLE_PHYSICS_CHIPMUNK_DETECT +#include "chipmunk.h" +struct cpBody; +struct cpShape; +#elif ENABLE_PHYSICS_BOX2D_DETECT class b2Body; class b2Fixture; struct b2Filter; - -struct cpBody; -struct cpShape; +#endif namespace cocostudio { class Bone; + +class ColliderFilter +{ +public: + ~ColliderFilter() { } +#if ENABLE_PHYSICS_BOX2D_DETECT +public: + ColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); + void updateShape(b2Fixture *fixture); +protected: + CC_SYNTHESIZE(unsigned short, _categoryBits, CategoryBits); + CC_SYNTHESIZE(unsigned short, _maskBits, MaskBits); + CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +public: + ColliderFilter(cpCollisionType collisionType = 0, cpGroup group = 0); + void updateShape(cpShape *shape); +protected: + CC_SYNTHESIZE(cpCollisionType, _collisionType, CollisionType); + CC_SYNTHESIZE(cpGroup, _group, Group); +#endif +}; + class ColliderBody : public cocos2d::Object { public: #if ENABLE_PHYSICS_BOX2D_DETECT CC_SYNTHESIZE(b2Fixture *, _fixture, B2Fixture) - CC_SYNTHESIZE(b2Filter *, _filter, B2Filter) - #elif ENABLE_PHYSICS_CHIPMUNK_DETECT CC_SYNTHESIZE(cpShape *, _shape, Shape) #endif @@ -59,12 +83,13 @@ public: ColliderBody(ContourData *contourData); ~ColliderBody(); - inline ContourData *getContourData() - { - return _contourData; - } + inline ContourData *getContourData() { return _contourData; } + + void setColliderFilter(ColliderFilter *filter); + ColliderFilter *getColliderFilter(); private: ContourData *_contourData; + ColliderFilter *_filter; #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); @@ -106,8 +131,12 @@ public: cocos2d::Array *getColliderBodyList(); + virtual void setColliderFilter(ColliderFilter *filter); + virtual ColliderFilter *getColliderFilter(); protected: cocos2d::Array *_colliderBodyList; + ColliderFilter *_filter; + CC_SYNTHESIZE(Bone *, _bone, Bone); #if ENABLE_PHYSICS_BOX2D_DETECT diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 35db4c129b..a6dfd04092 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1008,13 +1008,7 @@ void TestColliderDetector::initWorld() cpSpaceAddBody(space, body); armature2->setBody(body); - shape = armature2->getShapeList(); - while(shape) - { - cpShape *next = shape->next_private; - shape->collision_type = eEnemyTag; - shape = next; - } + armature2->setColliderFilter(&ColliderFilter(eEnemyTag)); cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); } From b0fdb66d2d8d17ea84c3b107a38fb66c3eebee45 Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 1 Nov 2013 14:38:14 +0800 Subject: [PATCH 327/557] Modify the all luajit build scripts and let libluajit.a of mac only support 64bit --- .../project.pbxproj.REMOVED.git-id | 2 +- external/lua/luajit/build_android.sh | 8 +++--- external/lua/luajit/build_ios.sh | 4 +-- external/lua/luajit/build_mac.sh | 25 +++---------------- .../prebuilt/mac/libluajit.a.REMOVED.git-id | 2 +- tools/tolua/cocos2dx.ini | 3 ++- 6 files changed, 13 insertions(+), 31 deletions(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 9bd7c96932..626de951df 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -99dcbba48124bf51788735fe775650f659d7302c \ No newline at end of file +167357a8d59c47386aaae51aafe1c47e34de0202 \ No newline at end of file diff --git a/external/lua/luajit/build_android.sh b/external/lua/luajit/build_android.sh index be17f6157f..c0551cb92a 100755 --- a/external/lua/luajit/build_android.sh +++ b/external/lua/luajit/build_android.sh @@ -2,7 +2,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" host_os=`uname -s | tr "[:upper:]" "[:lower:]"` -SRCDIR=$DIR/LuaJit-2.0.1 +SRCDIR=$DIR/src cd "$SRCDIR" NDK=$NDK_ROOT @@ -12,7 +12,7 @@ NDKP=$NDKVER/prebuilt/${host_os}-x86/bin/arm-linux-androideabi- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-arm" # Android/ARM, armeabi (ARMv5TE soft-float), Android 2.2+ (Froyo) -DESTDIR=$DIR/android/armeabi +DESTDIR=$DIR/prebuilt/android/armeabi rm "$DESTDIR"/*.a make clean make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_SYS=Linux TARGET_FLAGS="$NDKF" @@ -23,7 +23,7 @@ fi; # Android/ARM, armeabi-v7a (ARMv7 VFP), Android 4.0+ (ICS) NDKARCH="-march=armv7-a -mfloat-abi=softfp -Wl,--fix-cortex-a8" -DESTDIR=$DIR/android/armeabi-v7a +DESTDIR=$DIR/prebuilt/android/armeabi-v7a rm "$DESTDIR"/*.a make clean make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_SYS=Linux TARGET_FLAGS="$NDKF $NDKARCH" @@ -34,7 +34,7 @@ fi; # Android/x86, x86 (i686 SSE3), Android 4.0+ (ICS) NDKABI=14 -DESTDIR=$DIR/android/x86 +DESTDIR=$DIR/prebuilt/android/x86 NDKVER=$NDK/toolchains/x86-4.6 NDKP=$NDKVER/prebuilt/${host_os}-x86/bin/i686-linux-android- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-x86" diff --git a/external/lua/luajit/build_ios.sh b/external/lua/luajit/build_ios.sh index 79a8d4a5d4..52ea997371 100755 --- a/external/lua/luajit/build_ios.sh +++ b/external/lua/luajit/build_ios.sh @@ -3,8 +3,8 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" LIPO="xcrun -sdk iphoneos lipo" STRIP="xcrun -sdk iphoneos strip" -SRCDIR=$DIR/LuaJit-2.0.1 -DESTDIR=$DIR/ios +SRCDIR=$DIR/src +DESTDIR=$DIR/prebuilt/ios IXCODE=`xcode-select -print-path` ISDK=$IXCODE/Platforms/iPhoneOS.platform/Developer ISDKVER=iPhoneOS6.1.sdk diff --git a/external/lua/luajit/build_mac.sh b/external/lua/luajit/build_mac.sh index d3b43e2d4b..f5f93d3d56 100755 --- a/external/lua/luajit/build_mac.sh +++ b/external/lua/luajit/build_mac.sh @@ -1,36 +1,17 @@ #!/bin/sh DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -SRCDIR=$DIR/LuaJit-2.0.1 -DESTDIR=$DIR/mac +SRCDIR=$DIR/src +DESTDIR=$DIR/prebuilt/mac MACOSX_DEPLOYMENT_TARGET="10.6" rm "$DESTDIR"/*.a cd $SRCDIR -make clean -make CC="gcc -m32 -arch i386" clean all - -if [ -f $SRCDIR/src/libluajit.a ]; then - mv $SRCDIR/src/libluajit.a $DESTDIR/libluajit_32.a -fi; - make clean make CC="gcc -m64 -arch x86_64" clean all if [ -f $SRCDIR/src/libluajit.a ]; then - mv $SRCDIR/src/libluajit.a $DESTDIR/libluajit_64.a + mv $SRCDIR/src/libluajit.a $DESTDIR/libluajit.a fi; make clean - -# create lipo library -lipo -create -output $DESTDIR/libluajit.a $DESTDIR/libluajit_32.a $DESTDIR/libluajit_64.a - -rm $DESTDIR/libluajit_32.a $DESTDIR/libluajit_64.a - -# strip -strip -S $DESTDIR/libluajit.a - -# info -lipo -info $DESTDIR/libluajit.a - diff --git a/external/lua/luajit/prebuilt/mac/libluajit.a.REMOVED.git-id b/external/lua/luajit/prebuilt/mac/libluajit.a.REMOVED.git-id index df8d16ea2b..2b297152c9 100644 --- a/external/lua/luajit/prebuilt/mac/libluajit.a.REMOVED.git-id +++ b/external/lua/luajit/prebuilt/mac/libluajit.a.REMOVED.git-id @@ -1 +1 @@ -51a333ce3c98512e50967762ab907be96d6d14e5 \ No newline at end of file +c319cbee7c1d56c5e7add0ba9dcd272ccb36366d \ No newline at end of file diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index 8721cdba4f..2411628c85 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -103,7 +103,8 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS Camera::[getEyeXYZ getCenterXYZ getUpXYZ], ccFontDefinition::[*], Object::[autorelease isEqual acceptVisitor update], - UserDefault::[getInstance (s|g)etDataForKey] + UserDefault::[getInstance (s|g)etDataForKey], + Label::[getLettersInfo] rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame], ProgressTimer::[setReverseProgress=setReverseDirection], From 8580b166380041166bad7c60bc6366442e3bc53d Mon Sep 17 00:00:00 2001 From: samuelhu Date: Fri, 1 Nov 2013 14:40:35 +0800 Subject: [PATCH 328/557] Modify let the libluajit.a of mac only support 64bit --- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 626de951df..e3805fe0de 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -167357a8d59c47386aaae51aafe1c47e34de0202 \ No newline at end of file +e2d62e7c366bf3a2c2bbd08ce9b482dab2aa38c4 \ No newline at end of file From b2951b70ff7ffd56a865a376db8c23e2bc563f4f Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 14:50:06 +0800 Subject: [PATCH 329/557] issue #2771: enhance Listener use EventListener mechanism --- cocos/2d/CCScene.cpp | 3 +- cocos/base/CCObject.h | 1 + cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.cpp | 268 +++++++++++++++--- cocos/physics/CCPhysicsContact.h | 104 +++++-- cocos/physics/CCPhysicsWorld.cpp | 89 ++---- cocos/physics/CCPhysicsWorld.h | 15 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 25 +- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 2 + 9 files changed, 373 insertions(+), 136 deletions(-) diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 5d0de936de..3f05e43c83 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -102,8 +102,7 @@ bool Scene::initWithPhysics() Director * pDirector; CC_BREAK_IF( ! (pDirector = Director::getInstance()) ); this->setContentSize(pDirector->getWinSize()); - CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create())); - _physicsWorld->setScene(this); + CC_BREAK_IF(! (_physicsWorld = PhysicsWorld::create(*this))); this->scheduleUpdate(); // success diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 3c3e6c5321..dc1a6adfd2 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -207,6 +207,7 @@ typedef int (Object::*SEL_Compare)(Object*); #define CC_CALLBACK_0(__selector__,__target__, ...) std::bind(&__selector__,__target__, ##__VA_ARGS__) #define CC_CALLBACK_1(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, ##__VA_ARGS__) #define CC_CALLBACK_2(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__) +#define CC_CALLBACK_3(__selector__,__target__, ...) std::bind(&__selector__,__target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ##__VA_ARGS__) // end of base_nodes group /// @} diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index a82b7dc1d4..6073207dbd 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -44,7 +44,7 @@ class PhysicsJoint; class PhysicsBodyInfo; -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.01f, 0.5f, 0.5f); +const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); /** * A body affect by physics. diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 6f08fc6b24..744302cb46 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -30,22 +30,30 @@ #include "Box2D.h" #endif +#include "CCPhysicsBody.h" + #include "chipmunk/CCPhysicsContactInfo_chipmunk.h" #include "box2d/CCPhysicsContactInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "box2d/CCPhysicsHelper_box2d.h" +#include "CCEventCustom.h" + NS_CC_BEGIN PhysicsContact::PhysicsContact() -: _shapeA(nullptr) +: Event(Event::Type::CUSTOM) +, _world(nullptr) +, _shapeA(nullptr) , _shapeB(nullptr) +, _eventCode(EventCode::NONE) , _info(nullptr) , _notify(true) , _begin(false) , _data(nullptr) , _contactInfo(nullptr) , _contactData(nullptr) +, _result(true) { } @@ -172,25 +180,106 @@ Point PhysicsContactPostSolve::getSurfaceVelocity() return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); } -PhysicsContactListener::PhysicsContactListener() +EventListenerPhysicsContact::EventListenerPhysicsContact() : onContactBegin(nullptr) , onContactPreSolve(nullptr) , onContactPostSolve(nullptr) -, onContactEnd(nullptr) +, onContactSeperate(nullptr) +{ +} + +bool EventListenerPhysicsContact::init() +{ + auto func = [this](EventCustom* event) -> void + { + return onEvent(event); + }; + + return EventListenerCustom::init(std::hash()(PHYSICSCONTACT_EVENT_NAME), func); +} + +void EventListenerPhysicsContact::onEvent(EventCustom* event) +{ + PhysicsContact& contact = *(PhysicsContact*)(event->getUserData()); + + switch (contact.getEventCode()) + { + case PhysicsContact::EventCode::BEGIN: + { + bool ret = true; + + if (onContactBegin != nullptr + && contact.getNotify() + && test(contact.getShapeA(), contact.getShapeB())) + { + contact._begin = true; + contact.generateContactData(); + + // the mask has high priority than _listener->onContactBegin. + // so if the mask test is false, the two bodies won't have collision. + if (ret) + { + ret = onContactBegin(event, contact); + }else + { + onContactBegin(event, contact); + } + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::PRESOLVE: + { + bool ret = true; + + if (onContactPreSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); + contact._begin = false; + contact.generateContactData(); + + ret = onContactPreSolve(event, contact, solve); + } + + contact.setResult(ret); + break; + } + case PhysicsContact::EventCode::POSTSOLVE: + { + if (onContactPreSolve != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + PhysicsContactPostSolve solve(contact._contactInfo); + onContactPostSolve(event, contact, solve); + } + break; + } + case PhysicsContact::EventCode::SEPERATE: + { + if (onContactSeperate != nullptr + && test(contact.getShapeA(), contact.getShapeB())) + { + onContactSeperate(event, contact); + } + break; + } + default: + break; + } +} + +EventListenerPhysicsContact::~EventListenerPhysicsContact() { } -PhysicsContactListener::~PhysicsContactListener() +EventListenerPhysicsContact* EventListenerPhysicsContact::create() { + EventListenerPhysicsContact* obj = new EventListenerPhysicsContact(); -} - -PhysicsContactListener* PhysicsContactListener::create() -{ - PhysicsContactListener* obj = new PhysicsContactListener(); - - if (obj != nullptr) + if (obj != nullptr && obj->init()) { obj->autorelease(); return obj; @@ -200,17 +289,17 @@ PhysicsContactListener* PhysicsContactListener::create() return nullptr; } -bool PhysicsContactListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +bool EventListenerPhysicsContact::test(PhysicsShape* shapeA, PhysicsShape* shapeB) { CC_UNUSED_PARAM(shapeA); CC_UNUSED_PARAM(shapeB); return true; } -bool PhysicsContactListener::checkAvailable() +bool EventListenerPhysicsContact::checkAvailable() { if (onContactBegin == nullptr && onContactPreSolve == nullptr - && onContactPostSolve == nullptr && onContactEnd == nullptr) + && onContactPostSolve == nullptr && onContactSeperate == nullptr) { CCASSERT(false, "Invalid PhysicsContactListener."); return false; @@ -219,16 +308,16 @@ bool PhysicsContactListener::checkAvailable() return true; } -EventListener* PhysicsContactListener::clone() +EventListenerPhysicsContact* EventListenerPhysicsContact::clone() { - PhysicsContactListener* obj = PhysicsContactListener::create(); + EventListenerPhysicsContact* obj = EventListenerPhysicsContact::create(); if (obj != nullptr) { obj->onContactBegin = onContactBegin; obj->onContactPreSolve = onContactPreSolve; obj->onContactPostSolve = onContactPostSolve; - obj->onContactEnd = onContactEnd; + obj->onContactSeperate = onContactSeperate; return obj; } @@ -237,14 +326,79 @@ EventListener* PhysicsContactListener::clone() return nullptr; } - - - -PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::create(PhysicsBody* bodyA, PhysicsBody* bodyB) { - PhysicsContactWithBodysListener* obj = new PhysicsContactWithBodysListener(); + EventListenerPhysicsContactWithBodies* obj = new EventListenerPhysicsContactWithBodies(); + + if (obj != nullptr && obj->init()) + { + obj->_a = bodyA; + obj->_b = bodyB; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithBodies::EventListenerPhysicsContactWithBodies() +: _a(nullptr) +, _b(nullptr) +{ + +} + +EventListenerPhysicsContactWithBodies::~EventListenerPhysicsContactWithBodies() +{ + +} + + +bool EventListenerPhysicsContactWithBodies::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if ((shapeA->getBody() == _a && shapeB->getBody() == _b) + || (shapeA->getBody() == _b && shapeB->getBody() == _a)) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithBodies* EventListenerPhysicsContactWithBodies::clone() +{ + EventListenerPhysicsContactWithBodies* obj = EventListenerPhysicsContactWithBodies::create(_a, _b); if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithShapes::EventListenerPhysicsContactWithShapes() +: _a(nullptr) +, _b(nullptr) +{ +} + +EventListenerPhysicsContactWithShapes::~EventListenerPhysicsContactWithShapes() +{ +} + +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::create(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + EventListenerPhysicsContactWithShapes* obj = new EventListenerPhysicsContactWithShapes(); + + if (obj != nullptr && obj->init()) { obj->_a = shapeA; obj->_b = shapeB; @@ -256,17 +410,7 @@ PhysicsContactWithBodysListener* PhysicsContactWithBodysListener::create(Physics return nullptr; } -PhysicsContactWithBodysListener::PhysicsContactWithBodysListener() -{ - -} - -PhysicsContactWithBodysListener::~PhysicsContactWithBodysListener() -{ - -} - -bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +bool EventListenerPhysicsContactWithShapes::test(PhysicsShape* shapeA, PhysicsShape* shapeB) { if ((shapeA == _a && shapeB == _b) || (shapeA == _b && shapeB == _a)) @@ -277,16 +421,68 @@ bool PhysicsContactWithBodysListener::test(PhysicsShape* shapeA, PhysicsShape* s return false; } -EventListener* PhysicsContactWithBodysListener::clone() +EventListenerPhysicsContactWithShapes* EventListenerPhysicsContactWithShapes::clone() { - PhysicsContactWithBodysListener* obj = PhysicsContactWithBodysListener::create(_a, _b); + EventListenerPhysicsContactWithShapes* obj = EventListenerPhysicsContactWithShapes::create(_a, _b); if (obj != nullptr) { obj->onContactBegin = onContactBegin; obj->onContactPreSolve = onContactPreSolve; obj->onContactPostSolve = onContactPostSolve; - obj->onContactEnd = onContactEnd; + obj->onContactSeperate = onContactSeperate; + + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +EventListenerPhysicsContactWithGroup::EventListenerPhysicsContactWithGroup() +: _group(CP_NO_GROUP) +{ +} + +EventListenerPhysicsContactWithGroup::~EventListenerPhysicsContactWithGroup() +{ +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::create(int group) +{ + EventListenerPhysicsContactWithGroup* obj = new EventListenerPhysicsContactWithGroup(); + + if (obj != nullptr && obj->init()) + { + obj->_group = group; + obj->autorelease(); + return obj; + } + + CC_SAFE_DELETE(obj); + return nullptr; +} + +bool EventListenerPhysicsContactWithGroup::test(PhysicsShape* shapeA, PhysicsShape* shapeB) +{ + if (shapeA->getGroup() == _group || shapeB->getGroup() == _group) + { + return true; + } + + return false; +} + +EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::clone() +{ + EventListenerPhysicsContactWithGroup* obj = EventListenerPhysicsContactWithGroup::create(_group); + + if (obj != nullptr) + { + obj->onContactBegin = onContactBegin; + obj->onContactPreSolve = onContactPreSolve; + obj->onContactPostSolve = onContactPostSolve; + obj->onContactSeperate = onContactSeperate; return obj; } diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 82a47a8c23..a4b0454e37 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -30,11 +30,13 @@ #include "CCObject.h" #include "CCGeometry.h" -#include "CCEventListener.h" +#include "CCEventListenerCustom.h" +#include "CCEvent.h" NS_CC_BEGIN class PhysicsShape; +class PhysicsBody; class PhysicsWorld; class PhysicsContactInfo; @@ -54,9 +56,19 @@ typedef struct PhysicsContactData /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ -class PhysicsContact +class PhysicsContact : Event { public: + + enum class EventCode + { + NONE, + BEGIN, + PRESOLVE, + POSTSOLVE, + SEPERATE + }; + /* * @brief get contact shape A. */ @@ -75,12 +87,19 @@ public: */ inline void setData(void* data) { _data = data; } + EventCode getEventCode() { return _eventCode; }; + private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); + void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; inline bool getNotify() { return _notify; } inline void setNotify(bool notify) { _notify = notify; } + inline PhysicsWorld* getWorld() { return _world; } + inline void setWorld(PhysicsWorld* world) { _world = world; } + inline void setResult(bool result) { _result = result; } + inline bool resetResult() { bool ret = _result; _result = true; return ret; } void generateContactData(); @@ -89,18 +108,22 @@ private: ~PhysicsContact(); private: + PhysicsWorld* _world; PhysicsShape* _shapeA; PhysicsShape* _shapeB; + EventCode _eventCode; PhysicsContactInfo* _info; bool _notify; bool _begin; + bool _result; void* _data; void* _contactInfo; PhysicsContactData* _contactData; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; friend class PhysicsWorldCallback; + friend class PhysicsWorld; }; /* @@ -128,7 +151,7 @@ private: PhysicsContactData* _preContactData; void* _contactInfo; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; }; /* @@ -149,60 +172,99 @@ private: private: void* _contactInfo; - friend class PhysicsWorld; + friend class EventListenerPhysicsContact; }; +static const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; + /* * @brief contact listener. */ -class PhysicsContactListener : public EventListener +class EventListenerPhysicsContact : public EventListenerCustom { public: - static PhysicsContactListener* create(); + static EventListenerPhysicsContact* create(); virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual bool checkAvailable(); - virtual EventListener* clone(); + virtual bool checkAvailable() override; + virtual EventListenerPhysicsContact* clone() override; public: /* * @brief it will called at two shapes start to contact, and only call it once. */ - std::function onContactBegin; + std::function onContactBegin; /* * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. */ - std::function onContactPreSolve; + std::function onContactPreSolve; /* * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info */ - std::function onContactPostSolve; + std::function onContactPostSolve; /* * @brief it will called at two shapes separated, and only call it once. - * onContactBegin and onContactEnd will called in pairs. + * onContactBegin and onContactSeperate will called in pairs. */ - std::function onContactEnd; + std::function onContactSeperate; protected: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); + bool init(); + void onEvent(EventCustom* event); + +protected: + EventListenerPhysicsContact(); + virtual ~EventListenerPhysicsContact(); }; -class PhysicsContactWithBodysListener : public PhysicsContactListener +class EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact { public: - static PhysicsContactWithBodysListener* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB); virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual EventListener* clone(); + virtual EventListenerPhysicsContactWithBodies* clone() override; + +protected: + PhysicsBody* _a; + PhysicsBody* _b; + +protected: + EventListenerPhysicsContactWithBodies(); + virtual ~EventListenerPhysicsContactWithBodies(); +}; + +class EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListenerPhysicsContactWithShapes* clone() override; protected: PhysicsShape* _a; PhysicsShape* _b; protected: - PhysicsContactWithBodysListener(); - virtual ~PhysicsContactWithBodysListener(); + EventListenerPhysicsContactWithShapes(); + virtual ~EventListenerPhysicsContactWithShapes(); +}; + +class EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact +{ +public: + static EventListenerPhysicsContactWithGroup* create(int group); + + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual EventListenerPhysicsContactWithGroup* clone() override; + +protected: + int _group; + +protected: + EventListenerPhysicsContactWithGroup(); + virtual ~EventListenerPhysicsContactWithGroup(); }; NS_CC_END diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index a8d3d962c7..58bf2ecec3 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -53,6 +53,8 @@ #include "CCArray.h" #include "CCScene.h" #include "CCDirector.h" +#include "CCEventDispatcher.h" +#include "CCEventCustom.h" #include @@ -175,7 +177,7 @@ void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distanc arr->addObject(it->second->shape); } -bool PhysicsWorld::init() +bool PhysicsWorld::init(Scene& scene) { do { @@ -184,6 +186,8 @@ bool PhysicsWorld::init() _bodies = Array::create(); CC_BREAK_IF(_bodies == nullptr); _bodies->retain(); + + _scene = &scene; cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); @@ -458,11 +462,6 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::setScene(Scene *scene) -{ - _scene = scene; -} - void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) { for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) @@ -571,6 +570,7 @@ void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; + PhysicsShape* shapeA = contact.getShapeA(); PhysicsShape* shapeB = contact.getShapeB(); PhysicsBody* bodyA = shapeA->getBody(); @@ -597,7 +597,6 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } - // bitmask check if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) @@ -617,69 +616,42 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) } } - if (contact.getNotify() && _listener && _listener->onContactBegin) - { - contact._begin = true; - contact.generateContactData(); - - // the mask has high priority than _listener->onContactBegin. - // so if the mask test is false, the two bodies won't have collision. - if (ret) - { - ret = _listener->onContactBegin(*this, contact); - }else - { - _listener->onContactBegin(*this, contact); - } - } + contact.setEventCode(PhysicsContact::EventCode::BEGIN); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); - return ret; + return ret ? contact.resetResult() : false; } int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return true; - } + contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); - if (_listener && _listener->onContactPreSolve) - { - PhysicsContactPreSolve solve(contact._begin ? nullptr : contact._contactData, contact._contactInfo); - contact._begin = false; - contact.generateContactData(); - - return _listener->onContactPreSolve(*this, contact, solve); - } - - return true; + return contact.resetResult(); } void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactPreSolve) - { - PhysicsContactPostSolve solve(contact._contactInfo); - _listener->onContactPostSolve(*this, contact, solve); - } + contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactEnd) - { - _listener->onContactEnd(*this, contact); - } + contact.setEventCode(PhysicsContact::EventCode::SEPERATE); + contact.setWorld(this); + EventCustom event(PHYSICSCONTACT_EVENT_NAME); + event.setUserData(&contact); + _scene->getEventDispatcher()->dispatchEvent(&event); } void PhysicsWorld::setGravity(Point gravity) @@ -786,10 +758,10 @@ PhysicsBody* PhysicsWorld::getBodyByTag(int tag) #endif -PhysicsWorld* PhysicsWorld::create() +PhysicsWorld* PhysicsWorld::create(Scene& scene) { PhysicsWorld * world = new PhysicsWorld(); - if(world && world->init()) + if(world && world->init(scene)) { return world; } @@ -802,7 +774,6 @@ PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) , _info(nullptr) -, _listener(nullptr) , _bodies(nullptr) , _scene(nullptr) , _debugDraw(false) diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index aff9119485..6a7095da31 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -40,7 +40,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class PhysicsContactListener; class Array; class Sprite; @@ -101,10 +100,11 @@ public: PhysicsBody* getBodyByTag(int tag); /** Register a listener to receive contact callbacks*/ - inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } + //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } /** Unregister a listener. */ - inline void unregisterContactListener() { _listener = nullptr; } + //inline void unregisterContactListener() { _listener = nullptr; } + inline Scene& getScene() { return *_scene; } /** get the gravity value */ inline Point getGravity() { return _gravity; } /** set the gravity value */ @@ -120,10 +120,8 @@ public: virtual void removeAllBodies(); protected: - static PhysicsWorld* create(); - bool init(); - - void setScene(Scene* scene); + static PhysicsWorld* create(Scene& scene); + bool init(Scene& scene); virtual PhysicsBody* addBody(PhysicsBody* body); virtual PhysicsShape* addShape(PhysicsShape* shape); @@ -144,8 +142,7 @@ protected: Point _gravity; float _speed; PhysicsWorldInfo* _info; - PhysicsContactListener* _listener; - + //EventListenerPhysicsContact* _listener; Array* _bodies; std::list _joints; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f8e88891eb..f36b11e7d5 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -898,7 +898,7 @@ void PhysicsDemoPump::onEnter() // balls for (int i = 0; i < 6; ++i) { - auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.5f, 0.0f, 0.1f)); + auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f)); ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(ball); } @@ -908,8 +908,8 @@ void PhysicsDemoPump::onEnter() Point vec[4] = { - VisibleRect::leftTop() + Point(102, -146), - VisibleRect::leftTop() + Point(148, -159), + VisibleRect::leftTop() + Point(102, -148), + VisibleRect::leftTop() + Point(148, -161), VisibleRect::leftBottom() + Point(148, 20), VisibleRect::leftBottom() + Point(102, 20) }; @@ -918,7 +918,7 @@ void PhysicsDemoPump::onEnter() // small gear auto sgear = Node::create(); - auto sgearB = PhysicsBody::createCircle(50); + auto sgearB = PhysicsBody::createCircle(44); sgear->setPhysicsBody(sgearB); sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); this->addChild(sgear); @@ -946,7 +946,7 @@ void PhysicsDemoPump::onEnter() this->addChild(pump); pumpB->setCategoryBitmask(0x02); pumpB->setGravityEnable(false); - _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -50))); + _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -44))); // plugger Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; @@ -964,7 +964,7 @@ void PhysicsDemoPump::onEnter() pluggerB->setCategoryBitmask(0x02); sgearB->setCollisionBitmask(0x04 | 0x01); _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); - _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(50, 0))); + _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); } void PhysicsDemoPump::update(float delta) @@ -1024,7 +1024,6 @@ std::string PhysicsDemoPump::title() return "Pump"; } - void PhysicsDemoOneWayPlatform::onEnter() { PhysicsDemo::onEnter(); @@ -1044,7 +1043,17 @@ void PhysicsDemoOneWayPlatform::onEnter() platform->setPosition(VisibleRect::center()); this->addChild(platform); - this->addChild(makeBall(VisibleRect::center() + Point(0, 50), 5)); + auto ball = makeBall(VisibleRect::center() + Point(0, 50), 5); + this->addChild(ball); + + auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); + contactListener->onContactPreSolve = CC_CALLBACK_3(PhysicsDemoOneWayPlatform::onPreSolve, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); +} + +bool PhysicsDemoOneWayPlatform::onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve) +{ + return true; } std::string PhysicsDemoOneWayPlatform::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index dcf3cf4bb3..185c2a3e96 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -139,6 +139,8 @@ class PhysicsDemoOneWayPlatform : public PhysicsDemo public: void onEnter() override; std::string title() override; + + bool onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve); }; #endif From 6eb6809b2c524a005f9236d39bd1355a599d7ca0 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 1 Nov 2013 06:52:31 +0000 Subject: [PATCH 330/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c1da46eabb..3366eebe56 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c1da46eabb46727a66daa4d64d9841b09fa6d63c +Subproject commit 3366eebe56e09c3d32201654f5a29813c8b5defc From ed10b92a607098865eea82338c0c42e93c415ef9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 15:19:10 +0800 Subject: [PATCH 331/557] Fix of including wrong include files. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/platform/mac/CCDirectorCaller.mm | 2 +- .../mac/{CCEventDispatcher.h => CCEventDispatcherMac.h} | 0 .../mac/{CCEventDispatcher.mm => CCEventDispatcherMac.mm} | 3 +-- cocos/2d/platform/mac/EAGLView.mm | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) rename cocos/2d/platform/mac/{CCEventDispatcher.h => CCEventDispatcherMac.h} (100%) rename cocos/2d/platform/mac/{CCEventDispatcher.mm => CCEventDispatcherMac.mm} (99%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index f82767e410..d13b25c773 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -f918efd122d7a0cfabddf411f64d954d4fcd8579 \ No newline at end of file +245681d0a739a5432c0e588df5627789e03d902f \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 9bd7c96932..f27b44e3fa 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -99dcbba48124bf51788735fe775650f659d7302c \ No newline at end of file +92d0a8b3ee96411da3d9d2d3422dee5e9e0b40fb \ No newline at end of file diff --git a/cocos/2d/platform/mac/CCDirectorCaller.mm b/cocos/2d/platform/mac/CCDirectorCaller.mm index 83d9689470..af4645a7aa 100644 --- a/cocos/2d/platform/mac/CCDirectorCaller.mm +++ b/cocos/2d/platform/mac/CCDirectorCaller.mm @@ -25,7 +25,7 @@ #import "CCDirectorCaller.h" #import "CCDirector.h" #import "EAGLView.h" -#import "CCEventDispatcher.h" +#import "CCEventDispatcherMac.h" #include "CCAutoreleasePool.h" static id s_sharedDirectorCaller; diff --git a/cocos/2d/platform/mac/CCEventDispatcher.h b/cocos/2d/platform/mac/CCEventDispatcherMac.h similarity index 100% rename from cocos/2d/platform/mac/CCEventDispatcher.h rename to cocos/2d/platform/mac/CCEventDispatcherMac.h diff --git a/cocos/2d/platform/mac/CCEventDispatcher.mm b/cocos/2d/platform/mac/CCEventDispatcherMac.mm similarity index 99% rename from cocos/2d/platform/mac/CCEventDispatcher.mm rename to cocos/2d/platform/mac/CCEventDispatcherMac.mm index 6487d877a1..89660ce0f5 100644 --- a/cocos/2d/platform/mac/CCEventDispatcher.mm +++ b/cocos/2d/platform/mac/CCEventDispatcherMac.mm @@ -27,12 +27,11 @@ // But in case they are included, it won't be compiled. #import -#import "CCEventDispatcher.h" +#import "CCEventDispatcherMac.h" #import "ccConfig.h" #include "utlist.h" #include "CCDirector.h" -#include "platform/mac/CCEventDispatcher.h" //NS_CC_BEGIN; static CCEventDispatcher *sharedDispatcher = nil; diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm index 2bc17be1f1..ff456d0e6a 100644 --- a/cocos/2d/platform/mac/EAGLView.mm +++ b/cocos/2d/platform/mac/EAGLView.mm @@ -37,7 +37,7 @@ THE SOFTWARE. #import "CCTouch.h" #import "CCIMEDispatcher.h" #import "CCWindow.h" -#import "CCEventDispatcher.h" +#import "CCEventDispatcherMac.h" #import "CCEGLView.h" From a04d1acedeb4448bedcbdc549940fe33ad5441b5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 15:19:51 +0800 Subject: [PATCH 332/557] Fix of compilation errros of SimpleGame. --- samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp | 7 +++++-- samples/Cpp/SimpleGame/Classes/HelloWorldScene.h | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp index d5052e66a0..85d2f97be9 100644 --- a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp +++ b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp @@ -100,8 +100,11 @@ bool HelloWorld::init() this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 ); - this->setTouchEnabled(true); - + auto dispatcher = Director::getInstance()->getEventDispatcher(); + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(listener, this); + _targets = new Array(); _targets->init(); diff --git a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h index 279f2c4399..ee65eb2f08 100644 --- a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h +++ b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h @@ -30,7 +30,7 @@ public: void updateGame(float dt); - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event) override; + void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); protected: From daf4e22819c8d01869524a8afa6564f90dd56b68 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 15:33:57 +0800 Subject: [PATCH 333/557] [Bindings] Skip Label::getLettersInfo --- tools/tojs/cocos2dx.ini | 1 + tools/tolua/cocos2dx.ini | 1 + 2 files changed, 2 insertions(+) diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index 510440e508..e49e3dbc0f 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -51,6 +51,7 @@ skip = Node::[^setPosition$ getGrid setGLServerState description getUserObject . Copying::[*], LabelProtocol::[*], LabelTextFormatProtocol::[*], + Label::[getLettersInfo], .*Delegate::[*], PoolManager::[*], Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData], diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index 2411628c85..3a1d67655c 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -48,6 +48,7 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS Layer.*::[didAccelerate (g|s)etBlendFunc keyPressed keyReleased], Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns], MenuItem.*::[create setCallback initWithCallback], + Label::[getLettersInfo], Copying::[*], .*Protocol::[*], .*Delegate::[*], From 8e7ed129c52388670ad7abf79ceb260a57054aef Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 15:39:46 +0800 Subject: [PATCH 334/557] Update before-install.sh --- tools/travis-scripts/before-install.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh index 93cdb195fe..79154e4604 100755 --- a/tools/travis-scripts/before-install.sh +++ b/tools/travis-scripts/before-install.sh @@ -103,7 +103,6 @@ elif [ "$PLATFORM"x = "linux"x ]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 90 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7 g++ --version bash $COCOS2DX_ROOT/build/install-deps-linux.sh - bash $COCOS2DX_ROOT/build/install_glfw.sh install_android_ndk install_llvm elif [ "$PLATFORM"x = "nacl"x ]; then From 8aac938531aa640fdb5ba6a752b91baa8f1901f5 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 1 Nov 2013 07:42:11 +0000 Subject: [PATCH 335/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 3366eebe56..dac276f47b 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 3366eebe56e09c3d32201654f5a29813c8b5defc +Subproject commit dac276f47b7162898a526b385f076e5712acf12d From 2f67ceb495b4e35108436530deb22a7b64f199cb Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 16:26:03 +0800 Subject: [PATCH 336/557] issue #2771: fix some code style --- cocos/2d/CCNode.cpp | 4 +- cocos/physics/CCPhysicsBody.cpp | 6 +-- cocos/physics/CCPhysicsBody.h | 32 ++++++------ cocos/physics/CCPhysicsContact.cpp | 34 +++++++------ cocos/physics/CCPhysicsContact.h | 28 +++++------ cocos/physics/CCPhysicsJoint.cpp | 30 +++++------ cocos/physics/CCPhysicsJoint.h | 20 ++++---- cocos/physics/CCPhysicsShape.cpp | 18 +++---- cocos/physics/CCPhysicsShape.h | 28 +++++------ cocos/physics/CCPhysicsWorld.cpp | 50 +++++++++++++++---- cocos/physics/CCPhysicsWorld.h | 12 ++--- .../Classes/PhysicsTest/PhysicsTest.cpp | 11 ++-- 12 files changed, 152 insertions(+), 121 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 494f267136..cb1fb62f6c 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -1389,12 +1389,12 @@ void Node::setPhysicsBody(PhysicsBody* body) { if (_physicsBody != nullptr) { - _physicsBody->_owner = nullptr; + _physicsBody->_node = nullptr; _physicsBody->release(); } _physicsBody = body; - _physicsBody->_owner = this; + _physicsBody->_node = this; _physicsBody->retain(); _physicsBody->setPosition(getPosition()); _physicsBody->setRotation(getRotation()); diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 70bfe275b8..405687a21b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -60,7 +60,7 @@ namespace } PhysicsBody::PhysicsBody() -: _owner(nullptr) +: _node(nullptr) , _shapes(nullptr) , _world(nullptr) , _info(nullptr) @@ -570,7 +570,7 @@ void PhysicsBody::setMoment(float moment) } } -PhysicsShape* PhysicsBody::getShapeByTag(int tag) +PhysicsShape* PhysicsBody::getShapeByTag(int tag) const { for (auto child : *_shapes) { @@ -666,7 +666,7 @@ void PhysicsBody::setEnable(bool enable) } } -bool PhysicsBody::isResting() +bool PhysicsBody::isResting() const { return cpBodyIsSleeping(_info->body) == cpTrue; } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 6073207dbd..a4bad406b8 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -122,12 +122,12 @@ public: /* * @brief get the body shapes. */ - inline Array* getShapes() { return _shapes; } + inline Array* getShapes() const { return _shapes; } /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } - PhysicsShape* getShapeByTag(int tag); + inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + PhysicsShape* getShapeByTag(int tag) const; /* * @brief remove a shape from body */ @@ -152,7 +152,7 @@ public: /* * @brief get the sprite the body set to. */ - inline Node* getOwner() const { return _owner; } + inline Node* getNode() const { return _node; } void setCategoryBitmask(int bitmask); void setContactTestBitmask(int bitmask); @@ -162,7 +162,7 @@ public: inline int getCollisionBitmask() const { return _collisionBitmask; } void setGroup(int group); - inline int getGroup() { return _group; } + inline int getGroup() const { return _group; } /* * @brief get the body position. @@ -177,7 +177,7 @@ public: * @brief test the body is dynamic or not. * a dynamic body will effect with gravity. */ - inline bool isDynamic() { return _dynamic; } + inline bool isDynamic() const { return _dynamic; } /* * @brief set dynamic to body. * a dynamic body will effect with gravity. @@ -192,7 +192,7 @@ public: /* * @brief get the body mass. */ - inline float getMass() { return _mass; } + inline float getMass() const { return _mass; } /* * @brief add mass to body. * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. @@ -211,7 +211,7 @@ public: /* * @brief get the body moment of inertia. */ - inline float getMoment(float moment) { return _moment; } + inline float getMoment(float moment) const { return _moment; } /* * @brief add moment of inertia to body. * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. @@ -228,25 +228,25 @@ public: /* * @brief get angular damping. */ - inline float getLinearDamping() { return _linearDamping; } + inline float getLinearDamping() const { return _linearDamping; } inline void setLinearDamping(float damping) { _linearDamping = damping; } - inline float getAngularDamping() { return _angularDamping; } + inline float getAngularDamping() const { return _angularDamping; } inline void setAngularDamping(float damping) { _angularDamping = damping; } //virtual Clonable* clone() const override; - bool isResting(); - inline bool isEnable() { return _enable; } + bool isResting() const; + inline bool isEnable() const { return _enable; } void setEnable(bool enable); - inline bool isRotationEnable() { return _rotationEnable; } + inline bool isRotationEnable() const { return _rotationEnable; } void setRotationEnable(bool enable); - inline bool isGravityEnable() { return _gravityEnable; } + inline bool isGravityEnable() const { return _gravityEnable; } void setGravityEnable(bool enable); - inline int getTag() { return _tag; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } Point world2Local(const Point& point); @@ -266,7 +266,7 @@ protected: virtual ~PhysicsBody(); protected: - Node* _owner; + Node* _node; std::vector _joints; Array* _shapes; PhysicsWorld* _world; diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 744302cb46..1d0cfd8bdd 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -41,6 +41,8 @@ NS_CC_BEGIN +const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; + PhysicsContact::PhysicsContact() : Event(Event::Type::CUSTOM) , _world(nullptr) @@ -100,7 +102,7 @@ void PhysicsContact::generateContactData() return; } - cpArbiter* arb = (cpArbiter*)_contactInfo; + cpArbiter* arb = static_cast(_contactInfo); _contactData = new PhysicsContactData(); _contactData->count = cpArbiterGetCount(arb); for (int i=0; i<_contactData->count; ++i) @@ -118,34 +120,34 @@ PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* c { } -float PhysicsContactPreSolve::getElasticity() +float PhysicsContactPreSolve::getElasticity() const { - return ((cpArbiter*)_contactInfo)->e; + return static_cast(_contactInfo)->e; } -float PhysicsContactPreSolve::getFriciton() +float PhysicsContactPreSolve::getFriciton() const { - return ((cpArbiter*)_contactInfo)->u; + return static_cast(_contactInfo)->u; } -Point PhysicsContactPreSolve::getSurfaceVelocity() +Point PhysicsContactPreSolve::getSurfaceVelocity() const { - return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); } void PhysicsContactPreSolve::setElasticity(float elasticity) { - ((cpArbiter*)_contactInfo)->e = elasticity; + static_cast(_contactInfo)->e = elasticity; } void PhysicsContactPreSolve::setFriction(float friction) { - ((cpArbiter*)_contactInfo)->u = friction; + static_cast(_contactInfo)->u = friction; } void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) { - ((cpArbiter*)_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); + static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } PhysicsContactPreSolve::~PhysicsContactPreSolve() @@ -165,19 +167,19 @@ PhysicsContactPostSolve::~PhysicsContactPostSolve() } -float PhysicsContactPostSolve::getElasticity() +float PhysicsContactPostSolve::getElasticity() const { - return ((cpArbiter*)_contactInfo)->e; + return static_cast(_contactInfo)->e; } -float PhysicsContactPostSolve::getFriciton() +float PhysicsContactPostSolve::getFriciton() const { - return ((cpArbiter*)_contactInfo)->u; + return static_cast(_contactInfo)->u; } -Point PhysicsContactPostSolve::getSurfaceVelocity() +Point PhysicsContactPostSolve::getSurfaceVelocity() const { - return PhysicsHelper::cpv2point(((cpArbiter*)_contactInfo)->surface_vr); + return PhysicsHelper::cpv2point(static_cast(_contactInfo)->surface_vr); } EventListenerPhysicsContact::EventListenerPhysicsContact() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index a4b0454e37..32127da7a5 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -81,22 +81,22 @@ public: /* * @brief get data. */ - inline void* getData() { return _data; } + inline void* getData() const { return _data; } /* * @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact end. */ inline void setData(void* data) { _data = data; } - EventCode getEventCode() { return _eventCode; }; + EventCode getEventCode() const { return _eventCode; }; private: static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); bool init(PhysicsShape* a, PhysicsShape* b); void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; - inline bool getNotify() { return _notify; } + inline bool getNotify() const { return _notify; } inline void setNotify(bool notify) { _notify = notify; } - inline PhysicsWorld* getWorld() { return _world; } + inline PhysicsWorld* getWorld() const { return _world; } inline void setWorld(PhysicsWorld* world) { _world = world; } inline void setResult(bool result) { _result = result; } inline bool resetResult() { bool ret = _result; _result = true; return ret; } @@ -133,9 +133,9 @@ class PhysicsContactPreSolve { public: // getter/setter - float getElasticity(); - float getFriciton(); - Point getSurfaceVelocity(); + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; void setElasticity(float elasticity); void setFriction(float friction); void setSurfaceVelocity(Point surfaceVelocity); @@ -161,9 +161,9 @@ class PhysicsContactPostSolve { public: // getter - float getElasticity(); - float getFriciton(); - Point getSurfaceVelocity(); + float getElasticity() const; + float getFriciton() const; + Point getSurfaceVelocity() const; private: PhysicsContactPostSolve(void* contactInfo); @@ -175,8 +175,6 @@ private: friend class EventListenerPhysicsContact; }; -static const char* PHYSICSCONTACT_EVENT_NAME = "PhysicsContactEvent"; - /* * @brief contact listener. */ @@ -222,7 +220,7 @@ class EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithBodies* clone() override; protected: @@ -239,7 +237,7 @@ class EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithShapes* clone() override; protected: @@ -256,7 +254,7 @@ class EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact public: static EventListenerPhysicsContactWithGroup* create(int group); - virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB); + virtual bool test(PhysicsShape* shapeA, PhysicsShape* shapeB) override; virtual EventListenerPhysicsContactWithGroup* clone() override; protected: diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index e35b8d241c..99fed53d8b 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -155,14 +155,14 @@ PhysicsJointDistance::~PhysicsJointDistance() } #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -PhysicsBodyInfo* PhysicsJoint::bodyInfo(PhysicsBody* body) const +PhysicsBodyInfo* PhysicsJoint::getBodyInfo(PhysicsBody* body) const { return body->_info; } -Node* PhysicsJoint::bodyOwner(PhysicsBody* body) const +Node* PhysicsJoint::getBodyNode(PhysicsBody* body) const { - return body->_owner; + return body->_node; } @@ -198,17 +198,17 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - bodyOwner(a)->setPosition(anchr); - bodyOwner(b)->setPosition(anchr); + getBodyNode(a)->setPosition(anchr); + getBodyNode(b)->setPosition(anchr); // add a pivot joint to fixed two body together - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. - joint = cpGearJointNew(bodyInfo(a)->body, bodyInfo(b)->body, 0, 1); + joint = cpGearJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, 0, 1); CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -238,7 +238,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); @@ -258,7 +258,7 @@ void PhysicsJointPin::setMaxForce(float force) _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); } -float PhysicsJointPin::getMaxForce() +float PhysicsJointPin::getMaxForce() const { return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); } @@ -282,7 +282,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpGrooveJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); @@ -317,7 +317,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpSlideJointNew(bodyInfo(a)->body, bodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), 0, @@ -333,7 +333,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 return false; } -float PhysicsJointLimit::getMin() +float PhysicsJointLimit::getMin() const { return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); } @@ -343,7 +343,7 @@ void PhysicsJointLimit::setMin(float min) cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); } -float PhysicsJointLimit::getMax() +float PhysicsJointLimit::getMax() const { return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); } @@ -372,8 +372,8 @@ bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anc { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPinJointNew(bodyInfo(a)->body, - bodyInfo(b)->body, + cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->body, + getBodyInfo(b)->body, PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); CC_BREAK_IF(joint == nullptr); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 298992c5f3..2970d992d0 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -47,13 +47,13 @@ protected: virtual ~PhysicsJoint() = 0; public: - PhysicsBody* getBodyA() { return _bodyA; } - PhysicsBody* getBodyB() { return _bodyB; } - inline int getTag() { return _tag; } + PhysicsBody* getBodyA() const { return _bodyA; } + PhysicsBody* getBodyB() const { return _bodyB; } + inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() { return _enable; } + inline bool isEnable() const { return _enable; } void setEnable(bool enable); - inline bool isCollisionEnable() { return _collisionEnable; } + inline bool isCollisionEnable() const { return _collisionEnable; } void setCollisionEnable(bool enable); protected: @@ -62,8 +62,8 @@ protected: /** * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. */ - PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; - Node* bodyOwner(PhysicsBody* body) const; + PhysicsBodyInfo* getBodyInfo(PhysicsBody* body) const; + Node* getBodyNode(PhysicsBody* body) const; protected: PhysicsBody* _bodyA; @@ -133,9 +133,9 @@ class PhysicsJointLimit : public PhysicsJoint public: PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - float getMin(); + float getMin() const; void setMin(float min); - float getMax(); + float getMax() const; void setMax(float max); protected: @@ -155,7 +155,7 @@ public: static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); void setMaxForce(float force); - float getMaxForce(); + float getMaxForce() const; protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index bb17c54501..68ef1cf351 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -353,7 +353,7 @@ float PhysicsShapeCircle::calculateDefaultMoment() cpCircleShapeGetOffset(shape))); } -float PhysicsShapeCircle::getRadius() +float PhysicsShapeCircle::getRadius() const { return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); } @@ -405,12 +405,12 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* return false; } -Point PhysicsShapeEdgeSegment::getPointA() +Point PhysicsShapeEdgeSegment::getPointA() const { return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); } -Point PhysicsShapeEdgeSegment::getPointB() +Point PhysicsShapeEdgeSegment::getPointB() const { return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); } @@ -503,7 +503,7 @@ float PhysicsShapeBox::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapeBox::getPoints(Point* points) +Point* PhysicsShapeBox::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); @@ -511,7 +511,7 @@ Point* PhysicsShapeBox::getPoints(Point* points) return points; } -Size PhysicsShapeBox::getSize() +Size PhysicsShapeBox::getSize() const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), @@ -594,13 +594,13 @@ float PhysicsShapePolygon::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapePolygon::getPoints(Point* points) +Point* PhysicsShapePolygon::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } -int PhysicsShapePolygon::getPointsCount() +int PhysicsShapePolygon::getPointsCount() const { return ((cpPolyShape*)_info->shapes.front())->numVerts; } @@ -715,7 +715,7 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -int PhysicsShapeEdgePolygon::getPointsCount() +int PhysicsShapeEdgePolygon::getPointsCount() const { return _info->shapes.size() + 1; } @@ -776,7 +776,7 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -int PhysicsShapeEdgeChain::getPointsCount() +int PhysicsShapeEdgeChain::getPointsCount() const { return _info->shapes.size() + 1; } diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 8bc9224bf1..31497d14a2 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -156,8 +156,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - float getRadius(); - Point getOffset(); + float getRadius() const; + Point getOffset() override; protected: bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -177,8 +177,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - Point* getPoints(Point* points); - Size getSize(); + Point* getPoints(Point* points) const; + Size getSize() const; Point getOffset() override { return _offset; } protected: @@ -203,8 +203,8 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; Point getCenter() override; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -223,8 +223,8 @@ class PhysicsShapeEdgeSegment : public PhysicsShape public: static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getPointA(); - Point getPointB(); + Point getPointA() const; + Point getPointB() const; Point getCenter() override; protected: @@ -246,8 +246,8 @@ class PhysicsShapeEdgeBox : public PhysicsShape public: static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); Point getOffset() override { return _offset; } - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); @@ -268,8 +268,8 @@ class PhysicsShapeEdgePolygon : public PhysicsShape public: static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -290,8 +290,8 @@ class PhysicsShapeEdgeChain : public PhysicsShape public: static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); + Point* getPoints(Point* points) const; + int getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 58bf2ecec3..1cd2b936c5 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -60,6 +60,8 @@ NS_CC_BEGIN +extern const char* PHYSICSCONTACT_EVENT_NAME; + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) const float PHYSICS_INFINITY = INFINITY; @@ -269,7 +271,8 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) if (cpBodyIsStatic(shape->getBody()->_info->body)) { cpSpaceAddStaticShape(_info->space, cps); - }else + } + else { cpSpaceAddShape(_info->space, cps); } @@ -473,7 +476,8 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) cpBody *body_b = constraint->b; const cpConstraintClass *klass = constraint->klass_private; - if(klass == cpPinJointGetClass()){ + if(klass == cpPinJointGetClass()) + { cpPinJoint *joint = (cpPinJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -482,7 +486,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpSlideJointGetClass()){ + } + else if(klass == cpSlideJointGetClass()) + { cpSlideJoint *joint = (cpSlideJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -491,7 +497,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpPivotJointGetClass()){ + } + else if(klass == cpPivotJointGetClass()) + { cpPivotJoint *joint = (cpPivotJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot)); @@ -499,7 +507,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawDot(PhysicsHelper::cpv2point(a), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(b), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpGrooveJointGetClass()){ + } + else if(klass == cpGrooveJointGetClass()) + { cpGrooveJoint *joint = (cpGrooveJoint *)constraint; cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot)); @@ -508,7 +518,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) node->drawSegment(PhysicsHelper::cpv2point(a), PhysicsHelper::cpv2point(b), 1, Color4F(0.0f, 0.0f, 1.0f, 1.0f)); node->drawDot(PhysicsHelper::cpv2point(c), 2, Color4F(0.0f, 1.0f, 0.0f, 1.0f)); - } else if(klass == cpDampedSpringGetClass()){ + } + else if(klass == cpDampedSpringGetClass()) + { } } @@ -607,7 +619,8 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) { ret = shapeA->getGroup() > 0; - }else + } + else { if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) @@ -627,6 +640,11 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return true; + } + contact.setEventCode(PhysicsContact::EventCode::PRESOLVE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -638,6 +656,11 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return; + } + contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -647,6 +670,11 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { + if (!contact.getNotify()) + { + return; + } + contact.setEventCode(PhysicsContact::EventCode::SEPERATE); contact.setWorld(this); EventCustom event(PHYSICSCONTACT_EVENT_NAME); @@ -680,7 +708,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point { if (callback.report != nullptr) { - RayCastCallbackInfo info = {this, &callback, point1, point2, data}; + RayCastCallbackInfo info = { this, &callback, point1, point2, data }; PhysicsWorldCallback::continues = true; cpSpaceSegmentQuery(this->_info->space, @@ -710,7 +738,7 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* PhysicsWorld::getShapesAtPoint(Point point) +Array* PhysicsWorld::getShapesAtPoint(Point point) const { Array* arr = Array::create(); cpSpaceNearestPointQuery(this->_info->space, @@ -724,7 +752,7 @@ Array* PhysicsWorld::getShapesAtPoint(Point point) return arr; } -PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) +PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) const { cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, PhysicsHelper::point2cpv(point), @@ -741,7 +769,7 @@ Array* PhysicsWorld::getAllBodies() const return _bodies; } -PhysicsBody* PhysicsWorld::getBodyByTag(int tag) +PhysicsBody* PhysicsWorld::getBodyByTag(int tag) const { for (auto body : *_bodies) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 6a7095da31..e719dce2c4 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -94,24 +94,24 @@ public: void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); - Array* getShapesAtPoint(Point point); - PhysicsShape* getShapeAtPoint(Point point); + Array* getShapesAtPoint(Point point) const; + PhysicsShape* getShapeAtPoint(Point point) const; Array* getAllBodies() const; - PhysicsBody* getBodyByTag(int tag); + PhysicsBody* getBodyByTag(int tag) const; /** Register a listener to receive contact callbacks*/ //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } /** Unregister a listener. */ //inline void unregisterContactListener() { _listener = nullptr; } - inline Scene& getScene() { return *_scene; } + inline Scene& getScene() const { return *_scene; } /** get the gravity value */ - inline Point getGravity() { return _gravity; } + inline Point getGravity() const { return _gravity; } /** set the gravity value */ void setGravity(Point gravity); /** test the debug draw is enabled */ - inline bool isDebugDraw() { return _debugDraw; } + inline bool isDebugDraw() const { return _debugDraw; } /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f36b11e7d5..db51829b3f 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -13,6 +13,7 @@ namespace CL(PhysicsDemoJoints), CL(PhysicsDemoActions), CL(PhysicsDemoPump), + CL(PhysicsDemoOneWayPlatform), }; static int sceneIdx=-1; @@ -974,7 +975,7 @@ void PhysicsDemoPump::update(float delta) PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) { - body->getOwner()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); + body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); body->setVelocity(Point(0, 0)); } } @@ -992,7 +993,7 @@ void PhysicsDemoPump::update(float delta) } gear->setAngularVelocity(_rotationV); - _rotationV *= 0.995; + _rotationV *= 0.995f; } } @@ -1039,11 +1040,13 @@ void PhysicsDemoOneWayPlatform::onEnter() this->addChild(ground); auto platform = Node::create(); - platform->setPhysicsBody(PhysicsBody::createEdgeBox(Size(200, 50))); + platform->setPhysicsBody(PhysicsBody::createBox(Size(200, 50))); + platform->getPhysicsBody()->setDynamic(false); platform->setPosition(VisibleRect::center()); this->addChild(platform); - auto ball = makeBall(VisibleRect::center() + Point(0, 50), 5); + auto ball = makeBall(VisibleRect::center() - Point(0, 50), 5); + ball->getPhysicsBody()->setVelocity(Point(0, 200)); this->addChild(ball); auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); From a2adbff2c8cd805e0dfae3578eb888096d75bc71 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 1 Nov 2013 16:32:27 +0800 Subject: [PATCH 337/557] issue #2771: fix some code style --- cocos/physics/CCPhysicsBody.cpp | 9 --------- cocos/physics/CCPhysicsJoint.cpp | 7 ------- 2 files changed, 16 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 405687a21b..189b9edcfa 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -730,15 +730,6 @@ Point PhysicsBody::local2World(const Point& point) return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); } -//Clonable* PhysicsBody::clone() const -//{ -// PhysicsBody* body = new PhysicsBody(); -// -// body->autorelease(); -// -// return body; -//} - #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 99fed53d8b..694559264e 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -171,11 +171,6 @@ void PhysicsJoint::setCollisionEnable(bool enable) if (_collisionEnable != enable) { _collisionEnable = enable; - -// for (auto shape : _bodyB->_shapes) -// { -// shape->_info->setGroup(enable ? _bodyB->_info->group : _bodyA->_info->group); -// } } } @@ -245,8 +240,6 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) _info->add(joint); - //setCollisionEnable(false); - return true; } while (false); From 0a59d9eb3e2b591097c1770564c2ac515c654efd Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 1 Nov 2013 16:44:04 +0800 Subject: [PATCH 338/557] fix assetsmansger path --- build/android-build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/android-build.py b/build/android-build.py index e59ee61bf1..a9791936a5 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -176,7 +176,7 @@ def build_samples(target,ndk_build_param): elif target == 'simplegame': app_android_root = os.path.join(cocos_root, 'samples/Cpp/SimpleGame/proj.android') elif target == 'assetsmanager': - app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManager/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManagerTest/proj.android') elif target == 'hellolua': app_android_root = os.path.join(cocos_root, 'samples/Lua/HelloLua/proj.android') elif target == 'testlua': From 915d75ea7c6bdb9afd65c509fad8ca09e785b915 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 1 Nov 2013 16:44:35 +0800 Subject: [PATCH 339/557] build release version of android samples --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 7e86b00319..f9e5e0ff6b 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py all + ./android-build.py -n NDK_DEBUG=0 all # Build template # echo "Building template ..." From 9fad8bfc8dcc9c7ef8503fdaed4088ecf5e85f74 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 17:02:35 +0800 Subject: [PATCH 340/557] Don't set debug flag in AndroidManifest.xml. --- samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml | 3 +-- samples/Cpp/TestCpp/proj.android/AndroidManifest.xml | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml b/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml index 840bcce203..0937a1e991 100644 --- a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml +++ b/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml @@ -8,8 +8,7 @@ + android:icon="@drawable/icon"> + android:icon="@drawable/icon"> Date: Fri, 1 Nov 2013 17:03:15 +0800 Subject: [PATCH 341/557] fix a bug when building AssetsManagerTest --- build/android-build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/android-build.py b/build/android-build.py index a9791936a5..4212076c28 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -127,7 +127,7 @@ def copy_resources(target, app_android_root): copy_files(resources_dir, assets_dir) # jsb samples should copy javascript files and resources(shared with cocos2d-html5) - if target in JSB_SAMPLES or target == "assetsmanager": + if target in JSB_SAMPLES: resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") copy_files(resources_dir, assets_dir) From 463ed08ffe9d0eea3119212a5c857b5d2049a659 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Fri, 1 Nov 2013 17:29:09 +0800 Subject: [PATCH 342/557] issue #3037:Modify AssetsManagerTest.lua --- .../luaScript/AssetsManagerTest/AssetsManagerTest.lua | 4 ---- 1 file changed, 4 deletions(-) diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua index 67be1499eb..bd09f69e8a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua @@ -74,13 +74,9 @@ local function updateLayer() end local function update(sender) - progressLable:setString("") getAssetsManager():update() - - --isUpdateItemClicked = true - end local function reset(sender) From 8cf1337777be0e70bfc5fc2068c7304f105f5cda Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 17:48:10 +0800 Subject: [PATCH 343/557] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 469f299f7c..7260f3e164 100644 --- a/AUTHORS +++ b/AUTHORS @@ -634,6 +634,9 @@ Developers: superrad Clear NoSuchMethodError Exception when JniHelper fails to find methodID + Nite Luo (darkdukey) + Added Mouse Support For Desktop Platforms. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From eabb611093e919e89e43083be84ca2ef798c6d0d Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 17:49:01 +0800 Subject: [PATCH 344/557] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 158e288955..778f136096 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -9,6 +9,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] create_project.py does not rename/replace template projects completely. [FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] The Node's anchor point was changed after being added to ScrollView. + [NEW] Added Mouse Support For Desktop Platforms. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From a272bcd6ea4e2a7cd22489c13d0eea8039d887b3 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 1 Nov 2013 10:02:54 +0000 Subject: [PATCH 345/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index dac276f47b..c2828315e5 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit dac276f47b7162898a526b385f076e5712acf12d +Subproject commit c2828315e53a4dedcdbc9e64fee388e20e49b9b4 From 32c575586916d928e60946bb2f48134d0182cbea Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 1 Nov 2013 18:24:34 +0800 Subject: [PATCH 346/557] better log --- build/android-build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/android-build.py b/build/android-build.py index 4212076c28..be4800453a 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -192,7 +192,7 @@ def build_samples(target,ndk_build_param): elif target == 'watermelonwithme': app_android_root = os.path.join(cocos_root, 'samples/JavaScript/WatermelonWithMe/proj.android') else: - print 'unknown target %s, pass it', target + print 'unknown target: %s' % target continue copy_resources(target, app_android_root) From e893ae56972550de17a4b7edb56cbecb167fd99f Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 18:27:09 +0800 Subject: [PATCH 347/557] Using namespace std; for AssetsManagerTest. --- samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp index 31808c17b0..3e9381a865 100644 --- a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp +++ b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp @@ -18,6 +18,7 @@ USING_NS_CC; USING_NS_CC_EXT; +using namespace std; using namespace CocosDenshion; AppDelegate::AppDelegate() From b751c41498c32e279870a827b428b6207bbf4ece Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 18:27:47 +0800 Subject: [PATCH 348/557] [Android] Updating Android.mk for JSB projects. --- .../AssetsManagerTest/proj.android/jni/Android.mk | 10 ++++++++++ .../CocosDragonJS/proj.android/jni/Android.mk | 11 +++++++++++ .../CrystalCraze/proj.android/jni/Android.mk | 10 ++++++++++ .../MoonWarriors/proj.android/jni/Android.mk | 12 +++++++++++- .../WatermelonWithMe/proj.android/jni/Android.mk | 12 +++++++++++- 5 files changed, 53 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk index 78d938432f..28588e400a 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk @@ -12,9 +12,19 @@ LOCAL_SRC_FILES := hellocpp/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk index e06290f84b..1e65b8e7a5 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk +++ b/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk @@ -12,9 +12,20 @@ LOCAL_SRC_FILES := cocosdragonjs/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) + diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk index 3258f123af..9c8854568c 100644 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk +++ b/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk @@ -12,9 +12,19 @@ LOCAL_SRC_FILES := crystalcraze/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) $(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk index c409b4790b..93726f5b70 100644 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk +++ b/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk @@ -12,9 +12,19 @@ LOCAL_SRC_FILES := moonwarriors/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) -$(call import-module,scripting/javascript/bindings +$(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk index b666e13723..2d7b4097ab 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk +++ b/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk @@ -12,9 +12,19 @@ LOCAL_SRC_FILES := watermelonwithme/main.cpp \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static +LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT include $(BUILD_SHARED_LIBRARY) -$(call import-module,scripting/javascript/bindings +$(call import-module,scripting/javascript/bindings) +$(call import-module,scripting/javascript/bindings/chipmunk) +$(call import-module,scripting/javascript/bindings/extension) +$(call import-module,scripting/javascript/bindings/localstorage) +$(call import-module,scripting/javascript/bindings/network) +$(call import-module,scripting/javascript/bindings/cocosbuilder) From 50c426109264fc5f8f331e2965a01c79325154e0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 20:53:51 +0800 Subject: [PATCH 349/557] closed #3104: Touch listener should be registered in Menu::initXXX and Control::init rather than onEnter. --- cocos/2d/CCMenu.cpp | 22 +++++++-------- .../GUI/CCControlExtension/CCControl.cpp | 28 ++++++------------- extensions/GUI/CCControlExtension/CCControl.h | 11 -------- 3 files changed, 20 insertions(+), 41 deletions(-) diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 3b0cefbec3..6fef9d78a6 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -149,7 +149,6 @@ bool Menu::initWithArray(Array* pArrayOfItems) } } - // [self alignItemsVertically]; _selectedItem = NULL; _state = Menu::State::WAITING; @@ -157,6 +156,17 @@ bool Menu::initWithArray(Array* pArrayOfItems) setCascadeColorEnabled(true); setCascadeOpacityEnabled(true); + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->setSwallowTouches(true); + + touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this); + touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + return true; } return false; @@ -184,16 +194,6 @@ void Menu::addChild(Node * child, int zOrder, int tag) void Menu::onEnter() { Layer::onEnter(); - - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->setSwallowTouches(true); - - touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this); - touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this); - - _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); } void Menu::onExit() diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 2b97094acc..13d86e629c 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -80,6 +80,15 @@ bool Control::init() _dispatchTable = new Dictionary(); _dispatchTable->init(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(Control::onTouchEnded, this); + touchListener->onTouchCancelled = CC_CALLBACK_2(Control::onTouchCancelled, this); + + dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + return true; } else @@ -93,25 +102,6 @@ Control::~Control() CC_SAFE_RELEASE(_dispatchTable); } -void Control::onEnter() -{ - Layer::onEnter(); - - auto dispatcher = Director::getInstance()->getEventDispatcher(); - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(Control::onTouchEnded, this); - touchListener->onTouchCancelled = CC_CALLBACK_2(Control::onTouchCancelled, this); - - dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); -} - -void Control::onExit() -{ - Layer::onExit(); -} - void Control::sendActionsForControlEvents(EventType controlEvents) { // For each control events diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index 0a9952803b..d8644a516f 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -182,17 +182,6 @@ public: // Overrides virtual bool isOpacityModifyRGB() const override; virtual void setOpacityModifyRGB(bool bOpacityModifyRGB) override; - /** - * @js NA - * @lua NA - */ - virtual void onEnter() override; - /** - * @js NA - * @lua NA - */ - virtual void onExit() override; -// virtual void registerWithTouchDispatcher() override; protected: /** From 01b6e972a0ed681f2e723ce2de8f3f362e5b8bc0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 1 Nov 2013 20:58:25 +0800 Subject: [PATCH 350/557] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 778f136096..4d46f23c70 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -9,6 +9,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] create_project.py does not rename/replace template projects completely. [FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] The Node's anchor point was changed after being added to ScrollView. + [FIX] Refactored and improved EventDispatcher. [NEW] Added Mouse Support For Desktop Platforms. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes From 6360c407250eb60b5d6751f7a08ed8776de51ab7 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 1 Nov 2013 13:03:20 +0000 Subject: [PATCH 351/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c2828315e5..f399ed2207 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c2828315e53a4dedcdbc9e64fee388e20e49b9b4 +Subproject commit f399ed22077b04a757a1b5613acf20bfdf7796b7 From ffad18a1eddb16d84bf94ebda48ffe7a2e2c1982 Mon Sep 17 00:00:00 2001 From: Michael Contento Date: Sat, 2 Nov 2013 06:15:08 +0100 Subject: [PATCH 352/557] Trigger onKeyReleased only after the key has been released --- cocos/2d/platform/linux/CCEGLView.cpp | 2 +- cocos/2d/platform/mac/CCEGLView.mm | 2 +- cocos/2d/platform/win32/CCEGLView.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index ed1b2b6ddb..33b8796959 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -256,7 +256,7 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); } diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index 63bc94a43d..af3863476d 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -274,7 +274,7 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); } diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index b84d87c554..6b19ec5bb5 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -373,7 +373,7 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); } From 06f166f613efb7611b6d06c94925f982724d072c Mon Sep 17 00:00:00 2001 From: psi Date: Sat, 2 Nov 2013 16:03:54 +0900 Subject: [PATCH 353/557] why not search _toAddedListeners?? --- cocos/2d/CCEventDispatcher.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 14be190f68..1159bba86e 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -212,9 +212,16 @@ void EventDispatcher::removeEventListener(EventListener* listener) break; } - if (isFound) - { + if (isFound) { CC_SAFE_RELEASE(listener); + } else { + for(auto iter=_toAddedListeners.begin(); iter != _toAddedListeners.end(); ++iter) { + if ((*iter)->listener == listener) + { + _toAddedListeners.erase(iter); + break; + } + } } } From 7dc6513687c4f6992087060f7ca532a0bd4f5be6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 21:47:00 +0800 Subject: [PATCH 354/557] Adding more tests for EventDispatcherTest. --- .../NewEventDispatcherTest.cpp | 87 ++++++++++++++++++- .../NewEventDispatcherTest.h | 9 ++ 2 files changed, 94 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index bbc041c70b..5f06e0c9ed 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -19,7 +19,8 @@ std::function createFunctions[] = CL(CustomEventTest), CL(LabelKeyboardEventTest), CL(SpriteAccelerationEventTest), - CL(RemoveAndRetainNodeTest) + CL(RemoveAndRetainNodeTest), + CL(RemoveListenerAfterAddingTest) }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -665,4 +666,86 @@ std::string RemoveAndRetainNodeTest::title() std::string RemoveAndRetainNodeTest::subtitle() { return "Sprite should be removed after 5s, add to scene again after 5s"; -} \ No newline at end of file +} + +//RemoveListenerAfterAddingTest +void RemoveListenerAfterAddingTest::onEnter() +{ + EventDispatcherTestDemo::onEnter(); + + auto item1 = MenuItemFont::create("Click Me 1", [this](Object* sender){ + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event) -> bool{ + CCASSERT(false, "Should not come here!"); + return true; + }; + + _eventDispatcher->addEventListenerWithFixedPriority(listener, -1); + _eventDispatcher->removeEventListener(listener); + }); + + item1->setPosition(VisibleRect::center() + Point(0, 80)); + + auto addNextButton = [this](){ + auto next = MenuItemFont::create("Please Click Me To Reset!"); + next->setPosition(VisibleRect::center() + Point(0, -40)); + + auto menu = Menu::create(next, nullptr); + menu->setPosition(VisibleRect::leftBottom()); + menu->setAnchorPoint(Point::ZERO); + this->addChild(menu); + }; + + auto item2 = MenuItemFont::create("Click Me 2", [=](Object* sender){ + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event) -> bool{ + CCASSERT(false, "Should not come here!"); + return true; + }; + + _eventDispatcher->addEventListenerWithFixedPriority(listener, -1); + _eventDispatcher->removeEventListeners(EventListener::Type::TOUCH_ONE_BY_ONE); + + addNextButton(); + }); + + item2->setPosition(VisibleRect::center() + Point(0, 40)); + + auto item3 = MenuItemFont::create("Click Me 3", [=](Object* sender){ + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event) -> bool{ + CCASSERT(false, "Should not come here!"); + return true; + }; + + _eventDispatcher->addEventListenerWithFixedPriority(listener, -1); + _eventDispatcher->removeAllEventListeners(); + + addNextButton(); + }); + + item3->setPosition(VisibleRect::center()); + + auto menu = Menu::create(item1, item2, item3, nullptr); + menu->setPosition(VisibleRect::leftBottom()); + menu->setAnchorPoint(Point::ZERO); + + addChild(menu); +} + +void RemoveListenerAfterAddingTest::onExit() +{ + EventDispatcherTestDemo::onExit(); +} + +std::string RemoveListenerAfterAddingTest::title() +{ + return "RemoveListenerAfterAddingTest"; +} + +std::string RemoveListenerAfterAddingTest::subtitle() +{ + return "Should not crash!"; +} + + diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 080e623008..529813e7b8 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -96,4 +96,13 @@ private: bool _spriteSaved; }; +class RemoveListenerAfterAddingTest : public EventDispatcherTestDemo +{ +public: + virtual void onEnter() override; + virtual void onExit() override; + virtual std::string title() override; + virtual std::string subtitle() override; +}; + #endif /* defined(__samples__NewEventDispatcherTest__) */ From 8f213420ebee44f6a871d70c042da3af7068f293 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:05:04 +0800 Subject: [PATCH 355/557] closed #3106: Update NewEventDispatcherTest.cpp. --- .../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 5f06e0c9ed..1828dbb03d 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -687,7 +687,9 @@ void RemoveListenerAfterAddingTest::onEnter() item1->setPosition(VisibleRect::center() + Point(0, 80)); auto addNextButton = [this](){ - auto next = MenuItemFont::create("Please Click Me To Reset!"); + auto next = MenuItemFont::create("Please Click Me To Reset!", [this](Object* sender){ + this->restartCallback(nullptr); + }); next->setPosition(VisibleRect::center() + Point(0, -40)); auto menu = Menu::create(next, nullptr); From fd21e3ea38682352cb274bff902b9128b2c948ad Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:08:08 +0800 Subject: [PATCH 356/557] closed #3106: fixed: EventListeners can't be removed sometimes. --- cocos/2d/CCEventDispatcher.cpp | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index e4be089f7d..0b9f4d042d 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -442,11 +442,15 @@ void EventDispatcher::removeEventListener(EventListener* listener) break; } - if (isFound) { + if (isFound) + { CC_SAFE_RELEASE(listener); - } else { - for(auto iter=_toAddedListeners.begin(); iter != _toAddedListeners.end(); ++iter) { - if ((*iter)->listener == listener) + } + else + { + for(auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end(); ++iter) + { + if (*iter == listener) { _toAddedListeners.erase(iter); break; @@ -1048,6 +1052,18 @@ void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerI _priorityDirtyFlagMap.erase(listenerID); } } + + for(auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end();) + { + if ((*iter)->getListenerID() == listenerID) + { + iter = _toAddedListeners.erase(iter); + } + else + { + ++iter; + } + } } void EventDispatcher::removeEventListeners(EventListener::Type listenerType) From 2cd957a6fe24433a147a765ed0db339587fc5255 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:10:59 +0800 Subject: [PATCH 357/557] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 7260f3e164..b5e30d6e89 100644 --- a/AUTHORS +++ b/AUTHORS @@ -637,6 +637,9 @@ Developers: Nite Luo (darkdukey) Added Mouse Support For Desktop Platforms. + ledyba + Fixed a bug that EventListeners can't be removed sometimes. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From c0683410b36f69ba6a7a06e9a25c62019bd84b77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:13:01 +0800 Subject: [PATCH 358/557] update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 4d46f23c70..69e6d443fb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -11,6 +11,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] The Node's anchor point was changed after being added to ScrollView. [FIX] Refactored and improved EventDispatcher. [NEW] Added Mouse Support For Desktop Platforms. + [FIX] EventListeners can't be removed sometimes. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From 23faae22eec8566dfc39df364381bd83121b99f5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:16:07 +0800 Subject: [PATCH 359/557] UPDATE CHANGELOG[ci skip] --- CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 69e6d443fb..c8e6b9d403 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -23,6 +23,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Removed unused CCLOG() from GL initialization [iOS] [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. +[Desktop] + [FIX] Trigger onKeyReleased only after the key has been released. [Javascript binding] [FIX] Fixed a memory leak in ScriptingCore::runScript() [FIX] sys.localStorage.getItem() does not support non-ascii string. From f3be8ac6a68d42d4e429459a3dc3c727807a8ced Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 22:16:39 +0800 Subject: [PATCH 360/557] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index b5e30d6e89..41e87fa132 100644 --- a/AUTHORS +++ b/AUTHORS @@ -593,6 +593,7 @@ Developers: [Android] re-introduce Cocos2dxHelper.runOnGLThread(Runnable) [Android] added EGL_RENDERABLE_TYPE to OpenGL attributes Android: add xlargeScreens="true" to supports-screens + Trigger onKeyReleased only after the key has been released. bmanGH Use gl caching functions in TexturePVR::createGLTexture() From 5443fc0d07739743248eb431e1afb95bb1cdd23e Mon Sep 17 00:00:00 2001 From: psi Date: Sun, 3 Nov 2013 11:17:04 +0900 Subject: [PATCH 361/557] pXmlBuffer is not null terminated --- cocos/2d/CCUserDefault.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index ab30c805a0..5a85d65b41 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -66,7 +66,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle CCLOG("can not read xml file"); break; } - xmlDoc->Parse(pXmlBuffer); + xmlDoc->Parse(pXmlBuffer, nSize); delete[] pXmlBuffer; // get root node *rootNode = xmlDoc->RootElement(); From 6b8b1fb3c964a44999ce32f615edd374e577d801 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 14:01:02 +0800 Subject: [PATCH 362/557] Update android-build.py Fixing wrong capital letter, `samples/JavaScript` --> `samples/Javascript` --- build/android-build.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index be4800453a..07003e1953 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -182,15 +182,15 @@ def build_samples(target,ndk_build_param): elif target == 'testlua': app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') elif target == 'cocosdragon': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CocosDragonJS/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android') elif target == 'crystalcraze': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/CrystalCraze/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android') elif target == 'moonwarriors': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/MoonWarriors/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/MoonWarriors/proj.android') elif target == 'testjavascript': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/TestJavascript/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/TestJavascript/proj.android') elif target == 'watermelonwithme': - app_android_root = os.path.join(cocos_root, 'samples/JavaScript/WatermelonWithMe/proj.android') + app_android_root = os.path.join(cocos_root, 'samples/Javascript/WatermelonWithMe/proj.android') else: print 'unknown target: %s' % target continue From a823e66f8e3cdb9afd56ac9f79b443108c47ddbc Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 14:36:22 +0800 Subject: [PATCH 363/557] Update run-script.sh Adding soft-link for `samples/Cpp/SimpleGame/proj.android/obj`. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index f9e5e0ff6b..5cd83ad826 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -42,7 +42,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Create a directory for temporary objects mkdir android_build_objs - PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") + PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/SimpleGame" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") for i in ${PROJECTS[*]}; do ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/samples/$i/proj.android/obj done From 44bc52cf65eee6ad38a0046431c7159160cba988 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 15:36:05 +0800 Subject: [PATCH 364/557] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index c8e6b9d403..12f5963e3e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -12,6 +12,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Refactored and improved EventDispatcher. [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. + [FIX] When parsing XML using TinyXML, the data size has to be specified. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again From d335769e3fccbae58ad3fa9bbb14702c95d544e8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 3 Nov 2013 15:37:39 +0800 Subject: [PATCH 365/557] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 41e87fa132..0c11df97d6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -640,6 +640,7 @@ Developers: ledyba Fixed a bug that EventListeners can't be removed sometimes. + Fixed a bug that the data size has to be specified when parsing XML using TinyXML. Retired Core Developers: WenSheng Yang From 1cf0a926e19a6b8f75319f4a6acfb307a3202580 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 4 Nov 2013 02:46:22 +0000 Subject: [PATCH 366/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f399ed2207..006193d9b4 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f399ed22077b04a757a1b5613acf20bfdf7796b7 +Subproject commit 006193d9b4081c8af2b79be3cd9bcf90aedfdbae From f6d82d21d21421770bb030227e1dc4e5e970444f Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 10:48:45 +0800 Subject: [PATCH 367/557] closed #3108: add -fsigned-char to make char to signed as default --- samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk | 3 +-- samples/Cpp/HelloCpp/proj.android/jni/Application.mk | 2 +- samples/Cpp/SimpleGame/proj.android/jni/Application.mk | 2 +- samples/Cpp/TestCpp/proj.android/jni/Application.mk | 2 +- .../Javascript/CocosDragonJS/proj.android/jni/Application.mk | 3 +-- .../Javascript/CrystalCraze/proj.android/jni/Application.mk | 3 +-- .../Javascript/MoonWarriors/proj.android/jni/Application.mk | 3 +-- .../Javascript/TestJavascript/proj.android/jni/Application.mk | 3 +-- .../WatermelonWithMe/proj.android/jni/Application.mk | 3 +-- samples/Lua/HelloLua/proj.android/jni/Application.mk | 4 ++-- samples/Lua/TestLua/proj.android/jni/Application.mk | 2 +- template/multi-platform-cpp/proj.android/jni/Application.mk | 2 +- template/multi-platform-js/proj.android/jni/Application.mk | 4 ++-- template/multi-platform-lua/proj.android/jni/Application.mk | 2 +- 14 files changed, 16 insertions(+), 22 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk index 5273ceb9dd..74af9626ab 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk +++ b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk index 0e9d025fba..74af9626ab 100644 --- a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk +++ b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/TestCpp/proj.android/jni/Application.mk b/samples/Cpp/TestCpp/proj.android/jni/Application.mk index 9761d1692d..47d8add103 100644 --- a/samples/Cpp/TestCpp/proj.android/jni/Application.mk +++ b/samples/Cpp/TestCpp/proj.android/jni/Application.mk @@ -2,4 +2,4 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk +++ b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk index 24a7a8cbb3..3666985a1f 100644 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk +++ b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk @@ -1,7 +1,6 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk index 6608c6e10e..47d8add103 100644 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk +++ b/samples/Javascript/MoonWarriors/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT= -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk +++ b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk index dc8b56b0ac..47d8add103 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk +++ b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk @@ -1,6 +1,5 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -std=c++11 # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Lua/HelloLua/proj.android/jni/Application.mk b/samples/Lua/HelloLua/proj.android/jni/Application.mk index a829fc0f48..540e49c358 100644 --- a/samples/Lua/HelloLua/proj.android/jni/Application.mk +++ b/samples/Lua/HelloLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char -APP_CPPFLAGS += -fexceptions +APP_CPPFLAGS += -fexceptions diff --git a/samples/Lua/TestLua/proj.android/jni/Application.mk b/samples/Lua/TestLua/proj.android/jni/Application.mk index a829fc0f48..3961feba34 100644 --- a/samples/Lua/TestLua/proj.android/jni/Application.mk +++ b/samples/Lua/TestLua/proj.android/jni/Application.mk @@ -2,7 +2,7 @@ APP_STL := gnustl_static # add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] # in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char APP_CPPFLAGS += -fexceptions diff --git a/template/multi-platform-cpp/proj.android/jni/Application.mk b/template/multi-platform-cpp/proj.android/jni/Application.mk index b20df4f373..ae98b275c1 100644 --- a/template/multi-platform-cpp/proj.android/jni/Application.mk +++ b/template/multi-platform-cpp/proj.android/jni/Application.mk @@ -1,2 +1,2 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-js/proj.android/jni/Application.mk b/template/multi-platform-js/proj.android/jni/Application.mk index ee36f34b40..76c0f20fca 100644 --- a/template/multi-platform-js/proj.android/jni/Application.mk +++ b/template/multi-platform-js/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1 -APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti +APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char diff --git a/template/multi-platform-lua/proj.android/jni/Application.mk b/template/multi-platform-lua/proj.android/jni/Application.mk index 95acd5331a..de85c24eda 100644 --- a/template/multi-platform-lua/proj.android/jni/Application.mk +++ b/template/multi-platform-lua/proj.android/jni/Application.mk @@ -1,4 +1,4 @@ APP_STL := gnustl_static -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 +APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char APP_CPPFLAGS += -fexceptions From 6d6cbc98bbb69dba0eea999195a2284d310aa4c0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:46:56 +0800 Subject: [PATCH 368/557] Update travis.yml, only build master and develop branch [ci skip] --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.travis.yml b/.travis.yml index 966f293146..1e67e468bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,3 +26,9 @@ script: - tools/travis-scripts/run-script.sh before_install: - tools/travis-scripts/before-install.sh + +# whitelist +branches: + only: + - master + - develop From 00acd67ff37595dc78fb2c9f3424afe7c3247356 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 4 Nov 2013 14:36:38 +0800 Subject: [PATCH 369/557] issue #2771: finish OneWayPlatform demo and fix some bugs --- cocos/physics/CCPhysicsBody.cpp | 15 ++++++++---- cocos/physics/CCPhysicsContact.cpp | 4 ++-- cocos/physics/CCPhysicsShape.cpp | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 24 +++++++++---------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 2 +- 5 files changed, 27 insertions(+), 20 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 1922ee59d4..152a4fc454 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -79,7 +79,7 @@ PhysicsBody::PhysicsBody() , _tag(0) , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) -, _contactTestBitmask(0) +, _contactTestBitmask(UINT_MAX) , _group(0) { } @@ -287,12 +287,19 @@ void PhysicsBody::setDynamic(bool dynamic) if (dynamic != _dynamic) { _dynamic = dynamic; - if (_world != nullptr) + if (dynamic) { - if (dynamic) + cpBodySetMass(_info->body, _mass); + + if (_world != nullptr) { cpSpaceAddBody(_world->_info->space, _info->body); - }else + } + }else + { + cpBodySetMass(_info->body, PHYSICS_INFINITY); + + if (_world != nullptr) { cpSpaceRemoveBody(_world->_info->space, _info->body); } diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 1d0cfd8bdd..b5a7c7e0a3 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -194,7 +194,7 @@ bool EventListenerPhysicsContact::init() { auto func = [this](EventCustom* event) -> void { - return onEvent(event); + onEvent(event); }; return EventListenerCustom::init(std::hash()(PHYSICSCONTACT_EVENT_NAME), func); @@ -250,7 +250,7 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event) } case PhysicsContact::EventCode::POSTSOLVE: { - if (onContactPreSolve != nullptr + if (onContactPostSolve != nullptr && test(contact.getShapeA(), contact.getShapeB())) { PhysicsContactPostSolve solve(contact._contactInfo); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 68ef1cf351..c2334ec719 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -52,7 +52,7 @@ PhysicsShape::PhysicsShape() , _tag(0) , _categoryBitmask(UINT_MAX) , _collisionBitmask(UINT_MAX) -, _contactTestBitmask(0) +, _contactTestBitmask(UINT_MAX) , _group(0) { diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index db51829b3f..866cec82fd 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -204,10 +204,8 @@ void PhysicsDemoClickAdd::onEnter() #ifdef CC_USE_PHYSICS - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); + auto touchListener = EventListenerTouchAllAtOnce::create(); + touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); @@ -764,6 +762,8 @@ void PhysicsDemoJoints::onEnter() PhysicsDemo::onEnter(); auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoJoints::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoJoints::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -1039,24 +1039,24 @@ void PhysicsDemoOneWayPlatform::onEnter() ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(ground); - auto platform = Node::create(); - platform->setPhysicsBody(PhysicsBody::createBox(Size(200, 50))); + auto platform = makeBox(VisibleRect::center(), Size(200, 50)); platform->getPhysicsBody()->setDynamic(false); - platform->setPosition(VisibleRect::center()); this->addChild(platform); - auto ball = makeBall(VisibleRect::center() - Point(0, 50), 5); - ball->getPhysicsBody()->setVelocity(Point(0, 200)); + auto ball = makeBall(VisibleRect::center() - Point(0, 50), 20); + ball->getPhysicsBody()->setVelocity(Point(0, 150)); + ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + ball->getPhysicsBody()->setMass(1.0f); this->addChild(ball); auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); - contactListener->onContactPreSolve = CC_CALLBACK_3(PhysicsDemoOneWayPlatform::onPreSolve, this); + contactListener->onContactBegin = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); } -bool PhysicsDemoOneWayPlatform::onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve) +bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const PhysicsContact& contact) { - return true; + return contact.getContactData()->normal.y < 0; } std::string PhysicsDemoOneWayPlatform::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 185c2a3e96..4de964f2d3 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -140,7 +140,7 @@ public: void onEnter() override; std::string title() override; - bool onPreSolve(EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve); + bool onContactBegin(EventCustom* event, const PhysicsContact& contact); }; #endif From 790be0decccb6f2d7e1071979447e3222222231e Mon Sep 17 00:00:00 2001 From: samuele3 Date: Mon, 4 Nov 2013 14:43:22 +0800 Subject: [PATCH 370/557] issue #3037:Modify vs2012 config --- extensions/assets-manager/AssetsManager.h | 2 +- .../Classes/lua_assetsmanager_test_sample.cpp | 14 ++------------ .../Lua/TestLua/proj.win32/TestLua.win32.vcxproj | 8 +++++--- .../proj.win32/TestLua.win32.vcxproj.filters | 6 ++++++ 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 80f0ae5d81..f3e413f4bd 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -145,7 +145,7 @@ public: * @js NA * @lua NA */ - AssetsManagerDelegateProtocol* getDelegate() { return _delegate ;} + AssetsManagerDelegateProtocol* getDelegate() const { return _delegate ;} /** @brief Sets connection time out in seconds */ diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp index e3d6377f0b..7f0135f06e 100644 --- a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp +++ b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp @@ -26,10 +26,7 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) return 0; int argc = lua_gettop(L); -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - + if (0 == argc) { std::string pathToSave = FileUtils::getInstance()->getWritablePath(); @@ -50,18 +47,11 @@ static int lua_cocos2dx_createDownloadDir(lua_State* L) } #endif tolua_pushstring(L, pathToSave.c_str()); - CCLOG("the path to save is %s",pathToSave.c_str()); return 1; } CCLOG("'createDownloadDir' function wrong number of arguments: %d, was expecting %d\n", argc, 0); return 0; - -#if COCOS2D_DEBUG >= 1 -tolua_lerror: - tolua_error(L,"#ferror in function 'createDownloadDir'.",&tolua_err); - return 0; -#endif } static int lua_cocos2dx_deleteDownloadDir(lua_State* L) @@ -126,7 +116,7 @@ static int lua_cocos2dx_addSearchPath(lua_State* L) goto tolua_lerror; #endif std::string pathToSave = tolua_tostring(L, 1, ""); - bool before = tolua_toboolean(L, 2, 0); + bool before = (bool)tolua_toboolean(L, 2, 0); std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); if (before) { diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj index f70904ac2f..b95a8da2f8 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj @@ -66,7 +66,7 @@ - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -115,7 +115,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)" - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories) Level3 @@ -131,7 +131,7 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)"Windows MachineX86 $(OutDir);%(AdditionalLibraryDirectories) - lua51.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) true @@ -163,10 +163,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters index 7517b68f2b..12f4b9ee7c 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters +++ b/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters @@ -15,6 +15,9 @@ win32 + + Classes + @@ -23,5 +26,8 @@ win32 + + Classes + \ No newline at end of file From 3289ce8fe09f63f8e36de96a6bce1c84f2f1abe4 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Mon, 4 Nov 2013 14:50:23 +0800 Subject: [PATCH 371/557] issue #3037:Modify vs2012 config --- samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp index 7f0135f06e..a254c2cbbd 100644 --- a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp +++ b/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp @@ -116,7 +116,7 @@ static int lua_cocos2dx_addSearchPath(lua_State* L) goto tolua_lerror; #endif std::string pathToSave = tolua_tostring(L, 1, ""); - bool before = (bool)tolua_toboolean(L, 2, 0); + bool before = tolua_toboolean(L, 2, 0); std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); if (before) { From b5838b800d37f455b00e22a106c9aa67e9a7db5f Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 16:48:17 +0800 Subject: [PATCH 372/557] use python script to build template android projects --- CHANGELOG | 3 +- build/android-build.py | 4 - .../proj.android/build_native.cmd | 83 -------------- .../proj.android/build_native.py | 100 +++++++++++++++++ .../proj.android/build_native.sh | 91 --------------- .../proj.android/build_native.cmd | 90 --------------- .../proj.android/build_native.py | 104 ++++++++++++++++++ .../proj.android/build_native.sh | 100 ----------------- .../proj.android/build_native.cmd | 86 --------------- .../proj.android/build_native.py | 104 ++++++++++++++++++ .../proj.android/build_native.sh | 102 ----------------- 11 files changed, 310 insertions(+), 557 deletions(-) delete mode 100644 template/multi-platform-cpp/proj.android/build_native.cmd create mode 100755 template/multi-platform-cpp/proj.android/build_native.py delete mode 100755 template/multi-platform-cpp/proj.android/build_native.sh delete mode 100644 template/multi-platform-js/proj.android/build_native.cmd create mode 100755 template/multi-platform-js/proj.android/build_native.py delete mode 100755 template/multi-platform-js/proj.android/build_native.sh delete mode 100644 template/multi-platform-lua/proj.android/build_native.cmd create mode 100755 template/multi-platform-lua/proj.android/build_native.py delete mode 100755 template/multi-platform-lua/proj.android/build_native.sh diff --git a/CHANGELOG b/CHANGELOG index 12f5963e3e..0d0efb8f2d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,7 +19,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [NEW] Added xlargeScreens="true" to supports-screens - [NEW] Added build/android-build.py to build all Android samples + [NEW] Added build/android-build.py to build all Android samples, and remove all build_native.sh/cmd + [NEW] Added build_native.py to build template projects, and remove build_native.sh/cmd [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] diff --git a/build/android-build.py b/build/android-build.py index 07003e1953..d1a272c2db 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -2,10 +2,6 @@ # android-build.py # Build android samples -# You can use - - -# begin import sys import os, os.path import shutil diff --git a/template/multi-platform-cpp/proj.android/build_native.cmd b/template/multi-platform-cpp/proj.android/build_native.cmd deleted file mode 100644 index 5b25ec4817..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.cmd +++ /dev/null @@ -1,83 +0,0 @@ -@echo off - -set APPNAME="HelloCpp" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-cpp/proj.android/build_native.py b/template/multi-platform-cpp/proj.android/build_native.py new file mode 100755 index 0000000000..e426c2c0ec --- /dev/null +++ b/template/multi-platform-cpp/proj.android/build_native.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-cpp/proj.android/build_native.sh b/template/multi-platform-cpp/proj.android/build_native.sh deleted file mode 100755 index 47c3c53564..0000000000 --- a/template/multi-platform-cpp/proj.android/build_native.sh +++ /dev/null @@ -1,91 +0,0 @@ -APPNAME="HelloCpp" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# run ndk-build -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi diff --git a/template/multi-platform-js/proj.android/build_native.cmd b/template/multi-platform-js/proj.android/build_native.cmd deleted file mode 100644 index 82eb0151a5..0000000000 --- a/template/multi-platform-js/proj.android/build_native.cmd +++ /dev/null @@ -1,90 +0,0 @@ -@echo off - -set APPNAME="HelloJavascript" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -p Run make with -j8 option to take advantage of multiple processors - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-p" set PARALLEL_BUILD_FLAG=\-j8 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 -set BINDINGS_JS_ROOT=%COCOS2DX_ROOT%\cocos\scripting\javascript\script - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets -mkdir %APP_ANDROID_ROOT%\assets\res - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy bindings/*.js into assets' root -xcopy /e /q /r /y %BINDINGS_JS_ROOT%\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd %PARALLEL_BUILD_FLAG% NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-js/proj.android/build_native.py b/template/multi-platform-js/proj.android/build_native.py new file mode 100755 index 0000000000..4e67dd7cfb --- /dev/null +++ b/template/multi-platform-js/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # jsb project should copy javascript files and resources(shared with cocos2d-html5) + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-js/proj.android/build_native.sh b/template/multi-platform-js/proj.android/build_native.sh deleted file mode 100755 index 5a008713a3..0000000000 --- a/template/multi-platform-js/proj.android/build_native.sh +++ /dev/null @@ -1,100 +0,0 @@ -APPNAME="HelloJavascript" - -# options - -buildexternalsfromsource= -PARALLEL_BUILD_FLAG= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --p Run make with -j8 option to take advantage of multiple processors --h this help -EOF -} - -while getopts "sph" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -p) -PARALLEL_BUILD_FLAG=\-j8 -;; -h) -usage -exit 0 -;; -esac -done - -# exit this script if any commmand fails -set -e - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" -BINDINGS_JS_ROOT="$APP_ROOT/../../cocos/scripting/javascript/script" - -echo -echo "Paths" -echo " NDK_ROOT = $NDK_ROOT" -echo " COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo " APP_ROOT = $APP_ROOT" -echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo - -# Debug -set -x - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets -mkdir "$APP_ANDROID_ROOT"/assets/res - -# copy Resources/* into assets' root -cp -rf "$APP_ROOT"/Resources/* "$APP_ANDROID_ROOT"/assets - - -# copy bindings/*.js into assets' root -cp -rf "$BINDINGS_JS_ROOT"/* "$APP_ANDROID_ROOT"/assets - -echo "Using prebuilt externals" -echo - -set -x - -"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" \ - NDK_LOG=0 V=0 diff --git a/template/multi-platform-lua/proj.android/build_native.cmd b/template/multi-platform-lua/proj.android/build_native.cmd deleted file mode 100644 index 0177685738..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.cmd +++ /dev/null @@ -1,86 +0,0 @@ -@echo off - -set APPNAME="HelloLua" - -set buildexternalsfromsource= -set PARALLEL_BUILD_FLAG= - -goto :getopts - -:usage - echo Build C/C++ code for %APPNAME% using Android NDK - echo OPTIONS: - echo -s Build externals from source - echo -h this help - pause - exit /b 1 - -:def - echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment." - pause - exit /b 1 - -:getopts - set "par=%~1" - if "%par%"=="" (goto :L) - if "%~1"=="-s" set /a buildexternalsfromsource=1 - if "%~1"=="-h" goto :usage - shift - goto :getopts - -:L -set NDK_ROOT=%NDK_ROOT% -if "%NDK_ROOT%"=="" goto:def - -rem check toolchains -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.8 (goto :toolchains48) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.7 (goto :toolchains47) -if exist %NDK_ROOT%\toolchains\arm-linux-androideabi-4.6 (goto :toolchains46) -echo "Couldn't find the gcc toolchain." -pause -exit /b 1 - -:toolchains48 - set NDK_TOOLCHAIN_VERSION=4.8 - goto :InitPath -:toolchains47 - set NDK_TOOLCHAIN_VERSION=4.7 - goto :InitPath -:toolchains46 - set NDK_TOOLCHAIN_VERSION=4.6 - -:InitPath - -set COCOS2DX_ROOT=%~dp0..\..\.. -set APP_ROOT=%~dp0.. -set APP_ANDROID_ROOT=%~dp0 - -if "%buildexternalsfromsource%"=="1" (goto :MODULE1) else (goto :MODULE2) -:MODULE1 - echo "Building external dependencies from source" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\source - goto :COPY_RES -:MODULE2 - echo "Using prebuilt externals" - set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos;%COCOS2DX_ROOT%\external - -:COPY_RES -echo NDK_ROOT = %NDK_ROOT% -echo COCOS2DX_ROOT=%COCOS2DX_ROOT% -echo APP_ROOT=%APP_ROOT% -echo APP_ANDROID_ROOT=%APP_ANDROID_ROOT% -echo NDK_TOOLCHAIN_VERSION=%NDK_TOOLCHAIN_VERSION% - -rem make sure assets is exist -if exist %APP_ANDROID_ROOT%\assets rd /q /s %APP_ANDROID_ROOT%\assets - -mkdir %APP_ANDROID_ROOT%\assets - -rem copy Resources/* into assets' root -xcopy /e /q /r /y %APP_ROOT%\Resources\* %APP_ANDROID_ROOT%\assets - -rem copy common luaScript -xcopy /e /q /r /y %COCOS2DX_ROOT%\cocos\scripting\lua\script\* %APP_ANDROID_ROOT%\assets - -call %NDK_ROOT%\ndk-build.cmd NDK_LOG=0 V=0 %* -pause \ No newline at end of file diff --git a/template/multi-platform-lua/proj.android/build_native.py b/template/multi-platform-lua/proj.android/build_native.py new file mode 100755 index 0000000000..c1fe04ac28 --- /dev/null +++ b/template/multi-platform-lua/proj.android/build_native.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# build_native.py +# Build native codes + + +import sys +import os, os.path +import shutil + + +def check_environment_variables(): + ''' Checking the environment NDK_ROOT, which will be used for building + ''' + + try: + NDK_ROOT = os.environ['NDK_ROOT'] + except Exception: + print "NDK_ROOT not defined. Please define NDK_ROOT in your environment" + sys.exit(1) + + return NDK_ROOT + +def select_toolchain_version(): + '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when + using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. + Conclution: + ndk-r8e -> use gcc4.7 + ndk-r9 -> use gcc4.8 + ''' + + ndk_root = check_environment_variables() + if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' + print "The Selected NDK toolchain version was 4.8 !" + elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): + os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' + print "The Selected NDK toolchain version was 4.7 !" + else: + print "Couldn't find the gcc toolchain." + exit(1) + +def do_build(cocos_root, ndk_root, app_android_root): + + ndk_path = os.path.join(ndk_root, "ndk-build") + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + + ndk_build_param = sys.argv[1:] + if len(ndk_build_param) == 0: + command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + else: + command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + os.system(command) + +def copy_files(src, dst): + + for item in os.listdir(src): + path = os.path.join(src, item) + # Android can not package the file that ends with ".gz" + if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path): + shutil.copy(path, dst) + if os.path.isdir(path): + new_dst = os.path.join(dst, item) + os.mkdir(new_dst) + copy_files(path, new_dst) + +def copy_resources(app_android_root): + + # remove app_android_root/assets if it exists + assets_dir = os.path.join(app_android_root, "assets") + if os.path.isdir(assets_dir): + shutil.rmtree(assets_dir) + + # copy resources + os.mkdir(assets_dir) + resources_dir = os.path.join(app_android_root, "../Resources") + if os.path.isdir(resources_dir): + copy_files(resources_dir, assets_dir) + + # lua project should copy lua script + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script") + copy_files(resources_dir, assets_dir) + +def build(): + + ndk_root = check_environment_variables() + select_toolchain_version() + + current_dir = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(current_dir, "../../..") + + app_android_root = current_dir + copy_resources(app_android_root) + do_build(cocos_root, ndk_root, app_android_root) + +# -------------- main -------------- +if __name__ == '__main__': + + build() diff --git a/template/multi-platform-lua/proj.android/build_native.sh b/template/multi-platform-lua/proj.android/build_native.sh deleted file mode 100755 index 930a9e5249..0000000000 --- a/template/multi-platform-lua/proj.android/build_native.sh +++ /dev/null @@ -1,102 +0,0 @@ -APPNAME="HelloLua" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# paths - -if [ -z "${NDK_ROOT+aaa}" ];then -echo "please define NDK_ROOT" -exit 1 -fi - -# For compatibility of android-ndk-r9, 4.7 was removed from r9 -if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.7" ]; then - export NDK_TOOLCHAIN_VERSION=4.7 - echo "The Selected NDK toolchain version was 4.7 !" -else - if [ -d "${NDK_ROOT}/toolchains/arm-linux-androideabi-4.8" ]; then - export NDK_TOOLCHAIN_VERSION=4.8 - echo "The Selected NDK toolchain version was 4.8 !" - else - echo "Couldn't find the gcc toolchain." - exit 1 - fi -fi - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory -COCOS2DX_ROOT="$DIR/../../.." -APP_ROOT="$DIR/.." -APP_ANDROID_ROOT="$DIR" - -echo "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# make sure assets is exist -if [ -d "$APP_ANDROID_ROOT"/assets ]; then - rm -rf "$APP_ANDROID_ROOT"/assets -fi - -mkdir "$APP_ANDROID_ROOT"/assets - -# copy resources -for file in "$APP_ROOT"/Resources/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -# copy common luaScript -for file in "$APP_ROOT"/../../cocos/scripting/lua/script/* -do -if [ -d "$file" ]; then - cp -rf "$file" "$APP_ANDROID_ROOT"/assets -fi - -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/assets -fi -done - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos:${COCOS2DX_ROOT}/external" -fi \ No newline at end of file From cde79a9724bd8a0fb9dbdc47d58c3adb387e87ab Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 4 Nov 2013 18:01:42 +0800 Subject: [PATCH 373/557] use -j10 to build android samples --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 5cd83ad826..54cd858c49 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n NDK_DEBUG=0 all + ./android-build.py -n NDK_DEBUG=0 -j10 all # Build template # echo "Building template ..." From 46710c5f06d656177cdcd920cd1529291423ad46 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 4 Nov 2013 19:26:34 +0800 Subject: [PATCH 374/557] issue #2771: delay load --- cocos/physics/CCPhysicsWorld.cpp | 270 ++++++++++++------ cocos/physics/CCPhysicsWorld.h | 34 ++- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 15 + .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 8 + 4 files changed, 238 insertions(+), 89 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1cd2b936c5..913713277b 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -183,6 +183,12 @@ bool PhysicsWorld::init(Scene& scene) { do { + _delayAddBodies = Array::create(); + _delayRemoveBodies = Array::create(); + CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); + _delayAddBodies->retain(); + _delayRemoveBodies->retain(); + _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); _bodies = Array::create(); @@ -206,20 +212,99 @@ bool PhysicsWorld::init(Scene& scene) return false; } +void PhysicsWorld::delayTestAddBody(PhysicsBody* body) +{ + if (_delayRemoveBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayRemoveBodies->removeObject(body); + return; + } + + if (_info->space->locked_private) + { + if (_delayAddBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayAddBodies->addObject(body); + _delayDirty = true; + } + }else + { + realAddBody(body); + } +} + +void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) +{ + if (_delayAddBodies->getIndexOfObject(body) != UINT_MAX) + { + _delayAddBodies->removeObject(body); + return; + } + + if (_info->space->locked_private) + { + if (_delayRemoveBodies->getIndexOfObject(body) == UINT_MAX) + { + _delayRemoveBodies->addObject(body); + _delayDirty = true; + } + }else + { + realRemoveBody(body); + } +} + +void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) +{ + auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); + if (it != _delayRemoveJoints.end()) + { + _delayRemoveJoints.erase(it); + return; + } + + if (_info->space->locked_private) + { + if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) + { + _delayAddJoints.push_back(joint); + _delayDirty = true; + } + }else + { + realAddJoint(joint); + } +} + +void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) +{ + auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); + if (it != _delayAddJoints.end()) + { + _delayAddJoints.erase(it); + return; + } + + if (_info->space->locked_private) + { + if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) + { + _delayRemoveJoints.push_back(joint); + _delayDirty = true; + } + }else + { + realRemoveJoint(joint); + } +} + void PhysicsWorld::addJoint(PhysicsJoint* joint) { auto it = std::find(_joints.begin(), _joints.end(), joint); if (it == _joints.end()) { - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceAddConstraint(_info->space, subjoint); - } - } - + delayTestAddJoint(joint); _joints.push_back(joint); } @@ -231,14 +316,7 @@ void PhysicsWorld::removeJoint(PhysicsJoint* joint) if (it != _joints.end()) { - for (auto subjoint : joint->_info->joints) - { - if (cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceRemoveConstraint(_info->space, subjoint); - } - } - + delayTestRemoveJoint(*it); _joints.remove(joint); } } @@ -247,13 +325,7 @@ void PhysicsWorld::removeAllJoints() { for (auto joint : _joints) { - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceRemoveConstraint(_info->space, subjoint); - } - } + delayTestRemoveJoint(joint); } _joints.clear(); @@ -263,28 +335,22 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->shapes) { - if (cpSpaceContainsShape(_info->space, cps)) - { - continue; - } - - if (cpBodyIsStatic(shape->getBody()->_info->body)) - { - cpSpaceAddStaticShape(_info->space, cps); - } - else - { - cpSpaceAddShape(_info->space, cps); - } + _info->addShape(cps); } return shape; } -PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +void PhysicsWorld::realAddJoint(PhysicsJoint *joint) +{ + for (auto subjoint : joint->_info->joints) + { + _info->addJoint(subjoint); + } +} + +void PhysicsWorld::realAddBody(PhysicsBody* body) { - CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() != this && body->getWorld() != nullptr) { body->removeFromWorld(); @@ -303,7 +369,7 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) // add body to space if (body->isDynamic()) { - cpSpaceAddBody(_info->space, body->_info->body); + _info->addBody(body->_info->body); } // add shapes to space @@ -312,13 +378,38 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) addShape(dynamic_cast(shape)); } } +} + +PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +{ + CCASSERT(body != nullptr, "the body can not be nullptr"); + delayTestAddBody(body); _bodies->addObject(body); return body; } void PhysicsWorld::removeBody(PhysicsBody* body) +{ + delayTestRemoveBody(body); + _bodies->removeObject(body); +} + +void PhysicsWorld::removeBodyByTag(int tag) +{ + for (Object* obj : *_bodies) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == tag) + { + removeBody(body); + return; + } + } +} + +void PhysicsWorld::realRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -346,25 +437,16 @@ void PhysicsWorld::removeBody(PhysicsBody* body) } // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } + _info->removeBody(body->_info->body); body->_world = nullptr; - _bodies->removeObject(body); } -void PhysicsWorld::removeBodyByTag(int tag) +void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) { - for (Object* obj : *_bodies) + for (auto subjoint : joint->_info->joints) { - PhysicsBody* body = dynamic_cast(obj); - if (body->getTag() == tag) - { - removeBody(body); - return; - } + _info->removeJoint(subjoint); } } @@ -372,33 +454,7 @@ void PhysicsWorld::removeAllBodies() { for (Object* obj : *_bodies) { - PhysicsBody* body = dynamic_cast(obj); - - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - - // remove joints - for (auto joint : body->_joints) - { - removeJoint(joint); - } - - // remove shaps - for (auto shape : *body->getShapes()) - { - removeShape(dynamic_cast(shape)); - } - - // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } - - body->_world = nullptr; + delayTestRemoveBody(dynamic_cast(obj)); } _bodies->removeAllObjects(); @@ -416,8 +472,57 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) } } +void PhysicsWorld::updateBodies() +{ + if (_info->space->locked_private) + { + return; + } + + for (auto body : *_delayAddBodies) + { + realAddBody(dynamic_cast(body)); + } + + for (auto body : *_delayRemoveBodies) + { + realRemoveBody(dynamic_cast(body)); + } + + _delayAddBodies->removeAllObjects(); + _delayRemoveBodies->removeAllObjects(); +} + +void PhysicsWorld::updateJoints() +{ + if (_info->space->locked_private) + { + return; + } + + for (auto joint : _delayAddJoints) + { + realAddJoint(joint); + } + + for (auto joint : _delayRemoveJoints) + { + realRemoveJoint(joint); + } + + _delayAddJoints.clear(); + _delayRemoveJoints.clear(); +} + void PhysicsWorld::update(float delta) { + if (_delayDirty) + { + updateBodies(); + updateJoints(); + _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + } + for (auto body : *_bodies) { body->update(delta); @@ -804,8 +909,11 @@ PhysicsWorld::PhysicsWorld() , _info(nullptr) , _bodies(nullptr) , _scene(nullptr) +, _delayDirty(false) , _debugDraw(false) , _drawNode(nullptr) +, _delayAddBodies(nullptr) +, _delayRemoveBodies(nullptr) { } @@ -814,6 +922,8 @@ PhysicsWorld::~PhysicsWorld() { removeAllBodies(); removeAllJoints(); + CC_SAFE_RELEASE(_delayRemoveBodies); + CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index e719dce2c4..2d4e7def57 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -29,6 +29,7 @@ #define __CCPHYSICS_WORLD_H__ #include +#include #include "CCObject.h" #include "CCGeometry.h" @@ -86,11 +87,15 @@ class PhysicsWorld { public: /** Adds a joint to the physics world.*/ - void addJoint(PhysicsJoint* joint); + virtual void addJoint(PhysicsJoint* joint); /** Removes a joint from the physics world.*/ - void removeJoint(PhysicsJoint* joint); + virtual void removeJoint(PhysicsJoint* joint); /** Remove all joints from the physics world.*/ - void removeAllJoints(); + virtual void removeAllJoints(); + + virtual void removeBody(PhysicsBody* body); + virtual void removeBodyByTag(int tag); + virtual void removeAllBodies(); void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); @@ -115,10 +120,6 @@ public: /** set the debug draw */ inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } - virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); - virtual void removeAllBodies(); - protected: static PhysicsWorld* create(Scene& scene); bool init(Scene& scene); @@ -132,25 +133,40 @@ protected: virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); virtual void drawWithJoint(DrawNode* node, PhysicsJoint* joint); - virtual int collisionBeginCallback(PhysicsContact& contact); virtual int collisionPreSolveCallback(PhysicsContact& contact); virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); + virtual void realAddBody(PhysicsBody* body); + virtual void realRemoveBody(PhysicsBody* body); + virtual void realAddJoint(PhysicsJoint* joint); + virtual void realRemoveJoint(PhysicsJoint* joint); + virtual void delayTestAddBody(PhysicsBody* body); + virtual void delayTestRemoveBody(PhysicsBody* body); + virtual void delayTestAddJoint(PhysicsJoint* joint); + virtual void delayTestRemoveJoint(PhysicsJoint* joint); + virtual void updateBodies(); + virtual void updateJoints(); + protected: Point _gravity; float _speed; PhysicsWorldInfo* _info; - //EventListenerPhysicsContact* _listener; Array* _bodies; std::list _joints; Scene* _scene; + bool _delayDirty; bool _debugDraw; DrawNode* _drawNode; + Array* _delayAddBodies; + Array* _delayRemoveBodies; + std::vector _delayAddJoints; + std::vector _delayRemoveJoints; + protected: PhysicsWorld(); virtual ~PhysicsWorld(); diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index f58eebadf2..fecf2009aa 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -26,6 +26,21 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN +#define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ +void PhysicsWorldInfo::add##name(cp##type* data) \ +{ \ + if (!cpSpaceContains##type(space, data)) cpSpaceAdd##type(space, data); \ +} \ +\ +void PhysicsWorldInfo::remove##name(cp##type* data) \ +{ \ + if (cpSpaceContains##type(space, data)) cpSpaceRemove##type(space, data); \ +} \ + +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Body, Body) +PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) + PhysicsWorldInfo::PhysicsWorldInfo() { space = cpSpaceNew(); diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 158f074c77..5e6c78bc97 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -30,6 +30,7 @@ #include "chipmunk.h" #include "CCPlatformMacros.h" +#include NS_CC_BEGIN class PhysicsWorldInfo @@ -37,6 +38,13 @@ class PhysicsWorldInfo public: cpSpace* space; + void addShape(cpShape* shape); + void removeShape(cpShape* shape); + void addBody(cpBody* body); + void removeBody(cpBody* body); + void addJoint(cpConstraint* joint); + void removeJoint(cpConstraint* joint); + private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); From add96f63a6946fca576fc5d919bbd0d3959eb39d Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:40:07 +0800 Subject: [PATCH 375/557] Adding top level cmakefiles.txt --- CMakeLists.txt | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..512d1e916b --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,97 @@ +cmake_minimum_required(VERSION 2.6) +project (Cocos2dxSamples) + +# The version number +set(Cocos2dxSamples_VERSION_MAJOR 3) +set(Cocos2dxSamples_VERSION_MINOR 0) + +add_definitions(-DLINUX) + +# debug +message( "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}" ) +if ( "${CMAKE_BUILD_TYPE}" STREQUAL "DEBUG" ) + add_definitions(-D_DEBUG) +endif() + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") + +include_directories( + cocos/2d + cocos/2d/platform + cocos/2d/platform/linux + cocos/base + cocos/physics + cocos/math/kazmath/include + external/jpeg/include/linux + external/tiff/include/linux + external/webp/include/linux + external/glfw3/include/linux + external/tinyxml2 + external/unzip + external/chipmunk/include/chipmunk + external/freetype2/include/linux +) + +link_directories( + /usr/local/lib + ${CMAKE_SOURCE_DIR}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} +) + +set(COCOS_LIBRARIES + cocos2d + cocosbase + chipmunk_static + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + glfw + GLEW + GL + rt + z +) + +# kazmath +add_subdirectory(cocos/math/kazmath) + +# chipmunk library +set(BUILD_STATIC 1) + +# chipmunk library +add_subdirectory(external/chipmunk/src) + +# unzip library +add_subdirectory(external/unzip) + +# tinyxml2 library +add_subdirectory(external/tinyxml2) + +# cocos base library +add_subdirectory(cocos/base) + +# cocos physics sources +#add_subdirectory(cocos/physics) + +# cocos 2d library +add_subdirectory(cocos/2d) + +# sample HelloCpp +add_subdirectory(samples/Cpp/HelloCpp) + From 8cdd1af98278f0a9593c3bd94734cd66bb517e68 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:41:04 +0800 Subject: [PATCH 376/557] HelloCpp CMakeLists.txt --- samples/Cpp/HelloCpp/CMakeLists.txt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 samples/Cpp/HelloCpp/CMakeLists.txt diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt new file mode 100644 index 0000000000..f22b681d8f --- /dev/null +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -0,0 +1,14 @@ +set(SAMPLE_NAME hellocpp) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) From 8676523433a1fd9556681b73a7c3f0600b5dfce2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 14:44:54 +0800 Subject: [PATCH 377/557] Adding CMakeLists.txt --- cocos/2d/CMakeLists.txt | 125 ++++++++++++++++++++++++++++++ cocos/base/CMakeLists.txt | 20 +++++ cocos/math/kazmath/CMakeLists.txt | 17 ++++ cocos/physics/CMakeLists.txt | 17 ++++ external/tinyxml2/CMakeLists.txt | 7 ++ external/unzip/CMakeLists.txt | 8 ++ 6 files changed, 194 insertions(+) create mode 100644 cocos/2d/CMakeLists.txt create mode 100644 cocos/base/CMakeLists.txt create mode 100644 cocos/math/kazmath/CMakeLists.txt create mode 100644 cocos/physics/CMakeLists.txt create mode 100644 external/tinyxml2/CMakeLists.txt create mode 100644 external/unzip/CMakeLists.txt diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt new file mode 100644 index 0000000000..fdcd28a564 --- /dev/null +++ b/cocos/2d/CMakeLists.txt @@ -0,0 +1,125 @@ +set(COCOS2D_SRC + CCAction.cpp + CCActionCamera.cpp + CCActionEase.cpp + CCActionGrid.cpp + CCActionGrid3D.cpp + CCActionInstant.cpp + CCActionInterval.cpp + CCActionManager.cpp + CCActionPageTurn3D.cpp + CCActionProgressTimer.cpp + CCActionTiledGrid.cpp + CCActionCatmullRom.cpp + CCActionTween.cpp + CCAtlasNode.cpp + CCNode.cpp + CCEventAcceleration.cpp + CCEventListenerAcceleration.cpp + CCEvent.cpp + CCEventDispatcher.cpp + CCEventListener.cpp + CCEventKeyboard.cpp + CCEventListenerKeyboard.cpp + CCEventMouse.cpp + CCEventListenerMouse.cpp + CCTouch.cpp + CCEventTouch.cpp + CCEventListenerTouch.cpp + CCEventCustom.cpp + CCEventListenerCustom.cpp + CCDrawingPrimitives.cpp + CCDrawNode.cpp + CCGrabber.cpp + CCGrid.cpp + CCFont.cpp + CCFontAtlas.cpp + CCFontAtlasCache.cpp + CCFontAtlasFactory.cpp + CCFontDefinition.cpp + CCFontFNT.cpp + CCFontFreeType.cpp + CCLabel.cpp + CCLabelAtlas.cpp + CCLabelBMFont.cpp + CCLabelTTF.cpp + CCLabelTextFormatter.cpp + CCTextImage.cpp + CCLayer.cpp + CCScene.cpp + CCTransition.cpp + CCTransitionPageTurn.cpp + CCTransitionProgress.cpp + CCMenu.cpp + CCMenuItem.cpp + CCMotionStreak.cpp + CCProgressTimer.cpp + CCClippingNode.cpp + CCRenderTexture.cpp + CCParticleExamples.cpp + CCParticleSystem.cpp + CCParticleSystemQuad.cpp + CCParticleBatchNode.cpp + CCScriptSupport.cpp + CCAnimation.cpp + CCAnimationCache.cpp + CCSprite.cpp + CCSpriteBatchNode.cpp + CCSpriteFrame.cpp + CCSpriteFrameCache.cpp + ccUTF8.cpp + CCProfiling.cpp + CCUserDefault.cpp + TransformUtils.cpp + base64.cpp + ccUtils.cpp + CCVertex.cpp + CCNotificationCenter.cpp + TGAlib.cpp + ZipUtils.cpp + ccCArray.cpp + CCComponent.cpp + CCComponentContainer.cpp + CCIMEDispatcher.cpp + CCTextFieldTTF.cpp + CCTexture2D.cpp + CCTextureAtlas.cpp + CCTextureCache.cpp + CCParallaxNode.cpp + CCTMXLayer.cpp + CCTMXObjectGroup.cpp + CCTMXTiledMap.cpp + CCTMXXMLParser.cpp + CCTileMapAtlas.cpp + CCGLProgram.cpp + ccGLStateCache.cpp + CCShaderCache.cpp + ccShaders.cpp + CCCamera.cpp + CCConfiguration.cpp + CCDirector.cpp + CCScheduler.cpp + ccFPSImages.c + ccTypes.cpp + cocos2d.cpp + CCDeprecated.cpp + platform/CCSAXParser.cpp + platform/CCThread.cpp + platform/CCEGLViewProtocol.cpp + platform/CCFileUtils.cpp + platform/linux/CCStdC.cpp + platform/linux/CCFileUtilsLinux.cpp + platform/linux/CCCommon.cpp + platform/linux/CCApplication.cpp + platform/linux/CCEGLView.cpp + platform/linux/CCImage.cpp + platform/linux/CCDevice.cpp +) + +include(../physics/CMakeLists.txt) + +add_library(cocos2d STATIC + ${COCOS2D_SRC} + ${COCOS_PHYSICS_SRC} +) + diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt new file mode 100644 index 0000000000..c46e07c114 --- /dev/null +++ b/cocos/base/CMakeLists.txt @@ -0,0 +1,20 @@ +set(COCOS_BASE_SRC + CCAffineTransform.cpp + CCAutoreleasePool.cpp + CCGeometry.cpp + CCNS.cpp + CCObject.cpp + CCSet.cpp + CCArray.cpp + CCDictionary.cpp + CCString.cpp + CCDataVisitor.cpp + CCData.cpp + etc1.cpp + s3tc.cpp + atitc.cpp +) + +add_library(cocosbase STATIC + ${COCOS_BASE_SRC} +) diff --git a/cocos/math/kazmath/CMakeLists.txt b/cocos/math/kazmath/CMakeLists.txt new file mode 100644 index 0000000000..1dc636037d --- /dev/null +++ b/cocos/math/kazmath/CMakeLists.txt @@ -0,0 +1,17 @@ + +SET(KAZMATH_SOURCES + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/mat3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/plane.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec4.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/quaternion.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/vec3.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/utility.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/aabb.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/ray2.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/mat4stack.c + ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/matrix.c + ) + +ADD_SUBDIRECTORY(src) \ No newline at end of file diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt new file mode 100644 index 0000000000..2ca5a7f532 --- /dev/null +++ b/cocos/physics/CMakeLists.txt @@ -0,0 +1,17 @@ +set(COCOS_PHYSICS_SRC + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsBody.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsContact.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsShape.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsJoint.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsWorld.cpp +) diff --git a/external/tinyxml2/CMakeLists.txt b/external/tinyxml2/CMakeLists.txt new file mode 100644 index 0000000000..42822a3bc4 --- /dev/null +++ b/external/tinyxml2/CMakeLists.txt @@ -0,0 +1,7 @@ +set(TINYXML2_SRC + tinyxml2.cpp +) + +add_library(tinyxml2 STATIC + ${TINYXML2_SRC} +) diff --git a/external/unzip/CMakeLists.txt b/external/unzip/CMakeLists.txt new file mode 100644 index 0000000000..8d15111c8e --- /dev/null +++ b/external/unzip/CMakeLists.txt @@ -0,0 +1,8 @@ +set(UNZIP_SRC + ioapi.cpp + unzip.cpp +) + +add_library(unzip STATIC + ${UNZIP_SRC} +) From e560de6e4eb41e4c71afca0a94d3997cbb2e8cdf Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 16:31:52 +0800 Subject: [PATCH 378/557] HelloCpp works. --- CMakeLists.txt | 27 ++++++-------- build/BuildHelpers.CMakeLists.txt | 37 ++++++++++++++++++++ cocos/2d/platform/linux/CCFileUtilsLinux.cpp | 2 +- samples/CMakeLists.txt | 4 +++ samples/Cpp/HelloCpp/CMakeLists.txt | 10 ++++++ 5 files changed, 63 insertions(+), 17 deletions(-) create mode 100644 build/BuildHelpers.CMakeLists.txt create mode 100644 samples/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 512d1e916b..2e92c43ba0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,13 +5,16 @@ project (Cocos2dxSamples) set(Cocos2dxSamples_VERSION_MAJOR 3) set(Cocos2dxSamples_VERSION_MINOR 0) -add_definitions(-DLINUX) +include(build/BuildHelpers.CMakeLists.txt) -# debug -message( "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}" ) -if ( "${CMAKE_BUILD_TYPE}" STREQUAL "DEBUG" ) - add_definitions(-D_DEBUG) -endif() +set(CMAKE_BUILE_TYPE DEBUG) +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +add_definitions(-DLINUX) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -20,9 +23,6 @@ else() set(ARCH_DIR "32-bit") endif() -set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") - include_directories( cocos/2d cocos/2d/platform @@ -73,8 +73,6 @@ add_subdirectory(cocos/math/kazmath) # chipmunk library set(BUILD_STATIC 1) - -# chipmunk library add_subdirectory(external/chipmunk/src) # unzip library @@ -86,12 +84,9 @@ add_subdirectory(external/tinyxml2) # cocos base library add_subdirectory(cocos/base) -# cocos physics sources -#add_subdirectory(cocos/physics) - # cocos 2d library add_subdirectory(cocos/2d) -# sample HelloCpp -add_subdirectory(samples/Cpp/HelloCpp) +# build samples +add_subdirectory(samples) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt new file mode 100644 index 0000000000..c60446bd30 --- /dev/null +++ b/build/BuildHelpers.CMakeLists.txt @@ -0,0 +1,37 @@ + +# Copies files for the given game into the target res directory +# GAME_NAME name of the game +# REL_DIR to which directory these files are relative +# SRC_FILES which files from the REL_DIR to copy (GLOB) +macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES DST) + file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) + + set(ALL_FILES) + foreach(SRC_FILE ${RES_FILES}) + add_custom_command( + OUTPUT "${DST}/${SRC_FILE}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${REL_DIR}/${SRC_FILE}" + "${DST}/${SRC_FILE}" + COMMENT "Copy ${SRC_FILE}" + ) + list(APPEND ALL_FILES "${DST}/${SRC_FILE}" ) + endforeach() + # create target for copying these files + add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) +endmacro() + +# convenience to call above with current directory and everything in "res" +macro(COPY_RES GAME_NAME CRG_PATTERN DST) + # a target for all addition asserts (will be done in default compile, but if you target the executable + # it won't be done -- good for testing) + add_custom_target( ${GAME_NAME}_ASSETS ALL ) + + COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES + ${CMAKE_CURRENT_SOURCE_DIR} + "${CRG_PATTERN}" + ${DST} + ) + add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) +endmacro() + diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp index 227c59b0ba..dc3fb5b513 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp @@ -49,7 +49,7 @@ bool FileUtilsLinux::init() fullpath[length] = '\0'; std::string appPath = fullpath; _defaultResRootPath = appPath.substr(0, appPath.find_last_of("/")); - _defaultResRootPath += "/../../../Resources/"; + _defaultResRootPath += "/Resources/"; // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. const char* xdg_config_path = getenv("XDG_CONFIG_HOME"); diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt new file mode 100644 index 0000000000..d8f27098e1 --- /dev/null +++ b/samples/CMakeLists.txt @@ -0,0 +1,4 @@ + +add_subdirectory(Cpp/HelloCpp) +add_subdirectory(Cpp/TestCpp) + diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index f22b681d8f..6ac2ed3548 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -12,3 +12,13 @@ add_executable(${SAMPLE_NAME} ) target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) + +set(SAMPLE_BIN_DIR ${CMAKE_BINARY_DIR}/bin) + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}/HelloCpp") + +message(STATUS "Hello.........." ${CMAKE_BINARY_DIR}) + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}/HelloCpp") + From 922924e1aba1cf3fee57225e1d6e27a7db2b5a1a Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 18:07:34 +0800 Subject: [PATCH 379/557] TestCpp is ok. --- CMakeLists.txt | 29 ++- cocos/audio/CMakeLists.txt | 16 ++ .../cocosbuilder/CMakeLists.txt | 33 ++++ .../editor-support/cocostudio/CMakeLists.txt | 43 +++++ cocos/editor-support/spine/CMakeLists.txt | 31 ++++ cocos/gui/CMakeLists.txt | 29 +++ cocos/network/CMakeLists.txt | 8 + extensions/CMakeLists.txt | 34 ++++ external/Box2D/CMakeLists.txt | 55 ++++++ external/json/CMakeLists.txt | 14 ++ samples/CMakeLists.txt | 3 +- samples/Cpp/HelloCpp/CMakeLists.txt | 8 +- samples/Cpp/TestCpp/CMakeLists.txt | 165 ++++++++++++++++++ 13 files changed, 461 insertions(+), 7 deletions(-) create mode 100644 cocos/audio/CMakeLists.txt create mode 100644 cocos/editor-support/cocosbuilder/CMakeLists.txt create mode 100644 cocos/editor-support/cocostudio/CMakeLists.txt create mode 100644 cocos/editor-support/spine/CMakeLists.txt create mode 100644 cocos/gui/CMakeLists.txt create mode 100644 cocos/network/CMakeLists.txt create mode 100644 extensions/CMakeLists.txt create mode 100644 external/Box2D/CMakeLists.txt create mode 100644 external/json/CMakeLists.txt create mode 100644 samples/Cpp/TestCpp/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e92c43ba0..5c20488a6b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,7 @@ set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -add_definitions(-DLINUX) +add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -24,16 +24,22 @@ set(ARCH_DIR "32-bit") endif() include_directories( + . + cocos + cocos/audio/include cocos/2d cocos/2d/platform cocos/2d/platform/linux cocos/base cocos/physics + cocos/editor-support cocos/math/kazmath/include + external external/jpeg/include/linux external/tiff/include/linux external/webp/include/linux external/glfw3/include/linux + external/curl/include/linux/${ARCH_DIR} external/tinyxml2 external/unzip external/chipmunk/include/chipmunk @@ -46,9 +52,12 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/tiff/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/external/curl/prebuilt/linux/${ARCH_DIR} + ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib ) set(COCOS_LIBRARIES + audio cocos2d cocosbase chipmunk_static @@ -75,18 +84,36 @@ add_subdirectory(cocos/math/kazmath) set(BUILD_STATIC 1) add_subdirectory(external/chipmunk/src) +# box2d library +add_subdirectory(external/Box2D) + # unzip library add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) +# audio +add_subdirectory(cocos/audio) + # cocos base library add_subdirectory(cocos/base) # cocos 2d library add_subdirectory(cocos/2d) +add_subdirectory(cocos/gui) + +add_subdirectory(cocos/network) + +add_subdirectory(cocos/editor-support/spine) +add_subdirectory(cocos/editor-support/cocosbuilder) +add_subdirectory(cocos/editor-support/cocostudio) + +add_subdirectory(extensions) + +add_subdirectory(external/json) + # build samples add_subdirectory(samples) diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt new file mode 100644 index 0000000000..79f84aa217 --- /dev/null +++ b/cocos/audio/CMakeLists.txt @@ -0,0 +1,16 @@ +set(AUDIO_SRC + linux/SimpleAudioEngineFMOD.cpp + linux/FmodAudioPlayer.cpp +) + +include_directories( + third-party/fmod/lib64/api/inc +) + +add_library(audio STATIC + ${AUDIO_SRC} +) + +target_link_libraries(audio + fmodex64 +) \ No newline at end of file diff --git a/cocos/editor-support/cocosbuilder/CMakeLists.txt b/cocos/editor-support/cocosbuilder/CMakeLists.txt new file mode 100644 index 0000000000..57f1113de6 --- /dev/null +++ b/cocos/editor-support/cocosbuilder/CMakeLists.txt @@ -0,0 +1,33 @@ +set(CCB_SRC + CCBFileLoader.cpp + CCMenuItemImageLoader.cpp + CCBReader.cpp + CCMenuItemLoader.cpp + CCControlButtonLoader.cpp + CCNodeLoader.cpp + CCControlLoader.cpp + CCNodeLoaderLibrary.cpp + CCLabelBMFontLoader.cpp + CCParticleSystemQuadLoader.cpp + CCLabelTTFLoader.cpp + CCScale9SpriteLoader.cpp + CCLayerColorLoader.cpp + CCScrollViewLoader.cpp + CCLayerGradientLoader.cpp + CCSpriteLoader.cpp + CCLayerLoader.cpp + CCBAnimationManager.cpp + CCBKeyframe.cpp + CCBSequence.cpp + CCBSequenceProperty.cpp + CCBValue.cpp + CCNode+CCBRelativePositioning.cpp +) + +include_directories( + .. +) + +add_library(cocosbuilder STATIC + ${CCB_SRC} +) diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt new file mode 100644 index 0000000000..f86093b2ea --- /dev/null +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -0,0 +1,43 @@ +set(CS_SRC + CCActionFrame.cpp + CCActionFrameEasing.cpp + CCActionManagerEx.cpp + CCActionNode.cpp + CCActionObject.cpp + CCArmature.cpp + CCBone.cpp + CCArmatureAnimation.cpp + CCProcessBase.cpp + CCTween.cpp + CCDatas.cpp + CCBatchNode.cpp + CCDecorativeDisplay.cpp + CCDisplayFactory.cpp + CCDisplayManager.cpp + CCSkin.cpp + CCColliderDetector.cpp + CCArmatureDataManager.cpp + CCArmatureDefine.cpp + CCDataReaderHelper.cpp + CCSpriteFrameCacheHelper.cpp + CCTransformHelp.cpp + CCTweenFunction.cpp + CCUtilMath.cpp + CCComAttribute.cpp + CCComAudio.cpp + CCComController.cpp + CCComRender.cpp + CCInputDelegate.cpp + CSContentJsonDictionary.cpp + DictionaryHelper.cpp + CCSGUIReader.cpp + CCSSceneReader.cpp +) + +include_directories( + .. +) + +add_library(cocostudio STATIC + ${CS_SRC} +) diff --git a/cocos/editor-support/spine/CMakeLists.txt b/cocos/editor-support/spine/CMakeLists.txt new file mode 100644 index 0000000000..e76d1ea6f8 --- /dev/null +++ b/cocos/editor-support/spine/CMakeLists.txt @@ -0,0 +1,31 @@ +set(SPINE_SRC + Animation.cpp + AnimationState.cpp + AnimationStateData.cpp + Atlas.cpp + AtlasAttachmentLoader.cpp + Attachment.cpp + AttachmentLoader.cpp + Bone.cpp + BoneData.cpp + Json.cpp + RegionAttachment.cpp + Skeleton.cpp + SkeletonData.cpp + SkeletonJson.cpp + Skin.cpp + Slot.cpp + SlotData.cpp + extension.cpp + spine-cocos2dx.cpp + CCSkeleton.cpp + CCSkeletonAnimation.cpp +) + +include_directories( + .. +) + +add_library(spine STATIC + ${SPINE_SRC} +) diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt new file mode 100644 index 0000000000..069ce8a960 --- /dev/null +++ b/cocos/gui/CMakeLists.txt @@ -0,0 +1,29 @@ +set(GUI_SRC + UIRootWidget.cpp + UIWidget.cpp + Layout.cpp + LayoutParameter.cpp + UILayoutDefine.cpp + CocosGUI.cpp + UIHelper.cpp + UIInputManager.cpp + UILayer.cpp + UIDragPanel.cpp + UIListView.cpp + UIPageView.cpp + UIScrollView.cpp + UIButton.cpp + UICheckBox.cpp + UIImageView.cpp + UILabel.cpp + UILabelAtlas.cpp + UILabelBMFont.cpp + UILoadingBar.cpp + UISlider.cpp + UITextField.cpp +) + +add_library(gui STATIC + ${GUI_SRC} +) + diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt new file mode 100644 index 0000000000..8217122fa9 --- /dev/null +++ b/cocos/network/CMakeLists.txt @@ -0,0 +1,8 @@ +set(NETWORK_SRC + HttpClient.cpp + SocketIO.cpp +) + +add_library(network STATIC + ${NETWORK_SRC} +) diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt new file mode 100644 index 0000000000..5b85c4657b --- /dev/null +++ b/extensions/CMakeLists.txt @@ -0,0 +1,34 @@ +set(EXTENSIONS_SRC + assets-manager/AssetsManager.cpp + GUI/CCControlExtension/CCControl.cpp + GUI/CCControlExtension/CCControlButton.cpp + GUI/CCControlExtension/CCControlColourPicker.cpp + GUI/CCControlExtension/CCControlHuePicker.cpp + GUI/CCControlExtension/CCControlPotentiometer.cpp + GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp + GUI/CCControlExtension/CCControlSlider.cpp + GUI/CCControlExtension/CCControlStepper.cpp + GUI/CCControlExtension/CCControlSwitch.cpp + GUI/CCControlExtension/CCControlUtils.cpp + GUI/CCControlExtension/CCInvocation.cpp + GUI/CCControlExtension/CCScale9Sprite.cpp + GUI/CCEditBox/CCEditBox.cpp + GUI/CCEditBox/CCEditBoxImplAndroid.cpp + GUI/CCEditBox/CCEditBoxImplNone.cpp + GUI/CCEditBox/CCEditBoxImplTizen.cpp + GUI/CCEditBox/CCEditBoxImplWin.cpp + GUI/CCScrollView/CCScrollView.cpp + GUI/CCScrollView/CCSorting.cpp + GUI/CCScrollView/CCTableView.cpp + GUI/CCScrollView/CCTableViewCell.cpp + physics-nodes/CCPhysicsDebugNode.cpp + physics-nodes/CCPhysicsSprite.cpp +) + +include_directories( + .. +) + +add_library(extensions STATIC + ${EXTENSIONS_SRC} +) diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt new file mode 100644 index 0000000000..94a1fffb50 --- /dev/null +++ b/external/Box2D/CMakeLists.txt @@ -0,0 +1,55 @@ +set(BOX2D_SRC + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2PolygonShape.cpp + Collision/b2BroadPhase.cpp + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Distance.cpp + Collision/b2DynamicTree.cpp + Collision/b2TimeOfImpact.cpp + Common/b2BlockAllocator.cpp + Common/b2Draw.cpp + Common/b2Math.cpp + Common/b2Settings.cpp + Common/b2StackAllocator.cpp + Common/b2Timer.cpp + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2PolygonContact.cpp + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WheelJoint.cpp + Dynamics/b2Body.cpp + Dynamics/b2ContactManager.cpp + Dynamics/b2Fixture.cpp + Dynamics/b2Island.cpp + Dynamics/b2World.cpp + Dynamics/b2WorldCallbacks.cpp + Rope/b2Rope.cpp +) + +include_directories( + .. +) + +add_library(box2d STATIC + ${BOX2D_SRC} +) diff --git a/external/json/CMakeLists.txt b/external/json/CMakeLists.txt new file mode 100644 index 0000000000..257385a307 --- /dev/null +++ b/external/json/CMakeLists.txt @@ -0,0 +1,14 @@ +set(JSONCPP_SRC + json_reader.cpp + json_value.cpp + json_writer.cpp +) + +include_directories( + +) + +add_library(jsoncpp STATIC + ${JSONCPP_SRC} +) + diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index d8f27098e1..c3a9708207 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,4 +1,5 @@ -add_subdirectory(Cpp/HelloCpp) +#add_subdirectory(Cpp/HelloCpp) + add_subdirectory(Cpp/TestCpp) diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 6ac2ed3548..22770fff8e 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -13,12 +13,10 @@ add_executable(${SAMPLE_NAME} target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) -set(SAMPLE_BIN_DIR ${CMAKE_BINARY_DIR}/bin) +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}/HelloCpp") + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") -message(STATUS "Hello.........." ${CMAKE_BINARY_DIR}) - -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}/HelloCpp") +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt new file mode 100644 index 0000000000..c567f1331a --- /dev/null +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -0,0 +1,165 @@ +set(SAMPLE_NAME testcpp) + +set(SAMPLE_SRC + Classes/AccelerometerTest/AccelerometerTest.cpp + Classes/ActionManagerTest/ActionManagerTest.cpp + Classes/ActionsEaseTest/ActionsEaseTest.cpp + Classes/ActionsProgressTest/ActionsProgressTest.cpp + Classes/ActionsTest/ActionsTest.cpp + Classes/Box2DTest/Box2dTest.cpp + Classes/Box2DTestBed/Box2dView.cpp + Classes/Box2DTestBed/GLES-Render.cpp + Classes/Box2DTestBed/Test.cpp + Classes/Box2DTestBed/TestEntries.cpp + Classes/BugsTest/Bug-1159.cpp + Classes/BugsTest/Bug-1174.cpp + Classes/BugsTest/Bug-350.cpp + Classes/BugsTest/Bug-422.cpp + Classes/BugsTest/Bug-458/Bug-458.cpp + Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp + Classes/BugsTest/Bug-624.cpp + Classes/BugsTest/Bug-886.cpp + Classes/BugsTest/Bug-899.cpp + Classes/BugsTest/Bug-914.cpp + Classes/BugsTest/BugsTest.cpp + Classes/ChipmunkTest/ChipmunkTest.cpp + Classes/ClickAndMoveTest/ClickAndMoveTest.cpp + Classes/ClippingNodeTest/ClippingNodeTest.cpp + Classes/CocosDenshionTest/CocosDenshionTest.cpp + Classes/CurlTest/CurlTest.cpp + Classes/CurrentLanguageTest/CurrentLanguageTest.cpp + Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp + Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp + Classes/EffectsTest/EffectsTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp + Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp + Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp + Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp + Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp + Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp + Classes/ExtensionsTest/ExtensionsTest.cpp + Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp + Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp + Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp + Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp + Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UINodeContainerTest/UINodeContainerTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextAreaTest/UITextAreaTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextButtonTest/UITextButtonTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp + Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp + Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp + Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp + Classes/FontTest/FontTest.cpp + Classes/IntervalTest/IntervalTest.cpp + Classes/KeyboardTest/KeyboardTest.cpp + Classes/InputTest/MouseTest.cpp + Classes/KeypadTest/KeypadTest.cpp + Classes/LabelTest/LabelTest.cpp + Classes/LabelTest/LabelTestNew.cpp + Classes/LayerTest/LayerTest.cpp + Classes/MenuTest/MenuTest.cpp + Classes/MotionStreakTest/MotionStreakTest.cpp + Classes/MutiTouchTest/MutiTouchTest.cpp + Classes/NodeTest/NodeTest.cpp + Classes/ParallaxTest/ParallaxTest.cpp + Classes/ParticleTest/ParticleTest.cpp + Classes/PerformanceTest/PerformanceAllocTest.cpp + Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp + Classes/PerformanceTest/PerformanceParticleTest.cpp + Classes/PerformanceTest/PerformanceSpriteTest.cpp + Classes/PerformanceTest/PerformanceTest.cpp + Classes/PerformanceTest/PerformanceTextureTest.cpp + Classes/PerformanceTest/PerformanceTouchesTest.cpp + Classes/PhysicsTest/PhysicsTest.cpp + Classes/RenderTextureTest/RenderTextureTest.cpp + Classes/RotateWorldTest/RotateWorldTest.cpp + Classes/SceneTest/SceneTest.cpp + Classes/SchedulerTest/SchedulerTest.cpp + Classes/ShaderTest/ShaderTest.cpp + Classes/ShaderTest/ShaderTest2.cpp + Classes/SpriteTest/SpriteTest.cpp + Classes/TextInputTest/TextInputTest.cpp + Classes/Texture2dTest/Texture2dTest.cpp + Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp + Classes/TextureCacheTest/TextureCacheTest.cpp + Classes/TileMapTest/TileMapTest.cpp + Classes/TouchesTest/Ball.cpp + Classes/TouchesTest/Paddle.cpp + Classes/TouchesTest/TouchesTest.cpp + Classes/TransitionsTest/TransitionsTest.cpp + Classes/UserDefaultTest/UserDefaultTest.cpp + Classes/ZwoptexTest/ZwoptexTest.cpp + Classes/FileUtilsTest/FileUtilsTest.cpp + Classes/SpineTest/SpineTest.cpp + Classes/DataVisitorTest/DataVisitorTest.cpp + Classes/ConfigurationTest/ConfigurationTest.cpp + Classes/controller.cpp + Classes/testBasic.cpp + Classes/AppDelegate.cpp + Classes/BaseTest.cpp + Classes/VisibleRect.cpp + proj.linux/main.cpp +) + +include_directories( + Classes +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + gui + network + spine + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + box2d + jsoncpp + curl + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + From c085412636cca7db4d28ecc00238d554ab831d44 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 2 Nov 2013 19:14:29 +0800 Subject: [PATCH 380/557] [CMake] TestLua and HelloLua is ok. --- CMakeLists.txt | 6 +++++ cocos/scripting/CMakeLists.txt | 32 ++++++++++++++++++++++ external/lua/lua/CMakeLists.txt | 36 +++++++++++++++++++++++++ external/lua/tolua/CMakeLists.txt | 17 ++++++++++++ samples/CMakeLists.txt | 6 ++--- samples/Lua/HelloLua/CMakeLists.txt | 41 +++++++++++++++++++++++++++++ samples/Lua/TestLua/CMakeLists.txt | 41 +++++++++++++++++++++++++++++ 7 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 cocos/scripting/CMakeLists.txt create mode 100644 external/lua/lua/CMakeLists.txt create mode 100644 external/lua/tolua/CMakeLists.txt create mode 100644 samples/Lua/HelloLua/CMakeLists.txt create mode 100644 samples/Lua/TestLua/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 5c20488a6b..67dde5fa7f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,6 +34,7 @@ include_directories( cocos/physics cocos/editor-support cocos/math/kazmath/include + extensions external external/jpeg/include/linux external/tiff/include/linux @@ -114,6 +115,11 @@ add_subdirectory(extensions) add_subdirectory(external/json) +add_subdirectory(external/lua/lua) +add_subdirectory(external/lua/tolua) + +add_subdirectory(cocos/scripting) + # build samples add_subdirectory(samples) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt new file mode 100644 index 0000000000..5212c4bbef --- /dev/null +++ b/cocos/scripting/CMakeLists.txt @@ -0,0 +1,32 @@ +set(LUABINDING_SRC + auto-generated/lua-bindings/lua_cocos2dx_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp + lua/bindings/tolua_fix.c + lua/bindings/CCLuaBridge.cpp + lua/bindings/CCLuaEngine.cpp + lua/bindings/CCLuaStack.cpp + lua/bindings/CCLuaValue.cpp + lua/bindings/Cocos2dxLuaLoader.cpp + lua/bindings/CCBProxy.cpp + lua/bindings/LuaOpengl.cpp + lua/bindings/LuaScriptHandlerMgr.cpp + lua/bindings/LuaBasicConversions.cpp + lua/bindings/lua_cocos2dx_manual.cpp + lua/bindings/lua_cocos2dx_extension_manual.cpp + lua/bindings/lua_cocos2dx_deprecated.cpp + lua/bindings/lua_xml_http_request.cpp +) + +include_directories( + auto-generated/lua-bindings + lua/bindings + ../../cocos/editor-support/cocosbuilder + ../../cocos/editor-support/cocostudio + ../../external/lua/lua + ../../external/lua/tolua +) + + +add_library(luabinding STATIC + ${LUABINDING_SRC} +) diff --git a/external/lua/lua/CMakeLists.txt b/external/lua/lua/CMakeLists.txt new file mode 100644 index 0000000000..faba14e849 --- /dev/null +++ b/external/lua/lua/CMakeLists.txt @@ -0,0 +1,36 @@ +set(LUA_SRC + lapi.c + lauxlib.c + lbaselib.c + lcode.c + ldblib.c + ldebug.c + ldo.c + ldump.c + lfunc.c + lgc.c + linit.c + liolib.c + llex.c + lmathlib.c + lmem.c + loadlib.c + lobject.c + lopcodes.c + loslib.c + lparser.c + lstate.c + lstring.c + lstrlib.c + ltable.c + ltablib.c + ltm.c + lundump.c + lvm.c + lzio.c + print.c +) + +add_library(lua STATIC + ${LUA_SRC} +) \ No newline at end of file diff --git a/external/lua/tolua/CMakeLists.txt b/external/lua/tolua/CMakeLists.txt new file mode 100644 index 0000000000..481bdd1247 --- /dev/null +++ b/external/lua/tolua/CMakeLists.txt @@ -0,0 +1,17 @@ +set(TOLUA_SRC + tolua_event.c + tolua_is.c + tolua_map.c + tolua_push.c + tolua_to.c +) + +include_directories( + ../lua +) + + +add_library(tolua STATIC + ${TOLUA_SRC} +) + diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index c3a9708207..d73334ce7e 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,5 +1,5 @@ -#add_subdirectory(Cpp/HelloCpp) - +add_subdirectory(Cpp/HelloCpp) add_subdirectory(Cpp/TestCpp) - +add_subdirectory(Lua/HelloLua) +add_subdirectory(Lua/TestLua) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt new file mode 100644 index 0000000000..9c05dea1a9 --- /dev/null +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -0,0 +1,41 @@ +set(SAMPLE_NAME hellolua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + jsoncpp + curl + tolua + lua + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt new file mode 100644 index 0000000000..88f5ea0977 --- /dev/null +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -0,0 +1,41 @@ +set(SAMPLE_NAME testlua) + +set(SAMPLE_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +include_directories( + Classes + ../../../cocos/scripting/lua/bindings + ../../../external/lua/lua + ../../../external/lua/tolua +) + +# add the executable +add_executable(${SAMPLE_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${SAMPLE_NAME} + luabinding + gui + network + cocostudio + cocosbuilder + extensions + ${COCOS_LIBRARIES} + jsoncpp + curl + tolua + lua + rt +) + +set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") + +SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") + +COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") + From 59adba1a6d7160b0b9ae85c96e75f1e3b5b2b935 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 12:00:45 +0800 Subject: [PATCH 381/557] Updating physics/CMakeLists.txt --- cocos/physics/CMakeLists.txt | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt index 2ca5a7f532..1586db2379 100644 --- a/cocos/physics/CMakeLists.txt +++ b/cocos/physics/CMakeLists.txt @@ -1,17 +1,18 @@ set(COCOS_PHYSICS_SRC - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp + ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsBody.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsContact.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsShape.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsJoint.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/CCPhysicsWorld.cpp ) + From daa91ad41339fe4a79ca94e91052663f593719a2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:10:04 +0800 Subject: [PATCH 382/557] [CMake] Update library dependency. --- CMakeLists.txt | 28 +++---------------- cocos/2d/CMakeLists.txt | 19 ++++++++++++- .../editor-support/cocostudio/CMakeLists.txt | 4 +++ cocos/network/CMakeLists.txt | 4 +++ cocos/scripting/CMakeLists.txt | 5 ++++ samples/Cpp/HelloCpp/CMakeLists.txt | 2 +- samples/Cpp/TestCpp/CMakeLists.txt | 6 ++-- samples/Lua/HelloLua/CMakeLists.txt | 8 ++---- samples/Lua/TestLua/CMakeLists.txt | 8 ++---- 9 files changed, 42 insertions(+), 42 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 67dde5fa7f..4b7d98403d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,27 +57,6 @@ link_directories( ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib ) -set(COCOS_LIBRARIES - audio - cocos2d - cocosbase - chipmunk_static - tinyxml2 - kazmath - unzip - jpeg - webp - tiff - freetype - fontconfig - png - glfw - GLEW - GL - rt - z -) - # kazmath add_subdirectory(cocos/math/kazmath) @@ -94,6 +73,8 @@ add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) +add_subdirectory(external/json) + # audio add_subdirectory(cocos/audio) @@ -107,13 +88,12 @@ add_subdirectory(cocos/gui) add_subdirectory(cocos/network) +add_subdirectory(extensions) + add_subdirectory(cocos/editor-support/spine) add_subdirectory(cocos/editor-support/cocosbuilder) add_subdirectory(cocos/editor-support/cocostudio) -add_subdirectory(extensions) - -add_subdirectory(external/json) add_subdirectory(external/lua/lua) add_subdirectory(external/lua/tolua) diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index fdcd28a564..1e66ba9cb4 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -122,4 +122,21 @@ add_library(cocos2d STATIC ${COCOS2D_SRC} ${COCOS_PHYSICS_SRC} ) - +target_link_libraries(cocos2d + cocosbase + chipmunk_static + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + glfw + GLEW + GL + rt + z +) diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt index f86093b2ea..8aa09558d9 100644 --- a/cocos/editor-support/cocostudio/CMakeLists.txt +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -41,3 +41,7 @@ include_directories( add_library(cocostudio STATIC ${CS_SRC} ) + +target_link_libraries(cocostudio + jsoncpp +) diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 8217122fa9..1b001c6210 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -6,3 +6,7 @@ set(NETWORK_SRC add_library(network STATIC ${NETWORK_SRC} ) + +target_link_libraries(network + curl +) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index 5212c4bbef..bee2a84fe8 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -30,3 +30,8 @@ include_directories( add_library(luabinding STATIC ${LUABINDING_SRC} ) + +target_link_libraries(luabinding + tolua + lua +) diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 22770fff8e..e8ee537a78 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -11,7 +11,7 @@ add_executable(${SAMPLE_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} ${COCOS_LIBRARIES}) +target_link_libraries(${SAMPLE_NAME} audio cocos2d) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index c567f1331a..d6c921f1d5 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -149,11 +149,9 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} + audio + cocos2d box2d - jsoncpp - curl - rt ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index 9c05dea1a9..e1e41b7867 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -24,12 +24,8 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} - jsoncpp - curl - tolua - lua - rt + audio + cocos2d ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index 88f5ea0977..fb2225945d 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -24,12 +24,8 @@ target_link_libraries(${SAMPLE_NAME} cocostudio cocosbuilder extensions - ${COCOS_LIBRARIES} - jsoncpp - curl - tolua - lua - rt + audio + cocos2d ) set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") From f17aa8b4500fe96bb4b5de54f87867447b6c2639 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 13:53:30 +0800 Subject: [PATCH 383/557] Move the library of fmod to external folder. --- CMakeLists.txt | 3 +- cocos/audio/CMakeLists.txt | 4 - cocos/audio/third-party/fmod/Makefile | 81 ------------------- cocos/audio/third-party/fmod/lib64/Makefile | 65 --------------- .../include/32-bit}/fmod.h.REMOVED.git-id | 0 .../fmod/include/32-bit}/fmod.hpp | 0 .../fmod/include/32-bit}/fmod_codec.h | 0 .../fmod/include/32-bit}/fmod_dsp.h | 0 .../fmod/include/32-bit}/fmod_errors.h | 0 .../fmod/include/32-bit}/fmod_memoryinfo.h | 0 .../fmod/include/32-bit}/fmod_output.h | 0 .../fmod/include/32-bit}/fmodlinux.h | 0 .../include/64-bit}/fmod.h.REMOVED.git-id | 0 .../fmod/include/64-bit}/fmod.hpp | 0 .../fmod/include/64-bit}/fmod_codec.h | 0 .../fmod/include/64-bit}/fmod_dsp.h | 0 .../fmod/include/64-bit}/fmod_errors.h | 0 .../fmod/include/64-bit}/fmod_memoryinfo.h | 0 .../fmod/include/64-bit}/fmod_output.h | 0 .../fmod/include/64-bit}/fmodlinux.h | 0 .../libfmodex-4.36.01.so.REMOVED.git-id | 0 .../32-bit}/libfmodex.so.REMOVED.git-id | 0 .../libfmodexL-4.36.01.so.REMOVED.git-id | 0 .../32-bit}/libfmodexL.so.REMOVED.git-id | 0 .../libfmodex64-4.38.00.so.REMOVED.git-id | 0 .../64-bit}/libfmodex64.so.REMOVED.git-id | 0 .../libfmodexL64-4.38.00.so.REMOVED.git-id | 0 .../64-bit}/libfmodexL64.so.REMOVED.git-id | 0 28 files changed, 2 insertions(+), 151 deletions(-) delete mode 100644 cocos/audio/third-party/fmod/Makefile delete mode 100644 cocos/audio/third-party/fmod/lib64/Makefile rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod.h.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod.hpp (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_codec.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_dsp.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_errors.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_memoryinfo.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmod_output.h (100%) rename {cocos/audio/third-party/fmod/api/inc => external/linux-specific/fmod/include/32-bit}/fmodlinux.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod.h.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod.hpp (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_codec.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_dsp.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_errors.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_memoryinfo.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmod_output.h (100%) rename {cocos/audio/third-party/fmod/lib64/api/inc => external/linux-specific/fmod/include/64-bit}/fmodlinux.h (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodex-4.36.01.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodex.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodexL-4.36.01.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/api/lib => external/linux-specific/fmod/prebuilt/32-bit}/libfmodexL.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodex64-4.38.00.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodex64.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodexL64-4.38.00.so.REMOVED.git-id (100%) rename {cocos/audio/third-party/fmod/lib64/api/lib => external/linux-specific/fmod/prebuilt/64-bit}/libfmodexL64.so.REMOVED.git-id (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b7d98403d..7f93de1683 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,6 +45,7 @@ include_directories( external/unzip external/chipmunk/include/chipmunk external/freetype2/include/linux + external/linux-specific/fmod/include/${ARCH_DIR} ) link_directories( @@ -54,7 +55,7 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/webp/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/freetype2/prebuilt/linux/${ARCH_DIR} ${CMAKE_SOURCE_DIR}/external/curl/prebuilt/linux/${ARCH_DIR} - ${CMAKE_SOURCE_DIR}/cocos/audio/third-party/fmod/lib64/api/lib + ${CMAKE_SOURCE_DIR}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) # kazmath diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 79f84aa217..4f56e9b44b 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -3,10 +3,6 @@ set(AUDIO_SRC linux/FmodAudioPlayer.cpp ) -include_directories( - third-party/fmod/lib64/api/inc -) - add_library(audio STATIC ${AUDIO_SRC} ) diff --git a/cocos/audio/third-party/fmod/Makefile b/cocos/audio/third-party/fmod/Makefile deleted file mode 100644 index ef3df253c6..0000000000 --- a/cocos/audio/third-party/fmod/Makefile +++ /dev/null @@ -1,81 +0,0 @@ -LBITS := $(shell getconf LONG_BIT) -ifeq ($(LBITS),64) -FMODEX = libfmodex64 -FMODEXL = libfmodexL64 -VERSION = 4.38.00 -LIBDIR = lib64/api/lib -HDRDIR = lib64/api/inc -else -FMODEX = libfmodex -FMODEXL = libfmodexL -VERSION = 4.36.01 -LIBDIR = api/lib -HDRDIR = api/inc -endif - -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR} - ln -s -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so ${DESTLIBDIR}/${FMODEX}.so - ln -s -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so ${DESTLIBDIR}/${FMODEXL}.so - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/${FMODEX}.so - rm -f ${DESTLIBDIR}/${FMODEXL}.so - rm -f ${DESTLIBDIR}/${FMODEX}-${VERSION}.so - rm -f ${DESTLIBDIR}/${FMODEXL}-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/audio/third-party/fmod/lib64/Makefile b/cocos/audio/third-party/fmod/lib64/Makefile deleted file mode 100644 index c461587728..0000000000 --- a/cocos/audio/third-party/fmod/lib64/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -VERSION = 4.38.00 -LIBDIR = api/lib -HDRDIR = api/inc -DESTLIBDIR = /usr/local/lib -DESTHDRDIR = /usr/local/include/fmodex - -all: - @echo "Possible targets:" - @echo "'make fmod_examples' - Build all examples" - @echo "'make install' - Install FMOD Ex libraries and headers" - @echo "'make uninstall' - Uninstall FMOD Ex libraries and headers" - -fmod_examples: - cd examples/3d && make - cd examples/cdplayer && make - cd examples/channelgroups && make - cd examples/dsp_effectperspeaker && make - cd examples/dsp_custom && make - cd examples/effects && make - cd examples/filecallbacks && make - cd examples/generatetone && make - cd examples/loadfrommemory && make - cd examples/multiplesoundcard && make - cd examples/multispeakeroutput && make - cd examples/netstream && make - cd examples/offlinedecoding && make - cd examples/pitchdetection && make - cd examples/playlist && make - cd examples/playsound && make - cd examples/playstream && make - cd examples/plugin_dev/codec_raw && make - cd examples/plugin_dev/dsp_gain && make - cd examples/readtags && make - cd examples/realtimestitching && make - cd examples/recording && make - cd examples/recordtodisk && make - cd examples/ripnetstream && make - cd examples/submixing && make - cd examples/useplugins && make - cd examples/usercreatedsound && make - cd fmoddesignerapi/examples/effects && make - cd fmoddesignerapi/examples/info_only && make - cd fmoddesignerapi/examples/load_data && make - cd fmoddesignerapi/examples/max_playbacks && make - cd fmoddesignerapi/examples/parameters && make - cd fmoddesignerapi/examples/programmer_selected && make - cd fmoddesignerapi/examples/programmer_sound && make - cd fmoddesignerapi/examples/simple_event && make - -install: - @echo "Installing FMOD Ex libraries and headers..." - cp -f ${LIBDIR}/libfmodex64-${VERSION}.so ${DESTLIBDIR} - cp -f ${LIBDIR}/libfmodexL64-${VERSION}.so ${DESTLIBDIR} - ldconfig -n ${DESTLIBDIR} - mkdir -p ${DESTHDRDIR} - cp -f ${HDRDIR}/*.h* ${DESTHDRDIR} - @echo "done." - -uninstall: - @echo "Uninstalling FMOD Ex libraries..." - rm -f ${DESTLIBDIR}/libfmodex64-${VERSION}.so - rm -f ${DESTLIBDIR}/libfmodexL64-${VERSION}.so - ldconfig -n ${DESTLIBDIR} - rm -rf ${DESTHDRDIR} - @echo "done." diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/32-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/inc/fmod.hpp b/external/linux-specific/fmod/include/32-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/32-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/32-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/32-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/32-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/32-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/32-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/32-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/32-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmod_output.h b/external/linux-specific/fmod/include/32-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/32-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/32-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/32-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id b/external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.h.REMOVED.git-id rename to external/linux-specific/fmod/include/64-bit/fmod.h.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp b/external/linux-specific/fmod/include/64-bit/fmod.hpp similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod.hpp rename to external/linux-specific/fmod/include/64-bit/fmod.hpp diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h b/external/linux-specific/fmod/include/64-bit/fmod_codec.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_codec.h rename to external/linux-specific/fmod/include/64-bit/fmod_codec.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h b/external/linux-specific/fmod/include/64-bit/fmod_dsp.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_dsp.h rename to external/linux-specific/fmod/include/64-bit/fmod_dsp.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h b/external/linux-specific/fmod/include/64-bit/fmod_errors.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_errors.h rename to external/linux-specific/fmod/include/64-bit/fmod_errors.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h b/external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_memoryinfo.h rename to external/linux-specific/fmod/include/64-bit/fmod_memoryinfo.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h b/external/linux-specific/fmod/include/64-bit/fmod_output.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmod_output.h rename to external/linux-specific/fmod/include/64-bit/fmod_output.h diff --git a/cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h b/external/linux-specific/fmod/include/64-bit/fmodlinux.h similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/inc/fmodlinux.h rename to external/linux-specific/fmod/include/64-bit/fmodlinux.h diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodex.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodex.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL-4.36.01.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL-4.36.01.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/api/lib/libfmodexL.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/32-bit/libfmodexL.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodex64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodex64.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64-4.38.00.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64-4.38.00.so.REMOVED.git-id diff --git a/cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id b/external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id similarity index 100% rename from cocos/audio/third-party/fmod/lib64/api/lib/libfmodexL64.so.REMOVED.git-id rename to external/linux-specific/fmod/prebuilt/64-bit/libfmodexL64.so.REMOVED.git-id From 9be8ca371462ecfde174886c1260432c6539c139 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 14:49:42 +0800 Subject: [PATCH 384/557] [cmake] output lib to root/lib --- CMakeLists.txt | 1 - cocos/2d/CMakeLists.txt | 7 +++++++ cocos/audio/CMakeLists.txt | 9 ++++++++- cocos/base/CMakeLists.txt | 7 +++++++ cocos/editor-support/cocosbuilder/CMakeLists.txt | 7 +++++++ cocos/editor-support/cocostudio/CMakeLists.txt | 7 +++++++ cocos/editor-support/spine/CMakeLists.txt | 7 +++++++ cocos/gui/CMakeLists.txt | 5 +++++ cocos/math/kazmath/CMakeLists.txt | 8 +++++++- cocos/network/CMakeLists.txt | 7 +++++++ extensions/CMakeLists.txt | 7 +++++++ external/chipmunk/src/CMakeLists.txt | 9 +++++++++ external/json/CMakeLists.txt | 8 +++++++- external/tinyxml2/CMakeLists.txt | 7 +++++++ external/unzip/CMakeLists.txt | 7 +++++++ samples/Cpp/HelloCpp/CMakeLists.txt | 4 ++-- samples/Cpp/TestCpp/CMakeLists.txt | 4 ++-- samples/Lua/HelloLua/CMakeLists.txt | 4 ++-- samples/Lua/TestLua/CMakeLists.txt | 8 +++++--- 19 files changed, 110 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f93de1683..e07f618e27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,7 +62,6 @@ link_directories( add_subdirectory(cocos/math/kazmath) # chipmunk library -set(BUILD_STATIC 1) add_subdirectory(external/chipmunk/src) # box2d library diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 1e66ba9cb4..f147d233b6 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -140,3 +140,10 @@ target_link_libraries(cocos2d rt z ) + +set_target_properties(cocos2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 4f56e9b44b..9e88293ddd 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -9,4 +9,11 @@ add_library(audio STATIC target_link_libraries(audio fmodex64 -) \ No newline at end of file +) + +set_target_properties(audio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index c46e07c114..3d37d21a2f 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -18,3 +18,10 @@ set(COCOS_BASE_SRC add_library(cocosbase STATIC ${COCOS_BASE_SRC} ) + +set_target_properties(cocosbase + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocosbuilder/CMakeLists.txt b/cocos/editor-support/cocosbuilder/CMakeLists.txt index 57f1113de6..00763e1fb7 100644 --- a/cocos/editor-support/cocosbuilder/CMakeLists.txt +++ b/cocos/editor-support/cocosbuilder/CMakeLists.txt @@ -31,3 +31,10 @@ include_directories( add_library(cocosbuilder STATIC ${CCB_SRC} ) + +set_target_properties(cocosbuilder + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/cocostudio/CMakeLists.txt b/cocos/editor-support/cocostudio/CMakeLists.txt index 8aa09558d9..acff17a4a9 100644 --- a/cocos/editor-support/cocostudio/CMakeLists.txt +++ b/cocos/editor-support/cocostudio/CMakeLists.txt @@ -45,3 +45,10 @@ add_library(cocostudio STATIC target_link_libraries(cocostudio jsoncpp ) + +set_target_properties(cocostudio + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/editor-support/spine/CMakeLists.txt b/cocos/editor-support/spine/CMakeLists.txt index e76d1ea6f8..0d6664b98d 100644 --- a/cocos/editor-support/spine/CMakeLists.txt +++ b/cocos/editor-support/spine/CMakeLists.txt @@ -29,3 +29,10 @@ include_directories( add_library(spine STATIC ${SPINE_SRC} ) + +set_target_properties(spine + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt index 069ce8a960..916e5cf0f2 100644 --- a/cocos/gui/CMakeLists.txt +++ b/cocos/gui/CMakeLists.txt @@ -27,3 +27,8 @@ add_library(gui STATIC ${GUI_SRC} ) +set_target_properties(gui + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/math/kazmath/CMakeLists.txt b/cocos/math/kazmath/CMakeLists.txt index 1dc636037d..208b4a97c2 100644 --- a/cocos/math/kazmath/CMakeLists.txt +++ b/cocos/math/kazmath/CMakeLists.txt @@ -14,4 +14,10 @@ SET(KAZMATH_SOURCES ${CMAKE_SOURCE_DIR}/cocos/math/kazmath/src/GL/matrix.c ) -ADD_SUBDIRECTORY(src) \ No newline at end of file +ADD_SUBDIRECTORY(src) + +set_target_properties(kazmath + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 1b001c6210..3bd130111b 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -10,3 +10,10 @@ add_library(network STATIC target_link_libraries(network curl ) + +set_target_properties(network + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index 5b85c4657b..176cd831ce 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -32,3 +32,10 @@ include_directories( add_library(extensions STATIC ${EXTENSIONS_SRC} ) + +set_target_properties(extensions + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/chipmunk/src/CMakeLists.txt b/external/chipmunk/src/CMakeLists.txt index 6f10d0177d..a0d15b7b8a 100644 --- a/external/chipmunk/src/CMakeLists.txt +++ b/external/chipmunk/src/CMakeLists.txt @@ -1,3 +1,5 @@ +set(BUILD_STATIC 1) + file(GLOB chipmunk_source_files "*.c" "constraints/*.c") file(GLOB chipmunk_public_header "${chipmunk_SOURCE_DIR}/include/chipmunk/*.h") file(GLOB chipmunk_constraint_header "${chipmunk_SOURCE_DIR}/include/chipmunk/constraints/*.h") @@ -39,3 +41,10 @@ if(BUILD_SHARED OR INSTALL_STATIC) install(FILES ${chipmunk_public_header} DESTINATION include/chipmunk) install(FILES ${chipmunk_constraint_header} DESTINATION include/chipmunk/constraints) endif(BUILD_SHARED OR INSTALL_STATIC) + +set_target_properties(chipmunk_static + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/json/CMakeLists.txt b/external/json/CMakeLists.txt index 257385a307..87018744ef 100644 --- a/external/json/CMakeLists.txt +++ b/external/json/CMakeLists.txt @@ -1,6 +1,6 @@ set(JSONCPP_SRC json_reader.cpp - json_value.cpp + json_value.cpp json_writer.cpp ) @@ -12,3 +12,9 @@ add_library(jsoncpp STATIC ${JSONCPP_SRC} ) +set_target_properties(jsoncpp + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/tinyxml2/CMakeLists.txt b/external/tinyxml2/CMakeLists.txt index 42822a3bc4..6877779b2c 100644 --- a/external/tinyxml2/CMakeLists.txt +++ b/external/tinyxml2/CMakeLists.txt @@ -5,3 +5,10 @@ set(TINYXML2_SRC add_library(tinyxml2 STATIC ${TINYXML2_SRC} ) + +set_target_properties(tinyxml2 + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/external/unzip/CMakeLists.txt b/external/unzip/CMakeLists.txt index 8d15111c8e..ae98584279 100644 --- a/external/unzip/CMakeLists.txt +++ b/external/unzip/CMakeLists.txt @@ -6,3 +6,10 @@ set(UNZIP_SRC add_library(unzip STATIC ${UNZIP_SRC} ) + +set_target_properties(unzip + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) + diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index e8ee537a78..646a1574ab 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -13,9 +13,9 @@ add_executable(${SAMPLE_NAME} target_link_libraries(${SAMPLE_NAME} audio cocos2d) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index d6c921f1d5..0547ee04b1 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -154,9 +154,9 @@ target_link_libraries(${SAMPLE_NAME} box2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index e1e41b7867..81b1fa4357 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -28,9 +28,9 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index fb2225945d..cb37076c59 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -28,10 +28,12 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${SAMPLE_NAME}") +set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") -SET_TARGET_PROPERTIES(${SAMPLE_NAME} PROPERTIES +set_target_properties(${SAMPLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES(${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES_EXTRA(${SAMPLE_NAME} "${CMAKE_SOURCE_DIR}/samples/TestCpp/Resources/*") +# "${SAMPLE_BIN_DIR}") From 733197fa6518cdbd4eb7f8a818628798bcecdf3a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:48:36 +0800 Subject: [PATCH 385/557] [cmake] copy resources works. --- build/BuildHelpers.CMakeLists.txt | 44 ++++++++++++++++++++--------- samples/Cpp/HelloCpp/CMakeLists.txt | 14 ++++----- samples/Cpp/TestCpp/CMakeLists.txt | 14 ++++----- samples/Lua/HelloLua/CMakeLists.txt | 17 ++++++----- samples/Lua/TestLua/CMakeLists.txt | 22 +++++++++------ 5 files changed, 67 insertions(+), 44 deletions(-) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt index c60446bd30..92d537dd7d 100644 --- a/build/BuildHelpers.CMakeLists.txt +++ b/build/BuildHelpers.CMakeLists.txt @@ -1,37 +1,53 @@ - +# This file was copied from GamePlay # Copies files for the given game into the target res directory # GAME_NAME name of the game # REL_DIR to which directory these files are relative # SRC_FILES which files from the REL_DIR to copy (GLOB) -macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES DST) +macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES) file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) - + set(ALL_FILES) foreach(SRC_FILE ${RES_FILES}) - add_custom_command( - OUTPUT "${DST}/${SRC_FILE}" - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${REL_DIR}/${SRC_FILE}" - "${DST}/${SRC_FILE}" - COMMENT "Copy ${SRC_FILE}" - ) - list(APPEND ALL_FILES "${DST}/${SRC_FILE}" ) + IF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) + add_custom_command( + OUTPUT "${APP_BIN_DIR}/${SRC_FILE}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${REL_DIR}/${SRC_FILE}" + "${APP_BIN_DIR}/Resources/${SRC_FILE}" + COMMENT "Copy ${SRC_FILE}" + ) + list(APPEND ALL_FILES "${APP_BIN_DIR}/${SRC_FILE}" ) + ENDIF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) endforeach() # create target for copying these files add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) endmacro() # convenience to call above with current directory and everything in "res" -macro(COPY_RES GAME_NAME CRG_PATTERN DST) +macro(COPY_RES GAME_NAME) # a target for all addition asserts (will be done in default compile, but if you target the executable # it won't be done -- good for testing) add_custom_target( ${GAME_NAME}_ASSETS ALL ) + # copy entire "res" directory and "game.config" if there is one + set(CRG_PATTERN "*") COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES - ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Resources "${CRG_PATTERN}" - ${DST} ) add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) endmacro() +# Copies resources from an additional directory +# GAME_NAME name of the game +# REL_DIR from which directory +# ARGN which patterns to copy (should include res/ in name if to be placed in the res/ output) +macro(COPY_RES_EXTRA GAME_NAME EXTRA_RES REL_DIR) + # convert src's to full paths (based on rel_dir) + set(SRC_FILES) + foreach(SRC_FILE ${ARGN} ) + list(APPEND SRC_FILES "${REL_DIR}/${SRC_FILE}") + endforeach() + COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_${EXTRA_RES} ${REL_DIR} "${SRC_FILES}" ) + add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_${EXTRA_RES} ) +endmacro() diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index 646a1574ab..b335cf89fc 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME hellocpp) +set(APP_NAME hellocpp) set(SAMPLE_SRC proj.linux/main.cpp @@ -7,16 +7,16 @@ set(SAMPLE_SRC ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} audio cocos2d) +target_link_libraries(${APP_NAME} audio cocos2d) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 0547ee04b1..a4237425f9 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME testcpp) +set(APP_NAME testcpp) set(SAMPLE_SRC Classes/AccelerometerTest/AccelerometerTest.cpp @@ -138,11 +138,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} gui network spine @@ -154,10 +154,10 @@ target_link_libraries(${SAMPLE_NAME} box2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index 81b1fa4357..c048fae5c0 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME hellolua) +set(APP_NAME hellolua) set(SAMPLE_SRC proj.linux/main.cpp @@ -13,11 +13,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} luabinding gui network @@ -28,10 +28,13 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") +COPY_RES( ${APP_NAME} ) +COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua + script/* + ) diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index cb37076c59..dc81be8941 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -1,4 +1,4 @@ -set(SAMPLE_NAME testlua) +set(APP_NAME testlua) set(SAMPLE_SRC proj.linux/main.cpp @@ -13,11 +13,11 @@ include_directories( ) # add the executable -add_executable(${SAMPLE_NAME} +add_executable(${APP_NAME} ${SAMPLE_SRC} ) -target_link_libraries(${SAMPLE_NAME} +target_link_libraries(${APP_NAME} luabinding gui network @@ -28,12 +28,16 @@ target_link_libraries(${SAMPLE_NAME} cocos2d ) -set(SAMPLE_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${SAMPLE_NAME}") +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") -set_target_properties(${SAMPLE_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${SAMPLE_BIN_DIR}") +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES(${SAMPLE_NAME} "Resources/*" "${SAMPLE_BIN_DIR}") -COPY_RES_EXTRA(${SAMPLE_NAME} "${CMAKE_SOURCE_DIR}/samples/TestCpp/Resources/*") -# "${SAMPLE_BIN_DIR}") +COPY_RES(${APP_NAME}) +COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua + script/* + ) +COPY_RES_EXTRA(${APP_NAME} copy_cpp_res ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources + * + ) From edb1fc7822c24ce68c916547aef09e59551749f5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:48:59 +0800 Subject: [PATCH 386/557] [cmake] Deletes .icf files. --- samples/Cpp/HelloCpp/Resources/app.icf | 17 --- .../Cpp/HelloCpp/Resources/development.icf | 107 ------------------ samples/Cpp/SimpleGame/Resources/app.icf | 20 ---- .../Cpp/SimpleGame/Resources/development.icf | 107 ------------------ samples/Cpp/SimpleGame/Resources/sd/app.icf | 26 ----- samples/Cpp/TestCpp/Resources/app.icf | 26 ----- samples/Cpp/TestCpp/Resources/development.icf | 107 ------------------ samples/Lua/HelloLua/Resources/app.icf | 23 ---- .../Lua/HelloLua/Resources/development.icf | 107 ------------------ samples/Lua/TestLua/Resources/app.icf | 26 ----- samples/Lua/TestLua/Resources/development.icf | 107 ------------------ 11 files changed, 673 deletions(-) delete mode 100644 samples/Cpp/HelloCpp/Resources/app.icf delete mode 100644 samples/Cpp/HelloCpp/Resources/development.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/app.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/development.icf delete mode 100644 samples/Cpp/SimpleGame/Resources/sd/app.icf delete mode 100644 samples/Cpp/TestCpp/Resources/app.icf delete mode 100644 samples/Cpp/TestCpp/Resources/development.icf delete mode 100644 samples/Lua/HelloLua/Resources/app.icf delete mode 100644 samples/Lua/HelloLua/Resources/development.icf delete mode 100644 samples/Lua/TestLua/Resources/app.icf delete mode 100644 samples/Lua/TestLua/Resources/development.icf diff --git a/samples/Cpp/HelloCpp/Resources/app.icf b/samples/Cpp/HelloCpp/Resources/app.icf deleted file mode 100644 index 74755b2099..0000000000 --- a/samples/Cpp/HelloCpp/Resources/app.icf +++ /dev/null @@ -1,17 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. diff --git a/samples/Cpp/HelloCpp/Resources/development.icf b/samples/Cpp/HelloCpp/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Cpp/HelloCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/SimpleGame/Resources/app.icf b/samples/Cpp/SimpleGame/Resources/app.icf deleted file mode 100644 index 1ae216d665..0000000000 --- a/samples/Cpp/SimpleGame/Resources/app.icf +++ /dev/null @@ -1,20 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. - -[S3E] -DispFixRot=Landscape \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/Resources/development.icf b/samples/Cpp/SimpleGame/Resources/development.icf deleted file mode 100644 index c9d1b773f1..0000000000 --- a/samples/Cpp/SimpleGame/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "640" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "960" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Cpp/SimpleGame/Resources/sd/app.icf b/samples/Cpp/SimpleGame/Resources/sd/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Cpp/SimpleGame/Resources/sd/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/TestCpp/Resources/app.icf b/samples/Cpp/TestCpp/Resources/app.icf deleted file mode 100644 index 7fdabcd1f2..0000000000 --- a/samples/Cpp/TestCpp/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 100000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Cpp/TestCpp/Resources/development.icf b/samples/Cpp/TestCpp/Resources/development.icf deleted file mode 100644 index 363d486f04..0000000000 --- a/samples/Cpp/TestCpp/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "Samsung Galaxy S" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "ANDROID" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "NONE:OSX:480x320" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "ANDROID" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "false" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "800" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot90" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/HelloLua/Resources/app.icf b/samples/Lua/HelloLua/Resources/app.icf deleted file mode 100644 index dec7c07959..0000000000 --- a/samples/Lua/HelloLua/Resources/app.icf +++ /dev/null @@ -1,23 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/HelloLua/Resources/development.icf b/samples/Lua/HelloLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/HelloLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" diff --git a/samples/Lua/TestLua/Resources/app.icf b/samples/Lua/TestLua/Resources/app.icf deleted file mode 100644 index dbc72b4d77..0000000000 --- a/samples/Lua/TestLua/Resources/app.icf +++ /dev/null @@ -1,26 +0,0 @@ -# This file is for configuration settings for your -# application. -# -# The syntax is similar to windows .ini files ie -# -# [GroupName] -# Setting = Value -# -# Which can be read by your application using -# e.g s3eConfigGetString("GroupName", "Setting", string) -# -# All settings must be documented in .config.txt files. -# New settings specific to this application should be -# documented in app.config.txt -# -# Some conditional operations are also permitted, see the -# S3E documentation for details. -[S3E] -MemSize = 10000000 -# Sample only compatible with 480x320 display resolution -WinWidth=480 -WinHeight=320 - -[GL] -AllowNegativeUniformLocation=1 - diff --git a/samples/Lua/TestLua/Resources/development.icf b/samples/Lua/TestLua/Resources/development.icf deleted file mode 100644 index 09e69865f0..0000000000 --- a/samples/Lua/TestLua/Resources/development.icf +++ /dev/null @@ -1,107 +0,0 @@ -# Settings ICF file automatically generated by S3E development environment - -AccelEnabled = Type=bool, Default="true", Value = "true" -AudioAAC = Type=bool, Default="false", Value = "false" -AudioAACPlus = Type=bool, Default="false", Value = "false" -AudioMIDI = Type=bool, Default="true", Value = "true" -AudioMP3 = Type=bool, Default="true", Value = "true" -AudioPCM = Type=bool, Default="true", Value = "true" -AudioQCP = Type=bool, Default="false", Value = "false" -AudioVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -BacklightTimeout = Type=int, Min=0.000000, Max=120000.000000, Default="10000", Value = "10000" -CompassEnabled = Type=bool, Default="true", Value = "true" -ContactsFromAddrBook = Type=bool, Default="false", Value = "false" -DeviceAdvanceSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Left", Value = "Bottom Left" -DeviceArch = Type=string, Allowed="" "ARM4T" "ARM4" "ARM5T" "ARM5TE" "ARM5TEJ" "ARM6" "ARM6K" "ARM6T2" "ARM6Z" "X86" "PPC" "AMD64" "ARM7", Default="", Value = "" -DeviceBackSoftkeyPosition = Type=string, Allowed="Bottom Left" "Bottom Right" "Top Right" "Top Left", Default="Bottom Right", Value = "Bottom Right" -DeviceBatteryLevel = Type=int, Min=0.000000, Max=100.000000, Default="50", Value = "50" -DeviceClass = Type=string, Allowed="UNKNOWN" "SYMBIAN_GENERIC" "SYMBIAN_SERIES60" "SYMBIAN_SERIES60_EMULATOR" "SYMBIAN_UIQ" "SYMBIAN_UIQ_EMULATOR" "BREW_GENERIC" "BREW_QCIF_3D" "BREW_QCIF_25G" "BREW_SQCIF_256" "BREW_QVGA_3G" "WINDOWS_GENERIC" "WINMOBILE_GENERIC" "WINMOBILE_SP" "WINMOBILE_PPC" "LINUX_GENERIC" "LINUX_DESKTOP" "LINUX_EMBED" "WIPI_GENERIC" "NDS_GENERIC" "ARM_SEMIH_GENERIC" "NULCUES_GENERIC" "NGI_GENERIC", Default="WINDOWS_GENERIC", Value = "WINDOWS_GENERIC" -DeviceFPU = Type=string, Allowed="None" "VFP Present", Default="VFP Present", Value = "VFP Present" -DeviceFreeRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceIDInt = Type=int, Default="0", Value = "0" -DeviceIDString = Type=string, Default="", Value = "" -DeviceIMSI = Type=string, Default="SIMULATOR_IMSI", Value = "SIMULATOR_IMSI" -DeviceLSKIsBack = Type=bool, Default="false", Value = "false" -DeviceLanguage = Type=string, Allowed="UNKNOWN" "ENGLISH" "FRENCH" "GERMAN" "SPANISH" "ITALIAN" "PORTUGUESE" "DUTCH" "TURKISH" "CROATIAN" "CZECH" "DANISH" "FINNISH" "HUNGARIAN" "NORWEGIAN" "POLISH" "RUSSIAN" "SERBIAN" "SLOVAK" "SLOVENIAN" "SWEDISH" "UKRAINIAN" "GREEK" "JAPANESE" "SIMPL_CHINESE" "TRAD_CHINESE" "KOREAN" "ICELANDIC" "FLEMISH" "THAI" "AFRIKAANS" "ALBANIAN" "AMHARIC" "ARABIC" "ARMENIAN" "AZERBAIJANI" "TAGALOG" "BELARUSSIAN" "BENGALI" "BULGARIAN" "BURMESE" "CATALAN" "ESTONIAN" "FARSI" "GAELIC" "GEORGIAN" "GUJARATI" "HEBREW" "HINDI" "INDONESIAN" "IRISH" "KANNADA" "KAZAKH" "KHMER" "LAO" "LATVIAN" "LITHUANIAN" "MACEDONIAN" "MALAY" "MALAYALAM" "MARATHI" "MOLDOVIAN" "MONGOLIAN" "PUNJABI" "ROMANIAN" "SINHALESE" "SOMALI" "SWAHILI" "TAJIK" "TAMIL" "TELUGU" "TIBETAN" "TIGRINYA" "TURKMEN" "URDU" "UZBEK" "VIETNAMESE" "WELSH" "ZULU" "", Default="", Value = "" -DeviceMainsPower = Type=bool, Default="false", Value = "false" -DeviceName = Type=string, Default="My Computer", Value = "My Computer" -DeviceOS = Type=string, Allowed="NONE" "SYMBIAN" "BREW" "WINDOWS" "WINMOBILE" "LINUX" "WIPI" "NDS" "ARM_SEMIH" "NUCLEUS" "NGI" "WINCE" "SHARPEMP" "OSX" "IPHONE" "UIQ" "PS3" "X360" "BADA" "ANDROID" "WEBOS" "QNX", Default="NONE", Value = "NONE" -DeviceOSVersion = Type=string, Default="", Value = "" -DeviceOSVersionNumber = Type=int, Default="0", Value = "0" -DevicePhoneNumber = Type=string, Default="0044123456789", Value = "0044123456789" -DeviceTimezone = Type=string, Default="SYSTEM", Value = "SYSTEM" -DeviceTotalRAM = Type=int, Min=0.000000, Max=2097151.000000, Default="1048576", Value = "1048576" -DeviceUniqueID = Type=string, Default="SIMULATOR_ID", Value = "SIMULATOR_ID" -DeviceUniqueIDInt = Type=int, Default="01234567890", Value = "01234567890" -FileTotalStorageSize = Type=int, Min=0.000000, Max=2147483648.000000, Default="67108864", Value = "67108864" -FileUseSeparateRomRam = Type=bool, Default="true", Value = "true" -FileUseTotalStorageSize = Type=bool, Default="false", Value = "false" -GLAPI = Type=string, Allowed="None" "GLES 1.0 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.1 Common-Lite Profile from Imagination POWERVR(TM)" "GLES 1.0 Common Profile from Imagination POWERVR(TM)" "GLES 1.1 Common Profile from Imagination POWERVR(TM)" "GLES 2.0 from Imagination POWERVR(TM)" "Obey [S3E] SysGlesVersion .icf setting" "GLES 1.1 Common Profile from Qualcomm Snapdragon(TM)" "GLES 2.0 from Qualcomm Snapdragon(TM)" "GLES 2.0 ANGLE", Default="Obey [S3E] SysGlesVersion .icf setting", Value = "Obey [S3E] SysGlesVersion .icf setting" -GLDontUseHiddenWindow = Type=bool, Default="false", Value = "false" -GLTerminateOnSuspend = Type=bool, Default="false", Value = "false" -GLUsePVRVFrame = Type=bool, Default="false", Value = "false" -KeyboardHasAlpha = Type=bool, Default="true", Value = "true" -KeyboardHasDirection = Type=bool, Default="true", Value = "true" -KeyboardHasKeypad = Type=bool, Default="true", Value = "true" -KeyboardNumpadRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -LicenseExpiryDate = Type=int, Min=0.000000, Max=999999995904.000000, Default="0", Value = "0" -LicenseMinutesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LicenseStatus = Type=string, Allowed="EXPIRED" "DEMO" "USECOUNT" "EXPIRYDATE" "EXPIRYMINSUSE" "PURCHASE" "SUBSCRIPTION" "UPGRADE" "NONCOMMERCIAL", Default="NONCOMMERCIAL", Value = "NONCOMMERCIAL" -LicenseUsesRemaining = Type=int, Min=0.000000, Max=10000000.000000, Default="0", Value = "0" -LocationAltitude = Type=float, Min=-2000.000000, Max=100000.000000, Default="60.0", Value = "60.0" -LocationAvailable = Type=bool, Default="true", Value = "true" -LocationHeading = Type=float, Min=0.000000, Max=359.000000, Default="0.0", Value = "0.0" -LocationHorizontalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="20.0", Value = "20.0" -LocationLatitude = Type=float, Min=-90.000000, Max=90.000000, Default="51.511791", Value = "51.511791" -LocationLongitude = Type=float, Min=-180.000000, Max=180.000000, Default="-0.191084", Value = "-0.191084" -LocationSpeed = Type=float, Min=0.000000, Max=10000.000000, Default="0", Value = "0" -LocationVerticalAccuracy = Type=float, Min=0.000000, Max=100000.000000, Default="100.0", Value = "100.0" -MacOSSimulatorCustomSettings = Type=string, Default="", Value = "" -MacOSSimulatorDevices_ANDROID = Type=string, Allowed="Samsung Galaxy S:480x800:512" "HTC Sensation XL:480x800:768" "Samsung Galaxy Note:800x1280:1024" "Motorola Droid Razr:540x960:1024" "Kindle Fire:1024x600:512" "Samsung Galaxy Tab:1024x600:512", Default="Samsung Galaxy S:480x800:512", Value = "Samsung Galaxy S:480x800:512" -MacOSSimulatorDevices_IPHONE = Type=string, Allowed="iPhone 3GS:320x480:256" "iPhone 4:640x960:512" "iPhone 5:640x1136:1024" "iPad:768x1024:256" "iPad 2:768x1024:512" "iPad 3:1536x2048:1024", Default="iPhone 3GS:320x480:256", Value = "iPhone 3GS:320x480:256" -MacOSSimulatorPlatforms = Type=string, Allowed="IPHONE" "ANDROID", Default="IPHONE", Value = "IPHONE" -MacOSSimulatorUseCustomSettings = Type=bool, Default="true", Value = "true" -MemoryPoison = Type=bool, Default="true", Value = "true" -MemoryPoisonAlloc = Type=int, Min=0.000000, Max=255.000000, Default="170", Value = "170" -MemoryPoisonFree = Type=int, Min=0.000000, Max=255.000000, Default="221", Value = "221" -MemoryPoisonInit = Type=int, Min=0.000000, Max=255.000000, Default="204", Value = "204" -PointerAvailable = Type=bool, Default="true", Value = "true" -PointerMultiSimulationMode = Type=bool, Default="false", Value = "false" -PointerMultiTouchAvailable = Type=bool, Default="false", Value = "false" -PointerStylusType = Type=string, Allowed="INVALID" "STYLUS" "FINGER", Default="INVALID", Value = "INVALID" -PointerType = Type=string, Allowed="INVALID" "MOUSE" "STYLUS", Default="MOUSE", Value = "MOUSE" -SMSEnabled = Type=bool, Default="true", Value = "true" -SMSReceiveEnabled = Type=bool, Default="true", Value = "true" -SocketDNSDelay = Type=int, Min=0.000000, Max=30000.000000, Default="0", Value = "0" -SocketHTTPProxy = Type=string, Default="", Value = "" -SocketHostName = Type=string, Default="", Value = "" -SocketNetworkAvailable = Type=bool, Default="true", Value = "true" -SocketNetworkLoss = Type=bool, Default="false", Value = "false" -SocketNetworkType = Type=string, Allowed="NONE" "UNKNOWN" "LAN" "WLAN" "GPRS" "UMTS" "EVDO" "CDMA2000" "HSDPA" "WIMAX" "BLUETOOTH" "EDGE" "CDMA" "IDEN" "LTE" "EHRPD" "HSPAPLUS", Default="LAN", Value = "LAN" -SocketRecvLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SocketSendLimit = Type=int, Min=0.000000, Max=1000000.000000, Default="0", Value = "0" -SoundEnabled = Type=bool, Default="true", Value = "true" -SoundRecordEnabled = Type=bool, Default="true", Value = "true" -SoundSampleRate = Type=int, Allowed="8192" "11025" "16000" "22050" "44100", Default="22050", Value = "22050" -SoundStereo = Type=bool, Default="true", Value = "true" -SoundVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" -SurfaceDisableWhenGLIsActive = Type=bool, Default="false", Value = "false" -SurfaceDoubleBuffer = Type=bool, Default="false", Value = "false" -SurfaceHeight = Type=int, Min=128.000000, Max=4096.000000, Default="480", Value = "320" -SurfacePitch = Type=int, Min=0.000000, Max=8192.000000, Default="0", Value = "0" -SurfacePixelType = Type=string, Allowed="RGB444" "RGB555" "RGB565" "RGB666" "RGB888" "BGR444" "BGR555" "BGR565" "BGR666" "BGR888", Default="RGB565", Value = "RGB565" -SurfacePredefinedResolution = Type=string, Allowed="176x200" "176x208" "240x320 (QVGA Portrait)" "240x400" "320x240 (QVGA Landscape)" "320x400" "320x480 (iPhone Portrait)" "400x240" "480x320 (iPhone Landscape)" "360x640 (qHD Portrait)" "640x360 (qHD Landscape)" "480x640 (VGA Portrait)" "480x800 (WVGA Portrait)" "640x480 (VGA Landscape)" "800x400" "800x480 (WVGA Landscape)" "640x960 (iPhone 4 Portrait)" "960x640 (iPhone 4 Landscape)" "640x1136 (iPhone 5 Portrait)" "1136x640 (iPhone 5 Landscape)" "1024x600 (Playbook Landscape)" "600x1024 (Playbook Portrait)" "768x1024 (iPad Portrait)" "1024x768 (iPad Landscape)" "2048x1536 (iPad Retina Landscape)" "1536x2048 (iPad Retina Portrait)", Default="320x480 (iPhone Portrait)", Value = "176x200" -SurfaceRotation = Type=string, Allowed="Rot0" "Rot90" "Rot180" "Rot270", Default="Rot0", Value = "Rot0" -SurfaceUnalign = Type=bool, Default="true", Value = "true" -SurfaceUseMultiBuffers = Type=bool, Default="true", Value = "true" -SurfaceWidth = Type=int, Min=128.000000, Max=4096.000000, Default="320", Value = "480" -SymbianSoundLatency = Type=int, Min=20.000000, Max=1400.000000, Default="120", Value = "120" -ThreadEnabled = Type=bool, Default="true", Value = "true" -TimerAccuracy = Type=int, Min=0.000000, Max=1000.000000, Default="0", Value = "0" -TimerHiRes = Type=bool, Default="false", Value = "false" -TimerLocaltimeOffsetHours = Type=string, Allowed="-12" "-11" "-10" "-9" "-8" "-7" "-6" "-5" "-4" "-3" "-2" "-1" "0" "+1" "+2" "+3" "+4" "+5" "+6" "+7" "+8" "+9" "+10" "+11" "+12" "+13" "SYSTEM", Default="SYSTEM", Value = "SYSTEM" -VibraEnabled = Type=bool, Default="true", Value = "true" -Video3GPP = Type=bool, Default="false", Value = "false" -VideoJPEG = Type=bool, Default="true", Value = "true" -VideoMPEG4 = Type=bool, Default="true", Value = "true" -VideoVolumeDefault = Type=int, Min=0.000000, Max=256.000000, Default="256", Value = "256" From bc251bcc9580cbf7cbf14ee6e8bcb315d86685f3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:56:03 +0800 Subject: [PATCH 387/557] [cmake] Update make-all-linux-projects.sh. --- build/make-all-linux-project.sh | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/build/make-all-linux-project.sh b/build/make-all-linux-project.sh index 4889355380..98eaeef714 100755 --- a/build/make-all-linux-project.sh +++ b/build/make-all-linux-project.sh @@ -17,10 +17,8 @@ if $COCOS2DX_USEAPT; then ./install-deps-linux.sh fi -export MAKEFLAGS=-j10 +mkdir -p linux-build +cd linux-build +cmake ../.. +make -j10 -make PLATFORM=linux DEBUG=1 clean -make PLATFORM=linux DEBUG=0 clean - -make PLATFORM=linux DEBUG=1 all -make PLATFORM=linux DEBUG=0 all From b1a9843091e575d0569f57e31814255fb79d1a68 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 18:59:39 +0800 Subject: [PATCH 388/557] [cmake] update run-script.sh --- tools/travis-scripts/run-script.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 54cd858c49..7fc74092fd 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -72,7 +72,10 @@ elif [ "$PLATFORM"x = "linux"x ]; then ./generate-jsbindings.sh cd $COCOS2DX_ROOT/build - make -j4 + mkdir -p linux-build + cd linux-build + cmake ../.. + make -j10 elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes echo "Generating bindings glue codes ..." From 6a351711ae378950d058d59414ae212632c80327 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 21:05:29 +0800 Subject: [PATCH 389/557] [cmake] update run-script.sh --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 7fc74092fd..99cfba1eb1 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n NDK_DEBUG=0 -j10 all + ./android-build.py -n -j10 all # Build template # echo "Building template ..." From f968169da4b99345f1701df2d09e69fe0f5d7797 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 4 Nov 2013 21:59:03 +0800 Subject: [PATCH 390/557] Update run-script.sh --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 99cfba1eb1..e8d45a1415 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n -j10 all + ./android-build.py -n "NDK_BUG=0 -j10" all # Build template # echo "Building template ..." From 0350ac7021c9ce6126716648a9330b74e035064d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 11:53:40 -0800 Subject: [PATCH 391/557] arm64 support --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/platform/CCEGLViewProtocol.cpp | 20 ++++++++-------- cocos/2d/platform/CCEGLViewProtocol.h | 10 ++++---- cocos/2d/platform/ios/EAGLView.mm | 24 +++++++++---------- cocos/math/kazmath/src/mat4.c | 2 +- cocos/math/kazmath/src/neon_matrix_impl.c | 3 ++- external/curl/include/ios/curl/curlbuild.h | 2 +- 8 files changed, 33 insertions(+), 32 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index e32180792f..0532e4c91c 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -8c640bf1e2f1cd0a489e6169c930234b809636f2 \ No newline at end of file +76a9b59d223b70e0db8ee75c10c90910f44ca943 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index ba37de5f5d..7a61547a58 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b473303312be3b69891020b5fb470dd382f31284 \ No newline at end of file +339a697a5f1d1b9c06d6fa5262c9887df0f763de \ No newline at end of file diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 17eafdf0d6..9004f4c6fc 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -201,9 +201,9 @@ const char* EGLViewProtocol::getViewName() return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = nullptr; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -251,9 +251,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -283,7 +283,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys else { // It is error, should return. - CCLOG("Moving touches with id: %d error", id); + CCLOG("Moving touches with id: %p error", id); return; } } @@ -299,9 +299,9 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]) { - int id = 0; + void* id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -359,12 +359,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, void* ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, void* ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index b8744d0dd1..84bb1b4ee3 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -136,10 +136,10 @@ public: const char* getViewName(); /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, void* ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -156,7 +156,7 @@ public: */ float getScaleY() const; private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]); protected: EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index 5d305d4bdc..771d32fd1f 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -399,18 +399,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (void**)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -419,18 +419,18 @@ static CCEAGLView *view = 0; { return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (void**)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -440,18 +440,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (void**)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -461,18 +461,18 @@ static CCEAGLView *view = 0; return; } - int ids[IOS_MAX_TOUCHES_COUNT] = {0}; + UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0}; float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f}; float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f}; int i = 0; for (UITouch *touch in touches) { - ids[i] = (int)touch; + ids[i] = touch; xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (void**)ids, xs, ys); } #pragma mark - diff --git a/cocos/math/kazmath/src/mat4.c b/cocos/math/kazmath/src/mat4.c index 77495cfdaa..9c49b56071 100644 --- a/cocos/math/kazmath/src/mat4.c +++ b/cocos/math/kazmath/src/mat4.c @@ -216,7 +216,7 @@ kmMat4* const kmMat4Transpose(kmMat4* pOut, const kmMat4* pIn) */ kmMat4* const kmMat4Multiply(kmMat4* pOut, const kmMat4* pM1, const kmMat4* pM2) { -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) // It is possible to skip the memcpy() since "out" does not overwrite p1 or p2. // otherwise a temp must be needed. diff --git a/cocos/math/kazmath/src/neon_matrix_impl.c b/cocos/math/kazmath/src/neon_matrix_impl.c index 9790b73c92..b174ad0f87 100644 --- a/cocos/math/kazmath/src/neon_matrix_impl.c +++ b/cocos/math/kazmath/src/neon_matrix_impl.c @@ -23,7 +23,8 @@ #include "kazmath/neon_matrix_impl.h" -#if defined(__ARM_NEON__) +#if defined(__ARM_NEON__) && !defined(__arm64__) + void NEON_Matrix4Mul(const float* a, const float* b, float* output ) { diff --git a/external/curl/include/ios/curl/curlbuild.h b/external/curl/include/ios/curl/curlbuild.h index 98ede6eef7..c24099a90a 100644 --- a/external/curl/include/ios/curl/curlbuild.h +++ b/external/curl/include/ios/curl/curlbuild.h @@ -153,7 +153,7 @@ #endif /* The size of `long', as computed by sizeof. */ -#define CURL_SIZEOF_LONG 4 +#define CURL_SIZEOF_LONG sizeof(long) /* Integral data type used for curl_socklen_t. */ #define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t From ab6d620b3daf58789e0a1160dc4683f4fd445ced Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 15:11:20 -0800 Subject: [PATCH 392/557] Disables arm64 for the moment --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b016505abb..c6793fae44 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -d1d9b4192613089cb2c5ae3c1b9686903f6a4aa1 \ No newline at end of file +c49249b6c4c65ae98a4f04ee18f3546b413b53f7 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 7a61547a58..d74257f49d 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -339a697a5f1d1b9c06d6fa5262c9887df0f763de \ No newline at end of file +2bc0a50d02444f846edaf00627df2df32df64f75 \ No newline at end of file From 2f0a19c7a38847bef7715c7edf918694739726e3 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:30:00 -0800 Subject: [PATCH 393/557] Enables more warnings in Xcode project --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index c6793fae44..098e7c8f8f 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c49249b6c4c65ae98a4f04ee18f3546b413b53f7 \ No newline at end of file +dfbc1763de24004bc22496be8456fc4a21fda7b4 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index d74257f49d..d1e4777ebf 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2bc0a50d02444f846edaf00627df2df32df64f75 \ No newline at end of file +13f41d81e48285159fafa45159fdd1c081b4bb06 \ No newline at end of file From 24ecbc426cefc554086454233493cee3f6ce288f Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:30:33 -0800 Subject: [PATCH 394/557] removes Hungarian notation from CCACtionManager and fixes some 64-bit issues. --- cocos/2d/CCActionManager.cpp | 172 +++++++++++++++++------------------ cocos/2d/CCActionManager.h | 2 +- 2 files changed, 87 insertions(+), 87 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 9d1fb1ee93..4a01fd7663 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -65,55 +65,55 @@ ActionManager::~ActionManager(void) // private -void ActionManager::deleteHashElement(tHashElement *pElement) +void ActionManager::deleteHashElement(tHashElement *element) { - ccArrayFree(pElement->actions); - HASH_DEL(_targets, pElement); - pElement->target->release(); - free(pElement); + ccArrayFree(element->actions); + HASH_DEL(_targets, element); + element->target->release(); + free(element); } -void ActionManager::actionAllocWithHashElement(tHashElement *pElement) +void ActionManager::actionAllocWithHashElement(tHashElement *element) { // 4 actions per Node by default - if (pElement->actions == NULL) + if (element->actions == NULL) { - pElement->actions = ccArrayNew(4); + element->actions = ccArrayNew(4); }else - if (pElement->actions->num == pElement->actions->max) + if (element->actions->num == element->actions->max) { - ccArrayDoubleCapacity(pElement->actions); + ccArrayDoubleCapacity(element->actions); } } -void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) +void ActionManager::removeActionAtIndex(long index, tHashElement *element) { - Action *pAction = (Action*)pElement->actions->arr[index]; + Action *action = (Action*)element->actions->arr[index]; - if (pAction == pElement->currentAction && (! pElement->currentActionSalvaged)) + if (action == element->currentAction && (! element->currentActionSalvaged)) { - pElement->currentAction->retain(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + element->currentActionSalvaged = true; } - ccArrayRemoveObjectAtIndex(pElement->actions, index, true); + ccArrayRemoveObjectAtIndex(element->actions, index, true); // update actionIndex in case we are in tick. looping over the actions - if (pElement->actionIndex >= index) + if (element->actionIndex >= index) { - pElement->actionIndex--; + element->actionIndex--; } - if (pElement->actions->num == 0) + if (element->actions->num == 0) { - if (_currentTarget == pElement) + if (_currentTarget == element) { _currentTargetSalvaged = true; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } } @@ -122,21 +122,21 @@ void ActionManager::removeActionAtIndex(int index, tHashElement *pElement) void ActionManager::pauseTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - pElement->paused = true; + element->paused = true; } } void ActionManager::resumeTarget(Object *target) { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - pElement->paused = false; + element->paused = false; } } @@ -168,40 +168,40 @@ void ActionManager::resumeTargets(cocos2d::Set *targetsToResume) // run -void ActionManager::addAction(Action *pAction, Node *target, bool paused) +void ActionManager::addAction(Action *action, Node *target, bool paused) { - CCASSERT(pAction != NULL, ""); + CCASSERT(action != NULL, ""); CCASSERT(target != NULL, ""); - tHashElement *pElement = NULL; + tHashElement *element = NULL; // we should convert it to Object*, because we save it as Object* Object *tmp = target; - HASH_FIND_INT(_targets, &tmp, pElement); - if (! pElement) + HASH_FIND_INT(_targets, &tmp, element); + if (! element) { - pElement = (tHashElement*)calloc(sizeof(*pElement), 1); - pElement->paused = paused; + element = (tHashElement*)calloc(sizeof(*element), 1); + element->paused = paused; target->retain(); - pElement->target = target; - HASH_ADD_INT(_targets, target, pElement); + element->target = target; + HASH_ADD_INT(_targets, target, element); } - actionAllocWithHashElement(pElement); + actionAllocWithHashElement(element); - CCASSERT(! ccArrayContainsObject(pElement->actions, pAction), ""); - ccArrayAppendObject(pElement->actions, pAction); + CCASSERT(! ccArrayContainsObject(element->actions, action), ""); + ccArrayAppendObject(element->actions, action); - pAction->startWithTarget(target); + action->startWithTarget(target); } // remove void ActionManager::removeAllActions(void) { - for (tHashElement *pElement = _targets; pElement != NULL; ) + for (tHashElement *element = _targets; element != NULL; ) { - Object *target = pElement->target; - pElement = (tHashElement*)pElement->hh.next; + Object *target = element->target; + element = (tHashElement*)element->hh.next; removeAllActionsFromTarget(target); } } @@ -214,24 +214,24 @@ void ActionManager::removeAllActionsFromTarget(Object *target) return; } - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - if (ccArrayContainsObject(pElement->actions, pElement->currentAction) && (! pElement->currentActionSalvaged)) + if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged)) { - pElement->currentAction->retain(); - pElement->currentActionSalvaged = true; + element->currentAction->retain(); + element->currentActionSalvaged = true; } - ccArrayRemoveAllObjects(pElement->actions); - if (_currentTarget == pElement) + ccArrayRemoveAllObjects(element->actions); + if (_currentTarget == element) { _currentTargetSalvaged = true; } else { - deleteHashElement(pElement); + deleteHashElement(element); } } else @@ -240,23 +240,23 @@ void ActionManager::removeAllActionsFromTarget(Object *target) } } -void ActionManager::removeAction(Action *pAction) +void ActionManager::removeAction(Action *action) { // explicit null handling - if (pAction == NULL) + if (action == NULL) { return; } - tHashElement *pElement = NULL; - Object *target = pAction->getOriginalTarget(); - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + Object *target = action->getOriginalTarget(); + HASH_FIND_INT(_targets, &target, element); + if (element) { - unsigned int i = ccArrayGetIndexOfObject(pElement->actions, pAction); - if (UINT_MAX != i) + long i = ccArrayGetIndexOfObject(element->actions, action); + if (i != CC_INVALID_INDEX) { - removeActionAtIndex(i, pElement); + removeActionAtIndex(i, element); } } else @@ -270,19 +270,19 @@ void ActionManager::removeActionByTag(int tag, Object *target) CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(target != NULL, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); - if (pElement) + if (element) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + for (long i = 0; i < limit; ++i) { - Action *pAction = (Action*)pElement->actions->arr[i]; + Action *action = (Action*)element->actions->arr[i]; - if (pAction->getTag() == (int)tag && pAction->getOriginalTarget() == target) + if (action->getTag() == (int)tag && action->getOriginalTarget() == target) { - removeActionAtIndex(i, pElement); + removeActionAtIndex(i, element); break; } } @@ -297,21 +297,21 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); - if (pElement) + if (element) { - if (pElement->actions != NULL) + if (element->actions != NULL) { - unsigned int limit = pElement->actions->num; - for (unsigned int i = 0; i < limit; ++i) + long limit = element->actions->num; + for (long i = 0; i < limit; ++i) { - Action *pAction = (Action*)pElement->actions->arr[i]; + Action *action = (Action*)element->actions->arr[i]; - if (pAction->getTag() == (int)tag) + if (action->getTag() == (int)tag) { - return pAction; + return action; } } } @@ -329,11 +329,11 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // and, it is not possible to get the address of a reference unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { - tHashElement *pElement = NULL; - HASH_FIND_INT(_targets, &target, pElement); - if (pElement) + tHashElement *element = NULL; + HASH_FIND_INT(_targets, &target, element); + if (element) { - return pElement->actions ? pElement->actions->num : 0; + return element->actions ? element->actions->num : 0; } return 0; @@ -374,10 +374,10 @@ void ActionManager::update(float dt) { _currentTarget->currentAction->stop(); - Action *pAction = _currentTarget->currentAction; + Action *action = _currentTarget->currentAction; // Make currentAction nil to prevent removeAction from salvaging it. _currentTarget->currentAction = NULL; - removeAction(pAction); + removeAction(action); } _currentTarget->currentAction = NULL; diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 72427a5648..9e21a77125 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -126,7 +126,7 @@ public: protected: // declared in ActionManager.m - void removeActionAtIndex(int index, struct _hashElement *pElement); + void removeActionAtIndex(long index, struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement); void update(float dt); From ba7ed6e5787ef31e0f2de1c408fb1bc6248ea8ce Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 4 Nov 2013 16:31:36 -0800 Subject: [PATCH 395/557] Fixes some compiler warnings The warnings are related to: * 64-to-32-bit conversion * shadow variables --- cocos/2d/CCFont.cpp | 2 +- cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelBMFont.cpp | 22 ++--- cocos/2d/CCNode.cpp | 6 +- cocos/2d/CCNode.h | 4 +- cocos/2d/CCParticleSystem.cpp | 2 +- cocos/2d/CCProfiling.cpp | 2 +- cocos/2d/CCProfiling.h | 12 +-- cocos/2d/CCRenderTexture.cpp | 6 +- cocos/2d/CCSpriteBatchNode.cpp | 6 +- cocos/2d/CCSpriteBatchNode.h | 6 +- cocos/2d/CCTexture2D.cpp | 81 +++++++++-------- cocos/2d/CCTexture2D.h | 88 +++++++++---------- cocos/2d/CCTextureAtlas.cpp | 34 +++---- cocos/2d/CCTextureAtlas.h | 34 +++---- cocos/2d/ccCArray.cpp | 70 +++++++-------- cocos/2d/ccCArray.h | 34 +++---- cocos/2d/platform/CCEGLViewProtocol.cpp | 22 ++--- cocos/2d/platform/CCEGLViewProtocol.h | 10 +-- cocos/2d/platform/CCFileUtils.cpp | 2 +- cocos/2d/platform/ios/EAGLView.mm | 40 ++++----- cocos/2d/platform/mac/CCEGLView.mm | 6 +- cocos/2d/platform/mac/EAGLView.mm | 12 +-- cocos/base/CCArray.cpp | 52 +++++------ cocos/base/CCArray.h | 32 +++---- .../cocostudio/CCActionNode.cpp | 2 +- cocos/physics/CCPhysicsShape.cpp | 6 +- cocos/physics/CCPhysicsShape.h | 16 ++-- cocos/physics/CCPhysicsWorld.cpp | 8 +- 30 files changed, 313 insertions(+), 310 deletions(-) diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index cad004a906..3dc8271499 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -75,7 +75,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG default: if (customGlyphs) { - int lenght = strlen(customGlyphs); + size_t lenght = strlen(customGlyphs); _customGlyphs = new char [lenght + 2]; memcpy(_customGlyphs, customGlyphs, lenght); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 09192c0e89..68cc984636 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -158,7 +158,7 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment if (_commonLineHeight <= 0) return false; - int numLetter = 0; +// int numLetter = 0; unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); if(!utf16String) return false; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index e96df277b5..ca28f930cb 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -113,7 +113,7 @@ bool LabelAtlas::initWithString(const char *theString, const char *fntFile) //CCLabelAtlas - Atlas generation void LabelAtlas::updateAtlasValues() { - int n = _string.length(); + size_t n = _string.length(); const unsigned char *s = (unsigned char*)_string.c_str(); @@ -188,7 +188,7 @@ void LabelAtlas::updateAtlasValues() //CCLabelAtlas - LabelProtocol void LabelAtlas::setString(const char *label) { - int len = strlen(label); + size_t len = strlen(label); if (len > _textureAtlas->getTotalQuads()) { _textureAtlas->resizeCapacity(len); diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 601187d619..a9270757c7 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -200,7 +200,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr std::string strLeft = contents->getCString(); while (strLeft.length() > 0) { - int pos = strLeft.find('\n'); + size_t pos = strLeft.find('\n'); if (pos != (int)std::string::npos) { @@ -267,8 +267,8 @@ void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fnt ////////////////////////////////////////////////////////////////////////// // page ID. Sanity check - int index = line.find('=')+1; - int index2 = line.find(' ', index); + long index = line.find('=')+1; + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); CCASSERT(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); // file @@ -288,8 +288,8 @@ void CCBMFontConfiguration::parseInfoArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // padding - int index = line.find("padding="); - int index2 = line.find(' ', index); + long index = line.find("padding="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "padding=%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left); CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom); @@ -303,8 +303,8 @@ void CCBMFontConfiguration::parseCommonArguments(std::string line) ////////////////////////////////////////////////////////////////////////// // Height - int index = line.find("lineHeight="); - int index2 = line.find(' ', index); + long index = line.find("lineHeight="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "lineHeight=%d", &_commonHeight); // scaleW. sanity check @@ -334,8 +334,8 @@ void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontD ////////////////////////////////////////////////////////////////////////// // Character ID - int index = line.find("id="); - int index2 = line.find(' ', index); + long index = line.find("id="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "id=%u", &characterDefinition->charID); @@ -385,8 +385,8 @@ void CCBMFontConfiguration::parseKerningEntry(std::string line) // first int first; - int index = line.find("first="); - int index2 = line.find(' ', index); + long index = line.find("first="); + long index2 = line.find(' ', index); std::string value = line.substr(index, index2-index); sscanf(value.c_str(), "first=%d", &first); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index cb1fb62f6c..e329f49c3e 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -402,7 +402,7 @@ void Node::setPositionY(float y) setPosition(Point(_position.x, y)); } -unsigned int Node::getChildrenCount() const +long Node::getChildrenCount() const { return _children ? _children->count() : 0; } @@ -694,7 +694,7 @@ void Node::removeChild(Node* child, bool cleanup /* = true */) return; } - int index = _children->getIndexOfObject(child); + long index = _children->getIndexOfObject(child); if( index != CC_INVALID_INDEX ) this->detachChild( child, index, cleanup ); } @@ -754,7 +754,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup) } -void Node::detachChild(Node *child, int childIndex, bool doCleanup) +void Node::detachChild(Node *child, long childIndex, bool doCleanup) { // IMPORTANT: // -1st do onExit diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index cde05c34c3..5a363c8053 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -644,7 +644,7 @@ public: * * @return The amount of children. */ - unsigned int getChildrenCount() const; + long getChildrenCount() const; /** * Sets the parent node @@ -1421,7 +1421,7 @@ protected: void insertChild(Node* child, int z); /// Removes a child, call child->onExit(), do cleanup, remove it from children array. - void detachChild(Node *child, int index, bool doCleanup); + void detachChild(Node *child, long index, bool doCleanup); /// Convert cocos2d coordinates to UI windows coordinate. Point convertToWindowSpace(const Point& nodePoint) const; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index a42ac234cb..785251ca7a 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -388,7 +388,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn const char *textureData = dictionary->valueForKey("textureImageData")->getCString(); CCASSERT(textureData, ""); - int dataLen = strlen(textureData); + long dataLen = strlen(textureData); if(dataLen != 0) { // if it fails, try to get it from the base64-gzipped data diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 2794b3b183..3cd9878375 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName) CCASSERT(timer, "CCProfilingTimer not found"); - int duration = chrono::duration_cast(now - timer->_startTime).count(); + long duration = chrono::duration_cast(now - timer->_startTime).count(); timer->totalTime += duration; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; diff --git a/cocos/2d/CCProfiling.h b/cocos/2d/CCProfiling.h index d68dc6f918..b79c08c991 100644 --- a/cocos/2d/CCProfiling.h +++ b/cocos/2d/CCProfiling.h @@ -134,12 +134,12 @@ public: std::string _nameStr; std::chrono::high_resolution_clock::time_point _startTime; - int _averageTime1; - int _averageTime2; - int minTime; - int maxTime; - long long totalTime; - int numberOfCalls; + long _averageTime1; + long _averageTime2; + long minTime; + long maxTime; + long totalTime; + long numberOfCalls; }; extern void ProfilingBeginTimingBlock(const char *timerName); diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index d76c258f87..17697c9de5 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -198,8 +198,8 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); // textures must be power of two squared - unsigned int powW = 0; - unsigned int powH = 0; + long powW = 0; + long powH = 0; if (Configuration::getInstance()->supportsNPOT()) { @@ -212,7 +212,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat powH = ccNextPOT(h); } - int dataLen = (int)(powW * powH * 4); + long dataLen = (long)(powW * powH * 4); data = malloc(dataLen); CC_BREAK_IF(! data); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index d531a571dd..820a999401 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -64,7 +64,7 @@ SpriteBatchNode* SpriteBatchNode::createWithTexture(Texture2D* tex, int capacity * creation with File Image */ -SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = DEFAULT_CAPACITY*/) +SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, long capacity/* = DEFAULT_CAPACITY*/) { SpriteBatchNode *batchNode = new SpriteBatchNode(); batchNode->initWithFile(fileImage, capacity); @@ -76,7 +76,7 @@ SpriteBatchNode* SpriteBatchNode::create(const char *fileImage, int capacity/* = /* * init with Texture2D */ -bool SpriteBatchNode::initWithTexture(Texture2D *tex, int capacity) +bool SpriteBatchNode::initWithTexture(Texture2D *tex, long capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -112,7 +112,7 @@ bool SpriteBatchNode::init() /* * init with FileImage */ -bool SpriteBatchNode::initWithFile(const char* fileImage, int capacity) +bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity) { Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage); return initWithTexture(texture2D, capacity); diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index 6ba402fe57..8d1b930771 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -74,7 +74,7 @@ public: The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. */ - static SpriteBatchNode* create(const char* fileImage, int capacity = DEFAULT_CAPACITY); + static SpriteBatchNode* create(const char* fileImage, long capacity = DEFAULT_CAPACITY); /** * @js ctor */ @@ -88,14 +88,14 @@ public: /** initializes a SpriteBatchNode with a texture2d and capacity of children. The capacity will be increased in 33% in runtime if it run out of space. */ - bool initWithTexture(Texture2D *tex, int capacity); + bool initWithTexture(Texture2D *tex, long capacity); /** initializes a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children. The capacity will be increased in 33% in runtime if it run out of space. The file will be loaded using the TextureMgr. * @js init * @lua init */ - bool initWithFile(const char* fileImage, int capacity); + bool initWithFile(const char* fileImage, long capacity); bool init(); /** returns the TextureAtlas object */ diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 84a6822dda..397bdbf68a 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -119,7 +119,7 @@ static bool _PVRHaveAlphaPremultiplied = false; //conventer function // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB -void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i=0; i < dataLen; ++i) { @@ -130,7 +130,7 @@ void Texture2D::convertI8ToRGB888(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -141,7 +141,7 @@ void Texture2D::convertAI88ToRGB888(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0; i < dataLen; ++i) { @@ -153,7 +153,7 @@ void Texture2D::convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsi } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -165,7 +165,7 @@ void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, int dataLen, un } // IIIIIIII -> RRRRRGGGGGGBBBBB -void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -177,7 +177,7 @@ void Texture2D::convertI8ToRGB565(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -189,7 +189,7 @@ void Texture2D::convertAI88ToRGB565(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> RRRRGGGGBBBBAAAA -void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -202,7 +202,7 @@ void Texture2D::convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsi } // IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -215,7 +215,7 @@ void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, int dataLen, un } // IIIIIIII -> RRRRRGGGGGBBBBBA -void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -228,7 +228,7 @@ void Texture2D::convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsign } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA -void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 1; i < l; i += 2) @@ -241,7 +241,7 @@ void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsi } // IIIIIIII -> IIIIIIIIAAAAAAAA -void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) @@ -252,7 +252,7 @@ void Texture2D::convertI8ToAI88(const unsigned char* data, int dataLen, unsigned } // IIIIIIIIAAAAAAAA -> AAAAAAAA -void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 1; i < dataLen; i += 2) { @@ -261,7 +261,7 @@ void Texture2D::convertAI88ToA8(const unsigned char* data, int dataLen, unsigned } // IIIIIIIIAAAAAAAA -> IIIIIIII -void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 1; i < l; i += 2) { @@ -270,7 +270,7 @@ void Texture2D::convertAI88ToI8(const unsigned char* data, int dataLen, unsigned } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -282,7 +282,7 @@ void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB -void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -293,7 +293,7 @@ void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 2; i < l; i += 3) @@ -305,7 +305,7 @@ void Texture2D::convertRGB888ToRGB565(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB -void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 3; i < l; i += 4) @@ -317,7 +317,7 @@ void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII -void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -326,7 +326,7 @@ void Texture2D::convertRGB888ToI8(const unsigned char* data, int dataLen, unsign } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII -void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -335,7 +335,7 @@ void Texture2D::convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsi } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA -void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen -3; i < l; i += 4) { @@ -344,7 +344,7 @@ void Texture2D::convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsi } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 2; i < l; i += 3) { @@ -355,7 +355,7 @@ void Texture2D::convertRGB888ToAI88(const unsigned char* data, int dataLen, unsi // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA -void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData) { for (int i = 0, l = dataLen - 3; i < l; i += 4) { @@ -365,7 +365,7 @@ void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 2; i < l; i += 3) @@ -378,7 +378,7 @@ void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA -void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0, l = dataLen - 3; i < l; i += 4) @@ -391,10 +391,10 @@ void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 3) + for (long i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -404,10 +404,10 @@ void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, un } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA -void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData) +void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; - for (int i = 0, l = dataLen - 2; i < l; i += 4) + for (long i = 0, l = dataLen - 2; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G @@ -451,12 +451,12 @@ Texture2D::PixelFormat Texture2D::getPixelFormat() const return _pixelFormat; } -unsigned int Texture2D::getPixelsWide() const +long Texture2D::getPixelsWide() const { return _pixelsWide; } -unsigned int Texture2D::getPixelsHigh() const +long Texture2D::getPixelsHigh() const { return _pixelsHigh; } @@ -529,8 +529,10 @@ bool Texture2D::hasPremultipliedAlpha() const return _hasPremultipliedAlpha; } -bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize) +bool Texture2D::initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize) { + CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); + //if data has no mipmaps, we will consider it has only one mipmap MipmapInfo mipmap; mipmap.address = (unsigned char*)data; @@ -544,10 +546,11 @@ bool Texture2D::initWithData(const void *data, int dataLen, Texture2D::PixelForm } -bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh) +bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, long pixelsWide, long pixelsHigh) { //the pixelFormat must be a certain value - CCAssert(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); + CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); + CCASSERT(pixelsWide>0 && pixelsHigh>0, "Invalid size"); if (mipmapsNum <= 0) { @@ -670,7 +673,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat const char* Texture2D::description(void) const { - return String::createWithFormat("", _name, _pixelsWide, _pixelsHigh, _maxS, _maxT)->getCString(); + return String::createWithFormat("", _name, (long)_pixelsWide, (long)_pixelsHigh, _maxS, _maxT)->getCString(); } // implementation Texture2D (Image) @@ -771,7 +774,7 @@ bool Texture2D::initWithImage(Image *image, PixelFormat format) } } -Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -820,7 +823,7 @@ Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, i return format; } -Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -875,7 +878,7 @@ Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, return format; } -Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) { @@ -923,7 +926,7 @@ Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* dat return format; } -Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (format) @@ -995,7 +998,7 @@ rgb(2) -> 1235678 rgba(1) -> 12345678 */ -Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) +Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen) { switch (originFormat) { diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index 6f15273f9c..bdb28ce582 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -120,13 +120,13 @@ public: struct PixelFormatInfo { - PixelFormatInfo(GLenum internalFormat, GLenum format, GLenum type, int bpp, bool compressed, bool alpha) - : internalFormat(internalFormat) - , format(format) - , type(type) - , bpp(bpp) - , compressed(compressed) - , alpha(alpha) + PixelFormatInfo(GLenum anInternalFormat, GLenum aFormat, GLenum aType, int aBpp, bool aCompressed, bool anAlpha) + : internalFormat(anInternalFormat) + , format(aFormat) + , type(aType) + , bpp(aBpp) + , compressed(aCompressed) + , alpha(anAlpha) {} GLenum internalFormat; @@ -216,10 +216,10 @@ public: * @js NA * @lua NA */ - bool initWithData(const void *data, int dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize); + bool initWithData(const void *data, long dataLen, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh, const Size& contentSize); /** Initializes with mipmaps */ - bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh); + bool initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, Texture2D::PixelFormat pixelFormat, long pixelsWide, long pixelsHigh); /** Drawing extensions to make it easy to draw basic quads using a Texture2D object. @@ -326,10 +326,10 @@ public: Texture2D::PixelFormat getPixelFormat() const; /** Gets the width of the texture in pixels */ - unsigned int getPixelsWide() const; + long getPixelsWide() const; /** Gets the height of the texture in pixels */ - unsigned int getPixelsHigh() const; + long getPixelsHigh() const; /** Gets the texture name */ GLuint getName() const; @@ -360,56 +360,56 @@ private: Convert the format to the format param you specified, if the format is PixelFormat::Automatic, it will detect it automatically and convert to the closest format for you. It will return the converted format to you. if the outData != data, you must delete it manually. */ - static PixelFormat convertDataToFormat(const unsigned char* data, int dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertDataToFormat(const unsigned char* data, long dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertI8ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertAI88ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGB888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); - static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, int dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertI8ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertAI88ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertRGB888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); + static PixelFormat convertRGBA8888ToFormat(const unsigned char* data, long dataLen, PixelFormat format, unsigned char** outData, int* outDataLen); //I8 to XXX - static void convertI8ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertI8ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertI8ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertI8ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); //AI88 to XXX - static void convertAI88ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertAI88ToI8(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertAI88ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertAI88ToI8(const unsigned char* data, long dataLen, unsigned char* outData); //RGB888 to XXX - static void convertRGB888ToRGBA8888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGB888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertRGB888ToRGBA8888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGB888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); //RGBA8888 to XXX - static void convertRGBA8888ToRGB888(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB565(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToI8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToA8(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToAI88(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGBA4444(const unsigned char* data, int dataLen, unsigned char* outData); - static void convertRGBA8888ToRGB5A1(const unsigned char* data, int dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB888(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB565(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToI8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToA8(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToAI88(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGBA4444(const unsigned char* data, long dataLen, unsigned char* outData); + static void convertRGBA8888ToRGB5A1(const unsigned char* data, long dataLen, unsigned char* outData); protected: /** pixel format of the texture */ Texture2D::PixelFormat _pixelFormat; /** width in pixels */ - unsigned int _pixelsWide; + long _pixelsWide; /** height in pixels */ - unsigned int _pixelsHigh; + long _pixelsHigh; /** texture name */ GLuint _name; diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index c83a042dde..3ef2a365c4 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -107,7 +107,7 @@ void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) // TextureAtlas - alloc & init -TextureAtlas * TextureAtlas::create(const char* file, int capacity) +TextureAtlas * TextureAtlas::create(const char* file, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if(textureAtlas && textureAtlas->initWithFile(file, capacity)) @@ -119,7 +119,7 @@ TextureAtlas * TextureAtlas::create(const char* file, int capacity) return NULL; } -TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) +TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity) { TextureAtlas * textureAtlas = new TextureAtlas(); if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) @@ -131,7 +131,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, int capacity) return NULL; } -bool TextureAtlas::initWithFile(const char * file, int capacity) +bool TextureAtlas::initWithFile(const char * file, long capacity) { // retained in property Texture2D *texture = TextureCache::getInstance()->addImage(file); @@ -147,7 +147,7 @@ bool TextureAtlas::initWithFile(const char * file, int capacity) } } -bool TextureAtlas::initWithTexture(Texture2D *texture, int capacity) +bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); @@ -310,7 +310,7 @@ void TextureAtlas::mapBuffers() // TextureAtlas - Update, Insert, Move & Remove -void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) +void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, long index) { CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index"); @@ -323,7 +323,7 @@ void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, int index) } -void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) +void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, long index) { CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index"); @@ -347,7 +347,7 @@ void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, int index) } -void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) +void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount"); @@ -378,7 +378,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount) _dirty = true; } -void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) +void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) { CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -407,7 +407,7 @@ void TextureAtlas::insertQuadFromIndex(int oldIndex, int newIndex) _dirty = true; } -void TextureAtlas::removeQuadAtIndex(int index) +void TextureAtlas::removeQuadAtIndex(long index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); @@ -426,7 +426,7 @@ void TextureAtlas::removeQuadAtIndex(int index) _dirty = true; } -void TextureAtlas::removeQuadsAtIndex(int index, int amount) +void TextureAtlas::removeQuadsAtIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); @@ -448,7 +448,7 @@ void TextureAtlas::removeAllQuads() } // TextureAtlas - Resize -bool TextureAtlas::resizeCapacity(int newCapacity) +bool TextureAtlas::resizeCapacity(long newCapacity) { CCASSERT(newCapacity>=0, "capacity >= 0"); if( newCapacity == _capacity ) @@ -522,13 +522,13 @@ bool TextureAtlas::resizeCapacity(int newCapacity) return true; } -void TextureAtlas::increaseTotalQuadsWith(int amount) +void TextureAtlas::increaseTotalQuadsWith(long amount) { CCASSERT(amount>=0, "amount >= 0"); _totalQuads += amount; } -void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) +void TextureAtlas::moveQuadsFromIndex(long oldIndex, long amount, long newIndex) { CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); @@ -560,7 +560,7 @@ void TextureAtlas::moveQuadsFromIndex(int oldIndex, int amount, int newIndex) _dirty = true; } -void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) +void TextureAtlas::moveQuadsFromIndex(long index, long newIndex) { CCASSERT(index>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds"); @@ -568,7 +568,7 @@ void TextureAtlas::moveQuadsFromIndex(int index, int newIndex) memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0])); } -void TextureAtlas::fillWithEmptyQuadsFromIndex(int index, int amount) +void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0, "values must be >= 0"); V3F_C4B_T2F_Quad quad; @@ -588,13 +588,13 @@ void TextureAtlas::drawQuads() this->drawNumberOfQuads(_totalQuads, 0); } -void TextureAtlas::drawNumberOfQuads(int numberOfQuads) +void TextureAtlas::drawNumberOfQuads(long numberOfQuads) { CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0"); this->drawNumberOfQuads(numberOfQuads, 0); } -void TextureAtlas::drawNumberOfQuads(int numberOfQuads, int start) +void TextureAtlas::drawNumberOfQuads(long numberOfQuads, long start) { CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0"); diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 4c1bb6436a..1e5ec742d7 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -59,13 +59,13 @@ public: /** creates a TextureAtlas with an filename and with an initial capacity for Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* create(const char* file , int capacity); + static TextureAtlas* create(const char* file , long capacity); /** creates a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for n Quads. * The TextureAtlas capacity can be increased in runtime. */ - static TextureAtlas* createWithTexture(Texture2D *texture, int capacity); + static TextureAtlas* createWithTexture(Texture2D *texture, long capacity); /** * @js ctor */ @@ -81,7 +81,7 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithFile(const char* file, int capacity); + bool initWithFile(const char* file, long capacity); /** initializes a TextureAtlas with a previously initialized Texture2D object, and * with an initial capacity for Quads. @@ -89,43 +89,43 @@ public: * * WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) */ - bool initWithTexture(Texture2D *texture, int capacity); + bool initWithTexture(Texture2D *texture, long capacity); /** updates a Quad (texture, vertex and color) at a certain index * index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void updateQuad(V3F_C4B_T2F_Quad* quad, int index); + void updateQuad(V3F_C4B_T2F_Quad* quad, long index); /** Inserts a Quad (texture, vertex and color) at a certain index index must be between 0 and the atlas capacity - 1 @since v0.8 */ - void insertQuad(V3F_C4B_T2F_Quad* quad, int index); + void insertQuad(V3F_C4B_T2F_Quad* quad, long index); /** Inserts a c array of quads at a given index index must be between 0 and the atlas capacity - 1 this method doesn't enlarge the array when amount + index > totalQuads @since v1.1 */ - void insertQuads(V3F_C4B_T2F_Quad* quads, int index, int amount); + void insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount); /** Removes the quad that is located at a certain index and inserts it at a new index This operation is faster than removing and inserting in a quad in 2 different steps @since v0.7.2 */ - void insertQuadFromIndex(int fromIndex, int newIndex); + void insertQuadFromIndex(long fromIndex, long newIndex); /** removes a quad at a given index number. The capacity remains the same, but the total number of quads to be drawn is reduced in 1 @since v0.7.2 */ - void removeQuadAtIndex(int index); + void removeQuadAtIndex(long index); /** removes a amount of quads starting from index @since 1.1 */ - void removeQuadsAtIndex(int index, int amount); + void removeQuadsAtIndex(long index, long amount); /** removes all Quads. The TextureAtlas capacity remains untouched. No memory is freed. The total number of quads to be drawn will be 0 @@ -138,19 +138,19 @@ public: * It returns true if the resize was successful. * If it fails to resize the capacity it will return false with a new capacity of 0. */ - bool resizeCapacity(int capacity); + bool resizeCapacity(long capacity); /** Used internally by ParticleBatchNode don't use this unless you know what you're doing @since 1.1 */ - void increaseTotalQuadsWith(int amount); + void increaseTotalQuadsWith(long amount); /** Moves an amount of quads from oldIndex at newIndex @since v1.1 */ - void moveQuadsFromIndex(int oldIndex, int amount, int newIndex); + void moveQuadsFromIndex(long oldIndex, long amount, long newIndex); /** Moves quads from index till totalQuads to the newIndex @@ -158,26 +158,26 @@ public: This method doesn't enlarge the array if newIndex + quads to be moved > capacity @since 1.1 */ - void moveQuadsFromIndex(int index, int newIndex); + void moveQuadsFromIndex(long index, long newIndex); /** Ensures that after a realloc quads are still empty Used internally by ParticleBatchNode @since 1.1 */ - void fillWithEmptyQuadsFromIndex(int index, int amount); + void fillWithEmptyQuadsFromIndex(long index, long amount); /** draws n quads * n can't be greater than the capacity of the Atlas */ - void drawNumberOfQuads(int n); + void drawNumberOfQuads(long n); /** draws n quads from an index (offset). n + start can't be greater than the capacity of the atlas @since v1.0 */ - void drawNumberOfQuads(int numberOfQuads, int start); + void drawNumberOfQuads(long numberOfQuads, long start); /** draws all the Atlas's Quads */ diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index cd8f275311..f280bc5787 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -28,10 +28,10 @@ THE SOFTWARE. NS_CC_BEGIN -const int CC_INVALID_INDEX = -1; +const long CC_INVALID_INDEX = -1; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(int capacity) +ccArray* ccArrayNew(long capacity) { if (capacity == 0) capacity = 7; @@ -68,7 +68,7 @@ void ccArrayDoubleCapacity(ccArray *arr) arr->arr = newArr; } -void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) +void ccArrayEnsureExtraCapacity(ccArray *arr, long extra) { while (arr->max < arr->num + extra) { @@ -82,7 +82,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, int extra) void ccArrayShrink(ccArray *arr) { - int newSize = 0; + long newSize = 0; //only resize when necessary if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) @@ -104,11 +104,11 @@ void ccArrayShrink(ccArray *arr) } /** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */ -int ccArrayGetIndexOfObject(ccArray *arr, Object* object) +long ccArrayGetIndexOfObject(ccArray *arr, Object* object) { - const int arrNum = arr->num; + const long arrNum = arr->num; Object** ptr = arr->arr; - for(int i = 0; i < arrNum; ++i, ++ptr) + for(long i = 0; i < arrNum; ++i, ++ptr) { if( *ptr == object ) return i; @@ -143,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object) enough capacity. */ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) { - for(int i = 0; i < plusArr->num; i++) + for(long i = 0; i < plusArr->num; i++) { ccArrayAppendObject(arr, plusArr->arr[i]); } @@ -157,14 +157,14 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr) } /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index) { CCASSERT(index<=arr->num, "Invalid index. Out of bounds"); CCASSERT(object != NULL, "Invalid parameter!"); ccArrayEnsureExtraCapacity(arr, 1); - int remaining = arr->num - index; + long remaining = arr->num - index; if( remaining > 0) { memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining ); @@ -176,7 +176,7 @@ void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index) } /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2) +void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2) { CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds"); CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds"); @@ -198,7 +198,7 @@ void ccArrayRemoveAllObjects(ccArray *arr) /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = true*/) +void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj/* = true*/) { CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds"); if (bReleaseObj) @@ -208,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr arr->num--; - int remaining = arr->num - index; + long remaining = arr->num - index; if(remaining>0) { memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*)); @@ -218,16 +218,16 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = tr /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index) +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index) { CC_SAFE_RELEASE(arr->arr[index]); - int last = --arr->num; + long last = --arr->num; arr->arr[index] = arr->arr[last]; } void ccArrayFastRemoveObject(ccArray *arr, Object* object) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayFastRemoveObjectAtIndex(arr, index); @@ -238,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object) found the function has no effect. */ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) { - int index = ccArrayGetIndexOfObject(arr, object); + long index = ccArrayGetIndexOfObject(arr, object); if (index != CC_INVALID_INDEX) { ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); @@ -249,7 +249,7 @@ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true first matching instance in arr will be removed. */ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) { - for(int i = 0; i < minusArr->num; i++) + for(long i = 0; i < minusArr->num; i++) { ccArrayRemoveObject(arr, minusArr->arr[i]); } @@ -259,8 +259,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { - int back = 0; - int i = 0; + long back = 0; + long i = 0; for( i = 0; i < arr->num; i++) { @@ -282,7 +282,7 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) // #pragma mark ccCArray for Values (c structures) /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(int capacity) +ccCArray* ccCArrayNew(long capacity) { if (capacity == 0) { @@ -317,15 +317,15 @@ void ccCArrayDoubleCapacity(ccCArray *arr) } /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra) +void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra) { ccArrayEnsureExtraCapacity((ccArray*)arr,extra); } /** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */ -int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) +long ccCArrayGetIndexOfValue(ccCArray *arr, void* value) { - for( int i = 0; i < arr->num; i++) + for(long i = 0; i < arr->num; i++) { if( arr->arr[i] == value ) return i; @@ -340,11 +340,11 @@ bool ccCArrayContainsValue(ccCArray *arr, void* value) } /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index) +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index) { CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); - int remaining = arr->num - index; + long remaining = arr->num - index; // make sure it has enough capacity if (arr->num + 1 == arr->max) { @@ -385,7 +385,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value) enough capacity. */ void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) { - for( int i = 0; i < plusArr->num; i++) + for( long i = 0; i < plusArr->num; i++) { ccCArrayAppendValue(arr, plusArr->arr[i]); } @@ -408,9 +408,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) +void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index) { - for( int last = --arr->num; index < last; index++) + for( long last = --arr->num; index < last; index++) { arr->arr[index] = arr->arr[index + 1]; } @@ -421,9 +421,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index) Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index) { - int last = --arr->num; + long last = --arr->num; arr->arr[index] = arr->arr[last]; } @@ -432,7 +432,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index) */ void ccCArrayRemoveValue(ccCArray *arr, void* value) { - int index = ccCArrayGetIndexOfValue(arr, value); + long index = ccCArrayGetIndexOfValue(arr, value); if (index != CC_INVALID_INDEX) { ccCArrayRemoveValueAtIndex(arr, index); @@ -444,7 +444,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value) */ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) { - for(int i = 0; i < minusArr->num; i++) + for(long i = 0; i < minusArr->num; i++) { ccCArrayRemoveValue(arr, minusArr->arr[i]); } @@ -455,9 +455,9 @@ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) */ void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) { - int back = 0; + long back = 0; - for(int i = 0; i < arr->num; i++) + for(long i = 0; i < arr->num; i++) { if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) { diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index fff5152904..2bfff6224f 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -51,20 +51,20 @@ THE SOFTWARE. NS_CC_BEGIN -extern const int CC_INVALID_INDEX; +extern const long CC_INVALID_INDEX; // Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ -__object__=__array__->arr[0]; for(int i=0, num=__array__->num; iarr[i]) \ +__object__=__array__->arr[0]; for(long i=0, num=__array__->num; iarr[i]) \ typedef struct _ccArray { - int num, max; + long num, max; Object** arr; } ccArray; /** Allocates and initializes a new array with specified capacity */ -ccArray* ccArrayNew(int capacity); +ccArray* ccArrayNew(long capacity); /** Frees array after removing all remaining objects. Silently ignores nil arr. */ void ccArrayFree(ccArray*& arr); @@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr); void ccArrayDoubleCapacity(ccArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccArrayEnsureExtraCapacity(ccArray *arr, int extra); +void ccArrayEnsureExtraCapacity(ccArray *arr, long extra); /** shrinks the array so the memory footprint corresponds with the number of items */ void ccArrayShrink(ccArray *arr); /** Returns index of first occurrence of object, NSNotFound if object not found. */ -int ccArrayGetIndexOfObject(ccArray *arr, Object* object); +long ccArrayGetIndexOfObject(ccArray *arr, Object* object); /** Returns a Boolean value that indicates whether object is present in array. */ bool ccArrayContainsObject(ccArray *arr, Object* object); @@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); /** Inserts an object at index */ -void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index); +void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, long index); /** Swaps two objects */ -void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2); +void ccArraySwapObjectsAtIndexes(ccArray *arr, long index1, long index2); /** Removes all objects from arr */ void ccArrayRemoveAllObjects(ccArray *arr); /** Removes object at specified index and pushes back all subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj = true); +void ccArrayRemoveObjectAtIndex(ccArray *arr, long index, bool bReleaseObj = true); /** Removes object at specified index and fills the gap with the last object, thereby avoiding the need to push back subsequent objects. Behavior undefined if index outside [0, num-1]. */ -void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index); +void ccArrayFastRemoveObjectAtIndex(ccArray *arr, long index); void ccArrayFastRemoveObject(ccArray *arr, Object* object); @@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); // #pragma mark ccCArray for Values (c structures) typedef struct _ccCArray { - int num, max; + long num, max; void** arr; } ccCArray; /** Allocates and initializes a new C array with specified capacity */ -ccCArray* ccCArrayNew(int capacity); +ccCArray* ccCArrayNew(long capacity); /** Frees C array after removing all remaining values. Silently ignores nil arr. */ void ccCArrayFree(ccCArray *arr); @@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr); /** Increases array capacity such that max >= num + extra. */ -void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra); +void ccCArrayEnsureExtraCapacity(ccCArray *arr, long extra); /** Returns index of first occurrence of value, NSNotFound if value not found. */ -int ccCArrayGetIndexOfValue(ccCArray *arr, void* value); +long ccCArrayGetIndexOfValue(ccCArray *arr, void* value); /** Returns a Boolean value that indicates whether value is present in the C array. */ bool ccCArrayContainsValue(ccCArray *arr, void* value); /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ -void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index); +void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, long index); /** Appends an value. Behavior undefined if array doesn't have enough capacity. */ void ccCArrayAppendValue(ccCArray *arr, void* value); @@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr); Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index); +void ccCArrayRemoveValueAtIndex(ccCArray *arr, long index); /** Removes value at specified index and fills the gap with the last value, thereby avoiding the need to push back subsequent values. Behavior undefined if index outside [0, num-1]. @since v0.99.4 */ -void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index); +void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, long index); /** Searches for the first occurrence of value and removes it. If value is not found the function has no effect. @since v0.99.4 diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index 9004f4c6fc..0296eb5a17 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -12,7 +12,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { NULL }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -201,9 +201,9 @@ const char* EGLViewProtocol::getViewName() return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesBegin(int num, long ids[], float xs[], float ys[]) { - void* id = nullptr; + long id = 0; float x = 0.0f; float y = 0.0f; int nUnusedIndex = 0; @@ -251,9 +251,9 @@ void EGLViewProtocol::handleTouchesBegin(int num, void* ids[], float xs[], float dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesMove(int num, long ids[], float xs[], float ys[]) { - void* id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -283,7 +283,7 @@ void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float else { // It is error, should return. - CCLOG("Moving touches with id: %p error", id); + CCLOG("Moving touches with id: %ld error", id); return; } } @@ -299,9 +299,9 @@ void EGLViewProtocol::handleTouchesMove(int num, void* ids[], float xs[], float dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]) { - void* id = 0; + long id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -336,7 +336,7 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } else { - CCLOG("Ending touches with id: %d error", id); + CCLOG("Ending touches with id: %ld error", id); return; } @@ -359,12 +359,12 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesEnd(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, void* ids[], float xs[], float ys[]) +void EGLViewProtocol::handleTouchesCancel(int num, long ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index 84bb1b4ee3..ed54d59712 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -136,10 +136,10 @@ public: const char* getViewName(); /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, void* ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, void* ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, long ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, long ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -156,7 +156,7 @@ public: */ float getScaleY() const; private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, void* ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); protected: EGLTouchDelegate* _delegate; diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index e9e01589e2..d7244ba6f0 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -451,7 +451,7 @@ NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ Dictionary* FileUtils::createDictionaryWithContentsOfFile(const std::string& filename) {return NULL;} -bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return NULL;} +bool FileUtils::writeToFile(cocos2d::Dictionary *dict, const std::string &fullPath) {return false;} Array* FileUtils::createArrayWithContentsOfFile(const std::string& filename) {return NULL;} #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/EAGLView.mm index 771d32fd1f..5536a63752 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/EAGLView.mm @@ -75,7 +75,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #define IOS_MAX_TOUCHES_COUNT 10 -static CCEAGLView *view = 0; +static CCEAGLView *__view = 0; @interface CCEAGLView (Private) - (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; @@ -117,7 +117,7 @@ static CCEAGLView *view = 0; + (id) sharedEGLView { - return view; + return __view; } - (id) initWithFrame:(CGRect)frame @@ -147,14 +147,14 @@ static CCEAGLView *view = 0; } - view = self; + __view = self; originalRect_ = self.frame; self.keyboardShowNotification = nil; - if ([view respondsToSelector:@selector(setContentScaleFactor:)]) + if ([__view respondsToSelector:@selector(setContentScaleFactor:)]) { - view.contentScaleFactor = [[UIScreen mainScreen] scale]; + __view.contentScaleFactor = [[UIScreen mainScreen] scale]; } } @@ -180,7 +180,7 @@ static CCEAGLView *view = 0; } } - view = self; + __view = self; return self; } @@ -205,13 +205,13 @@ static CCEAGLView *view = 0; -(int) getWidth { CGSize bound = [self bounds].size; - return bound.width * self.contentScaleFactor; + return (int)bound.width * self.contentScaleFactor; } -(int) getHeight { CGSize bound = [self bounds].size; - return bound.height * self.contentScaleFactor; + return (int)bound.height * self.contentScaleFactor; } @@ -406,11 +406,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (long*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -426,11 +426,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesMove(i, (long*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -447,11 +447,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (long*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -468,11 +468,11 @@ static CCEAGLView *view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (void**)ids, xs, ys); + cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (long*)ids, xs, ys); } #pragma mark - diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index af3863476d..d66f1dc17c 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -202,7 +202,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -211,7 +211,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -249,7 +249,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm index ff456d0e6a..1894440ced 100644 --- a/cocos/2d/platform/mac/EAGLView.mm +++ b/cocos/2d/platform/mac/EAGLView.mm @@ -327,7 +327,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -335,7 +335,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (long*)ids, xs, ys); } - (void)mouseMoved:(NSEvent *)theEvent @@ -351,7 +351,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -359,7 +359,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (long*)ids, xs, ys); } - (void)mouseUp:(NSEvent *)theEvent @@ -370,7 +370,7 @@ static CCEAGLView *view; float x = local_point.x; float y = [self getHeight] - local_point.y; - int ids[1] = {0}; + NSInteger ids[1] = {0}; float xs[1] = {0.0f}; float ys[1] = {0.0f}; @@ -378,7 +378,7 @@ static CCEAGLView *view; xs[0] = x / frameZoomFactor_; ys[0] = y / frameZoomFactor_; - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (long*)ids, xs, ys); } - (void)rightMouseDown:(NSEvent *)theEvent { diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index 3a55d6050d..90c88ebe34 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -105,7 +105,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -182,7 +182,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -200,7 +200,7 @@ int Array::getIndexOfObject(Object* object) const { auto it = data.begin(); - for (int i = 0; it != data.end(); ++it, ++i) + for (long i = 0; it != data.end(); ++it, ++i) { if (it->get() == object) { @@ -238,7 +238,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -279,7 +279,7 @@ void Array::removeObject(Object* object, bool releaseObj /* ignored */) data.erase( std::remove( data.begin(), data.end(), object ) ); } -void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) +void Array::removeObjectAtIndex(long index, bool releaseObj /* ignored */) { auto obj = data[index]; data.erase( data.begin() + index ); @@ -295,7 +295,7 @@ void Array::removeAllObjects() data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { removeObjectAtIndex(index); } @@ -315,12 +315,12 @@ void Array::exchangeObject(Object* object1, Object* object2) std::swap( data[idx1], data[idx2] ); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { std::swap( data[index1], data[index2] ); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject /* ignored */) { data[index] = object; } @@ -448,7 +448,7 @@ Array* Array::createWithArray(Array* otherArray) return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +Array* Array::createWithCapacity(long capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -531,7 +531,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool Array::initWithCapacity(long capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -555,7 +555,7 @@ bool Array::initWithArray(Array* otherArray) return ret; } -int Array::getIndexOfObject(Object* object) const +long Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } @@ -574,7 +574,7 @@ Object* Array::getRandomObject() r = 0; } - return data->arr[(int)(data->num * r)]; + return data->arr[(long)(data->num * r)]; } bool Array::containsObject(Object* object) const @@ -584,7 +584,7 @@ bool Array::containsObject(Object* object) const bool Array::isEqualToArray(Array* otherArray) { - for (int i = 0; i< this->count(); i++) + for (long i = 0; i< this->count(); i++) { if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i))) { @@ -606,13 +606,13 @@ void Array::addObjectsFromArray(Array* otherArray) ccArrayAppendArrayWithResize(data, otherArray->data); } -void Array::insertObject(Object* object, int index) +void Array::insertObject(Object* object, long index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, int index) +void Array::setObject(Object* object, long index) { CCASSERT(index>=0 && index < count(), "Invalid index"); @@ -635,7 +635,7 @@ void Array::removeObject(Object* object, bool releaseObj/* = true*/) ccArrayRemoveObject(data, object, releaseObj); } -void Array::removeObjectAtIndex(int index, bool releaseObj) +void Array::removeObjectAtIndex(long index, bool releaseObj) { ccArrayRemoveObjectAtIndex(data, index, releaseObj); } @@ -650,7 +650,7 @@ void Array::removeAllObjects() ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(int index) +void Array::fastRemoveObjectAtIndex(long index) { ccArrayFastRemoveObjectAtIndex(data, index); } @@ -662,14 +662,14 @@ void Array::fastRemoveObject(Object* object) void Array::exchangeObject(Object* object1, Object* object2) { - int index1 = ccArrayGetIndexOfObject(data, object1); - if (index1 == UINT_MAX) + long index1 = ccArrayGetIndexOfObject(data, object1); + if (index1 == CC_INVALID_INDEX) { return; } - int index2 = ccArrayGetIndexOfObject(data, object2); - if (index2 == UINT_MAX) + long index2 = ccArrayGetIndexOfObject(data, object2); + if (index2 == CC_INVALID_INDEX) { return; } @@ -677,12 +677,12 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void Array::exchangeObjectAtIndex(long index1, long index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) +void Array::replaceObjectAtIndex(long index, Object* object, bool releaseObject/* = true*/) { ccArrayInsertObjectAtIndex(data, object, index); ccArrayRemoveObjectAtIndex(data, index+1); @@ -693,10 +693,10 @@ void Array::reverseObjects() if (data->num > 1) { // floorf(), since in the case of an even number, the number of swaps stays the same - int count = (int) floorf(data->num/2.f); - int maxIndex = data->num - 1; + long count = (long) floorf(data->num/2.f); + long maxIndex = data->num - 1; - for (int i = 0; i < count ; i++) + for (long i = 0; i < count ; i++) { ccArraySwapObjectsAtIndexes(data, i, maxIndex); --maxIndex; diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 7f67569faa..f68ee8b64d 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -250,7 +250,7 @@ public: /** Create an array with a default capacity * @js NA */ - static Array* createWithCapacity(int capacity); + static Array* createWithCapacity(long capacity); /** Create an array with from an existing array * @js NA */ @@ -295,7 +295,7 @@ public: * @js NA * @lua NA */ - bool initWithCapacity(int capacity); + bool initWithCapacity(long capacity); /** Initializes an array with an existing array * @js NA * @lua NA @@ -307,7 +307,7 @@ public: /** Returns element count of the array * @js NA */ - int count() const + long count() const { #if CC_USE_ARRAY_VECTOR return data.size(); @@ -318,7 +318,7 @@ public: /** Returns capacity of the array * @js NA */ - int capacity() const + long capacity() const { #if CC_USE_ARRAY_VECTOR return data.capacity(); @@ -330,17 +330,17 @@ public: * @js NA * @lua NA */ - int getIndexOfObject(Object* object) const; + long getIndexOfObject(Object* object) const; /** * @js NA */ - CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); } + CC_DEPRECATED_ATTRIBUTE long indexOfObject(Object* object) const { return getIndexOfObject(object); } /** Returns an element with a certain index * @js NA * @lua NA */ - Object* getObjectAtIndex(int index) + Object* getObjectAtIndex(long index) { CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()"); #if CC_USE_ARRAY_VECTOR @@ -349,7 +349,7 @@ public: return data->arr[index]; #endif } - CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); } + CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(long index) { return getObjectAtIndex(index); } /** Returns the last element of the array * @js NA */ @@ -401,17 +401,17 @@ public: /** Insert a certain object at a certain index * @js NA */ - void insertObject(Object* object, int index); + void insertObject(Object* object, long index); /** sets a certain object at a certain index * @js NA * @lua NA */ - void setObject(Object* object, int index); + void setObject(Object* object, long index); /** sets a certain object at a certain index without retaining. Use it with caution * @js NA * @lua NA */ - void fastSetObject(Object* object, int index) + void fastSetObject(Object* object, long index) { #if CC_USE_ARRAY_VECTOR setObject(object, index); @@ -424,7 +424,7 @@ public: * @js NA * @lua NA */ - void swap( int indexOne, int indexTwo ) + void swap( long indexOne, long indexTwo ) { CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices"); #if CC_USE_ARRAY_VECTOR @@ -447,7 +447,7 @@ public: /** Remove an element with a certain index * @js NA */ - void removeObjectAtIndex(int index, bool releaseObj = true); + void removeObjectAtIndex(long index, bool releaseObj = true); /** Remove all elements * @js NA */ @@ -463,7 +463,7 @@ public: /** Fast way to remove an element with a certain index * @js NA */ - void fastRemoveObjectAtIndex(int index); + void fastRemoveObjectAtIndex(long index); // Rearranging Content @@ -474,12 +474,12 @@ public: /** Swap two elements with certain indexes * @js NA */ - void exchangeObjectAtIndex(int index1, int index2); + void exchangeObjectAtIndex(long index1, long index2); /** Replace object at index with another object. * @js NA */ - void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true); + void replaceObjectAtIndex(long index, Object* object, bool releaseObject = true); /** Revers the array * @js NA diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index fceca8816c..f0f3828791 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -424,7 +424,7 @@ bool ActionNode::updateActionToTimeLine(float fTime) bool bFindFrame = false; ActionFrame* srcFrame = NULL; - ActionFrame* destFrame = NULL; +// ActionFrame* destFrame = NULL; for (int n = 0; n < _frameArrayNum; n++) { diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 68ef1cf351..b481e0c0d9 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -600,7 +600,7 @@ Point* PhysicsShapePolygon::getPoints(Point* points) const return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } -int PhysicsShapePolygon::getPointsCount() const +long PhysicsShapePolygon::getPointsCount() const { return ((cpPolyShape*)_info->shapes.front())->numVerts; } @@ -715,7 +715,7 @@ Point PhysicsShapeEdgePolygon::getCenter() return _center; } -int PhysicsShapeEdgePolygon::getPointsCount() const +long PhysicsShapeEdgePolygon::getPointsCount() const { return _info->shapes.size() + 1; } @@ -776,7 +776,7 @@ Point PhysicsShapeEdgeChain::getCenter() return _center; } -int PhysicsShapeEdgeChain::getPointsCount() const +long PhysicsShapeEdgeChain::getPointsCount() const { return _info->shapes.size() + 1; } diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 31497d14a2..5bc1ca9dfa 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -50,10 +50,10 @@ typedef struct PhysicsMaterial , friction(0.0f) {} - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction) + PhysicsMaterial(float aDensity, float aRestitution, float aFriction) + : density(aDensity) + , restitution(aRestitution) + , friction(aFriction) {} }PhysicsMaterial; @@ -204,7 +204,7 @@ public: float calculateDefaultMoment() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; Point getCenter() override; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); @@ -247,7 +247,7 @@ public: static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); Point getOffset() override { return _offset; } Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); @@ -269,7 +269,7 @@ public: static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -291,7 +291,7 @@ public: static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; - int getPointsCount() const; + long getPointsCount() const; protected: bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1cd2b936c5..6b6e221571 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -465,9 +465,9 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) +void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joints) { - for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + for (auto it = joints->_info->joints.begin(); it != joints->_info->joints.end(); ++it) { cpConstraint *constraint = *it; @@ -526,9 +526,9 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) } } -void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) +void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shapes) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) + for (auto it = shapes->_info->shapes.begin(); it != shapes->_info->shapes.end(); ++it) { cpShape *shape = *it; From 25196072f264d6d85d46830c10708b739ded5819 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 11:57:20 +0800 Subject: [PATCH 396/557] 1. change color json format 2. fix tween easing 3. fix CCBone crate bug --- cocos/editor-support/cocostudio/CCArmature.h | 1 + .../cocostudio/CCArmatureDefine.h | 1 + cocos/editor-support/cocostudio/CCBone.cpp | 16 ++- .../cocostudio/CCDataReaderHelper.cpp | 130 ++++++++---------- .../cocostudio/CCDataReaderHelper.h | 22 +-- cocos/editor-support/cocostudio/CCDatas.h | 4 +- .../cocostudio/CCProcessBase.cpp | 2 +- .../editor-support/cocostudio/CCProcessBase.h | 2 +- cocos/editor-support/cocostudio/CCTween.cpp | 16 +-- cocos/editor-support/cocostudio/CCTween.h | 2 +- .../cocostudio/CCTweenFunction.cpp | 26 ++-- .../cocostudio/CCTweenFunction.h | 7 +- 12 files changed, 108 insertions(+), 121 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index bf11841f7e..b58591ae19 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -65,6 +65,7 @@ CC_DEPRECATED_ATTRIBUTE typedef Bone CCBone; CC_DEPRECATED_ATTRIBUTE typedef ArmatureAnimation CCArmatureAnimation; CC_DEPRECATED_ATTRIBUTE typedef Armature CCArmature; CC_DEPRECATED_ATTRIBUTE typedef ArmatureDataManager CCArmatureDataManager; +CC_DEPRECATED_ATTRIBUTE typedef TweenType CCTweenType; class Armature : public cocos2d::NodeRGBA, public cocos2d::BlendProtocol { diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index b3fca84e01..0691058417 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -30,6 +30,7 @@ THE SOFTWARE. #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f +#define VERSION_COLOR_READING 1.1f #ifndef AUTO_ADD_SPRITE_FRAME_NAME_PREFIX #define AUTO_ADD_SPRITE_FRAME_NAME_PREFIX 0 diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 3132acec79..faf4b0ee94 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -90,10 +90,7 @@ Bone::~Bone(void) CC_SAFE_DELETE(_displayManager); CC_SAFE_DELETE(_worldInfo); - if(_boneData) - { - _boneData->release(); - } + CC_SAFE_RELEASE_NULL(_boneData); CC_SAFE_RELEASE(_childArmature); } @@ -129,6 +126,9 @@ bool Bone::init(const char *name) CC_SAFE_DELETE(_worldInfo); _worldInfo = new BaseData(); + CC_SAFE_DELETE(_boneData); + _boneData = new CCBoneData(); + bRet = true; } while (0); @@ -140,8 +140,12 @@ void Bone::setBoneData(BoneData *boneData) { CCASSERT(NULL != boneData, "_boneData must not be NULL"); - _boneData = boneData; - _boneData->retain(); + if (_boneData != boneData) + { + CC_SAFE_RETAIN(boneData); + CC_SAFE_RELEASE(_boneData); + _boneData = boneData; + } _name = _boneData->name; _ZOrder = _boneData->zOrder; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index c64a469c71..7ff2117b41 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -140,12 +140,8 @@ namespace cocostudio { float s_PositionReadScale = 1; -float s_ContentScale = 1; -static float s_FlashToolVersion = VERSION_2_0; -static float s_CocoStudioVersion = VERSION_COMBINED; std::vector DataReaderHelper::_configFileList; -std::string DataReaderHelper::_basefilePath = ""; DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; @@ -188,6 +184,8 @@ void DataReaderHelper::loadData() // generate data info DataInfo *pDataInfo = new DataInfo(); pDataInfo->asyncStruct = pAsyncStruct; + pDataInfo->filename = pAsyncStruct->filename; + pDataInfo->baseFilePath = pAsyncStruct->baseFilePath; if (pAsyncStruct->configType == DragonBone_XML) { @@ -280,15 +278,16 @@ void DataReaderHelper::addDataFromFile(const char *filePath) //! find the base file path - _basefilePath = filePath; - size_t pos = _basefilePath.find_last_of("/"); + std::string basefilePath = filePath; + size_t pos = basefilePath.find_last_of("/"); + if (pos != std::string::npos) { - _basefilePath = _basefilePath.substr(0, pos + 1); + basefilePath = basefilePath.substr(0, pos + 1); } else { - _basefilePath = ""; + basefilePath = ""; } @@ -303,6 +302,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) DataInfo dataInfo; dataInfo.filename = filePathStr; dataInfo.asyncStruct = NULL; + dataInfo.baseFilePath = basefilePath; if (str.compare(".xml") == 0) { @@ -502,7 +502,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *root = document.RootElement(); CCASSERT(root, "XML error or XML is empty."); - root->QueryFloatAttribute(VERSION, &s_FlashToolVersion); + root->QueryFloatAttribute(VERSION, &dataInfo->flashToolVersion); /* @@ -512,7 +512,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *armatureXML = armaturesXML->FirstChildElement(ARMATURE); while(armatureXML) { - ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); + ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML, dataInfo); if (dataInfo->asyncStruct) { @@ -536,7 +536,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *animationXML = animationsXML->FirstChildElement(ANIMATION); while(animationXML) { - AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); + AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML, dataInfo); if (dataInfo->asyncStruct) { _dataReaderHelper->_addDataMutex.lock(); @@ -558,7 +558,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data tinyxml2::XMLElement *textureXML = texturesXML->FirstChildElement(SUB_TEXTURE); while(textureXML) { - TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); + TextureData *textureData = DataReaderHelper::decodeTexture(textureXML, dataInfo); if (dataInfo->asyncStruct) { @@ -574,7 +574,7 @@ void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *data } } -ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML) +ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo) { ArmatureData *armatureData = new ArmatureData(); armatureData->init(); @@ -606,7 +606,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML } } - BoneData *boneData = decodeBone(boneXML, parentXML); + BoneData *boneData = decodeBone(boneXML, parentXML, dataInfo); armatureData->addBoneData(boneData); boneData->release(); @@ -616,7 +616,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML return armatureData; } -BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml) +BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml, DataInfo *dataInfo) { BoneData *boneData = new BoneData(); boneData->init(); @@ -634,7 +634,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: tinyxml2::XMLElement *displayXML = boneXML->FirstChildElement(DISPLAY); while(displayXML) { - DisplayData *displayData = decodeBoneDisplay(displayXML); + DisplayData *displayData = decodeBoneDisplay(displayXML, dataInfo); boneData->addDisplayData(displayData); displayData->release(); @@ -644,7 +644,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: return boneData; } -DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML) +DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo) { int _isArmature = 0; @@ -687,7 +687,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM return displayData; } -AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML) +AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo) { AnimationData *aniData = new AnimationData(); @@ -701,7 +701,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation while( movementXML ) { - MovementData *movementData = decodeMovement(movementXML, armatureData); + MovementData *movementData = decodeMovement(movementXML, armatureData, dataInfo); aniData->addMovement(movementData); movementData->release(); @@ -712,7 +712,7 @@ AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animation return aniData; } -MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData) +MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo) { MovementData *movementData = new MovementData(); @@ -747,12 +747,12 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML { if( movementXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - movementData->tweenEasing = (CCTweenType)tweenEasing; + movementData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - movementData->tweenEasing = TWEEN_EASING_MAX; + movementData->tweenEasing = Linear; } } @@ -788,7 +788,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } } - MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData); + MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData, dataInfo); movementData->addMovementBoneData(moveBoneData); moveBoneData->release(); @@ -799,7 +799,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } -MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData) +MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo) { MovementBoneData *movBoneData = new MovementBoneData(); movBoneData->init(); @@ -874,7 +874,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } } - FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData); + FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData, dataInfo); movBoneData->addFrameData(frameData); frameData->release(); @@ -918,7 +918,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov return movBoneData; } -FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData) +FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo) { float x, y, scale_x, scale_y, skew_x, skew_y = 0; int duration, displayIndex, zOrder, tweenEasing, blendType = 0; @@ -944,7 +944,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { if(frameXML->QueryFloatAttribute(A_COCOS2DX_X, &x) == tinyxml2::XML_SUCCESS) { @@ -1037,12 +1037,12 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm { if( frameXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) { - frameData->tweenEasing = (CCTweenType)tweenEasing; + frameData->tweenEasing = tweenEasing == 2 ? Sine_EaseInOut : (TweenType)tweenEasing; } } else { - frameData->tweenEasing = TWEEN_EASING_MAX; + frameData->tweenEasing = Linear; } } @@ -1052,7 +1052,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm * recalculate frame data from parent frame data, use for translate matrix */ BaseData helpNode; - if (s_FlashToolVersion >= VERSION_2_0) + if (dataInfo->flashToolVersion >= VERSION_2_0) { parentFrameXml->QueryFloatAttribute(A_COCOS2DX_X, &helpNode.x); parentFrameXml->QueryFloatAttribute(A_COCOS2DX_Y, &helpNode.y); @@ -1076,7 +1076,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm return frameData; } -TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) +TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo) { TextureData *textureData = new TextureData(); textureData->init(); @@ -1088,7 +1088,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) float px, py, width, height = 0; - if(s_FlashToolVersion >= VERSION_2_0) + if(dataInfo->flashToolVersion >= VERSION_2_0) { textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_X, &px); textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_Y, &py); @@ -1112,7 +1112,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) while (contourXML) { - ContourData *contourData = decodeContour(contourXML); + ContourData *contourData = decodeContour(contourXML, dataInfo); textureData->addContourData(contourData); contourData->release(); @@ -1122,7 +1122,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) return textureData; } -ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) +ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo) { ContourData *contourData = new ContourData(); contourData->init(); @@ -1153,14 +1153,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d JsonDictionary json; json.initWithDescription(fileContent); - if (dataInfo->asyncStruct) - { - dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); - } - else - { - s_ContentScale = json.getItemFloatValue(CONTENT_SCALE, 1); - } + dataInfo->contentScale = json.getItemFloatValue(CONTENT_SCALE, 1); // Decode armatures int length = json.getArrayItemCount(ARMATURE_DATA); @@ -1248,7 +1241,7 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d std::string plistPath = filePath + ".plist"; std::string pngPath = filePath + ".png"; - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((_basefilePath + plistPath).c_str(), (_basefilePath + pngPath).c_str()); + ArmatureDataManager::getInstance()->addSpriteFrameFromFile((dataInfo->baseFilePath + plistPath).c_str(), (dataInfo->baseFilePath + pngPath).c_str()); } } } @@ -1265,7 +1258,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *d armatureData->name = name; } - s_CocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); + dataInfo->cocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); int length = json.getArrayItemCount(BONE_DATA); for (int i = 0; i < length; i++) @@ -1344,16 +1337,8 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - if (dataInfo->asyncStruct) - { - sdd->skinData.x *= dataInfo->contentScale; - sdd->skinData.y *= dataInfo->contentScale; - } - else - { - sdd->skinData.x *= s_ContentScale; - sdd->skinData.y *= s_ContentScale; - } + sdd->skinData.x *= dataInfo->contentScale; + sdd->skinData.y *= dataInfo->contentScale; delete dic; } @@ -1384,7 +1369,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo } else { - static_cast(displayData)->plist = _basefilePath + plist; + static_cast(displayData)->plist = dataInfo->baseFilePath + plist; } } } @@ -1435,7 +1420,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *d movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); movementData->duration = json.getItemIntValue(A_DURATION, 0); movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); - movementData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); const char *name = json.getItemStringValue(A_NAME); if(name != NULL) @@ -1479,7 +1464,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat movementBoneData->addFrameData(frameData); frameData->release(); - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->frameID = movementBoneData->duration; movementBoneData->duration += frameData->duration; @@ -1489,7 +1474,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat } - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) + if (dataInfo->cocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) { //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movementBoneData->frameList.data->arr; @@ -1513,7 +1498,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat } } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { if (movementBoneData->frameList.count() > 0) { @@ -1535,7 +1520,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf decodeNode(frameData, json, dataInfo); - frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); + frameData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); @@ -1546,7 +1531,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf frameData->strEvent = event; } - if (s_CocoStudioVersion < VERSION_COMBINED) + if (dataInfo->cocoStudioVersion < VERSION_COMBINED) { frameData->duration = json.getItemIntValue(A_DURATION, 1); } @@ -1617,17 +1602,8 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - if (dataInfo->asyncStruct) - { - node->x *= dataInfo->contentScale; - node->y *= dataInfo->contentScale; - } - else - { - node->x *= s_ContentScale; - node->y *= s_ContentScale; - } - + node->x *= dataInfo->contentScale; + node->y *= dataInfo->contentScale; node->zOrder = json.getItemIntValue(A_Z, 0); @@ -1636,7 +1612,15 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + JsonDictionary *colorDic = NULL; + if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) + { + colorDic = json.getSubItemFromArray(COLOR_INFO, 0); + } + else + { + colorDic = json.getSubDictionary(COLOR_INFO); + } if (colorDic) { diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index c2df44b512..82f551e52f 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -74,6 +74,9 @@ protected: std::queue configFileQueue; float contentScale; std::string filename; + std::string baseFilePath; + float flashToolVersion; + float cocoStudioVersion; } DataInfo; public: @@ -123,29 +126,29 @@ public: /** * Decode Armature Datas from xml export from Dragon Bone flash tool */ - static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML); - static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML); - static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML); + static ArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo); + static BoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML, DataInfo *dataInfo); + static DisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo); /** * Decode ArmatureAnimation Datas from xml export from Dragon Bone flash tool */ - static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML); - static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData); - static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData); - static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData); + static AnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo); + static MovementData *decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData, DataInfo *dataInfo); + static MovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData, DataInfo *dataInfo); + static FrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData, DataInfo *dataInfo); /** * Decode Texture Datas from xml export from Dragon Bone flash tool */ - static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML); + static TextureData *decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo); /** * Decode Contour Datas from xml export from Dragon Bone flash tool */ - static ContourData *decodeContour(tinyxml2::XMLElement *contourXML); + static ContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); public: static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); @@ -193,7 +196,6 @@ protected: std::queue *_asyncStructQueue; std::queue *_dataQueue; - static std::string _basefilePath; static std::vector _configFileList; static DataReaderHelper *_dataReaderHelper; diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 26128020cf..5f08757d13 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -341,7 +341,7 @@ public: public: int frameID; int duration; //! The frame will last duration frames - CCTweenType tweenEasing; //! Every frame's tween easing effect + TweenType tweenEasing; //! Every frame's tween easing effect bool isTween; //! Whether it's a tween key frame /** @@ -435,7 +435,7 @@ public: * Which tween easing effect the movement use * TWEEN_EASING_MAX : use the value from MovementData get from flash design panel */ - CCTweenType tweenEasing; + TweenType tweenEasing; /** * @brief save movment bone data diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index 1c9bd8965e..62bac419b6 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -89,7 +89,7 @@ void ProcessBase::play(void *animation, int durationTo, int durationTween, int * When changing end, m_iTotalFrames will be setted to _durationTween */ _nextFrameIndex = durationTo; - _tweenEasing = (CCTweenType)tweenEasing; + _tweenEasing = (TweenType)tweenEasing; } diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 77c5da4ebb..e59244433e 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -146,7 +146,7 @@ protected: CC_SYNTHESIZE(AnimationType, _loopType, LoopType); //! The tween easing effect - CC_SYNTHESIZE(CCTweenType, _tweenEasing, TweenEasing); + CC_SYNTHESIZE(TweenType, _tweenEasing, TweenEasing); //! The animation update speed CC_SYNTHESIZE(float, _animationInternal, AnimationInternal); diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 77f9a3b2ff..ce55cb4189 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -414,7 +414,7 @@ float Tween::updateFrameData(float currentPercent) { from = to = frames[0]; setBetween(from, to); - return currentPercent; + return _currentPercent; } if(playedTime >= frames[length - 1]->frameID) @@ -422,6 +422,8 @@ float Tween::updateFrameData(float currentPercent) // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. if (_passLastFrame) { + from = to = frames[length - 1]; + setBetween(from, to); return _currentPercent; } _passLastFrame = true; @@ -472,16 +474,10 @@ float Tween::updateFrameData(float currentPercent) /* * If frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ - - CCTweenType tweenType; - - if ( _frameTweenEasing != TWEEN_EASING_MAX) + TweenType tweenType = (_frameTweenEasing != Linear) ? _frameTweenEasing : _tweenEasing; + if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) { - tweenType = (_tweenEasing == TWEEN_EASING_MAX) ? _frameTweenEasing : _tweenEasing; - if (tweenType != TWEEN_EASING_MAX && tweenType != Linear) - { - currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); - } + currentPercent = TweenFunction::tweenTo(0, 1, currentPercent, 1, tweenType); } return currentPercent; diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 61213371e8..c4fc110334 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -131,7 +131,7 @@ protected: Bone *_bone; //! A weak reference to the Bone - CCTweenType _frameTweenEasing; //! Dedermine which tween effect current frame use + TweenType _frameTweenEasing; //! Dedermine which tween effect current frame use int _betweenDuration; //! Current key frame will last _betweenDuration frames int _totalDuration; diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.cpp b/cocos/editor-support/cocostudio/CCTweenFunction.cpp index 37b523fc79..74e4471768 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.cpp +++ b/cocos/editor-support/cocostudio/CCTweenFunction.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. namespace cocostudio { -float TweenFunction::tweenTo(float from, float change, float time, float duration, CCTweenType tweenType) +float TweenFunction::tweenTo(float from, float change, float time, float duration, TweenType tweenType) { float delta = 0; @@ -163,8 +163,8 @@ float TweenFunction::quadEaseOut(float t, float b, float c, float d) } float TweenFunction::quadEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t + b; --t; return -c / 2 * (t * (t - 2) - 1) + b; @@ -182,8 +182,8 @@ float TweenFunction::cubicEaseOut(float t, float b, float c, float d) } float TweenFunction::cubicEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; @@ -201,8 +201,8 @@ float TweenFunction::quartEaseOut(float t, float b, float c, float d) } float TweenFunction::quartEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; @@ -220,8 +220,8 @@ float TweenFunction::quintEaseOut(float t, float b, float c, float d) } float TweenFunction::quintEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return c / 2 * t * t * t * t * t + b; t -= 2; return c / 2 * (t * t * t * t * t + 2) + b; @@ -272,8 +272,8 @@ float TweenFunction::circEaseOut(float t, float b, float c, float d) } float TweenFunction::circEaseInOut(float t, float b, float c, float d) { - t /= d; - if ((t / 2) < 1) + t = t/d*2; + if ((t) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b; t -= 2; return c / 2 * (sqrt(1 - t * t) + 1) + b; @@ -323,8 +323,8 @@ float TweenFunction::elasticEaseInOut(float t, float b, float c, float d, float float s = 0; if (t == 0) return b; - t /= d; - if ((t / 2) == 2) + t = t/d*2; + if ((t) == 2) return b + c; if (!p) p = d * (.3 * 1.5); diff --git a/cocos/editor-support/cocostudio/CCTweenFunction.h b/cocos/editor-support/cocostudio/CCTweenFunction.h index 255d19d58e..ff7ad6016d 100644 --- a/cocos/editor-support/cocostudio/CCTweenFunction.h +++ b/cocos/editor-support/cocostudio/CCTweenFunction.h @@ -31,16 +31,15 @@ THE SOFTWARE. namespace cocostudio { -enum CCTweenType +enum TweenType { TWEEN_EASING_MIN = -1, Linear, Sine_EaseIn, - Sine_EaseInOut, Sine_EaseOut, - + Sine_EaseInOut, Quad_EaseIn, Quad_EaseOut, @@ -85,7 +84,7 @@ class TweenFunction { public: - static float tweenTo(float from, float change, float time, float duration, CCTweenType tweenType); + static float tweenTo(float from, float change, float time, float duration, TweenType tweenType); static float linear(float t, float b, float c, float d); From b076711b699b3b37ec44f014e017a3af440e670e Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 13:42:27 +0800 Subject: [PATCH 397/557] fix compile error --- cocos/editor-support/cocostudio/CCColliderDetector.cpp | 2 +- cocos/editor-support/cocostudio/CCColliderDetector.h | 7 +++---- .../CocoStudioArmatureTest/ArmatureScene.cpp | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index cceb1a9b72..21cf39e486 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -56,7 +56,7 @@ void ColliderFilter::updateShape(b2Fixture *fixture) } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT -ColliderFilter::ColliderFilter(cpCollisionType collisionType, cpGroup group) +ColliderFilter::ColliderFilter(uintptr_t collisionType, uintptr_t group) : _collisionType(collisionType) , _group(group) { diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index e2da724c80..0b9c058aa8 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -34,7 +34,6 @@ THE SOFTWARE. #if ENABLE_PHYSICS_CHIPMUNK_DETECT -#include "chipmunk.h" struct cpBody; struct cpShape; #elif ENABLE_PHYSICS_BOX2D_DETECT @@ -62,11 +61,11 @@ protected: CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); #elif ENABLE_PHYSICS_CHIPMUNK_DETECT public: - ColliderFilter(cpCollisionType collisionType = 0, cpGroup group = 0); + ColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); void updateShape(cpShape *shape); protected: - CC_SYNTHESIZE(cpCollisionType, _collisionType, CollisionType); - CC_SYNTHESIZE(cpGroup, _group, Group); + CC_SYNTHESIZE(uintptr_t, _collisionType, CollisionType); + CC_SYNTHESIZE(uintptr_t, _group, Group); #endif }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index a6dfd04092..0b662d9c15 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1008,7 +1008,8 @@ void TestColliderDetector::initWorld() cpSpaceAddBody(space, body); armature2->setBody(body); - armature2->setColliderFilter(&ColliderFilter(eEnemyTag)); + ColliderFilter filter = ColliderFilter(eEnemyTag); + armature2->setColliderFilter(&filter); cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); } From a3a2b0274ea24b89e0672d608ca24549578f6575 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 14:23:48 +0800 Subject: [PATCH 398/557] Updating submodule of bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index b6f97d9fc2..eb2dbfef01 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit b6f97d9fc2d3450426423583c7a6aaf4a366a99d +Subproject commit eb2dbfef01a1d43691f31386069b65c319e41e2c From 5cecc93c3ef0cf9ae5909700a4556dc76f11f29b Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 06:31:26 +0000 Subject: [PATCH 399/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 006193d9b4..56a3820b26 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 006193d9b4081c8af2b79be3cd9bcf90aedfdbae +Subproject commit 56a3820b2660d69ebd958838f515cd75f08eaf18 From b445f0824add0abfcc9a760ca1b029cc0275f249 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 15:09:51 +0800 Subject: [PATCH 400/557] issue #2868:Bind UI and Scene parser to lua by bindings-generator and add releated test samples --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/gui/UIHelper.h | 2 +- cocos/scripting/lua/bindings/CCLuaStack.cpp | 2 + .../luaScript/ExtensionTest/ArmatureTest.lua | 147 +++++------------- tools/bindings-generator | 2 +- tools/tolua/cocos2dx_extension.ini | 17 +- tools/tolua/cocos2dx_studio.ini | 67 ++++++++ tools/tolua/genbindings.sh | 8 +- 8 files changed, 117 insertions(+), 130 deletions(-) create mode 100644 tools/tolua/cocos2dx_studio.ini diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index ac519a56c8..b99b211450 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5a0361664f33af4303065c98da4b8d8e4efe48b4 \ No newline at end of file +ab3cbe9f9358e0c472a7775bb7087507f50892e9 \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index cab106d26a..2c477ea266 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -44,7 +44,7 @@ public: /** * Default destructor */ - ~UIHelper(); + virtual ~UIHelper(); //initializes state of UIHelper. void init(); diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index bad774b677..a0269bf318 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -54,6 +54,7 @@ extern "C" { #include "lua_cocos2dx_extension_manual.h" #include "lua_cocos2dx_deprecated.h" #include "lua_xml_http_request.h" +#include "lua_cocos2dx_studio_auto.hpp" namespace { int lua_print(lua_State * luastate) @@ -135,6 +136,7 @@ bool LuaStack::init(void) register_all_cocos2dx_deprecated(_state); register_cocos2dx_extension_CCBProxy(_state); tolua_opengl_open(_state); + register_all_cocos2dx_studio(_state); register_all_cocos2dx_manual(_state); register_all_cocos2dx_extension_manual(_state); register_all_cocos2dx_manual_deprecated(_state); diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua index 66a224d9e2..446854de11 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ArmatureTest.lua @@ -4,16 +4,15 @@ local scheduler = cc.Director:getInstance():getScheduler() local ArmatureTestIndex = { TEST_COCOSTUDIO_WITH_SKELETON = 1, - TEST_COCOSTUDIO_WITHOUT_SKELETON = 2, - TEST_DRAGON_BONES_2_0 = 3, - TEST_PERFORMANCE = 4, - TEST_CHANGE_ZORDER = 5, - TEST_ANIMATION_EVENT = 6, - TEST_PARTICLE_DISPLAY = 7, - TEST_USE_DIFFERENT_PICTURE = 8, - TEST_BOUDINGBOX = 9, - TEST_ANCHORPOINT = 10, - TEST_ARMATURE_NESTING = 11, + TEST_DRAGON_BONES_2_0 = 2, + TEST_PERFORMANCE = 3, + TEST_CHANGE_ZORDER = 4, + TEST_ANIMATION_EVENT = 5, + TEST_PARTICLE_DISPLAY = 6, + TEST_USE_DIFFERENT_PICTURE = 7, + TEST_BOUDINGBOX = 8, + TEST_ANCHORPOINT = 9, + TEST_ARMATURE_NESTING = 10, } local armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON @@ -31,13 +30,13 @@ function ArmatureTestScene.extend(target) end function ArmatureTestScene:runThisTest() - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") - cc.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/TestBone0.png", "armature/TestBone0.plist", "armature/TestBone.json") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Cowboy0.png", "armature/Cowboy0.plist", "armature/Cowboy.ExportJson") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/knight.png", "armature/knight.plist", "armature/knight.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/robot.png", "armature/robot.plist", "armature/robot.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml") + ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml") armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON self:addChild(restartArmatureTest()) @@ -59,7 +58,7 @@ function ArmatureTestScene.create() end function ArmatureTestScene.toMainMenuCallback() - cc.ArmatureDataManager:purgeArmatureSystem() + ccs.ArmatureDataManager:purgeArmatureSystem() end local ArmatureTestLayer = class("ArmatureTestLayer") @@ -72,8 +71,6 @@ end function ArmatureTestLayer.title(idx) if ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then return "Test Export From CocoStudio With Skeleton Effect" - elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITHOUT_SKELETON == idx then - return "Test Export From CocoStudio Without Skeleton Effect" elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then return "Test Export From DragonBones version 2.0" elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then @@ -209,7 +206,7 @@ function TestCSWithSkeleton.extend(target) end function TestCSWithSkeleton:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.2) armature:setAnchorPoint(cc.p(0.5, 0.5)) @@ -230,40 +227,6 @@ function TestCSWithSkeleton.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer) TestDragonBones20.__index = TestDragonBones20 @@ -278,7 +241,7 @@ function TestDragonBones20.extend(target) end function TestDragonBones20:onEnter() - local armature = cc.Armature:create("Dragon") + local armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(1) armature:getAnimation():setAnimationScale(0.4) armature:setScale(0.6) @@ -320,7 +283,7 @@ function TestPerformance.update(delta) TestPerformance.times = TestPerformance.times + delta if TestPerformance.times > 0.25 then TestPerformance.time = 0 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(50 + TestPerformance.armatureCount * 5, winSize.height / 2)) armature:setScale(0.6) @@ -363,40 +326,6 @@ function TestPerformance.create() return layer end -local TestCSWithoutSkeleton = class("TestCSWithoutSkeleton",ArmatureTestLayer) -TestCSWithoutSkeleton.__index = TestCSWithoutSkeleton - -function TestCSWithoutSkeleton.extend(target) - local t = tolua.getpeer(target) - if not t then - t = {} - tolua.setpeer(target, t) - end - setmetatable(t, TestCSWithoutSkeleton) - return target -end - -function TestCSWithoutSkeleton:onEnter() - local armature = cc.Armature:create("TestBone") - armature:getAnimation():playByIndex(0) - armature:setScale(0.2) - armature:setAnchorPoint(cc.p(0.5, 0.5)) - armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2)) - self:addChild(armature) -end - -function TestCSWithoutSkeleton.create() - local layer = TestCSWithoutSkeleton.extend(cc.Layer:create()) - - if nil ~= layer then - layer:createMenu() - layer:createToExtensionMenu() - layer:onEnter() - layer:creatTitleAndSubTitle(armatureSceneIdx) - end - return layer -end - local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer) TestChangeZorder.__index = TestChangeZorder TestChangeZorder.currentTag = -1 @@ -414,21 +343,21 @@ end function TestChangeZorder:onEnter() self.currentTag = -1 - local armature = cc.Armature:create("Knight_f/Knight") + local armature = ccs.Armature:create("Knight_f/Knight") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 )) armature:setScale(0.6) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("TestBone") + armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setScale(0.24) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) self.currentTag = self.currentTag + 1 self:addChild(armature, self.currentTag, self.currentTag) - armature = cc.Armature:create("Dragon") + armature = ccs.Armature:create("Dragon") armature:getAnimation():playByIndex(0) armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100)) armature:setScale(0.6) @@ -471,7 +400,7 @@ function TestAnimationEvent.extend(target) end function TestAnimationEvent:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():play("Fire") armature:setScaleX(-0.24) armature:setScaleY(0.24) @@ -511,25 +440,25 @@ function TestParticleDisplay:onEnter() self:setTouchEnabled(true) self.animationID = 0 - self.armature = cc.Armature:create("robot") + self.armature = ccs.Armature:create("robot") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(0.48) self:addChild(self.armature) - local displayData = cc.ParticleDisplayData:create() - displayData:setParam("Particles/SmallSun.plist") + local p1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") + local p2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist") - local bone = cc.Bone:create("p1") - bone:addDisplay(displayData, 0) + local bone = ccs.Bone:create("p1") + bone:addDisplay(p1, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a3") - bone = cc.Bone:create("p2") - bone:addDisplay(displayData, 0) + bone = ccs.Bone:create("p2") + bone:addDisplay(p2, 0) bone:changeDisplayByIndex(0, true) bone:setIgnoreMovementBoneData(true) bone:setZOrder(100) @@ -583,7 +512,7 @@ function TestUseMutiplePicture:onEnter() self:setTouchEnabled(true) self.displayIndex = 1 - self.armature = cc.Armature:create("Knight_f/Knight") + self.armature = ccs.Armature:create("Knight_f/Knight") self.armature:getAnimation():playByIndex(0) self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y)) self.armature:setScale(1.2) @@ -600,11 +529,10 @@ function TestUseMutiplePicture:onEnter() "weapon_f-hammer.png", }; - local spriteDisplayData = cc.SpriteDisplayData:create() local i = 1 for i = 1,table.getn(weapon) do - spriteDisplayData:setParam(weapon[i]) - self.armature:getBone("weapon"):addDisplay(spriteDisplayData, i - 1) + local skin = ccs.Skin:createWithSpriteFrameName(weapon[i]) + self.armature:getBone("weapon"):addDisplay(skin, i - 1) end local function onTouchBegan(x, y) @@ -649,7 +577,7 @@ function TestBoundingBox.extend(target) end function TestBoundingBox:onEnter() - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0) armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -685,7 +613,7 @@ end function TestAnchorPoint:onEnter() local i = 1 for i = 1 , 5 do - local armature = cc.Armature:create("Cowboy") + local armature = ccs.Armature:create("Cowboy") armature:getAnimation():playByIndex(0); armature:setPosition(VisibleRect:center()) armature:setScale(0.2) @@ -731,7 +659,7 @@ function TestArmatureNesting:onEnter() self:setTouchEnabled(true) self.weaponIndex = 0 - self.armature = cc.Armature:create("cyborg") + self.armature = ccs.Armature:create("cyborg") self.armature:getAnimation():playByIndex(1) self.armature:setPosition(VisibleRect:center()) self.armature:setScale(1.2) @@ -770,7 +698,6 @@ end local armatureSceneArr = { TestCSWithSkeleton.create, - TestCSWithoutSkeleton.create, TestDragonBones20.create, TestPerformance.create, TestChangeZorder.create, diff --git a/tools/bindings-generator b/tools/bindings-generator index b6f97d9fc2..d41959ab0b 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit b6f97d9fc2d3450426423583c7a6aaf4a366a99d +Subproject commit d41959ab0b15c20aa0802ab5c9ef92be7b742bd4 diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index dd5aa433aa..5940e44111 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -13,7 +13,8 @@ android_flags = -D_SIZE_T_DEFINED_ clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include clang_flags = -nostdinc -x c++ -std=c++11 -cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT cxxgenerator_headers = @@ -22,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h +headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ EditBox$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -47,16 +48,10 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*], - ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], - Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], - Skin::[getSkinData setSkinData], - ArmatureAnimation::[updateHandler updateFrameData frameEvent], - Bone::[(s|g)etIgnoreMovementBoneData] + ControlSwitchSprite::[*] -rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager], - ArmatureDataManager::[sharedArmatureDataManager=getInstance] +rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] rename_classes = CCBReader::_Reader, CCBAnimationManager::AnimationManager diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini new file mode 100644 index 0000000000..c30134f97d --- /dev/null +++ b/tools/tolua/cocos2dx_studio.ini @@ -0,0 +1,67 @@ +[cocos2dx_studio] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_studio + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = ccs + +android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include +android_flags = -D_SIZE_T_DEFINED_ + +clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include +clang_flags = -nostdinc -x c++ -std=c++11 + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath/include -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s + +cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT + +cxxgenerator_headers = + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h %(cocosdir)s/cocos/gui/CocosGUI.h + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWidget GUIRenderer Layout RectClippingNode UIRootWidget UIButton UICheckBox UIImageView UILabel UICCLabelAtlas UILabelAtlas UILoadingBar UIScrollView UISlider UICCTextField UITextField UIListView UIDragPanel UILabelBMFont UIPageView UIHelper UILayer + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener addEventListener], + ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], + Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], + Skin::[(s|g)etSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent], + Bone::[(s|g)etIgnoreMovementBoneData] + +rename_functions = ArmatureDataManager::[sharedArmatureDataManager=getInstance] + +rename_classes = + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Object ProcessBase + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = ArmatureDataManager + +# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. +script_control_cpp = no + diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index b236c43ae8..e6997542bf 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -78,9 +78,5 @@ echo -e "$_CONTENTS" > "$_CONF_INI_FILE" echo --- # Generate bindings for cocos2dx -echo "Generating bindings for cocos2dx..." -set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto - -echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto +echo "Generating bindings for cocos2dx_studio..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto From 3eef64c3b8d44adc58688c8a86921a2440983bd1 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 15:32:13 +0800 Subject: [PATCH 401/557] 1. Change NULL to null 2. Remove CocoStudio/Armature files --- .../editor-support/cocostudio/CCArmature.cpp | 88 +- cocos/editor-support/cocostudio/CCArmature.h | 2 +- .../cocostudio/CCArmatureAnimation.cpp | 36 +- .../cocostudio/CCArmatureAnimation.h | 4 +- .../cocostudio/CCArmatureDataManager.cpp | 16 +- .../cocostudio/CCArmatureDefine.h | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 24 +- cocos/editor-support/cocostudio/CCBone.cpp | 60 +- cocos/editor-support/cocostudio/CCBone.h | 2 +- .../cocostudio/CCColliderDetector.cpp | 54 +- .../cocostudio/CCDataReaderHelper.cpp | 76 +- .../cocostudio/CCDataReaderHelper.h | 4 +- cocos/editor-support/cocostudio/CCDatas.h | 4 +- .../cocostudio/CCDecorativeDisplay.cpp | 8 +- .../cocostudio/CCDisplayFactory.cpp | 4 +- .../cocostudio/CCDisplayManager.cpp | 28 +- cocos/editor-support/cocostudio/CCSkin.cpp | 16 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 4 +- cocos/editor-support/cocostudio/CCTween.cpp | 26 +- cocos/editor-support/cocostudio/CCTween.h | 2 +- extensions/CocoStudio/Armature/CCArmature.cpp | 785 -------- extensions/CocoStudio/Armature/CCBone.cpp | 401 ----- extensions/CocoStudio/Armature/CCBone.h | 199 --- .../Armature/display/CCDisplayManager.cpp | 396 ----- .../CocoStudio/Armature/display/CCSkin.cpp | 205 --- .../Armature/utils/CCArmatureDefine.cpp | 34 - .../Armature/utils/CCDataReaderHelper.cpp | 1582 ----------------- .../CocoStudioArmatureTest/ArmatureScene.cpp | 50 +- 28 files changed, 255 insertions(+), 3857 deletions(-) delete mode 100644 extensions/CocoStudio/Armature/CCArmature.cpp delete mode 100644 extensions/CocoStudio/Armature/CCBone.cpp delete mode 100644 extensions/CocoStudio/Armature/CCBone.h delete mode 100644 extensions/CocoStudio/Armature/display/CCDisplayManager.cpp delete mode 100644 extensions/CocoStudio/Armature/display/CCSkin.cpp delete mode 100644 extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp delete mode 100644 extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index baa56ddfb7..be5c9d0c33 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -49,7 +49,7 @@ Armature *Armature::create() return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } @@ -62,7 +62,7 @@ Armature *Armature::create(const char *name) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature *Armature::create(const char *name, Bone *parentBone) @@ -74,31 +74,31 @@ Armature *Armature::create(const char *name, Bone *parentBone) return armature; } CC_SAFE_DELETE(armature); - return NULL; + return nullptr; } Armature::Armature() - : _armatureData(NULL) - , _batchNode(NULL) - , _atlas(NULL) - , _parentBone(NULL) + : _armatureData(nullptr) + , _batchNode(nullptr) + , _atlas(nullptr) + , _parentBone(nullptr) , _armatureTransformDirty(true) - , _boneDic(NULL) - , _topBoneList(NULL) - , _animation(NULL) - , _textureAtlasDic(NULL) + , _boneDic(nullptr) + , _topBoneList(nullptr) + , _animation(nullptr) + , _textureAtlasDic(nullptr) { } Armature::~Armature(void) { - if(NULL != _boneDic) + if(nullptr != _boneDic) { _boneDic->removeAllObjects(); CC_SAFE_DELETE(_boneDic); } - if (NULL != _topBoneList) + if (nullptr != _topBoneList) { _topBoneList->removeAllObjects(); CC_SAFE_DELETE(_topBoneList); @@ -110,7 +110,7 @@ Armature::~Armature(void) bool Armature::init() { - return init(NULL); + return init(nullptr); } @@ -139,7 +139,7 @@ bool Armature::init(const char *name) _blendFunc.dst = CC_BLEND_DST; - _name = name == NULL ? "" : name; + _name = name == nullptr ? "" : name; ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance(); @@ -159,7 +159,7 @@ bool Armature::init(const char *name) _armatureData = armatureData; - DictElement *_element = NULL; + DictElement *_element = nullptr; Dictionary *boneDataDic = &armatureData->boneDataDic; CCDICT_FOREACH(boneDataDic, _element) { @@ -228,13 +228,13 @@ bool Armature::init(const char *name, Bone *parentBone) Bone *Armature::createBone(const char *boneName) { Bone *existedBone = getBone(boneName); - if(existedBone != NULL) + if(existedBone != nullptr) return existedBone; BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName); std::string parentName = boneData->parentName; - Bone *bone = NULL; + Bone *bone = nullptr; if( parentName.length() != 0 ) { @@ -257,10 +257,10 @@ Bone *Armature::createBone(const char *boneName) void Armature::addBone(Bone *bone, const char *parentName) { - CCASSERT( bone != NULL, "Argument must be non-nil"); - CCASSERT(_boneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again"); + CCASSERT( bone != nullptr, "Argument must be non-nil"); + CCASSERT(_boneDic->objectForKey(bone->getName()) == nullptr, "bone already added. It can't be added again"); - if (NULL != parentName) + if (nullptr != parentName) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); if (boneParent) @@ -286,9 +286,9 @@ void Armature::addBone(Bone *bone, const char *parentName) void Armature::removeBone(Bone *bone, bool recursion) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); - bone->setArmature(NULL); + bone->setArmature(nullptr); bone->removeFromParent(recursion); if (_topBoneList->containsObject(bone)) @@ -308,15 +308,15 @@ Bone *Armature::getBone(const char *name) const void Armature::changeBoneParent(Bone *bone, const char *parentName) { - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); + CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); if(bone->getParentBone()) { bone->getParentBone()->getChildren()->removeObject(bone); - bone->setParentBone(NULL); + bone->setParentBone(nullptr); } - if (parentName != NULL) + if (parentName != nullptr) { Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); @@ -451,7 +451,7 @@ void Armature::update(float dt) { _animation->update(dt); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_topBoneList, object) { static_cast(object)->update(dt); @@ -462,20 +462,20 @@ void Armature::update(float dt) void Armature::draw() { - if (_parentBone == NULL && _batchNode == NULL) + if (_parentBone == nullptr && _batchNode == nullptr) { CC_NODE_DRAW_SETUP(); GL::blendFunc(_blendFunc.src, _blendFunc.dst); } - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Node *node = bone->getDisplayRenderNode(); - if (NULL == node) + if (nullptr == node) continue; switch (bone->getDisplayRenderNodeType()) @@ -556,7 +556,7 @@ void Armature::draw() } } - if(_atlas && !_batchNode && _parentBone == NULL) + if(_atlas && !_batchNode && _parentBone == nullptr) { _atlas->drawQuads(); _atlas->removeAllQuads(); @@ -642,7 +642,7 @@ Rect Armature::getBoundingBox() const Rect boundingBox = Rect(0, 0, 0, 0); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) @@ -686,7 +686,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) return bs; } } - return NULL; + return nullptr; } TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) @@ -703,7 +703,7 @@ TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) } TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); - if (atlas == NULL) + if (atlas == nullptr) { atlas = TextureAtlas::createWithTexture(texture, 4); _textureAtlasDic->setObject(atlas, key); @@ -715,7 +715,7 @@ void Armature::setParentBone(Bone *parentBone) { _parentBone = parentBone; - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(_boneDic, element) { Bone *bone = static_cast(element->getObject()); @@ -730,7 +730,7 @@ Bone *Armature::getParentBone() void CCArmature::setColliderFilter(ColliderFilter *filter) { - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(_boneDic, element) { Bone *bone = static_cast(element->getObject()); @@ -754,18 +754,18 @@ void Armature::setBody(b2Body *body) _body = body; _body->SetUserData(this); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; + Object *displayObject = nullptr; CCARRAY_FOREACH(displayList, displayObject) { ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + if (detector != nullptr) { detector->setBody(_body); } @@ -782,7 +782,7 @@ b2Fixture *Armature::getShapeList() } else { - return NULL; + return nullptr; } } @@ -802,18 +802,18 @@ void Armature::setBody(cpBody *body) _body = body; _body->data = this; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = NULL; + Object *displayObject = nullptr; CCARRAY_FOREACH(displayList, displayObject) { ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) + if (detector != nullptr) { detector->setBody(_body); } @@ -830,7 +830,7 @@ cpShape *Armature::getShapeList() } else { - return NULL; + return nullptr; } } #endif diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index b58591ae19..9f6fc3331b 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -112,7 +112,7 @@ public: * Add a Bone to this Armature, * * @param bone The Bone you want to add to Armature - * @param parentName The parent Bone's name you want to add to . If it's NULL, then set Armature to its parent + * @param parentName The parent Bone's name you want to add to . If it's nullptr, then set Armature to its parent */ virtual void addBone(Bone *bone, const char *parentName); /** diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index ed6e383751..8f9c9252bd 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -43,24 +43,24 @@ ArmatureAnimation *ArmatureAnimation::create(Armature *armature) return pArmatureAnimation; } CC_SAFE_DELETE(pArmatureAnimation); - return NULL; + return nullptr; } ArmatureAnimation::ArmatureAnimation() - : _animationData(NULL) + : _animationData(nullptr) , _speedScale(1) - , _movementData(NULL) - , _armature(NULL) + , _movementData(nullptr) + , _armature(nullptr) , _movementID("") , _toIndex(0) - , _tweenList(NULL) + , _tweenList(nullptr) , _ignoreFrameEvent(false) - , _movementEventCallFunc(NULL) - , _frameEventCallFunc(NULL) - , _movementEventTarget(NULL) - , _frameEventTarget(NULL) + , _movementEventCallFunc(nullptr) + , _frameEventCallFunc(nullptr) + , _movementEventTarget(nullptr) + , _frameEventTarget(nullptr) { } @@ -94,7 +94,7 @@ bool ArmatureAnimation::init(Armature *armature) void ArmatureAnimation:: pause() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->pause(); @@ -104,7 +104,7 @@ void ArmatureAnimation:: pause() void ArmatureAnimation::resume() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->resume(); @@ -114,7 +114,7 @@ void ArmatureAnimation::resume() void ArmatureAnimation::stop() { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->stop(); @@ -145,7 +145,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -173,7 +173,7 @@ void ArmatureAnimation::setAnimationInternal(float animationInternal) _animationInternal = animationInternal; - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -232,10 +232,10 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura _durationTween = durationTween; } - MovementBoneData *movementBoneData = NULL; + MovementBoneData *movementBoneData = nullptr; _tweenList->removeAllObjects(); - DictElement *element = NULL; + DictElement *element = nullptr; Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) @@ -302,7 +302,7 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex) _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; _currentFrame = _nextFrameIndex * _currentPercent; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->gotoAndPlay(frameIndex); @@ -327,7 +327,7 @@ int ArmatureAnimation::getMovementCount() void ArmatureAnimation::update(float dt) { ProcessBase::update(dt); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_tweenList, object) { static_cast(object)->update(dt); diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 5fe23543bf..3c6e7e5a2c 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -182,13 +182,13 @@ public: /** * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ void setMovementEventCallFunc(cocos2d::Object *target, SEL_MovementEventCallFunc callFunc); /** * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index ca1945b418..c8278387ce 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -32,11 +32,11 @@ using namespace cocos2d; namespace cocostudio { -static ArmatureDataManager *s_sharedArmatureDataManager = NULL; +static ArmatureDataManager *s_sharedArmatureDataManager = nullptr; ArmatureDataManager *ArmatureDataManager::getInstance() { - if (s_sharedArmatureDataManager == NULL) + if (s_sharedArmatureDataManager == nullptr) { s_sharedArmatureDataManager = new ArmatureDataManager(); if (!s_sharedArmatureDataManager || !s_sharedArmatureDataManager->init()) @@ -56,9 +56,9 @@ void ArmatureDataManager::destoryInstance() ArmatureDataManager::ArmatureDataManager(void) { - _armarureDatas = NULL; - _animationDatas = NULL; - _textureDatas = NULL; + _armarureDatas = nullptr; + _animationDatas = nullptr; + _textureDatas = nullptr; _autoLoadSpriteFile = false; } @@ -156,7 +156,7 @@ void ArmatureDataManager::addArmatureData(const char *id, ArmatureData *armature ArmatureData *ArmatureDataManager::getArmatureData(const char *id) { - ArmatureData *armatureData = NULL; + ArmatureData *armatureData = nullptr; if (_armarureDatas) { armatureData = (ArmatureData *)_armarureDatas->objectForKey(id); @@ -187,7 +187,7 @@ void ArmatureDataManager::addAnimationData(const char *id, AnimationData *animat AnimationData *ArmatureDataManager::getAnimationData(const char *id) { - AnimationData *animationData = NULL; + AnimationData *animationData = nullptr; if (_animationDatas) { animationData = (AnimationData *)_animationDatas->objectForKey(id); @@ -219,7 +219,7 @@ void ArmatureDataManager::addTextureData(const char *id, TextureData *textureDat TextureData *ArmatureDataManager::getTextureData(const char *id) { - TextureData *textureData = NULL; + TextureData *textureData = nullptr; if (_textureDatas) { textureData = (TextureData *)_textureDatas->objectForKey(id); diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 0691058417..c79b58ff81 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -50,7 +50,7 @@ THE SOFTWARE. #endif #define CS_RETURN_IF(cond) if (cond) return -#define CS_RETURN_NULL_IF(cond) if (cond) return NULL; +#define CS_RETURN_NULL_IF(cond) if (cond) return nullptr; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index bb84576d66..d674d8487b 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -40,12 +40,12 @@ BatchNode *BatchNode::create() return batchNode; } CC_SAFE_DELETE(batchNode); - return NULL; + return nullptr; } BatchNode::BatchNode() - : _atlas(NULL) - , _textureAtlasDic(NULL) + : _atlas(nullptr) + , _textureAtlasDic(nullptr) { } @@ -79,18 +79,18 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) { Node::addChild(child, zOrder, tag); Armature *armature = dynamic_cast(child); - if (armature != NULL) + if (armature != nullptr) { armature->setBatchNode(this); Dictionary *dict = armature->getBoneDic(); - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(displayList, object) { DecorativeDisplay *display = static_cast(object); @@ -107,18 +107,18 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) void BatchNode::removeChild(Node* child, bool cleanup) { Armature *armature = dynamic_cast(child); - if (armature != NULL) + if (armature != nullptr) { - armature->setBatchNode(NULL); + armature->setBatchNode(nullptr); Dictionary *dict = armature->getBoneDic(); - DictElement *element = NULL; + DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(displayList, object) { DecorativeDisplay *display = static_cast(object); @@ -166,7 +166,7 @@ void BatchNode::visit() void BatchNode::draw() { CC_NODE_DRAW_SETUP(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { Armature *armature = dynamic_cast(object); @@ -193,7 +193,7 @@ TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) int key = texture->getName(); TextureAtlas *atlas = static_cast(_textureAtlasDic->objectForKey(key)); - if (atlas == NULL) + if (atlas == nullptr) { atlas = CCTextureAtlas::createWithTexture(texture, 4); _textureAtlasDic->setObject(atlas, key); diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index faf4b0ee94..45562f898e 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -43,7 +43,7 @@ Bone *Bone::create() return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } @@ -57,27 +57,27 @@ Bone *Bone::create(const char *name) return pBone; } CC_SAFE_DELETE(pBone); - return NULL; + return nullptr; } Bone::Bone() { - _tweenData = NULL; - _parentBone = NULL; - _armature = NULL; - _childArmature = NULL; - _boneData = NULL; - _tween = NULL; - _tween = NULL; - _children = NULL; - _displayManager = NULL; + _tweenData = nullptr; + _parentBone = nullptr; + _armature = nullptr; + _childArmature = nullptr; + _boneData = nullptr; + _tween = nullptr; + _tween = nullptr; + _children = nullptr; + _displayManager = nullptr; _ignoreMovementBoneData = false; _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); _boneTransformDirty = true; _blendType = BLEND_NORMAL; - _worldInfo = NULL; + _worldInfo = nullptr; - _armatureParentBone = NULL; + _armatureParentBone = nullptr; _dataVersion = 0; } @@ -97,7 +97,7 @@ Bone::~Bone(void) bool Bone::init() { - return Bone::init(NULL); + return Bone::init(nullptr); } @@ -107,7 +107,7 @@ bool Bone::init(const char *name) do { - if(NULL != name) + if(nullptr != name) { _name = name; } @@ -138,7 +138,7 @@ bool Bone::init(const char *name) void Bone::setBoneData(BoneData *boneData) { - CCASSERT(NULL != boneData, "_boneData must not be NULL"); + CCASSERT(nullptr != boneData, "_boneData must not be nullptr"); if (_boneData != boneData) { @@ -169,7 +169,7 @@ void Bone::setArmature(Armature *armature) } else { - _armatureParentBone = NULL; + _armatureParentBone = nullptr; } } @@ -229,7 +229,7 @@ void Bone::update(float delta) DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_children, object) { Bone *childBone = (Bone *)object; @@ -282,7 +282,7 @@ void Bone::updateColor() { Node *display = _displayManager->getDisplayRenderNode(); RGBAProtocol *protocol = dynamic_cast(display); - if(protocol != NULL) + if(protocol != nullptr) { protocol->setColor(Color3B(_displayedColor.r * _tweenData->r / 255, _displayedColor.g * _tweenData->g / 255, _displayedColor.b * _tweenData->b / 255)); protocol->setOpacity(_displayedOpacity * _tweenData->a / 255); @@ -304,8 +304,8 @@ void Bone::updateZOrder() void Bone::addChildBone(Bone *child) { - CCASSERT( NULL != child, "Argument must be non-nil"); - CCASSERT( NULL == child->_parentBone, "child already added. It can't be added again"); + CCASSERT( nullptr != child, "Argument must be non-nil"); + CCASSERT( nullptr == child->_parentBone, "child already added. It can't be added again"); if(!_children) { @@ -327,7 +327,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion) if(recursion) { Array *_ccbones = bone->_children; - Object *_object = NULL; + Object *_object = nullptr; CCARRAY_FOREACH(_ccbones, _object) { Bone *_ccBone = (Bone *)_object; @@ -335,9 +335,9 @@ void Bone::removeChildBone(Bone *bone, bool recursion) } } - bone->setParentBone(NULL); + bone->setParentBone(nullptr); - bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL); + bone->getDisplayManager()->setCurrentDecorativeDisplay(nullptr); _children->removeObject(bone); } @@ -345,7 +345,7 @@ void Bone::removeChildBone(Bone *bone, bool recursion) void Bone::removeFromParent(bool recursion) { - if (NULL != _parentBone) + if (nullptr != _parentBone) { _parentBone->removeChildBone(this, recursion); } @@ -365,9 +365,9 @@ void Bone::setChildArmature(Armature *armature) { if (_childArmature != armature) { - if (armature == NULL && _childArmature) + if (armature == nullptr && _childArmature) { - _childArmature->setParentBone(NULL); + _childArmature->setParentBone(nullptr); } CC_SAFE_RETAIN(armature); @@ -441,7 +441,7 @@ Array *Bone::getColliderBodyList() return detector->getColliderBodyList(); } } - return NULL; + return nullptr; } @@ -449,7 +449,7 @@ Array *Bone::getColliderBodyList() void Bone::setColliderFilter(ColliderFilter *filter) { Array *array = _displayManager->getDecorativeDisplayList(); - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(array, object) { DecorativeDisplay *decoDisplay = static_cast(object); @@ -468,7 +468,7 @@ ColliderFilter *Bone::getColliderFilter() return detector->getColliderFilter(); } } - return NULL; + return nullptr; } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 6edd3fe8cb..58a15c3987 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -102,7 +102,7 @@ public: * It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName). * * @param parent the parent bone. - * NULL : remove this bone from armature + * nullptr : remove this bone from armature */ void setParentBone(Bone *parent); diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index 21cf39e486..be587ecefb 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -70,7 +70,7 @@ void ColliderFilter::updateShape(cpShape *shape) #if ENABLE_PHYSICS_BOX2D_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _fixture(NULL) + : _fixture(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); @@ -84,7 +84,7 @@ ColliderBody::ColliderBody(ContourData *contourData) #elif ENABLE_PHYSICS_CHIPMUNK_DETECT ColliderBody::ColliderBody(ContourData *contourData) - : _shape(NULL) + : _shape(nullptr) , _contourData(contourData) { CC_SAFE_RETAIN(_contourData); @@ -127,7 +127,7 @@ ColliderDetector *ColliderDetector::create() return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector *ColliderDetector::create(Bone *bone) @@ -139,15 +139,15 @@ ColliderDetector *ColliderDetector::create(Bone *bone) return pColliderDetector; } CC_SAFE_DELETE(pColliderDetector); - return NULL; + return nullptr; } ColliderDetector::ColliderDetector() - : _colliderBodyList(NULL) - , _filter(NULL) + : _colliderBodyList(nullptr) + , _filter(nullptr) , _active(false) { - _body = NULL; + _body = nullptr; } ColliderDetector::~ColliderDetector() @@ -198,7 +198,7 @@ void ColliderDetector::addContourData(ContourData *contourData) void ColliderDetector::addContourDataList(Array *contourDataList) { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(contourDataList, object) { addContourData((ContourData *)object); @@ -207,7 +207,7 @@ void ColliderDetector::addContourDataList(Array *contourDataList) void ColliderDetector::removeContourData(ContourData *contourData) { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *body = (ColliderBody*)object; @@ -242,28 +242,28 @@ void ColliderDetector::setActive(bool active) } else { - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); _body->DestroyFixture(fixture); - colliderBody->setB2Fixture(NULL); + colliderBody->setB2Fixture(nullptr); } } } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT if (_body) { - Object *object = NULL; + Object *object = nullptr; if (_active) { CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - if(shape->space_private == NULL) + if(shape->space_private == nullptr) { cpSpaceAddShape(_body->space_private, shape); } @@ -275,7 +275,7 @@ void ColliderDetector::setActive(bool active) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); - if (shape->space_private != NULL) + if (shape->space_private != nullptr) { cpSpaceRemoveShape(_body->space_private, shape); } @@ -299,7 +299,7 @@ void ColliderDetector::setColliderFilter(ColliderFilter *filter) { *_filter = *filter; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; @@ -333,21 +333,21 @@ void ColliderDetector::updateTransform(AffineTransform &t) return; } - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); #if ENABLE_PHYSICS_BOX2D_DETECT - b2PolygonShape *shape = NULL; - if (_body != NULL) + b2PolygonShape *shape = nullptr; + if (_body != nullptr) { shape = (b2PolygonShape *)colliderBody->getB2Fixture()->GetShape(); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - cpPolyShape *shape = NULL; - if (_body != NULL) + cpPolyShape *shape = nullptr; + if (_body != nullptr) { shape = (cpPolyShape *)colliderBody->getShape(); } @@ -372,13 +372,13 @@ void ColliderDetector::updateTransform(AffineTransform &t) #endif #if ENABLE_PHYSICS_BOX2D_DETECT - if (shape != NULL) + if (shape != nullptr) { b2Vec2 &bv = shape->m_vertices[i]; bv.Set(helpPoint.x / PT_RATIO, helpPoint.y / PT_RATIO); } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - if (shape != NULL) + if (shape != nullptr) { cpVect v ; v.x = helpPoint.x; @@ -389,7 +389,7 @@ void ColliderDetector::updateTransform(AffineTransform &t) } #if ENABLE_PHYSICS_CHIPMUNK_DETECT - cpConvexHull(num, shape->verts, NULL, NULL, 0); + cpConvexHull(num, shape->verts, nullptr, nullptr, 0); for (int i = 0; i < num; i++) { cpVect b = shape->verts[(i + 1) % shape->numVerts]; @@ -408,14 +408,14 @@ void ColliderDetector::setBody(b2Body *pBody) { _body = pBody; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); const Array *array = &contourData->vertexList; - Object *object = NULL; + Object *object = nullptr; b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()]; @@ -439,7 +439,7 @@ void ColliderDetector::setBody(b2Body *pBody) b2Fixture *fixture = _body->CreateFixture(&fixtureDef); fixture->SetUserData(_bone); - if (colliderBody->getB2Fixture() != NULL) + if (colliderBody->getB2Fixture() != nullptr) { _body->DestroyFixture(colliderBody->getB2Fixture()); } @@ -459,7 +459,7 @@ void ColliderDetector::setBody(cpBody *pBody) { _body = pBody; - Object *object = NULL; + Object *object = nullptr; CCARRAY_FOREACH(_colliderBodyList, object) { ColliderBody *colliderBody = (ColliderBody *)object; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 7ff2117b41..50b59715c7 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -143,14 +143,14 @@ float s_PositionReadScale = 1; std::vector DataReaderHelper::_configFileList; -DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; +DataReaderHelper *DataReaderHelper::_dataReaderHelper = nullptr; //! Async load void DataReaderHelper::loadData() { - AsyncStruct *pAsyncStruct = NULL; + AsyncStruct *pAsyncStruct = nullptr; while (true) { @@ -202,12 +202,12 @@ void DataReaderHelper::loadData() _dataInfoMutex.unlock(); } - if( _asyncStructQueue != NULL ) + if( _asyncStructQueue != nullptr ) { delete _asyncStructQueue; - _asyncStructQueue = NULL; + _asyncStructQueue = nullptr; delete _dataQueue; - _dataQueue = NULL; + _dataQueue = nullptr; } } @@ -259,7 +259,7 @@ DataReaderHelper::~DataReaderHelper() if (_loadingThread) _loadingThread->join(); CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; + _dataReaderHelper = nullptr; } void DataReaderHelper::addDataFromFile(const char *filePath) @@ -301,7 +301,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) DataInfo dataInfo; dataInfo.filename = filePathStr; - dataInfo.asyncStruct = NULL; + dataInfo.asyncStruct = nullptr; dataInfo.baseFilePath = basefilePath; if (str.compare(".xml") == 0) @@ -354,7 +354,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *imagePath, const char *p // lazy init - if (_asyncStructQueue == NULL) + if (_asyncStructQueue == nullptr) { _asyncStructQueue = new std::queue(); _dataQueue = new std::queue(); @@ -591,7 +591,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML * If this bone have parent, then get the parent bone xml */ const char *parentName = boneXML->Attribute(A_PARENT); - tinyxml2::XMLElement *parentXML = NULL; + tinyxml2::XMLElement *parentXML = nullptr; if (parentName) { parentXML = armatureXML->FirstChildElement(BONE); @@ -624,7 +624,7 @@ BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2:: std::string name = boneXML->Attribute(A_NAME); boneData->name = name; - if( boneXML->Attribute(A_PARENT) != NULL ) + if( boneXML->Attribute(A_PARENT) != nullptr ) { boneData->parentName = boneXML->Attribute(A_PARENT); } @@ -671,7 +671,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXM } - if(displayXML->Attribute(A_NAME) != NULL ) + if(displayXML->Attribute(A_NAME) != nullptr ) { if(!_isArmature) { @@ -740,7 +740,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML } const char *_easing = movementXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) @@ -773,7 +773,7 @@ MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML std::string parentName = boneData->parentName; - tinyxml2::XMLElement *parentXml = NULL; + tinyxml2::XMLElement *parentXml = nullptr; if (parentName.length() != 0) { parentXml = movementXML->FirstChildElement(BONE); @@ -827,14 +827,14 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov int parentTotalDuration = 0; int currentDuration = 0; - tinyxml2::XMLElement *parentFrameXML = NULL; + tinyxml2::XMLElement *parentFrameXML = nullptr; std::vector parentXmlList; /* * get the parent frame xml list, we need get the origin data */ - if( parentXml != NULL ) + if( parentXml != nullptr ) { parentFrameXML = parentXml->FirstChildElement(FRAME); while (parentFrameXML) @@ -843,7 +843,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov parentFrameXML = parentFrameXML->NextSiblingElement(FRAME); } - parentFrameXML = NULL; + parentFrameXML = nullptr; length = parentXmlList.size(); } @@ -925,19 +925,19 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm FrameData *frameData = new FrameData(); - if(frameXML->Attribute(A_MOVEMENT) != NULL) + if(frameXML->Attribute(A_MOVEMENT) != nullptr) { frameData->strMovement = frameXML->Attribute(A_MOVEMENT); } - if(frameXML->Attribute(A_EVENT) != NULL) + if(frameXML->Attribute(A_EVENT) != nullptr) { frameData->strEvent = frameXML->Attribute(A_EVENT); } - if(frameXML->Attribute(A_SOUND) != NULL) + if(frameXML->Attribute(A_SOUND) != nullptr) { frameData->strSound = frameXML->Attribute(A_SOUND); } - if(frameXML->Attribute(A_SOUND_EFFECT) != NULL) + if(frameXML->Attribute(A_SOUND_EFFECT) != nullptr) { frameData->strSoundEffect = frameXML->Attribute(A_SOUND_EFFECT); } @@ -1030,7 +1030,7 @@ FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxm const char *_easing = frameXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) + if(_easing != nullptr) { std::string str = _easing; if(str.compare(FL_NAN) != 0) @@ -1081,7 +1081,7 @@ TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML, D TextureData *textureData = new TextureData(); textureData->init(); - if( textureXML->Attribute(A_NAME) != NULL) + if( textureXML->Attribute(A_NAME) != nullptr) { textureData->name = textureXML->Attribute(A_NAME); } @@ -1216,14 +1216,14 @@ void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *d } // Auto load sprite file - bool autoLoad = dataInfo->asyncStruct == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; + bool autoLoad = dataInfo->asyncStruct == nullptr ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; if (autoLoad) { length = json.getArrayItemCount(CONFIG_FILE_PATH); for (int i = 0; i < length; i++) { const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); - if (path == NULL) + if (path == nullptr) { CCLOG("load CONFIG_FILE_PATH error."); return; @@ -1253,7 +1253,7 @@ ArmatureData *DataReaderHelper::decodeArmature(JsonDictionary &json, DataInfo *d armatureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { armatureData->name = name; } @@ -1282,13 +1282,13 @@ BoneData *DataReaderHelper::decodeBone(JsonDictionary &json, DataInfo *dataInfo) decodeNode(boneData, json, dataInfo); const char *str = json.getItemStringValue(A_NAME); - if(str != NULL) + if(str != nullptr) { boneData->name = str; } str = json.getItemStringValue(A_PARENT); - if(str != NULL) + if(str != nullptr) { boneData->parentName = str; } @@ -1312,7 +1312,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo { DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; switch (displayType) { @@ -1321,13 +1321,13 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new SpriteDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((SpriteDisplayData *)displayData)->displayName = name; } JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); - if (dic != NULL) + if (dic != nullptr) { SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; @@ -1350,7 +1350,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new ArmatureDisplayData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { ((ArmatureDisplayData *)displayData)->displayName = name; } @@ -1361,7 +1361,7 @@ DisplayData *DataReaderHelper::decodeBoneDisplay(JsonDictionary &json, DataInfo displayData = new ParticleDisplayData(); const char *plist = json.getItemStringValue(A_PLIST); - if(plist != NULL) + if(plist != nullptr) { if (dataInfo->asyncStruct) { @@ -1391,7 +1391,7 @@ AnimationData *DataReaderHelper::decodeAnimation(JsonDictionary &json, DataInfo AnimationData *aniData = new AnimationData(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { aniData->name = name; } @@ -1423,7 +1423,7 @@ MovementData *DataReaderHelper::decodeMovement(JsonDictionary &json, DataInfo *d movementData->tweenEasing = (TweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementData->name = name; } @@ -1450,7 +1450,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(JsonDictionary &json, Dat movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { movementBoneData->name = name; } @@ -1526,7 +1526,7 @@ FrameData *DataReaderHelper::decodeFrame(JsonDictionary &json, DataInfo *dataInf frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); const char *event = json.getItemStringValue(A_EVENT); - if (event != NULL) + if (event != nullptr) { frameData->strEvent = event; } @@ -1549,7 +1549,7 @@ TextureData *DataReaderHelper::decodeTexture(JsonDictionary &json) textureData->init(); const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) + if(name != nullptr) { textureData->name = name; } @@ -1612,7 +1612,7 @@ void DataReaderHelper::decodeNode(BaseData *node, JsonDictionary &json, DataInfo node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - JsonDictionary *colorDic = NULL; + JsonDictionary *colorDic = nullptr; if (dataInfo->cocoStudioVersion < VERSION_COLOR_READING) { colorDic = json.getSubItemFromArray(COLOR_INFO, 0); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index 82f551e52f..33088e0043 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -119,7 +119,7 @@ public: * * @param xmlPath The cache of the xml */ - static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = NULL); + static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = nullptr); @@ -151,7 +151,7 @@ public: static ContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); public: - static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); + static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = nullptr); static ArmatureData *decodeArmature(JsonDictionary &json, DataInfo *dataInfo); static BoneData *decodeBone(JsonDictionary &json, DataInfo *dataInfo); diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 5f08757d13..4b9c2feca6 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -39,7 +39,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } #define CC_CREATE_NO_PARAM(varType)\ @@ -52,7 +52,7 @@ public: \ return var;\ }\ CC_SAFE_DELETE(var);\ - return NULL;\ + return nullptr;\ } namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp index e595ecbe0c..81cc4bc751 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.cpp @@ -37,16 +37,16 @@ DecorativeDisplay *DecorativeDisplay::create() return pDisplay; } CC_SAFE_DELETE(pDisplay); - return NULL; + return nullptr; } DecorativeDisplay::DecorativeDisplay() - : _display(NULL) - , _displayData(NULL) + : _display(nullptr) + , _displayData(nullptr) { #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - _colliderDetector = NULL; + _colliderDetector = nullptr; #endif } diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index b130428ab1..7f329ff3cc 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -133,7 +133,7 @@ void DisplayFactory::addSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisplay) { - Skin *skin = NULL; + Skin *skin = nullptr; SpriteDisplayData *displayData = (SpriteDisplayData *)decoDisplay->getDisplayData(); @@ -157,7 +157,7 @@ void DisplayFactory::createSpriteDisplay(Bone *bone, DecorativeDisplay *decoDisp decoDisplay->setDisplay(skin); - if (skin == NULL) + if (skin == nullptr) { return; } diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index bffcf80c64..5efa5510c7 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -41,19 +41,19 @@ DisplayManager *DisplayManager::create(Bone *bone) return pDisplayManager; } CC_SAFE_DELETE(pDisplayManager); - return NULL; + return nullptr; } DisplayManager::DisplayManager() - : _decoDisplayList(NULL) - , _displayRenderNode(NULL) + : _decoDisplayList(nullptr) + , _displayRenderNode(nullptr) , _displayType(CS_DISPLAY_MAX) - , _currentDecoDisplay(NULL) + , _currentDecoDisplay(nullptr) , _displayIndex(-1) , _forceChangeDisplay(false) , _visible(true) - , _bone(NULL) + , _bone(nullptr) { } @@ -91,7 +91,7 @@ bool DisplayManager::init(Bone *bone) void DisplayManager::addDisplay(DisplayData *displayData, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -115,7 +115,7 @@ void DisplayManager::addDisplay(DisplayData *displayData, int index) void DisplayManager::addDisplay(Node *display, int index) { - DecorativeDisplay *decoDisplay = NULL; + DecorativeDisplay *decoDisplay = nullptr; if( (index >= 0) && (index < _decoDisplayList->count()) ) { @@ -127,7 +127,7 @@ void DisplayManager::addDisplay(Node *display, int index) _decoDisplayList->addObject(decoDisplay); } - DisplayData *displayData = NULL; + DisplayData *displayData = nullptr; if (Skin *skin = dynamic_cast(display)) { skin->setBone(_bone); @@ -175,7 +175,7 @@ void DisplayManager::removeDisplay(int index) { if(index == _displayIndex) { - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); _displayIndex = -1; } @@ -206,7 +206,7 @@ void DisplayManager::changeDisplayByIndex(int index, bool force) if(_displayRenderNode) { _displayRenderNode->removeFromParentAndCleanup(true); - setCurrentDecorativeDisplay(NULL); + setCurrentDecorativeDisplay(nullptr); } return; } @@ -235,12 +235,12 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) } #endif - Node *displayRenderNode = _currentDecoDisplay == NULL ? NULL : _currentDecoDisplay->getDisplay(); + Node *displayRenderNode = _currentDecoDisplay == nullptr ? nullptr : _currentDecoDisplay->getDisplay(); if (_displayRenderNode) { - if (dynamic_cast(_displayRenderNode) != NULL) + if (dynamic_cast(_displayRenderNode) != nullptr) { - _bone->setChildArmature(NULL); + _bone->setChildArmature(nullptr); } _displayRenderNode->removeFromParentAndCleanup(true); _displayRenderNode->release(); @@ -310,7 +310,7 @@ void DisplayManager::initDisplayList(BoneData *boneData) CS_RETURN_IF(!boneData); - Object *object = NULL; + Object *object = nullptr; Array *displayDataList = &boneData->displayDataList; CCARRAY_FOREACH(displayDataList, object) { diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 5cb8483a95..b0496729f4 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -48,7 +48,7 @@ Skin *Skin::create() return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) @@ -60,7 +60,7 @@ Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin *Skin::create(const char *pszFileName) @@ -72,12 +72,12 @@ Skin *Skin::create(const char *pszFileName) return skin; } CC_SAFE_DELETE(skin); - return NULL; + return nullptr; } Skin::Skin() - : _bone(NULL) - , _armature(NULL) + : _bone(nullptr) + , _armature(nullptr) , _displayName("") { _skinTransform = AffineTransformIdentity; @@ -85,12 +85,12 @@ Skin::Skin() bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) { - CCAssert(pszSpriteFrameName != NULL, ""); + CCAssert(pszSpriteFrameName != nullptr, ""); SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); bool ret = true; - if (pFrame != NULL) + if (pFrame != nullptr) { ret = initWithSpriteFrame(pFrame); } @@ -188,7 +188,7 @@ void Skin::updateTransform() SET_VERTEX3F( _quad.tr.vertices, RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); } - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS + // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _textureAtlas->getTotalQuads()); diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index 68fa7ebfb5..d3e2b620fd 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -29,7 +29,7 @@ using namespace cocos2d; namespace cocostudio { -SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = NULL; +SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = nullptr; SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() { @@ -44,7 +44,7 @@ SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() void SpriteFrameCacheHelper::purge() { delete _spriteFrameCacheHelper; - _spriteFrameCacheHelper = NULL; + _spriteFrameCacheHelper = nullptr; } void SpriteFrameCacheHelper::addSpriteFrameFromFile(const char *plistPath, const char *imagePath) diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index ce55cb4189..75ff8bbb7e 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -43,24 +43,24 @@ Tween *Tween::create(Bone *bone) return pTween; } CC_SAFE_DELETE(pTween); - return NULL; + return nullptr; } Tween::Tween() - : _movementBoneData(NULL) - , _tweenData(NULL) - , _from(NULL) - , _to(NULL) - , _between(NULL) - , _bone(NULL) + : _movementBoneData(nullptr) + , _tweenData(nullptr) + , _from(nullptr) + , _to(nullptr) + , _between(nullptr) + , _bone(nullptr) , _frameTweenEasing(Linear) , _fromIndex(0) , _toIndex(0) - , _animation(NULL) + , _animation(nullptr) , _passLastFrame(false) { @@ -86,7 +86,7 @@ bool Tween::init(Bone *bone) _tweenData = _bone->getTweenData(); _tweenData->displayIndex = -1; - _animation = _bone->getArmature() != NULL ? _bone->getArmature()->getAnimation() : NULL; + _animation = _bone->getArmature() != nullptr ? _bone->getArmature()->getAnimation() : nullptr; bRet = true; } @@ -98,7 +98,7 @@ bool Tween::init(Bone *bone) void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing) { - ProcessBase::play(NULL, durationTo, durationTween, loop, tweenEasing); + ProcessBase::play(nullptr, durationTo, durationTween, loop, tweenEasing); if (loop) { @@ -354,7 +354,7 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) FrameData *Tween::tweenNodeTo(float percent, FrameData *node) { - node = node == NULL ? _tweenData : node; + node = node == nullptr ? _tweenData : node; if (!_from->isTween) { @@ -407,8 +407,8 @@ float Tween::updateFrameData(float currentPercent) int length = _movementBoneData->frameList.count(); FrameData **frames = (FrameData **)_movementBoneData->frameList.data->arr; - FrameData *from = NULL; - FrameData *to = NULL; + FrameData *from = nullptr; + FrameData *to = nullptr; if (playedTime < frames[0]->frameID) { diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index c4fc110334..ce08f2264e 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -108,7 +108,7 @@ protected: /** * According to the percent to calculate current FrameData with tween effect */ - virtual FrameData *tweenNodeTo(float percent, FrameData *node = NULL); + virtual FrameData *tweenNodeTo(float percent, FrameData *node = nullptr); /** * According to the percent to calculate current color with tween effect diff --git a/extensions/CocoStudio/Armature/CCArmature.cpp b/extensions/CocoStudio/Armature/CCArmature.cpp deleted file mode 100644 index c5709b0418..0000000000 --- a/extensions/CocoStudio/Armature/CCArmature.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCArmature.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCArmatureDefine.h" -#include "utils/CCDataReaderHelper.h" -#include "datas/CCDatas.h" -#include "display/CCSkin.h" - -#if ENABLE_PHYSICS_BOX2D_DETECT -#include "Box2D/Box2D.h" -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT -#include "chipmunk.h" -#endif - - -NS_CC_EXT_ARMATURE_BEGIN - -Armature *Armature::create() -{ - Armature *armature = new Armature(); - if (armature && armature->init()) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - - -Armature *Armature::create(const char *name) -{ - Armature *armature = new Armature(); - if (armature && armature->init(name)) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - -Armature *Armature::create(const char *name, Bone *parentBone) -{ - Armature *armature = new Armature(); - if (armature && armature->init(name, parentBone)) - { - armature->autorelease(); - return armature; - } - CC_SAFE_DELETE(armature); - return NULL; -} - -Armature::Armature() - : _armatureData(NULL) - , _batchNode(NULL) - , _atlas(NULL) - , _parentBone(NULL) - , _armatureTransformDirty(true) - , _boneDic(NULL) - , _topBoneList(NULL) - , _animation(NULL) -{ -} - - -Armature::~Armature(void) -{ - if(NULL != _boneDic) - { - _boneDic->removeAllObjects(); - CC_SAFE_DELETE(_boneDic); - } - if (NULL != _topBoneList) - { - _topBoneList->removeAllObjects(); - CC_SAFE_DELETE(_topBoneList); - } - CC_SAFE_DELETE(_animation); -} - - -bool Armature::init() -{ - return init(NULL); -} - - -bool Armature::init(const char *name) -{ - bool bRet = false; - do - { - removeAllChildren(); - - CC_SAFE_DELETE(_animation); - _animation = new ArmatureAnimation(); - _animation->init(this); - - CC_SAFE_DELETE(_boneDic); - _boneDic = new Dictionary(); - - CC_SAFE_DELETE(_topBoneList); - _topBoneList = new Array(); - _topBoneList->init(); - - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - - - _name = name == NULL ? "" : name; - - ArmatureDataManager *armatureDataManager = ArmatureDataManager::getInstance(); - - if(_name.length() != 0) - { - _name = name; - - AnimationData *animationData = armatureDataManager->getAnimationData(name); - CCASSERT(animationData, "AnimationData not exist! "); - - _animation->setAnimationData(animationData); - - - ArmatureData *armatureData = armatureDataManager->getArmatureData(name); - CCASSERT(armatureData, ""); - - _armatureData = armatureData; - - - DictElement *_element = NULL; - Dictionary *boneDataDic = &armatureData->boneDataDic; - CCDICT_FOREACH(boneDataDic, _element) - { - Bone *bone = createBone(_element->getStrKey()); - - //! init bone's Tween to 1st movement's 1st frame - do - { - - MovementData *movData = animationData->getMovement(animationData->movementNames.at(0).c_str()); - CC_BREAK_IF(!movData); - - MovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName().c_str()); - CC_BREAK_IF(!movBoneData || movBoneData->frameList.count() <= 0); - - FrameData *frameData = movBoneData->getFrameData(0); - CC_BREAK_IF(!frameData); - - bone->getTweenData()->copy(frameData); - bone->changeDisplayByIndex(frameData->displayIndex, false); - } - while (0); - } - - update(0); - updateOffsetPoint(); - } - else - { - _name = "new_armature"; - _armatureData = ArmatureData::create(); - _armatureData->name = _name; - - AnimationData *animationData = AnimationData::create(); - animationData->name = _name; - - armatureDataManager->addArmatureData(_name.c_str(), _armatureData); - armatureDataManager->addAnimationData(_name.c_str(), animationData); - - _animation->setAnimationData(animationData); - - } - - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - - unscheduleUpdate(); - scheduleUpdate(); - - setCascadeOpacityEnabled(true); - setCascadeColorEnabled(true); - - bRet = true; - } - while (0); - - return bRet; -} - -bool Armature::init(const char *name, Bone *parentBone) -{ - _parentBone = parentBone; - return init(name); -} - - -Bone *Armature::createBone(const char *boneName) -{ - Bone *existedBone = getBone(boneName); - if(existedBone != NULL) - return existedBone; - - BoneData *boneData = (BoneData *)_armatureData->getBoneData(boneName); - std::string parentName = boneData->parentName; - - Bone *bone = NULL; - - if( parentName.length() != 0 ) - { - createBone(parentName.c_str()); - bone = Bone::create(boneName); - addBone(bone, parentName.c_str()); - } - else - { - bone = Bone::create(boneName); - addBone(bone, ""); - } - - bone->setBoneData(boneData); - bone->getDisplayManager()->changeDisplayByIndex(-1, false); - - return bone; -} - - -void Armature::addBone(Bone *bone, const char *parentName) -{ - CCASSERT( bone != NULL, "Argument must be non-nil"); - CCASSERT(_boneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again"); - - if (NULL != parentName) - { - Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); - if (boneParent) - { - boneParent->addChildBone(bone); - } - else - { - _topBoneList->addObject(bone); - } - } - else - { - _topBoneList->addObject(bone); - } - - bone->setArmature(this); - - _boneDic->setObject(bone, bone->getName()); - addChild(bone); -} - - -void Armature::removeBone(Bone *bone, bool recursion) -{ - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); - - bone->setArmature(NULL); - bone->removeFromParent(recursion); - - if (_topBoneList->containsObject(bone)) - { - _topBoneList->removeObject(bone); - } - _boneDic->removeObjectForKey(bone->getName()); - removeChild(bone, true); -} - - -Bone *Armature::getBone(const char *name) const -{ - return (Bone *)_boneDic->objectForKey(name); -} - - -void Armature::changeBoneParent(Bone *bone, const char *parentName) -{ - CCASSERT(bone != NULL, "bone must be added to the bone dictionary!"); - - if(bone->getParentBone()) - { - bone->getParentBone()->getChildren()->removeObject(bone); - bone->setParentBone(NULL); - } - - if (parentName != NULL) - { - Bone *boneParent = (Bone *)_boneDic->objectForKey(parentName); - - if (boneParent) - { - boneParent->addChildBone(bone); - if (_topBoneList->containsObject(bone)) - { - _topBoneList->removeObject(bone); - } - } - else - { - _topBoneList->addObject(bone); - } - } -} - -Dictionary *Armature::getBoneDic() -{ - return _boneDic; -} - -const AffineTransform &Armature::getNodeToParentTransform() const -{ - if (_transformDirty) - { - _armatureTransformDirty = true; - - // Translate values - float x = _position.x; - float y = _position.y; - - if (_ignoreAnchorPointForPosition) - { - x += _anchorPointInPoints.x; - y += _anchorPointInPoints.y; - } - - // Rotation values - // Change rotation code to handle X and Y - // If we skew with the exact same value for both x and y then we're simply just rotating - float cx = 1, sx = 0, cy = 1, sy = 0; - if (_rotationX || _rotationY) - { - float radiansX = -CC_DEGREES_TO_RADIANS(_rotationX); - float radiansY = -CC_DEGREES_TO_RADIANS(_rotationY); - cx = cosf(radiansX); - sx = sinf(radiansX); - cy = cosf(radiansY); - sy = sinf(radiansY); - } - - // Add offset point - x += cy * _offsetPoint.x * _scaleX + -sx * _offsetPoint.y * _scaleY; - y += sy * _offsetPoint.x * _scaleX + cx * _offsetPoint.y * _scaleY; - - bool needsSkewMatrix = ( _skewX || _skewY ); - - // optimization: - // inline anchor point calculation if skew is not needed - // Adjusted transform calculation for rotational skew - if (! needsSkewMatrix && !_anchorPointInPoints.equals(Point::ZERO)) - { - x += cy * -_anchorPointInPoints.x * _scaleX + -sx * -_anchorPointInPoints.y * _scaleY; - y += sy * -_anchorPointInPoints.x * _scaleX + cx * -_anchorPointInPoints.y * _scaleY; - } - - - // Build Transform Matrix - // Adjusted transform calculation for rotational skew - _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); - - // XXX: Try to inline skew - // If skew is needed, apply skew and then anchor point - if (needsSkewMatrix) - { - AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); - _transform = AffineTransformConcat(skewMatrix, _transform); - - // adjust anchor point - if (!_anchorPointInPoints.equals(Point::ZERO)) - { - _transform = AffineTransformTranslate(_transform, -_anchorPointInPoints.x, -_anchorPointInPoints.y); - } - } - - if (_additionalTransformDirty) - { - _transform = AffineTransformConcat(_transform, _additionalTransform); - _additionalTransformDirty = false; - } - - _transformDirty = false; - } - - return _transform; -} - -void Armature::updateOffsetPoint() -{ - // Set contentsize and Calculate anchor point. - Rect rect = getBoundingBox(); - setContentSize(rect.size); - _offsetPoint = Point(-rect.origin.x, -rect.origin.y); - if (rect.size.width != 0 && rect.size.height != 0) - { - setAnchorPoint(Point(_offsetPoint.x / rect.size.width, _offsetPoint.y / rect.size.height)); - } -} - -void Armature::setAnimation(ArmatureAnimation *animation) -{ - _animation = animation; -} - -ArmatureAnimation *Armature::getAnimation() -{ - return _animation; -} - -bool Armature::getArmatureTransformDirty() -{ - return _armatureTransformDirty; -} - -void Armature::update(float dt) -{ - _animation->update(dt); - - Object *object = NULL; - CCARRAY_FOREACH(_topBoneList, object) - { - static_cast(object)->update(dt); - } - - _armatureTransformDirty = false; -} - -void Armature::draw() -{ - if (_parentBone == NULL) - { - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - DisplayManager *displayManager = bone->getDisplayManager(); - Node *node = displayManager->getDisplayRenderNode(); - - if (NULL == node) - continue; - - switch (displayManager->getCurrentDecorativeDisplay()->getDisplayData()->displayType) - { - case CS_DISPLAY_SPRITE: - { - Skin *skin = static_cast(node); - - TextureAtlas *textureAtlas = skin->getTextureAtlas(); - BlendType blendType = bone->getBlendType(); - if(_atlas != textureAtlas || blendType != BLEND_NORMAL) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - } - - _atlas = textureAtlas; - if (_atlas->getCapacity() == _atlas->getTotalQuads() && !_atlas->resizeCapacity(_atlas->getCapacity() * 2)) - return; - - skin->updateTransform(); - - if (blendType != BLEND_NORMAL) - { - updateBlendType(blendType); - _atlas->drawQuads(); - _atlas->removeAllQuads(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - } - break; - case CS_DISPLAY_ARMATURE: - { - Armature *armature = static_cast(node); - - TextureAtlas *textureAtlas = armature->getTextureAtlas(); - if(_atlas != textureAtlas) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - } - armature->draw(); - - _atlas = armature->getTextureAtlas(); - } - break; - default: - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - node->visit(); - - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - break; - } - } - else if(Node *node = dynamic_cast(object)) - { - if (_atlas) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } - node->visit(); - - CC_NODE_DRAW_SETUP(); - GL::blendFunc(_blendFunc.src, _blendFunc.dst); - } - } - - if(_atlas && !_batchNode && _parentBone == NULL) - { - _atlas->drawQuads(); - _atlas->removeAllQuads(); - } -} - - -void Armature::updateBlendType(BlendType blendType) -{ - BlendFunc blendFunc; - switch (blendType) - { - case BLEND_NORMAL: - { - blendFunc.src = CC_BLEND_SRC; - blendFunc.dst = CC_BLEND_DST; - } - break; - case BLEND_ADD: - { - blendFunc.src = GL_SRC_ALPHA; - blendFunc.dst = GL_ONE; - } - break; - case BLEND_MULTIPLY: - { - blendFunc.src = GL_DST_COLOR; - blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA; - } - break; - case BLEND_SCREEN: - { - blendFunc.src = GL_ONE; - blendFunc.dst = GL_ONE_MINUS_SRC_COLOR; - } - break; - default: - { - blendFunc.src = CC_BLEND_SRC; - blendFunc.dst = CC_BLEND_DST; - } - break; - } - GL::blendFunc(blendFunc.src, blendFunc.dst); -} - - - -void Armature::visit() -{ - // quick return if not visible. children won't be drawn. - if (!_visible) - { - return; - } - kmGLPushMatrix(); - - if (_grid && _grid->isActive()) - { - _grid->beforeDraw(); - } - - transform(); - sortAllChildren(); - draw(); - updateEventPriorityIndex(); - - // reset for next frame - _orderOfArrival = 0; - - if (_grid && _grid->isActive()) - { - _grid->afterDraw(this); - } - - kmGLPopMatrix(); -} - -Rect Armature::getBoundingBox() const -{ - float minx, miny, maxx, maxy = 0; - - bool first = true; - - Rect boundingBox = Rect(0, 0, 0, 0); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Rect r = bone->getDisplayManager()->getBoundingBox(); - - if(first) - { - minx = r.getMinX(); - miny = r.getMinY(); - maxx = r.getMaxX(); - maxy = r.getMaxY(); - - first = false; - } - else - { - minx = r.getMinX() < boundingBox.getMinX() ? r.getMinX() : boundingBox.getMinX(); - miny = r.getMinY() < boundingBox.getMinY() ? r.getMinY() : boundingBox.getMinY(); - maxx = r.getMaxX() > boundingBox.getMaxX() ? r.getMaxX() : boundingBox.getMaxX(); - maxy = r.getMaxY() > boundingBox.getMaxY() ? r.getMaxY() : boundingBox.getMaxY(); - } - - boundingBox.setRect(minx, miny, maxx - minx, maxy - miny); - } - } - - return boundingBox; -} - -Bone *Armature::getBoneAtPoint(float x, float y) -{ - int length = _children->count(); - Bone *bs; - - for(int i = length - 1; i >= 0; i--) - { - bs = static_cast( _children->getObjectAtIndex(i) ); - if(bs->getDisplayManager()->containPoint(x, y)) - { - return bs; - } - } - return NULL; -} - -#if ENABLE_PHYSICS_BOX2D_DETECT -b2Body *Armature::getBody() -{ - return _body; -} - -void Armature::setBody(b2Body *body) -{ - if (_body == body) - { - return; - } - - _body = body; - _body->SetUserData(this); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) - { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) - { - detector->setBody(_body); - } - } - } - } -} - -b2Fixture *Armature::getShapeList() -{ - if (_body) - { - return _body->GetFixtureList(); - } - else - { - return NULL; - } -} - -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT -cpBody *Armature::getBody() -{ - return _body; -} - -void Armature::setBody(cpBody *body) -{ - if (_body == body) - { - return; - } - - _body = body; - _body->data = this; - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - if (Bone *bone = dynamic_cast(object)) - { - Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - - Object *displayObject = NULL; - CCARRAY_FOREACH(displayList, displayObject) - { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); - if (detector != NULL) - { - detector->setBody(_body); - } - } - } - } -} - -cpShape *Armature::getShapeList() -{ - if (_body) - { - return _body->shapeList_private; - } - else - { - return NULL; - } -} -#endif - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/CCBone.cpp b/extensions/CocoStudio/Armature/CCBone.cpp deleted file mode 100644 index d9ad2bfdc7..0000000000 --- a/extensions/CocoStudio/Armature/CCBone.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCBone.h" -#include "CCArmature.h" -#include "utils/CCUtilMath.h" -#include "utils/CCArmatureDataManager.h" -#include "utils/CCTransformHelp.h" -#include "display/CCDisplayManager.h" - -NS_CC_EXT_ARMATURE_BEGIN - -Bone *Bone::create() -{ - - Bone *pBone = new Bone(); - if (pBone && pBone->init()) - { - pBone->autorelease(); - return pBone; - } - CC_SAFE_DELETE(pBone); - return NULL; - -} - -Bone *Bone::create(const char *name) -{ - - Bone *pBone = new Bone(); - if (pBone && pBone->init(name)) - { - pBone->autorelease(); - return pBone; - } - CC_SAFE_DELETE(pBone); - return NULL; -} - -Bone::Bone() -{ - _tweenData = NULL; - _parentBone = NULL; - _armature = NULL; - _childArmature = NULL; - _boneData = NULL; - _tween = NULL; - _tween = NULL; - _children = NULL; - _displayManager = NULL; - _ignoreMovementBoneData = false; - _worldTransform = AffineTransformMake(1, 0, 0, 1, 0, 0); - _boneTransformDirty = true; - _blendType = BLEND_NORMAL; -} - - -Bone::~Bone(void) -{ - CC_SAFE_DELETE(_tweenData); - CC_SAFE_DELETE(_children); - CC_SAFE_DELETE(_tween); - CC_SAFE_DELETE(_displayManager); - - if(_boneData) - { - _boneData->release(); - } - - CC_SAFE_RELEASE(_childArmature); -} - -bool Bone::init() -{ - return Bone::init(NULL); -} - - -bool Bone::init(const char *name) -{ - bool bRet = false; - do - { - - if(NULL != name) - { - _name = name; - } - - CC_SAFE_DELETE(_tweenData); - _tweenData = new FrameData(); - - CC_SAFE_DELETE(_tween); - _tween = new Tween(); - _tween->init(this); - - CC_SAFE_DELETE(_displayManager); - _displayManager = new DisplayManager(); - _displayManager->init(this); - - - bRet = true; - } - while (0); - - return bRet; -} - -void Bone::setBoneData(BoneData *boneData) -{ - CCASSERT(NULL != boneData, "_boneData must not be NULL"); - - _boneData = boneData; - _boneData->retain(); - - _name = _boneData->name; - _ZOrder = _boneData->zOrder; - - _displayManager->initDisplayList(boneData); -} - -BoneData *Bone::getBoneData() -{ - return _boneData; -} - -void Bone::setArmature(Armature *armature) -{ - _armature = armature; - if (_armature) - { - _tween->setAnimation(_armature->getAnimation()); - } -} - - -Armature *Bone::getArmature() -{ - return _armature; -} - -void Bone::update(float delta) -{ - if (_parentBone) - _boneTransformDirty = _boneTransformDirty || _parentBone->isTransformDirty(); - - CCBone *armatureParentBone = _armature->getParentBone(); - if (armatureParentBone && !_boneTransformDirty) - { - _boneTransformDirty = armatureParentBone->isTransformDirty(); - } - - - if (_boneTransformDirty) - { - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) - { - TransformHelp::nodeConcat(*_tweenData, *_boneData); - _tweenData->scaleX -= 1; - _tweenData->scaleY -= 1; - } - - TransformHelp::nodeToMatrix(*_tweenData, _worldTransform); - - _worldTransform = AffineTransformConcat(getNodeToParentTransform(), _worldTransform); - - if(_parentBone) - { - _worldTransform = AffineTransformConcat(_worldTransform, _parentBone->_worldTransform); - } - else - { - if (armatureParentBone) - { - _worldTransform = CCAffineTransformConcat(_worldTransform, armatureParentBone->getNodeToArmatureTransform()); - } - } - } - - DisplayFactory::updateDisplay(this, _displayManager->getCurrentDecorativeDisplay(), delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - - Object *object = NULL; - CCARRAY_FOREACH(_children, object) - { - Bone *childBone = (Bone *)object; - childBone->update(delta); - } - - _boneTransformDirty = false; -} - - -void Bone::updateDisplayedColor(const Color3B &parentColor) -{ - _realColor = Color3B(255, 255, 255); - NodeRGBA::updateDisplayedColor(parentColor); - updateColor(); -} - -void Bone::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _realOpacity = 255; - NodeRGBA::updateDisplayedOpacity(parentOpacity); - updateColor(); -} - -void Bone::setColor(const Color3B &color) -{ - CCNodeRGBA::setColor(color); - updateColor(); -} -void Bone::setOpacity(GLubyte opacity) -{ - CCNodeRGBA::setOpacity(opacity); - updateColor(); -} - -void Bone::updateColor() -{ - Node *display = _displayManager->getDisplayRenderNode(); - RGBAProtocol *protocol = dynamic_cast(display); - if(protocol != NULL) - { - protocol->setColor(Color3B(_displayedColor.r * _tweenData->r / 255, _displayedColor.g * _tweenData->g / 255, _displayedColor.b * _tweenData->b / 255)); - protocol->setOpacity(_displayedOpacity * _tweenData->a / 255); - } -} - -void Bone::updateZOrder() -{ - if (_armature->getArmatureData()->dataVersion >= VERSION_COMBINED) - { - int zorder = _tweenData->zOrder + _boneData->zOrder; - setZOrder(zorder); - } - else - { - setZOrder(_tweenData->zOrder); - } -} - -void Bone::addChildBone(Bone *child) -{ - CCASSERT( NULL != child, "Argument must be non-nil"); - CCASSERT( NULL == child->_parentBone, "child already added. It can't be added again"); - - if(!_children) - { - _children = Array::createWithCapacity(4); - _children->retain(); - } - - if (_children->getIndexOfObject(child) == UINT_MAX) - { - _children->addObject(child); - child->setParentBone(this); - } -} - -void Bone::removeChildBone(Bone *bone, bool recursion) -{ - if ( _children->getIndexOfObject(bone) != UINT_MAX ) - { - if(recursion) - { - Array *_ccbones = bone->_children; - Object *_object = NULL; - CCARRAY_FOREACH(_ccbones, _object) - { - Bone *_ccBone = (Bone *)_object; - bone->removeChildBone(_ccBone, recursion); - } - } - - bone->setParentBone(NULL); - - bone->getDisplayManager()->setCurrentDecorativeDisplay(NULL); - - _children->removeObject(bone); - } -} - -void Bone::removeFromParent(bool recursion) -{ - if (NULL != _parentBone) - { - _parentBone->removeChildBone(this, recursion); - } -} - -void Bone::setParentBone(Bone *parent) -{ - _parentBone = parent; -} - -Bone *Bone::getParentBone() -{ - return _parentBone; -} - -void Bone::setChildArmature(Armature *armature) -{ - if (_childArmature != armature) - { - CC_SAFE_RETAIN(armature); - CC_SAFE_RELEASE(_childArmature); - _childArmature = armature; - } -} - -Armature *Bone::getChildArmature() -{ - return _childArmature; -} - -Tween *Bone::getTween() -{ - return _tween; -} - -void Bone::setZOrder(int zOrder) -{ - if (_ZOrder != zOrder) - Node::setZOrder(zOrder); -} - -void Bone::setTransformDirty(bool dirty) -{ - _boneTransformDirty = dirty; -} - -bool Bone::isTransformDirty() -{ - return _boneTransformDirty; -} - -AffineTransform Bone::getNodeToArmatureTransform() const -{ - return _worldTransform; -} - -AffineTransform Bone::getNodeToWorldTransform() const -{ - return AffineTransformConcat(_worldTransform, _armature->getNodeToWorldTransform()); -} - -Node *Bone::getDisplayRenderNode() -{ - return _displayManager->getDisplayRenderNode(); -} - -void Bone::addDisplay(DisplayData *displayData, int index) -{ - _displayManager->addDisplay(displayData, index); -} - -void Bone::addDisplay(Node *display, int index) -{ - _displayManager->addDisplay(display, index); -} - -void Bone::changeDisplayByIndex(int index, bool force) -{ - _displayManager->changeDisplayByIndex(index, force); -} - -Array *Bone::getColliderBodyList() -{ - if (DecorativeDisplay *decoDisplay = _displayManager->getCurrentDecorativeDisplay()) - { - if (ColliderDetector *detector = decoDisplay->getColliderDetector()) - { - return detector->getColliderBodyList(); - } - } - return NULL; -} - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/CCBone.h b/extensions/CocoStudio/Armature/CCBone.h deleted file mode 100644 index 1aecfcb099..0000000000 --- a/extensions/CocoStudio/Armature/CCBone.h +++ /dev/null @@ -1,199 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCBONE_H__ -#define __CCBONE_H__ - -#include "utils/CCArmatureDefine.h" -#include "datas/CCDatas.h" -#include "animation/CCTween.h" -#include "display/CCDecorativeDisplay.h" -#include "display/CCDisplayManager.h" - -NS_CC_EXT_ARMATURE_BEGIN - - -class Armature; - -class Bone : public NodeRGBA -{ -public: - /** - * Allocates and initializes a bone. - * @return A initialized bone which is marked as "autorelease". - */ - static Bone *create(); - /** - * Allocates and initializes a bone. - * - * @param name If name is not null, then set name to the bone's name - * @return A initialized bone which is marked as "autorelease". - */ - static Bone *create(const char *name); - -public: - Bone(); - /** - * @js NA - * @lua NA - */ - virtual ~Bone(void); - - /** - * Initializes an empty Bone with nothing init. - */ - virtual bool init(); - - /** - * Initializes a Bone with the specified name - * @param name Bone's name. - */ - virtual bool init(const char *name); - - /** - * Add display and use displayData to init the display. - * If index already have a display, then replace it. - * If index is current display index, then also change display to _index - * - * @param displayData it include the display information, like DisplayType. - * If you want to create a sprite display, then create a SpriteDisplayData param - * - * @param index the index of the display you want to replace or add to - * -1 : append display from back - */ - void addDisplay(DisplayData *displayData, int index); - - void addDisplay(Node *display, int index); - - void changeDisplayByIndex(int index, bool force); - - /** - * Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's parent - * @param child the child you want to add - */ - void addChildBone(Bone *child); - - /** - * Set parent bone. - * If parent is NUll, then also remove this bone from armature. - * It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName). - * - * @param parent the parent bone. - * NULL : remove this bone from armature - */ - void setParentBone(Bone *parent); - - /** - * Get parent bone - * @return parent bone - */ - Bone *getParentBone(); - - /** - * Remove itself from its parent. - * @param recursion whether or not to remove childBone's display - */ - void removeFromParent(bool recursion); - - /** - * Removes a child Bone - * @param bone the bone you want to remove - */ - void removeChildBone(Bone *bone, bool recursion); - - void update(float delta) override; - - virtual void updateDisplayedColor(const Color3B &parentColor) override; - virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; - - virtual void setColor(const Color3B& color) override; - virtual void setOpacity(GLubyte opacity) override; - - //! Update color to render display - virtual void updateColor(); - - //! Update zorder - virtual void updateZOrder(); - - virtual void setZOrder(int zOrder) override; - - Tween *getTween(); - - /* - * Whether or not the bone's transform property changed. if true, the bone will update the transform. - */ - virtual void setTransformDirty(bool dirty); - - virtual bool isTransformDirty(); - - virtual AffineTransform getNodeToArmatureTransform() const; - virtual AffineTransform getNodeToWorldTransform() const override; - - Node *getDisplayRenderNode(); - - /* - * Get the ColliderBody list in this bone. The object in the Array is ColliderBody. - */ - virtual Array *getColliderBodyList(); - -public: - /* - * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData - * when call setData function, it will copy from the BoneData. - */ - CC_PROPERTY(BoneData *, _boneData, BoneData); - - //! A weak reference to the Armature - CC_PROPERTY(Armature *, _armature, Armature); - - //! A weak reference to the child Armature - CC_PROPERTY(Armature *, _childArmature, ChildArmature); - - CC_SYNTHESIZE(DisplayManager *, _displayManager, DisplayManager) - - /* - * When Armature play an animation, if there is not a MovementBoneData of this bone in this MovementData, this bone will be hidden. - * Set IgnoreMovementBoneData to true, then this bone will also be shown. - */ - CC_SYNTHESIZE(bool, _ignoreMovementBoneData, IgnoreMovementBoneData) - - CC_SYNTHESIZE(BlendType, _blendType, BlendType) -protected: - Tween *_tween; //! Calculate tween effect - - //! Used for making tween effect in every frame - CC_SYNTHESIZE_READONLY(FrameData *, _tweenData, TweenData); - - CC_SYNTHESIZE(std::string, _name, Name); - - Bone *_parentBone; //! A weak reference to its parent - bool _boneTransformDirty; //! Whether or not transform dirty - - //! self Transform, use this to change display's state - AffineTransform _worldTransform; -}; - -NS_CC_EXT_ARMATURE_END - -#endif /*__CCBONE_H__*/ diff --git a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp b/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp deleted file mode 100644 index ae69ea8230..0000000000 --- a/extensions/CocoStudio/Armature/display/CCDisplayManager.cpp +++ /dev/null @@ -1,396 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCDisplayManager.h" -#include "../CCBone.h" -#include "../CCArmature.h" -#include "../utils/CCUtilMath.h" -#include "../display/CCSkin.h" - -NS_CC_EXT_ARMATURE_BEGIN - -DisplayManager *DisplayManager::create(Bone *bone) -{ - DisplayManager *pDisplayManager = new DisplayManager(); - if (pDisplayManager && pDisplayManager->init(bone)) - { - pDisplayManager->autorelease(); - return pDisplayManager; - } - CC_SAFE_DELETE(pDisplayManager); - return NULL; -} - - -DisplayManager::DisplayManager() - : _decoDisplayList(NULL) - , _displayRenderNode(NULL) - , _currentDecoDisplay(NULL) - , _displayIndex(-1) - , _forceChangeDisplay(false) - , _visible(true) - , _bone(NULL) -{ -} - -DisplayManager::~DisplayManager() -{ - CC_SAFE_DELETE(_decoDisplayList); - - if( _displayRenderNode ) - { - _displayRenderNode->removeFromParentAndCleanup(true); - if(_displayRenderNode->retainCount() > 0) - CC_SAFE_RELEASE_NULL(_displayRenderNode); - } - -} - -bool DisplayManager::init(Bone *bone) -{ - bool ret = false; - - do - { - - _bone = bone; - - initDisplayList(bone->getBoneData()); - - ret = true; - } - while (0); - - return ret; -} - - -void DisplayManager::addDisplay(DisplayData *displayData, int index) -{ - DecorativeDisplay *decoDisplay = NULL; - - if(index >= 0 && (unsigned int)index < _decoDisplayList->count()) - { - decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); - } - else - { - decoDisplay = DecorativeDisplay::create(); - _decoDisplayList->addObject(decoDisplay); - } - - DisplayFactory::addDisplay(_bone, decoDisplay, displayData); - - //! if changed display index is current display index, then change current display to the new display - if(index == _displayIndex) - { - _displayIndex = -1; - changeDisplayByIndex(index, false); - } -} - -void DisplayManager::addDisplay(Node *display, int index) -{ - DecorativeDisplay *decoDisplay = NULL; - - if(index >= 0 && (unsigned int)index < _decoDisplayList->count()) - { - decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); - } - else - { - decoDisplay = DecorativeDisplay::create(); - _decoDisplayList->addObject(decoDisplay); - } - - DisplayData *displayData = NULL; - if (Skin *skin = dynamic_cast(display)) - { - skin->setBone(_bone); - displayData = SpriteDisplayData::create(); - - DisplayFactory::initSpriteDisplay(_bone, decoDisplay, skin->getDisplayName().c_str(), skin); - - if (SpriteDisplayData *spriteDisplayData = (SpriteDisplayData *)decoDisplay->getDisplayData()) - { - skin->setSkinData(spriteDisplayData->skinData); - ((CCSpriteDisplayData *)displayData)->skinData = spriteDisplayData->skinData; - } - else - { - BaseData baseData; - skin->setSkinData(baseData); - } - } - else if (dynamic_cast(display)) - { - displayData = ParticleDisplayData::create(); - } - else if(Armature *armature = dynamic_cast(display)) - { - displayData = ArmatureDisplayData::create(); - armature->setParentBone(_bone); - } - else - { - displayData = DisplayData::create(); - } - - decoDisplay->setDisplay(display); - decoDisplay->setDisplayData(displayData); - - //! if changed display index is current display index, then change current display to the new display - if(index == _displayIndex) - { - _displayIndex = -1; - changeDisplayByIndex(index, false); - } -} - -void DisplayManager::removeDisplay(int index) -{ - _decoDisplayList->removeObjectAtIndex(index); - - if(index == _displayIndex) - { - setCurrentDecorativeDisplay(NULL); - } -} - -Array *DisplayManager::getDecorativeDisplayList() -{ - return _decoDisplayList; -} - -void DisplayManager::changeDisplayByIndex(int index, bool force) -{ - CCASSERT( (_decoDisplayList ? index < (int)_decoDisplayList->count() : true), "the _index value is out of range"); - - _forceChangeDisplay = force; - - //! If index is equal to current display index,then do nothing - if ( _displayIndex == index) - return; - - - _displayIndex = index; - - //! If displayIndex < 0, it means you want to hide you display - if (_displayIndex < 0) - { - if(_displayRenderNode) - { - _displayRenderNode->removeFromParentAndCleanup(true); - setCurrentDecorativeDisplay(NULL); - } - return; - } - - - DecorativeDisplay *decoDisplay = (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(_displayIndex); - - setCurrentDecorativeDisplay(decoDisplay); -} - -void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) -{ -#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - if (_currentDecoDisplay && _currentDecoDisplay->getColliderDetector()) - { - _currentDecoDisplay->getColliderDetector()->setActive(false); - } -#endif - - _currentDecoDisplay = decoDisplay; - -#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - if (_currentDecoDisplay && _currentDecoDisplay->getColliderDetector()) - { - _currentDecoDisplay->getColliderDetector()->setActive(true); - } -#endif - - Node *displayRenderNode = _currentDecoDisplay == NULL ? NULL : _currentDecoDisplay->getDisplay(); - if (_displayRenderNode) - { - if (dynamic_cast(_displayRenderNode) != NULL) - { - _bone->setChildArmature(NULL); - } - _displayRenderNode->removeFromParentAndCleanup(true); - _displayRenderNode->release(); - } - - _displayRenderNode = displayRenderNode; - - if(_displayRenderNode) - { - if (Armature *armature = dynamic_cast(_displayRenderNode)) - { - _bone->setChildArmature(armature); - } - else if (ParticleSystemQuad *particle = dynamic_cast(_displayRenderNode)) - { - particle->resetSystem(); - } - - if (RGBAProtocol *rgbaProtocaol = dynamic_cast(_displayRenderNode)) - { - rgbaProtocaol->setColor(_bone->getDisplayedColor()); - rgbaProtocaol->setOpacity(_bone->getDisplayedOpacity()); - } - - _displayRenderNode->retain(); - _displayRenderNode->setVisible(_visible); - } -} - -Node *DisplayManager::getDisplayRenderNode() -{ - return _displayRenderNode; -} - -int DisplayManager::getCurrentDisplayIndex() -{ - return _displayIndex; -} - -DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() -{ - return _currentDecoDisplay; -} - -DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) -{ - return (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); -} - -void DisplayManager::initDisplayList(BoneData *boneData) -{ - CC_SAFE_DELETE(_decoDisplayList); - _decoDisplayList = Array::create(); - _decoDisplayList->retain(); - - CS_RETURN_IF(!boneData); - - Object *object = NULL; - Array *displayDataList = &boneData->displayDataList; - CCARRAY_FOREACH(displayDataList, object) - { - DisplayData *displayData = (DisplayData *)object; - - DecorativeDisplay *decoDisplay = DecorativeDisplay::create(); - decoDisplay->setDisplayData(displayData); - - DisplayFactory::createDisplay(_bone, decoDisplay); - - _decoDisplayList->addObject(decoDisplay); - } -} - - -bool DisplayManager::containPoint(Point &point) -{ - if(!_visible || _displayIndex < 0) - { - return false; - } - - bool ret = false; - - switch (_currentDecoDisplay->getDisplayData()->displayType) - { - case CS_DISPLAY_SPRITE: - { - /* - * First we first check if the point is in the sprite content rect. If false, then we continue to check - * the contour point. If this step is also false, then we can say the bone not contain this point. - * - */ - - Point outPoint = Point(0, 0); - - Sprite *sprite = (Sprite *)_currentDecoDisplay->getDisplay(); - sprite = (Sprite *)sprite->getChildByTag(0); - - ret = CC_SPRITE_CONTAIN_POINT_WITH_RETURN(sprite, point, outPoint); - - } - break; - - default: - break; - } - return ret; -} - -bool DisplayManager::containPoint(float x, float y) -{ - Point p = Point(x, y); - return containPoint(p); -} - - -void DisplayManager::setVisible(bool visible) -{ - if(!_displayRenderNode) - return; - - _visible = visible; - _displayRenderNode->setVisible(visible); -} - -bool DisplayManager::isVisible() -{ - return _visible; -} - - -Size DisplayManager::getContentSize() -{ - CS_RETURN_IF(!_displayRenderNode) Size(0, 0); - return _displayRenderNode->getContentSize(); -} - -Rect DisplayManager::getBoundingBox() -{ - CS_RETURN_IF(!_displayRenderNode) Rect(0, 0, 0, 0); - return _displayRenderNode->getBoundingBox(); -} - - -Point DisplayManager::getAnchorPoint() -{ - CS_RETURN_IF(!_displayRenderNode) Point(0, 0); - return _displayRenderNode->getAnchorPoint(); -} - -Point DisplayManager::getAnchorPointInPoints() -{ - CS_RETURN_IF(!_displayRenderNode) Point(0, 0); - return _displayRenderNode->getAnchorPointInPoints(); -} - - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/display/CCSkin.cpp b/extensions/CocoStudio/Armature/display/CCSkin.cpp deleted file mode 100644 index a35bbffcbe..0000000000 --- a/extensions/CocoStudio/Armature/display/CCSkin.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCSkin.h" -#include "../utils/CCTransformHelp.h" -#include "../utils/CCSpriteFrameCacheHelper.h" -#include "../CCArmature.h" - -NS_CC_EXT_ARMATURE_BEGIN - -#if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -Skin *Skin::create() -{ - Skin *skin = new Skin(); - if(skin && skin->init()) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin *Skin::createWithSpriteFrameName(const char *pszSpriteFrameName) -{ - Skin *skin = new Skin(); - if(skin && skin->initWithSpriteFrameName(pszSpriteFrameName)) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin *Skin::create(const char *pszFileName) -{ - Skin *skin = new Skin(); - if(skin && skin->initWithFile(pszFileName)) - { - skin->autorelease(); - return skin; - } - CC_SAFE_DELETE(skin); - return NULL; -} - -Skin::Skin() - : _bone(NULL) - , _displayName("") -{ - _skinTransform = AffineTransformIdentity; -} - -bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) -{ - bool ret = Sprite::initWithSpriteFrameName(pszSpriteFrameName); - - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszSpriteFrameName; - } - - return ret; -} - -bool Skin::initWithFile(const char *pszFilename) -{ - bool ret = Sprite::initWithFile(pszFilename); - - if (ret) - { - TextureAtlas *atlas = SpriteFrameCacheHelper::getInstance()->getTexureAtlasWithTexture(_texture); - setTextureAtlas(atlas); - - _displayName = pszFilename; - } - - return ret; -} - -void Skin::setSkinData(const BaseData &var) -{ - _skinData = var; - - setScaleX(_skinData.scaleX); - setScaleY(_skinData.scaleY); - setRotation(CC_RADIANS_TO_DEGREES(_skinData.skewX)); - setPosition(Point(_skinData.x, _skinData.y)); - - _skinTransform = getNodeToParentTransform(); - updateArmatureTransform(); -} - -const BaseData &Skin::getSkinData() const -{ - return _skinData; -} - -void Skin::updateArmatureTransform() -{ - _transform = AffineTransformConcat(_skinTransform, _bone->getNodeToArmatureTransform()); -} - -void Skin::updateTransform() -{ - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if( !_visible) - { - _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0, 0, 0); - } - else - { - // - // calculate the Quad based on the Affine Matrix - // - - Size &size = _rect.size; - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - - float x = _transform.tx; - float y = _transform.ty; - - float cr = _transform.a; - float sr = _transform.b; - float cr2 = _transform.d; - float sr2 = -_transform.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); - } - - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS - if (_textureAtlas) - { - _textureAtlas->updateQuad(&_quad, _textureAtlas->getTotalQuads()); - } -} - -AffineTransform Skin::getNodeToWorldTransform() const -{ - return AffineTransformConcat(_transform, _bone->getArmature()->getNodeToWorldTransform()); -} - -AffineTransform Skin::getNodeToWorldTransformAR() const -{ - AffineTransform displayTransform = _transform; - Point anchorPoint = _anchorPointInPoints; - - anchorPoint = PointApplyAffineTransform(anchorPoint, displayTransform); - - displayTransform.tx = anchorPoint.x; - displayTransform.ty = anchorPoint.y; - - return AffineTransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); -} - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp deleted file mode 100644 index cbd53fe1e0..0000000000 --- a/extensions/CocoStudio/Armature/utils/CCArmatureDefine.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCArmatureDefine.h" - -NS_CC_EXT_ARMATURE_BEGIN - -const char *armatureVersion() -{ - return "0.4.0.0"; -} - -NS_CC_EXT_ARMATURE_END diff --git a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp deleted file mode 100644 index 45b63c4db5..0000000000 --- a/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.cpp +++ /dev/null @@ -1,1582 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "support/tinyxml2/tinyxml2.h" -#include "CCDataReaderHelper.h" -#include "CCArmatureDataManager.h" -#include "CCTransformHelp.h" -#include "CCUtilMath.h" -#include "CCArmatureDefine.h" -#include "../datas/CCDatas.h" - - -static const char *VERSION = "version"; -static const float VERSION_2_0 = 2.0f; - -static const char *ARMATURES = "armatures"; -static const char *ARMATURE = "armature"; -static const char *BONE = "b"; -static const char *DISPLAY = "d"; - -static const char *ANIMATIONS = "animations"; -static const char *ANIMATION = "animation"; -static const char *MOVEMENT = "mov"; -static const char *FRAME = "f"; - -static const char *TEXTURE_ATLAS = "TextureAtlas"; -static const char *SUB_TEXTURE = "SubTexture"; - -static const char *A_NAME = "name"; -static const char *A_DURATION = "dr"; -static const char *A_FRAME_INDEX = "fi"; -static const char *A_DURATION_TO = "to"; -static const char *A_DURATION_TWEEN = "drTW"; -static const char *A_LOOP = "lp"; -static const char *A_MOVEMENT_SCALE = "sc"; -static const char *A_MOVEMENT_DELAY = "dl"; -static const char *A_DISPLAY_INDEX = "dI"; - -// static const char *A_VERT = "vert"; -// static const char *A_FRAG = "frag"; -static const char *A_PLIST = "plist"; - -static const char *A_PARENT = "parent"; -static const char *A_SKEW_X = "kX"; -static const char *A_SKEW_Y = "kY"; -static const char *A_SCALE_X = "cX"; -static const char *A_SCALE_Y = "cY"; -static const char *A_Z = "z"; -static const char *A_EVENT = "evt"; -static const char *A_SOUND = "sd"; -static const char *A_SOUND_EFFECT = "sdE"; -static const char *A_TWEEN_EASING = "twE"; -//static const char *A_TWEEN_ROTATE = "twR"; -static const char *A_IS_ARMATURE = "isArmature"; -static const char *A_DISPLAY_TYPE = "displayType"; -static const char *A_MOVEMENT = "mov"; - -static const char *A_X = "x"; -static const char *A_Y = "y"; - -static const char *A_COCOS2DX_X = "cocos2d_x"; -static const char *A_COCOS2DX_Y = "cocos2d_y"; - -static const char *A_WIDTH = "width"; -static const char *A_HEIGHT = "height"; -static const char *A_PIVOT_X = "pX"; -static const char *A_PIVOT_Y = "pY"; - -static const char *A_COCOS2D_PIVOT_X = "cocos2d_pX"; -static const char *A_COCOS2D_PIVOT_Y = "cocos2d_pY"; - -static const char *A_BLEND_TYPE = "bd"; - -static const char *A_ALPHA = "a"; -static const char *A_RED = "r"; -static const char *A_GREEN = "g"; -static const char *A_BLUE = "b"; -static const char *A_ALPHA_OFFSET = "aM"; -static const char *A_RED_OFFSET = "rM"; -static const char *A_GREEN_OFFSET = "gM"; -static const char *A_BLUE_OFFSET = "bM"; -static const char *A_COLOR_TRANSFORM = "colorTransform"; -static const char *A_TWEEN_FRAME = "tweenFrame"; -//static const char *A_ROTATION = "rotation"; -//static const char *A_USE_COLOR_INFO = "uci"; - - - -static const char *CONTOUR = "con"; -static const char *CONTOUR_VERTEX = "con_vt"; - -//static const char *MOVEMENT_EVENT_FRAME = "movementEventFrame"; -//static const char *SOUND_FRAME = "soundFrame"; - - -static const char *FL_NAN = "NaN"; - - -static const char *FRAME_DATA = "frame_data"; -static const char *MOVEMENT_BONE_DATA = "mov_bone_data"; -static const char *MOVEMENT_DATA = "mov_data"; -static const char *ANIMATION_DATA = "animation_data"; -static const char *DISPLAY_DATA = "display_data"; -static const char *SKIN_DATA = "skin_data"; -static const char *BONE_DATA = "bone_data"; -static const char *ARMATURE_DATA = "armature_data"; -static const char *CONTOUR_DATA = "contour_data"; -static const char *TEXTURE_DATA = "texture_data"; -static const char *VERTEX_POINT = "vertex"; -static const char *COLOR_INFO = "color"; - -static const char *CONFIG_FILE_PATH = "config_file_path"; - - -NS_CC_EXT_ARMATURE_BEGIN - - -std::vector s_arrConfigFileList; -float s_PositionReadScale = 1; -static float s_FlashToolVersion = VERSION_2_0; -static float s_CocoStudioVersion = VERSION_COMBINED; - -static std::string s_BasefilePath = ""; - -DataReaderHelper *DataReaderHelper::_dataReaderHelper = NULL; - - - -//! Async load -void DataReaderHelper::loadData() -{ - AsyncStruct *pAsyncStruct = NULL; - - while (true) - { - // create autorelease pool for iOS - Thread thread; - thread.createAutoreleasePool(); - - std::queue *pQueue = _asyncStructQueue; - _asyncStructQueueMutex.lock(); // get async struct from queue - if (pQueue->empty()) - { - _asyncStructQueueMutex.unlock(); - if (need_quit) - { - break; - } - else - { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); - continue; - } - } - else - { - pAsyncStruct = pQueue->front(); - pQueue->pop(); - _asyncStructQueueMutex.unlock(); - } - - // generate image info - DataInfo *pDataInfo = new DataInfo(); - pDataInfo->asyncStruct = pAsyncStruct; - - if (pAsyncStruct->configType == DragonBone_XML) - { - DataReaderHelper::addDataFromCache(pAsyncStruct->fileContent.c_str(), pDataInfo); - } - else if(pAsyncStruct->configType == CocoStudio_JSON) - { - DataReaderHelper::addDataFromJsonCache(pAsyncStruct->fileContent.c_str(), pDataInfo); - } - - // put the image info into the queue - _dataInfoMutex.lock(); - _dataQueue->push(pDataInfo); - _dataInfoMutex.unlock(); - } - - if( _asyncStructQueue != NULL ) - { - delete _asyncStructQueue; - _asyncStructQueue = NULL; - delete _dataQueue; - _dataQueue = NULL; - } -} - - -DataReaderHelper *DataReaderHelper::getInstance() -{ - if(!_dataReaderHelper) - { - _dataReaderHelper = new DataReaderHelper(); - } - - return _dataReaderHelper; -} - -void DataReaderHelper::setPositionReadScale(float scale) -{ - s_PositionReadScale = scale; -} - -float DataReaderHelper::getPositionReadScale() -{ - return s_PositionReadScale; -} - - -void DataReaderHelper::purge() -{ - DataReaderHelper::clear(); - CC_SAFE_RELEASE_NULL(_dataReaderHelper); -} - -void DataReaderHelper::clear() -{ - s_arrConfigFileList.clear(); -} - -DataReaderHelper::DataReaderHelper() - : _loadingThread(nullptr) - , _asyncStructQueue(nullptr) - , _dataQueue(nullptr) - , need_quit(false) - , _asyncRefCount(0) - , _asyncRefTotalCount(0) -{ - -} - -DataReaderHelper::~DataReaderHelper() -{ - need_quit = true; - - _sleepCondition.notify_one(); - if (_loadingThread) _loadingThread->join(); - - CC_SAFE_DELETE(_loadingThread); - _dataReaderHelper = NULL; -} - -void DataReaderHelper::addDataFromFile(const char *filePath) -{ - /* - * Check if file is already added to ArmatureDataManager, if then return. - */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) - { - if (s_arrConfigFileList[i].compare(filePath) == 0) - { - return; - } - } - s_arrConfigFileList.push_back(filePath); - - - //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); - if (pos != std::string::npos) - { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); - } - else - { - s_BasefilePath = ""; - } - - - std::string filePathStr = filePath; - size_t startPos = filePathStr.find_last_of("."); - std::string str = &filePathStr[startPos]; - - unsigned long size; - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); - - if (str.compare(".xml") == 0) - { - DataReaderHelper::addDataFromCache(pFileContent); - } - else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) - { - DataReaderHelper::addDataFromJsonCache(pFileContent); - } -} - -void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target, SEL_SCHEDULE selector) -{ - /* - * Check if file is already added to ArmatureDataManager, if then return. - */ - for(unsigned int i = 0; i < s_arrConfigFileList.size(); i++) - { - if (s_arrConfigFileList[i].compare(filePath) == 0) - { - if (target && selector) - { - if (_asyncRefTotalCount == 0 && _asyncRefCount == 0) - { - (target->*selector)(1); - } - else - { - (target->*selector)((_asyncRefTotalCount - _asyncRefCount) / (float)_asyncRefTotalCount); - } - } - return; - } - } - s_arrConfigFileList.push_back(filePath); - - //! find the base file path - s_BasefilePath = filePath; - size_t pos = s_BasefilePath.find_last_of("/"); - if (pos != std::string::npos) - { - s_BasefilePath = s_BasefilePath.substr(0, pos + 1); - } - else - { - s_BasefilePath = ""; - } - - - // lazy init - if (_asyncStructQueue == NULL) - { - _asyncStructQueue = new std::queue(); - _dataQueue = new std::queue(); - - // create a new thread to load images - _loadingThread = new std::thread(&DataReaderHelper::loadData, this); - - need_quit = false; - } - - if (0 == _asyncRefCount) - { - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); - } - - ++_asyncRefCount; - ++_asyncRefTotalCount; - - if (target) - { - target->retain(); - } - - // generate async struct - AsyncStruct *data = new AsyncStruct(); - data->filename = filePath; - data->baseFilePath = s_BasefilePath; - data->target = target; - data->selector = selector; - data->autoLoadSpriteFile = ArmatureDataManager::getInstance()->isAutoLoadSpriteFile(); - - - std::string filePathStr = filePath; - size_t startPos = filePathStr.find_last_of("."); - std::string str = &filePathStr[startPos]; - - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - unsigned long size; - data->fileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); - - if (str.compare(".xml") == 0) - { - data->configType = DragonBone_XML; - } - else if(str.compare(".json") == 0 || str.compare(".ExportJson") == 0) - { - data->configType = CocoStudio_JSON; - } - - - // add async struct into queue - _asyncStructQueueMutex.lock(); - _asyncStructQueue->push(data); - _asyncStructQueueMutex.unlock(); - - _sleepCondition.notify_one(); -} - -void DataReaderHelper::addDataAsyncCallBack(float dt) -{ - // the data is generated in loading thread - std::queue *dataQueue = _dataQueue; - - _dataInfoMutex.lock(); - if (dataQueue->empty()) - { - _dataInfoMutex.unlock(); - } - else - { - DataInfo *pDataInfo = dataQueue->front(); - dataQueue->pop(); - _dataInfoMutex.unlock(); - - AsyncStruct *pAsyncStruct = pDataInfo->asyncStruct; - - while (!pDataInfo->configFileQueue.empty()) - { - std::string configPath = pDataInfo->configFileQueue.front(); - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str()); - pDataInfo->configFileQueue.pop(); - } - - - Object *target = pAsyncStruct->target; - SEL_SCHEDULE selector = pAsyncStruct->selector; - - --_asyncRefCount; - - if (target && selector) - { - (target->*selector)((_asyncRefTotalCount - _asyncRefCount) / (float)_asyncRefTotalCount); - target->release(); - } - - - delete pAsyncStruct; - delete pDataInfo; - - if (0 == _asyncRefCount) - { - _asyncRefTotalCount = 0; - CCDirector::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); - } - } -} - - - - - - -void DataReaderHelper::addDataFromCache(const char *pFileContent, DataInfo *dataInfo) -{ - tinyxml2::XMLDocument document; - document.Parse(pFileContent); - - tinyxml2::XMLElement *root = document.RootElement(); - CCASSERT(root, "XML error or XML is empty."); - - root->QueryFloatAttribute(VERSION, &s_FlashToolVersion); - - - /* - * Begin decode armature data from xml - */ - tinyxml2::XMLElement *armaturesXML = root->FirstChildElement(ARMATURES); - tinyxml2::XMLElement *armatureXML = armaturesXML->FirstChildElement(ARMATURE); - while(armatureXML) - { - ArmatureData *armatureData = DataReaderHelper::decodeArmature(armatureXML); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); - armatureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - - armatureXML = armatureXML->NextSiblingElement(ARMATURE); - } - - - /* - * Begin decode animation data from xml - */ - tinyxml2::XMLElement *animationsXML = root->FirstChildElement(ANIMATIONS); - tinyxml2::XMLElement *animationXML = animationsXML->FirstChildElement(ANIMATION); - while(animationXML) - { - AnimationData *animationData = DataReaderHelper::decodeAnimation(animationXML); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); - animationData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - animationXML = animationXML->NextSiblingElement(ANIMATION); - } - - - /* - * Begin decode texture data from xml - */ - tinyxml2::XMLElement *texturesXML = root->FirstChildElement(TEXTURE_ATLAS); - tinyxml2::XMLElement *textureXML = texturesXML->FirstChildElement(SUB_TEXTURE); - while(textureXML) - { - TextureData *textureData = DataReaderHelper::decodeTexture(textureXML); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); - textureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - textureXML = textureXML->NextSiblingElement(SUB_TEXTURE); - } -} - -ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML) -{ - ArmatureData *armatureData = new ArmatureData(); - armatureData->init(); - - const char *name = armatureXML->Attribute(A_NAME); - armatureData->name = name; - - - tinyxml2::XMLElement *boneXML = armatureXML->FirstChildElement(BONE); - - while( boneXML ) - { - /* - * If this bone have parent, then get the parent bone xml - */ - const char *parentName = boneXML->Attribute(A_PARENT); - tinyxml2::XMLElement *parentXML = NULL; - if (parentName) - { - parentXML = armatureXML->FirstChildElement(BONE); - std::string name = parentName; - while (parentXML) - { - if (name.compare(parentXML->Attribute(A_NAME)) == 0) - { - break; - } - parentXML = parentXML->NextSiblingElement(BONE); - } - } - - BoneData *boneData = decodeBone(boneXML, parentXML); - armatureData->addBoneData(boneData); - boneData->release(); - - boneXML = boneXML->NextSiblingElement(BONE); - } - - return armatureData; -} - -BoneData *DataReaderHelper::decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXml) -{ - BoneData *boneData = new BoneData(); - boneData->init(); - - std::string name = boneXML->Attribute(A_NAME); - boneData->name = name; - - if( boneXML->Attribute(A_PARENT) != NULL ) - { - boneData->parentName = boneXML->Attribute(A_PARENT); - } - - boneXML->QueryIntAttribute(A_Z, &boneData->zOrder); - - tinyxml2::XMLElement *displayXML = boneXML->FirstChildElement(DISPLAY); - while(displayXML) - { - DisplayData *displayData = decodeBoneDisplay(displayXML); - boneData->addDisplayData(displayData); - displayData->release(); - - displayXML = displayXML->NextSiblingElement(DISPLAY); - } - - return boneData; -} - -DisplayData *DataReaderHelper::decodeBoneDisplay(tinyxml2::XMLElement *displayXML) -{ - int _isArmature = 0; - - DisplayData *displayData; - - if( displayXML->QueryIntAttribute(A_IS_ARMATURE, &(_isArmature)) == tinyxml2::XML_SUCCESS ) - { - if(!_isArmature) - { - displayData = new SpriteDisplayData(); - displayData->displayType = CS_DISPLAY_SPRITE; - } - else - { - displayData = new ArmatureDisplayData(); - displayData->displayType = CS_DISPLAY_ARMATURE; - } - - } - else - { - displayData = new SpriteDisplayData(); - displayData->displayType = CS_DISPLAY_SPRITE; - } - - - if(displayXML->Attribute(A_NAME) != NULL ) - { - if(!_isArmature) - { - ((SpriteDisplayData *)displayData)->displayName = displayXML->Attribute(A_NAME); - } - else - { - ((ArmatureDisplayData *)displayData)->displayName = displayXML->Attribute(A_NAME); - } - - } - - return displayData; -} - -AnimationData *DataReaderHelper::decodeAnimation(tinyxml2::XMLElement *animationXML) -{ - AnimationData *aniData = new AnimationData(); - - const char *name = animationXML->Attribute(A_NAME); - - ArmatureData *armatureData = ArmatureDataManager::getInstance()->getArmatureData(name); - - aniData->name = name; - - tinyxml2::XMLElement *movementXML = animationXML->FirstChildElement(MOVEMENT); - - while( movementXML ) - { - MovementData *movementData = decodeMovement(movementXML, armatureData); - aniData->addMovement(movementData); - movementData->release(); - - movementXML = movementXML->NextSiblingElement(MOVEMENT); - - } - - return aniData; -} - -MovementData *DataReaderHelper::decodeMovement(tinyxml2::XMLElement *movementXML, ArmatureData *armatureData) -{ - MovementData *movementData = new MovementData(); - - const char *movName = movementXML->Attribute(A_NAME); - movementData->name = movName; - - - int duration, durationTo, durationTween, loop, tweenEasing = 0; - - if( movementXML->QueryIntAttribute(A_DURATION, &(duration)) == tinyxml2::XML_SUCCESS) - { - movementData->duration = duration; - } - if( movementXML->QueryIntAttribute(A_DURATION_TO, &(durationTo)) == tinyxml2::XML_SUCCESS) - { - movementData->durationTo = durationTo; - } - if( movementXML->QueryIntAttribute(A_DURATION_TWEEN, &(durationTween)) == tinyxml2::XML_SUCCESS) - { - movementData->durationTween = durationTween; - } - if( movementXML->QueryIntAttribute(A_LOOP, &(loop)) == tinyxml2::XML_SUCCESS) - { - movementData->loop = (bool)loop; - } - - const char *_easing = movementXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) - { - std::string str = _easing; - if(str.compare(FL_NAN) != 0) - { - if( movementXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) - { - movementData->tweenEasing = (CCTweenType)tweenEasing; - } - } - else - { - movementData->tweenEasing = TWEEN_EASING_MAX; - } - } - - tinyxml2::XMLElement *movBoneXml = movementXML->FirstChildElement(BONE); - while(movBoneXml) - { - const char *boneName = movBoneXml->Attribute(A_NAME); - - if (movementData->getMovementBoneData(boneName)) - { - movBoneXml = movBoneXml->NextSiblingElement(); - continue; - } - - - BoneData *boneData = (BoneData *)armatureData->getBoneData(boneName); - - std::string parentName = boneData->parentName; - - - tinyxml2::XMLElement *parentXml = NULL; - if (parentName.length() != 0) - { - parentXml = movementXML->FirstChildElement(BONE); - - while (parentXml) - { - if (parentName.compare(parentXml->Attribute(A_NAME)) == 0) - { - break; - } - parentXml = parentXml->NextSiblingElement(BONE); - } - } - - MovementBoneData *moveBoneData = decodeMovementBone(movBoneXml, parentXml, boneData); - movementData->addMovementBoneData(moveBoneData); - moveBoneData->release(); - - movBoneXml = movBoneXml->NextSiblingElement(BONE); - } - - return movementData; -} - - -MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, BoneData *boneData) -{ - MovementBoneData *movBoneData = new MovementBoneData(); - movBoneData->init(); - - float scale, delay; - - if( movBoneXml ) - { - if( movBoneXml->QueryFloatAttribute(A_MOVEMENT_SCALE, &scale) == tinyxml2::XML_SUCCESS ) - { - movBoneData->scale = scale; - } - if( movBoneXml->QueryFloatAttribute(A_MOVEMENT_DELAY, &delay) == tinyxml2::XML_SUCCESS ) - { - if(delay > 0) - { - delay -= 1; - } - movBoneData->delay = delay; - } - } - - int length = 0; - int i = 0; - int parentTotalDuration = 0; - int currentDuration = 0; - - tinyxml2::XMLElement *parentFrameXML = NULL; - - std::vector parentXmlList; - - /* - * get the parent frame xml list, we need get the origin data - */ - if( parentXml != NULL ) - { - parentFrameXML = parentXml->FirstChildElement(FRAME); - while (parentFrameXML) - { - parentXmlList.push_back(parentFrameXML); - parentFrameXML = parentFrameXML->NextSiblingElement(FRAME); - } - - parentFrameXML = NULL; - - length = parentXmlList.size(); - } - - - int totalDuration = 0; - - std::string name = movBoneXml->Attribute(A_NAME); - - movBoneData->name = name; - - tinyxml2::XMLElement *frameXML = movBoneXml->FirstChildElement(FRAME); - - while( frameXML ) - { - if(parentXml) - { - /* - * in this loop we get the corresponding parent frame xml - */ - while(i < length && (parentFrameXML ? (totalDuration < parentTotalDuration || totalDuration >= parentTotalDuration + currentDuration) : true)) - { - parentFrameXML = parentXmlList[i]; - parentTotalDuration += currentDuration; - parentFrameXML->QueryIntAttribute(A_DURATION, ¤tDuration); - i++; - - } - } - - FrameData *frameData = decodeFrame( frameXML, parentFrameXML, boneData); - movBoneData->addFrameData(frameData); - frameData->release(); - - frameData->frameID = totalDuration; - totalDuration += frameData->duration; - movBoneData->duration = totalDuration; - - frameXML = frameXML->NextSiblingElement(FRAME); - } - - - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } - - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - - - // - FrameData *frameData = new FrameData(); - frameData->copy((FrameData *)movBoneData->frameList.getLastObject()); - frameData->frameID = movBoneData->duration; - movBoneData->addFrameData(frameData); - frameData->release(); - - return movBoneData; -} - -FrameData *DataReaderHelper::decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, BoneData *boneData) -{ - float x, y, scale_x, scale_y, skew_x, skew_y = 0; - int duration, displayIndex, zOrder, tweenEasing, blendType = 0; - - FrameData *frameData = new FrameData(); - - if(frameXML->Attribute(A_MOVEMENT) != NULL) - { - frameData->strMovement = frameXML->Attribute(A_MOVEMENT); - } - if(frameXML->Attribute(A_EVENT) != NULL) - { - frameData->strEvent = frameXML->Attribute(A_EVENT); - } - if(frameXML->Attribute(A_SOUND) != NULL) - { - frameData->strSound = frameXML->Attribute(A_SOUND); - } - if(frameXML->Attribute(A_SOUND_EFFECT) != NULL) - { - frameData->strSoundEffect = frameXML->Attribute(A_SOUND_EFFECT); - } - - - - if (s_FlashToolVersion >= VERSION_2_0) - { - if(frameXML->QueryFloatAttribute(A_COCOS2DX_X, &x) == tinyxml2::XML_SUCCESS) - { - frameData->x = x; - frameData->x *= s_PositionReadScale; - } - if(frameXML->QueryFloatAttribute(A_COCOS2DX_Y, &y) == tinyxml2::XML_SUCCESS) - { - frameData->y = -y; - frameData->y *= s_PositionReadScale; - } - } - else - { - if(frameXML->QueryFloatAttribute(A_X, &x) == tinyxml2::XML_SUCCESS) - { - frameData->x = x; - frameData->x *= s_PositionReadScale; - } - if(frameXML->QueryFloatAttribute(A_Y, &y) == tinyxml2::XML_SUCCESS) - { - frameData->y = -y; - frameData->y *= s_PositionReadScale; - } - } - - if( frameXML->QueryFloatAttribute(A_SCALE_X, &scale_x) == tinyxml2::XML_SUCCESS ) - { - frameData->scaleX = scale_x; - } - if( frameXML->QueryFloatAttribute(A_SCALE_Y, &scale_y) == tinyxml2::XML_SUCCESS ) - { - frameData->scaleY = scale_y; - } - if( frameXML->QueryFloatAttribute(A_SKEW_X, &skew_x) == tinyxml2::XML_SUCCESS ) - { - frameData->skewX = CC_DEGREES_TO_RADIANS(skew_x); - } - if( frameXML->QueryFloatAttribute(A_SKEW_Y, &skew_y) == tinyxml2::XML_SUCCESS ) - { - frameData->skewY = CC_DEGREES_TO_RADIANS(-skew_y); - } - if( frameXML->QueryIntAttribute(A_DURATION, &duration) == tinyxml2::XML_SUCCESS ) - { - frameData->duration = duration; - } - if( frameXML->QueryIntAttribute(A_DISPLAY_INDEX, &displayIndex) == tinyxml2::XML_SUCCESS ) - { - frameData->displayIndex = displayIndex; - } - if( frameXML->QueryIntAttribute(A_Z, &zOrder) == tinyxml2::XML_SUCCESS ) - { - frameData->zOrder = zOrder; - } - if ( frameXML->QueryIntAttribute(A_BLEND_TYPE, &blendType) == tinyxml2::XML_SUCCESS ) - { - frameData->blendType = (BlendType)blendType; - } - - tinyxml2::XMLElement *colorTransformXML = frameXML->FirstChildElement(A_COLOR_TRANSFORM); - if (colorTransformXML) - { - int alpha, red, green, blue = 100; - int alphaOffset, redOffset, greenOffset, blueOffset = 0; - - colorTransformXML->QueryIntAttribute(A_ALPHA, &alpha); - colorTransformXML->QueryIntAttribute(A_RED, &red); - colorTransformXML->QueryIntAttribute(A_GREEN, &green); - colorTransformXML->QueryIntAttribute(A_BLUE, &blue) ; - - colorTransformXML->QueryIntAttribute(A_ALPHA_OFFSET, &alphaOffset); - colorTransformXML->QueryIntAttribute(A_RED_OFFSET, &redOffset); - colorTransformXML->QueryIntAttribute(A_GREEN_OFFSET, &greenOffset); - colorTransformXML->QueryIntAttribute(A_BLUE_OFFSET, &blueOffset) ; - - frameData->a = 2.55 * alphaOffset + alpha; - frameData->r = 2.55 * redOffset + red; - frameData->g = 2.55 * greenOffset + green; - frameData->b = 2.55 * blueOffset + blue; - - frameData->isUseColorInfo = true; - } - - - const char *_easing = frameXML->Attribute(A_TWEEN_EASING); - if(_easing != NULL) - { - std::string str = _easing; - if(str.compare(FL_NAN) != 0) - { - if( frameXML->QueryIntAttribute(A_TWEEN_EASING, &(tweenEasing)) == tinyxml2::XML_SUCCESS) - { - frameData->tweenEasing = (CCTweenType)tweenEasing; - } - } - else - { - frameData->tweenEasing = TWEEN_EASING_MAX; - } - } - - if(parentFrameXml) - { - /* - * recalculate frame data from parent frame data, use for translate matrix - */ - BaseData helpNode; - if (s_FlashToolVersion >= VERSION_2_0) - { - parentFrameXml->QueryFloatAttribute(A_COCOS2DX_X, &helpNode.x); - parentFrameXml->QueryFloatAttribute(A_COCOS2DX_Y, &helpNode.y); - } - else - { - parentFrameXml->QueryFloatAttribute(A_X, &helpNode.x); - parentFrameXml->QueryFloatAttribute(A_Y, &helpNode.y); - } - - - parentFrameXml->QueryFloatAttribute(A_SKEW_X, &helpNode.skewX); - parentFrameXml->QueryFloatAttribute(A_SKEW_Y, &helpNode.skewY); - - helpNode.y = -helpNode.y; - helpNode.skewX = CC_DEGREES_TO_RADIANS(helpNode.skewX); - helpNode.skewY = CC_DEGREES_TO_RADIANS(-helpNode.skewY); - - TransformHelp::transformFromParent(*frameData, helpNode); - } - return frameData; -} - -TextureData *DataReaderHelper::decodeTexture(tinyxml2::XMLElement *textureXML) -{ - TextureData *textureData = new TextureData(); - textureData->init(); - - if( textureXML->Attribute(A_NAME) != NULL) - { - textureData->name = textureXML->Attribute(A_NAME); - } - - float px, py, width, height = 0; - - if(s_FlashToolVersion >= VERSION_2_0) - { - textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_X, &px); - textureXML->QueryFloatAttribute(A_COCOS2D_PIVOT_Y, &py); - } - else - { - textureXML->QueryFloatAttribute(A_PIVOT_X, &px); - textureXML->QueryFloatAttribute(A_PIVOT_Y, &py); - } - - textureXML->QueryFloatAttribute(A_WIDTH, &width); - textureXML->QueryFloatAttribute(A_HEIGHT, &height); - - float anchorPointX = px / width; - float anchorPointY = (height - py) / height; - - textureData->pivotX = anchorPointX; - textureData->pivotY = anchorPointY; - - tinyxml2::XMLElement *contourXML = textureXML->FirstChildElement(CONTOUR); - - while (contourXML) - { - ContourData *contourData = decodeContour(contourXML); - textureData->addContourData(contourData); - contourData->release(); - - contourXML = contourXML->NextSiblingElement(CONTOUR); - } - - return textureData; -} - -ContourData *DataReaderHelper::decodeContour(tinyxml2::XMLElement *contourXML) -{ - ContourData *contourData = new ContourData(); - contourData->init(); - - tinyxml2::XMLElement *vertexDataXML = contourXML->FirstChildElement(CONTOUR_VERTEX); - - while (vertexDataXML) - { - ContourVertex2 *vertex = new ContourVertex2(0, 0); - vertex->release(); - - vertexDataXML->QueryFloatAttribute(A_X, &vertex->x); - vertexDataXML->QueryFloatAttribute(A_Y, &vertex->y); - - vertex->y = -vertex->y; - contourData->vertexList.addObject(vertex); - - vertexDataXML = vertexDataXML->NextSiblingElement(CONTOUR_VERTEX); - } - - return contourData; -} - - - -void DataReaderHelper::addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo) -{ - cs::JsonDictionary json; - json.initWithDescription(fileContent); - - // Decode armatures - int length = json.getArrayItemCount(ARMATURE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i); - ArmatureData *armatureData = decodeArmature(*armatureDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData); - armatureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete armatureDic; - } - - // Decode animations - length = json.getArrayItemCount(ANIMATION_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i); - AnimationData *animationData = decodeAnimation(*animationDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData); - animationData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete animationDic; - } - - // Decode textures - length = json.getArrayItemCount(TEXTURE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i); - TextureData *textureData = decodeTexture(*textureDic); - - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.lock(); - } - ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData); - textureData->release(); - if (dataInfo) - { - _dataReaderHelper->_addDataMutex.unlock(); - } - delete textureDic; - } - - // Auto load sprite file - bool autoLoad = dataInfo == NULL ? ArmatureDataManager::getInstance()->isAutoLoadSpriteFile() : dataInfo->asyncStruct->autoLoadSpriteFile; - if (autoLoad) - { - length = json.getArrayItemCount(CONFIG_FILE_PATH); - for (int i = 0; i < length; i++) - { - const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i); - if (path == NULL) - { - CCLOG("load CONFIG_FILE_PATH error."); - return; - } - - std::string filePath = path; - filePath = filePath.erase(filePath.find_last_of(".")); - - if (dataInfo != NULL) - { - dataInfo->configFileQueue.push(filePath); - } - else - { - std::string plistPath = filePath + ".plist"; - std::string pngPath = filePath + ".png"; - - ArmatureDataManager::getInstance()->addSpriteFrameFromFile((s_BasefilePath + plistPath).c_str(), (s_BasefilePath + pngPath).c_str()); - } - } - } -} - -ArmatureData *DataReaderHelper::decodeArmature(cs::JsonDictionary &json) -{ - ArmatureData *armatureData = new ArmatureData(); - armatureData->init(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - armatureData->name = name; - } - - s_CocoStudioVersion = armatureData->dataVersion = json.getItemFloatValue(VERSION, 0.1f); - - int length = json.getArrayItemCount(BONE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(BONE_DATA, i); - BoneData *boneData = decodeBone(*dic); - armatureData->addBoneData(boneData); - boneData->release(); - - delete dic; - } - - return armatureData; -} - -BoneData *DataReaderHelper::decodeBone(cs::JsonDictionary &json) -{ - BoneData *boneData = new BoneData(); - boneData->init(); - - decodeNode(boneData, json); - - const char *str = json.getItemStringValue(A_NAME); - if(str != NULL) - { - boneData->name = str; - } - - str = json.getItemStringValue(A_PARENT); - if(str != NULL) - { - boneData->parentName = str; - } - - int length = json.getArrayItemCount(DISPLAY_DATA); - - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(DISPLAY_DATA, i); - DisplayData *displayData = decodeBoneDisplay(*dic); - boneData->addDisplayData(displayData); - displayData->release(); - - delete dic; - } - - return boneData; -} - -DisplayData *DataReaderHelper::decodeBoneDisplay(cs::JsonDictionary &json) -{ - DisplayType displayType = (DisplayType)json.getItemIntValue(A_DISPLAY_TYPE, CS_DISPLAY_SPRITE); - - DisplayData *displayData = NULL; - - switch (displayType) - { - case CS_DISPLAY_SPRITE: - { - displayData = new SpriteDisplayData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - ((SpriteDisplayData *)displayData)->displayName = name; - } - - cs::JsonDictionary *dic = json.getSubItemFromArray(SKIN_DATA, 0); - if (dic != NULL) - { - SpriteDisplayData *sdd = (SpriteDisplayData *)displayData; - sdd->skinData.x = dic->getItemFloatValue(A_X, 0) * s_PositionReadScale; - sdd->skinData.y = dic->getItemFloatValue(A_Y, 0) * s_PositionReadScale; - sdd->skinData.scaleX = dic->getItemFloatValue(A_SCALE_X, 1); - sdd->skinData.scaleY = dic->getItemFloatValue(A_SCALE_Y, 1); - sdd->skinData.skewX = dic->getItemFloatValue(A_SKEW_X, 0); - sdd->skinData.skewY = dic->getItemFloatValue(A_SKEW_Y, 0); - delete dic; - } - } - - break; - case CS_DISPLAY_ARMATURE: - { - displayData = new ArmatureDisplayData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - ((ArmatureDisplayData *)displayData)->displayName = name; - } - } - break; - case CS_DISPLAY_PARTICLE: - { - displayData = new ParticleDisplayData(); - - const char *plist = json.getItemStringValue(A_PLIST); - if(plist != NULL) - { - ((ParticleDisplayData *)displayData)->plist = s_BasefilePath + plist; - } - } - break; - default: - displayData = new SpriteDisplayData(); - - break; - } - - - displayData->displayType = displayType; - - return displayData; -} - -AnimationData *DataReaderHelper::decodeAnimation(cs::JsonDictionary &json) -{ - AnimationData *aniData = new AnimationData(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - aniData->name = name; - } - - int length = json.getArrayItemCount(MOVEMENT_DATA); - - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_DATA, i); - MovementData *movementData = decodeMovement(*dic); - aniData->addMovement(movementData); - movementData->release(); - - delete dic; - } - - return aniData; -} - -MovementData *DataReaderHelper::decodeMovement(cs::JsonDictionary &json) -{ - MovementData *movementData = new MovementData(); - - movementData->loop = json.getItemBoolvalue(A_LOOP, true); - movementData->durationTween = json.getItemIntValue(A_DURATION_TWEEN, 0); - movementData->durationTo = json.getItemIntValue(A_DURATION_TO, 0); - movementData->duration = json.getItemIntValue(A_DURATION, 0); - movementData->scale = json.getItemFloatValue(A_MOVEMENT_SCALE, 1); - movementData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - movementData->name = name; - } - - int length = json.getArrayItemCount(MOVEMENT_BONE_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(MOVEMENT_BONE_DATA, i); - MovementBoneData *movementBoneData = decodeMovementBone(*dic); - movementData->addMovementBoneData(movementBoneData); - movementBoneData->release(); - - delete dic; - } - - return movementData; -} - -MovementBoneData *DataReaderHelper::decodeMovementBone(cs::JsonDictionary &json) -{ - MovementBoneData *movementBoneData = new MovementBoneData(); - movementBoneData->init(); - - movementBoneData->delay = json.getItemFloatValue(A_MOVEMENT_DELAY, 0); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - movementBoneData->name = name; - } - - int length = json.getArrayItemCount(FRAME_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(FRAME_DATA, i); - FrameData *frameData = decodeFrame(*dic); - - movementBoneData->addFrameData(frameData); - frameData->release(); - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - frameData->frameID = movementBoneData->duration; - movementBoneData->duration += frameData->duration; - } - - delete dic; - } - - - if (s_CocoStudioVersion < VERSION_CHANGE_ROTATION_RANGE) - { - //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) - CCFrameData **frames = (CCFrameData **)movementBoneData->frameList.data->arr; - for (int i = movementBoneData->frameList.count() - 1; i >= 0; i--) - { - if (i > 0) - { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; - - if (difSkewX < -M_PI || difSkewX > M_PI) - { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; - } - - if (difSkewY < -M_PI || difSkewY > M_PI) - { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; - } - } - } - } - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - if (movementBoneData->frameList.count() > 0) - { - FrameData *frameData = new FrameData(); - frameData->copy((FrameData *)movementBoneData->frameList.getLastObject()); - movementBoneData->addFrameData(frameData); - frameData->release(); - - frameData->frameID = movementBoneData->duration; - } - } - - return movementBoneData; -} - -FrameData *DataReaderHelper::decodeFrame(cs::JsonDictionary &json) -{ - FrameData *frameData = new FrameData(); - - decodeNode(frameData, json); - - frameData->tweenEasing = (CCTweenType)json.getItemIntValue(A_TWEEN_EASING, Linear); - frameData->displayIndex = json.getItemIntValue(A_DISPLAY_INDEX, 0); - frameData->blendType = (BlendType)json.getItemIntValue(A_BLEND_TYPE, 0); - frameData->isTween = (bool)json.getItemBoolvalue(A_TWEEN_FRAME, true); - - const char *event = json.getItemStringValue(A_EVENT); - if (event != NULL) - { - frameData->strEvent = event; - } - - if (s_CocoStudioVersion < VERSION_COMBINED) - { - frameData->duration = json.getItemIntValue(A_DURATION, 1); - } - else - { - frameData->frameID = json.getItemIntValue(A_FRAME_INDEX, 0); - } - - return frameData; -} - -TextureData *DataReaderHelper::decodeTexture(cs::JsonDictionary &json) -{ - TextureData *textureData = new TextureData(); - textureData->init(); - - const char *name = json.getItemStringValue(A_NAME); - if(name != NULL) - { - textureData->name = name; - } - - textureData->width = json.getItemFloatValue(A_WIDTH, 0); - textureData->height = json.getItemFloatValue(A_HEIGHT, 0); - textureData->pivotX = json.getItemFloatValue(A_PIVOT_X, 0); - textureData->pivotY = json.getItemFloatValue(A_PIVOT_Y, 0); - - int length = json.getArrayItemCount(CONTOUR_DATA); - for (int i = 0; i < length; i++) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(CONTOUR_DATA, i); - ContourData *contourData = decodeContour(*dic); - textureData->contourDataList.addObject(contourData); - contourData->release(); - - delete dic; - } - - return textureData; -} - -ContourData *DataReaderHelper::decodeContour(cs::JsonDictionary &json) -{ - ContourData *contourData = new ContourData(); - contourData->init(); - - int length = json.getArrayItemCount(VERTEX_POINT); - for (int i = length - 1; i >= 0; i--) - { - cs::JsonDictionary *dic = json.getSubItemFromArray(VERTEX_POINT, i); - - ContourVertex2 *vertex = new ContourVertex2(0, 0); - - vertex->x = dic->getItemFloatValue(A_X, 0); - vertex->y = dic->getItemFloatValue(A_Y, 0); - - contourData->vertexList.addObject(vertex); - vertex->release(); - - delete dic; - } - - return contourData; -} - -void DataReaderHelper::decodeNode(BaseData *node, cs::JsonDictionary &json) -{ - node->x = json.getItemFloatValue(A_X, 0) * s_PositionReadScale; - node->y = json.getItemFloatValue(A_Y, 0) * s_PositionReadScale; - node->zOrder = json.getItemIntValue(A_Z, 0); - - node->skewX = json.getItemFloatValue(A_SKEW_X, 0); - node->skewY = json.getItemFloatValue(A_SKEW_Y, 0); - node->scaleX = json.getItemFloatValue(A_SCALE_X, 1); - node->scaleY = json.getItemFloatValue(A_SCALE_Y, 1); - - cs::JsonDictionary *colorDic = json.getSubItemFromArray(COLOR_INFO, 0); - - if (colorDic) - { - node->a = colorDic->getItemIntValue(A_ALPHA, 255); - node->r = colorDic->getItemIntValue(A_RED, 255); - node->g = colorDic->getItemIntValue(A_GREEN, 255); - node->b = colorDic->getItemIntValue(A_BLUE, 255); - - node->isUseColorInfo = true; - - delete colorDic; - } - -} - -NS_CC_EXT_ARMATURE_END diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 0b662d9c15..b571dfb808 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -15,7 +15,7 @@ static int s_nActionIdx = -1; Layer *CreateLayer(int index) { - Layer *pLayer = NULL; + Layer *pLayer = nullptr; switch(index) { case TEST_ASYNCHRONOUS_LOADING: @@ -167,7 +167,7 @@ void ArmatureTestLayer::onEnter() restartItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(ArmatureTestLayer::restartCallback, this) ); nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(ArmatureTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); + Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); menu->setPosition(Point::ZERO); backItem->setPosition(Point(VisibleRect::center().x - restartItem->getContentSize().width * 2, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); @@ -183,7 +183,7 @@ void ArmatureTestLayer::onExit() { removeAllChildren(); - backItem = restartItem = nextItem = NULL; + backItem = restartItem = nextItem = nullptr; Layer::onExit(); } @@ -319,7 +319,7 @@ std::string TestDirectLoading::title() void TestCSWithSkeleton::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Cowboy"); armature->getAnimation()->playByIndex(0); armature->setScale(0.2f); @@ -340,7 +340,7 @@ void TestDragonBones20::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; armature = Armature::create("Dragon"); armature->getAnimation()->playByIndex(1); armature->getAnimation()->setSpeedScale(0.4f); @@ -372,7 +372,7 @@ void TestPerformance::onEnter() MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); increase->setColor(Color3B(0,200,20)); - Menu *menu = Menu::create(decrease, increase, NULL); + Menu *menu = Menu::create(decrease, increase, nullptr); menu->alignItemsHorizontally(); menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); @@ -413,7 +413,7 @@ void TestPerformance::addArmature(int number) { armatureCount++; - Armature *armature = NULL; + Armature *armature = nullptr; armature = new Armature(); armature->init("Knight_f/Knight"); armature->getAnimation()->playByIndex(0); @@ -467,7 +467,7 @@ void TestChangeZorder::onEnter() { ArmatureTestLayer::onEnter(); - Armature *armature = NULL; + Armature *armature = nullptr; currentTag = -1; armature = Armature::create("Knight_f/Knight"); @@ -524,7 +524,7 @@ void TestAnimationEvent::onEnter() /* * Set armature's movement event callback function - * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + * To disconnect this event, just setMovementEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(TestAnimationEvent::animationEvent)); addChild(armature); @@ -543,14 +543,14 @@ void TestAnimationEvent::animationEvent(Armature *armature, MovementEventType mo { ActionInterval *actionToRight = MoveTo::create(2, Point(VisibleRect::right().x - 50, VisibleRect::right().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), NULL)); + armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), nullptr)); armature->getAnimation()->play("Walk"); } else if (id.compare("FireMax") == 0) { ActionInterval *actionToLeft = MoveTo::create(2, Point(VisibleRect::left().x + 50, VisibleRect::left().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), NULL)); + armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), nullptr)); armature->getAnimation()->play("Walk"); } } @@ -580,7 +580,7 @@ void TestFrameEvent::onEnter() /* * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestFrameEvent::onFrameEvent)); @@ -608,8 +608,8 @@ void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIn } void TestFrameEvent::checkAction(float dt) { - if ( this->numberOfRunningActions() == 0 && this->getGrid() != NULL) - this->setGrid(NULL); + if ( this->numberOfRunningActions() == 0 && this->getGrid() != nullptr) + this->setGrid(nullptr); } @@ -750,7 +750,7 @@ void TestColliderDetector::onEnter() /* * Set armature's frame event callback function - * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + * To disconnect this event, just setFrameEventCallFunc(nullptr, nullptr); */ armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestColliderDetector::onFrameEvent)); @@ -1011,7 +1011,7 @@ void TestColliderDetector::initWorld() ColliderFilter filter = ColliderFilter(eEnemyTag); armature2->setColliderFilter(&filter); - cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL); + cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, nullptr, nullptr, endHit, nullptr); } #endif @@ -1106,7 +1106,7 @@ void TestArmatureNesting::onTouchesEnded(const std::vector& touches, Eve ++weaponIndex; weaponIndex = weaponIndex % 4; - if(armature != NULL) + if(armature != nullptr) { armature->getBone("armInside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); armature->getBone("armOutside")->getChildArmature()->getAnimation()->playByIndex(weaponIndex); @@ -1125,18 +1125,18 @@ Hero *Hero::create(const char *name) return hero; } CC_SAFE_DELETE(hero); - return NULL; + return nullptr; } Hero::Hero() - : m_pMount(NULL) - , m_pLayer(NULL) + : m_pMount(nullptr) + , m_pLayer(nullptr) { } void Hero::changeMount(Armature *armature) { - if (armature == NULL) + if (armature == nullptr) { retain(); @@ -1203,7 +1203,7 @@ void TestArmatureNesting2::onEnter() LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::ChangeMountCallback, this)); - Menu* pMenu =Menu::create(pMenuItem, NULL); + Menu* pMenu =Menu::create(pMenuItem, nullptr); pMenu->setPosition( Point() ); pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); @@ -1241,7 +1241,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev { Point point = touches[0]->getLocation(); - Armature *armature = hero->getMount() == NULL ? hero : hero->getMount(); + Armature *armature = hero->getMount() == nullptr ? hero : hero->getMount(); //Set armature direction if (point.x < armature->getPositionX()) @@ -1255,7 +1255,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, NULL)); + armature->runAction(Sequence::create(move, nullptr)); } void TestArmatureNesting2::ChangeMountCallback(Object* pSender) @@ -1264,7 +1264,7 @@ void TestArmatureNesting2::ChangeMountCallback(Object* pSender) if (hero->getMount()) { - hero->changeMount(NULL); + hero->changeMount(nullptr); } else { From 963d7f3bd00a00b8b7d57b72fef1e4b73d935c9e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 15:33:34 +0800 Subject: [PATCH 402/557] Changes the touch id declaration from int to long. --- cocos/2d/platform/linux/CCEGLView.cpp | 6 +++--- cocos/2d/platform/win32/CCEGLView.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 33b8796959..a136ba54b3 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -186,7 +186,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -195,7 +195,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -231,7 +231,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 6b19ec5bb5..3a18b81917 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -303,7 +303,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = true; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); } } @@ -312,7 +312,7 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in s_captured = false; if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); } } @@ -348,7 +348,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, { if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) { - int id = 0; + long id = 0; eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); } } From 8c62bf813fc0e2433ee9483ebc14d806b517fe20 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 5 Nov 2013 15:54:33 +0800 Subject: [PATCH 403/557] issue #2771: enhance API and add Slice demo --- cocos/physics/CCPhysicsBody.cpp | 26 +++- cocos/physics/CCPhysicsBody.h | 10 +- cocos/physics/CCPhysicsContact.cpp | 9 +- cocos/physics/CCPhysicsContact.h | 1 + cocos/physics/CCPhysicsShape.cpp | 18 +++ cocos/physics/CCPhysicsShape.h | 2 + cocos/physics/CCPhysicsWorld.cpp | 22 ++- cocos/physics/CCPhysicsWorld.h | 14 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 137 ++++++++++++++++-- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 27 +++- 10 files changed, 233 insertions(+), 33 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 152a4fc454..8a177e6252 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -157,12 +157,12 @@ PhysicsBody* PhysicsBody::create(float mass, float moment) } -PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeCircle::create(radius, material)); + body->addShape(PhysicsShapeCircle::create(radius, material, offset)); body->autorelease(); return body; } @@ -171,12 +171,12 @@ PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeBox::create(size, material)); + body->addShape(PhysicsShapeBox::create(size, material, offset)); body->autorelease(); return body; } @@ -185,12 +185,12 @@ PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material) return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material) +PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapePolygon::create(points, count, material)); + body->addShape(PhysicsShapePolygon::create(points, count, material, offset)); body->autorelease(); return body; } @@ -214,12 +214,12 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial ma return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/, Point offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { - body->addShape(PhysicsShapeEdgeBox::create(size, material, border)); + body->addShape(PhysicsShapeEdgeBox::create(size, material, border, offset)); body->_dynamic = false; body->autorelease(); return body; @@ -536,6 +536,16 @@ Point PhysicsBody::getVelocity() return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); } +Point PhysicsBody::getVelocityAtLocalPoint(Point point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->body, PhysicsHelper::point2cpv(point))); +} + +Point PhysicsBody::getVelocityAtWorldPoint(Point point) +{ + return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->body, PhysicsHelper::point2cpv(point))); +} + void PhysicsBody::setAngularVelocity(float velocity) { cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index a4bad406b8..60dd314966 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -59,16 +59,16 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); + static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); /** * @brief Create a body contains a EdgeSegment shape. @@ -77,7 +77,7 @@ public: /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, Point offset = Point::ZERO); /** * @brief Create a body contains a EdgePolygon shape. */ @@ -113,6 +113,8 @@ public: virtual void setVelocity(Point velocity); virtual Point getVelocity(); virtual void setAngularVelocity(float velocity); + virtual Point getVelocityAtLocalPoint(Point point); + virtual Point getVelocityAtWorldPoint(Point point); virtual float getAngularVelocity(); virtual void setVelocityLimit(float limit); virtual float getVelocityLimit(); diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index b5a7c7e0a3..e3a4907a97 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -120,6 +120,11 @@ PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* c { } +PhysicsContactPreSolve::~PhysicsContactPreSolve() +{ + CC_SAFE_DELETE(_preContactData); +} + float PhysicsContactPreSolve::getElasticity() const { return static_cast(_contactInfo)->e; @@ -150,9 +155,9 @@ void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); } -PhysicsContactPreSolve::~PhysicsContactPreSolve() +void PhysicsContactPreSolve::ignore() { - CC_SAFE_DELETE(_preContactData); + cpArbiterIgnore(static_cast(_contactInfo)); } // PhysicsContactPostSolve implementation diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 32127da7a5..ee279ef474 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -139,6 +139,7 @@ public: void setElasticity(float elasticity); void setFriction(float friction); void setSurfaceVelocity(Point surfaceVelocity); + void ignore(); private: PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo); diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index c2334ec719..fea8365c08 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -594,6 +594,11 @@ float PhysicsShapePolygon::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } +Point PhysicsShapePolygon::getPoint(int i) const +{ + return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->shapes.front(), i)); +} + Point* PhysicsShapePolygon::getPoints(Point* points) const { cpShape* shape = _info->shapes.front(); @@ -792,6 +797,19 @@ void PhysicsShape::setGroup(int group) } } +bool PhysicsShape::containsPoint(Point point) const +{ + for (auto shape : _info->shapes) + { + if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point))) + { + return true; + } + } + + return false; +} + #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #endif diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 31497d14a2..4ddcfe8a18 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -98,6 +98,7 @@ public: virtual float calculateDefaultArea() { return 0; } virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } + bool containsPoint(Point point) const; static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); static Point getPolyonCenter(Point* points, int count); @@ -203,6 +204,7 @@ public: float calculateDefaultArea() override; float calculateDefaultMoment() override; + Point getPoint(int i) const; Point* getPoints(Point* points) const; int getPointsCount() const; Point getCenter() override; diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 913713277b..cafdb79be8 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -146,12 +146,17 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect auto it = PhysicsShapeInfo::map.find(shape); CC_ASSERT(it != PhysicsShapeInfo::map.end()); - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, - Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), - Point(n.x, n.y), - (float)t, - info->data); + PhysicsRayCastCallback::Info callbackInfo = + { + it->second->shape, + info->p1, + info->p2, + Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), + Point(n.x, n.y), + (float)t, + }; + + PhysicsWorldCallback::continues = info->callback->report(*info->world, callbackInfo, info->data); } void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) @@ -747,6 +752,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { if (!contact.getNotify()) { + cpArbiterIgnore(static_cast(contact._contactInfo)); return true; } @@ -811,6 +817,8 @@ void PhysicsWorld::setGravity(Point gravity) void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) { + CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + if (callback.report != nullptr) { RayCastCallbackInfo info = { this, &callback, point1, point2, data }; @@ -829,6 +837,8 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) { + CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + if (callback.report != nullptr) { RectQueryCallbackInfo info = {this, &callback, data}; diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 2d4e7def57..360844db3f 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -50,6 +50,18 @@ class DrawNode; class PhysicsWorld; class PhysicsRayCastCallback { +public: + typedef struct Info + { + PhysicsShape* shape; + Point start; + Point end; + Point contact; + Point normal; + float fraction; + void* data; + }Info; + public: PhysicsRayCastCallback() : report(nullptr) @@ -65,7 +77,7 @@ public: * @param normal the normal vector at the point of intersection * @return true to continue, false to terminate */ - std::function report; + std::function report; }; class PhysicsRectQueryCallback diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 866cec82fd..99ce9d0c90 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -14,6 +14,7 @@ namespace CL(PhysicsDemoActions), CL(PhysicsDemoPump), CL(PhysicsDemoOneWayPlatform), + CL(PhysicsDemoSlice), }; static int sceneIdx=-1; @@ -601,9 +602,9 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data) { - *((Point*)data) = point; + *((Point*)data) = info.contact; return false; } @@ -619,12 +620,12 @@ private: PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() : _friction(1.0f) { - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool { - if (_friction > fraction) + if (_friction > info.fraction) { - *((Point*)data) = point; - _friction = fraction; + *((Point*)data) = info.contact; + _friction = info.fraction; } return true; @@ -649,11 +650,11 @@ public: PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() : num(0) { - report = [this](PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data)->bool + report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool { if (num < MAX_MULTI_RAYCAST_NUM) { - points[num++] = point; + points[num++] = info.contact; } return true; @@ -675,7 +676,7 @@ void PhysicsDemoRayCast::update(float delta) { PhysicsRayCastCallback callback; Point point3 = point2; - callback.report = anyRay; + callback.report = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); @@ -941,8 +942,9 @@ void PhysicsDemoPump::onEnter() // pump auto pump = Node::create(); - pump->setPosition(PhysicsShape::getPolyonCenter(vec, 4)); - auto pumpB = PhysicsBody::createPolygon(PhysicsShape::recenterPoints(vec, 4), 4); + auto center = PhysicsShape::getPolyonCenter(vec, 4); + pump->setPosition(center); + auto pumpB = PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center); pump->setPhysicsBody(pumpB); this->addChild(pump); pumpB->setCategoryBitmask(0x02); @@ -1062,4 +1064,117 @@ bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const Physics std::string PhysicsDemoOneWayPlatform::title() { return "One Way Platform"; +} + +void PhysicsDemoSlice::onEnter() +{ + PhysicsDemo::onEnter(); + + _sliceTag = 1; + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = [](Touch* touch, Event* event)->bool{ return true; }; + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoSlice::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto ground = Node::create(); + ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); + this->addChild(ground); + + auto box = Node::create(); + Point points[4] = {Point(-100, -100), Point(-100, 100), Point(100, 100), Point(100, -100)}; + box->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); + box->setPosition(VisibleRect::center()); + box->getPhysicsBody()->setTag(_sliceTag); + addChild(box); +} + +bool PhysicsDemoSlice::slice(PhysicsWorld &world, PhysicsRayCastCallback::Info &info, void *data) +{ + if (info.shape->getBody()->getTag() != _sliceTag) + { + return true; + } + + if (!info.shape->containsPoint(info.start) && !info.shape->containsPoint(info.end)) + { + Point normal = info.end - info.start; + normal = normal.getPerp().normalize(); + float dist = info.start.dot(normal); + dist = dist; + + clipPoly(dynamic_cast(info.shape), normal, dist); + clipPoly(dynamic_cast(info.shape), -normal, -dist); + + info.shape->getBody()->removeFromWorld(); + } + + return true; +} + +void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float distance) +{ + PhysicsBody* body = shape->getBody(); + int count = shape->getPointsCount(); + int pointsCount = 0; + Point* points = new Point[count + 1]; + + for (int i=0, j=count-1; ilocal2World(shape->getPoint(j)); + float aDist = a.dot(normal) - distance; + + if (aDist < 0.0f) + { + points[pointsCount] = a; + ++pointsCount; + } + + Point b = body->local2World(shape->getPoint(i)); + float bDist = b.dot(normal) - distance; + + if (aDist*bDist < 0.0f) + { + float t = abs(aDist)/(abs(aDist) + abs(bDist)); + points[pointsCount] = a.lerp(b, t); + ++pointsCount; + } + } + + Point center = PhysicsShape::getPolyonCenter(points, pointsCount); + Node* node = Node::create(); + PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); + node->setPosition(center); + node->setPhysicsBody(polyon); + polyon->setVelocity(body->getVelocityAtWorldPoint(center)); + polyon->setAngularVelocity(body->getAngularVelocity()); + polyon->setTag(_sliceTag); + addChild(node); +} + +void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) +{ + PhysicsRayCastCallback callback; + callback.report = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); + _scene->getPhysicsWorld()->rayCast(callback, touch->getStartLocation(), touch->getLocation(), nullptr); +} + +std::string PhysicsDemoSlice::title() +{ + return "Slice"; +} + +std::string PhysicsDemoSlice::subtitle() +{ + return "click and drag to slice up the block"; +} + +void PhysicsDemoWater::onEnter() +{ + +} + +std::string PhysicsDemoWater::title() +{ + return "Water"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 4de964f2d3..425dbc56f9 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - static bool anyRay(PhysicsWorld& world, PhysicsShape& shape, Point point, Point normal, float fraction, void* data); + bool anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); private: float _angle; @@ -143,4 +143,29 @@ public: bool onContactBegin(EventCustom* event, const PhysicsContact& contact); }; +class PhysicsDemoSlice : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; + std::string subtitle() override; + + bool slice(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); + + bool onTouchBegan(Touch *touch, Event *event); + void onTouchMoved(Touch *touch, Event *event); + void onTouchEnded(Touch *touch, Event *event); + +private: + int _sliceTag; +}; + +class PhysicsDemoWater : public PhysicsDemo +{ +public: + void onEnter() override; + std::string title() override; +}; + #endif From f2f7e61b073b99369e1ac06feada5402c4dc239e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 5 Nov 2013 16:04:06 +0800 Subject: [PATCH 404/557] Update CHNAGELOG[ci skip] --- CHANGELOG | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 0d0efb8f2d..797c52821d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. + [NEW] Arm64 support. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again @@ -25,6 +26,8 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Removed unused CCLOG() from GL initialization [iOS] [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. +[Linux] + [NEW] Used CMake to build linux projects. [Desktop] [FIX] Trigger onKeyReleased only after the key has been released. [Javascript binding] From 8c75cd0dfa490d0e29ad70dd14a963572f63ae2c Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 08:07:15 +0000 Subject: [PATCH 405/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 56a3820b26..4ea4a8fa89 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 56a3820b2660d69ebd958838f515cd75f08eaf18 +Subproject commit 4ea4a8fa89fd3b9b5ec3e8b6f69841dfe0e3b75c From 61d8f9673cc18fcb8f3ae95672e54d59aa4c14ed Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 17:34:25 +0800 Subject: [PATCH 406/557] issue #2868:Move armature related lua binding from namespace 'cc' to namespace 'ccd' --- .../cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- cocos/scripting/lua/bindings/Android.mk | 1 + cocos/scripting/lua/bindings/Makefile | 1 + tools/tolua/cocos2dx_studio.ini | 6 +++--- tools/tolua/genbindings.sh | 7 +++++++ 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b99b211450..91f22feb89 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ab3cbe9f9358e0c472a7775bb7087507f50892e9 \ No newline at end of file +db96f13af3f35778c8d9c2b6bec189fcdaf7216e \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index b39ee5f6a5..f198157af9 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -17,6 +17,7 @@ LOCAL_SRC_FILES := CCLuaBridge.cpp \ LuaBasicConversions.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ + ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ lua_cocos2dx_manual.cpp \ lua_cocos2dx_extension_manual.cpp \ lua_cocos2dx_deprecated.cpp \ diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile index c797ce3b9e..546ad977b4 100644 --- a/cocos/scripting/lua/bindings/Makefile +++ b/cocos/scripting/lua/bindings/Makefile @@ -49,6 +49,7 @@ SOURCES = ../../../../external/lua/lua/lapi.c \ tolua_fix.c \ ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ + ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ CCLuaBridge.cpp \ CCLuaEngine.cpp \ CCLuaStack.cpp \ diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini index c30134f97d..8959fd0005 100644 --- a/tools/tolua/cocos2dx_studio.ini +++ b/tools/tolua/cocos2dx_studio.ini @@ -23,11 +23,11 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h %(cocosdir)s/cocos/gui/CocosGUI.h +headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWidget GUIRenderer Layout RectClippingNode UIRootWidget UIButton UICheckBox UIImageView UILabel UICCLabelAtlas UILabelAtlas UILoadingBar UIScrollView UISlider UICCTextField UITextField UIListView UIDragPanel UILabelBMFont UIPageView UIHelper UILayer +classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -38,7 +38,7 @@ classes =Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ UIWid skip = .*Delegate::[*], .*Loader.*::[*], - *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener addEventListener], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager], Armature::[createBone updateBlendType getCPBody setCPBody (s|g)etBlendFunc getShapeList ^getBody$], Skin::[(s|g)etSkinData], diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index e6997542bf..9dc005d4a0 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -78,5 +78,12 @@ echo -e "$_CONTENTS" > "$_CONF_INI_FILE" echo --- # Generate bindings for cocos2dx +echo "Generating bindings for cocos2dx..." +set -x +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto + +echo "Generating bindings for cocos2dx_extension..." +LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto + echo "Generating bindings for cocos2dx_studio..." LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto From 66256e9ad7f726739e423d27b97d6388172fa92c Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 5 Nov 2013 17:48:29 +0800 Subject: [PATCH 407/557] issue #2868:Move armature related lua binding from namespace 'cc' to namespace 'ccs' --- cocos/scripting/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index bee2a84fe8..478ae9a039 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -1,6 +1,7 @@ set(LUABINDING_SRC auto-generated/lua-bindings/lua_cocos2dx_auto.cpp auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp + auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp lua/bindings/tolua_fix.c lua/bindings/CCLuaBridge.cpp lua/bindings/CCLuaEngine.cpp From 47e0d343ff8968d2971c4e3a8a5bacbfd12216b5 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 5 Nov 2013 11:30:43 +0000 Subject: [PATCH 408/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 4ea4a8fa89..c2b42be577 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 4ea4a8fa89fd3b9b5ec3e8b6f69841dfe0e3b75c +Subproject commit c2b42be577425e4dd6c2501e8f0cd1520ca3d059 From 16c23d0ad3ca414b206232e0082222b40f65f97d Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 19:53:38 +0800 Subject: [PATCH 409/557] remove CC_PROPERTY and CC_SYNTHESIZE. --- .../editor-support/cocostudio/CCArmature.cpp | 16 ++--- cocos/editor-support/cocostudio/CCArmature.h | 62 ++++++++++------ .../cocostudio/CCArmatureAnimation.cpp | 12 ++-- .../cocostudio/CCArmatureAnimation.h | 18 +++-- .../editor-support/cocostudio/CCBatchNode.cpp | 6 +- cocos/editor-support/cocostudio/CCBatchNode.h | 16 ++--- cocos/editor-support/cocostudio/CCBone.cpp | 8 +-- cocos/editor-support/cocostudio/CCBone.h | 64 +++++++++++------ .../cocostudio/CCColliderDetector.cpp | 4 +- .../cocostudio/CCColliderDetector.h | 72 ++++++++++++++----- .../cocostudio/CCDecorativeDisplay.h | 41 +++++++++-- .../cocostudio/CCDisplayManager.cpp | 22 +++--- .../cocostudio/CCDisplayManager.h | 26 +++---- .../editor-support/cocostudio/CCProcessBase.h | 35 ++++++--- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.h | 20 ++++-- cocos/editor-support/cocostudio/CCTween.cpp | 2 +- cocos/editor-support/cocostudio/CCTween.h | 5 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 8 +-- .../CocoStudioArmatureTest/ArmatureScene.h | 2 +- 20 files changed, 297 insertions(+), 144 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index be5c9d0c33..7cd7ad9295 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -335,7 +335,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName) } } -Dictionary *Armature::getBoneDic() +const Dictionary *Armature::getBoneDic() const { return _boneDic; } @@ -437,12 +437,12 @@ void Armature::setAnimation(ArmatureAnimation *animation) _animation = animation; } -ArmatureAnimation *Armature::getAnimation() +ArmatureAnimation *Armature::getAnimation() const { return _animation; } -bool Armature::getArmatureTransformDirty() +bool Armature::getArmatureTransformDirty() const { return _armatureTransformDirty; } @@ -673,7 +673,7 @@ Rect Armature::getBoundingBox() const return RectApplyAffineTransform(boundingBox, getNodeToParentTransform()); } -Bone *Armature::getBoneAtPoint(float x, float y) +Bone *Armature::getBoneAtPoint(float x, float y) const { int length = _children->count(); Bone *bs; @@ -689,7 +689,7 @@ Bone *Armature::getBoneAtPoint(float x, float y) return nullptr; } -TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) +TextureAtlas *Armature::getTexureAtlasWithTexture(Texture2D *texture) const { int key = texture->getName(); @@ -723,7 +723,7 @@ void Armature::setParentBone(Bone *parentBone) } } -Bone *Armature::getParentBone() +Bone *Armature::getParentBone() const { return _parentBone; } @@ -739,7 +739,7 @@ void CCArmature::setColliderFilter(ColliderFilter *filter) } #if ENABLE_PHYSICS_BOX2D_DETECT -b2Body *Armature::getBody() +b2Body *Armature::getBody() const { return _body; } @@ -787,7 +787,7 @@ b2Fixture *Armature::getShapeList() } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT -cpBody *Armature::getBody() +cpBody *Armature::getBody() const { return _body; } diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 9f6fc3331b..6182072265 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -99,7 +99,7 @@ public: /** * Init the empty armature */ - virtual bool init(); + virtual bool init() override; /** * Init an armature with specified name @@ -140,14 +140,14 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - cocos2d::Dictionary *getBoneDic(); + const cocos2d::Dictionary *getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time */ - virtual cocos2d::Rect getBoundingBox() const; + virtual cocos2d::Rect getBoundingBox() const override; - Bone *getBoneAtPoint(float x, float y); + Bone *getBoneAtPoint(float x, float y) const; // overrides /** @@ -170,18 +170,43 @@ public: virtual void updateOffsetPoint(); virtual void setAnimation(ArmatureAnimation *animation); - virtual ArmatureAnimation *getAnimation(); + virtual ArmatureAnimation *getAnimation() const; - virtual bool getArmatureTransformDirty(); + virtual bool getArmatureTransformDirty() const; - virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; virtual void setColliderFilter(ColliderFilter *filter); + + virtual void setArmatureData(ArmatureData *armatureData) { _armatureData = armatureData; } + virtual const ArmatureData *getArmatureData() const { return _armatureData; } + + virtual void setBatchNode(BatchNode *batchNode) { _batchNode = batchNode; } + virtual const BatchNode *getBatchNode() const { return _batchNode; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string &getName() const { return _name; } + + virtual void setTextureAtlas(cocos2d::TextureAtlas *atlas) { _atlas = atlas; } + virtual cocos2d::TextureAtlas *getTextureAtlas() const { return _atlas; } + + virtual void setParentBone(Bone *parentBone); + virtual Bone *getParentBone() const; + + virtual void setVersion(float version) { _version = version; } + virtual float getVersion() const { return _version; } + #if ENABLE_PHYSICS_BOX2D_DETECT virtual b2Fixture *getShapeList(); + + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT virtual cpShape *getShapeList(); + + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; #endif protected: @@ -194,19 +219,14 @@ protected: //! Update blend function void updateBlendType(BlendType blendType); - CC_SYNTHESIZE(ArmatureData *, _armatureData, ArmatureData); - - CC_SYNTHESIZE(BatchNode *, _batchNode, BatchNode); - - CC_SYNTHESIZE(std::string, _name, Name); - - CC_SYNTHESIZE(cocos2d::TextureAtlas *, _atlas, TextureAtlas); - - CC_PROPERTY(Bone *, _parentBone, ParentBone); - - CC_SYNTHESIZE(float, _version, Version); - protected: + ArmatureData *_armatureData; + BatchNode *_batchNode; + std::string _name; + cocos2d::TextureAtlas *_atlas; + Bone *_parentBone; + float _version; + mutable bool _armatureTransformDirty; cocos2d::Dictionary *_boneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. @@ -222,9 +242,9 @@ protected: cocos2d::Dictionary *_textureAtlasDic; #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + b2Body *_body; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + cpBody *_body; #endif }; diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 8f9c9252bd..6b234782bd 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -146,7 +146,7 @@ void ArmatureAnimation::setSpeedScale(float speedScale) _processScale = !_movementData ? _speedScale : _speedScale * _movementData->scale; DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -174,7 +174,7 @@ void ArmatureAnimation::setAnimationInternal(float animationInternal) _animationInternal = animationInternal; DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { Bone *bone = static_cast(element->getObject()); @@ -236,7 +236,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura _tweenList->removeAllObjects(); DictElement *element = nullptr; - Dictionary *dict = _armature->getBoneDic(); + const Dictionary *dict = _armature->getBoneDic(); CCDICT_FOREACH(dict, element) { @@ -261,7 +261,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura } else { - if(!bone->getIgnoreMovementBoneData()) + if(!bone->isIgnoreMovementBoneData()) { //! this bone is not include in this movement, so hide it bone->getDisplayManager()->changeDisplayByIndex(-1, false); @@ -319,7 +319,7 @@ void ArmatureAnimation::gotoAndPause(int frameIndex) pause(); } -int ArmatureAnimation::getMovementCount() +int ArmatureAnimation::getMovementCount() const { return _animationData->getMovementCount(); } @@ -416,7 +416,7 @@ void ArmatureAnimation::updateHandler() } } -std::string ArmatureAnimation::getCurrentMovementID() +std::string ArmatureAnimation::getCurrentMovementID() const { if (_isComplete) { diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 3c6e7e5a2c..8d306398e9 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -170,7 +170,7 @@ public: /** * Get movement count */ - int getMovementCount(); + int getMovementCount() const; void update(float dt); @@ -178,7 +178,7 @@ public: * Get current movementID * @return The name of current movement */ - std::string getCurrentMovementID(); + std::string getCurrentMovementID() const; /** * Set armature's movement event callback function @@ -192,6 +192,16 @@ public: */ void setFrameEventCallFunc(cocos2d::Object *target, SEL_FrameEventCallFunc callFunc); + virtual void setAnimationData(AnimationData *data) + { + if (_animationData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_animationData); + _animationData = data; + } + } + virtual AnimationData *getAnimationData() const { return _animationData; } protected: /** @@ -209,12 +219,12 @@ protected: */ void frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); - inline bool isIgnoreFrameEvent() { return _ignoreFrameEvent; } + bool isIgnoreFrameEvent() const { return _ignoreFrameEvent; } friend class Tween; protected: //! AnimationData save all MovementDatas this animation used. - CC_SYNTHESIZE_RETAIN(AnimationData *, _animationData, AnimationData); + AnimationData *_animationData; //! Scale the animation speed float _speedScale; diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index d674d8487b..36158a12dd 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -83,7 +83,7 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) { armature->setBatchNode(this); - Dictionary *dict = armature->getBoneDic(); + const Dictionary *dict = armature->getBoneDic(); DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { @@ -111,7 +111,7 @@ void BatchNode::removeChild(Node* child, bool cleanup) { armature->setBatchNode(nullptr); - Dictionary *dict = armature->getBoneDic(); + const Dictionary *dict = armature->getBoneDic(); DictElement *element = nullptr; CCDICT_FOREACH(dict, element) { @@ -188,7 +188,7 @@ void BatchNode::draw() } } -TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) +TextureAtlas *BatchNode::getTexureAtlasWithTexture(Texture2D *texture) const { int key = texture->getName(); diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index 44f10872c2..fa654a19ba 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -40,15 +40,15 @@ public: BatchNode(); ~BatchNode(); - virtual bool init(); - virtual void addChild(cocos2d::Node *pChild); - virtual void addChild(cocos2d::Node *pChild, int zOrder); - virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag); - virtual void removeChild(cocos2d::Node* child, bool cleanup); - virtual void visit(); - void draw(); + virtual bool init() override; + virtual void addChild(cocos2d::Node *pChild) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder) override; + virtual void addChild(cocos2d::Node *pChild, int zOrder, int tag) override; + virtual void removeChild(cocos2d::Node* child, bool cleanup) override; + virtual void visit() override; + void draw() override; - virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture); + virtual cocos2d::TextureAtlas *getTexureAtlasWithTexture(cocos2d::Texture2D *texture) const; protected: cocos2d::TextureAtlas *_atlas; cocos2d::Dictionary *_textureAtlasDic; diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 45562f898e..26c5653d58 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -127,7 +127,7 @@ bool Bone::init(const char *name) _worldInfo = new BaseData(); CC_SAFE_DELETE(_boneData); - _boneData = new CCBoneData(); + _boneData = new BoneData(); bRet = true; } @@ -153,7 +153,7 @@ void Bone::setBoneData(BoneData *boneData) _displayManager->initDisplayList(boneData); } -BoneData *Bone::getBoneData() +BoneData *Bone::getBoneData() const { return _boneData; } @@ -174,7 +174,7 @@ void Bone::setArmature(Armature *armature) } -Armature *Bone::getArmature() +Armature *Bone::getArmature() const { return _armature; } @@ -376,7 +376,7 @@ void Bone::setChildArmature(Armature *armature) } } -Armature *Bone::getChildArmature() +Armature *Bone::getChildArmature() const { return _childArmature; } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 58a15c3987..9082f1ebb3 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -63,7 +63,7 @@ public: /** * Initializes an empty Bone with nothing init. */ - virtual bool init(); + virtual bool init() override; /** * Initializes a Bone with the specified name @@ -124,10 +124,10 @@ public: */ void removeChildBone(Bone *bone, bool recursion); - void update(float delta); + void update(float delta) override; - void updateDisplayedColor(const cocos2d::Color3B &parentColor); - void updateDisplayedOpacity(GLubyte parentOpacity); + void updateDisplayedColor(const cocos2d::Color3B &parentColor) override; + void updateDisplayedOpacity(GLubyte parentOpacity) override; virtual void setColor(const cocos2d::Color3B& color) override; virtual void setOpacity(GLubyte opacity) override; @@ -138,15 +138,15 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder); + virtual void setZOrder(int zOrder) override; Tween *getTween(); /* * Whether or not the bone's transform property changed. if true, the bone will update the transform. */ - virtual inline void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } - virtual inline bool isTransformDirty() { return _boneTransformDirty; } + virtual void setTransformDirty(bool dirty) { _boneTransformDirty = dirty; } + virtual bool isTransformDirty() { return _boneTransformDirty; } virtual cocos2d::AffineTransform getNodeToArmatureTransform() const; virtual cocos2d::AffineTransform getNodeToWorldTransform() const override; @@ -161,45 +161,69 @@ public: virtual void setColliderFilter(ColliderFilter *filter); virtual ColliderFilter *getColliderFilter(); -public: + + virtual void setBoneData(BoneData *boneData); + virtual BoneData *getBoneData() const; + + virtual void setArmature(Armature *armature); + virtual Armature *getArmature() const; + + virtual void setChildArmature(Armature *childArmature); + virtual Armature *getChildArmature() const; + + virtual DisplayManager *getDisplayManager() const { return _displayManager; } + + virtual void setIgnoreMovementBoneData(bool ignore) { _ignoreMovementBoneData = ignore; } + virtual bool isIgnoreMovementBoneData() const { return _ignoreMovementBoneData; } + + virtual void setBlendType(BlendType type) { _blendType = type; } + virtual BlendType getBlendType() const { return _blendType; } + + virtual FrameData *getTweenData() const { return _tweenData; } + + virtual void setName(const std::string &name) { _name = name; } + virtual const std::string getName() const { return _name; } + + virtual const BaseData *getWorldInfo() const { return _worldInfo; } +protected: + void applyParentTransform(Bone *parent); + /* * The origin state of the Bone. Display's state is effected by _boneData, m_pNode, _tweenData * when call setData function, it will copy from the BoneData. */ - CC_PROPERTY(BoneData *, _boneData, BoneData); + BoneData *_boneData; //! A weak reference to the Armature - CC_PROPERTY(Armature *, _armature, Armature); + Armature *_armature; //! A weak reference to the child Armature - CC_PROPERTY(Armature *, _childArmature, ChildArmature); + Armature *_childArmature; - CC_SYNTHESIZE(DisplayManager *, _displayManager, DisplayManager) + DisplayManager *_displayManager; /* * When Armature play an animation, if there is not a MovementBoneData of this bone in this MovementData, this bone will be hidden. * Set IgnoreMovementBoneData to true, then this bone will also be shown. */ - CC_SYNTHESIZE(bool, _ignoreMovementBoneData, IgnoreMovementBoneData) + bool _ignoreMovementBoneData; - CC_SYNTHESIZE(BlendType, _blendType, BlendType) -protected: - void applyParentTransform(Bone *parent); + BlendType _blendType; Tween *_tween; //! Calculate tween effect //! Used for making tween effect in every frame - CC_SYNTHESIZE_READONLY(FrameData *, _tweenData, TweenData); + FrameData *_tweenData; - CC_SYNTHESIZE(std::string, _name, Name); + std::string _name; - Bone *_parentBone; //! A weak reference to its parent + Bone *_parentBone; //! A weak reference to its parent bool _boneTransformDirty; //! Whether or not transform dirty //! self Transform, use this to change display's state cocos2d::AffineTransform _worldTransform; - CC_SYNTHESIZE_READONLY(BaseData*, _worldInfo, WorldInfo); + BaseData *_worldInfo; //! Armature's parent bone Bone *_armatureParentBone; diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index be587ecefb..adbea59a31 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -449,7 +449,7 @@ void ColliderDetector::setBody(b2Body *pBody) } } -b2Body *ColliderDetector::getBody() +b2Body *ColliderDetector::getBody() const { return _body; } @@ -492,7 +492,7 @@ void ColliderDetector::setBody(cpBody *pBody) } } -cpBody *ColliderDetector::getBody() +cpBody *ColliderDetector::getBody() const { return _body; } diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.h b/cocos/editor-support/cocostudio/CCColliderDetector.h index 0b9c058aa8..2737980f60 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.h +++ b/cocos/editor-support/cocostudio/CCColliderDetector.h @@ -55,29 +55,37 @@ public: public: ColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); void updateShape(b2Fixture *fixture); + + virtual void setCategoryBits(unsigned short categoryBits) { _categoryBits = categoryBits; } + virtual unsigned short getCategoryBits() const { return _categoryBits; } + + virtual void setMaskBits(unsigned short maskBits) { _maskBits = maskBits; } + virtual unsigned short getMaskBits() const { return _maskBits; } + + virtual void setGroupIndex(signed short groupIndex) { _groupIndex = groupIndex; } + virtual signed short getGroupIndex() const { return _groupIndex; } protected: - CC_SYNTHESIZE(unsigned short, _categoryBits, CategoryBits); - CC_SYNTHESIZE(unsigned short, _maskBits, MaskBits); - CC_SYNTHESIZE(signed short, _groupIndex, GroupIndex); + unsigned short _categoryBits; + unsigned short _maskBits; + signed short _groupIndex; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT public: ColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); void updateShape(cpShape *shape); + + virtual void setCollisionType(uintptr_t collisionType) { _collisionType = collisionType; } + virtual uintptr_t getCollisionType() const { return _collisionType; } + + virtual void setGroup(uintptr_t group) { _group = group; } + virtual uintptr_t getGroup() const { return _group; } protected: - CC_SYNTHESIZE(uintptr_t, _collisionType, CollisionType); - CC_SYNTHESIZE(uintptr_t, _group, Group); + uintptr_t _collisionType; + uintptr_t _group; #endif }; class ColliderBody : public cocos2d::Object { -public: -#if ENABLE_PHYSICS_BOX2D_DETECT - CC_SYNTHESIZE(b2Fixture *, _fixture, B2Fixture) -#elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE(cpShape *, _shape, Shape) -#endif - public: ColliderBody(ContourData *contourData); ~ColliderBody(); @@ -86,12 +94,31 @@ public: void setColliderFilter(ColliderFilter *filter); ColliderFilter *getColliderFilter(); + +#if ENABLE_PHYSICS_BOX2D_DETECT + virtual void setB2Fixture(b2Fixture *fixture) { _fixture = fixture; } + virtual b2Fixture *getB2Fixture() const { return _fixture; } +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setShape(cpShape *shape) { _shape = shape; } + virtual cpShape *getShape() const { return _shape; } +#endif + +#if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + virtual const cocos2d::Array *getCalculatedVertexList() const { return _calculatedVertexList; } +#endif private: + +#if ENABLE_PHYSICS_BOX2D_DETECT + b2Fixture *_fixture; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + cpShape *_shape; +#endif + ContourData *_contourData; ColliderFilter *_filter; #if ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX - CC_SYNTHESIZE_READONLY(CCArray *, _calculatedVertexList, CalculatedVertexList); + cocos2d::Array *_calculatedVertexList; #endif }; @@ -132,16 +159,27 @@ public: virtual void setColliderFilter(ColliderFilter *filter); virtual ColliderFilter *getColliderFilter(); -protected: + + virtual void setBone(Bone *bone) { _bone = bone; } + virtual Bone *getBone() const { return _bone; } + +#if ENABLE_PHYSICS_BOX2D_DETECT + virtual void setBody(b2Body *body); + virtual b2Body *getBody() const; +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setBody(cpBody *body); + virtual cpBody *getBody() const; +#endif + protected: cocos2d::Array *_colliderBodyList; ColliderFilter *_filter; - CC_SYNTHESIZE(Bone *, _bone, Bone); + Bone *_bone; #if ENABLE_PHYSICS_BOX2D_DETECT - CC_PROPERTY(b2Body *, _body, Body); + b2Body *_body; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_PROPERTY(cpBody *, _body, Body); + cpBody *_body; #endif protected: diff --git a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h index 7196d0e9ec..0444cae440 100644 --- a/cocos/editor-support/cocostudio/CCDecorativeDisplay.h +++ b/cocos/editor-support/cocostudio/CCDecorativeDisplay.h @@ -53,13 +53,46 @@ public: virtual bool init(); -protected: + virtual void setDisplay(cocos2d::Node *display) + { + if (_display != display) + { + CC_SAFE_RETAIN(display); + CC_SAFE_RELEASE(_display); + _display = display; + } + } + virtual cocos2d::Node *getDisplay() const { return _display; } - CC_SYNTHESIZE_RETAIN(cocos2d::Node *, _display, Display); - CC_SYNTHESIZE_RETAIN(DisplayData *, _displayData, DisplayData); + virtual void setDisplayData(DisplayData *data) + { + if (_displayData != data) + { + CC_SAFE_RETAIN(data); + CC_SAFE_RELEASE(_displayData); + _displayData = data; + } + } + virtual DisplayData *getDisplayData() const { return _displayData; } #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT - CC_SYNTHESIZE_RETAIN(ColliderDetector *, _colliderDetector, ColliderDetector); + virtual void setColliderDetector(ColliderDetector *detector) + { + if (_colliderDetector != detector) + { + CC_SAFE_RETAIN(detector); + CC_SAFE_RELEASE(_colliderDetector); + _colliderDetector = detector; + } + } + virtual ColliderDetector *getColliderDetector() const { return _colliderDetector; } +#endif +protected: + cocos2d::Node *_display; + DisplayData *_displayData; + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + ColliderDetector *_colliderDetector; #endif }; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 5efa5510c7..52af6b2d1d 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -182,7 +182,7 @@ void DisplayManager::removeDisplay(int index) _decoDisplayList->removeObjectAtIndex(index); } -Array *DisplayManager::getDecorativeDisplayList() +Array *DisplayManager::getDecorativeDisplayList() const { return _decoDisplayList; } @@ -276,28 +276,28 @@ void DisplayManager::setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay) } } -Node *DisplayManager::getDisplayRenderNode() +Node *DisplayManager::getDisplayRenderNode() const { return _displayRenderNode; } -DisplayType DisplayManager::getDisplayRenderNodeType() +DisplayType DisplayManager::getDisplayRenderNodeType() const { return _displayType; } -int DisplayManager::getCurrentDisplayIndex() +int DisplayManager::getCurrentDisplayIndex() const { return _displayIndex; } -DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() +DecorativeDisplay *DisplayManager::getCurrentDecorativeDisplay() const { return _currentDecoDisplay; } -DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) +DecorativeDisplay *DisplayManager::getDecorativeDisplayByIndex( int index) const { return (DecorativeDisplay *)_decoDisplayList->getObjectAtIndex(index); } @@ -377,32 +377,32 @@ void DisplayManager::setVisible(bool visible) _displayRenderNode->setVisible(visible); } -bool DisplayManager::isVisible() +bool DisplayManager::isVisible() const { return _visible; } -Size DisplayManager::getContentSize() +Size DisplayManager::getContentSize() const { CS_RETURN_IF(!_displayRenderNode) Size(0, 0); return _displayRenderNode->getContentSize(); } -Rect DisplayManager::getBoundingBox() +Rect DisplayManager::getBoundingBox() const { CS_RETURN_IF(!_displayRenderNode) Rect(0, 0, 0, 0); return _displayRenderNode->getBoundingBox(); } -Point DisplayManager::getAnchorPoint() +Point DisplayManager::getAnchorPoint() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPoint(); } -Point DisplayManager::getAnchorPointInPoints() +Point DisplayManager::getAnchorPointInPoints() const { CS_RETURN_IF(!_displayRenderNode) Point(0, 0); return _displayRenderNode->getAnchorPointInPoints(); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.h b/cocos/editor-support/cocostudio/CCDisplayManager.h index 0856886c57..1f1b4190ba 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.h +++ b/cocos/editor-support/cocostudio/CCDisplayManager.h @@ -76,7 +76,7 @@ public: void removeDisplay(int index); - cocos2d::Array *getDecorativeDisplayList(); + cocos2d::Array *getDecorativeDisplayList() const; /** * Change display by index. You can just use this method to change display in the display list. @@ -90,14 +90,14 @@ public: void changeDisplayByIndex(int index, bool force); - cocos2d::Node *getDisplayRenderNode(); - DisplayType getDisplayRenderNodeType(); + cocos2d::Node *getDisplayRenderNode() const; + DisplayType getDisplayRenderNodeType() const; - int getCurrentDisplayIndex(); + int getCurrentDisplayIndex() const; virtual void setCurrentDecorativeDisplay(DecorativeDisplay *decoDisplay); - virtual DecorativeDisplay *getCurrentDecorativeDisplay(); - virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index); + virtual DecorativeDisplay *getCurrentDecorativeDisplay() const; + virtual DecorativeDisplay *getDecorativeDisplayByIndex( int index) const; /** * Sets whether the display is visible @@ -112,13 +112,13 @@ public: * @see setVisible(bool) * @return true if the node is visible, false if the node is hidden. */ - virtual bool isVisible(); + virtual bool isVisible() const; - cocos2d::Size getContentSize(); - cocos2d::Rect getBoundingBox(); + cocos2d::Size getContentSize() const; + cocos2d::Rect getBoundingBox() const; - cocos2d::Point getAnchorPoint(); - cocos2d::Point getAnchorPointInPoints(); + cocos2d::Point getAnchorPoint() const; + cocos2d::Point getAnchorPointInPoints() const; /** * Check if the position is inside the bone. @@ -130,6 +130,8 @@ public: */ virtual bool containPoint(float x, float y); + virtual void setForceChangeDisplay(bool force) { _forceChangeDisplay = force; } + virtual bool isForceChangeDisplay() const { return _forceChangeDisplay; } protected: cocos2d::Array *_decoDisplayList; //! Display render node. @@ -141,7 +143,7 @@ protected: //! Current display index int _displayIndex; - CC_SYNTHESIZE(bool, _forceChangeDisplay, ForceChangeDisplay) + bool _forceChangeDisplay; //! Whether of not the bone is visible. Default is true bool _visible; diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index e59244433e..c6b62793b4 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -114,6 +114,23 @@ public: virtual int getCurrentFrameIndex(); + virtual void setProcessScale(float processScale) { _processScale = processScale; } + virtual float getProcessScale() const { return _processScale; } + + virtual void setIsPause(bool pause) { _isPause = pause; } + virtual bool isPause() const { return _isPause; } + + virtual void setIsComplete(bool complete) { _isComplete = complete; } + virtual bool isComplete() const { return _isComplete; } + + virtual void setIsPlaying(bool playing) { _isPlaying = playing; } + virtual bool isPlaying() const { return _isPlaying; } + + virtual float getCurrentPercent() const { return _currentPercent; } + virtual int getRawDuration() const { return _rawDuration; } + + virtual void setAnimationInternal(float animationInternal) { _animationInternal = animationInternal; } + virtual float getAnimationInternal() const { return _animationInternal; } protected: virtual void gotoFrame(int frameIndex); @@ -125,31 +142,31 @@ protected: protected: //! Scale the process speed - CC_SYNTHESIZE(float, _processScale, ProcessScale); + float _processScale; //! Set and get whether the aniamtion is pause - CC_SYNTHESIZE(bool, _isPause, IsPause); + bool _isPause; //! Set and get whether the aniamtion is complete - CC_SYNTHESIZE(bool, _isComplete, IsComplete); + bool _isComplete; //! Set and get whether the aniamtion is playing - CC_SYNTHESIZE(bool, _isPlaying, IsPlaying); + bool _isPlaying; //! Current percent this process arrived - CC_SYNTHESIZE(float, _currentPercent, CurrentPercent); + float _currentPercent; //! The raw duration - CC_SYNTHESIZE(int, _rawDuration, RawDuration); + int _rawDuration; //! The animation whether or not loop - CC_SYNTHESIZE(AnimationType, _loopType, LoopType); + AnimationType _loopType; //! The tween easing effect - CC_SYNTHESIZE(TweenType, _tweenEasing, TweenEasing); + TweenType _tweenEasing; //! The animation update speed - CC_SYNTHESIZE(float, _animationInternal, AnimationInternal); + float _animationInternal; protected: diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index b0496729f4..62710e561d 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -224,7 +224,7 @@ void Skin::setBone(Bone *bone) } } -Bone *Skin::getBone() +Bone *Skin::getBone() const { return _bone; } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 2d934b8e4b..6e62da7d22 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,22 +39,28 @@ public: public: Skin(); - bool initWithSpriteFrameName(const char *pszSpriteFrameName); - bool initWithFile(const char *pszFilename); + bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; + bool initWithFile(const char *pszFilename) override; void updateArmatureTransform(); - void updateTransform(); + void updateTransform() override; - cocos2d::AffineTransform getNodeToWorldTransform() const; + cocos2d::AffineTransform getNodeToWorldTransform() const override; cocos2d::AffineTransform getNodeToWorldTransformAR() const; - CC_PROPERTY_PASS_BY_REF(BaseData, _skinData, SkinData); - CC_PROPERTY(Bone *, _bone, Bone); + virtual void setSkinData(const BaseData &data); + virtual const BaseData &getSkinData() const; + virtual void setBone(Bone *bone); + virtual Bone *getBone() const; + + virtual const std::string &getDisplayName() const { return _displayName; } protected: + BaseData _skinData; + Bone *_bone; Armature *_armature; cocos2d::AffineTransform _skinTransform; - CC_SYNTHESIZE_READONLY(std::string, _displayName, DisplayName) + std::string _displayName; }; } diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index 75ff8bbb7e..dec84bf295 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -328,7 +328,7 @@ void Tween::arriveKeyFrame(FrameData *keyFrameData) //! Change bone's display int displayIndex = keyFrameData->displayIndex; - if (!displayManager->getForceChangeDisplay()) + if (!displayManager->isForceChangeDisplay()) { displayManager->changeDisplayByIndex(displayIndex, false); } diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index ce08f2264e..8b4dcba9d2 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -88,6 +88,9 @@ public: virtual void gotoAndPlay(int frameIndex); virtual void gotoAndPause(int frameIndex); + + virtual void setMovementBoneData(MovementBoneData *data) { _movementBoneData = data; } + virtual const MovementBoneData *getMovementBoneData() const { return _movementBoneData; } protected: /** @@ -121,7 +124,7 @@ protected: virtual void arriveKeyFrame(FrameData *keyFrameData); protected: //! A weak reference to the current MovementBoneData. The data is in the data pool - CC_SYNTHESIZE(MovementBoneData *, _movementBoneData, MovementBoneData) + MovementBoneData *_movementBoneData; FrameData *_tweenData; //! The computational tween frame data, //! A weak reference to the Bone's tweenData FrameData *_from; //! From frame data, used for calculate between value diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index b571dfb808..65cd9044ef 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -271,9 +271,9 @@ std::string TestAsynchronousLoading::subtitle() return "current percent : "; } -void TestAsynchronousLoading::restartCallback(CCObject* pSender) +void TestAsynchronousLoading::restartCallback(Object* pSender) { - ArmatureDataManager::getInstance()->purge(); + ArmatureDataManager::getInstance()->destoryInstance(); ArmatureTestLayer::restartCallback(pSender); } void TestAsynchronousLoading::dataLoaded(float percent) @@ -307,7 +307,7 @@ void TestDirectLoading::onEnter() Armature *armature = Armature::create("bear"); armature->getAnimation()->playByIndex(0); - armature->setPosition(ccp(VisibleRect::center().x, VisibleRect::center().y)); + armature->setPosition(Point(VisibleRect::center().x, VisibleRect::center().y)); addChild(armature); } std::string TestDirectLoading::title() @@ -608,7 +608,7 @@ void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIn } void TestFrameEvent::checkAction(float dt) { - if ( this->numberOfRunningActions() == 0 && this->getGrid() != nullptr) + if ( this->getNumberOfRunningActions() == 0 && this->getGrid() != nullptr) this->setGrid(nullptr); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index f8429fc595..79e29b61dc 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -74,7 +74,7 @@ public: virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); - virtual void restartCallback(CCObject* pSender); + virtual void restartCallback(Object* pSender); void dataLoaded(float percent); }; From af129e25f008aeeb58eba99677a8c0e44c2e1f11 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 5 Nov 2013 20:02:58 +0800 Subject: [PATCH 410/557] issue #2771: change some coding style --- cocos/base/CCGeometry.cpp | 10 ++ cocos/base/CCGeometry.h | 10 ++ cocos/physics/CCPhysicsBody.cpp | 100 ++++++++--------- cocos/physics/CCPhysicsBody.h | 32 +++--- cocos/physics/CCPhysicsContact.cpp | 4 +- cocos/physics/CCPhysicsContact.h | 2 +- cocos/physics/CCPhysicsJoint.cpp | 26 ++--- cocos/physics/CCPhysicsSetting.h | 3 + cocos/physics/CCPhysicsShape.cpp | 104 +++++++++--------- cocos/physics/CCPhysicsShape.h | 48 ++++---- cocos/physics/CCPhysicsWorld.cpp | 88 +++++++-------- cocos/physics/CCPhysicsWorld.h | 14 +-- .../chipmunk/CCPhysicsBodyInfo_chipmunk.cpp | 9 +- .../chipmunk/CCPhysicsBodyInfo_chipmunk.h | 8 +- .../CCPhysicsContactInfo_chipmunk.cpp | 2 +- .../chipmunk/CCPhysicsContactInfo_chipmunk.h | 5 +- .../chipmunk/CCPhysicsJointInfo_chipmunk.cpp | 28 ++--- .../chipmunk/CCPhysicsJointInfo_chipmunk.h | 12 +- .../chipmunk/CCPhysicsShapeInfo_chipmunk.cpp | 56 +++++----- .../chipmunk/CCPhysicsShapeInfo_chipmunk.h | 20 +++- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 8 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 12 +- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 4 +- 24 files changed, 325 insertions(+), 286 deletions(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 1d5c4896c6..8ab9e39dda 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -96,6 +96,16 @@ bool Point::operator!=(const Point& right) return this->x != right.x || this->y != right.y; } +bool Point::operator==(const Point& right) const +{ + return this->x == right.x && this->y == right.y; +} + +bool Point::operator!=(const Point& right) const +{ + return this->x != right.x || this->y != right.y; +} + Point Point::operator*(float a) const { return Point(this->x * a, this->y * a); diff --git a/cocos/base/CCGeometry.h b/cocos/base/CCGeometry.h index 847557cb35..3b6b8c2655 100644 --- a/cocos/base/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -123,6 +123,16 @@ public: * @lua NA */ bool operator!=(const Point& right); + /** + * @js NA + * @lua NA + */ + bool operator==(const Point& right) const; + /** + * @js NA + * @lua NA + */ + bool operator!=(const Point& right) const; /** * @js NA * @lua NA diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 8a177e6252..131bfdc3c5 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -157,7 +157,7 @@ PhysicsBody* PhysicsBody::create(float mass, float moment) } -PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createCircle(float radius, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -171,7 +171,7 @@ PhysicsBody* PhysicsBody::createCircle(float radius, PhysicsMaterial material, P return nullptr; } -PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -185,7 +185,7 @@ PhysicsBody* PhysicsBody::createBox(Size size, PhysicsMaterial material, Point o return nullptr; } -PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMaterial material, Point offset) +PhysicsBody* PhysicsBody::createPolygon(const Point* points, int count, const PhysicsMaterial& material, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -199,7 +199,7 @@ PhysicsBody* PhysicsBody::createPolygon(Point* points, int count, PhysicsMateria return nullptr; } -PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -214,7 +214,7 @@ PhysicsBody* PhysicsBody::createEdgeSegment(Point a, Point b, PhysicsMaterial ma return nullptr; } -PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, float border/* = 1*/, Point offset) +PhysicsBody* PhysicsBody::createEdgeBox(const Size& size, const PhysicsMaterial& material, float border/* = 1*/, const Point& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -230,7 +230,7 @@ PhysicsBody* PhysicsBody::createEdgeBox(Size size, PhysicsMaterial material, flo return nullptr; } -PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -246,7 +246,7 @@ PhysicsBody* PhysicsBody::createEdgePolygon(Point* points, int count, PhysicsMat return nullptr; } -PhysicsBody* PhysicsBody::createEdgeChain(Point* points, int count, PhysicsMaterial material, float border/* = 1*/) +PhysicsBody* PhysicsBody::createEdgeChain(const Point* points, int count, const PhysicsMaterial& material, float border/* = 1*/) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) @@ -272,9 +272,9 @@ bool PhysicsBody::init() CC_BREAK_IF(_shapes == nullptr); _shapes->retain(); - _info->body = cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment)); + _info->setBody(cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment))); - CC_BREAK_IF(_info->body == nullptr); + CC_BREAK_IF(_info->getBody() == nullptr); return true; } while (false); @@ -289,19 +289,19 @@ void PhysicsBody::setDynamic(bool dynamic) _dynamic = dynamic; if (dynamic) { - cpBodySetMass(_info->body, _mass); + cpBodySetMass(_info->getBody(), _mass); if (_world != nullptr) { - cpSpaceAddBody(_world->_info->space, _info->body); + cpSpaceAddBody(_world->_info->getSpace(), _info->getBody()); } }else { - cpBodySetMass(_info->body, PHYSICS_INFINITY); + cpBodySetMass(_info->getBody(), PHYSICS_INFINITY); if (_world != nullptr) { - cpSpaceRemoveBody(_world->_info->space, _info->body); + cpSpaceRemoveBody(_world->_info->getSpace(), _info->getBody()); } } @@ -312,7 +312,7 @@ void PhysicsBody::setRotationEnable(bool enable) { if (_rotationEnable != enable) { - cpBodySetMoment(_info->body, enable ? _moment : PHYSICS_INFINITY); + cpBodySetMoment(_info->getBody(), enable ? _moment : PHYSICS_INFINITY); _rotationEnable = enable; } } @@ -338,23 +338,23 @@ void PhysicsBody::setGravityEnable(bool enable) void PhysicsBody::setPosition(Point position) { - cpBodySetPos(_info->body, PhysicsHelper::point2cpv(position)); + cpBodySetPos(_info->getBody(), PhysicsHelper::point2cpv(position)); } void PhysicsBody::setRotation(float rotation) { - cpBodySetAngle(_info->body, PhysicsHelper::float2cpfloat(rotation)); + cpBodySetAngle(_info->getBody(), PhysicsHelper::float2cpfloat(rotation)); } Point PhysicsBody::getPosition() const { - cpVect vec = cpBodyGetPos(_info->body); + cpVect vec = cpBodyGetPos(_info->getBody()); return PhysicsHelper::cpv2point(vec); } float PhysicsBody::getRotation() const { - return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->body) / 3.14f * 180.0f); + return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->getBody()) / 3.14f * 180.0f); } PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) @@ -388,29 +388,29 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape) return shape; } -void PhysicsBody::applyForce(Point force) +void PhysicsBody::applyForce(const Vect& force) { applyForce(force, Point::ZERO); } -void PhysicsBody::applyForce(Point force, Point offset) +void PhysicsBody::applyForce(const Vect& force, const Point& offset) { - cpBodyApplyForce(_info->body, PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); + cpBodyApplyForce(_info->getBody(), PhysicsHelper::point2cpv(force), PhysicsHelper::point2cpv(offset)); } -void PhysicsBody::applyImpulse(Point impulse) +void PhysicsBody::applyImpulse(const Vect& impulse) { applyImpulse(impulse, Point()); } -void PhysicsBody::applyImpulse(Point impulse, Point offset) +void PhysicsBody::applyImpulse(const Vect& impulse, const Point& offset) { - cpBodyApplyImpulse(_info->body, PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); + cpBodyApplyImpulse(_info->getBody(), PhysicsHelper::point2cpv(impulse), PhysicsHelper::point2cpv(offset)); } void PhysicsBody::applyTorque(float torque) { - cpBodySetTorque(_info->body, PhysicsHelper::float2cpfloat(torque)); + cpBodySetTorque(_info->getBody(), PhysicsHelper::float2cpfloat(torque)); } void PhysicsBody::setMass(float mass) @@ -439,7 +439,7 @@ void PhysicsBody::setMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMass(float mass) @@ -481,7 +481,7 @@ void PhysicsBody::addMass(float mass) } } - cpBodySetMass(_info->body, PhysicsHelper::float2cpfloat(_mass)); + cpBodySetMass(_info->getBody(), PhysicsHelper::float2cpfloat(_mass)); } void PhysicsBody::addMoment(float moment) @@ -522,58 +522,58 @@ void PhysicsBody::addMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -void PhysicsBody::setVelocity(Point velocity) +void PhysicsBody::setVelocity(const Point& velocity) { - cpBodySetVel(_info->body, PhysicsHelper::point2cpv(velocity)); + cpBodySetVel(_info->getBody(), PhysicsHelper::point2cpv(velocity)); } Point PhysicsBody::getVelocity() { - return PhysicsHelper::cpv2point(cpBodyGetVel(_info->body)); + return PhysicsHelper::cpv2point(cpBodyGetVel(_info->getBody())); } -Point PhysicsBody::getVelocityAtLocalPoint(Point point) +Point PhysicsBody::getVelocityAtLocalPoint(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyGetVelAtLocalPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); } -Point PhysicsBody::getVelocityAtWorldPoint(Point point) +Point PhysicsBody::getVelocityAtWorldPoint(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyGetVelAtWorldPoint(_info->getBody(), PhysicsHelper::point2cpv(point))); } void PhysicsBody::setAngularVelocity(float velocity) { - cpBodySetAngVel(_info->body, PhysicsHelper::float2cpfloat(velocity)); + cpBodySetAngVel(_info->getBody(), PhysicsHelper::float2cpfloat(velocity)); } float PhysicsBody::getAngularVelocity() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVel(_info->getBody())); } void PhysicsBody::setVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetVelLimit(_info->getBody())); } void PhysicsBody::setAngularVelocityLimit(float limit) { - cpBodySetVelLimit(_info->body, PhysicsHelper::float2cpfloat(limit)); + cpBodySetVelLimit(_info->getBody(), PhysicsHelper::float2cpfloat(limit)); } float PhysicsBody::getAngularVelocityLimit() { - return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->body)); + return PhysicsHelper::cpfloat2float(cpBodyGetAngVelLimit(_info->getBody())); } void PhysicsBody::setMoment(float moment) @@ -583,11 +583,11 @@ void PhysicsBody::setMoment(float moment) if (_rotationEnable) { - cpBodySetMoment(_info->body, PhysicsHelper::float2cpfloat(_moment)); + cpBodySetMoment(_info->getBody(), PhysicsHelper::float2cpfloat(_moment)); } } -PhysicsShape* PhysicsBody::getShapeByTag(int tag) const +PhysicsShape* PhysicsBody::getShape(int tag) const { for (auto child : *_shapes) { @@ -601,7 +601,7 @@ PhysicsShape* PhysicsBody::getShapeByTag(int tag) const return nullptr; } -void PhysicsBody::removeShapeByTag(int tag) +void PhysicsBody::removeShape(int tag) { for (auto child : *_shapes) { @@ -685,7 +685,7 @@ void PhysicsBody::setEnable(bool enable) bool PhysicsBody::isResting() const { - return cpBodyIsSleeping(_info->body) == cpTrue; + return cpBodyIsSleeping(_info->getBody()) == cpTrue; } void PhysicsBody::update(float delta) @@ -693,9 +693,9 @@ void PhysicsBody::update(float delta) // damping compute if (_dynamic) { - _info->body->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); - _info->body->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); + _info->getBody()->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); + _info->getBody()->w *= cpfclamp(1.0f - delta * _angularDamping, 0.0f, 1.0f); } } @@ -739,12 +739,12 @@ void PhysicsBody::setGroup(int group) Point PhysicsBody::world2Local(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->getBody(), PhysicsHelper::point2cpv(point))); } Point PhysicsBody::local2World(const Point& point) { - return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->body, PhysicsHelper::point2cpv(point))); + return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->getBody(), PhysicsHelper::point2cpv(point))); } #elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 60dd314966..7c0c79002e 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -59,62 +59,62 @@ public: /** * @brief Create a body contains a circle shape. */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a box shape. */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a polygon shape. * points is an array of Point structs defining a convex hull with a clockwise winding. */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, Point offset = Point::ZERO); + static PhysicsBody* createPolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgeSegment shape. */ - static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeSegment(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeBox shape. */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, Point offset = Point::ZERO); + static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); /** * @brief Create a body contains a EdgePolygon shape. */ - static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgePolygon(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); /** * @brief Create a body contains a EdgeChain shape. */ - static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); + static PhysicsBody* createEdgeChain(const Point* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); virtual PhysicsShape* addShape(PhysicsShape* shape); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force); + virtual void applyForce(const Vect& force); /** * @brief Applies a immediate force to body. */ - virtual void applyForce(Point force, Point offset); + virtual void applyForce(const Vect& force, const Point& offset); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse); + virtual void applyImpulse(const Vect& impulse); /** * @brief Applies a continuous force to body. */ - virtual void applyImpulse(Point impulse, Point offset); + virtual void applyImpulse(const Vect& impulse, const Point& offset); /** * @brief Applies a torque force to body. */ virtual void applyTorque(float torque); - virtual void setVelocity(Point velocity); + virtual void setVelocity(const Vect& velocity); virtual Point getVelocity(); virtual void setAngularVelocity(float velocity); - virtual Point getVelocityAtLocalPoint(Point point); - virtual Point getVelocityAtWorldPoint(Point point); + virtual Point getVelocityAtLocalPoint(const Point& point); + virtual Point getVelocityAtWorldPoint(const Point& point); virtual float getAngularVelocity(); virtual void setVelocityLimit(float limit); virtual float getVelocityLimit(); @@ -129,12 +129,12 @@ public: * @brief get the first body shapes. */ inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } - PhysicsShape* getShapeByTag(int tag) const; + PhysicsShape* getShape(int tag) const; /* * @brief remove a shape from body */ void removeShape(PhysicsShape* shape); - void removeShapeByTag(int tag); + void removeShape(int tag); /* * @brief remove all shapes */ diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index e3a4907a97..71bdf5a1d0 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -150,9 +150,9 @@ void PhysicsContactPreSolve::setFriction(float friction) static_cast(_contactInfo)->u = friction; } -void PhysicsContactPreSolve::setSurfaceVelocity(Point surfaceVelocity) +void PhysicsContactPreSolve::setSurfaceVelocity(const Vect& velocity) { - static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(surfaceVelocity); + static_cast(_contactInfo)->surface_vr = PhysicsHelper::point2cpv(velocity); } void PhysicsContactPreSolve::ignore() diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index ee279ef474..3982f4fdd6 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -138,7 +138,7 @@ public: Point getSurfaceVelocity() const; void setElasticity(float elasticity); void setFriction(float friction); - void setSurfaceVelocity(Point surfaceVelocity); + void setSurfaceVelocity(const Vect& velocity); void ignore(); private: diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 694559264e..791266f8ba 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -197,13 +197,13 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) getBodyNode(b)->setPosition(anchr); // add a pivot joint to fixed two body together - cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); _info->add(joint); // add a gear joint to make two body have the same rotation. - joint = cpGearJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, 0, 1); + joint = cpGearJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), 0, 1); CC_BREAK_IF(joint == nullptr); _info->add(joint); @@ -233,7 +233,7 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) do { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpPivotJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr)); CC_BREAK_IF(joint == nullptr); @@ -248,12 +248,12 @@ bool PhysicsJointPin::init(PhysicsBody *a, PhysicsBody *b, const Point& anchr) void PhysicsJointPin::setMaxForce(float force) { - _info->joints.front()->maxForce = PhysicsHelper::float2cpfloat(force); + _info->getJoints().front()->maxForce = PhysicsHelper::float2cpfloat(force); } float PhysicsJointPin::getMaxForce() const { - return PhysicsHelper::cpfloat2float(_info->joints.front()->maxForce); + return PhysicsHelper::cpfloat2float(_info->getJoints().front()->maxForce); } PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) @@ -275,7 +275,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpGrooveJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(grooveA), PhysicsHelper::point2cpv(grooveB), PhysicsHelper::point2cpv(anchr)); @@ -310,7 +310,7 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->body, getBodyInfo(b)->body, + cpConstraint* joint = cpSlideJointNew(getBodyInfo(a)->getBody(), getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2), 0, @@ -328,22 +328,22 @@ bool PhysicsJointLimit::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1 float PhysicsJointLimit::getMin() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMin(_info->getJoints().front())); } void PhysicsJointLimit::setMin(float min) { - cpSlideJointSetMin(_info->joints.front(), PhysicsHelper::float2cpfloat(min)); + cpSlideJointSetMin(_info->getJoints().front(), PhysicsHelper::float2cpfloat(min)); } float PhysicsJointLimit::getMax() const { - return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->joints.front())); + return PhysicsHelper::cpfloat2float(cpSlideJointGetMax(_info->getJoints().front())); } void PhysicsJointLimit::setMax(float max) { - cpSlideJointSetMax(_info->joints.front(), PhysicsHelper::float2cpfloat(max)); + cpSlideJointSetMax(_info->getJoints().front(), PhysicsHelper::float2cpfloat(max)); } PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) @@ -365,8 +365,8 @@ bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anc { CC_BREAK_IF(!PhysicsJoint::init(a, b)); - cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->body, - getBodyInfo(b)->body, + cpConstraint* joint = cpPinJointNew(getBodyInfo(a)->getBody(), + getBodyInfo(b)->getBody(), PhysicsHelper::point2cpv(anchr1), PhysicsHelper::point2cpv(anchr2)); CC_BREAK_IF(joint == nullptr); diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index ee3214bcd7..9eb82f2fa2 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -47,6 +47,9 @@ namespace cocos2d { extern const float PHYSICS_INFINITY; + class Point; + typedef Point Vect; + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) static const int PHYSICS_CONTACT_POINT_MAX = 4; #else diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index fea8365c08..89d0551cff 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -105,7 +105,7 @@ void PhysicsShape::setMoment(float moment) _moment = moment; } -void PhysicsShape::setMaterial(PhysicsMaterial material) +void PhysicsShape::setMaterial(const PhysicsMaterial& material) { setDensity(material.density); setRestitution(material.restitution); @@ -216,7 +216,7 @@ void PhysicsShape::setRestitution(float restitution) { _material.restitution = restitution; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution)); } @@ -226,14 +226,14 @@ void PhysicsShape::setFriction(float friction) { _material.friction = friction; - for (cpShape* shape : _info->shapes) + for (cpShape* shape : _info->getShapes()) { cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction)); } } -Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) +Point* PhysicsShape::recenterPoints(Point* points, int count, const Point& center) { cpVect* cpvs = new cpVect[count]; cpRecenterPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -251,7 +251,7 @@ Point* PhysicsShape::recenterPoints(Point* points, int count, Point center) return points; } -Point PhysicsShape::getPolyonCenter(Point* points, int count) +Point PhysicsShape::getPolyonCenter(const Point* points, int count) { cpVect* cpvs = new cpVect[count]; cpVect center = cpCentroidForPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count)); @@ -280,14 +280,14 @@ void PhysicsShape::setBody(PhysicsBody *body) _body = nullptr; }else { - _info->setBody(body->_info->body); + _info->setBody(body->_info->getBody()); //_info->setGroup(body->_info->group); _body = body; } } // PhysicsShapeCircle -PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeCircle* shape = new PhysicsShapeCircle(); if (shape && shape->init(radius, material, offset)) @@ -300,13 +300,13 @@ PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, PhysicsMaterial mat return nullptr; } -bool PhysicsShapeCircle::init(float radius, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE)); - cpShape* shape = cpCircleShapeNew(_info->shareBody, radius, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpCircleShapeNew(_info->getSharedBody(), radius, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -328,7 +328,7 @@ float PhysicsShapeCircle::calculateArea(float radius) return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius)); } -float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset) +float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Point& offset) { return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), @@ -339,12 +339,12 @@ float PhysicsShapeCircle::calculateMoment(float mass, float radius, Point offset float PhysicsShapeCircle::calculateDefaultArea() { - return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->shapes.front()))); + return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->getShapes().front()))); } float PhysicsShapeCircle::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), @@ -355,16 +355,16 @@ float PhysicsShapeCircle::calculateDefaultMoment() float PhysicsShapeCircle::getRadius() const { - return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->shapes.front())); + return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->getShapes().front())); } Point PhysicsShapeCircle::getOffset() { - return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->shapes.front())); + return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->getShapes().front())); } // PhysicsShapeEdgeSegment -PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment(); if (shape && shape->init(a, b, material, border)) @@ -377,13 +377,13 @@ PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(Point a, Point b, Physi return nullptr; } -bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeSegment::init(const Point& a, const Point& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { do { CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT)); - cpShape* shape = cpSegmentShapeNew(_info->shareBody, + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), PhysicsHelper::point2cpv(a), PhysicsHelper::point2cpv(b), PhysicsHelper::float2cpfloat(border)); @@ -407,12 +407,12 @@ bool PhysicsShapeEdgeSegment::init(Point a, Point b, PhysicsMaterial material/* Point PhysicsShapeEdgeSegment::getPointA() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->ta); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->ta); } Point PhysicsShapeEdgeSegment::getPointB() const { - return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->shapes.front()))->tb); + return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->tb); } Point PhysicsShapeEdgeSegment::getCenter() @@ -421,7 +421,7 @@ Point PhysicsShapeEdgeSegment::getCenter() } // PhysicsShapeBox -PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeBox* PhysicsShapeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeBox* shape = new PhysicsShapeBox(); if (shape && shape->init(size, material, offset)) @@ -434,7 +434,7 @@ PhysicsShapeBox* PhysicsShapeBox::create(Size size, PhysicsMaterial material/* = return nullptr; } -bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, Point offset /*= Point(0, 0)*/) +bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset /*= Point(0, 0)*/) { do { @@ -446,7 +446,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} }; - cpShape* shape = cpPolyShapeNew(_info->shareBody, 4, vec, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), 4, vec, PhysicsHelper::point2cpv(offset)); CC_BREAK_IF(shape == nullptr); @@ -465,7 +465,7 @@ bool PhysicsShapeBox::init(Size size, PhysicsMaterial material/* = MaterialDefau return false; } -float PhysicsShapeBox::calculateArea(Size size) +float PhysicsShapeBox::calculateArea(const Size& size) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -475,7 +475,7 @@ float PhysicsShapeBox::calculateArea(Size size) return PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec)); } -float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) +float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Point& offset) { cpVect wh = PhysicsHelper::size2cpv(size); cpVect vec[4] = @@ -492,20 +492,20 @@ float PhysicsShapeBox::calculateMoment(float mass, Size size, Point offset) float PhysicsShapeBox::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapeBox::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } Point* PhysicsShapeBox::getPoints(Point* points) const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); return points; @@ -513,13 +513,13 @@ Point* PhysicsShapeBox::getPoints(Point* points) const Size PhysicsShapeBox::getSize() const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1)), cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)))); } // PhysicsShapePolygon -PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +PhysicsShapePolygon* PhysicsShapePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapePolygon* shape = new PhysicsShapePolygon(); if (shape && shape->init(points, count, material, offset)) @@ -532,7 +532,7 @@ PhysicsShapePolygon* PhysicsShapePolygon::create(Point* points, int count, Physi return nullptr; } -bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, Point offset/* = Point(0, 0)*/) +bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Point& offset/* = Point(0, 0)*/) { do { @@ -540,7 +540,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - cpShape* shape = cpPolyShapeNew(_info->shareBody, count, vecs, PhysicsHelper::point2cpv(offset)); + cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset)); CC_SAFE_DELETE(vecs); CC_BREAK_IF(shape == nullptr); @@ -560,7 +560,7 @@ bool PhysicsShapePolygon::init(Point* points, int count, PhysicsMaterial materia return false; } -float PhysicsShapePolygon::calculateArea(Point* points, int count) +float PhysicsShapePolygon::calculateArea(const Point* points, int count) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -570,7 +570,7 @@ float PhysicsShapePolygon::calculateArea(Point* points, int count) return area; } -float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, Point offset) +float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int count, const Point& offset) { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); @@ -583,31 +583,31 @@ float PhysicsShapePolygon::calculateMoment(float mass, Point* points, int count, float PhysicsShapePolygon::calculateDefaultArea() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); } float PhysicsShapePolygon::calculateDefaultMoment() { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } Point PhysicsShapePolygon::getPoint(int i) const { - return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->shapes.front(), i)); + return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i)); } Point* PhysicsShapePolygon::getPoints(Point* points) const { - cpShape* shape = _info->shapes.front(); + cpShape* shape = _info->getShapes().front(); return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } int PhysicsShapePolygon::getPointsCount() const { - return ((cpPolyShape*)_info->shapes.front())->numVerts; + return ((cpPolyShape*)_info->getShapes().front())->numVerts; } Point PhysicsShapePolygon::getCenter() @@ -616,7 +616,7 @@ Point PhysicsShapePolygon::getCenter() } // PhysicsShapeEdgeBox -PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/* = Point(0, 0)*/) +PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/* = Point(0, 0)*/) { PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox(); if (shape && shape->init(size, material, border, offset)) @@ -629,7 +629,7 @@ PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(Size size, PhysicsMaterial mate return nullptr; } -bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/, Point offset/*= Point(0, 0)*/) +bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Point& offset/*= Point(0, 0)*/) { do { @@ -644,7 +644,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD int i = 0; for (; i < 4; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%4], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%4], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); _info->add(shape); @@ -664,7 +664,7 @@ bool PhysicsShapeEdgeBox::init(Size size, PhysicsMaterial material/* = MaterialD } // PhysicsShapeEdgeBox -PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon(); if (shape && shape->init(points, count, material, border)) @@ -677,7 +677,7 @@ PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(Point* points, int coun return nullptr; } -bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgePolygon::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -691,7 +691,7 @@ bool PhysicsShapeEdgePolygon::init(Point* points, int count, PhysicsMaterial mat int i = 0; for (; i < count; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[(i+1)%count], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%count], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -722,11 +722,11 @@ Point PhysicsShapeEdgePolygon::getCenter() int PhysicsShapeEdgePolygon::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; } // PhysicsShapeEdgeChain -PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain(); if (shape && shape->init(points, count, material, border)) @@ -739,7 +739,7 @@ PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(Point* points, int count, P return nullptr; } -bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial material/* = MaterialDefault*/, float border/* = 1*/) +bool PhysicsShapeEdgeChain::init(const Point* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/) { cpVect* vec = nullptr; do @@ -753,7 +753,7 @@ bool PhysicsShapeEdgeChain::init(Point* points, int count, PhysicsMaterial mater int i = 0; for (; i < count - 1; ++i) { - cpShape* shape = cpSegmentShapeNew(_info->shareBody, vec[i], vec[i+1], + cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[i+1], PhysicsHelper::float2cpfloat(border)); CC_BREAK_IF(shape == nullptr); cpShapeSetElasticity(shape, 1.0f); @@ -783,23 +783,23 @@ Point PhysicsShapeEdgeChain::getCenter() int PhysicsShapeEdgeChain::getPointsCount() const { - return _info->shapes.size() + 1; + return _info->getShapes().size() + 1; } void PhysicsShape::setGroup(int group) { if (group < 0) { - for (auto shape : _info->shapes) + for (auto shape : _info->getShapes()) { cpShapeSetGroup(shape, (cpGroup)group); } } } -bool PhysicsShape::containsPoint(Point point) const +bool PhysicsShape::containsPoint(const Point& point) const { - for (auto shape : _info->shapes) + for (auto shape : _info->getShapes()) { if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point))) { diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4ddcfe8a18..4aba49d4d7 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -92,16 +92,16 @@ public: void setDensity(float density); void setRestitution(float restitution); void setFriction(float friction); - void setMaterial(PhysicsMaterial material); + void setMaterial(const PhysicsMaterial& material); virtual float calculateDefaultMoment() { return 0; } virtual float calculateDefaultArea() { return 0; } virtual Point getOffset() { return Point::ZERO; } virtual Point getCenter() { return getOffset(); } - bool containsPoint(Point point) const; + bool containsPoint(const Point& point) const; - static Point* recenterPoints(Point* points, int count, Point center = Point::ZERO); - static Point getPolyonCenter(Point* points, int count); + static Point* recenterPoints(Point* points, int count, const Point& center = Point::ZERO); + static Point getPolyonCenter(const Point* points, int count); inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } inline int getCategoryBitmask() const { return _categoryBitmask; } @@ -150,9 +150,9 @@ protected: class PhysicsShapeCircle : public PhysicsShape { public: - static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + static PhysicsShapeCircle* create(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point(0, 0)); static float calculateArea(float radius); - static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); + static float calculateMoment(float mass, float radius, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -160,7 +160,7 @@ public: float getRadius() const; Point getOffset() override; protected: - bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeCircle(); @@ -171,9 +171,9 @@ protected: class PhysicsShapeBox : public PhysicsShape { public: - static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Size size); - static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); + static PhysicsShapeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Size& size); + static float calculateMoment(float mass, const Size& size, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -183,7 +183,7 @@ public: Point getOffset() override { return _offset; } protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeBox(); @@ -197,9 +197,9 @@ protected: class PhysicsShapePolygon : public PhysicsShape { public: - static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Point* points, int count); - static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); + static PhysicsShapePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); + static float calculateArea(const Point* points, int count); + static float calculateMoment(float mass, const Point* points, int count, const Point& offset = Point::ZERO); float calculateDefaultArea() override; float calculateDefaultMoment() override; @@ -209,7 +209,7 @@ public: int getPointsCount() const; Point getCenter() override; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapePolygon(); @@ -223,14 +223,14 @@ protected: class PhysicsShapeEdgeSegment : public PhysicsShape { public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgeSegment* create(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getPointA() const; Point getPointB() const; Point getCenter() override; protected: - bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeSegment(); @@ -246,13 +246,13 @@ protected: class PhysicsShapeEdgeBox : public PhysicsShape { public: - static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); + static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); Point getOffset() override { return _offset; } - Point* getPoints(Point* points) const; + Point* getPoints(const Point* points) const; int getPointsCount() const; protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); + bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, const Point& offset = Point::ZERO); protected: PhysicsShapeEdgeBox(); @@ -268,13 +268,13 @@ protected: class PhysicsShapeEdgePolygon : public PhysicsShape { public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; int getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgePolygon(); @@ -290,13 +290,13 @@ protected: class PhysicsShapeEdgeChain : public PhysicsShape { public: - static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); Point getCenter() override; Point* getPoints(Point* points) const; int getPointsCount() const; protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); + bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); protected: PhysicsShapeEdgeChain(); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index cafdb79be8..2a067720c1 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -106,11 +106,11 @@ int PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSp { CP_ARBITER_GET_SHAPES(arb, a, b); - auto ita = PhysicsShapeInfo::map.find(a); - auto itb = PhysicsShapeInfo::map.find(b); - CC_ASSERT(ita != PhysicsShapeInfo::map.end() && itb != PhysicsShapeInfo::map.end()); + auto ita = PhysicsShapeInfo::getMap().find(a); + auto itb = PhysicsShapeInfo::getMap().find(b); + CC_ASSERT(ita != PhysicsShapeInfo::getMap().end() && itb != PhysicsShapeInfo::getMap().end()); - PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); + PhysicsContact* contact = PhysicsContact::create(ita->second->getShape(), itb->second->getShape()); arb->data = contact; contact->_contactInfo = arb; @@ -143,12 +143,12 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect return; } - auto it = PhysicsShapeInfo::map.find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + auto it = PhysicsShapeInfo::getMap().find(shape); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); PhysicsRayCastCallback::Info callbackInfo = { - it->second->shape, + it->second->getShape(), info->p1, info->p2, Point(info->p1.x+(info->p2.x-info->p1.x)*t, info->p1.y+(info->p2.y-info->p1.y)*t), @@ -161,9 +161,9 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); if (!PhysicsWorldCallback::continues) { @@ -171,17 +171,17 @@ void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallba } PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->shape, + *it->second->getShape(), info->data); } void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) { - auto it = PhysicsShapeInfo::map.find(shape); + auto it = PhysicsShapeInfo::getMap().find(shape); - CC_ASSERT(it != PhysicsShapeInfo::map.end()); + CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - arr->addObject(it->second->shape); + arr->addObject(it->second->getShape()); } bool PhysicsWorld::init(Scene& scene) @@ -202,9 +202,9 @@ bool PhysicsWorld::init(Scene& scene) _scene = &scene; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(_gravity)); - cpSpaceSetDefaultCollisionHandler(_info->space, + cpSpaceSetDefaultCollisionHandler(_info->getSpace(), (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, @@ -225,7 +225,7 @@ void PhysicsWorld::delayTestAddBody(PhysicsBody* body) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (_delayAddBodies->getIndexOfObject(body) == UINT_MAX) { @@ -246,7 +246,7 @@ void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (_delayRemoveBodies->getIndexOfObject(body) == UINT_MAX) { @@ -268,7 +268,7 @@ void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) { @@ -290,7 +290,7 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) return; } - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) { @@ -338,7 +338,7 @@ void PhysicsWorld::removeAllJoints() PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { _info->addShape(cps); } @@ -348,7 +348,7 @@ PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) void PhysicsWorld::realAddJoint(PhysicsJoint *joint) { - for (auto subjoint : joint->_info->joints) + for (auto subjoint : joint->_info->getJoints()) { _info->addJoint(subjoint); } @@ -374,7 +374,7 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) // add body to space if (body->isDynamic()) { - _info->addBody(body->_info->body); + _info->addBody(body->_info->getBody()); } // add shapes to space @@ -401,7 +401,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) _bodies->removeObject(body); } -void PhysicsWorld::removeBodyByTag(int tag) +void PhysicsWorld::removeBody(int tag) { for (Object* obj : *_bodies) { @@ -442,14 +442,14 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) } // remove body - _info->removeBody(body->_info->body); + _info->removeBody(body->_info->getBody()); body->_world = nullptr; } void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) { - for (auto subjoint : joint->_info->joints) + for (auto subjoint : joint->_info->getJoints()) { _info->removeJoint(subjoint); } @@ -468,18 +468,18 @@ void PhysicsWorld::removeAllBodies() void PhysicsWorld::removeShape(PhysicsShape* shape) { - for (auto cps : shape->_info->shapes) + for (auto cps : shape->_info->getShapes()) { - if (cpSpaceContainsShape(_info->space, cps)) + if (cpSpaceContainsShape(_info->getSpace(), cps)) { - cpSpaceRemoveShape(_info->space, cps); + cpSpaceRemoveShape(_info->getSpace(), cps); } } } void PhysicsWorld::updateBodies() { - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { return; } @@ -500,7 +500,7 @@ void PhysicsWorld::updateBodies() void PhysicsWorld::updateJoints() { - if (_info->space->locked_private) + if (_info->getSpace()->locked_private) { return; } @@ -533,7 +533,7 @@ void PhysicsWorld::update(float delta) body->update(delta); } - cpSpaceStep(_info->space, delta); + cpSpaceStep(_info->getSpace(), delta); if (_drawNode) { @@ -577,7 +577,7 @@ void PhysicsWorld::debugDraw() void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) { - for (auto it = joint->_info->joints.begin(); it != joint->_info->joints.end(); ++it) + for (auto it = joint->_info->getJoints().begin(); it != joint->_info->getJoints().end(); ++it) { cpConstraint *constraint = *it; @@ -638,7 +638,7 @@ void PhysicsWorld::drawWithJoint(DrawNode* node, PhysicsJoint* joint) void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) { - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) + for (auto it = shape->_info->getShapes().begin(); it != shape->_info->getShapes().end(); ++it) { cpShape *shape = *it; @@ -811,11 +811,11 @@ void PhysicsWorld::setGravity(Point gravity) } _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); + cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(gravity)); } -void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data) +void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data) { CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); @@ -824,7 +824,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point RayCastCallbackInfo info = { this, &callback, point1, point2, data }; PhysicsWorldCallback::continues = true; - cpSpaceSegmentQuery(this->_info->space, + cpSpaceSegmentQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point1), PhysicsHelper::point2cpv(point2), CP_ALL_LAYERS, @@ -835,7 +835,7 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, Point point1, Point } -void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data) +void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data) { CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); @@ -844,7 +844,7 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void RectQueryCallbackInfo info = {this, &callback, data}; PhysicsWorldCallback::continues = true; - cpSpaceBBQuery(this->_info->space, + cpSpaceBBQuery(this->_info->getSpace(), PhysicsHelper::rect2cpbb(rect), CP_ALL_LAYERS, CP_NO_GROUP, @@ -853,10 +853,10 @@ void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void } } -Array* PhysicsWorld::getShapesAtPoint(Point point) const +Array* PhysicsWorld::getShapes(const Point& point) const { Array* arr = Array::create(); - cpSpaceNearestPointQuery(this->_info->space, + cpSpaceNearestPointQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, @@ -867,16 +867,16 @@ Array* PhysicsWorld::getShapesAtPoint(Point point) const return arr; } -PhysicsShape* PhysicsWorld::getShapeAtPoint(Point point) const +PhysicsShape* PhysicsWorld::getShape(const Point& point) const { - cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->space, + cpShape* shape = cpSpaceNearestPointQueryNearest(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, CP_NO_GROUP, nullptr); - return shape == nullptr ? nullptr : PhysicsShapeInfo::map.find(shape)->second->shape; + return shape == nullptr ? nullptr : PhysicsShapeInfo::getMap().find(shape)->second->getShape(); } Array* PhysicsWorld::getAllBodies() const @@ -884,7 +884,7 @@ Array* PhysicsWorld::getAllBodies() const return _bodies; } -PhysicsBody* PhysicsWorld::getBodyByTag(int tag) const +PhysicsBody* PhysicsWorld::getBody(int tag) const { for (auto body : *_bodies) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 360844db3f..e4cad6e7eb 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -77,7 +77,7 @@ public: * @param normal the normal vector at the point of intersection * @return true to continue, false to terminate */ - std::function report; + std::function report; }; class PhysicsRectQueryCallback @@ -106,15 +106,15 @@ public: virtual void removeAllJoints(); virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); + virtual void removeBody(int tag); virtual void removeAllBodies(); - void rayCast(PhysicsRayCastCallback& callback, Point point1, Point point2, void* data); - void rectQuery(PhysicsRectQueryCallback& callback, Rect rect, void* data); - Array* getShapesAtPoint(Point point) const; - PhysicsShape* getShapeAtPoint(Point point) const; + void rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data); + void rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data); + Array* getShapes(const Point& point) const; + PhysicsShape* getShape(const Point& point) const; Array* getAllBodies() const; - PhysicsBody* getBodyByTag(int tag) const; + PhysicsBody* getBody(int tag) const; /** Register a listener to receive contact callbacks*/ //inline void registerContactListener(EventListenerPhysicsContact* delegate) { _listener = delegate; } diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 42ce5cc7ec..79ad011c17 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -27,18 +27,13 @@ NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() -: body(nullptr) +: _body(nullptr) { } PhysicsBodyInfo::~PhysicsBodyInfo() { - if (body) cpBodyFree(body); -} - -Clonable* PhysicsBodyInfo::clone() const -{ - return nullptr; + if (_body) cpBodyFree(_body); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 19e43c23fb..dd2d276ac5 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -34,16 +34,18 @@ NS_CC_BEGIN -class PhysicsBodyInfo : public Clonable +class PhysicsBodyInfo { public: - cpBody* body; + inline cpBody* getBody() const { return _body; } + inline void setBody(cpBody* body) { _body = body; } private: PhysicsBodyInfo(); ~PhysicsBodyInfo(); - Clonable* clone() const override; +private: + cpBody* _body; friend class PhysicsBody; }; diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 283a4998ab..150c77a030 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -27,7 +27,7 @@ NS_CC_BEGIN PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) -: contact(contact) +: _contact(contact) { } diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 7dc6561fec..4b01ad9d53 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -36,12 +36,15 @@ class PhysicsContact; class PhysicsContactInfo { public: - PhysicsContact* contact; + inline PhysicsContact* getContact() const { return _contact; } private: PhysicsContactInfo(PhysicsContact* contact); ~PhysicsContactInfo(); +private: + PhysicsContact* _contact; + friend class PhysicsContact; }; diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index 82053ce4b1..2f8b7817cf 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -27,16 +27,16 @@ #include NS_CC_BEGIN -std::map PhysicsJointInfo::map; +std::map PhysicsJointInfo::_map; PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) -: joint(joint) +: _joint(joint) { } PhysicsJointInfo::~PhysicsJointInfo() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { cpConstraintFree(joint); } @@ -46,21 +46,21 @@ void PhysicsJointInfo::add(cpConstraint* joint) { if (joint == nullptr) return; - joints.push_back(joint); - map.insert(std::pair(joint, this)); + _joints.push_back(joint); + _map.insert(std::pair(joint, this)); } void PhysicsJointInfo::remove(cpConstraint* joint) { if (joint == nullptr) return; - auto it = std::find(joints.begin(), joints.end(), joint); - if (it != joints.end()) + auto it = std::find(_joints.begin(), _joints.end(), joint); + if (it != _joints.end()) { - joints.erase(it); + _joints.erase(it); - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } @@ -68,14 +68,14 @@ void PhysicsJointInfo::remove(cpConstraint* joint) void PhysicsJointInfo::removeAll() { - for (cpConstraint* joint : joints) + for (cpConstraint* joint : _joints) { - auto mit = map.find(joint); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(joint); + if (mit != _map.end()) _map.erase(mit); cpConstraintFree(joint); } - joints.clear(); + _joints.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 8116c48eae..016cd74d12 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -43,15 +43,19 @@ public: void remove(cpConstraint* shape); void removeAll(); -public: - std::vector joints; - PhysicsJoint* joint; - static std::map map; + PhysicsJoint* getJoint() const { return _joint; } + std::vector& getJoints() { return _joints; } + static std::map& getMap() { return _map; } private: PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); +private: + std::vector _joints; + PhysicsJoint* _joint; + static std::map _map; + friend class PhysicsJoint; }; diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index 74abfc75f1..d12a053181 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -27,27 +27,27 @@ #include NS_CC_BEGIN -std::map PhysicsShapeInfo::map; -cpBody* PhysicsShapeInfo::shareBody = nullptr; +std::map PhysicsShapeInfo::_map; +cpBody* PhysicsShapeInfo::_sharedBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) -: shape(shape) -, group(CP_NO_GROUP) +: _shape(shape) +, _group(CP_NO_GROUP) { - if (shareBody == nullptr) + if (_sharedBody == nullptr) { - shareBody = cpBodyNewStatic(); + _sharedBody = cpBodyNewStatic(); } - body = shareBody; + _body = _sharedBody; } PhysicsShapeInfo::~PhysicsShapeInfo() { - for (auto shape : shapes) + for (auto shape : _shapes) { - auto it = map.find(shape); - if (it != map.end()) map.erase(shape); + auto it = _map.find(shape); + if (it != _map.end()) _map.erase(shape); cpShapeFree(shape); } @@ -55,9 +55,9 @@ PhysicsShapeInfo::~PhysicsShapeInfo() void PhysicsShapeInfo::setGroup(cpGroup group) { - this->group = group; + this->_group = group; - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { cpShapeSetGroup(shape, group); } @@ -65,12 +65,12 @@ void PhysicsShapeInfo::setGroup(cpGroup group) void PhysicsShapeInfo::setBody(cpBody* body) { - if (this->body != body) + if (this->_body != body) { - this->body = body; - for (cpShape* shape : shapes) + this->_body = body; + for (cpShape* shape : _shapes) { - cpShapeSetBody(shape, body == nullptr ? shareBody : body); + cpShapeSetBody(shape, body == nullptr ? _sharedBody : body); } } } @@ -79,22 +79,22 @@ void PhysicsShapeInfo::add(cpShape* shape) { if (shape == nullptr) return; - cpShapeSetGroup(shape, group); - shapes.push_back(shape); - map.insert(std::pair(shape, this)); + cpShapeSetGroup(shape, _group); + _shapes.push_back(shape); + _map.insert(std::pair(shape, this)); } void PhysicsShapeInfo::remove(cpShape* shape) { if (shape == nullptr) return; - auto it = std::find(shapes.begin(), shapes.end(), shape); - if (it != shapes.end()) + auto it = std::find(_shapes.begin(), _shapes.end(), shape); + if (it != _shapes.end()) { - shapes.erase(it); + _shapes.erase(it); - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } @@ -102,14 +102,14 @@ void PhysicsShapeInfo::remove(cpShape* shape) void PhysicsShapeInfo::removeAll() { - for (cpShape* shape : shapes) + for (cpShape* shape : _shapes) { - auto mit = map.find(shape); - if (mit != map.end()) map.erase(mit); + auto mit = _map.find(shape); + if (mit != _map.end()) _map.erase(mit); cpShapeFree(shape); } - shapes.clear(); + _shapes.clear(); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 83be655b02..b519fd378a 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -47,17 +47,25 @@ public: void setBody(cpBody* body); public: - std::vector shapes; - PhysicsShape* shape; - cpBody* body; - cpGroup group; - static std::map map; - static cpBody* shareBody; + PhysicsShape* getShape() const { return _shape; } + std::vector& getShapes() { return _shapes; } + cpBody* getBody() const { return _body; } + cpGroup getGourp() const { return _group; } + static std::map& getMap() { return _map; } + static cpBody* getSharedBody() { return _sharedBody; } private: PhysicsShapeInfo(PhysicsShape* shape); ~PhysicsShapeInfo(); +private: + std::vector _shapes; + PhysicsShape* _shape; + cpBody* _body; + cpGroup _group; + static std::map _map; + static cpBody* _sharedBody; + friend class PhysicsShape; }; diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index fecf2009aa..a12e473ec1 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -29,12 +29,12 @@ NS_CC_BEGIN #define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ void PhysicsWorldInfo::add##name(cp##type* data) \ { \ - if (!cpSpaceContains##type(space, data)) cpSpaceAdd##type(space, data); \ + if (!cpSpaceContains##type(_space, data)) cpSpaceAdd##type(_space, data); \ } \ \ void PhysicsWorldInfo::remove##name(cp##type* data) \ { \ - if (cpSpaceContains##type(space, data)) cpSpaceRemove##type(space, data); \ + if (cpSpaceContains##type(_space, data)) cpSpaceRemove##type(_space, data); \ } \ PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) @@ -43,12 +43,12 @@ PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) PhysicsWorldInfo::PhysicsWorldInfo() { - space = cpSpaceNew(); + _space = cpSpaceNew(); } PhysicsWorldInfo::~PhysicsWorldInfo() { - cpSpaceFree(space); + cpSpaceFree(_space); } NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 5e6c78bc97..b50e1a3240 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -36,8 +36,7 @@ NS_CC_BEGIN class PhysicsWorldInfo { public: - cpSpace* space; - + cpSpace* getSpace() const { return _space; } void addShape(cpShape* shape); void removeShape(cpShape* shape); void addBody(cpBody* body); @@ -49,6 +48,9 @@ private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); +private: + cpSpace* _space; + friend class PhysicsWorld; }; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 99ce9d0c90..88b17e365e 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -602,7 +602,7 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data) { *((Point*)data) = info.contact; return false; @@ -620,7 +620,7 @@ private: PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() : _friction(1.0f) { - report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool + report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool { if (_friction > info.fraction) { @@ -650,7 +650,7 @@ public: PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() : num(0) { - report = [this](PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data)->bool + report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool { if (num < MAX_MULTI_RAYCAST_NUM) { @@ -1089,7 +1089,7 @@ void PhysicsDemoSlice::onEnter() addChild(box); } -bool PhysicsDemoSlice::slice(PhysicsWorld &world, PhysicsRayCastCallback::Info &info, void *data) +bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastCallback::Info &info, void *data) { if (info.shape->getBody()->getTag() != _sliceTag) { @@ -1150,6 +1150,8 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float polyon->setAngularVelocity(body->getAngularVelocity()); polyon->setTag(_sliceTag); addChild(node); + + delete[] points; } void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) @@ -1171,7 +1173,7 @@ std::string PhysicsDemoSlice::subtitle() void PhysicsDemoWater::onEnter() { - + PhysicsDemo::onEnter(); } std::string PhysicsDemoWater::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 425dbc56f9..7355045cad 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - bool anyRay(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + bool anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); private: float _angle; @@ -150,7 +150,7 @@ public: std::string title() override; std::string subtitle() override; - bool slice(PhysicsWorld& world, PhysicsRayCastCallback::Info& info, void* data); + bool slice(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); bool onTouchBegan(Touch *touch, Event *event); From 8b86373b08ccc2126c8cb1eac4e6ae59331bc325 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Tue, 5 Nov 2013 20:33:29 +0800 Subject: [PATCH 411/557] 1.Change to range-based loop --- .../cocostudio/CCArmatureDataManager.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index c8278387ce..0e139ef560 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -115,24 +115,24 @@ void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) { if (RelativeData *data = getRelativeData(configFilePath)) { - for (std::vector::iterator i = data->armatures.begin(); i != data->armatures.end(); i++) + for (std::string str : data->armatures) { - removeArmatureData(i->c_str()); + removeArmatureData(str.c_str()); } - for (std::vector::iterator i = data->animations.begin(); i != data->animations.end(); i++) + for (std::string str : data->animations) { - removeAnimationData(i->c_str()); + removeAnimationData(str.c_str()); } - for (std::vector::iterator i = data->textures.begin(); i != data->textures.end(); i++) + for (std::string str : data->textures) { - removeTextureData(i->c_str()); + removeTextureData(str.c_str()); } - for (std::vector::iterator i = data->plistFiles.begin(); i != data->plistFiles.end(); i++) + for (std::string str : data->plistFiles) { - SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(i->c_str()); + SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(str.c_str()); } _relativeDatas.erase(configFilePath); From 471dd07f3b33074755807a3b95e29f0497523975 Mon Sep 17 00:00:00 2001 From: Chris Hannon Date: Tue, 5 Nov 2013 15:54:31 -0500 Subject: [PATCH 412/557] [android] update nativeactivity.cpp to work with changes made in commit 0220f27 (AMD support), changing int to long int for the second argument in most touch callbacks --- cocos/2d/platform/android/nativeactivity.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 5ac17a5ee5..12e25d597d 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -292,7 +292,7 @@ static void engine_term_display(struct engine* engine) { /* * Get X, Y positions and ID's for all pointers */ -static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { +static void getTouchPos(AInputEvent *event, long ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); @@ -321,7 +321,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -340,7 +340,7 @@ static int32_t handle_touch_input(AInputEvent *event) { LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -353,10 +353,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; @@ -369,7 +369,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -387,7 +387,7 @@ static int32_t handle_touch_input(AInputEvent *event) { float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); - int pId = pointerId; + long pId = pointerId; float x = xP; float y = yP; @@ -400,10 +400,10 @@ static int32_t handle_touch_input(AInputEvent *event) { { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; + long ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; From 84a6aa29cd61e7624830f1461d6aa00047d0a934 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 5 Nov 2013 17:36:44 -0800 Subject: [PATCH 413/557] Adds more 64-bit fixes Replaces more `int` with `long` where it makes sense. Also , it repalces some `unsigned long` with `long` for "lenght" values as described in our c++ guideline --- cocos/2d/CCDirector.cpp | 4 +- cocos/2d/CCDirector.h | 2 +- cocos/2d/CCFontFreeType.cpp | 4 +- cocos/2d/CCTextureCache.cpp | 6 +-- cocos/2d/CCUserDefault.cpp | 2 +- cocos/2d/CCUserDefault.mm | 4 +- cocos/2d/TGAlib.cpp | 10 ++--- cocos/2d/ZipUtils.cpp | 28 +++++++------- cocos/2d/ZipUtils.h | 20 +++++----- cocos/2d/platform/CCFileUtils.cpp | 4 +- cocos/2d/platform/CCFileUtils.h | 4 +- cocos/2d/platform/CCImage.h | 4 +- cocos/2d/platform/CCImageCommon_cpp.h | 28 +++++++------- cocos/2d/platform/CCSAXParser.cpp | 8 ++-- cocos/base/CCString.cpp | 38 +++++++++---------- .../editor-support/cocosbuilder/CCBReader.cpp | 2 +- .../cocosbuilder/CCNodeLoader.cpp | 2 +- .../cocostudio/CCDataReaderHelper.cpp | 4 +- .../cocostudio/CCSGUIReader.cpp | 4 +- .../cocostudio/CCSSceneReader.cpp | 8 ++-- cocos/editor-support/spine/spine-cocos2dx.cpp | 2 +- .../javascript/bindings/ScriptingCore.cpp | 2 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 23 files changed, 96 insertions(+), 96 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 7255659d07..130d170d30 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -831,7 +831,7 @@ void Director::calculateMPF() } // returns the FPS image data pointer and len -void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length) +void Director::getFPSImageData(unsigned char** datapointer, long* length) { // XXX fixed me if it should be used *datapointer = cc_fps_images_png; @@ -855,7 +855,7 @@ void Director::createStatsLabel() Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); unsigned char *data = nullptr; - unsigned int dataLength = 0; + long dataLength = 0; getFPSImageData(&data, &dataLength); Image* image = new Image(); diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 5f0d6eb0a8..b01b0fe954 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -376,7 +376,7 @@ protected: void showStats(); void createStatsLabel(); void calculateMPF(); - void getFPSImageData(unsigned char** datapointer, unsigned int* length); + void getFPSImageData(unsigned char** datapointer, long* length); /** calculates delta time since last time it was called */ void calculateDeltaTime(); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 0e4e49d96f..5e2173204f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -99,8 +99,8 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) { FT_Face face; - int len = 0; - _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len)); + long len = 0; + _ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len); if (!_ttfData) return false; diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 95c02f8ff4..8f3fc6fe3a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -614,10 +614,10 @@ void VolatileTexture::reloadAllTextures() case kImageFile: { Image* image = new Image(); - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &nSize); + long size = 0; + unsigned char* pBuffer = FileUtils::getInstance()->getFileData(vt->_fileName.c_str(), "rb", &size); - if (image && image->initWithImageData(pBuffer, nSize)) + if (image && image->initWithImageData(pBuffer, size)) { Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat); diff --git a/cocos/2d/CCUserDefault.cpp b/cocos/2d/CCUserDefault.cpp index 5a85d65b41..2104051f76 100644 --- a/cocos/2d/CCUserDefault.cpp +++ b/cocos/2d/CCUserDefault.cpp @@ -58,7 +58,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; //CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt"); - unsigned long nSize; + long nSize; const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) diff --git a/cocos/2d/CCUserDefault.mm b/cocos/2d/CCUserDefault.mm index b55acfcf24..da1c8827fd 100644 --- a/cocos/2d/CCUserDefault.mm +++ b/cocos/2d/CCUserDefault.mm @@ -73,8 +73,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/TGAlib.cpp b/cocos/2d/TGAlib.cpp index ba4ca83b01..8725e765cb 100644 --- a/cocos/2d/TGAlib.cpp +++ b/cocos/2d/TGAlib.cpp @@ -198,8 +198,8 @@ tImageTGA * tgaLoad(const char *filename) int mode,total; tImageTGA *info = NULL; - unsigned long nSize = 0; - unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &nSize); + long size = 0; + unsigned char* pBuffer = FileUtils::getInstance()->getFileData(filename, "rb", &size); do { @@ -207,7 +207,7 @@ tImageTGA * tgaLoad(const char *filename) info = (tImageTGA *)malloc(sizeof(tImageTGA)); // get the file header info - if (! tgaLoadHeader(pBuffer, nSize, info)) + if (! tgaLoadHeader(pBuffer, size, info)) { info->status = TGA_ERROR_MEMORY; break; @@ -245,11 +245,11 @@ tImageTGA * tgaLoad(const char *filename) // finally load the image pixels if ( info->type == 10 ) { - bLoadImage = tgaLoadRLEImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadRLEImageData(pBuffer, size, info); } else { - bLoadImage = tgaLoadImageData(pBuffer, nSize, info); + bLoadImage = tgaLoadImageData(pBuffer, size, info); } // check for errors when reading the pixels diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index db2fab18ce..2e5d9fe43f 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false; // --------------------- ZipUtils --------------------- -inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) +inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len) { const int enclen = 1024; const int securelen = 512; @@ -108,7 +108,7 @@ inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) } } -inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) +inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, long len) { unsigned int cs = 0; const int cslen = 128; @@ -127,12 +127,12 @@ inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) // Should buffer factor be 1.5 instead of 2 ? #define BUFFER_INC_FACTOR (2) -int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, unsigned int outLenghtHint) +int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint) { /* ret value */ int err = Z_OK; - int bufferSize = outLenghtHint; + long bufferSize = outLenghtHint; *out = new unsigned char[bufferSize]; z_stream d_stream; /* decompression stream */ @@ -192,9 +192,9 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, return err; } -int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLengthHint) +int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint) { - unsigned int outLength = 0; + long outLength = 0; int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); if (err != Z_OK || *out == NULL) { @@ -223,7 +223,7 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, return outLength; } -int ZipUtils::ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out) +int ZipUtils::ccInflateMemory(unsigned char *in, long inLength, unsigned char **out) { // 256k for hint return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024); @@ -304,7 +304,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -316,7 +316,7 @@ bool ZipUtils::ccIsCCZFile(const char *path) return ccIsCCZBuffer(compressed, fileLen); } -bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, int len) +bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, long len) { if (len < sizeof(struct CCZHeader)) { @@ -333,7 +333,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -345,7 +345,7 @@ bool ZipUtils::ccIsGZipFile(const char *path) return ccIsGZipBuffer(compressed, fileLen); } -bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len) +bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, long len) { if (len < 2) { @@ -356,7 +356,7 @@ bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, int len) } -int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, int bufferLen, unsigned char **out) +int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out) { struct CCZHeader *header = (struct CCZHeader*) buffer; @@ -454,7 +454,7 @@ int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out) // load file into memory unsigned char* compressed = NULL; - unsigned long fileLen = 0; + long fileLen = 0; compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen); if(NULL == compressed || 0 == fileLen) @@ -582,7 +582,7 @@ bool ZipFile::fileExists(const std::string &fileName) const return ret; } -unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long *pSize) +unsigned char *ZipFile::getFileData(const std::string &fileName, long *pSize) { unsigned char * pBuffer = NULL; if (pSize) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index 5564807540..48552502b4 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -64,7 +64,7 @@ namespace cocos2d * @since v0.8.1 */ - static int ccInflateMemory(unsigned char *in, unsigned int inLength, unsigned char **out); + static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out); /** * Inflates either zlib or gzip deflated memory. The inflated memory is @@ -76,7 +76,7 @@ namespace cocos2d * @since v1.0.0 */ - static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int outLenghtHint); + static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLenghtHint); /** inflates a GZip file into memory * @@ -100,7 +100,7 @@ namespace cocos2d * * @since v3.0 */ - static bool ccIsGZipBuffer(const unsigned char *buffer, int len); + static bool ccIsGZipBuffer(const unsigned char *buffer, long len); /** inflates a CCZ file into memory * @@ -116,7 +116,7 @@ namespace cocos2d * * @since v3.0 */ - static int ccInflateCCZBuffer(const unsigned char *buffer, int len, unsigned char **out); + static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out); /** test a file is a CCZ format file or not * @@ -132,7 +132,7 @@ namespace cocos2d * * @since v3.0 */ - static bool ccIsCCZBuffer(const unsigned char *buffer, int len); + static bool ccIsCCZBuffer(const unsigned char *buffer, long len); /** Sets the pvr.ccz encryption key parts separately for added * security. @@ -187,10 +187,10 @@ namespace cocos2d static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); private: - static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, - unsigned int outLenghtHint); - static inline void ccDecodeEncodedPvr (unsigned int *data, int len); - static inline unsigned int ccChecksumPvr(const unsigned int *data, int len); + static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, + long outLenghtHint); + static inline void ccDecodeEncodedPvr (unsigned int *data, long len); + static inline unsigned int ccChecksumPvr(const unsigned int *data, long len); static unsigned int s_uEncryptedPvrKeyParts[4]; static unsigned int s_uEncryptionKey[1024]; @@ -253,7 +253,7 @@ namespace cocos2d * * @since v2.0.5 */ - unsigned char *getFileData(const std::string &fileName, unsigned long *pSize); + unsigned char *getFileData(const std::string &fileName, long *size); private: /** Internal data like zip file pointer / file list array and so on */ diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index d7244ba6f0..6760432cad 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -488,7 +488,7 @@ void FileUtils::purgeCachedEntries() _fullPathCache.clear(); } -unsigned char* FileUtils::getFileData(const char* filename, const char* mode, unsigned long * size) +unsigned char* FileUtils::getFileData(const char* filename, const char* mode, long *size) { unsigned char * buffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); @@ -518,7 +518,7 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, un return buffer; } -unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long * size) +unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char* filename, long *size) { unsigned char * buffer = NULL; unzFile pFile = NULL; diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 299807af01..855f016fe5 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -88,7 +88,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size); + virtual unsigned char* getFileData(const char* filename, const char* mode, long *size); /** * Gets resource file data from a zip file. @@ -98,7 +98,7 @@ public: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, unsigned long *size); + virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, long *size); /** Returns the fullpath for a given filename. diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index 25f09dade2..1f2e04ced7 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -119,10 +119,10 @@ public: * @js NA * @lua NA */ - bool initWithImageData(const unsigned char * data, int dataLen); + bool initWithImageData(const unsigned char * data, long dataLen); // @warning kFmtRawData only support RGBA8888 - bool initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti = false); + bool initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti = false); /** @brief Create image with specified string. diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index be7480a0ae..f2fc7a9a08 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -416,7 +416,7 @@ bool Image::initWithImageFile(const char * strPath) SDL_FreeSurface(iSurf); #else - unsigned long bufferLen = 0; + long bufferLen = 0; unsigned char* buffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "rb", &bufferLen); if (buffer != nullptr && bufferLen > 0) @@ -432,23 +432,23 @@ bool Image::initWithImageFile(const char * strPath) bool Image::initWithImageFileThreadSafe(const char *fullpath) { - bool bRet = false; - unsigned long dataLen = 0; + bool ret = false; + long dataLen = 0; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) FileUtilsAndroid *fileUitls = (FileUtilsAndroid*)FileUtils::getInstance(); - unsigned char *pBuffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); + unsigned char *buffer = fileUitls->getFileDataForAsync(fullpath, "rb", &dataLen); #else - unsigned char *pBuffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); + unsigned char *buffer = FileUtils::getInstance()->getFileData(fullpath, "rb", &dataLen); #endif - if (pBuffer != NULL && dataLen > 0) + if (buffer != NULL && dataLen > 0) { - bRet = initWithImageData(pBuffer, dataLen); + ret = initWithImageData(buffer, dataLen); } - CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + CC_SAFE_DELETE_ARRAY(buffer); + return ret; } -bool Image::initWithImageData(const unsigned char * data, int dataLen) +bool Image::initWithImageData(const unsigned char * data, long dataLen) { bool ret = false; @@ -1190,13 +1190,13 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (!testFormatForPvr2TCSupport(formatFlags)) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1204,7 +1204,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen) if (it == Texture2D::getPixelFormatInfoMap().end()) { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", formatFlags); + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); return false; } @@ -1757,7 +1757,7 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen) return bRet; } -bool Image::initWithRawData(const unsigned char * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti) +bool Image::initWithRawData(const unsigned char * data, long dataLen, long width, long height, long bitsPerComponent, bool preMulti) { bool bRet = false; do diff --git a/cocos/2d/platform/CCSAXParser.cpp b/cocos/2d/platform/CCSAXParser.cpp index 0f823f938d..04201557c1 100644 --- a/cocos/2d/platform/CCSAXParser.cpp +++ b/cocos/2d/platform/CCSAXParser.cpp @@ -114,15 +114,15 @@ bool SAXParser::parse(const char* pXMLData, unsigned int uDataLength) bool SAXParser::parse(const char *pszFile) { - bool bRet = false; - unsigned long size = 0; + bool ret = false; + long size = 0; char* pBuffer = (char*)FileUtils::getInstance()->getFileData(pszFile, "rt", &size); if (pBuffer != NULL && size > 0) { - bRet = parse(pBuffer, size); + ret = parse(pBuffer, size); } CC_SAFE_DELETE_ARRAY(pBuffer); - return bRet; + return ret; } void SAXParser::startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts) diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index f9962b1ba4..67193eb52c 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -216,15 +216,15 @@ bool String::isEqual(const Object* pObject) String* String::create(const std::string& str) { - String* pRet = new String(str); - pRet->autorelease(); - return pRet; + String* ret = new String(str); + ret->autorelease(); + return ret; } -String* String::createWithData(const unsigned char* pData, unsigned long nLen) +String* String::createWithData(const unsigned char* data, unsigned long nLen) { - String* pRet = NULL; - if (pData != NULL) + String* ret = NULL; + if (data != NULL) { char* pStr = (char*)malloc(nLen+1); if (pStr != NULL) @@ -232,36 +232,36 @@ String* String::createWithData(const unsigned char* pData, unsigned long nLen) pStr[nLen] = '\0'; if (nLen > 0) { - memcpy(pStr, pData, nLen); + memcpy(pStr, data, nLen); } - pRet = String::create(pStr); + ret = String::create(pStr); free(pStr); } } - return pRet; + return ret; } String* String::createWithFormat(const char* format, ...) { - String* pRet = String::create(""); + String* ret = String::create(""); va_list ap; va_start(ap, format); - pRet->initWithFormatAndValist(format, ap); + ret->initWithFormatAndValist(format, ap); va_end(ap); - return pRet; + return ret; } String* String::createWithContentsOfFile(const char* filename) { - unsigned long size = 0; - unsigned char* pData = 0; - String* pRet = NULL; - pData = FileUtils::getInstance()->getFileData(filename, "rb", &size); - pRet = String::createWithData(pData, size); - CC_SAFE_DELETE_ARRAY(pData); - return pRet; + long size = 0; + unsigned char* data = 0; + String* ret = NULL; + data = FileUtils::getInstance()->getFileData(filename, "rb", &size); + ret = String::createWithData(data, size); + CC_SAFE_DELETE_ARRAY(data); + return ret; } void String::acceptVisitor(DataVisitor &visitor) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 938c595f46..154d2b0b36 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -244,7 +244,7 @@ Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, } std::string strPath = FileUtils::getInstance()->fullPathForFilename(strCCBFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(strPath.c_str(), "rb", &size); Data *data = new Data(pBytes, size); diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index f1aedc7104..e82764ce86 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -918,7 +918,7 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader // Load sub file std::string path = FileUtils::getInstance()->fullPathForFilename(ccbFileName.c_str()); - unsigned long size = 0; + long size = 0; unsigned char * pBytes = FileUtils::getInstance()->getFileData(path.c_str(), "rb", &size); CCBReader * reader = new CCBReader(pCCBReader); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 4749f5eaf9..b03d2b1f1f 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -298,7 +298,7 @@ void DataReaderHelper::addDataFromFile(const char *filePath) size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; - unsigned long size; + long size; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); const char *pFileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); @@ -389,7 +389,7 @@ void DataReaderHelper::addDataFromFileAsync(const char *filePath, Object *target std::string str = &filePathStr[startPos]; std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); - unsigned long size; + long size; data->fileContent = (char *)CCFileUtils::getInstance()->getFileData(fullPath.c_str() , "r", &size); if (str.compare(".xml") == 0) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 77cb5d56de..5e199edbbc 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -207,7 +207,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) JsonDictionary *jsonDict = NULL; jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); - unsigned long size = 0; + long size = 0; des = (char*)(FileUtils::getInstance()->getFileData(jsonpath.c_str(),"r" , &size)); if(NULL == des || strcmp(des, "") == 0) { @@ -225,7 +225,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) } int texturesCount = DICTOOL->getArrayCount_json(jsonDict, "textures"); - int pos = jsonpath.find_last_of('/'); + long pos = jsonpath.find_last_of('/'); m_strFilePath = jsonpath.substr(0,pos+1); for (int i=0; igetFileData(pPath.c_str(),"r" , &size)); JsonDictionary *jsonDict = new JsonDictionary(); jsonDict->initWithDescription(des); @@ -227,7 +227,7 @@ namespace cocostudio { const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); - for (int i = 0; i < childrenCount; ++i) + for (long i = 0; i < childrenCount; ++i) { const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); std::string plistpath; @@ -283,7 +283,7 @@ namespace cocostudio { if (nResType == 0) { pAttribute = ComAttribute::create(); - unsigned long size = 0; + long size = 0; const char* pData = 0; pData = (char*)(cocos2d::FileUtils::getInstance()->getFileData(pPath.c_str(), "r", &size)); if(pData != NULL && strcmp(pData, "") != 0) diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index cd9ea67e30..dbc389db51 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -47,7 +47,7 @@ void _AtlasPage_disposeTexture (AtlasPage* self) { } char* _Util_readFile (const char* path, int* length) { - unsigned long size; + long size; char* data = reinterpret_cast(FileUtils::getInstance()->getFileData( FileUtils::getInstance()->fullPathForFilename(path).c_str(), "r", &size)); *length = size; diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 5d902c1c23..1f7f01c566 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -527,7 +527,7 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; - unsigned long length = 0; + long length = 0; unsigned char* data = futil->getFileData(byteCodePath.c_str(), "rb", &length); diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 39e01fd1ef..071cbc433d 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file +827b30175daeeaa135581f3546d5458db6d9dcdf \ No newline at end of file From 8b1d3af720c334546f7d1cb4cf86d4bbddd66b6f Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Tue, 5 Nov 2013 23:55:24 -0300 Subject: [PATCH 414/557] added | operator for Control::EventType --- .../GUI/CCControlExtension/CCControl.cpp | 5 +++++ extensions/GUI/CCControlExtension/CCControl.h | 2 ++ .../CCControlButtonTest.cpp | 19 ++++++++++++++++++- .../CCControlButtonTest/CCControlButtonTest.h | 2 ++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 13d86e629c..15fe7b1a8d 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -326,4 +326,9 @@ bool Control::hasVisibleParents() const } return true; } + +Control::EventType operator|(Control::EventType a, Control::EventType b) { + return static_cast(static_cast(a) | static_cast(b)); +} + NS_CC_EXT_END diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index d8644a516f..12533f7041 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -262,6 +262,8 @@ protected: CC_SYNTHESIZE_READONLY(State, _state, State); }; +Control::EventType operator|(Control::EventType a, Control::EventType b); + // end of GUI group /// @} /// @} diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp index a7fe134383..d5914b2db1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp @@ -110,6 +110,7 @@ ControlButton *ControlButtonTest_HelloVariableSize::standardButtonWithTitle(cons ControlButtonTest_Event::ControlButtonTest_Event() : _displayValueLabel(NULL) +, _displayBitmaskLabel(NULL) { } @@ -117,6 +118,7 @@ ControlButtonTest_Event::ControlButtonTest_Event() ControlButtonTest_Event::~ControlButtonTest_Event() { CC_SAFE_RELEASE_NULL(_displayValueLabel); + CC_SAFE_RELEASE_NULL(_displayBitmaskLabel); } bool ControlButtonTest_Event::init() @@ -130,7 +132,13 @@ bool ControlButtonTest_Event::init() _displayValueLabel->setAnchorPoint(Point(0.5f, -1)); _displayValueLabel->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 2.0f)); addChild(_displayValueLabel, 1); - + + setDisplayBitmaskLabel(LabelTTF::create("No bitmask event", "Marker Felt", 24)); + _displayBitmaskLabel->setAnchorPoint(Point(0.5f, -1)); + Point bitmaskLabelPos = _displayValueLabel->getPosition() - Point(0, _displayBitmaskLabel->getBoundingBox().size.height); + _displayBitmaskLabel->setPosition(bitmaskLabelPos); + addChild(_displayBitmaskLabel, 1); + // Add the button auto backgroundButton = Scale9Sprite::create("extensions/button.png"); auto backgroundHighlightedButton = Scale9Sprite::create("extensions/buttonHighlighted.png"); @@ -162,11 +170,20 @@ bool ControlButtonTest_Event::init() controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpInsideAction), Control::EventType::TOUCH_UP_INSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchUpOutsideAction), Control::EventType::TOUCH_UP_OUTSIDE); controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchCancelAction), Control::EventType::TOUCH_CANCEL); + // test for issue 2882 + controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(ControlButtonTest_Event::touchBitmaskAction), + Control::EventType::TOUCH_DOWN | Control::EventType::DRAG_INSIDE | Control::EventType::DRAG_OUTSIDE | Control::EventType::DRAG_ENTER | Control::EventType::DRAG_EXIT | Control::EventType::TOUCH_UP_INSIDE | Control::EventType::TOUCH_UP_OUTSIDE | Control::EventType::TOUCH_CANCEL | Control::EventType::VALUE_CHANGED); + return true; } return false; } +void ControlButtonTest_Event::touchBitmaskAction(Object *senderz, Control::EventType controlEvent) +{ + _displayBitmaskLabel->setString(String::createWithFormat("using bitmask (%d)", controlEvent)->getCString()); +} + void ControlButtonTest_Event::touchDownAction(Object *senderz, Control::EventType controlEvent) { _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h index 6e4d602107..1efbf9c604 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h @@ -54,8 +54,10 @@ public: void touchUpInsideAction(Object *sender, Control::EventType controlEvent); void touchUpOutsideAction(Object *sender, Control::EventType controlEvent); void touchCancelAction(Object *sender, Control::EventType controlEvent); + void touchBitmaskAction(Object *sender, Control::EventType controlEvent); protected: CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayValueLabel, DisplayValueLabel) + CC_SYNTHESIZE_RETAIN(LabelTTF *, _displayBitmaskLabel, DisplayBitmaskLabel) CONTROL_SCENE_CREATE_FUNC(ControlButtonTest_Event) }; From c364c4f083c815b133f7f5580e2345b8112b3f77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 10:55:39 +0800 Subject: [PATCH 415/557] issue #3113: Updating CMakeLists.txt, Improve Copying files. --- build/BuildHelpers.CMakeLists.txt | 60 +++++------------------------ samples/Cpp/HelloCpp/CMakeLists.txt | 5 ++- samples/Cpp/TestCpp/CMakeLists.txt | 5 ++- samples/Lua/HelloLua/CMakeLists.txt | 8 ++-- samples/Lua/TestLua/CMakeLists.txt | 11 +++--- 5 files changed, 27 insertions(+), 62 deletions(-) diff --git a/build/BuildHelpers.CMakeLists.txt b/build/BuildHelpers.CMakeLists.txt index 92d537dd7d..6e848d4f29 100644 --- a/build/BuildHelpers.CMakeLists.txt +++ b/build/BuildHelpers.CMakeLists.txt @@ -1,53 +1,13 @@ -# This file was copied from GamePlay -# Copies files for the given game into the target res directory -# GAME_NAME name of the game -# REL_DIR to which directory these files are relative -# SRC_FILES which files from the REL_DIR to copy (GLOB) -macro(COPY_RES_FILES GAME_NAME GAME_RES_TARGET REL_DIR SRC_FILES) - file( GLOB_RECURSE RES_FILES RELATIVE ${REL_DIR} ${SRC_FILES} ) +macro(pre_build TARGET_NAME) + add_custom_target( ${TARGET_NAME}_PRE_BUILD ALL ) - set(ALL_FILES) - foreach(SRC_FILE ${RES_FILES}) - IF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) - add_custom_command( - OUTPUT "${APP_BIN_DIR}/${SRC_FILE}" - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${REL_DIR}/${SRC_FILE}" - "${APP_BIN_DIR}/Resources/${SRC_FILE}" - COMMENT "Copy ${SRC_FILE}" - ) - list(APPEND ALL_FILES "${APP_BIN_DIR}/${SRC_FILE}" ) - ENDIF(NOT (SRC_FILE MATCHES "(^\\.\\.)")) - endforeach() - # create target for copying these files - add_custom_target( ${GAME_RES_TARGET} DEPENDS ${ALL_FILES} ) -endmacro() + add_custom_command( + TARGET ${TARGET_NAME}_PRE_BUILD + ${ARGN} + PRE_BUILD + COMMENT "${TARGET_NAME}_PRE_BUILD ..." + ) -# convenience to call above with current directory and everything in "res" -macro(COPY_RES GAME_NAME) - # a target for all addition asserts (will be done in default compile, but if you target the executable - # it won't be done -- good for testing) - add_custom_target( ${GAME_NAME}_ASSETS ALL ) - - # copy entire "res" directory and "game.config" if there is one - set(CRG_PATTERN "*") - COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_CORE_RES - ${CMAKE_CURRENT_SOURCE_DIR}/Resources - "${CRG_PATTERN}" - ) - add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_CORE_RES ) -endmacro() - -# Copies resources from an additional directory -# GAME_NAME name of the game -# REL_DIR from which directory -# ARGN which patterns to copy (should include res/ in name if to be placed in the res/ output) -macro(COPY_RES_EXTRA GAME_NAME EXTRA_RES REL_DIR) - # convert src's to full paths (based on rel_dir) - set(SRC_FILES) - foreach(SRC_FILE ${ARGN} ) - list(APPEND SRC_FILES "${REL_DIR}/${SRC_FILE}") - endforeach() - COPY_RES_FILES( ${GAME_NAME} ${GAME_NAME}_${EXTRA_RES} ${REL_DIR} "${SRC_FILES}" ) - add_dependencies( ${GAME_NAME}_ASSETS ${GAME_NAME}_${EXTRA_RES} ) + add_custom_target( ${TARGET_NAME}_CORE_PRE_BUILD ) + add_dependencies( ${TARGET_NAME}_PRE_BUILD ${TARGET_NAME}_CORE_PRE_BUILD ) endmacro() diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt index b335cf89fc..667bf7cd18 100644 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ b/samples/Cpp/HelloCpp/CMakeLists.txt @@ -18,5 +18,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index a4237425f9..e5493d194c 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -159,5 +159,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt index c048fae5c0..e0d1f3a753 100644 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ b/samples/Lua/HelloLua/CMakeLists.txt @@ -33,8 +33,8 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES( ${APP_NAME} ) - -COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua - script/* +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources ) diff --git a/samples/Lua/TestLua/CMakeLists.txt b/samples/Lua/TestLua/CMakeLists.txt index dc81be8941..743f3eeb3f 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/samples/Lua/TestLua/CMakeLists.txt @@ -33,11 +33,10 @@ set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin/${APP_NAME}") set_target_properties(${APP_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") -COPY_RES(${APP_NAME}) -COPY_RES_EXTRA(${APP_NAME} copy_core_scripts ${CMAKE_SOURCE_DIR}/cocos/scripting/lua - script/* - ) -COPY_RES_EXTRA(${APP_NAME} copy_cpp_res ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources - * +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources ${APP_BIN_DIR}/Resources ) From 555f3609c84c87c07f07c2c4172e0967e67f737a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 5 Nov 2013 19:02:03 -0800 Subject: [PATCH 416/557] Uses `const std::string&` ... instead of const char* * Because it is more robust * and it is faster... yes faster. It is faster because internally some of our classes use std::string (like FileUtils and Dictionary) so converting back-and-forth from const char * to std::string is very expensive. It is faster to have everthing in std::string as soon as possible to prevent further conversions. There are still some parts of the code that require conversion, but most of the code was converted. --- cocos/2d/CCAnimationCache.cpp | 40 +++++++++---------- cocos/2d/CCAnimationCache.h | 12 +++--- cocos/2d/CCLabel.cpp | 14 +++---- cocos/2d/CCLabel.h | 8 ++-- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelAtlas.h | 2 +- cocos/2d/CCLabelBMFont.cpp | 45 +++++++++------------ cocos/2d/CCLabelBMFont.h | 28 ++++++------- cocos/2d/CCLabelTTF.cpp | 4 +- cocos/2d/CCLabelTTF.h | 2 +- cocos/2d/CCParticleSystem.cpp | 14 +++---- cocos/2d/CCParticleSystem.h | 6 +-- cocos/2d/CCProtocols.h | 2 +- cocos/2d/CCSprite.cpp | 24 +++++------ cocos/2d/CCSprite.h | 14 +++---- cocos/2d/CCSpriteFrame.cpp | 36 ++++++++--------- cocos/2d/CCSpriteFrame.h | 8 ++-- cocos/2d/CCSpriteFrameCache.cpp | 70 ++++++++++++++++----------------- cocos/2d/CCSpriteFrameCache.h | 18 ++++----- 19 files changed, 168 insertions(+), 183 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index 37f516347a..a2c0fa9303 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -71,22 +71,20 @@ AnimationCache::~AnimationCache() CC_SAFE_RELEASE(_animations); } -void AnimationCache::addAnimation(Animation *animation, const char * name) +void AnimationCache::addAnimation(Animation *animation, const std::string& name) { _animations->setObject(animation, name); } -void AnimationCache::removeAnimation(const char* name) +void AnimationCache::removeAnimation(const std::string& name) { - if (! name) - { + if (name.size()==0) return; - } _animations->removeObjectForKey(name); } -Animation* AnimationCache::getAnimation(const char* name) +Animation* AnimationCache::getAnimation(const std::string& name) { return (Animation*)_animations->objectForKey(name); } @@ -95,17 +93,17 @@ void AnimationCache::parseVersion1(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - Dictionary* animationDict = static_cast(pElement->getObject()); + Dictionary* animationDict = static_cast(element->getObject()); Array* frameNames = static_cast(animationDict->objectForKey("frames")); float delay = animationDict->valueForKey("delay")->floatValue(); Animation* animation = NULL; if ( frameNames == NULL ) { - CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", element->getStrKey()); continue; } @@ -115,11 +113,11 @@ void AnimationCache::parseVersion1(Dictionary* animations) Object* pObj = NULL; CCARRAY_FOREACH(frameNames, pObj) { - const char* frameName = static_cast(pObj)->getCString(); + const std::string& frameName = static_cast(pObj)->getCString(); SpriteFrame* spriteFrame = frameCache->getSpriteFrameByName(frameName); if ( ! spriteFrame ) { - CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", pElement->getStrKey(), frameName); + CCLOG("cocos2d: AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the SpriteFrameCache. This frame will not be added to the animation.", element->getStrKey(), frameName.c_str()); continue; } @@ -131,15 +129,15 @@ void AnimationCache::parseVersion1(Dictionary* animations) } if ( frames->count() == 0 ) { - CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", element->getStrKey()); continue; } else if ( frames->count() != frameNames->count() ) { - CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", pElement->getStrKey()); + CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", element->getStrKey()); } animation = Animation::create(frames, delay, 1); - AnimationCache::getInstance()->addAnimation(animation, pElement->getStrKey()); + AnimationCache::getInstance()->addAnimation(animation, element->getStrKey()); frames->release(); } } @@ -148,11 +146,11 @@ void AnimationCache::parseVersion2(Dictionary* animations) { SpriteFrameCache *frameCache = SpriteFrameCache::getInstance(); - DictElement* pElement = NULL; - CCDICT_FOREACH(animations, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(animations, element) { - const char* name = pElement->getStrKey(); - Dictionary* animationDict = static_cast(pElement->getObject()); + const char* name = element->getStrKey(); + Dictionary* animationDict = static_cast(element->getObject()); const String* loops = animationDict->valueForKey("loops"); bool restoreOriginalFrame = animationDict->valueForKey("restoreOriginalFrame")->boolValue(); @@ -241,9 +239,9 @@ void AnimationCache::addAnimationsWithDictionary(Dictionary* dictionary) } /** Read an NSDictionary from a plist file and parse it automatically for animations */ -void AnimationCache::addAnimationsWithFile(const char* plist) +void AnimationCache::addAnimationsWithFile(const std::string& plist) { - CCASSERT( plist, "Invalid texture file name"); + CCASSERT( plist.size()>0, "Invalid texture file name"); std::string path = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFile(path.c_str()); diff --git a/cocos/2d/CCAnimationCache.h b/cocos/2d/CCAnimationCache.h index f30d6ee94f..475c16ce87 100644 --- a/cocos/2d/CCAnimationCache.h +++ b/cocos/2d/CCAnimationCache.h @@ -76,29 +76,29 @@ public: /** Adds a Animation with a name. */ - void addAnimation(Animation *animation, const char * name); + void addAnimation(Animation *animation, const std::string& name); /** Deletes a Animation from the cache. */ - void removeAnimation(const char* name); + void removeAnimation(const std::string& name); /** @deprecated. Use removeAnimation() instead * @js NA * @lua NA */ - CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const char* name){ removeAnimation(name);} + CC_DEPRECATED_ATTRIBUTE void removeAnimationByName(const std::string& name){ removeAnimation(name);} /** Returns a Animation that was previously added. If the name is not found it will return nil. You should retain the returned copy if you are going to use it. */ - Animation* getAnimation(const char* name); + Animation* getAnimation(const std::string& name); /** @deprecated. Use getAnimation() instead * @js NA * @lua NA */ - CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const char* name){ return getAnimation(name); } + CC_DEPRECATED_ATTRIBUTE Animation* animationByName(const std::string& name){ return getAnimation(name); } /** Adds an animation from an NSDictionary Make sure that the frames were previously loaded in the SpriteFrameCache. @@ -112,7 +112,7 @@ public: * @js addAnimations * @lua addAnimations */ - void addAnimationsWithFile(const char* plist); + void addAnimationsWithFile(const std::string& plist); private: void parseVersion1(Dictionary* animations); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 68cc984636..0dc7fc5081 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -29,9 +29,9 @@ NS_CC_BEGIN -Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) +Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) { - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs); + FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs); if (!tmpAtlas) return nullptr; @@ -48,10 +48,10 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo return nullptr; } -Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) +Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize) { - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); + FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str()); if (!tmpAtlas) return 0; @@ -135,12 +135,12 @@ bool Label::init() return true; } -void Label::setString(const char *stringToRender) +void Label::setString(const std::string &stringToRender) { setText(stringToRender, _width, TextHAlignment::CENTER, false); } -bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) +bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) { if (!_fontAtlas) return false; @@ -159,7 +159,7 @@ bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment return false; // int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); + unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str()); if(!utf16String) return false; diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 0d668256f2..a4c9a127e2 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -51,13 +51,13 @@ class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAPr public: // static create - static Label* createWithTTF(const char* label, const char* fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); + static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); - static Label* createWithBMFont(const char* label, const char* bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); + static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); - bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); + bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); - virtual void setString(const char *stringToRender) override; + virtual void setString(const std::string &stringToRender) override; virtual void setAlignment(TextHAlignment alignment); virtual void setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index ca28f930cb..f1a9126b54 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -186,9 +186,9 @@ void LabelAtlas::updateAtlasValues() } //CCLabelAtlas - LabelProtocol -void LabelAtlas::setString(const char *label) +void LabelAtlas::setString(const std::string &label) { - size_t len = strlen(label); + size_t len = label.size(); if (len > _textureAtlas->getTotalQuads()) { _textureAtlas->resizeCapacity(len); diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 2c7d98ea5b..b8df38f62d 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -87,7 +87,7 @@ public: // super methods virtual void updateAtlasValues(); - virtual void setString(const char *label); + virtual void setString(const std::string &label); virtual const char* getString(void) const; #if CC_LABELATLAS_DEBUG_DRAW diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index a9270757c7..1000889c62 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -62,7 +62,7 @@ static unsigned short* copyUTF16StringN(unsigned short* str) // static Dictionary* s_pConfigurations = NULL; -CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) +CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) { CCBMFontConfiguration* pRet = NULL; @@ -75,7 +75,7 @@ CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) pRet = static_cast( s_pConfigurations->objectForKey(fntFile) ); if( pRet == NULL ) { - pRet = CCBMFontConfiguration::create(fntFile); + pRet = CCBMFontConfiguration::create(fntFile.c_str()); if (pRet) { s_pConfigurations->setObject(pRet, fntFile); @@ -180,7 +180,7 @@ void CCBMFontConfiguration::purgeFontDefDictionary() } } -std::set* CCBMFontConfiguration::parseConfigFile(const char *controlFile) +std::set* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile) { std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); String *contents = String::createWithContentsOfFile(fullpath.c_str()); @@ -191,7 +191,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr if (!contents) { - CCLOG("cocos2d: Error parsing FNTfile %s", controlFile); + CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); return NULL; } @@ -259,7 +259,7 @@ std::set* CCBMFontConfiguration::parseConfigFile(const char *contr return validCharsString; } -void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) +void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile) { ////////////////////////////////////////////////////////////////////////// // line to parse: @@ -431,23 +431,23 @@ LabelBMFont * LabelBMFont::create() return NULL; } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment) { return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO); } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width) { return LabelBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO); } -LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile) +LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile) { return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); } //LabelBMFont - Creation & Init -LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) +LabelBMFont *LabelBMFont::create(const std::string& str, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) { LabelBMFont *pRet = new LabelBMFont(); if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) @@ -461,22 +461,21 @@ LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float wid bool LabelBMFont::init() { - return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); + return initWithString("", "", kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); } -bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) +bool LabelBMFont::initWithString(const std::string& theString, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) { CCASSERT(!_configuration, "re-init is no longer supported"); - CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont"); - + Texture2D *texture = NULL; - if (fntFile) + if (fntFile.size() > 0 ) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); if (!newConf) { - CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile); + CCLOG("cocos2d: WARNING. LabelBMFont: Impossible to create font. Please check file: '%s'", fntFile.c_str()); release(); return false; } @@ -495,12 +494,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo texture->autorelease(); } - if (theString == NULL) - { - theString = ""; - } - - if (SpriteBatchNode::initWithTexture(texture, strlen(theString))) + if (SpriteBatchNode::initWithTexture(texture, theString.size())) { _width = width; _alignment = alignment; @@ -724,20 +718,17 @@ void LabelBMFont::createFontChars() } //LabelBMFont - LabelProtocol protocol -void LabelBMFont::setString(const char *newString) +void LabelBMFont::setString(const std::string &newString) { this->setString(newString, true); } -void LabelBMFont::setString(const char *newString, bool needUpdateLabel) +void LabelBMFont::setString(const std::string &newString, bool needUpdateLabel) { - if (newString == NULL) { - newString = ""; - } if (needUpdateLabel) { _initialStringUTF8 = newString; } - unsigned short* utf16String = cc_utf8_to_utf16(newString); + unsigned short* utf16String = cc_utf8_to_utf16(newString.c_str()); setString(utf16String, needUpdateLabel); CC_SAFE_DELETE_ARRAY(utf16String); } diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index 11ff078ac5..0da1584387 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -145,16 +145,16 @@ public: /** initializes a BitmapFontConfiguration with a FNT file */ bool initWithFNTfile(const char *FNTfile); - inline const char* getAtlasName(){ return _atlasName.c_str(); } - inline void setAtlasName(const char* atlasName) { _atlasName = atlasName; } + inline const std::string& getAtlasName(){ return _atlasName; } + inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } std::set* getCharacterSet() const; private: - std::set* parseConfigFile(const char *controlFile); + std::set* parseConfigFile(const std::string& controlFile); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseInfoArguments(std::string line); void parseCommonArguments(std::string line); - void parseImageFileName(std::string line, const char *fntFile); + void parseImageFileName(std::string line, const std::string& fntFile); void parseKerningEntry(std::string line); void purgeKerningDictionary(); void purgeFontDefDictionary(); @@ -209,13 +209,13 @@ public: static void purgeCachedData(); /** creates a bitmap font atlas with an initial string and the FNT file */ - static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment, Point imageOffset); - static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment); - static LabelBMFont * create(const char *str, const char *fntFile, float width); + static LabelBMFont * create(const std::string& str, const std::string& fntFile, float width); - static LabelBMFont * create(const char *str, const char *fntFile); + static LabelBMFont * create(const std::string& str, const std::string& fntFile); /** Creates an label. */ @@ -223,15 +223,15 @@ public: bool init(); /** init a bitmap font atlas with an initial string and the FNT file */ - bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); + bool initWithString(const std::string& str, const std::string& fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); /** updates the font chars based on the string to render */ void createFontChars(); // super method - virtual void setString(const char *newString); - virtual void setString(const char *newString, bool needUpdateLabel); + virtual void setString(const std::string& newString); + virtual void setString(const std::string& newString, bool needUpdateLabel); - virtual const char* getString(void) const; + virtual const char* getString() const; virtual void setCString(const char *label); virtual void setAnchorPoint(const Point& var); virtual void updateLabel(); @@ -264,7 +264,7 @@ public: virtual void draw(); #endif // CC_LABELBMFONT_DEBUG_DRAW private: - char * atlasNameFromFntFile(const char *fntFile); + char * atlasNameFromFntFile(const std::string& fntFile); int kerningAmountForFirst(unsigned short first, unsigned short second); float getLetterPosXLeft( Sprite* characterSprite ); float getLetterPosXRight( Sprite* characterSprite ); @@ -309,7 +309,7 @@ protected: /** Free function that parses a FNT file a place it on the cache */ -CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file ); +CC_DLL CCBMFontConfiguration * FNTConfigLoadFile(const std::string &file); /** Purges the FNT config cache */ CC_DLL void FNTConfigRemoveCache( void ); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index bead3ea020..051b07d9b7 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -171,10 +171,8 @@ bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinitio } -void LabelTTF::setString(const char *string) +void LabelTTF::setString(const std::string &string) { - CCASSERT(string != NULL, "Invalid string"); - if (_string.compare(string)) { _string = string; diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 9243a50e1c..1f785028c4 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -144,7 +144,7 @@ public: /** changes the string to render * @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas */ - virtual void setString(const char *label); + virtual void setString(const std::string &label); virtual const char* getString(void) const; TextHAlignment getHorizontalAlignment() const; diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 785251ca7a..21c473f2f2 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -136,7 +136,7 @@ ParticleSystem::ParticleSystem() } // implementation ParticleSystem -ParticleSystem * ParticleSystem::create(const char *plistFile) +ParticleSystem * ParticleSystem::create(const std::string& plistFile) { ParticleSystem *pRet = new ParticleSystem(); if (pRet && pRet->initWithFile(plistFile)) @@ -165,7 +165,7 @@ bool ParticleSystem::init() return initWithTotalParticles(150); } -bool ParticleSystem::initWithFile(const char *plistFile) +bool ParticleSystem::initWithFile(const std::string& plistFile) { bool bRet = false; _plistFile = FileUtils::getInstance()->fullPathForFilename(plistFile); @@ -195,7 +195,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary) return initWithDictionary(dictionary, ""); } -bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirname) +bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::string& dirname) { bool bRet = false; unsigned char *buffer = NULL; @@ -353,17 +353,17 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn { string textureDir = textureName.substr(0, rPos + 1); - if (dirname != NULL && textureDir != dirname) + if (dirname.size()>0 && textureDir != dirname) { textureName = textureName.substr(rPos+1); - textureName = string(dirname) + textureName; + textureName = dirname + textureName; } } else { - if (dirname != NULL) + if (dirname.size()>0) { - textureName = string(dirname) + textureName; + textureName = dirname + textureName; } } diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index ae22671c4c..1cd30b56c8 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -167,7 +167,7 @@ public: http://particledesigner.71squared.com/ @since v2.0 */ - static ParticleSystem * create(const char *plistFile); + static ParticleSystem * create(const std::string& plistFile); //! create a system with a fixed number of particles static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); @@ -188,7 +188,7 @@ public: http://particledesigner.71squared.com/ @since v0.99.3 */ - bool initWithFile(const char *plistFile); + bool initWithFile(const std::string& plistFile); /** initializes a QuadParticleSystem from a Dictionary. @since v0.99.3 @@ -198,7 +198,7 @@ public: /** initializes a particle system from a NSDictionary and the path from where to load the png @since v2.1 */ - bool initWithDictionary(Dictionary *dictionary, const char *dirname); + bool initWithDictionary(Dictionary *dictionary, const std::string& dirname); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(unsigned int numberOfParticles); diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index 01b7ebc011..17249816c0 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -229,7 +229,7 @@ public: * @js NA * @lua NA */ - virtual void setString(const char *label) = 0; + virtual void setString(const std::string &label) = 0; /** * Returns the string that is currently being used in this label diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 676138d9b1..fa6f4878b0 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -82,7 +82,7 @@ Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) return NULL; } -Sprite* Sprite::create(const char *filename) +Sprite* Sprite::create(const std::string& filename) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename)) @@ -94,7 +94,7 @@ Sprite* Sprite::create(const char *filename) return NULL; } -Sprite* Sprite::create(const char *filename, const Rect& rect) +Sprite* Sprite::create(const std::string& filename, const Rect& rect) { Sprite *sprite = new Sprite(); if (sprite && sprite->initWithFile(filename, rect)) @@ -118,13 +118,13 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) return NULL; } -Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) +Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); + sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != NULL, msg); #endif @@ -215,9 +215,9 @@ bool Sprite::initWithTexture(Texture2D *texture) return initWithTexture(texture, rect); } -bool Sprite::initWithFile(const char *filename) +bool Sprite::initWithFile(const std::string& filename) { - CCASSERT(filename != NULL, "Invalid filename for sprite"); + CCASSERT(filename.size()>0, "Invalid filename for sprite"); Texture2D *texture = TextureCache::getInstance()->addImage(filename); if (texture) @@ -233,9 +233,9 @@ bool Sprite::initWithFile(const char *filename) return false; } -bool Sprite::initWithFile(const char *filename, const Rect& rect) +bool Sprite::initWithFile(const std::string &filename, const Rect& rect) { - CCASSERT(filename != NULL, ""); + CCASSERT(filename.size()>0, "Invalid filename"); Texture2D *texture = TextureCache::getInstance()->addImage(filename); if (texture) @@ -259,9 +259,9 @@ bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) return bRet; } -bool Sprite::initWithSpriteFrameName(const char *spriteFrameName) +bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) { - CCASSERT(spriteFrameName != NULL, ""); + CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName"); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); return initWithSpriteFrame(frame); @@ -992,9 +992,9 @@ void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); } -void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int frameIndex) +void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex) { - CCASSERT(animationName, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); + CCASSERT(animationName.size()>0, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); Animation *a = AnimationCache::getInstance()->getAnimation(animationName); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index cc6470c7da..7ebf7ff616 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -105,7 +105,7 @@ public: * @param filename The string which indicates a path to image file, e.g., "scene1/monster.png". * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* create(const char *filename); + static Sprite* create(const std::string& filename); /** * Creates a sprite with an image filename and a rect. @@ -114,7 +114,7 @@ public: * @param rect Only the contents inside rect of filename's texture will be applied for this sprite. * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* create(const char *filename, const Rect& rect); + static Sprite* create(const std::string& filename, const Rect& rect); /** * Creates a sprite with an exsiting texture contained in a Texture2D object @@ -154,7 +154,7 @@ public: * @param spriteFrameName A null terminated string which indicates the sprite frame name. * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* createWithSpriteFrameName(const char *spriteFrameName); + static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); /// @} end of creators group @@ -233,7 +233,7 @@ public: * @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache * @return true if the sprite is initialized properly, false otherwise. */ - virtual bool initWithSpriteFrameName(const char *spriteFrameName); + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); /** * Initializes a sprite with an image filename. @@ -247,7 +247,7 @@ public: * @js init * @lua init */ - virtual bool initWithFile(const char *filename); + virtual bool initWithFile(const std::string& filename); /** * Initializes a sprite with an image filename, and a rect. @@ -262,7 +262,7 @@ public: * @js init * @lua init */ - virtual bool initWithFile(const char *filename, const Rect& rect); + virtual bool initWithFile(const std::string& filename, const Rect& rect); /// @} end of initializers @@ -354,7 +354,7 @@ public: * Changes the display frame with animation name and index. * The animation name will be get from the AnimationCache */ - virtual void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex); + virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex); /// @} diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index 8bc0bafa6d..d2fd2c2495 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -31,61 +31,61 @@ NS_CC_BEGIN // implementation of SpriteFrame -SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect) +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; + SpriteFrame *pSpriteFrame = new SpriteFrame(); pSpriteFrame->initWithTextureFilename(filename, rect); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::createWithTexture(Texture2D *pobTexture, const Rect& rect) +SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const Rect& rect) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; - pSpriteFrame->initWithTexture(pobTexture, rect); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::createWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; - pSpriteFrame->initWithTexture(pobTexture, rect, rotated, offset, originalSize); + SpriteFrame *pSpriteFrame = new SpriteFrame(); + pSpriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize); pSpriteFrame->autorelease(); return pSpriteFrame; } -SpriteFrame* SpriteFrame::create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +SpriteFrame* SpriteFrame::create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - SpriteFrame *pSpriteFrame = new SpriteFrame();; + SpriteFrame *pSpriteFrame = new SpriteFrame(); pSpriteFrame->initWithTextureFilename(filename, rect, rotated, offset, originalSize); pSpriteFrame->autorelease(); return pSpriteFrame; } -bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect) +bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS(rect); - return initWithTexture(pobTexture, rectInPixels, false, Point::ZERO, rectInPixels.size); + return initWithTexture(texture, rectInPixels, false, Point::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect) +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect) { Rect rectInPixels = CC_RECT_POINTS_TO_PIXELS( rect ); return initWithTextureFilename(filename, rectInPixels, false, Point::ZERO, rectInPixels.size); } -bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +bool SpriteFrame::initWithTexture(Texture2D* texture, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { - _texture = pobTexture; + _texture = texture; - if (pobTexture) + if (texture) { - pobTexture->retain(); + texture->retain(); } _rectInPixels = rect; @@ -99,7 +99,7 @@ bool SpriteFrame::initWithTexture(Texture2D* pobTexture, const Rect& rect, bool return true; } -bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) +bool SpriteFrame::initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize) { _texture = NULL; _textureFilename = filename; diff --git a/cocos/2d/CCSpriteFrame.h b/cocos/2d/CCSpriteFrame.h index f9b2d68c4a..4d205d0f8a 100644 --- a/cocos/2d/CCSpriteFrame.h +++ b/cocos/2d/CCSpriteFrame.h @@ -58,12 +58,12 @@ public: /** Create a SpriteFrame with a texture filename, rect in points. It is assumed that the frame was not trimmed. */ - static SpriteFrame* create(const char* filename, const Rect& rect); + static SpriteFrame* create(const std::string& filename, const Rect& rect); /** Create a SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels. The originalSize is the size in pixels of the frame before being trimmed. */ - static SpriteFrame* create(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); + static SpriteFrame* create(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); /** Create a SpriteFrame with a texture, rect in points. It is assumed that the frame was not trimmed. @@ -88,7 +88,7 @@ public: /** Initializes a SpriteFrame with a texture filename, rect in points; It is assumed that the frame was not trimmed. */ - bool initWithTextureFilename(const char* filename, const Rect& rect); + bool initWithTextureFilename(const std::string& filename, const Rect& rect); /** Initializes a SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. The originalSize is the size in points of the frame before being trimmed. @@ -100,7 +100,7 @@ public: @since v1.1 */ - bool initWithTextureFilename(const char* filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); + bool initWithTextureFilename(const std::string& filename, const Rect& rect, bool rotated, const Point& offset, const Size& originalSize); // attributes diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 78fc2f8fa6..7ab33b85fe 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -102,11 +102,11 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex // check the format CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:"); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(framesDict, element) { - Dictionary* frameDict = static_cast(pElement->getObject()); - std::string spriteFrameName = pElement->getStrKey(); + Dictionary* frameDict = static_cast(element->getObject()); + std::string spriteFrameName = element->getStrKey(); SpriteFrame* spriteFrame = static_cast(_spriteFrames->objectForKey(spriteFrameName)); if (spriteFrame) { @@ -203,7 +203,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(Dictionary* dictionary, Tex } } -void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D *pobTexture) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Texture2D *pobTexture) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszPlist); Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); @@ -212,9 +212,9 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D * dict->release(); } -void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) { - CCASSERT(textureFileName, "texture name should not be null"); + CCASSERT(textureFileName.size()>0, "texture name should not be null"); Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); if (texture) @@ -223,13 +223,13 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* te } else { - CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName); + CCLOG("cocos2d: SpriteFrameCache: couldn't load texture file. File not found %s", textureFileName.c_str()); } } -void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) +void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) { - CCASSERT(pszPlist, "plist filename should not be NULL"); + CCASSERT(pszPlist.size()>0, "plist filename should not be NULL"); if (_loadedFileNames->find(pszPlist) == _loadedFileNames->end()) { @@ -280,7 +280,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) } } -void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const char *pszFrameName) +void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const std::string& pszFrameName) { _spriteFrames->setObject(pobFrame, pszFrameName); } @@ -295,14 +295,14 @@ void SpriteFrameCache::removeSpriteFrames(void) void SpriteFrameCache::removeUnusedSpriteFrames(void) { bool bRemoved = false; - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - SpriteFrame* spriteFrame = static_cast(pElement->getObject()); + SpriteFrame* spriteFrame = static_cast(element->getObject()); if( spriteFrame->retainCount() == 1 ) { - CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", pElement->getStrKey()); - _spriteFrames->removeObjectForElememt(pElement); + CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", element->getStrKey()); + _spriteFrames->removeObjectForElememt(element); bRemoved = true; } } @@ -315,16 +315,14 @@ void SpriteFrameCache::removeUnusedSpriteFrames(void) } -void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) +void SpriteFrameCache::removeSpriteFrameByName(const std::string& name) { // explicit nil handling - if( ! pszName ) - { + if( ! name.size()>0 ) return; - } // Is this an alias ? - String* key = (String*)_spriteFramesAliases->objectForKey(pszName); + String* key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { @@ -333,20 +331,20 @@ void SpriteFrameCache::removeSpriteFrameByName(const char *pszName) } else { - _spriteFrames->removeObjectForKey(pszName); + _spriteFrames->removeObjectForKey(name); } // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache _loadedFileNames->clear(); } -void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist) +void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist); Dictionary* dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); if (dict == nullptr) { - CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist); + CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str()); return; } removeSpriteFramesFromDictionary((Dictionary*)dict); @@ -365,12 +363,12 @@ void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary) Dictionary* framesDict = static_cast(dictionary->objectForKey("frames")); Array* keysToRemove = Array::create(); - DictElement* pElement = NULL; - CCDICT_FOREACH(framesDict, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(framesDict, element) { - if (_spriteFrames->objectForKey(pElement->getStrKey())) + if (_spriteFrames->objectForKey(element->getStrKey())) { - keysToRemove->addObject(String::create(pElement->getStrKey())); + keysToRemove->addObject(String::create(element->getStrKey())); } } @@ -381,33 +379,33 @@ void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture) { Array* keysToRemove = Array::create(); - DictElement* pElement = NULL; - CCDICT_FOREACH(_spriteFrames, pElement) + DictElement* element = NULL; + CCDICT_FOREACH(_spriteFrames, element) { - string key = pElement->getStrKey(); + string key = element->getStrKey(); SpriteFrame* frame = static_cast(_spriteFrames->objectForKey(key.c_str())); if (frame && (frame->getTexture() == texture)) { - keysToRemove->addObject(String::create(pElement->getStrKey())); + keysToRemove->addObject(String::create(element->getStrKey())); } } _spriteFrames->removeObjectsForKeys(keysToRemove); } -SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const char *pszName) +SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name) { - SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(pszName); + SpriteFrame* frame = (SpriteFrame*)_spriteFrames->objectForKey(name); if (!frame) { // try alias dictionary - String *key = (String*)_spriteFramesAliases->objectForKey(pszName); + String *key = (String*)_spriteFramesAliases->objectForKey(name); if (key) { frame = (SpriteFrame*)_spriteFrames->objectForKey(key->getCString()); if (! frame) { - CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", pszName); + CCLOG("cocos2d: SpriteFrameCache: Frame '%s' not found", name.c_str()); } } } diff --git a/cocos/2d/CCSpriteFrameCache.h b/cocos/2d/CCSpriteFrameCache.h index c7249d222c..11733fa0ff 100644 --- a/cocos/2d/CCSpriteFrameCache.h +++ b/cocos/2d/CCSpriteFrameCache.h @@ -85,29 +85,29 @@ public: public: /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png - * If you want to use another texture, you should use the addSpriteFramesWithFile(const char *plist, const char *textureFileName) method. + * If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) method. * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char *plist); + void addSpriteFramesWithFile(const std::string& plist); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. @since v0.99.5 * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char* plist, const char* textureFileName); + void addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName); /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. * @js addSpriteFrames * @lua addSpriteFrames */ - void addSpriteFramesWithFile(const char *plist, Texture2D *texture); + void addSpriteFramesWithFile(const std::string&plist, Texture2D *texture); /** Adds an sprite frame with a given name. If the name already exists, then the contents of the old name will be replaced with the new one. */ - void addSpriteFrame(SpriteFrame *frame, const char *frameName); + void addSpriteFrame(SpriteFrame *frame, const std::string& frameName); /** Purges the dictionary of loaded sprite frames. * Call this method if you receive the "Memory Warning". @@ -124,14 +124,14 @@ public: void removeUnusedSpriteFrames(void); /** Deletes an sprite frame from the sprite frame cache. */ - void removeSpriteFrameByName(const char *name); + void removeSpriteFrameByName(const std::string& name); /** Removes multiple Sprite Frames from a plist file. * Sprite Frames stored in this file will be removed. * It is convenient to call this method when a specific texture needs to be removed. * @since v0.99.5 */ - void removeSpriteFramesFromFile(const char* plist); + void removeSpriteFramesFromFile(const std::string& plist); /** Removes all Sprite Frames associated with the specified textures. * It is convenient to call this method when a specific texture needs to be removed. @@ -145,10 +145,10 @@ public: * @js getSpriteFrame * @lua getSpriteFrame */ - SpriteFrame* getSpriteFrameByName(const char *name); + SpriteFrame* getSpriteFrameByName(const std::string& name); /** @deprecated use getSpriteFrameByName() instead */ - CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const char *name) { return getSpriteFrameByName(name); } + CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const std::string&name) { return getSpriteFrameByName(name); } private: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. From f05c1590ae426078dc6af3d1bd1099f6b5f966c2 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 11:20:16 +0800 Subject: [PATCH 417/557] 1.fix particle kCCPositionTypeFree state bug --- cocos/editor-support/cocostudio/CCArmature.h | 2 +- cocos/editor-support/cocostudio/CCDisplayFactory.cpp | 9 +++++++++ cocos/editor-support/cocostudio/CCDisplayManager.cpp | 8 ++++++++ cocos/editor-support/cocostudio/CCProcessBase.h | 2 +- 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index 6182072265..e29323ff86 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -94,7 +94,7 @@ public: * @js NA * @lua NA */ - ~Armature(void); + virtual ~Armature(void); /** * Init the empty armature diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 7f329ff3cc..a4f1432727 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -255,6 +255,15 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi { ParticleDisplayData *displayData = (ParticleDisplayData *)decoDisplay->getDisplayData(); ParticleSystem *system = ParticleSystemQuad::create(displayData->plist.c_str()); + + system->removeFromParent(); + + Armature *armature = bone->getArmature(); + if (armature) + { + system->setParent(armature); + } + decoDisplay->setDisplay(system); } void DisplayFactory::updateParticleDisplay(Bone *bone, Node *display, float dt) diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 52af6b2d1d..ce808ca3b9 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -149,6 +149,14 @@ void DisplayManager::addDisplay(Node *display, int index) else if (dynamic_cast(display)) { displayData = ParticleDisplayData::create(); + + display->removeFromParent(); + + Armature *armature = _bone->getArmature(); + if (armature) + { + display->setParent(armature); + } } else if(Armature *armature = dynamic_cast(display)) { diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index c6b62793b4..2b3ef4ab47 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -58,7 +58,7 @@ public: * @js NA * @lua NA */ - ~ProcessBase(void); + virtual ~ProcessBase(void); /** * Play animation by animation name. From c32628e93039f22a833e45ace1996018e62be46a Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 14:19:08 +0800 Subject: [PATCH 418/557] [ci skip] --- CHANGELOG | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 797c52821d..e206d5cea7 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,18 +10,19 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Could not set next animation in CCBAnimationCompleted callback. [FIX] The Node's anchor point was changed after being added to ScrollView. [FIX] Refactored and improved EventDispatcher. - [NEW] Added Mouse Support For Desktop Platforms. [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. + [FIX] Parameter type: const char* -> const string& [NEW] Arm64 support. + [NEW] Added Mouse Support For Desktop Platforms. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes - [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [FIX] Fixed application will crash when pause and resume. [FIX] Clear NoSuchMethodError Exception when JniHelper fails to find method id [NEW] Added xlargeScreens="true" to supports-screens [NEW] Added build/android-build.py to build all Android samples, and remove all build_native.sh/cmd [NEW] Added build_native.py to build template projects, and remove build_native.sh/cmd + [NEW] Added Cocos2dxHelper.runOnGLThread(Runnable) again [Mac] [FIX] Removed unused CCLOG() from GL initialization [iOS] From d7ed908818bc79139685dcbe734680183a6319aa Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 06:20:17 +0000 Subject: [PATCH 419/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c2b42be577..e150a74a02 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c2b42be577425e4dd6c2501e8f0cd1520ca3d059 +Subproject commit e150a74a028e26cff0dac7d2238e2cd16fbaf370 From 75dd32cde932de99e564daf8231eaddc9c241adb Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 14:34:27 +0800 Subject: [PATCH 420/557] issue #2771: fix physics test compile error --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 88b17e365e..0885218d9a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -382,7 +382,7 @@ Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial materi bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapesAtPoint(location); + Array* arr = _scene->getPhysicsWorld()->getShapes(location); PhysicsShape* shape = nullptr; for (Object* obj : *arr) @@ -982,7 +982,7 @@ void PhysicsDemoPump::update(float delta) } } - PhysicsBody* gear = _scene->getPhysicsWorld()->getBodyByTag(1); + PhysicsBody* gear = _scene->getPhysicsWorld()->getBody(1); if (gear != nullptr) { From a01fcc6f368fb17c1a4e089edc9bc4efae5c5097 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 14:51:56 +0800 Subject: [PATCH 421/557] issue #2771: move header definition to first line --- cocos/physics/CCPhysicsBody.h | 9 ++++----- cocos/physics/CCPhysicsContact.h | 8 ++++---- cocos/physics/CCPhysicsJoint.h | 9 ++++----- cocos/physics/CCPhysicsShape.h | 8 ++++---- cocos/physics/CCPhysicsWorld.h | 9 ++++----- cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsContactInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsHelper_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsJointInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h | 8 ++++---- cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h | 8 ++++---- cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h | 8 ++++---- 17 files changed, 68 insertions(+), 71 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 7c0c79002e..4e6f60f038 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" #include "CCArray.h" @@ -300,6 +300,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_BODY_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_BODY_H__ diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 3982f4fdd6..846761d1cb 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" #include "CCEventListenerCustom.h" @@ -267,6 +267,6 @@ protected: }; NS_CC_END -#endif //__CCPHYSICS_CONTACT_H__ #endif // CC_USE_PHYSICS +#endif //__CCPHYSICS_CONTACT_H__ diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 2970d992d0..ff5285b819 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" @@ -181,6 +181,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_JOINT_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_JOINT_H__ diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 4aba49d4d7..b9525506d1 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include "CCObject.h" #include "CCGeometry.h" @@ -309,6 +309,6 @@ protected: }; NS_CC_END -#endif // __CCPHYSICS_FIXTURE_H__ #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_FIXTURE_H__ diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index e4cad6e7eb..2e70749f57 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ +#include "CCPhysicsSetting.h" +#ifdef CC_USE_PHYSICS + #include #include @@ -192,6 +192,5 @@ protected: NS_CC_END -#endif // __CCPHYSICS_WORLD_H__ - #endif // CC_USE_PHYSICS +#endif // __CCPHYSICS_WORLD_H__ diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index ed5135bf36..f04076ffcf 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_BOX2D_H__ +#define __CCPHYSICS_BODY_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -40,6 +40,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_BODY_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index c8d4a262d5..d66ed0e131 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_BOX2D_H__ +#define __CCPHYSICS_CONTACT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_CONTACT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_CONTACT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsHelper_box2d.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h index 01f156628d..f14fcef36f 100644 --- a/cocos/physics/box2d/CCPhysicsHelper_box2d.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -22,11 +22,11 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_BOX2D_H__ +#define __CCPHYSICS_HELPER_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -37,6 +37,6 @@ class PhysicsHelper }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_HELPER_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index c8223b6f8c..e1404eec45 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_BOX2D_H__ +#define __CCPHYSICS_JOINT_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_JOINT_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_JOINT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index cd1fc6abcc..15720797e0 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_BOX2D_H__ +#define __CCPHYSICS_SHAPE_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_SHAPE_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index 9df3ec46cd..fac9fd5181 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_BOX2D_H__ +#define __CCPHYSICS_WORLD_INFO_BOX2D_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ - #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -39,6 +39,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D +#endif // __CCPHYSICS_WORLD_INFO_BOX2D_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index dd2d276ac5..143fec843c 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCObject.h" @@ -51,6 +51,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 4b01ad9d53..6cc0e189c1 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_CONTACT_INFO_H__ -#define __CCPHYSICS_CONTACT_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" NS_CC_BEGIN @@ -49,6 +49,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index bf6f6d14db..52d0023b8b 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__ +#define __CCPHYSICS_HELPER_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -68,6 +68,6 @@ public: }; NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_HELPER_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index 016cd74d12..bdd3f1e887 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include @@ -60,6 +60,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index b519fd378a..2bdd55a7f9 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - #include #include #include "chipmunk.h" @@ -70,6 +70,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index b50e1a3240..0c098d3d90 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -22,12 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ +#define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ + #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#ifndef __CCPHYSICS_WORLD_INFO_H__ -#define __CCPHYSICS_WORLD_INFO_H__ - #include "chipmunk.h" #include "CCPlatformMacros.h" #include @@ -55,6 +55,6 @@ private: }; NS_CC_END -#endif // __CCPHYSICS_WORLD_INFO_H__ #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ From f3c40a3e7aea34bdd59b42d99dcc2b4f0d934cc9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 14:54:35 +0800 Subject: [PATCH 422/557] issue #3113: 32Bit fix and 13.10 32bit complication is ok. --- cocos/2d/CMakeLists.txt | 2 ++ cocos/audio/CMakeLists.txt | 8 +++++++- cocos/network/CMakeLists.txt | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index f147d233b6..9446d95364 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -134,9 +134,11 @@ target_link_libraries(cocos2d freetype fontconfig png + pthread glfw GLEW GL + X11 rt z ) diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 9e88293ddd..12fde54f25 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -7,8 +7,14 @@ add_library(audio STATIC ${AUDIO_SRC} ) +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + target_link_libraries(audio - fmodex64 + ${FMOD_LIB} ) set_target_properties(audio diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index 3bd130111b..f2deb9b365 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -9,6 +9,10 @@ add_library(network STATIC target_link_libraries(network curl + ldap + lber + idn + rtmp ) set_target_properties(network From 12d6bc1722d9b4cf35f433c5cd706a9c504a6ad0 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 15:25:44 +0800 Subject: [PATCH 423/557] 1. change CCARRAY_FOREACH to range-based loop --- .../editor-support/cocostudio/CCArmature.cpp | 27 +++++++----------- cocos/editor-support/cocostudio/CCArmature.h | 6 ++-- .../cocostudio/CCArmatureAnimation.cpp | 16 ++++------- .../cocostudio/CCArmatureDataManager.cpp | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 10 +++---- cocos/editor-support/cocostudio/CCBone.cpp | 27 ++++++++++-------- cocos/editor-support/cocostudio/CCBone.h | 7 ++++- .../cocostudio/CCColliderDetector.cpp | 28 +++++++------------ .../cocostudio/CCDisplayFactory.cpp | 2 +- .../cocostudio/CCDisplayManager.cpp | 6 ++-- 10 files changed, 58 insertions(+), 73 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 7cd7ad9295..b09922ff70 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -335,7 +335,7 @@ void Armature::changeBoneParent(Bone *bone, const char *parentName) } } -const Dictionary *Armature::getBoneDic() const +Dictionary *Armature::getBoneDic() const { return _boneDic; } @@ -451,8 +451,7 @@ void Armature::update(float dt) { _animation->update(dt); - Object *object = nullptr; - CCARRAY_FOREACH(_topBoneList, object) + for (auto object : *_topBoneList) { static_cast(object)->update(dt); } @@ -468,8 +467,7 @@ void Armature::draw() GL::blendFunc(_blendFunc.src, _blendFunc.dst); } - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for (auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { @@ -642,8 +640,7 @@ Rect Armature::getBoundingBox() const Rect boundingBox = Rect(0, 0, 0, 0); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { @@ -754,17 +751,15 @@ void Armature::setBody(b2Body *body) _body = body; _body->SetUserData(this); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object : *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = nullptr; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject : displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); if (detector != nullptr) { detector->setBody(_body); @@ -802,17 +797,15 @@ void Armature::setBody(cpBody *body) _body = body; _body->data = this; - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + for(auto object: *_children) { if (Bone *bone = dynamic_cast(object)) { Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *displayObject = nullptr; - CCARRAY_FOREACH(displayList, displayObject) + for(auto displayObject: *displayList) { - ColliderDetector *detector = ((DecorativeDisplay *)displayObject)->getColliderDetector(); + ColliderDetector *detector = static_cast(displayObject)->getColliderDetector(); if (detector != nullptr) { detector->setBody(_body); diff --git a/cocos/editor-support/cocostudio/CCArmature.h b/cocos/editor-support/cocostudio/CCArmature.h index e29323ff86..3ace91b05e 100644 --- a/cocos/editor-support/cocostudio/CCArmature.h +++ b/cocos/editor-support/cocostudio/CCArmature.h @@ -140,7 +140,7 @@ public: * Get Armature's bone dictionary * @return Armature's bone dictionary */ - const cocos2d::Dictionary *getBoneDic() const; + cocos2d::Dictionary *getBoneDic() const; /** * This boundingBox will calculate all bones' boundingBox every time @@ -180,10 +180,10 @@ public: virtual void setArmatureData(ArmatureData *armatureData) { _armatureData = armatureData; } - virtual const ArmatureData *getArmatureData() const { return _armatureData; } + virtual ArmatureData *getArmatureData() const { return _armatureData; } virtual void setBatchNode(BatchNode *batchNode) { _batchNode = batchNode; } - virtual const BatchNode *getBatchNode() const { return _batchNode; } + virtual BatchNode *getBatchNode() const { return _batchNode; } virtual void setName(const std::string &name) { _name = name; } virtual const std::string &getName() const { return _name; } diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 6b234782bd..49aa8e1c6f 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -94,8 +94,7 @@ bool ArmatureAnimation::init(Armature *armature) void ArmatureAnimation:: pause() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->pause(); } @@ -104,8 +103,7 @@ void ArmatureAnimation:: pause() void ArmatureAnimation::resume() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->resume(); } @@ -114,8 +112,7 @@ void ArmatureAnimation::resume() void ArmatureAnimation::stop() { - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->stop(); } @@ -302,8 +299,7 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex) _currentPercent = (float)_curFrameIndex / (float)_movementData->duration; _currentFrame = _nextFrameIndex * _currentPercent; - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + for(auto object : *_tweenList) { static_cast(object)->gotoAndPlay(frameIndex); } @@ -327,8 +323,8 @@ int ArmatureAnimation::getMovementCount() const void ArmatureAnimation::update(float dt) { ProcessBase::update(dt); - Object *object = nullptr; - CCARRAY_FOREACH(_tweenList, object) + + for(auto object : *_tweenList) { static_cast(object)->update(dt); } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 0e139ef560..57f9bf5cdc 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -136,7 +136,7 @@ void ArmatureDataManager::removeArmatureFileInfo(const char *configFilePath) } _relativeDatas.erase(configFilePath); - DataReaderHelper::sharedDataReaderHelper()->removeConfigFile(configFilePath); + DataReaderHelper::getInstance()->removeConfigFile(configFilePath); } } diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 36158a12dd..7219969b57 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -90,8 +90,7 @@ void BatchNode::addChild(Node *child, int zOrder, int tag) Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(displayList, object) + for(auto object : *displayList) { DecorativeDisplay *display = static_cast(object); @@ -118,8 +117,7 @@ void BatchNode::removeChild(Node* child, bool cleanup) Bone *bone = static_cast(element->getObject()); Array *displayList = bone->getDisplayManager()->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(displayList, object) + for(auto object : *displayList) { DecorativeDisplay *display = static_cast(object); @@ -166,8 +164,8 @@ void BatchNode::visit() void BatchNode::draw() { CC_NODE_DRAW_SETUP(); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + + for(auto object : *_children) { Armature *armature = dynamic_cast(object); if (armature) diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 26c5653d58..cbd4544120 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -229,11 +229,13 @@ void Bone::update(float delta) DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); - Object *object = nullptr; - CCARRAY_FOREACH(_children, object) + if (_children) { - Bone *childBone = (Bone *)object; - childBone->update(delta); + for(auto object : *_children) + { + Bone *childBone = (Bone *)object; + childBone->update(delta); + } } _boneTransformDirty = false; @@ -322,16 +324,16 @@ void Bone::addChildBone(Bone *child) void Bone::removeChildBone(Bone *bone, bool recursion) { - if ( _children->getIndexOfObject(bone) != UINT_MAX ) + if (_children && _children->getIndexOfObject(bone) != UINT_MAX ) { if(recursion) { - Array *_ccbones = bone->_children; - Object *_object = nullptr; - CCARRAY_FOREACH(_ccbones, _object) + Array *ccbones = bone->_children; + + for(auto object : *ccbones) { - Bone *_ccBone = (Bone *)_object; - bone->removeChildBone(_ccBone, recursion); + Bone *ccBone = (Bone *)object; + bone->removeChildBone(ccBone, recursion); } } @@ -412,6 +414,7 @@ DisplayType Bone::getDisplayRenderNodeType() return _displayManager->getDisplayRenderNodeType(); } + void Bone::addDisplay(DisplayData *displayData, int index) { _displayManager->addDisplay(displayData, index); @@ -449,8 +452,8 @@ Array *Bone::getColliderBodyList() void Bone::setColliderFilter(ColliderFilter *filter) { Array *array = _displayManager->getDecorativeDisplayList(); - Object *object = nullptr; - CCARRAY_FOREACH(array, object) + + for(auto object : *array) { DecorativeDisplay *decoDisplay = static_cast(object); if (ColliderDetector *detector = decoDisplay->getColliderDetector()) diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 9082f1ebb3..4d67c41e2e 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -176,6 +176,11 @@ public: virtual void setIgnoreMovementBoneData(bool ignore) { _ignoreMovementBoneData = ignore; } virtual bool isIgnoreMovementBoneData() const { return _ignoreMovementBoneData; } + /* + * This function is deprecated, please use isIgnoreMovementBoneData() + */ + CC_DEPRECATED_ATTRIBUTE virtual bool getIgnoreMovementBoneData() const { return isIgnoreMovementBoneData(); } + virtual void setBlendType(BlendType type) { _blendType = type; } virtual BlendType getBlendType() const { return _blendType; } @@ -184,7 +189,7 @@ public: virtual void setName(const std::string &name) { _name = name; } virtual const std::string getName() const { return _name; } - virtual const BaseData *getWorldInfo() const { return _worldInfo; } + virtual BaseData *getWorldInfo() const { return _worldInfo; } protected: void applyParentTransform(Bone *parent); diff --git a/cocos/editor-support/cocostudio/CCColliderDetector.cpp b/cocos/editor-support/cocostudio/CCColliderDetector.cpp index adbea59a31..35d1fe95f3 100644 --- a/cocos/editor-support/cocostudio/CCColliderDetector.cpp +++ b/cocos/editor-support/cocostudio/CCColliderDetector.cpp @@ -198,8 +198,7 @@ void ColliderDetector::addContourData(ContourData *contourData) void ColliderDetector::addContourDataList(Array *contourDataList) { - Object *object = nullptr; - CCARRAY_FOREACH(contourDataList, object) + for(auto object : *contourDataList) { addContourData((ContourData *)object); } @@ -207,8 +206,7 @@ void ColliderDetector::addContourDataList(Array *contourDataList) void ColliderDetector::removeContourData(ContourData *contourData) { - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *body = (ColliderBody*)object; if (body && body->getContourData() == contourData) @@ -242,8 +240,7 @@ void ColliderDetector::setActive(bool active) } else { - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; b2Fixture *fixture = colliderBody->getB2Fixture(); @@ -256,10 +253,9 @@ void ColliderDetector::setActive(bool active) #elif ENABLE_PHYSICS_CHIPMUNK_DETECT if (_body) { - Object *object = nullptr; if (_active) { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); @@ -271,7 +267,7 @@ void ColliderDetector::setActive(bool active) } else { - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; cpShape *shape = colliderBody->getShape(); @@ -299,8 +295,7 @@ void ColliderDetector::setColliderFilter(ColliderFilter *filter) { *_filter = *filter; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; colliderBody->setColliderFilter(filter); @@ -333,8 +328,7 @@ void ColliderDetector::updateTransform(AffineTransform &t) return; } - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; ContourData *contourData = colliderBody->getContourData(); @@ -408,8 +402,7 @@ void ColliderDetector::setBody(b2Body *pBody) { _body = pBody; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; @@ -420,7 +413,7 @@ void ColliderDetector::setBody(b2Body *pBody) b2Vec2 *b2bv = new b2Vec2[contourData->vertexList.count()]; int i = 0; - CCARRAY_FOREACH(array, object) + for(auto object : *array) { ContourVertex2 *v = (ContourVertex2 *)object; b2bv[i].Set(v->x / PT_RATIO, v->y / PT_RATIO); @@ -459,8 +452,7 @@ void ColliderDetector::setBody(cpBody *pBody) { _body = pBody; - Object *object = nullptr; - CCARRAY_FOREACH(_colliderBodyList, object) + for(auto object : *_colliderBodyList) { ColliderBody *colliderBody = (ColliderBody *)object; diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index a4f1432727..46c7750d48 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -245,7 +245,7 @@ void DisplayFactory::updateArmatureDisplay(Bone *bone, Node *display, float dt) void DisplayFactory::addParticleDisplay(Bone *bone, DecorativeDisplay *decoDisplay, DisplayData *displayData) { - ParticleDisplayData *adp = ParticleDisplayData::create(); ; + ParticleDisplayData *adp = ParticleDisplayData::create(); adp->copy((ParticleDisplayData *)displayData); decoDisplay->setDisplayData(adp); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index ce808ca3b9..a8c8f5d760 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -318,11 +318,9 @@ void DisplayManager::initDisplayList(BoneData *boneData) CS_RETURN_IF(!boneData); - Object *object = nullptr; - Array *displayDataList = &boneData->displayDataList; - CCARRAY_FOREACH(displayDataList, object) + for(auto object : boneData->displayDataList) { - DisplayData *displayData = (DisplayData *)object; + DisplayData *displayData = static_cast(object); DecorativeDisplay *decoDisplay = DecorativeDisplay::create(); decoDisplay->setDisplayData(displayData); From 2e80e95a37bb424d8cccc87ce7a3697d75b9b2fe Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 15:26:33 +0800 Subject: [PATCH 424/557] [Linux] compilation fix for PR #4099 --- cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp index a3ae0474d8..69967031a8 100644 --- a/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp +++ b/cocos/scripting/lua/bindings/Cocos2dxLuaLoader.cpp @@ -46,7 +46,7 @@ extern "C" } filename.append(".lua"); - unsigned long codeBufferSize = 0; + long codeBufferSize = 0; unsigned char* codeBuffer = FileUtils::getInstance()->getFileData(filename.c_str(), "rb", &codeBufferSize); if (codeBuffer) From f6070406cd5ac2389392835fe101443554f4d343 Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Wed, 6 Nov 2013 15:31:58 +0800 Subject: [PATCH 425/557] Missing add "JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET " before calling JS_CallFunctionValue --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 3 +++ cocos/scripting/javascript/bindings/ScriptingCore.h | 2 ++ .../bindings/chipmunk/js_bindings_chipmunk_manual.cpp | 8 ++++++++ .../bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../bindings/cocosbuilder/cocosbuilder_specifics.hpp | 2 ++ .../bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp | 9 +++++++++ 6 files changed, 25 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 5d902c1c23..ab4afd4091 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -96,6 +96,9 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, if (func == JSVAL_VOID) { return; } jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 8df12fddc6..992569afc9 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -320,6 +320,8 @@ public: JS_RemoveObjectRoot(this->_cx, &this->_jsthis); } JSBool invoke(unsigned int argc, jsval *argv, jsval &rval) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + return JS_CallFunctionValue(this->_cx, this->_jsthis, this->_fval, argc, argv, &rval); } private: diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 197a270e91..903b777fde 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -638,6 +638,8 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); @@ -662,6 +664,8 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); @@ -687,6 +691,8 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); @@ -705,6 +711,8 @@ static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) args[0] = opaque_to_jsval( handler->cx, arb); args[1] = opaque_to_jsval( handler->cx, space ); } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 39e01fd1ef..60a40d7ff2 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -c93df276adb92b5e076db49c4f9482b8eb37d45c \ No newline at end of file +d922b0cdce5f5f90c7feca934b43c294a9585ab1 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp index f6b3252c57..774c75820b 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocosbuilder/cocosbuilder_specifics.hpp @@ -14,6 +14,8 @@ public: jsval retval = JSVAL_NULL; if(!JSVAL_IS_VOID(_jsCallback) && !JSVAL_IS_VOID(_jsThisObj)) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, JSVAL_TO_OBJECT(_jsThisObj), _jsCallback, 0, NULL, &retval); } } diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index 34ecbca985..4838fbcab2 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -73,6 +73,9 @@ void JSArmatureWrapper::movementCallbackFunc(cocostudio::Armature *pArmature, co valArr[2] = idVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 3, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } @@ -88,6 +91,9 @@ void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) jsval percentVal = DOUBLE_TO_JSVAL(percent); JS_AddValueRoot(cx, &percentVal); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 1, &percentVal, &retval); JS_RemoveValueRoot(cx, &percentVal); } @@ -113,6 +119,9 @@ void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *f valArr[3] = currentIndexVal; JS_AddValueRoot(cx, valArr); + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } From efd8f629924e5cc71f2e7efca6ff52a5dd8db24d Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 15:40:06 +0800 Subject: [PATCH 426/557] add virtual --- cocos/editor-support/cocostudio/CCSkin.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 6e62da7d22..3d937a76bb 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,8 +39,8 @@ public: public: Skin(); - bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; - bool initWithFile(const char *pszFilename) override; + virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; + virtual bool initWithFile(const char *pszFilename) override; void updateArmatureTransform(); void updateTransform() override; From f36fd002cdff05a4a95bf0d35b4ba01534329eba Mon Sep 17 00:00:00 2001 From: garfield_ho Date: Wed, 6 Nov 2013 15:40:23 +0800 Subject: [PATCH 427/557] Remove duplicate --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 2 -- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index ab4afd4091..dc3859eba1 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -97,8 +97,6 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 60a40d7ff2..4bf97ac9a7 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -d922b0cdce5f5f90c7feca934b43c294a9585ab1 \ No newline at end of file +b29fccdfcc5201f7a53a2c7896310afd9884ed8f \ No newline at end of file From 6c27a0df0b61e1750c34c290cbe72471b19d908d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 6 Nov 2013 15:43:29 +0800 Subject: [PATCH 428/557] issue #2771: make api more friendly --- cocos/physics/CCPhysicsBody.h | 8 ++--- cocos/physics/CCPhysicsContact.cpp | 3 +- cocos/physics/CCPhysicsContact.h | 6 ++-- cocos/physics/CCPhysicsJoint.h | 4 +-- cocos/physics/CCPhysicsShape.cpp | 12 +++---- cocos/physics/CCPhysicsShape.h | 34 +++++++++---------- cocos/physics/CCPhysicsWorld.cpp | 22 ++++++------ .../chipmunk/CCPhysicsHelper_chipmunk.h | 12 +++---- 8 files changed, 51 insertions(+), 50 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 4e6f60f038..6ae92e4b33 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -128,7 +128,7 @@ public: /* * @brief get the first body shapes. */ - inline PhysicsShape* getShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + inline PhysicsShape* getFirstShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } PhysicsShape* getShape(int tag) const; /* * @brief remove a shape from body @@ -238,13 +238,13 @@ public: //virtual Clonable* clone() const override; bool isResting() const; - inline bool isEnable() const { return _enable; } + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isRotationEnable() const { return _rotationEnable; } + inline bool isRotationEnabled() const { return _rotationEnable; } void setRotationEnable(bool enable); - inline bool isGravityEnable() const { return _gravityEnable; } + inline bool isGravityEnabled() const { return _gravityEnable; } void setGravityEnable(bool enable); diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 71bdf5a1d0..9d6325c150 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -50,7 +50,7 @@ PhysicsContact::PhysicsContact() , _shapeB(nullptr) , _eventCode(EventCode::NONE) , _info(nullptr) -, _notify(true) +, _notificationEnable(true) , _begin(false) , _data(nullptr) , _contactInfo(nullptr) @@ -216,7 +216,6 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event) bool ret = true; if (onContactBegin != nullptr - && contact.getNotify() && test(contact.getShapeA(), contact.getShapeB())) { contact._begin = true; diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 846761d1cb..7117d746ce 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -94,8 +94,8 @@ private: bool init(PhysicsShape* a, PhysicsShape* b); void setEventCode(EventCode eventCode) { _eventCode = eventCode; }; - inline bool getNotify() const { return _notify; } - inline void setNotify(bool notify) { _notify = notify; } + inline bool isNotificationEnabled() const { return _notificationEnable; } + inline void setNotificationEnable(bool enable) { _notificationEnable = enable; } inline PhysicsWorld* getWorld() const { return _world; } inline void setWorld(PhysicsWorld* world) { _world = world; } inline void setResult(bool result) { _result = result; } @@ -113,7 +113,7 @@ private: PhysicsShape* _shapeB; EventCode _eventCode; PhysicsContactInfo* _info; - bool _notify; + bool _notificationEnable; bool _begin; bool _result; diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index ff5285b819..fea8ba4707 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -51,9 +51,9 @@ public: PhysicsBody* getBodyB() const { return _bodyB; } inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() const { return _enable; } + inline bool isEnabled() const { return _enable; } void setEnable(bool enable); - inline bool isCollisionEnable() const { return _collisionEnable; } + inline bool isCollisionEnabled() const { return _collisionEnable; } void setCollisionEnable(bool enable); protected: diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 89d0551cff..7cc64483cd 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsShape.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -503,12 +505,10 @@ float PhysicsShapeBox::calculateDefaultMoment() : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } -Point* PhysicsShapeBox::getPoints(Point* points) const +void PhysicsShapeBox::getPoints(Point* points) const { cpShape* shape = _info->getShapes().front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); - - return points; + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); } Size PhysicsShapeBox::getSize() const @@ -599,10 +599,10 @@ Point PhysicsShapePolygon::getPoint(int i) const return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i)); } -Point* PhysicsShapePolygon::getPoints(Point* points) const +void PhysicsShapePolygon::getPoints(Point* outPoints) const { cpShape* shape = _info->getShapes().front(); - return PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts); + PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, outPoints, ((cpPolyShape*)shape)->numVerts); } int PhysicsShapePolygon::getPointsCount() const diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index b9525506d1..8ff31f49df 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -154,17 +154,17 @@ public: static float calculateArea(float radius); static float calculateMoment(float mass, float radius, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; float getRadius() const; - Point getOffset() override; + virtual Point getOffset() override; protected: bool init(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); protected: PhysicsShapeCircle(); - ~PhysicsShapeCircle(); + virtual ~PhysicsShapeCircle(); }; /** A box shape */ @@ -175,12 +175,12 @@ public: static float calculateArea(const Size& size); static float calculateMoment(float mass, const Size& size, const Point& offset = Point::ZERO); - float calculateDefaultArea() override; - float calculateDefaultMoment() override; + virtual float calculateDefaultArea() override; + virtual float calculateDefaultMoment() override; - Point* getPoints(Point* points) const; + void getPoints(Point* outPoints) const; Size getSize() const; - Point getOffset() override { return _offset; } + virtual Point getOffset() override { return _offset; } protected: bool init(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); @@ -205,9 +205,9 @@ public: float calculateDefaultMoment() override; Point getPoint(int i) const; - Point* getPoints(Point* points) const; + void getPoints(Point* outPoints) const; int getPointsCount() const; - Point getCenter() override; + virtual Point getCenter() override; protected: bool init(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Point& offset = Point::ZERO); @@ -227,7 +227,7 @@ public: Point getPointA() const; Point getPointB() const; - Point getCenter() override; + virtual Point getCenter() override; protected: bool init(const Point& a, const Point& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); @@ -247,8 +247,8 @@ class PhysicsShapeEdgeBox : public PhysicsShape { public: static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Point& offset = Point::ZERO); - Point getOffset() override { return _offset; } - Point* getPoints(const Point* points) const; + virtual Point getOffset() override { return _offset; } + void getPoints(const Point* outPoints) const; int getPointsCount() const; protected: @@ -269,8 +269,8 @@ class PhysicsShapeEdgePolygon : public PhysicsShape { public: static PhysicsShapeEdgePolygon* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points) const; + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; int getPointsCount() const; protected: @@ -291,8 +291,8 @@ class PhysicsShapeEdgeChain : public PhysicsShape { public: static PhysicsShapeEdgeChain* create(const Point* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points) const; + virtual Point getCenter() override; + void getPoints(Point* outPoints) const; int getPointsCount() const; protected: diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 2a067720c1..3c5956b85c 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -25,6 +25,8 @@ #include "CCPhysicsWorld.h" #ifdef CC_USE_PHYSICS +#include + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" #elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) @@ -361,12 +363,12 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) body->removeFromWorld(); } - if (body->isEnable()) + if (body->isEnabled()) { body->_world = this; //is gravity enable - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } @@ -424,7 +426,7 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) } // reset the gravity - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } @@ -707,13 +709,13 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) continue; } - if (!joint->isCollisionEnable()) + if (!joint->isCollisionEnabled()) { PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); if (body == bodyB) { - contact.setNotify(false); + contact.setNotificationEnable(false); return false; } } @@ -723,7 +725,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 || (shapeB->getContactTestBitmask() & shapeA->getCategoryBitmask()) == 0) { - contact.setNotify(false); + contact.setNotificationEnable(false); } if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) @@ -750,7 +752,7 @@ int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { cpArbiterIgnore(static_cast(contact._contactInfo)); return true; @@ -767,7 +769,7 @@ int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } @@ -781,7 +783,7 @@ void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact) void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) { - if (!contact.getNotify()) + if (!contact.isNotificationEnabled()) { return; } @@ -802,7 +804,7 @@ void PhysicsWorld::setGravity(Point gravity) PhysicsBody* body = dynamic_cast(child); // reset gravity for body - if (!body->isGravityEnable()) + if (!body->isGravityEnabled()) { body->applyForce(-_gravity); body->applyForce(gravity); diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 52d0023b8b..094a6b6c35 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -46,24 +46,24 @@ public: static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); } static Rect cpbb2rect(const cpBB& bb) { return Rect(bb.l, bb.b, bb.r, bb.t); } - static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) + static Point* cpvs2points(const cpVect* cpvs, Point* out, int count) { for (int i = 0; i < count; ++i) { - points[i] = cpv2point(cpvs[i]); + out[i] = cpv2point(cpvs[i]); } - return points; + return out; } - static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) + static cpVect* points2cpvs(const Point* points, cpVect* out, int count) { for (int i = 0; i < count; ++i) { - cpvs[i] = point2cpv(points[i]); + out[i] = point2cpv(points[i]); } - return cpvs; + return out; } }; From ba8b4866e289a89fae87b6fb456a7bdfbae820f1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 15:57:57 +0800 Subject: [PATCH 429/557] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 0c11df97d6..37e302de05 100644 --- a/AUTHORS +++ b/AUTHORS @@ -628,6 +628,7 @@ Developers: HoGarfield (garfield_ho) Fixed a bug that CCBReader can't play sequence automatically in JSB. Could not set next animation in CCBAnimationCompleted callback. + Fixed missing to add JSAutoCompartment when invoking JS functions from C++. lite3 Fixed a bug that Node's anchor point was changed after being added to ScrollView. From d990699417ac4a5dee2af27d84e132553a3c8a62 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 08:00:35 +0000 Subject: [PATCH 430/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index e150a74a02..9b0b068f92 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit e150a74a028e26cff0dac7d2238e2cd16fbaf370 +Subproject commit 9b0b068f923249440b8a8c758b1c06d29f6cbdfe From e0aa82da138c7a789e3335eac249143b23f78e91 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 16:04:06 +0800 Subject: [PATCH 431/557] Merge master branch to develop branch --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../cocostudio/CCActionNode.cpp | 2 +- .../cocostudio/CCSGUIReader.cpp | 35 +- .../cocostudio/CCSSceneReader.cpp | 4 +- cocos/gui/CocosGUI.h | 5 +- cocos/gui/Layout.cpp | 785 -------- cocos/gui/UIButton.cpp | 176 +- cocos/gui/UIButton.h | 19 +- cocos/gui/UICheckBox.cpp | 64 +- cocos/gui/UICheckBox.h | 17 +- cocos/gui/UIDragPanel.cpp | 1269 ------------ cocos/gui/UIDragPanel.h | 367 ---- cocos/gui/UIHelper.cpp | 134 +- cocos/gui/UIHelper.h | 65 +- cocos/gui/UIImageView.cpp | 49 +- cocos/gui/UIImageView.h | 16 +- cocos/gui/UIInputManager.cpp | 6 +- cocos/gui/UIInputManager.h | 4 +- cocos/gui/UILabel.cpp | 39 +- cocos/gui/UILabel.h | 13 +- cocos/gui/UILabelAtlas.cpp | 51 +- cocos/gui/UILabelAtlas.h | 19 +- cocos/gui/UILabelBMFont.cpp | 45 +- cocos/gui/UILabelBMFont.h | 9 +- cocos/gui/UILayer.cpp | 4 +- cocos/gui/UILayout.cpp | 1010 ++++++++++ cocos/gui/{Layout.h => UILayout.h} | 47 +- cocos/gui/UILayoutDefine.cpp | 2 +- cocos/gui/UILayoutDefine.h | 28 +- ...outParameter.cpp => UILayoutParameter.cpp} | 39 +- ...{LayoutParameter.h => UILayoutParameter.h} | 42 +- cocos/gui/UIListView.cpp | 1753 ++++------------- cocos/gui/UIListView.h | 294 ++- cocos/gui/UILoadingBar.cpp | 98 +- cocos/gui/UILoadingBar.h | 7 +- cocos/gui/UIPageView.cpp | 151 +- cocos/gui/UIPageView.h | 26 +- cocos/gui/UIRootWidget.cpp | 6 +- cocos/gui/UIRootWidget.h | 10 +- cocos/gui/UIScrollInterface.h | 1 - cocos/gui/UIScrollView.cpp | 1595 +++++++++++---- cocos/gui/UIScrollView.h | 216 +- cocos/gui/UISlider.cpp | 138 +- cocos/gui/UISlider.h | 9 +- cocos/gui/UITextField.cpp | 149 +- cocos/gui/UITextField.h | 46 +- cocos/gui/UIWidget.cpp | 305 +-- cocos/gui/UIWidget.h | 71 +- .../CocoStudioGUITest/CocosGUIScene.cpp | 1 - .../UIDragPanelTest/UIDragPanelTest.cpp | 160 +- .../UIDragPanelTest/UIDragPanelTest.h | 2 - .../UIListViewTest/UIListViewTest.cpp | 202 +- .../UIListViewTest/UIListViewTest.h | 2 - .../UIPageViewTest/UIPageViewTest.cpp | 4 +- .../UIPanelTest/UIPanelTest.cpp | 56 +- .../CocoStudioGUITest/UIScene.cpp | 3 +- .../CocoStudioGUITest/UIScene.h | 2 +- .../UIScrollViewTest/UIScrollViewTest.cpp | 7 +- .../UITextFieldTest/UITextFieldTest.cpp | 10 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 1 - 61 files changed, 4104 insertions(+), 5590 deletions(-) delete mode 100644 cocos/gui/Layout.cpp delete mode 100644 cocos/gui/UIDragPanel.cpp delete mode 100644 cocos/gui/UIDragPanel.h create mode 100644 cocos/gui/UILayout.cpp rename cocos/gui/{Layout.h => UILayout.h} (89%) rename cocos/gui/{LayoutParameter.cpp => UILayoutParameter.cpp} (65%) rename cocos/gui/{LayoutParameter.h => UILayoutParameter.h} (82%) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index ac519a56c8..0d15fff578 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5a0361664f33af4303065c98da4b8d8e4efe48b4 \ No newline at end of file +12034db6a7c20a09b3e866ab79a536bfc0208d3f \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index ba37de5f5d..07c8b22d15 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b473303312be3b69891020b5fb470dd382f31284 \ No newline at end of file +f441e32e09388d5c434035e100e591cf9a6d29fd \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index fceca8816c..c0484a9dd8 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -159,7 +159,7 @@ void ActionNode::initActionNodeFromRoot(Object* root) UIWidget* rootWidget = dynamic_cast(root); if (rootWidget != NULL) { - UIWidget* widget = UIHelper::instance()->seekActionWidgetByActionTag(rootWidget, getActionTag()); + UIWidget* widget = UIHelper::seekActionWidgetByActionTag(rootWidget, getActionTag()); if (widget != NULL) { setObject(widget); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 77cb5d56de..8fd5fba3a1 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -152,7 +152,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "Panel") == 0) { - widget = Layout::create(); + widget = UILayout::create(); setPropsForPanelFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "Slider") == 0) @@ -177,7 +177,7 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "DragPanel") == 0) { - widget = UIDragPanel::create(); + widget = UIScrollView::create(); setPropsForDragPanelFromJsonDictionary(widget, uiOptions); } @@ -232,20 +232,20 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) const char* file = DICTOOL->getStringValueFromArray_json(jsonDict, "textures", i); std::string tp = m_strFilePath; tp.append(file); - CCUIHELPER->addSpriteFrame(tp.c_str()); +// CCUIHELPER->addSpriteFrame(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); - CCUIHELPER->setFileDesignWidth(winSize.width); - CCUIHELPER->setFileDesignHeight(winSize.height); +// CCUIHELPER->setFileDesignWidth(winSize.width); +// CCUIHELPER->setFileDesignHeight(winSize.height); } else { - CCUIHELPER->setFileDesignWidth(fileDesignWidth); - CCUIHELPER->setFileDesignHeight(fileDesignHeight); +// CCUIHELPER->setFileDesignWidth(fileDesignWidth); +// CCUIHELPER->setFileDesignHeight(fileDesignHeight); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); @@ -253,7 +253,7 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) /* *********temp********* */ if (widget->getContentSize().equals(Size::ZERO)) { - Layout* rootWidget = dynamic_cast(widget); + UILayout* rootWidget = dynamic_cast(widget); rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); } /* ********************** */ @@ -792,7 +792,7 @@ void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictio setPropsForWidgetFromJsonDictionary(widget, options); UILabel* label = (UILabel*)widget; bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable"); - label->setTouchScaleChangeAble(touchScaleChangeAble); + label->setTouchScaleChangeEnabled(touchScaleChangeAble); const char* text = DICTOOL->getStringValue_json(options, "text"); label->setText(text); bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); @@ -877,10 +877,9 @@ void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonD void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { setPropsForWidgetFromJsonDictionary(widget, options); - Layout* containerWidget = (Layout*)widget; + UILayout* containerWidget = (UILayout*)widget; if (!dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget)) + && !dynamic_cast(containerWidget)) { containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble")); } @@ -892,7 +891,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio if (m_bOlderVersion) { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -959,7 +958,7 @@ void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictio else { setPropsForContainerWidgetFromJsonDictionary(widget, options); - Layout* panel = (Layout*)widget; + UILayout* panel = (UILayout*)widget; bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); int cr = DICTOOL->getIntValue_json(options, "bgColorR"); @@ -1394,7 +1393,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi //textField->setSize(CCSizeMake(dw, dh)); } bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable"); - textField->setMaxLengthEnable(maxLengthEnable); + textField->setMaxLengthEnabled(maxLengthEnable); if (maxLengthEnable) { @@ -1402,7 +1401,7 @@ void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDi textField->setMaxLength(maxLength); } bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable"); - textField->setPasswordEnable(passwordEnable); + textField->setPasswordEnabled(passwordEnable); if (passwordEnable) { textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText")); @@ -1557,10 +1556,10 @@ void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, Json { setPropsForPanelFromJsonDictionary(widget, options); - UIDragPanel* dragPanel = (UIDragPanel*)widget; + UIScrollView* dragPanel = (UIScrollView*)widget; bool bounceEnable = DICTOOL->getBooleanValue_json(options, "bounceEnable"); - dragPanel->setBounceEnable(bounceEnable); + dragPanel->setBounceEnabled(bounceEnable); float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 3d8bc7fd8c..c660b91990 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -320,8 +320,8 @@ namespace cocostudio { { gui::UILayer *pLayer = gui::UILayer::create(); pLayer->scheduleUpdate(); - UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); - pLayer->addWidget(widget); +// UIWidget* widget= gui::UIHelper::instance()->createWidgetFromJsonFile(pPath.c_str()); +// pLayer->addWidget(widget); ComRender *pRender = ComRender::create(pLayer, "GUIComponent"); if (pComName != NULL) { diff --git a/cocos/gui/CocosGUI.h b/cocos/gui/CocosGUI.h index 497c4f89b6..663aff26e7 100644 --- a/cocos/gui/CocosGUI.h +++ b/cocos/gui/CocosGUI.h @@ -27,7 +27,7 @@ #include "gui/UIWidget.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIRootWidget.h" #include "gui/UIButton.h" #include "gui/UICheckBox.h" @@ -36,10 +36,9 @@ #include "gui/UILabelAtlas.h" #include "gui/UILoadingBar.h" #include "gui/UIScrollView.h" +#include "gui/UIListView.h" #include "gui/UISlider.h" #include "gui/UITextField.h" -#include "gui/UIListView.h" -#include "gui/UIDragPanel.h" #include "gui/UILabelBMFont.h" #include "gui/UIPageView.h" #include "gui/UIHelper.h" diff --git a/cocos/gui/Layout.cpp b/cocos/gui/Layout.cpp deleted file mode 100644 index a9e4f75a30..0000000000 --- a/cocos/gui/Layout.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/Layout.h" -#include "gui/UILayer.h" -#include "gui/UIHelper.h" -#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - - using namespace cocos2d; - using namespace cocos2d::extension; - -namespace gui { - -#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) - -Layout::Layout(): -_clippingEnabled(false), -_backGroundScale9Enabled(false), -_backGroundImage(NULL), -_backGroundImageFileName(""), -_backGroundImageCapInsets(Rect::ZERO), -_colorType(LAYOUT_COLOR_NONE), -_bgImageTexType(UI_TEX_TYPE_LOCAL), -_colorRender(NULL), -_gradientRender(NULL), -_cColor(Color3B::WHITE), -_gStartColor(Color3B::WHITE), -_gEndColor(Color3B::WHITE), -_alongVector(Point(0.0f, -1.0f)), -_cOpacity(255), -_backGroundImageTextureSize(Size::ZERO), -_layoutType(LAYOUT_ABSOLUTE) -{ - _widgetType = WidgetTypeContainer; -} - -Layout::~Layout() -{ -} - -Layout* Layout::create() -{ - Layout* layout = new Layout(); - if (layout && layout->init()) - { - layout->autorelease(); - return layout; - } - CC_SAFE_DELETE(layout); - return NULL; -} - -bool Layout::init() -{ - _children = CCArray::create(); - _children->retain(); - initRenderer(); - _renderer->retain(); - _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = dynamic_cast(_renderer); - if (renderRGBA) - { - renderRGBA->setCascadeColorEnabled(false); - renderRGBA->setCascadeOpacityEnabled(false); - } - ignoreContentAdaptWithSize(false); - setSize(Size::ZERO); - setBright(true); - setAnchorPoint(Point(0, 0)); - _scheduler = Director::getInstance()->getScheduler(); - CC_SAFE_RETAIN(_scheduler); - return true; -} - -void Layout::initRenderer() -{ - _renderer = RectClippingNode::create(); -} - -bool Layout::isClippingEnabled() -{ - return _clippingEnabled; -} - -bool Layout::hitTest(const Point &pt) -{ - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(0.0f, 0.0f, _size.width, _size.height); - if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) - { - return true; - } - return false; -} - -void Layout::setClippingEnabled(bool able) -{ - _clippingEnabled = able; - DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); -} - -void Layout::onSizeChanged() -{ - DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); - doLayout(); - if (_backGroundImage) - { - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - } - if (_colorRender) - { - _colorRender->setContentSize(_size); - } - if (_gradientRender) - { - _gradientRender->setContentSize(_size); - } -} - -void Layout::setBackGroundImageScale9Enabled(bool able) -{ - if (_backGroundScale9Enabled == able) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundScale9Enabled = able; - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _renderer->addChild(_backGroundImage); - } - else - { - _backGroundImage = Sprite::create(); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setZOrder(-1); - setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); - setBackGroundImageCapInsets(_backGroundImageCapInsets); -} - -void Layout::setBackGroundImage(const char* fileName,TextureResType texType) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - if (_backGroundImage == NULL) - { - addBackGroundImage(); - } - _backGroundImageFileName = fileName; - _bgImageTexType = texType; - if (_backGroundScale9Enabled) - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - switch (_bgImageTexType) - { - case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); - break; - case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); - break; - default: - break; - } - } - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - else - { - dynamic_cast(_backGroundImage)->setColor(getColor()); - dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); - } - _backGroundImageTextureSize = _backGroundImage->getContentSize(); - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::setBackGroundImageCapInsets(const Rect &capInsets) -{ - _backGroundImageCapInsets = capInsets; - if (_backGroundScale9Enabled) - { - dynamic_cast(_backGroundImage)->setCapInsets(capInsets); - } -} - -void Layout::addBackGroundImage() -{ - if (_backGroundScale9Enabled) - { - _backGroundImage = Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - dynamic_cast(_backGroundImage)->setPreferredSize(_size); - } - else - { - _backGroundImage = CCSprite::create(); - _backGroundImage->setZOrder(-1); - _renderer->addChild(_backGroundImage); - } - _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); -} - -void Layout::removeBackGroundImage() -{ - if (!_backGroundImage) - { - return; - } - _renderer->removeChild(_backGroundImage, true); - _backGroundImage = NULL; - _backGroundImageFileName = ""; - _backGroundImageTextureSize = Size::ZERO; -} - -void Layout::setBackGroundColorType(LayoutBackGroundColorType type) -{ - if (_colorType == type) - { - return; - } - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - case LAYOUT_COLOR_SOLID: - if (_colorRender) - { - _renderer->removeChild(_colorRender, true); - _colorRender = NULL; - } - break; - case LAYOUT_COLOR_GRADIENT: - if (_gradientRender) - { - _renderer->removeChild(_gradientRender, true); - _gradientRender = NULL; - } - break; - default: - break; - } - _colorType = type; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender = CCLayerColor::create(); - _colorRender->setContentSize(_size); - _colorRender->setOpacity(_cOpacity); - _colorRender->setColor(_cColor); - _renderer->addChild(_colorRender,-2); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender = CCLayerGradient::create(); - _gradientRender->setContentSize(_size); - _gradientRender->setOpacity(_cOpacity); - _gradientRender->setStartColor(_gStartColor); - _gradientRender->setEndColor(_gEndColor); - _gradientRender->setVector(_alongVector); - _renderer->addChild(_gradientRender,-2); - break; - default: - break; - } -} - -void Layout::setBackGroundColor(const Color3B &color) -{ - _cColor = color; - if (_colorRender) - { - _colorRender->setColor(color); - } -} - -void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endColor) -{ - _gStartColor = startColor; - if (_gradientRender) - { - _gradientRender->setStartColor(startColor); - } - _gEndColor = endColor; - if (_gradientRender) - { - _gradientRender->setEndColor(endColor); - } -} - -void Layout::setBackGroundColorOpacity(int opacity) -{ - _cOpacity = opacity; - switch (_colorType) - { - case LAYOUT_COLOR_NONE: - break; - case LAYOUT_COLOR_SOLID: - _colorRender->setOpacity(opacity); - break; - case LAYOUT_COLOR_GRADIENT: - _gradientRender->setOpacity(opacity); - break; - default: - break; - } -} - -void Layout::setBackGroundColorVector(const Point &vector) -{ - _alongVector = vector; - if (_gradientRender) - { - _gradientRender->setVector(vector); - } -} - -void Layout::setColor(const Color3B &color) -{ - UIWidget::setColor(color); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setColor(color); - } - } -} - -void Layout::setOpacity(int opacity) -{ - UIWidget::setOpacity(opacity); - if (_backGroundImage) - { - RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); - if (rgbap) - { - rgbap->setOpacity(opacity); - } - } -} - -const Size& Layout::getBackGroundImageTextureSize() const -{ - return _backGroundImageTextureSize; -} - -const Size& Layout::getContentSize() const -{ - return _renderer->getContentSize(); -} - -void Layout::setLayoutType(LayoutType type) -{ - _layoutType = type; -} - -LayoutType Layout::getLayoutType() const -{ - return _layoutType; -} - -void Layout::doLayout() -{ - switch (_layoutType) - { - case LAYOUT_ABSOLUTE: - break; - case LAYOUT_LINEAR_VERTICAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float topBoundary = layoutSize.height; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? topBoundary - ((1.0f-ap.y) * cs.height) : topBoundary - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_LEFT: - break; - case LINEAR_GRAVITY_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case LINEAR_GRAVITY_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width / 2.0f - cs.width * (0.5f-ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - topBoundary = child->getBottomInParent() - mg.bottom; - } - } - break; - } - case LAYOUT_LINEAR_HORIZONTAL: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - float leftBoundary = 0.0f; - for (int i=0; i(layoutChildrenArray->arr[i]); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - - if (layoutParameter) - { - WidgetType childType = child->getWidgetType(); - UILinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = childType == WidgetTypeWidget ? leftBoundary + (ap.x * cs.width) : leftBoundary; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - (1.0f - ap.y) * cs.height : layoutSize.height - cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_TOP: - break; - case LINEAR_GRAVITY_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case LINEAR_GRAVITY_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height/2.0f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - default: - break; - } - UIMargin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - leftBoundary = child->getRightInParent() + mg.right; - } - } - break; - } - case LAYOUT_RELATIVE: - { - ccArray* layoutChildrenArray = getChildren()->data; - int length = layoutChildrenArray->num; - Size layoutSize = getSize(); - for (int i=0; i(layoutChildrenArray->arr[i]); - WidgetType childType = child->getWidgetType(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); - if (layoutParameter) - { - float finalPosX = childType == WidgetTypeWidget ? ap.x * cs.width : 0.0f; - float finalPosY = childType == WidgetTypeWidget ? layoutSize.height - ((1.0f - ap.y) * cs.height) : layoutSize.height - cs.height; - UIRelativeAlign align = layoutParameter->getAlign(); - const char* relativeName = layoutParameter->getRelativeToWidgetName(); - UIWidget* relativeWidget = NULL; - if (relativeName && strcmp(relativeName, "")) - { - relativeWidget = CCUIHELPER->seekWidgetByRelativeName(this, relativeName); - } - switch (align) - { - case RELATIVE_ALIGN_NONE: - break; - case RELATIVE_ALIGN_PARENT_LEFT: - break; - case RELATIVE_ALIGN_PARENT_TOP: - break; - case RELATIVE_ALIGN_PARENT_RIGHT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width - ((1.0f - ap.x) * cs.width) : layoutSize.width - cs.width; - break; - case RELATIVE_ALIGN_PARENT_BOTTOM: - finalPosY = childType == WidgetTypeWidget ? ap.y * cs.height : 0.0f; - break; - case RELATIVE_CENTER_IN_PARENT: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_CENTER_HORIZONTAL: - finalPosX = childType == WidgetTypeWidget ? layoutSize.width * 0.5f - cs.width * (0.5f - ap.x) : (layoutSize.width - cs.width) * 0.5f; - break; - case RELATIVE_CENTER_VERTICAL: - finalPosY = childType == WidgetTypeWidget ? layoutSize.height * 0.5f - cs.height * (0.5f - ap.y) : (layoutSize.height - cs.height) * 0.5f; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_LEFT_OF_CENTER: - break; - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationRight = relativeWidget->getLeftInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - ap.y * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - break; - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - if (relativeWidget) - { - float locationLeft = relativeWidget->getRightInParent(); - float locationBottom = relativeWidget->getBottomInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_ABOVE_CENTER: - break; - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - if (relativeWidget) - { - float locationBottom = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationBottom + ap.y * cs.height : locationBottom; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationLeft + ap.x * cs.width : locationLeft; - } - break; - case RELATIVE_LOCATION_BELOW_CENTER: - break; - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - if (relativeWidget) - { - float locationTop = relativeWidget->getBottomInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = childType == WidgetTypeWidget ? locationTop - (1.0f - ap.y) * cs.height : locationTop - cs.height; - finalPosX = childType == WidgetTypeWidget ? locationRight - (1.0f - ap.x) * cs.width : locationRight - cs.width; - } - break; - default: - break; - } - UIMargin relativeWidgetMargin; - UIMargin mg; - if (relativeWidget) - { - relativeWidgetMargin = relativeWidget->getLayoutParameter()->getMargin(); - mg = child->getLayoutParameter()->getMargin(); - } - //handle margin - switch (align) - { - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - case RELATIVE_LOCATION_ABOVE_CENTER: - finalPosY += relativeWidgetMargin.top; - finalPosY += mg.bottom; - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - case RELATIVE_LOCATION_BELOW_CENTER: - finalPosY -= relativeWidgetMargin.bottom; - finalPosY -= mg.top; - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_LEFT_OF_CENTER: - finalPosX -= relativeWidgetMargin.left; - finalPosX -= mg.right; - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - finalPosX += relativeWidgetMargin.right; - finalPosX += mg.left; - break; - default: - break; - } - child->setPosition(Point(finalPosX, finalPosY)); - } - } - break; - } - default: - break; - } -} - -const char* Layout::getDescription() const -{ - return "Layout"; -} - -RectClippingNode::RectClippingNode(): -m_pInnerStencil(NULL), -_enabled(true), -_clippingSize(Size(50.0f, 50.0f)), -_clippingEnabled(false) -{ - -} - -RectClippingNode::~RectClippingNode() -{ - -} - -RectClippingNode* RectClippingNode::create() -{ - RectClippingNode *pRet = new RectClippingNode(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - - return pRet; -} - -bool RectClippingNode::init() -{ - m_pInnerStencil = CCDrawNode::create(); - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - - Color4F green(0, 1, 0, 1); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); - if (CCClippingNode::init(m_pInnerStencil)) - { - return true; - } - return false; -} - - -void RectClippingNode::setClippingSize(const Size &size) -{ - setContentSize(size); - _clippingSize = size; - rect[0] = Point(0, 0); - rect[1] = Point(_clippingSize.width, 0); - rect[2] = Point(_clippingSize.width, _clippingSize.height); - rect[3] = Point(0, _clippingSize.height); - Color4F green(0, 1, 0, 1); - m_pInnerStencil->clear(); - m_pInnerStencil->drawPolygon(rect, 4, green, 0, green); -} - -void RectClippingNode::setClippingEnabled(bool enabled) -{ - _clippingEnabled = enabled; -} - -void RectClippingNode::visit() -{ - if (!_enabled) - { - return; - } - if (_clippingEnabled) - { - CCClippingNode::visit(); - } - else - { - CCNode::visit(); - } -} - -void RectClippingNode::setEnabled(bool enabled) -{ - _enabled = enabled; -} - -bool RectClippingNode::isEnabled() const -{ - return _enabled; -} - -} diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 12cc3cc932..b0c0c89630 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -25,9 +25,6 @@ #include "gui/UIButton.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { #define NORMALRENDERERZ (0) @@ -45,9 +42,9 @@ _clickedFileName(""), _disabledFileName(""), _prevIgnoreSize(true), _scale9Enabled(false), -_capInsetsNormal(Rect::ZERO), -_capInsetsPressed(Rect::ZERO), -_capInsetsDisabled(Rect::ZERO), +_capInsetsNormal(cocos2d::Rect::ZERO), +_capInsetsPressed(cocos2d::Rect::ZERO), +_capInsetsDisabled(cocos2d::Rect::ZERO), _normalTexType(UI_TEX_TYPE_LOCAL), _pressedTexType(UI_TEX_TYPE_LOCAL), _disabledTexType(UI_TEX_TYPE_LOCAL), @@ -55,7 +52,7 @@ _normalTextureSize(_size), _pressedTextureSize(_size), _disabledTextureSize(_size), _pressedActionEnabled(false), -_titleColor(Color3B::WHITE) +_titleColor(cocos2d::Color3B::WHITE) { } @@ -88,10 +85,10 @@ bool UIButton::init() void UIButton::initRenderer() { UIWidget::initRenderer(); - _buttonNormalRenderer = Sprite::create(); - _buttonClickedRenderer = Sprite::create(); - _buttonDisableRenderer = Sprite::create(); - _titleRenderer = LabelTTF::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); + _titleRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_buttonNormalRenderer,NORMALRENDERERZ); _renderer->addChild(_buttonClickedRenderer,PRESSEDRENDERERZ); _renderer->addChild(_buttonDisableRenderer,DISABLEDRENDERERZ); @@ -117,15 +114,15 @@ void UIButton::setScale9Enabled(bool able) _buttonDisableRenderer = NULL; if (_scale9Enabled) { - _buttonNormalRenderer = Scale9Sprite::create(); - _buttonClickedRenderer = Scale9Sprite::create(); - _buttonDisableRenderer = Scale9Sprite::create(); + _buttonNormalRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonClickedRenderer = cocos2d::extension::Scale9Sprite::create(); + _buttonDisableRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _buttonNormalRenderer = CCSprite::create(); - _buttonClickedRenderer = CCSprite::create(); - _buttonDisableRenderer = CCSprite::create(); + _buttonNormalRenderer = cocos2d::Sprite::create(); + _buttonClickedRenderer = cocos2d::Sprite::create(); + _buttonDisableRenderer = cocos2d::Sprite::create(); } loadTextureNormal(_normalFileName.c_str(), _normalTexType); @@ -179,32 +176,33 @@ void UIButton::loadTextureNormal(const char* normal,TextureResType texType) switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(_capInsetsNormal); } else { switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); break; default: break; } - dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); - dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonNormalRenderer)->setColor(getColor()); + dynamic_cast(_buttonNormalRenderer)->setOpacity(getOpacity()); } _normalTextureSize = _buttonNormalRenderer->getContentSize(); updateAnchorPoint(); @@ -224,32 +222,33 @@ void UIButton::loadTexturePressed(const char* selected,TextureResType texType) switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(_capInsetsPressed); } else { switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); break; default: break; } - dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); - dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonClickedRenderer)->setColor(getColor()); + dynamic_cast(_buttonClickedRenderer)->setOpacity(getOpacity()); } _pressedTextureSize = _buttonClickedRenderer->getContentSize(); updateAnchorPoint(); @@ -269,73 +268,74 @@ void UIButton::loadTextureDisabled(const char* disabled,TextureResType texType) switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(_capInsetsDisabled); } else { switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); break; default: break; } - dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); - dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); + dynamic_cast(_buttonDisableRenderer)->setColor(getColor()); + dynamic_cast(_buttonDisableRenderer)->setOpacity(getOpacity()); } _disabledTextureSize = _buttonDisableRenderer->getContentSize(); updateAnchorPoint(); disabledTextureScaleChangedWithSize(); } -void UIButton::setCapInsets(const Rect &capInsets) +void UIButton::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsNormalRenderer(capInsets); setCapInsetsPressedRenderer(capInsets); setCapInsetsDisabledRenderer(capInsets); } -void UIButton::setCapInsetsNormalRenderer(const Rect &capInsets) +void UIButton::setCapInsetsNormalRenderer(const cocos2d::Rect &capInsets) { _capInsetsNormal = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonNormalRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsPressedRenderer(const Rect &capInsets) +void UIButton::setCapInsetsPressedRenderer(const cocos2d::Rect &capInsets) { _capInsetsPressed = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonClickedRenderer)->setCapInsets(capInsets); } -void UIButton::setCapInsetsDisabledRenderer(const Rect &capInsets) +void UIButton::setCapInsetsDisabledRenderer(const cocos2d::Rect &capInsets) { _capInsetsDisabled = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); + dynamic_cast(_buttonDisableRenderer)->setCapInsets(capInsets); } void UIButton::onPressStateChangedToNormal() @@ -348,9 +348,9 @@ void UIButton::onPressStateChangedToNormal() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.0f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.0f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.0f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -367,9 +367,9 @@ void UIButton::onPressStateChangedToPressed() _buttonNormalRenderer->stopAllActions(); _buttonClickedRenderer->stopAllActions(); _buttonDisableRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction1 = ScaleTo::create(0.05f, 1.1f); - Action *zoomAction2 = ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction1 = cocos2d::ScaleTo::create(0.05f, 1.1f); + cocos2d::Action *zoomAction2 = cocos2d::ScaleTo::create(0.05f, 1.1f); _buttonNormalRenderer->runAction(zoomAction); _buttonClickedRenderer->runAction(zoomAction1); _buttonDisableRenderer->runAction(zoomAction2); @@ -390,9 +390,9 @@ void UIButton::setFlipX(bool flipX) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); - dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonNormalRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonClickedRenderer)->setFlippedX(flipX); + dynamic_cast(_buttonDisableRenderer)->setFlippedX(flipX); } void UIButton::setFlipY(bool flipY) @@ -402,9 +402,9 @@ void UIButton::setFlipY(bool flipY) { return; } - dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); - dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonNormalRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonClickedRenderer)->setFlippedY(flipY); + dynamic_cast(_buttonDisableRenderer)->setFlippedY(flipY); } bool UIButton::isFlipX() @@ -413,7 +413,7 @@ bool UIButton::isFlipX() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedX(); } bool UIButton::isFlipY() @@ -422,16 +422,16 @@ bool UIButton::isFlipY() { return false; } - return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); + return dynamic_cast(_buttonNormalRenderer)->isFlippedY(); } -void UIButton::setAnchorPoint(const Point &pt) +void UIButton::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _buttonNormalRenderer->setAnchorPoint(pt); _buttonClickedRenderer->setAnchorPoint(pt); _buttonDisableRenderer->setAnchorPoint(pt); - _titleRenderer->setPosition(Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); + _titleRenderer->setPosition(cocos2d::Point(_size.width*(0.5f-_anchorPoint.x), _size.height*(0.5f-_anchorPoint.y))); } void UIButton::onSizeChanged() @@ -441,12 +441,12 @@ void UIButton::onSizeChanged() disabledTextureScaleChangedWithSize(); } -const Size& UIButton::getContentSize() const +const cocos2d::Size& UIButton::getContentSize() const { return _normalTextureSize; } -Node* UIButton::getVirtualRenderer() +cocos2d::Node* UIButton::getVirtualRenderer() { if (_bright) { @@ -480,11 +480,11 @@ void UIButton::normalTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonNormalRenderer)->setPreferredSize(_size); } else { - Size textureSize = _normalTextureSize; + cocos2d::Size textureSize = _normalTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonNormalRenderer->setScale(1.0f); @@ -511,11 +511,11 @@ void UIButton::pressedTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonClickedRenderer)->setPreferredSize(_size); } else { - Size textureSize = _pressedTextureSize; + cocos2d::Size textureSize = _pressedTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonClickedRenderer->setScale(1.0f); @@ -542,11 +542,11 @@ void UIButton::disabledTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); + dynamic_cast(_buttonDisableRenderer)->setPreferredSize(_size); } else { - Size textureSize = _disabledTextureSize; + cocos2d::Size textureSize = _disabledTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _buttonDisableRenderer->setScale(1.0f); @@ -575,13 +575,13 @@ const char* UIButton::getTitleText() const return _titleRenderer->getString(); } -void UIButton::setTitleColor(const Color3B& color) +void UIButton::setTitleColor(const cocos2d::Color3B& color) { _titleColor = color; _titleRenderer->setColor(color); } -const Color3B& UIButton::getTitleColor() const +const cocos2d::Color3B& UIButton::getTitleColor() const { return _titleRenderer->getColor(); } @@ -606,7 +606,7 @@ const char* UIButton::getTitleFontName() const return _titleRenderer->getFontName(); } -void UIButton::setColor(const Color3B &color) +void UIButton::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); setTitleColor(_titleColor); @@ -617,4 +617,30 @@ const char* UIButton::getDescription() const return "Button"; } +UIWidget* UIButton::createCloneInstance() +{ + return UIButton::create(); +} + +void UIButton::copySpecialProperties(UIWidget *widget) +{ + UIButton* button = dynamic_cast(widget); + if (button) + { + _prevIgnoreSize = button->_prevIgnoreSize; + setScale9Enabled(button->_scale9Enabled); + loadTextureNormal(button->_normalFileName.c_str(), button->_normalTexType); + loadTexturePressed(button->_clickedFileName.c_str(), button->_pressedTexType); + loadTextureDisabled(button->_disabledFileName.c_str(), button->_disabledTexType); + setCapInsetsNormalRenderer(button->_capInsetsNormal); + setCapInsetsPressedRenderer(button->_capInsetsPressed); + setCapInsetsDisabledRenderer(button->_capInsetsDisabled); + setTitleText(button->getTitleText()); + setTitleFontName(button->getTitleFontName()); + setTitleFontSize(button->getTitleFontSize()); + setTitleColor(button->getTitleColor()); + setPressedActionEnabled(button->_pressedActionEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index 94d40ec65f..bc6958c3e4 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -27,8 +27,12 @@ #include "gui/UIWidget.h" -namespace gui { +namespace gui{ +/** +* @js NA +* @lua NA +*/ class UIButton : public UIWidget { public: @@ -162,6 +166,11 @@ public: */ virtual void setColor(const cocos2d::Color3B &color); + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + void setTitleText(const char* text); const char* getTitleText() const; void setTitleColor(const cocos2d::Color3B& color); @@ -170,11 +179,7 @@ public: float getTitleFontSize() const; void setTitleFontName(const char* fontName); const char* getTitleFontName() const; - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -186,6 +191,8 @@ protected: void normalTextureScaleChangedWithSize(); void pressedTextureScaleChangedWithSize(); void disabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _buttonNormalRenderer; cocos2d::Node* _buttonClickedRenderer; diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index f685d73b11..a826fa40ef 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -24,10 +24,9 @@ #include "gui/UICheckBox.h" - using namespace cocos2d; - namespace gui { + UICheckBox::UICheckBox(): _backGroundBoxRenderer(NULL), _backGroundSelectedBoxRenderer(NULL), @@ -41,7 +40,12 @@ _backGroundTexType(UI_TEX_TYPE_LOCAL), _backGroundSelectedTexType(UI_TEX_TYPE_LOCAL), _frontCrossTexType(UI_TEX_TYPE_LOCAL), _backGroundDisabledTexType(UI_TEX_TYPE_LOCAL), -_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL) +_frontCrossDisabledTexType(UI_TEX_TYPE_LOCAL), +_backGroundFileName(""), +_backGroundSelectedFileName(""), +_frontCrossFileName(""), +_backGroundDisabledFileName(""), +_frontCrossDisabledFileName("") { } @@ -75,11 +79,11 @@ bool UICheckBox::init() void UICheckBox::initRenderer() { UIWidget::initRenderer(); - _backGroundBoxRenderer = Sprite::create(); - _backGroundSelectedBoxRenderer = Sprite::create(); - _frontCrossRenderer = Sprite::create(); - _backGroundBoxDisabledRenderer = Sprite::create(); - _frontCrossDisabledRenderer = Sprite::create(); + _backGroundBoxRenderer = cocos2d::Sprite::create(); + _backGroundSelectedBoxRenderer = cocos2d::Sprite::create(); + _frontCrossRenderer = cocos2d::Sprite::create(); + _backGroundBoxDisabledRenderer = cocos2d::Sprite::create(); + _frontCrossDisabledRenderer = cocos2d::Sprite::create(); _renderer->addChild(_backGroundBoxRenderer); _renderer->addChild(_backGroundSelectedBoxRenderer); _renderer->addChild(_frontCrossRenderer); @@ -102,6 +106,7 @@ void UICheckBox::loadTextureBackGround(const char *backGround,TextureResType tex { return; } + _backGroundFileName = backGround; _backGroundTexType = texType; switch (_backGroundTexType) { @@ -125,6 +130,7 @@ void UICheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,Te { return; } + _backGroundSelectedFileName = backGroundSelected; _backGroundSelectedTexType = texType; switch (_backGroundSelectedTexType) { @@ -148,6 +154,7 @@ void UICheckBox::loadTextureFrontCross(const char *cross,TextureResType texType) { return; } + _frontCrossFileName = cross; _frontCrossTexType = texType; switch (_frontCrossTexType) { @@ -171,6 +178,7 @@ void UICheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,Te { return; } + _backGroundDisabledFileName = backGroundDisabled; _backGroundDisabledTexType = texType; switch (_backGroundDisabledTexType) { @@ -194,6 +202,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te { return; } + _frontCrossDisabledFileName = frontCrossDisabled; _frontCrossDisabledTexType = texType; switch (_frontCrossDisabledTexType) { @@ -211,7 +220,7 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te frontCrossDisabledTextureScaleChangedWithSize(); } -void UICheckBox::onTouchEnded(const Point &touchPoint) +void UICheckBox::onTouchEnded(const cocos2d::Point &touchPoint) { if (_focus) { @@ -289,7 +298,7 @@ void UICheckBox::unSelectedEvent() } } -void UICheckBox::addEventListener(Object *target, SEL_SelectedStateEvent selector) +void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { _selectedStateEventListener = target; _selectedStateEventSelector = selector; @@ -323,7 +332,7 @@ bool UICheckBox::isFlipY() return _backGroundBoxRenderer->isFlippedY(); } -void UICheckBox::setAnchorPoint(const Point &pt) +void UICheckBox::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _backGroundBoxRenderer->setAnchorPoint(pt); @@ -342,12 +351,12 @@ void UICheckBox::onSizeChanged() frontCrossDisabledTextureScaleChangedWithSize(); } -const Size& UICheckBox::getContentSize() const +const cocos2d::Size& UICheckBox::getContentSize() const { return _backGroundBoxRenderer->getContentSize(); } -Node* UICheckBox::getVirtualRenderer() +cocos2d::Node* UICheckBox::getVirtualRenderer() { return _backGroundBoxRenderer; } @@ -361,7 +370,7 @@ void UICheckBox::backGroundTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxRenderer->setScale(1.0f); @@ -382,7 +391,7 @@ void UICheckBox::backGroundSelectedTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundSelectedBoxRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundSelectedBoxRenderer->setScale(1.0f); @@ -403,7 +412,7 @@ void UICheckBox::frontCrossTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossRenderer->setScale(1.0f); @@ -424,7 +433,7 @@ void UICheckBox::backGroundDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _backGroundBoxDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _backGroundBoxDisabledRenderer->setScale(1.0f); @@ -445,7 +454,7 @@ void UICheckBox::frontCrossDisabledTextureScaleChangedWithSize() } else { - Size textureSize = _frontCrossDisabledRenderer->getContentSize(); + cocos2d::Size textureSize = _frontCrossDisabledRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _frontCrossDisabledRenderer->setScale(1.0f); @@ -463,4 +472,23 @@ const char* UICheckBox::getDescription() const return "CheckBox"; } +UIWidget* UICheckBox::createCloneInstance() +{ + return UICheckBox::create(); +} + +void UICheckBox::copySpecialProperties(UIWidget *widget) +{ + UICheckBox* checkBox = dynamic_cast(widget); + if (checkBox) + { + loadTextureBackGround(checkBox->_backGroundFileName.c_str(), checkBox->_backGroundTexType); + loadTextureBackGroundSelected(checkBox->_backGroundSelectedFileName.c_str(), checkBox->_backGroundSelectedTexType); + loadTextureFrontCross(checkBox->_frontCrossFileName.c_str(), checkBox->_frontCrossTexType); + loadTextureBackGroundDisabled(checkBox->_backGroundDisabledFileName.c_str(), checkBox->_backGroundDisabledTexType); + loadTextureFrontCrossDisabled(checkBox->_frontCrossDisabledFileName.c_str(), checkBox->_frontCrossDisabledTexType); + setSelectedState(checkBox->_isSelected); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UICheckBox.h b/cocos/gui/UICheckBox.h index 46183f04db..5e9c836617 100644 --- a/cocos/gui/UICheckBox.h +++ b/cocos/gui/UICheckBox.h @@ -35,9 +35,13 @@ typedef enum CHECKBOX_STATE_EVENT_UNSELECTED }CheckBoxEventType; -typedef void (cocos2d::CCObject::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); +typedef void (cocos2d::Object::*SEL_SelectedStateEvent)(cocos2d::Object*,CheckBoxEventType); #define checkboxselectedeventselector(_SELECTOR) (SEL_SelectedStateEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UICheckBox : public UIWidget { public: @@ -156,11 +160,12 @@ public: //override "getVirtualRenderer" method of widget. virtual cocos2d::Node* getVirtualRenderer(); - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool init(); virtual void initRenderer(); @@ -175,6 +180,8 @@ protected: void frontCrossTextureScaleChangedWithSize(); void backGroundDisabledTextureScaleChangedWithSize(); void frontCrossDisabledTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Sprite* _backGroundBoxRenderer; cocos2d::Sprite* _backGroundSelectedBoxRenderer; @@ -191,6 +198,12 @@ protected: TextureResType _frontCrossTexType; TextureResType _backGroundDisabledTexType; TextureResType _frontCrossDisabledTexType; + + std::string _backGroundFileName; + std::string _backGroundSelectedFileName; + std::string _frontCrossFileName; + std::string _backGroundDisabledFileName; + std::string _frontCrossDisabledFileName; }; } diff --git a/cocos/gui/UIDragPanel.cpp b/cocos/gui/UIDragPanel.cpp deleted file mode 100644 index 7c717c0636..0000000000 --- a/cocos/gui/UIDragPanel.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "gui/UIDragPanel.h" -#include "gui/UILayer.h" - - using namespace cocos2d; - -namespace gui { - -UIDragPanel::UIDragPanel() -: _innerContainer(NULL) -, _touchPressed(false) -, _touchMoved(false) -, _touchReleased(false) -, _touchCanceld(false) -, _touchStartNodeSpace(Point::ZERO) -, _touchStartWorldSpace(Point::ZERO) -, _touchEndWorldSpace(Point::ZERO) -, _slidTime(0.0f) -, _moveType(DRAGPANEL_MOVE_TYPE_AUTOMOVE) -, _autoMoveDuration(0.5f) -, _autoMoveEaseRate(2.0f) -, _eventLister(NULL) -, _eventSelector(NULL) -, _berthDirection(DRAGPANEL_BERTH_DIR_NONE) -, _bounceEnable(false) -, _bounceDirection(DRAGPANEL_BOUNCE_DIR_NONE) -, _bounceDuration(0.5f) -, _bounceEaseRate(2.0f) -, _runningAction(false) -, _actionType(0) -, _actionWidget(NULL) -, _duration(0.0f) -, _elapsed(0.0f) -, _firstTick(false) -, _positionDelta(Point::ZERO) -, _startPosition(Point::ZERO) -, _previousPosition(Point::ZERO) -, _endPosition(Point::ZERO) -{ - -} - -UIDragPanel::~UIDragPanel() -{ - -} - -UIDragPanel* UIDragPanel::create() -{ - UIDragPanel* widget = new UIDragPanel(); - if (widget && widget->init()) - { - widget->autorelease(); - return widget; - } - CC_SAFE_DELETE(widget); - return NULL; -} - -bool UIDragPanel::init() -{ - if (Layout::init()) - { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - return true; - } - return false; -} - -void UIDragPanel::initRenderer() -{ - Layout::initRenderer(); - - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); - -} - -void UIDragPanel::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - -bool UIDragPanel::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIDragPanel::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIDragPanel::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIDragPanel::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIDragPanel::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIDragPanel::update(float dt) -{ - // widget action - if (_runningAction) - { - if (actionIsDone()) - { - actionDone(); - actionStop(); - } - else - { - actionStep(dt); - } - } - - recordSlidTime(dt); -} - -bool UIDragPanel::addChild(UIWidget *widget) -{ - _innerContainer->addChild(widget); - return true; -} - -bool UIDragPanel::removeChild(UIWidget *child) -{ - bool value = false; - if (_innerContainer->removeChild(child)) - { - value = true; - } - - return value; -} - -void UIDragPanel::removeAllChildren() -{ - _innerContainer->removeAllChildren(); -} - -Array* UIDragPanel::getChildren() -{ - return _innerContainer->getChildren(); -} - -void UIDragPanel::onSizeChanged() -{ - Layout::onSizeChanged(); - Size innerSize = _innerContainer->getSize(); - float orginInnerSizeWidth = innerSize.width; - float orginInnerSizeHeight = innerSize.height; - float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); - float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); -} - -const Size& UIDragPanel::getInnerContainerSize() const -{ - return _innerContainer->getContentSize(); -} - -void UIDragPanel::setInnerContainerSize(const cocos2d::Size &size) -{ - float innerSizeWidth = _size.width; - float innerSizeHeight = _size.height; - if (size.width < _size.width) - { - CCLOG("Inner width <= scrollview width, it will be force sized!"); - } - else - { - innerSizeWidth = size.width; - } - if (size.height < _size.height) - { - CCLOG("Inner height <= scrollview height, it will be force sized!"); - } - else - { - innerSizeHeight = size.height; - } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); -} - -const Point& UIDragPanel::getInnerContainerPosition() const -{ - return _innerContainer->getPosition(); -} - -void UIDragPanel::setInnerContainerPosition(const Point &point, bool animated) -{ - Point delta = point - _innerContainer->getPosition(); - -// Point delta = ccpSub(point, _innerContainer->getPosition()); - setInnerContainerOffset(delta, animated); -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset, bool animated) -{ - if (animated) - { - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); - } - else - { - setInnerContainerOffset(offset); - } -} - -void UIDragPanel::setInnerContainerOffset(const Point &offset) -{ - Point delta = offset; - - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - moveWithDelta(delta); - if (checkBerth()) - { - berthEvent(); - } -} - - -void UIDragPanel::handlePressLogic(const Point &touchPoint) -{ - // check inner rect < drag panel rect - if (checkContainInnerRect()) - { - _touchPressed = false; - return; - } - - _touchPressed = true; - _touchMoved = false; - _touchReleased = false; - _touchCanceld = false; - - if (_runningAction) - { - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - stopAutoMove(); - actionStop(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - _touchPressed = false; - break; - - default: - break; - } - } - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _touchStartNodeSpace = nsp; - - _touchStartWorldSpace = touchPoint; -} - -void UIDragPanel::handleMoveLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - _touchMoved = true; - - Point nsp = _renderer->convertToNodeSpace(touchPoint); - Point delta = nsp - _touchStartNodeSpace; -// Point delta = ccpSub(nsp, _touchStartNodeSpace); - _touchStartNodeSpace = nsp; - - // reset berth dir to none - if (!_bounceEnable) - { - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } - - // check will berth (bounce disable) - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - // move - moveWithDelta(delta); - // check bounce or berth - if (_bounceEnable) - { - // bounce - if (!hitTest(touchPoint)) - { - _touchMoved = false; - - if (checkNeedBounce()) - { - _touchCanceld = true; - startBounce(); - } - } - } - else - { - // berth - if (checkBerth()) - { - berthEvent(); - } - } -} - -void UIDragPanel::handleReleaseLogic(const Point &touchPoint) -{ - if (!_touchPressed) - { - return; - } - - _touchPressed = false; - _touchMoved = false; - _touchReleased = true; - _touchCanceld = false; - - // check touch out of drag panel boundary - if (_touchCanceld) - { - return; - } - - if (hitTest(touchPoint)) - { - _touchEndWorldSpace = touchPoint; - startAutoMove(); - } -} - -void UIDragPanel::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIDragPanel::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { -// float offset = ccpDistance(sender->getTouchStartPos(), touchPoint); - float offset = sender->getTouchStartPos().getDistance(touchPoint); - if (offset > 5.0) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIDragPanel::recordSlidTime(float dt) -{ - if (_touchPressed) - { - _slidTime += dt; - } -} - -// check if dragpanel rect contain inner rect -bool UIDragPanel::checkContainInnerRect() -{ - float width = _size.width; - float height = _size.height; - float innerWidth = _innerContainer->getSize().width; - float innerHeight = _innerContainer->getSize().height; - - if (innerWidth <= width && innerHeight <= height) - { - return true; - } - - return false; -} - -// move -void UIDragPanel::moveWithDelta(const Point &delta) -{ - Point newPos = _innerContainer->getPosition() + delta; -// Point newPos = ccpAdd(_innerContainer->getPosition(), delta); - _innerContainer->setPosition(newPos); -} - -// auto move -void UIDragPanel::autoMove() -{ - if (_bounceEnable) - { - if (checkNeedBounce()) - { - stopAutoMove(); - startBounce(); - } - } -} - -void UIDragPanel::autoMoveOver() -{ - stopAutoMove(); - - if (checkBerth()) - { - berthEvent(); - _berthDirection = DRAGPANEL_BERTH_DIR_NONE; - } -} - -void UIDragPanel::startAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_AUTOMOVE; - - actionStop(); - - Point delta = _touchEndWorldSpace - _touchStartWorldSpace; -// Point delta = ccpSub(m_touchEndWorldSpace, _touchStartWorldSpace); - delta.x /= _slidTime * 60; - delta.y /= _slidTime * 60; - _slidTime = 0.0; - - // bounceEnable is disable - if (!_bounceEnable) - { - if (checkToBoundaryWithDeltaPosition(delta)) - { - delta = calculateToBoundaryDeltaPosition(delta); - } - } - actionStartWithWidget(_innerContainer); - moveByWithDuration(_autoMoveDuration, delta); -} - -void UIDragPanel::stopAutoMove() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::setAutoMoveDuration(float duration) -{ - _autoMoveDuration = duration; -} - -void UIDragPanel::setAutoMoveEaseRate(float rate) -{ - _autoMoveEaseRate = rate; -} - -// berth - -// check if move to boundary - -bool UIDragPanel::checkToBoundaryWithDeltaPosition(const Point& delta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool toLeftBottom = false; - bool toLeftTop = false; - bool toRightBottom = false; - bool toRightTop = false; - bool toLeft = false; - bool toRight = false; - bool toTop = false; - bool toBottom = false; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - toLeftBottom = true; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - toLeftTop = true; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - toRightBottom = true; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right top - { - toRightTop = true; - } - else if (innerLeft + delta.x > left) // left - { - toLeft = true; - } - else if (innerRight + delta.x < right) // right - { - toRight = true; - } - else if (innerTop + delta.y < top) // top - { - toTop = true; - } - else if (innerBottom + delta.y > bottom) // bottom - { - toBottom = true; - } - - if (toLeft || toTop || toRight || toBottom - || toLeftBottom || toLeftTop || toRightBottom || toRightTop) - { - return true; - } - - return false; -} - -Point UIDragPanel::calculateToBoundaryDeltaPosition(const Point& paramDelta) -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - Point delta = paramDelta; - - if (innerLeft + delta.x > left && innerBottom + delta.y > bottom) // left bottom - { - delta.x = left - innerLeft; - delta.y = bottom - innerBottom; - } - else if (innerLeft + delta.x > left && innerTop + delta.y < top) // left top - { - delta.x = left - innerLeft; - delta.y = top - innerTop; - } - else if (innerRight + delta.x < right && innerBottom + delta.y > bottom) // right bottom - { - delta.x = right - innerRight; - delta.y = bottom - innerBottom; - } - else if (innerRight + delta.x < right && innerTop + delta.y < top) // right bottom - { - delta.x = right - innerRight; - delta.y = top - innerTop; - } - else if (innerLeft + delta.x > left) // left - { - delta.x = left - innerLeft; - } - else if (innerRight + delta.x < right) // right - { - delta.x = right - innerRight; - } - else if (innerTop + delta.y < top) // top - { - delta.y = top - innerTop; - } - else if (innerBottom + delta.y > bottom) // bottom - { - delta.y = bottom - innerBottom; - } - - return delta; -} - -bool UIDragPanel::isBerth() -{ - return _berthDirection != DRAGPANEL_BERTH_DIR_NONE; -} - -// check berth -bool UIDragPanel::checkBerth() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - if (innerLeft == left && innerBottom == bottom) // left bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFTBOTTOM; - } - else if (innerLeft == left && innerTop == top) // left top - { - _berthDirection = DRAGPANEL_BERTH_DIR_LFETTOP; - } - else if (innerRight == right && innerBottom == bottom) // right bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTBOTTOM; - } - else if (innerRight == right && innerTop == top) // right top - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHTTOP; - } - else if (innerLeft == left) // left - { - _berthDirection = DRAGPANEL_BERTH_DIR_LEFT; - } - else if (innerRight == right) // right - { - _berthDirection = DRAGPANEL_BERTH_DIR_RIGHT; - } - else if (innerTop == top) // top - { - _berthDirection = DRAGPANEL_BERTH_DIR_TOP; - } - else if (innerBottom == bottom) // bottom - { - _berthDirection = DRAGPANEL_BERTH_DIR_BOTTOM; - } - - if (_berthDirection != DRAGPANEL_BERTH_DIR_NONE) - { - return true; - } - - return false; -} - -void UIDragPanel::berthEvent() -{ - switch (_berthDirection) - { - case DRAGPANEL_BERTH_DIR_LEFTBOTTOM: - berthToLeftBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LFETTOP: - berthToLeftTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTBOTTOM: - berthToRightBottomEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHTTOP: - berthToRightTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_LEFT: - berthToLeftEvent(); - break; - - case DRAGPANEL_BERTH_DIR_TOP: - berthToTopEvent(); - break; - - case DRAGPANEL_BERTH_DIR_RIGHT: - berthToRightEvent(); - break; - - case DRAGPANEL_BERTH_DIR_BOTTOM: - berthToBottomEvent(); - break; - - default: - break; - } -} - -void UIDragPanel::berthToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFTBOTTOM); - } -} - -void UIDragPanel::berthToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LFETTOP); - } -} - -void UIDragPanel::berthToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM); - } -} - -void UIDragPanel::berthToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHTTOP); - } -} - -void UIDragPanel::berthToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_LEFT); - } -} - -void UIDragPanel::berthToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_TOP); - } -} - -void UIDragPanel::berthToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_RIGHT); - } -} - -void UIDragPanel::berthToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BERTH_BOTTOM); - } -} - -void UIDragPanel::addEventListener(Object *target, SEL_DragPanelEvent selector) -{ - _eventLister = target; - _eventSelector = selector; -} - -// bounce -bool UIDragPanel::isBounceEnable() -{ - return _bounceEnable; -} - -void UIDragPanel::setBounceEnable(bool bounce) -{ - _bounceEnable = bounce; -} - -bool UIDragPanel::checkNeedBounce() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float left = 0; - float top = _size.height; - float right = _size.width; - float bottom = 0; - - bool need = ((innerLeft > left && innerBottom > bottom) - || (innerLeft > left && innerTop < top) - || (innerRight < right && innerBottom > bottom) - || (innerRight < right && innerTop < top) - || (innerLeft > left) - || (innerTop < top) - || (innerRight < right) - || (innerBottom > bottom)); - return need; -} - -void UIDragPanel::startBounce() -{ - if (_moveType == DRAGPANEL_MOVE_TYPE_BOUNCE) - { - return; - } - - actionStop(); - _moveType = DRAGPANEL_MOVE_TYPE_BOUNCE; - bounceToCorner(); -} - -void UIDragPanel::stopBounce() -{ - _moveType = DRAGPANEL_MOVE_TYPE_NONE; -} - -void UIDragPanel::bounceToCorner() -{ - float innerLeft = _innerContainer->getLeftInParent(); - float innerTop = _innerContainer->getTopInParent(); - float innerRight = _innerContainer->getRightInParent(); - float innerBottom = _innerContainer->getBottomInParent(); - - float width = _size.width; - float height = _size.height; - float left = 0; - float top = height; - float right = width; - float bottom = 0; - - float from_x = 0; - float from_y = 0; - float to_x = 0; - float to_y = 0; - Point delta = Point::ZERO; - - if (innerLeft > left && innerBottom > bottom) // left bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM; - } - else if (innerLeft > left && innerTop < top) // left top - { - from_x = innerLeft; - from_y = innerTop; - to_x = left; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFTTOP; - } - else if (innerRight < right && innerBottom > bottom) // right bottom - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM; - } - else if (innerRight < right && innerTop < top) // right top - { - from_x = innerRight; - from_y = innerTop; - to_x = right; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHTTOP; - } - else if (innerLeft > left) // left - { - from_x = innerLeft; - from_y = innerBottom; - to_x = left; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_LEFT; - } - else if (innerTop < top) // top - { - from_x = innerLeft; - from_y = innerTop; - to_x = from_x; - to_y = top; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_TOP; - } - else if (innerRight < right) // right - { - from_x = innerRight; - from_y = innerBottom; - to_x = right; - to_y = from_y; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_RIGHT; - } - else if (innerBottom > bottom) // bottom - { - from_x = innerLeft; - from_y = innerBottom; - to_x = from_x; - to_y = bottom; - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_BOTTOM; - } - delta = Point(to_x, to_y) - Point(from_x, from_y); -// delta = ccpSub(ccp(to_x, to_y), ccp(from_x, from_y)); - - actionStartWithWidget(_innerContainer); - moveByWithDuration(_bounceDuration, delta); -} - -void UIDragPanel::bounceOver() -{ - stopBounce(); - - switch (_bounceDirection) - { - case DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM: - bounceToLeftBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFTTOP: - bounceToLeftTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM: - bounceToRightBottomEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHTTOP: - bounceToRightTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_LEFT: - bounceToLeftEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_TOP: - bounceToTopEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_RIGHT: - bounceToRightEvent(); - break; - - case DRAGPANEL_BOUNCE_DIR_BOTTOM: - bounceToBottomEvent(); - break; - - default: - break; - } - - _bounceDirection = DRAGPANEL_BOUNCE_DIR_NONE; -} - -void UIDragPanel::bounceToLeftBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM); - } -} - -void UIDragPanel::bounceToLeftTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFTTOP); - } -} - -void UIDragPanel::bounceToRightBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM); - } -} - -void UIDragPanel::bounceToRightTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHTTOP); - } -} - -void UIDragPanel::bounceToLeftEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_LEFT); - } -} - -void UIDragPanel::bounceToTopEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_TOP); - } -} - -void UIDragPanel::bounceToRightEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_RIGHT); - } -} - -void UIDragPanel::bounceToBottomEvent() -{ - if (_eventLister && _eventSelector) - { - (_eventLister->*_eventSelector)(this, DRAGPANEL_EVENT_BOUNCE_BOTTOM); - } -} - -// widget action -void UIDragPanel::actionWithDuration(float duration) -{ - _duration = duration; - - if (_duration == 0) - { - _duration = FLT_EPSILON; - } - - _elapsed = 0; - _firstTick = true; -} - -bool UIDragPanel::actionIsDone() -{ - bool value = (_elapsed >= _duration); - return value; -} - -void UIDragPanel::actionStartWithWidget(UIWidget *widget) -{ - _runningAction = true; - _actionWidget = widget; -} - -void UIDragPanel::actionStep(float dt) -{ - if (_firstTick) - { - _firstTick = false; - _elapsed = 0; - } - else - { - _elapsed += dt; - } - - actionUpdate(MAX (0, - MIN(1, _elapsed / - MAX(_duration, FLT_EPSILON) - ) - ) - ); -} - -void UIDragPanel::actionUpdate(float dt) -{ - switch (_actionType) - { - case 1: // move by - moveByUpdate(dt); - break; - - case 2: // move to - moveToUpdate(dt); - break; - - default: - break; - } -} - -void UIDragPanel::actionStop() -{ - _runningAction = false; -} - -void UIDragPanel::actionDone() -{ - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMoveOver(); - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - bounceOver(); - break; - - default: - break; - } -} - -// move by -void UIDragPanel::moveByWithDuration(float duration, const Point& deltaPosition) -{ - actionWithDuration(duration); - _positionDelta = deltaPosition; - moveByInit(); - _actionType = 1; -} - -void UIDragPanel::moveByInit() -{ - _previousPosition = _startPosition = _actionWidget->getPosition(); -} - -void UIDragPanel::moveByUpdate(float t) -{ - float easeRate = 0.0f; - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - easeRate = _autoMoveEaseRate; - break; - - case DRAGPANEL_MOVE_TYPE_BOUNCE: - easeRate = _bounceEaseRate; - break; - - default: - break; - } - t = powf(t, 1 / easeRate); - - Point currentPos = _actionWidget->getPosition(); - Point diff = currentPos - _previousPosition; - _startPosition = _startPosition + diff; -// Point diff = ccpSub(currentPos, _previousPosition); -// _startPosition = ccpAdd( _startPosition, diff); - -// Point newPos = ccpAdd( _startPosition, ccpMult(_positionDelta, t) ); - Point newPos = _startPosition + (_positionDelta * t); - - _actionWidget->setPosition(newPos); - _previousPosition = newPos; - - switch (_moveType) - { - case DRAGPANEL_MOVE_TYPE_AUTOMOVE: - autoMove(); - break; - - default: - break; - } -} - -// move to -void UIDragPanel::moveToWithDuration(float duration, const Point& position) -{ - actionWithDuration(duration); - _endPosition = position; - moveToInit(); - _actionType = 2; -} - -void UIDragPanel::moveToInit() -{ - moveByInit(); - _positionDelta = _endPosition - _actionWidget->getPosition(); -// _positionDelta = ccpSub( _endPosition, _actionWidget->getPosition() ); -} - -void UIDragPanel::moveToUpdate(float t) -{ - moveByUpdate(t); -} - -Layout* UIDragPanel::getInnerContainer() -{ - return _innerContainer; -} - -void UIDragPanel::setLayoutType(LayoutType type) -{ - _innerContainer->setLayoutType(type); -} - -LayoutType UIDragPanel::getLayoutType() const -{ - return _innerContainer->getLayoutType(); -} - -void UIDragPanel::doLayout() -{ - _innerContainer->doLayout(); -} - -const char* UIDragPanel::getDescription() const -{ - return "DragPanel"; -} - -} \ No newline at end of file diff --git a/cocos/gui/UIDragPanel.h b/cocos/gui/UIDragPanel.h deleted file mode 100644 index d6b4f0b62c..0000000000 --- a/cocos/gui/UIDragPanel.h +++ /dev/null @@ -1,367 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __UIDRAGPANEL_H__ -#define __UIDRAGPANEL_H__ - -#include "gui/Layout.h" -#include "gui/UIScrollInterface.h" - -namespace gui { - -/** - * drag panel move type - */ -enum DRAGPANEL_MOVE_TYPE -{ - DRAGPANEL_MOVE_TYPE_NONE, - DRAGPANEL_MOVE_TYPE_AUTOMOVE, - DRAGPANEL_MOVE_TYPE_BOUNCE, -}; - -/** - * dragpanel berth direction - */ -enum DRAGPANEL_BERTH_DIR -{ - DRAGPANEL_BERTH_DIR_NONE, - DRAGPANEL_BERTH_DIR_LEFTBOTTOM, - DRAGPANEL_BERTH_DIR_LFETTOP, - DRAGPANEL_BERTH_DIR_RIGHTBOTTOM, - DRAGPANEL_BERTH_DIR_RIGHTTOP, - DRAGPANEL_BERTH_DIR_LEFT, - DRAGPANEL_BERTH_DIR_TOP, - DRAGPANEL_BERTH_DIR_RIGHT, - DRAGPANEL_BERTH_DIR_BOTTOM, -}; - -/** - * dragpanel bounce direction - */ -enum DRAGPANEL_BOUNCE_DIR -{ - DRAGPANEL_BOUNCE_DIR_NONE, - DRAGPANEL_BOUNCE_DIR_LEFTBOTTOM, - DRAGPANEL_BOUNCE_DIR_LEFTTOP, - DRAGPANEL_BOUNCE_DIR_RIGHTBOTTOM, - DRAGPANEL_BOUNCE_DIR_RIGHTTOP, - DRAGPANEL_BOUNCE_DIR_LEFT, - DRAGPANEL_BOUNCE_DIR_TOP, - DRAGPANEL_BOUNCE_DIR_RIGHT, - DRAGPANEL_BOUNCE_DIR_BOTTOM, -}; - -typedef enum -{ - DRAGPANEL_EVENT_BERTH_LEFTBOTTOM, - DRAGPANEL_EVENT_BERTH_LFETTOP, - DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM, - DRAGPANEL_EVENT_BERTH_RIGHTTOP, - DRAGPANEL_EVENT_BERTH_LEFT, - DRAGPANEL_EVENT_BERTH_TOP, - DRAGPANEL_EVENT_BERTH_RIGHT, - DRAGPANEL_EVENT_BERTH_BOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_LEFTTOP, - DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM, - DRAGPANEL_EVENT_BOUNCE_RIGHTTOP, - DRAGPANEL_EVENT_BOUNCE_LEFT, - DRAGPANEL_EVENT_BOUNCE_TOP, - DRAGPANEL_EVENT_BOUNCE_RIGHT, - DRAGPANEL_EVENT_BOUNCE_BOTTOM, -}DragPanelEventType; - -/** - * dragpanel event - */ -typedef void (cocos2d::Object::*SEL_DragPanelEvent)(cocos2d::Object*, DragPanelEventType); -#define dragpaneleventselector(_SELECTOR)(SEL_DragPanelEvent)(&_SELECTOR) - -class UIDragPanel : public Layout, public UIScrollInterface -{ -public: - UIDragPanel(); - virtual ~UIDragPanel(); - - static UIDragPanel* create(); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); - - virtual void update(float dt); - - /** - * add widget child override - */ - virtual bool addChild(UIWidget* widget); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * get widget children of inner container - */ - virtual cocos2d::Array* getChildren(); - /* gui mark */ - /** - * get and set inner container size - */ - const cocos2d::Size& getInnerContainerSize() const; - void setInnerContainerSize(const cocos2d::Size &size); - /** - * get and set inner container position - */ - const cocos2d::Point& getInnerContainerPosition() const; - void setInnerContainerPosition(const cocos2d::Point& point, bool animated); - /** - * set inner container offset - */ - void setInnerContainerOffset(const cocos2d::Point& offset, bool animated); - /**/ - - // auto move - /** - * set auto move duration - */ - void setAutoMoveDuration(float duration); - /** - * set auto move ease rate - */ - void setAutoMoveEaseRate(float rate); - - // berth - /** - * get berth or not - */ - bool isBerth(); - - /** - * event - */ - void addEventListener(cocos2d::Object* target, SEL_DragPanelEvent selector); - - /** - * get and set bounce enable - */ - bool isBounceEnable(); - void setBounceEnable(bool bounce); - /** - * set bounce duration - */ - void setBounceDuratoin(float duration); - /** - * set bounce ease rate - */ - void setBounceEaseRate(float rate); - - /** - * Gets inner container of dragpanel. - * - * Inner container is the container of dragpanel's children. - * - * @return inner container. - */ - Layout* getInnerContainer(); - - /** - * Sets LayoutType. - * - * @see LayoutType - * - * @param LayoutType - */ - virtual void setLayoutType(LayoutType type); - - /** - * Gets LayoutType. - * - * @see LayoutType - * - * @return LayoutType - */ - virtual LayoutType getLayoutType() const; - - virtual void doLayout(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; - -protected: - virtual bool init(); - virtual void initRenderer(); - virtual void releaseResoures(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint); -// void updateWidthAndHeight(); - void recordSlidTime(float dt); - - /* gui mark */ - void setInnerContainerOffset(const cocos2d::Point& offset); - /**/ - - // check if dragpanel rect contain inner rect - bool checkContainInnerRect(); - - // move - void moveWithDelta(const cocos2d::Point& delta); - - // auto move - void autoMove(); - void autoMoveOver(); - void startAutoMove(); - void stopAutoMove(); - - // berth - // check if move to boundary with update - bool checkToBoundaryWithDeltaPosition(const cocos2d::Point& delta); - - // calculate to boundary delta - cocos2d::Point calculateToBoundaryDeltaPosition(const cocos2d::Point& paramDelta); - - // check berth - bool checkBerth(); - - // berth event - void berthEvent(); - void berthToLeftEvent(); - void berthToRightEvent(); - void berthToTopEvent(); - void berthToBottomEvent(); - void berthToLeftBottomEvent(); - void berthToLeftTopEvent(); - void berthToRightBottomEvent(); - void berthToRightTopEvent(); - - // bounce - bool checkNeedBounce(); - void startBounce(); - void stopBounce(); - void bounceToCorner(); - void bounceOver(); - // bounce event - void bounceToLeftBottomEvent(); - void bounceToRightBottomEvent(); - void bounceToLeftTopEvent(); - void bounceToRightTopEvent(); - void bounceToLeftEvent(); - void bounceToTopEvent(); - void bounceToRightEvent(); - void bounceToBottomEvent(); - - void actionWithDuration(float duration); - bool actionIsDone(); - void actionStartWithWidget(UIWidget* widget); - void actionStep(float dt); - void actionUpdate(float dt); - void actionStop(); - void actionDone(); - void moveByWithDuration(float duration, const cocos2d::Point& deltaPosition); - void moveByInit(); - void moveByUpdate(float t); - void moveToWithDuration(float duration, const cocos2d::Point& position); - void moveToInit(); - void moveToUpdate(float t); - virtual void onSizeChanged(); - /*compatible*/ - /** - * These methods will be removed - */ - virtual void setClippingEnable(bool is){setClippingEnabled(is);}; - /************/ - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; -protected: - Layout* _innerContainer; - - /* - DRAGPANEL_DIR m_eDirection; - DRAGPANEL_MOVE_DIR m_eMoveDirection; - */ - - bool _touchPressed; - bool _touchMoved; - bool _touchReleased; - bool _touchCanceld; // check touch out of drag panel boundary - - cocos2d::Point _touchStartNodeSpace; - cocos2d::Point _touchStartWorldSpace; - cocos2d::Point _touchEndWorldSpace; - - float _slidTime; - - // move type - DRAGPANEL_MOVE_TYPE _moveType; - - // auto move - float _autoMoveDuration; - float _autoMoveEaseRate; - - // event - cocos2d::Object* _eventLister; - SEL_DragPanelEvent _eventSelector; - - // berth - DRAGPANEL_BERTH_DIR _berthDirection; - - // bounce - bool _bounceEnable; - DRAGPANEL_BOUNCE_DIR _bounceDirection; - float _bounceDuration; - float _bounceEaseRate; - - - float _runningAction; - int _actionType; - - UIWidget* _actionWidget; - - float _duration; - float _elapsed; - bool _firstTick; - - cocos2d::Point _positionDelta; - cocos2d::Point _startPosition; - cocos2d::Point _previousPosition; - - cocos2d::Point _endPosition; -}; - -} - -#endif /* defined(__TestCpp__UIDragPanel__) */ diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index 409d0f4461..d896a6372c 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -22,111 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/UIHelper.h" -#include "cocos2d.h" -#include "cocostudio/DictionaryHelper.h" -#include "cocostudio/CCSGUIReader.h" - - -using namespace cocos2d; -using namespace cocostudio; +#include "CocosGUI.h" namespace gui { - -static UIHelper* helperInstance = NULL; - -UIHelper* UIHelper::instance() -{ - if (!helperInstance) - { - helperInstance = new UIHelper(); - } - return helperInstance; -} - -void UIHelper::purgeUIHelper() -{ - CC_SAFE_DELETE(helperInstance); -} - -UIHelper::UIHelper(): -_textureFiles(NULL), -_fileDesignHeight(0.0f), -_fileDesignWidth(0.0f) -{ - Size winSize = Director::getInstance()->getWinSize(); - _fileDesignWidth = winSize.width; - _fileDesignHeight = winSize.height; - init(); -} - -UIHelper::~UIHelper() -{ - cocostudio::CCSGUIReader::purgeCCSGUIReader(); -} - -void UIHelper::init() -{ - _textureFiles = CCArray::create(); - _textureFiles->retain(); -} - -UIWidget* UIHelper::createWidgetFromJsonFile(const char *fileName) -{ - return CCSGUIReader::shareReader()->widgetFromJsonFile(fileName); -} - -void UIHelper::addSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - return; - } - } - _textureFiles->addObject(CCString::create(fileName)); - SpriteFrameCache::getInstance()->addSpriteFramesWithFile(fileName); -} - -void UIHelper::removeSpriteFrame(const char *fileName) -{ - if (!fileName || strcmp(fileName, "") == 0) - { - return; - } - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - if (strcmp(file->_string.c_str(), fileName) == 0) - { - SpriteFrameCache::getInstance()->removeSpriteFrameByName(fileName); - _textureFiles->removeObject(file); - return; - } - } -} - -void UIHelper::removeAllSpriteFrame() -{ - ccArray* arrayTextures = _textureFiles->data; - int length = arrayTextures->num; - for (int i=0;iarr[i]); - SpriteFrameCache::getInstance()->removeSpriteFrameByName(file->_string.c_str()); - } - _textureFiles->removeAllObjects(); -} UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -138,7 +36,7 @@ UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;igetChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;iarr[i]); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter()); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) { return child; @@ -196,26 +94,6 @@ UIWidget* UIHelper::seekWidgetByRelativeName(UIWidget *root, const char *name) return NULL; } -void UIHelper::setFileDesignWidth(float width) -{ - _fileDesignWidth = width; -} - -float UIHelper::getFileDesignWidth() -{ - return _fileDesignWidth; -} - -void UIHelper::setFileDesignHeight(float height) -{ - _fileDesignHeight = height; -} - -float UIHelper::getFileDesignHeight() -{ - return _fileDesignHeight; -} - /*temp action*/ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { @@ -227,7 +105,7 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) { return root; } - ccArray* arrayRootChildren = root->getChildren()->data; + cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; int length = arrayRootChildren->num; for (int i=0;i(_imageRenderer) #define DYNAMIC_CAST_SCALE9SPRITE dynamic_cast(_imageRenderer) @@ -41,7 +39,7 @@ _touchRelease(false), _doubleClickEnabled(false), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _imageRenderer(NULL), _textureFile(""), _imageTexType(UI_TEX_TYPE_LOCAL), @@ -70,7 +68,7 @@ UIImageView* UIImageView::create() void UIImageView::initRenderer() { UIWidget::initRenderer(); - _imageRenderer = Sprite::create(); + _imageRenderer = cocos2d::Sprite::create(); _renderer->addChild(_imageRenderer); } @@ -90,6 +88,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithFile(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -104,6 +103,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) DYNAMIC_CAST_SCALE9SPRITE->initWithSpriteFrameName(fileName); DYNAMIC_CAST_SCALE9SPRITE->setColor(getColor()); DYNAMIC_CAST_SCALE9SPRITE->setOpacity(getOpacity()); + DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(_capInsets); } else { @@ -120,7 +120,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) imageTextureScaleChangedWithSize(); } -void UIImageView::setTextureRect(const Rect &rect) +void UIImageView::setTextureRect(const cocos2d::Rect &rect) { if (_scale9Enabled) { @@ -131,7 +131,7 @@ void UIImageView::setTextureRect(const Rect &rect) } } -bool UIImageView::onTouchBegan(const Point &touchPoint) +bool UIImageView::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -149,7 +149,7 @@ bool UIImageView::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIImageView::onTouchEnded(const Point &touchPoint) +void UIImageView::onTouchEnded(const cocos2d::Point &touchPoint) { if (_doubleClickEnabled) { @@ -278,11 +278,11 @@ void UIImageView::setScale9Enabled(bool able) _imageRenderer = NULL; if (_scale9Enabled) { - _imageRenderer = extension::Scale9Sprite::create(); + _imageRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _imageRenderer = CCSprite::create(); + _imageRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_imageTexType); _renderer->addChild(_imageRenderer); @@ -308,7 +308,7 @@ void UIImageView::ignoreContentAdaptWithSize(bool ignore) } } -void UIImageView::setCapInsets(const Rect &capInsets) +void UIImageView::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) @@ -318,7 +318,7 @@ void UIImageView::setCapInsets(const Rect &capInsets) DYNAMIC_CAST_SCALE9SPRITE->setCapInsets(capInsets); } -void UIImageView::setAnchorPoint(const Point &pt) +void UIImageView::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _imageRenderer->setAnchorPoint(pt); @@ -329,12 +329,12 @@ void UIImageView::onSizeChanged() imageTextureScaleChangedWithSize(); } -const Size& UIImageView::getContentSize() const +const cocos2d::Size& UIImageView::getContentSize() const { return _imageTextureSize; } -Node* UIImageView::getVirtualRenderer() +cocos2d::Node* UIImageView::getVirtualRenderer() { return _imageRenderer; } @@ -353,11 +353,11 @@ void UIImageView::imageTextureScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_imageRenderer)->setPreferredSize(_size); + dynamic_cast(_imageRenderer)->setPreferredSize(_size); } else { - Size textureSize = _imageRenderer->getContentSize(); + cocos2d::Size textureSize = _imageRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _imageRenderer->setScale(1.0f); @@ -376,4 +376,21 @@ const char* UIImageView::getDescription() const return "ImageView"; } +UIWidget* UIImageView::createCloneInstance() +{ + return UIImageView::create(); +} + +void UIImageView::copySpecialProperties(UIWidget *widget) +{ + UIImageView* imageView = dynamic_cast(widget); + if (imageView) + { + _prevIgnoreSize = imageView->_prevIgnoreSize; + setScale9Enabled(imageView->_scale9Enabled); + loadTexture(imageView->_textureFile.c_str(), imageView->_imageTexType); + setCapInsets(imageView->_capInsets); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIImageView.h b/cocos/gui/UIImageView.h index 91bd2573ec..16103aa256 100644 --- a/cocos/gui/UIImageView.h +++ b/cocos/gui/UIImageView.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UIImageView : public UIWidget { public: @@ -100,22 +104,22 @@ public: //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore); - + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; void setDoubleClickEnabled(bool able); void doubleClickEvent(); void checkDoubleClick(float dt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - - /** - * Returns the "class name" of widget. - */ - virtual const char* getDescription() const; protected: virtual void initRenderer(); virtual void onSizeChanged(); void imageTextureScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: int _clickCount; float _clickTimeInterval; diff --git a/cocos/gui/UIInputManager.cpp b/cocos/gui/UIInputManager.cpp index 0fe2eb153e..bb36043855 100644 --- a/cocos/gui/UIInputManager.cpp +++ b/cocos/gui/UIInputManager.cpp @@ -37,11 +37,11 @@ _longClickRecordTime(0.0), _checkedDoubleClickWidget(NULL), _rootWidget(NULL) { - _manageredWidget = CCArray::create(); + _manageredWidget = Array::create(); _manageredWidget->retain(); - _checkedDoubleClickWidget = CCArray::create(); + _checkedDoubleClickWidget = Array::create(); _checkedDoubleClickWidget->retain(); - _selectedWidgets = CCArray::create(); + _selectedWidgets = Array::create(); _selectedWidgets->retain(); } diff --git a/cocos/gui/UIInputManager.h b/cocos/gui/UIInputManager.h index 9547b091a1..ed5a931f89 100644 --- a/cocos/gui/UIInputManager.h +++ b/cocos/gui/UIInputManager.h @@ -26,7 +26,7 @@ #define __UIINPUTMANAGER_H__ #include "cocos2d.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { @@ -41,7 +41,7 @@ public: /** * Default destructor */ - ~UIInputManager(); + virtual ~UIInputManager(); /** * Regist a widget to input manager. diff --git a/cocos/gui/UILabel.cpp b/cocos/gui/UILabel.cpp index 6ac5d68fdf..4c8779c9eb 100644 --- a/cocos/gui/UILabel.cpp +++ b/cocos/gui/UILabel.cpp @@ -24,10 +24,9 @@ #include "gui/UILabel.h" - using namespace cocos2d; - namespace gui { + UILabel::UILabel(): _touchScaleChangeEnabled(false), _normalScaleValue(1.0f), @@ -67,7 +66,7 @@ bool UILabel::init() void UILabel::initRenderer() { UIWidget::initRenderer(); - _labelRenderer = CCLabelTTF::create(); + _labelRenderer = cocos2d::LabelTTF::create(); _renderer->addChild(_labelRenderer); } @@ -95,29 +94,31 @@ int UILabel::getStringLength() void UILabel::setFontSize(int size) { + _fontSize = size; _labelRenderer->setFontSize(size); labelScaleChangedWithSize(); } void UILabel::setFontName(const char* name) { + _fontName = name; _labelRenderer->setFontName(name); labelScaleChangedWithSize(); } -void UILabel::setTextAreaSize(const Size &size) +void UILabel::setTextAreaSize(const cocos2d::Size &size) { _labelRenderer->setDimensions(size); labelScaleChangedWithSize(); } -void UILabel::setTextHorizontalAlignment(TextHAlignment alignment) +void UILabel::setTextHorizontalAlignment(cocos2d::TextHAlignment alignment) { _labelRenderer->setHorizontalAlignment(alignment); labelScaleChangedWithSize(); } -void UILabel::setTextVerticalAlignment(TextVAlignment alignment) +void UILabel::setTextVerticalAlignment(cocos2d::TextVAlignment alignment) { _labelRenderer->setVerticalAlignment(alignment); labelScaleChangedWithSize(); @@ -182,7 +183,7 @@ bool UILabel::isFlipY() return _labelRenderer->isFlippedY(); } -void UILabel::setAnchorPoint(const Point &pt) +void UILabel::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelRenderer->setAnchorPoint(pt); @@ -193,12 +194,12 @@ void UILabel::onSizeChanged() labelScaleChangedWithSize(); } -const Size& UILabel::getContentSize() const +const cocos2d::Size& UILabel::getContentSize() const { return _labelRenderer->getContentSize(); } -Node* UILabel::getVirtualRenderer() +cocos2d::Node* UILabel::getVirtualRenderer() { return _labelRenderer; } @@ -212,7 +213,7 @@ void UILabel::labelScaleChangedWithSize() } else { - Size textureSize = _labelRenderer->getContentSize(); + cocos2d::Size textureSize = _labelRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelRenderer->setScale(1.0f); @@ -223,6 +224,7 @@ void UILabel::labelScaleChangedWithSize() _labelRenderer->setScaleX(scaleX); _labelRenderer->setScaleY(scaleY); } + } const char* UILabel::getDescription() const @@ -230,4 +232,21 @@ const char* UILabel::getDescription() const return "Label"; } +UIWidget* UILabel::createCloneInstance() +{ + return UILabel::create(); +} + +void UILabel::copySpecialProperties(UIWidget *widget) +{ + UILabel* label = dynamic_cast(widget); + if (label) + { + setFontName(label->_fontName.c_str()); + setFontSize(label->_labelRenderer->getFontSize()); + setText(label->getStringValue()); + setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabel.h b/cocos/gui/UILabel.h index 0d9150f17d..5c6a4a105b 100644 --- a/cocos/gui/UILabel.h +++ b/cocos/gui/UILabel.h @@ -27,8 +27,13 @@ #include "gui/UIWidget.h" + namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabel : public UIWidget { public: @@ -124,11 +129,7 @@ public: void setTextAreaSize(const cocos2d::Size &size); void setTextHorizontalAlignment(cocos2d::TextHAlignment alignment); - void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); - - - void setTouchScaleChangeAble(bool able){setTouchScaleChangeEnabled(able);}; - bool getTouchScaleChangeAble(){return isTouchScaleChangeEnabled();}; + void setTextVerticalAlignment(cocos2d::TextVAlignment alignment); protected: virtual bool init(); virtual void initRenderer(); @@ -138,6 +139,8 @@ protected: virtual void onSizeChanged(); void clickScale(float scale); void labelScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: bool _touchScaleChangeEnabled; float _normalScaleValue; diff --git a/cocos/gui/UILabelAtlas.cpp b/cocos/gui/UILabelAtlas.cpp index 72b816e4a6..8e8db6c422 100644 --- a/cocos/gui/UILabelAtlas.cpp +++ b/cocos/gui/UILabelAtlas.cpp @@ -24,10 +24,9 @@ #include "gui/UILabelAtlas.h" - using namespace cocos2d; - namespace gui { + UICCLabelAtlas::UICCLabelAtlas() { @@ -56,7 +55,7 @@ void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, un initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); } -void UICCLabelAtlas::setProperty(const char *string, Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, texture, itemWidth, itemHeight, startCharMap); } @@ -68,20 +67,26 @@ void UICCLabelAtlas::draw() return; } - CCAtlasNode::draw(); + cocos2d::AtlasNode::draw(); } void UICCLabelAtlas::updateDisplayedOpacity(GLubyte opacity) { - CCAtlasNode::setOpacity(opacity); + cocos2d::AtlasNode::setOpacity(opacity); } UILabelAtlas::UILabelAtlas(): -_laberAtlasRenderer(NULL) +_laberAtlasRenderer(NULL), +_stringValue(""), +_charMapFileName(""), +_itemWidth(0), +_itemHeight(0), +_startCharMap("") { + } UILabelAtlas::~UILabelAtlas() @@ -108,8 +113,13 @@ void UILabelAtlas::initRenderer() _renderer->addChild(_laberAtlasRenderer); } -void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap,bool useSpriteFrame) +void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap) { + _stringValue = stringValue; + _charMapFileName = charMapFile; + _itemWidth = itemWidth; + _itemHeight = itemHeight; + _startCharMap = startCharMap; _laberAtlasRenderer->setProperty(stringValue, charMapFile, itemWidth, itemHeight, (int)(startCharMap[0])); updateAnchorPoint(); labelAtlasScaleChangedWithSize(); @@ -117,6 +127,7 @@ void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, void UILabelAtlas::setStringValue(const char *value) { + _stringValue = value; _laberAtlasRenderer->setString(value); labelAtlasScaleChangedWithSize(); } @@ -126,10 +137,10 @@ const char* UILabelAtlas::getStringValue() return _laberAtlasRenderer->getString(); } -void UILabelAtlas::setAnchorPoint(const Point &pt) +void UILabelAtlas::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); - _laberAtlasRenderer->setAnchorPoint(Point(pt.x, pt.y)); + _laberAtlasRenderer->setAnchorPoint(cocos2d::Point(pt.x, pt.y)); } void UILabelAtlas::onSizeChanged() @@ -137,12 +148,12 @@ void UILabelAtlas::onSizeChanged() labelAtlasScaleChangedWithSize(); } -const Size& UILabelAtlas::getContentSize() const +const cocos2d::Size& UILabelAtlas::getContentSize() const { return _laberAtlasRenderer->getContentSize(); } -Node* UILabelAtlas::getVirtualRenderer() +cocos2d::Node* UILabelAtlas::getVirtualRenderer() { return _laberAtlasRenderer; } @@ -156,7 +167,7 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() } else { - Size textureSize = _laberAtlasRenderer->getContentSize(); + cocos2d::Size textureSize = _laberAtlasRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _laberAtlasRenderer->setScale(1.0f); @@ -171,7 +182,21 @@ void UILabelAtlas::labelAtlasScaleChangedWithSize() const char* UILabelAtlas::getDescription() const { - return "LabelAtlase"; + return "LabelAtlas"; } +UIWidget* UILabelAtlas::createCloneInstance() +{ + return UILabelAtlas::create(); +} + +void UILabelAtlas::copySpecialProperties(UIWidget *widget) +{ + UILabelAtlas* labelAtlas = dynamic_cast(widget); + if (labelAtlas) + { + setProperty(labelAtlas->_stringValue.c_str(), labelAtlas->_charMapFileName.c_str(), labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap.c_str()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILabelAtlas.h b/cocos/gui/UILabelAtlas.h index b74ea87644..73b902633f 100644 --- a/cocos/gui/UILabelAtlas.h +++ b/cocos/gui/UILabelAtlas.h @@ -29,6 +29,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCLabelAtlas : public cocos2d::LabelAtlas { public: @@ -51,7 +55,10 @@ public: virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; - +/** + * @js NA + * @lua NA + */ class UILabelAtlas : public UIWidget { public: @@ -71,7 +78,7 @@ public: static UILabelAtlas* create(); /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap,bool useSpriteFrame = false); + void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap); //set string value for labelatlas. void setStringValue(const char* value); @@ -92,12 +99,20 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelAtlasScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCLabelAtlas* _laberAtlasRenderer; + std::string _stringValue; + std::string _charMapFileName; + int _itemWidth; + int _itemHeight; + std::string _startCharMap; }; } diff --git a/cocos/gui/UILabelBMFont.cpp b/cocos/gui/UILabelBMFont.cpp index b112c06bf4..d8560fd4a8 100644 --- a/cocos/gui/UILabelBMFont.cpp +++ b/cocos/gui/UILabelBMFont.cpp @@ -24,13 +24,13 @@ #include "gui/UILabelBMFont.h" - using namespace cocos2d; - namespace gui { UILabelBMFont::UILabelBMFont(): _labelBMFontRenderer(NULL), -_fntFileHasInit(false) +_fntFileHasInit(false), +_fntFileName(""), +_stringValue("") { } @@ -54,38 +54,45 @@ UILabelBMFont* UILabelBMFont::create() void UILabelBMFont::initRenderer() { UIWidget::initRenderer(); - _labelBMFontRenderer = CCLabelBMFont::create(); + _labelBMFontRenderer = cocos2d::LabelBMFont::create(); _renderer->addChild(_labelBMFontRenderer); } void UILabelBMFont::setFntFile(const char *fileName) { - if (!fileName || strcmp(fileName, "") == 0) + if (!fileName || std::strcmp(fileName, "") == 0) { return; } + _fntFileName = fileName; _labelBMFontRenderer->initWithString("", fileName); updateAnchorPoint(); labelBMFontScaleChangedWithSize(); _fntFileHasInit = true; + setText(_stringValue.c_str()); } void UILabelBMFont::setText(const char* value) { - if (!value || !_fntFileHasInit) + if (!value) { return; } - _labelBMFontRenderer->setString(value); + _stringValue = value; + if (!_fntFileHasInit) + { + return; + } + _labelBMFontRenderer->setString(value); labelBMFontScaleChangedWithSize(); } const char* UILabelBMFont::getStringValue() { - return _labelBMFontRenderer->getString(); + return _stringValue.c_str(); } -void UILabelBMFont::setAnchorPoint(const Point &pt) +void UILabelBMFont::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _labelBMFontRenderer->setAnchorPoint(pt); @@ -96,12 +103,12 @@ void UILabelBMFont::onSizeChanged() labelBMFontScaleChangedWithSize(); } -const Size& UILabelBMFont::getContentSize() const +const cocos2d::Size& UILabelBMFont::getContentSize() const { return _labelBMFontRenderer->getContentSize(); } -Node* UILabelBMFont::getVirtualRenderer() +cocos2d::Node* UILabelBMFont::getVirtualRenderer() { return _labelBMFontRenderer; } @@ -115,7 +122,7 @@ void UILabelBMFont::labelBMFontScaleChangedWithSize() } else { - Size textureSize = _labelBMFontRenderer->getContentSize(); + cocos2d::Size textureSize = _labelBMFontRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _labelBMFontRenderer->setScale(1.0f); @@ -133,5 +140,19 @@ const char* UILabelBMFont::getDescription() const return "LabelBMFont"; } +UIWidget* UILabelBMFont::createCloneInstance() +{ + return UILabelBMFont::create(); +} + +void UILabelBMFont::copySpecialProperties(UIWidget *widget) +{ + UILabelBMFont* labelBMFont = dynamic_cast(widget); + if (labelBMFont) + { + setFntFile(labelBMFont->_fntFileName.c_str()); + setText(labelBMFont->_stringValue.c_str()); + } +} } \ No newline at end of file diff --git a/cocos/gui/UILabelBMFont.h b/cocos/gui/UILabelBMFont.h index ddf4e31728..5c03c1ae75 100644 --- a/cocos/gui/UILabelBMFont.h +++ b/cocos/gui/UILabelBMFont.h @@ -29,6 +29,10 @@ namespace gui { +/** +* @js NA +* @lua NA +*/ class UILabelBMFont : public UIWidget { public: @@ -58,7 +62,6 @@ public: virtual void setAnchorPoint(const cocos2d::Point &pt); virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); - /** * Returns the "class name" of widget. */ @@ -67,9 +70,13 @@ protected: virtual void initRenderer(); virtual void onSizeChanged(); void labelBMFontScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::LabelBMFont* _labelBMFontRenderer; bool _fntFileHasInit; + std::string _fntFileName; + std::string _stringValue; }; } diff --git a/cocos/gui/UILayer.cpp b/cocos/gui/UILayer.cpp index bfdea4094f..a935f9efc5 100644 --- a/cocos/gui/UILayer.cpp +++ b/cocos/gui/UILayer.cpp @@ -119,7 +119,7 @@ UIWidget* UILayer::getWidgetByTag(int tag) { return NULL; } - return CCUIHELPER->seekWidgetByTag(_rootWidget, tag); + return UIHelper::seekWidgetByTag(_rootWidget, tag); } UIWidget* UILayer::getWidgetByName(const char* name) @@ -128,7 +128,7 @@ UIWidget* UILayer::getWidgetByName(const char* name) { return NULL; } - return CCUIHELPER->seekWidgetByName(_rootWidget, name); + return UIHelper::seekWidgetByName(_rootWidget, name); } UIRootWidget* UILayer::getRootWidget() diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp new file mode 100644 index 0000000000..70b66a0b56 --- /dev/null +++ b/cocos/gui/UILayout.cpp @@ -0,0 +1,1010 @@ +/**************************************************************************** + 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 "gui/UILayout.h" +#include "gui/UILayer.h" +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" + +namespace gui { + + +#define DYNAMIC_CAST_CLIPPINGLAYER dynamic_cast(_renderer) + +UILayout::UILayout(): +_clippingEnabled(false), +_backGroundScale9Enabled(false), +_backGroundImage(NULL), +_backGroundImageFileName(""), +_backGroundImageCapInsets(cocos2d::Rect::ZERO), +_colorType(LAYOUT_COLOR_NONE), +_bgImageTexType(UI_TEX_TYPE_LOCAL), +_colorRender(NULL), +_gradientRender(NULL), +_cColor(cocos2d::Color3B::WHITE), +_gStartColor(cocos2d::Color3B::WHITE), +_gEndColor(cocos2d::Color3B::WHITE), +_alongVector(cocos2d::Point(0.0f, -1.0f)), +_cOpacity(255), +_backGroundImageTextureSize(cocos2d::Size::ZERO), +_layoutType(LAYOUT_ABSOLUTE) +{ + _widgetType = WidgetTypeContainer; +} + +UILayout::~UILayout() +{ +} + +UILayout* UILayout::create() +{ + UILayout* layout = new UILayout(); + if (layout && layout->init()) + { + layout->autorelease(); + return layout; + } + CC_SAFE_DELETE(layout); + return NULL; +} + +bool UILayout::init() +{ + _children = cocos2d::Array::create(); + _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); + initRenderer(); + _renderer->retain(); + _renderer->setZOrder(_widgetZOrder); + cocos2d::RGBAProtocol* renderRGBA = dynamic_cast(_renderer); + if (renderRGBA) + { + renderRGBA->setCascadeColorEnabled(false); + renderRGBA->setCascadeOpacityEnabled(false); + } + ignoreContentAdaptWithSize(false); + setSize(cocos2d::Size::ZERO); + setBright(true); + setAnchorPoint(cocos2d::Point(0, 0)); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); + CC_SAFE_RETAIN(_scheduler); + return true; +} + +void UILayout::initRenderer() +{ + _renderer = UIRectClippingNode::create(); +} + +bool UILayout::addChild(UIWidget *child) +{ + supplyTheLayoutParameterLackToChild(child); + return UIWidget::addChild(child); +} + +bool UILayout::isClippingEnabled() +{ + return _clippingEnabled; +} + +bool UILayout::hitTest(const cocos2d::Point &pt) +{ + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(0.0f, 0.0f, _size.width, _size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + +void UILayout::setClippingEnabled(bool able) +{ + _clippingEnabled = able; + DYNAMIC_CAST_CLIPPINGLAYER->setClippingEnabled(able); +} + +void UILayout::onSizeChanged() +{ + DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); + doLayout(); + if (_backGroundImage) + { + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + } + if (_colorRender) + { + _colorRender->setContentSize(_size); + } + if (_gradientRender) + { + _gradientRender->setContentSize(_size); + } +} + +void UILayout::setBackGroundImageScale9Enabled(bool able) +{ + if (_backGroundScale9Enabled == able) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundScale9Enabled = able; + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _renderer->addChild(_backGroundImage); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setZOrder(-1); + setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); + setBackGroundImageCapInsets(_backGroundImageCapInsets); +} + +void UILayout::setBackGroundImage(const char* fileName,TextureResType texType) +{ + if (!fileName || strcmp(fileName, "") == 0) + { + return; + } + if (_backGroundImage == NULL) + { + addBackGroundImage(); + } + _backGroundImageFileName = fileName; + _bgImageTexType = texType; + if (_backGroundScale9Enabled) + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + switch (_bgImageTexType) + { + case UI_TEX_TYPE_LOCAL: + dynamic_cast(_backGroundImage)->initWithFile(fileName); + break; + case UI_TEX_TYPE_PLIST: + dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + break; + default: + break; + } + } + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + else + { + dynamic_cast(_backGroundImage)->setColor(getColor()); + dynamic_cast(_backGroundImage)->setOpacity(getOpacity()); + } + _backGroundImageTextureSize = _backGroundImage->getContentSize(); + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::setBackGroundImageCapInsets(const cocos2d::Rect &capInsets) +{ + _backGroundImageCapInsets = capInsets; + if (_backGroundScale9Enabled) + { + dynamic_cast(_backGroundImage)->setCapInsets(capInsets); + } +} + +void UILayout::supplyTheLayoutParameterLackToChild(UIWidget *child) +{ + if (!child) + { + return; + } + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_HORIZONTAL: + case LAYOUT_LINEAR_VERTICAL: + { + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!layoutParameter) + { + child->setLayoutParameter(UILinearLayoutParameter::create()); + } + break; + } + case LAYOUT_RELATIVE: + { + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + if (!layoutParameter) + { + child->setLayoutParameter(UIRelativeLayoutParameter::create()); + } + break; + } + default: + break; + } +} + +void UILayout::addBackGroundImage() +{ + if (_backGroundScale9Enabled) + { + _backGroundImage = cocos2d::extension::Scale9Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + dynamic_cast(_backGroundImage)->setPreferredSize(_size); + } + else + { + _backGroundImage = cocos2d::Sprite::create(); + _backGroundImage->setZOrder(-1); + _renderer->addChild(_backGroundImage); + } + _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); +} + +void UILayout::removeBackGroundImage() +{ + if (!_backGroundImage) + { + return; + } + _renderer->removeChild(_backGroundImage, true); + _backGroundImage = NULL; + _backGroundImageFileName = ""; + _backGroundImageTextureSize = cocos2d::Size::ZERO; +} + +void UILayout::setBackGroundColorType(LayoutBackGroundColorType type) +{ + if (_colorType == type) + { + return; + } + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + case LAYOUT_COLOR_SOLID: + if (_colorRender) + { + _renderer->removeChild(_colorRender, true); + _colorRender = NULL; + } + break; + case LAYOUT_COLOR_GRADIENT: + if (_gradientRender) + { + _renderer->removeChild(_gradientRender, true); + _gradientRender = NULL; + } + break; + default: + break; + } + _colorType = type; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender = cocos2d::LayerColor::create(); + _colorRender->setContentSize(_size); + _colorRender->setOpacity(_cOpacity); + _colorRender->setColor(_cColor); + _renderer->addChild(_colorRender,-2); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender = cocos2d::LayerGradient::create(); + _gradientRender->setContentSize(_size); + _gradientRender->setOpacity(_cOpacity); + _gradientRender->setStartColor(_gStartColor); + _gradientRender->setEndColor(_gEndColor); + _gradientRender->setVector(_alongVector); + _renderer->addChild(_gradientRender,-2); + break; + default: + break; + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &color) +{ + _cColor = color; + if (_colorRender) + { + _colorRender->setColor(color); + } +} + +void UILayout::setBackGroundColor(const cocos2d::Color3B &startColor, const cocos2d::Color3B &endColor) +{ + _gStartColor = startColor; + if (_gradientRender) + { + _gradientRender->setStartColor(startColor); + } + _gEndColor = endColor; + if (_gradientRender) + { + _gradientRender->setEndColor(endColor); + } +} + +void UILayout::setBackGroundColorOpacity(int opacity) +{ + _cOpacity = opacity; + switch (_colorType) + { + case LAYOUT_COLOR_NONE: + break; + case LAYOUT_COLOR_SOLID: + _colorRender->setOpacity(opacity); + break; + case LAYOUT_COLOR_GRADIENT: + _gradientRender->setOpacity(opacity); + break; + default: + break; + } +} + +void UILayout::setBackGroundColorVector(const cocos2d::Point &vector) +{ + _alongVector = vector; + if (_gradientRender) + { + _gradientRender->setVector(vector); + } +} + +void UILayout::setColor(const cocos2d::Color3B &color) +{ + UIWidget::setColor(color); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setColor(color); + } + } +} + +void UILayout::setOpacity(int opacity) +{ + UIWidget::setOpacity(opacity); + if (_backGroundImage) + { + cocos2d::RGBAProtocol* rgbap = dynamic_cast(_backGroundImage); + if (rgbap) + { + rgbap->setOpacity(opacity); + } + } +} + +const cocos2d::Size& UILayout::getBackGroundImageTextureSize() const +{ + return _backGroundImageTextureSize; +} + +const cocos2d::Size& UILayout::getContentSize() const +{ + return _renderer->getContentSize(); +} + +void UILayout::setLayoutType(LayoutType type) +{ + _layoutType = type; + + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + for (int i=0; i(layoutChildrenArray->arr[i]); + supplyTheLayoutParameterLackToChild(child); + } +} + +LayoutType UILayout::getLayoutType() const +{ + return _layoutType; +} + +void UILayout::doLayout() +{ + switch (_layoutType) + { + case LAYOUT_ABSOLUTE: + break; + case LAYOUT_LINEAR_VERTICAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float topBoundary = layoutSize.height; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = ap.x * cs.width; + float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; + } + } + break; + } + case LAYOUT_LINEAR_HORIZONTAL: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + cocos2d::Size layoutSize = getSize(); + float leftBoundary = 0.0f; + for (int i=0; i(layoutChildrenArray->arr[i]); + UILinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + UILinearGravity childGravity = layoutParameter->getGravity(); + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + float finalPosX = leftBoundary + (ap.x * cs.width); + float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = ap.y * cs.height; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); + break; + default: + break; + } + UIMargin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; + } + } + break; + } + case LAYOUT_RELATIVE: + { + cocos2d::ccArray* layoutChildrenArray = getChildren()->data; + int length = layoutChildrenArray->num; + int unlayoutChildCount = length; + cocos2d::Size layoutSize = getSize(); + + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + layoutParameter->_put = false; + } + + while (unlayoutChildCount > 0) + { + for (int i=0; i(layoutChildrenArray->arr[i]); + UIRelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + + if (layoutParameter) + { + if (layoutParameter->_put) + { + continue; + } + cocos2d::Point ap = child->getAnchorPoint(); + cocos2d::Size cs = child->getSize(); + UIRelativeAlign align = layoutParameter->getAlign(); + const char* relativeName = layoutParameter->getRelativeToWidgetName(); + UIWidget* relativeWidget = NULL; + UIRelativeLayoutParameter* relativeWidgetLP = NULL; + float finalPosX = 0.0f; + float finalPosY = 0.0f; + if (relativeName && strcmp(relativeName, "")) + { + relativeWidget = UIHelper::seekWidgetByRelativeName(this, relativeName); + if (relativeWidget) + { + relativeWidgetLP = dynamic_cast(relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + } + } + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_CENTER_IN_PARENT: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX = ap.x * cs.width; + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = ap.y * cs.height; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationBottom = relativeWidget->getTopInParent(); + + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosX = locationLeft + ap.x * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + cocos2d::Size rbs = relativeWidget->getSize(); + float locationTop = relativeWidget->getBottomInParent(); + + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + default: + break; + } + UIMargin relativeWidgetMargin; + UIMargin mg = layoutParameter->getMargin(); + if (relativeWidget) + { + relativeWidgetMargin = relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)->getMargin(); + } + //handle margin + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX += mg.left; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX -= mg.right; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX += mg.left; + break; + case RELATIVE_CENTER_IN_PARENT: + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX -= mg.right; + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX += mg.left; + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX -= mg.right; + finalPosY += mg.bottom; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + case RELATIVE_LOCATION_ABOVE_CENTER: + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + finalPosY += mg.bottom; + finalPosY += relativeWidgetMargin.top; + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + case RELATIVE_LOCATION_LEFT_OF_CENTER: + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + finalPosX -= mg.right; + finalPosX -= relativeWidgetMargin.left; + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + finalPosX += mg.left; + finalPosX += relativeWidgetMargin.right; + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + case RELATIVE_LOCATION_BELOW_CENTER: + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + finalPosY -= mg.top; + finalPosY -= relativeWidgetMargin.bottom; + break; + default: + break; + } + child->setPosition(cocos2d::Point(finalPosX, finalPosY)); + layoutParameter->_put = true; + unlayoutChildCount--; + } + } + } + break; + } + default: + break; + } +} + +const char* UILayout::getDescription() const +{ + return "Layout"; +} + +UIWidget* UILayout::createCloneInstance() +{ + return UILayout::create(); +} + +void UILayout::copyClonedWidgetChildren(UIWidget* model) +{ + UIWidget::copyClonedWidgetChildren(model); + doLayout(); +} + +void UILayout::copySpecialProperties(UIWidget *widget) +{ + UILayout* layout = dynamic_cast(widget); + if (layout) + { + setBackGroundImageScale9Enabled(layout->_backGroundScale9Enabled); + setBackGroundImage(layout->_backGroundImageFileName.c_str(),layout->_bgImageTexType); + setBackGroundImageCapInsets(layout->_backGroundImageCapInsets); + setBackGroundColorType(layout->_colorType); + setBackGroundColor(layout->_cColor); + setBackGroundColor(layout->_gStartColor, layout->_gEndColor); + setBackGroundColorOpacity(layout->_cOpacity); + setBackGroundColorVector(layout->_alongVector); + setLayoutType(layout->_layoutType); + setClippingEnabled(layout->_clippingEnabled); + } +} + +UIRectClippingNode::UIRectClippingNode(): +_innerStencil(NULL), +_enabled(true), +_clippingSize(cocos2d::Size(50.0f, 50.0f)), +_clippingEnabled(false) +{ + +} + +UIRectClippingNode::~UIRectClippingNode() +{ + +} + +UIRectClippingNode* UIRectClippingNode::create() +{ + UIRectClippingNode *pRet = new UIRectClippingNode(); + if (pRet && pRet->init()) + { + pRet->autorelease(); + } + else + { + CC_SAFE_DELETE(pRet); + } + + return pRet; +} + +bool UIRectClippingNode::init() +{ + _innerStencil = cocos2d::DrawNode::create(); + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + + cocos2d::Color4F green = {0, 1, 0, 1}; + _innerStencil->drawPolygon(rect, 4, green, 0, green); + if (cocos2d::ClippingNode::init(_innerStencil)) + { + return true; + } + return false; +} + + +void UIRectClippingNode::setClippingSize(const cocos2d::Size &size) +{ + setContentSize(size); + _clippingSize = size; + rect[0] = cocos2d::Point(0, 0); + rect[1] = cocos2d::Point(_clippingSize.width, 0); + rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); + rect[3] = cocos2d::Point(0, _clippingSize.height); + cocos2d::Color4F green = {0, 1, 0, 1}; + _innerStencil->clear(); + _innerStencil->drawPolygon(rect, 4, green, 0, green); +} + +void UIRectClippingNode::setClippingEnabled(bool enabled) +{ + _clippingEnabled = enabled; +} + +void UIRectClippingNode::visit() +{ + if (!_enabled) + { + return; + } + if (_clippingEnabled) + { + cocos2d::ClippingNode::visit(); + } + else + { + cocos2d::Node::visit(); + } +} + +void UIRectClippingNode::setEnabled(bool enabled) +{ + _enabled = enabled; +} + +bool UIRectClippingNode::isEnabled() const +{ + return _enabled; +} + +} \ No newline at end of file diff --git a/cocos/gui/Layout.h b/cocos/gui/UILayout.h similarity index 89% rename from cocos/gui/Layout.h rename to cocos/gui/UILayout.h index b58b0fbd2b..918bd868af 100644 --- a/cocos/gui/Layout.h +++ b/cocos/gui/UILayout.h @@ -44,23 +44,28 @@ typedef enum LAYOUT_RELATIVE }LayoutType; -class Layout : public UIWidget + +/** + * @js NA + * @lua NA + */ +class UILayout : public UIWidget { public: /** * Default constructor */ - Layout(); + UILayout(); /** * Default destructor */ - virtual ~Layout(); + virtual ~UILayout(); /** * Allocates and initializes a layout. */ - static Layout* create(); + static UILayout* create(); //override "hitTest" method of widget. virtual bool hitTest(const cocos2d::Point &pt); @@ -168,6 +173,11 @@ public: */ virtual const cocos2d::Size& getContentSize() const; + /** + * Returns the "class name" of widget. + */ + virtual const char* getDescription() const; + /** * Sets LayoutType. * @@ -187,11 +197,14 @@ public: virtual LayoutType getLayoutType() const; virtual void doLayout(); - + /** - * Returns the "class name" of widget. + * Adds a child to the container. + * + * @param child A child widget */ - virtual const char* getDescription() const; + virtual bool addChild(UIWidget* child); + protected: //override "init" method of widget. virtual bool init(); @@ -204,6 +217,11 @@ protected: //init background image renderer. void addBackGroundImage(); + + void supplyTheLayoutParameterLackToChild(UIWidget* child); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _clippingEnabled; @@ -224,23 +242,26 @@ protected: cocos2d::Size _backGroundImageTextureSize; LayoutType _layoutType; }; - -class RectClippingNode : public cocos2d::ClippingNode +/** + * @js NA + * @lua NA + */ +class UIRectClippingNode : public cocos2d::ClippingNode { public: - virtual ~RectClippingNode(); + virtual ~UIRectClippingNode(); virtual bool init(); - static RectClippingNode* create(); + static UIRectClippingNode* create(); void setClippingSize(const cocos2d::Size& size); void setClippingEnabled(bool enabled); virtual void visit(); void setEnabled(bool enabled); bool isEnabled() const; protected: - cocos2d::DrawNode* m_pInnerStencil; + cocos2d::DrawNode* _innerStencil; bool _enabled; private: - RectClippingNode(); + UIRectClippingNode(); cocos2d::Point rect[4]; cocos2d::Size _clippingSize; bool _clippingEnabled; diff --git a/cocos/gui/UILayoutDefine.cpp b/cocos/gui/UILayoutDefine.cpp index d79444fc75..b6b785a47d 100644 --- a/cocos/gui/UILayoutDefine.cpp +++ b/cocos/gui/UILayoutDefine.cpp @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "gui/UILayoutDefine.h" +#include "UILayoutDefine.h" namespace gui { diff --git a/cocos/gui/UILayoutDefine.h b/cocos/gui/UILayoutDefine.h index 1d0bd716bf..0b772837ca 100644 --- a/cocos/gui/UILayoutDefine.h +++ b/cocos/gui/UILayoutDefine.h @@ -26,9 +26,13 @@ #define __UILAYOUTDEFINE_H__ #include "cocos2d.h" +#include "ExtensionMacros.h" namespace gui { - +/** +* @js NA +* @lua NA +*/ class UIMargin { public: @@ -46,6 +50,7 @@ public: bool equals(const UIMargin& target) const; }; +const UIMargin UIMarginZero = UIMargin(); typedef enum { @@ -61,22 +66,25 @@ typedef enum typedef enum { RELATIVE_ALIGN_NONE, - RELATIVE_ALIGN_PARENT_LEFT, - RELATIVE_ALIGN_PARENT_TOP, - RELATIVE_ALIGN_PARENT_RIGHT, - RELATIVE_ALIGN_PARENT_BOTTOM, + RELATIVE_ALIGN_PARENT_TOP_LEFT, + RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_TOP_RIGHT, + RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL, RELATIVE_CENTER_IN_PARENT, - RELATIVE_CENTER_HORIZONTAL, - RELATIVE_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_LEFT_BOTTOM, + RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM, + + RELATIVE_LOCATION_ABOVE_LEFTALIGN, + RELATIVE_LOCATION_ABOVE_CENTER, + RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_LEFT_OF_TOPALIGN, RELATIVE_LOCATION_LEFT_OF_CENTER, RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN, RELATIVE_LOCATION_RIGHT_OF_TOPALIGN, RELATIVE_LOCATION_RIGHT_OF_CENTER, RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN, - RELATIVE_LOCATION_ABOVE_LEFTALIGN, - RELATIVE_LOCATION_ABOVE_CENTER, - RELATIVE_LOCATION_ABOVE_RIGHTALIGN, RELATIVE_LOCATION_BELOW_LEFTALIGN, RELATIVE_LOCATION_BELOW_CENTER, RELATIVE_LOCATION_BELOW_RIGHTALIGN diff --git a/cocos/gui/LayoutParameter.cpp b/cocos/gui/UILayoutParameter.cpp similarity index 65% rename from cocos/gui/LayoutParameter.cpp rename to cocos/gui/UILayoutParameter.cpp index 01caa33158..c468f69a24 100644 --- a/cocos/gui/LayoutParameter.cpp +++ b/cocos/gui/UILayoutParameter.cpp @@ -22,14 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "gui/LayoutParameter.h" -#include "gui/Layout.h" +#include "gui/UILayoutParameter.h" +#include "gui/UILayout.h" namespace gui { -LayoutParameter* LayoutParameter::create() + +UILayoutParameter* UILayoutParameter::create() { - LayoutParameter* parameter = new LayoutParameter(); + UILayoutParameter* parameter = new UILayoutParameter(); if (parameter) { parameter->autorelease(); @@ -39,24 +40,24 @@ LayoutParameter* LayoutParameter::create() return NULL; } -void LayoutParameter::setMargin(const UIMargin &margin) +void UILayoutParameter::setMargin(const UIMargin &margin) { _margin = margin; } -const UIMargin& LayoutParameter::getMargin() const +const UIMargin& UILayoutParameter::getMargin() const { return _margin; } -LayoutParameterType LayoutParameter::getLayoutType() const +LayoutParameterType UILayoutParameter::getLayoutType() const { return _layoutParameterType; } -LinearLayoutParameter* LinearLayoutParameter::create() +UILinearLayoutParameter* UILinearLayoutParameter::create() { - LinearLayoutParameter* parameter = new LinearLayoutParameter(); + UILinearLayoutParameter* parameter = new UILinearLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -66,19 +67,19 @@ LinearLayoutParameter* LinearLayoutParameter::create() return NULL; } -void LinearLayoutParameter::setGravity(UILinearGravity gravity) +void UILinearLayoutParameter::setGravity(UILinearGravity gravity) { _linearGravity = gravity; } -UILinearGravity LinearLayoutParameter::getGravity() const +UILinearGravity UILinearLayoutParameter::getGravity() const { return _linearGravity; } -RelativeLayoutParameter* RelativeLayoutParameter::create() +UIRelativeLayoutParameter* UIRelativeLayoutParameter::create() { - RelativeLayoutParameter* parameter = new RelativeLayoutParameter(); + UIRelativeLayoutParameter* parameter = new UIRelativeLayoutParameter(); if (parameter) { parameter->autorelease(); @@ -88,32 +89,32 @@ RelativeLayoutParameter* RelativeLayoutParameter::create() return NULL; } -void RelativeLayoutParameter::setAlign(UIRelativeAlign align) +void UIRelativeLayoutParameter::setAlign(UIRelativeAlign align) { _relativeAlign = align; } -UIRelativeAlign RelativeLayoutParameter::getAlign() const +UIRelativeAlign UIRelativeLayoutParameter::getAlign() const { return _relativeAlign; } -void RelativeLayoutParameter::setRelativeToWidgetName(const char *name) +void UIRelativeLayoutParameter::setRelativeToWidgetName(const char *name) { _relativeWidgetName = name; } -const char* RelativeLayoutParameter::getRelativeToWidgetName() const +const char* UIRelativeLayoutParameter::getRelativeToWidgetName() const { return _relativeWidgetName.c_str(); } -void RelativeLayoutParameter::setRelativeName(const char* name) +void UIRelativeLayoutParameter::setRelativeName(const char* name) { _relativeLayoutName = name; } -const char* RelativeLayoutParameter::getRelativeName() const +const char* UIRelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName.c_str(); } diff --git a/cocos/gui/LayoutParameter.h b/cocos/gui/UILayoutParameter.h similarity index 82% rename from cocos/gui/LayoutParameter.h rename to cocos/gui/UILayoutParameter.h index 3c457635d1..60a7e387ad 100644 --- a/cocos/gui/LayoutParameter.h +++ b/cocos/gui/UILayoutParameter.h @@ -35,25 +35,28 @@ typedef enum LAYOUT_PARAMETER_LINEAR, LAYOUT_PARAMETER_RELATIVE }LayoutParameterType; - -class LayoutParameter : public cocos2d::Object +/** +* @js NA +* @lua NA +*/ +class UILayoutParameter : public cocos2d::Object { public: /** * Default constructor */ - LayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; + UILayoutParameter() : _margin(UIMargin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; /** * Default destructor */ - virtual ~LayoutParameter(){}; + virtual ~UILayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LayoutParameter* create(); + static UILayoutParameter* create(); /** * Sets Margin parameter for LayoutParameter. @@ -85,25 +88,28 @@ protected: UIMargin _margin; LayoutParameterType _layoutParameterType; }; - -class LinearLayoutParameter : public LayoutParameter +/** +* @js NA +* @lua NA +*/ +class UILinearLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - LinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; + UILinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; /** * Default destructor */ - virtual ~LinearLayoutParameter(){}; + virtual ~UILinearLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static LinearLayoutParameter* create(); + static UILinearLayoutParameter* create(); /** * Sets UILinearGravity parameter for LayoutParameter. @@ -125,25 +131,31 @@ public: protected: UILinearGravity _linearGravity; }; +/** +* @js NA +* @lua NA +*/ -class RelativeLayoutParameter : public LayoutParameter +class UILayout; + +class UIRelativeLayoutParameter : public UILayoutParameter { public: /** * Default constructor */ - RelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; + UIRelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""),_put(false){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; /** * Default destructor */ - virtual ~RelativeLayoutParameter(){}; + virtual ~UIRelativeLayoutParameter(){}; /** * Allocates and initializes. * @return A initialized LayoutParameter which is marked as "autorelease". */ - static RelativeLayoutParameter* create(); + static UIRelativeLayoutParameter* create(); /** * Sets UIRelativeAlign parameter for LayoutParameter. @@ -194,6 +206,8 @@ protected: UIRelativeAlign _relativeAlign; std::string _relativeWidgetName; std::string _relativeLayoutName; + bool _put; + friend class UILayout; }; } diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 5ec6e71540..81baaad41d 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -23,55 +23,24 @@ ****************************************************************************/ #include "gui/UIListView.h" - - using namespace cocos2d; +#include "gui/UIHelper.h" +#include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" namespace gui { -UIListView::UIListView() -: _direction(LISTVIEW_DIR_VERTICAL) -, _moveDirection(LISTVIEW_MOVE_DIR_NONE) -, _touchStartLocation(0.0f) -, _touchEndLocation(0.0f) -, _touchMoveStartLocation(0.0f) -, _topBoundary(0.0f) -, _bottomBoundary(0.0f) -, _leftBoundary(0.0f) -, _rightBoundary(0.0f) -, _autoScroll(false) -, _autoScrollOriginalSpeed(0.0f) -, _autoScrollAcceleration(600.0f) -, _bePressed(false) -, _slidTime(0.0f) -, _childFocusCancelOffset(5.0f) -, _eventListener(NULL) -, _eventSelector(NULL) -, _childPool(NULL) -, _updatePool(NULL) -, _dataLength(0) -, _begin(0) -, _end(0) -, _updateChild(NULL) -, _updateDataIndex(-1) -, _updateSuccess(false) -, _overTopArray(NULL) -, _overBottomArray(NULL) -, _overLeftArray(NULL) -, _overRightArray(NULL) -, _disBoundaryToChild_0(0.0f) -, _disBetweenChild(0.0f) -, _scrollDegreeRange(45.0f) +UIListView::UIListView(): +_model(NULL), +_items(NULL), +_gravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL), +_itemsMargin(0.0f) { + } UIListView::~UIListView() { - CC_SAFE_RELEASE_NULL(_childPool); - CC_SAFE_RELEASE_NULL(_updatePool); - CC_SAFE_RELEASE_NULL(_overTopArray); - CC_SAFE_RELEASE_NULL(_overBottomArray); - CC_SAFE_RELEASE_NULL(_overLeftArray); - CC_SAFE_RELEASE_NULL(_overRightArray); + _items->removeAllObjects(); + CC_SAFE_RELEASE(_items); } UIListView* UIListView::create() @@ -88,1373 +57,365 @@ UIListView* UIListView::create() bool UIListView::init() { - if (Layout::init()) + if (UIScrollView::init()) { - setUpdateEnabled(true); - setTouchEnabled(true); - setClippingEnabled(true); - - _childPool = CCArray::create(); - _updatePool = CCArray::create(); - CC_SAFE_RETAIN(_childPool); - CC_SAFE_RETAIN(_updatePool); - _overTopArray = cocos2d::CCArray::create(); - _overBottomArray = cocos2d::CCArray::create(); - _overLeftArray = cocos2d::CCArray::create(); - _overRightArray = cocos2d::CCArray::create(); - CC_SAFE_RETAIN(_overTopArray); - CC_SAFE_RETAIN(_overBottomArray); - CC_SAFE_RETAIN(_overLeftArray); - CC_SAFE_RETAIN(_overRightArray); - + _items = cocos2d::Array::create(); + CC_SAFE_RETAIN(_items); + setLayoutType(LAYOUT_LINEAR_VERTICAL); return true; } return false; } +void UIListView::setItemModel(UIWidget *model) +{ + if (!model) + { + return; + } + CC_SAFE_RELEASE_NULL(_model); + _model = model; + CC_SAFE_RETAIN(_model); +} + +void UIListView::updateInnerContainerSize() +{ + if (!_model) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + int childrenCount = _items->count(); + float totalHeight = _model->getSize().height * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = _size.width; + float finalHeight = totalHeight; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + int childrenCount = _items->count(); + float totalWidth = _model->getSize().width * childrenCount + (childrenCount - 1) * _itemsMargin; + float finalWidth = totalWidth; + float finalHeight = _size.height; + setInnerContainerSize(cocos2d::Size(finalWidth, finalHeight)); + break; + } + default: + break; + } +} + +void UIListView::remedyLayoutParameter(UIWidget *item) +{ + if (!item) + { + return; + } + switch (_direction) { + case SCROLLVIEW_DIR_VERTICAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + defaultLp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + defaultLp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(0.0f, _itemsMargin, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_LEFT: + llp->setGravity(LINEAR_GRAVITY_LEFT); + break; + case LISTVIEW_GRAVITY_RIGHT: + llp->setGravity(LINEAR_GRAVITY_RIGHT); + break; + case LISTVIEW_GRAVITY_CENTER_HORIZONTAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); + break; + default: + break; + } + } + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + UILinearLayoutParameter* llp = (UILinearLayoutParameter*)(item->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (!llp) + { + UILinearLayoutParameter* defaultLp = UILinearLayoutParameter::create(); + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + defaultLp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + defaultLp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + defaultLp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + if (getIndex(item) == 0) + { + defaultLp->setMargin(UIMarginZero); + } + else + { + defaultLp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + item->setLayoutParameter(defaultLp); + } + else + { + if (getIndex(item) == 0) + { + llp->setMargin(UIMarginZero); + } + else + { + llp->setMargin(UIMargin(_itemsMargin, 0.0f, 0.0f, 0.0f)); + } + switch (_gravity) { + case LISTVIEW_GRAVITY_TOP: + llp->setGravity(LINEAR_GRAVITY_TOP); + break; + case LISTVIEW_GRAVITY_BOTTOM: + llp->setGravity(LINEAR_GRAVITY_BOTTOM); + break; + case LISTVIEW_GRAVITY_CENTER_VERTICAL: + llp->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); + break; + default: + break; + } + } + break; + } + default: + break; + } + +} + +void UIListView::pushBackDefaultItem() +{ + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->addObject(newItem); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::insertDefaultItem(int index) +{ + if (!_items) + { + return; + } + if (!_model) + { + return; + } + UIWidget* newItem = _model->clone(); + _items->insertObject(newItem, index); + remedyLayoutParameter(newItem); + addChild(newItem); +} + +void UIListView::pushBackCustomItem(UIWidget* item) +{ + _items->addObject(item); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::insertCustomItem(UIWidget* item, int index) +{ + _items->insertObject(item, index); + remedyLayoutParameter(item); + addChild(item); +} + +void UIListView::removeItem(int index) +{ + if (!_items) + { + return; + } + UIWidget* item = getItem(index); + if (!item) + { + return; + + } + _items->removeObject(item); + removeChild(item); +} + +void UIListView::removeLastItem() +{ + removeItem(_items->count() -1); +} + +UIWidget* UIListView::getItem(unsigned int index) +{ + if ((int)index < 0 || index >= _items->count()) + { + return NULL; + } + return (UIWidget*)(_items->data->arr[index]); +} + +cocos2d::Array* UIListView::getItems() +{ + return _items; +} + +unsigned int UIListView::getIndex(UIWidget *item) const +{ + if (!_items) + { + return -1; + } + if (!item) + { + return -1; + } + return _items->getIndexOfObject(item); +} + +void UIListView::setGravity(ListViewGravity gravity) +{ + if (_gravity == gravity) + { + return; + } + _gravity = gravity; + refreshView(); +} + +void UIListView::setItemsMargin(float margin) +{ + if (_itemsMargin == margin) + { + return; + } + _itemsMargin = margin; + refreshView(); +} + +void UIListView::setDirection(SCROLLVIEW_DIR dir) +{ + switch (dir) + { + case SCROLLVIEW_DIR_VERTICAL: + setLayoutType(LAYOUT_LINEAR_VERTICAL); + break; + case SCROLLVIEW_DIR_HORIZONTAL: + setLayoutType(LAYOUT_LINEAR_HORIZONTAL); + break; + case SCROLLVIEW_DIR_BOTH: + return; + default: + return; + break; + } + UIScrollView::setDirection(dir); + +} + +void UIListView::refreshView() +{ + if (!_items) + { + return; + } + cocos2d::ccArray* arrayItems = _items->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + item->setZOrder(i); + remedyLayoutParameter(item); + } + updateInnerContainerSize(); + doLayout(); +} + void UIListView::onSizeChanged() { - Layout::onSizeChanged(); - _topBoundary = _size.height; - _rightBoundary = _size.width; -} - -bool UIListView::addChild(UIWidget* widget) -{ - Layout::addChild(widget); - resetProperty(); - return true; -} - -void UIListView::removeAllChildren() -{ - _updatePool->removeAllObjects(); - _childPool->removeAllObjects(); - Layout::removeAllChildren(); -} - -bool UIListView::removeChild(UIWidget* child) -{ - bool value = false; - - if (Layout::removeChild(child)) - { - value = true; - resetProperty(); - } - - return value; -} - -bool UIListView::onTouchBegan(const Point &touchPoint) -{ - bool pass = Layout::onTouchBegan(touchPoint); - handlePressLogic(touchPoint); - return pass; -} - -void UIListView::onTouchMoved(const Point &touchPoint) -{ - Layout::onTouchMoved(touchPoint); - handleMoveLogic(touchPoint); -} - -void UIListView::onTouchEnded(const Point &touchPoint) -{ - Layout::onTouchEnded(touchPoint); - handleReleaseLogic(touchPoint); -} - -void UIListView::onTouchCancelled(const Point &touchPoint) -{ - Layout::onTouchCancelled(touchPoint); -} - -void UIListView::onTouchLongClicked(const Point &touchPoint) -{ - -} - -void UIListView::update(float dt) -{ - if (_autoScroll) - { - autoScrollChildren(dt); - } - recordSlidTime(dt); -} - -void UIListView::setDirection(ListViewDirection dir) -{ - _direction = dir; -} - -ListViewDirection UIListView::getDirection() -{ - return _direction; -} - -void UIListView::resetProperty() -{ - ccArray* arrayChildren = _children->data; - - if (arrayChildren->num <= 0) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - if (_topBoundary == 0) - { - return; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - if (_rightBoundary == 0) - { - return; - } - break; - - default: - break; - } - - float scroll_top = _topBoundary; - float scroll_left = _leftBoundary; - - switch (_children->count()) - { - case 1: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - } - break; - - default: - break; - } - } - break; - - default: - { - UIWidget* child_0 = dynamic_cast(arrayChildren->arr[0]); - UIWidget* child_1 = dynamic_cast(arrayChildren->arr[1]); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float child_0_top = child_0->getTopInParent(); - _disBoundaryToChild_0 = scroll_top - child_0_top; - _disBetweenChild = child_0->getPosition().y - child_1->getPosition().y; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float child_0_left = child_0->getLeftInParent(); - _disBoundaryToChild_0 = child_0_left - scroll_left; - _disBetweenChild = child_1->getPosition().x - child_0->getPosition().x; - } - break; - - default: - break; - } - } - break; - } -} - -void UIListView::handlePressLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - - default: - break; - } - startRecordSlidAction(); - clearCollectOverArray(); -} - -void UIListView::handleMoveLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = LISTVIEW_MOVE_DIR_UP; // up - } - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = LISTVIEW_MOVE_DIR_RIGHT; // right - } - } - break; - - default: - break; - } - scrollChildren(offset); -} - -void UIListView::handleReleaseLogic(const Point &touchPoint) -{ - Point nsp = _renderer->convertToNodeSpace(touchPoint); - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } - endRecordSlidAction(); -} - -void UIListView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) -{ - switch (handleState) - { - case 0: - handlePressLogic(touchPoint); - break; - - case 1: - { - float offset = 0; - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } - if (offset > _childFocusCancelOffset) - { - sender->setFocused(false); - handleMoveLogic(touchPoint); - } - } - break; - - case 2: - handleReleaseLogic(touchPoint); - break; - - case 3: - break; - } -} - -void UIListView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) -{ - interceptTouchEvent(handleState, sender, touchPoint); -} - -void UIListView::moveChildren(float offset) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i = 0; i < childrenCount; i++) - { - UIWidget* child = (UIWidget*)(arrayChildren->arr[i]); - _moveChildPoint.x = child->getPosition().x; - _moveChildPoint.y = child->getPosition().y + offset; - child->setPosition(_moveChildPoint); - } - break; - } - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - { - ccArray* arrayChildren = _children->data; - int childrenCount = arrayChildren->num; - for (int i=0;iarr[i]); - _moveChildPoint.x = child->getPosition().x + offset; - _moveChildPoint.y = child->getPosition().y; - child->setPosition(_moveChildPoint); - } - break; - } - - default: - break; - } -} - -bool UIListView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_bottom = child_last->getBottomInParent(); - float scroll_bottom = _bottomBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset > scroll_bottom + _disBoundaryToChild_0 - child_last_bottom) - { - realOffset = scroll_bottom + _disBoundaryToChild_0 - child_last_bottom; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverTopChild(); - unsigned int count = _overTopArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overTopArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_top = child_0->getTopInParent(); - float scroll_top = _topBoundary; - - if (_begin == 0) - { - if (realOffset < scroll_top - _disBoundaryToChild_0 - child_0_top) - { - realOffset = scroll_top - _disBoundaryToChild_0 - child_0_top; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_begin > 0) - { - collectOverBottomChild(); - int count = _overBottomArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overBottomArray->removeAllObjects(); - } - } - } - break; - - default: - break; - } - return true; - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - realOffset = MAX(realOffset, -_disBetweenChild); - - UIWidget* child_last = dynamic_cast(_childPool->getLastObject()); - float child_last_right = child_last->getRightInParent(); - float scroll_right = _rightBoundary; - - if (_end == _dataLength - 1) - { - if (realOffset < scroll_right - _disBoundaryToChild_0 - child_last_right) - { - realOffset = scroll_right - _disBoundaryToChild_0 - child_last_right; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - if (_end < _dataLength - 1) - { - collectOverLeftChild(); - int count = _overLeftArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overLeftArray->removeAllObjects(); - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - realOffset = MIN(realOffset, _disBetweenChild); - - UIWidget* child_0 = dynamic_cast(_childPool->getObjectAtIndex(0)); - float child_0_left = child_0->getLeftInParent(); - float scroll_left = _leftBoundary; - - if (_begin == 0) - { - if (realOffset > scroll_left + _disBoundaryToChild_0 - child_0_left) - { - realOffset = scroll_left + _disBoundaryToChild_0 - child_0_left; - } - moveChildren(realOffset); - return false; - } - moveChildren(realOffset); - - collectOverRightChild(); - int count = _overRightArray->count(); - if (count > 0) - { - updateChild(); - setLoopPosition(); - _overRightArray->removeAllObjects(); - } - } - break; - - default: - break; - } - return true; - break; - - default: - break; - } - - return false; -} - -void UIListView::autoScrollChildren(float dt) -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -float UIListView::getCurAutoScrollDistance(float time) -{ - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; -} - -void UIListView::startAutoScrollChildren(float v) -{ - _autoScrollOriginalSpeed = v; - _autoScroll = true; -} - -void UIListView::stopAutoScrollChildren() -{ - _autoScroll = false; - _autoScrollOriginalSpeed = 0.0f; -} - -void UIListView::recordSlidTime(float dt) -{ - if (_bePressed) - { - _slidTime += dt; - } -} - -void UIListView::startRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_autoScroll) - { - stopAutoScrollChildren(); - } - _bePressed = true; - _slidTime = 0.0; -} - -void UIListView::endRecordSlidAction() -{ - if (_children->count() <= 0) - { - return; - } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed / 4); - - _bePressed = false; - _slidTime = 0.0; -} - -UIWidget* UIListView::getCheckPositionChild() -{ - UIWidget* child = NULL; - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - child = dynamic_cast(_childPool->getLastObject()); - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - child = dynamic_cast(_childPool->getObjectAtIndex(0)); - break; - - default: - break; - } - break; - - default: - break; - } - - return child; -} - -void UIListView::initChildWithDataLength(int length) -{ - _dataLength = length; - _begin = 0; - _end = 0; - - // init child pool - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - setUpdateChild(child); - setUpdateDataIndex(i); - initChildEvent(); - _childPool->addObject(child); - _end = i; - } -} - -UIWidget* UIListView::getChildFromUpdatePool() -{ - UIWidget* child = dynamic_cast(_updatePool->getLastObject()); - _updatePool->removeLastObject(); - return child; -} - -void UIListView::pushChildToPool() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - UIWidget* child = dynamic_cast(_childPool->getObjectAtIndex(0)); - _updatePool->insertObject(child, 0); - _childPool->removeObjectAtIndex(0); - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - UIWidget* child = dynamic_cast(_childPool->getLastObject()); - _updatePool->insertObject(child, 0); - _childPool->removeLastObject(); - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::getAndCallback() -{ - UIWidget* child = getChildFromUpdatePool(); - - if (child == NULL) - { - return; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - ++_end; - setUpdateChild(child); - setUpdateDataIndex(_end); - updateChildEvent(); - - if (_updateSuccess == false) - { - --_end; - _childPool->insertObject(child, 0); - return; - } - ++_begin; - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - --_begin; - setUpdateChild(child); - setUpdateDataIndex(_begin); - updateChildEvent(); - - if (_updateSuccess == false) - { - ++_begin; - _childPool->addObject(child); - return; - } - --_end; - break; - - default: - break; - } - break; - - default: - break; - } - - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - _childPool->addObject(child); - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - _childPool->addObject(child); - break; - case LISTVIEW_MOVE_DIR_RIGHT: // right - _childPool->insertObject(child, 0); - break; - - default: - break; - } - break; - - default: - break; - } -} - -int UIListView::getDataLength() -{ - return _dataLength; -} - -UIWidget* UIListView::getUpdateChild() -{ - return _updateChild; -} - -void UIListView::setUpdateChild(UIWidget* child) -{ - _updateChild = child; -} - -int UIListView::getUpdateDataIndex() -{ - return _updateDataIndex; -} - -void UIListView::setUpdateDataIndex(int index) -{ - _updateDataIndex = index; -} - -bool UIListView::getUpdateSuccess() -{ - return _updateSuccess; -} - -void UIListView::setUpdateSuccess(bool sucess) -{ - _updateSuccess = sucess; -} - -void UIListView::clearCollectOverArray() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: - _overTopArray->removeAllObjects(); - _overBottomArray->removeAllObjects(); - break; - - case LISTVIEW_DIR_HORIZONTAL: - _overLeftArray->removeAllObjects(); - _overRightArray->removeAllObjects(); - break; - - default: - break; - } -} - -void UIListView::collectOverTopChild() -{ - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - _overTopArray->addObject(child); - } - } -} - -void UIListView::collectOverBottomChild() -{ - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - _overBottomArray->addObject(child); - } - } -} - -void UIListView::collectOverLeftChild() -{ - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - _overLeftArray->addObject(child); - } - } -} - -void UIListView::collectOverRightChild() -{ - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int times = arrayChildren->num; - for (int i = 0; i < times; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - if (child_left >= scroll_right) - { - _overRightArray->addObject(child); - } - } -} - -void UIListView::setLoopPosition() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overTopArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overTopArray->getObjectAtIndex(i)); - - if (i == 0) - { - float height = child->getSize().height; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? height / 2 : height; - float y = _topBoundary - _disBoundaryToChild_0 - offset; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overTopArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - else - { - float scroll_top = _topBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_bottom = child->getBottomInParent(); - - if (child_bottom >= scroll_top) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y - _disBetweenChild)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overBottomArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overBottomArray->getObjectAtIndex(i)); - - if (i == 0) - { - float y = _bottomBoundary + _disBoundaryToChild_0 - _disBetweenChild; - child->setPosition(Point(child->getPosition().x, y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overBottomArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(child->getPosition().x, prev_child->getPosition().y + _disBetweenChild)); - } - } - } - else - { - float scroll_bottom = _bottomBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_top = child->getTopInParent(); - - if (child_top <= scroll_bottom) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(child->getPosition().x, next_child->getPosition().y + _disBetweenChild)); - } - } - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overLeftArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overLeftArray->getObjectAtIndex(i)); - - if (i == 0) - { - float width = child->getSize().width; - float offset = (child->getWidgetType() == WidgetTypeWidget) ? (width / 2) : 0; - float x = _leftBoundary + _disBoundaryToChild_0 + width + offset; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overLeftArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_left = _leftBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_right = child->getRightInParent(); - - if (child_right <= scroll_left) - { - int index = (i == 0) ? (count - 1) : (i - 1); - UIWidget* prev_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(prev_child->getPosition().x + _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - ccArray* arrayChildren = _children->data; - unsigned int childrenCount = arrayChildren->num; - - if (_overRightArray->count() == childrenCount) - { - unsigned int count = childrenCount; - for (unsigned int i = 0; i < count; ++i) - { - UIWidget* child = dynamic_cast(_overRightArray->getObjectAtIndex(i)); - - if (i == 0) - { - float x = _rightBoundary - _disBoundaryToChild_0 + _disBetweenChild; - child->setPosition(Point(x, child->getPosition().y)); - } - else - { - UIWidget* prev_child = dynamic_cast(_overRightArray->getObjectAtIndex(i - 1)); - child->setPosition(Point(prev_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - else - { - float scroll_right = _rightBoundary; - - ccArray* arrayChildren = _children->data; - int count = arrayChildren->num; - for (int i = count - 1; i >= 0; --i) - { - UIWidget* child = dynamic_cast(arrayChildren->arr[i]); - float child_left = child->getLeftInParent(); - - if (child_left >= scroll_right) - { - int index = (i == count - 1) ? 0 : (i + 1); - UIWidget* next_child = dynamic_cast(arrayChildren->arr[index]); - child->setPosition(Point(next_child->getPosition().x - _disBetweenChild, child->getPosition().y)); - } - } - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::updateChild() -{ - switch (_direction) - { - case LISTVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_UP: // up - { - int count = _overTopArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_DOWN: // down - { - int count = _overBottomArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - case LISTVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) - { - case LISTVIEW_MOVE_DIR_LEFT: // left - { - int count = _overLeftArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - case LISTVIEW_MOVE_DIR_RIGHT: // right - { - int count = _overRightArray->count(); - for (int i = 0; i < count; ++i) - { - pushChildToPool(); - getAndCallback(); - } - } - break; - - default: - break; - } - break; - - default: - break; - } -} - -void UIListView::initChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_INIT_CHILD); - } -} - -void UIListView::updateChildEvent() -{ - if (_eventListener && _eventSelector) - { - (_eventListener->*_eventSelector)(this, LISTVIEW_EVENT_UPDATE_CHILD); - } -} - -void UIListView::addEventListenter(Object *target, SEL_ListViewEvent selector) -{ - _eventListener = target; - _eventSelector = selector; + UIScrollView::onSizeChanged(); + refreshView(); } const char* UIListView::getDescription() const { - return "ListView"; + return "ListViewEx"; } +UIWidget* UIListView::createCloneInstance() +{ + return UIListView::create(); +} -} \ No newline at end of file +void UIListView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayItems = dynamic_cast(model)->getItems()->data; + int length = arrayItems->num; + for (int i=0; iarr[i]); + pushBackCustomItem(item->clone()); + } +} + +void UIListView::copySpecialProperties(UIWidget *widget) +{ + UIListView* listViewEx = dynamic_cast(widget); + if (listViewEx) + { + UIScrollView::copySpecialProperties(widget); + setItemModel(listViewEx->_model); + setItemsMargin(listViewEx->_itemsMargin); + setGravity(listViewEx->_gravity); + } +} + +} diff --git a/cocos/gui/UIListView.h b/cocos/gui/UIListView.h index 8830db6209..c78d06ace2 100644 --- a/cocos/gui/UIListView.h +++ b/cocos/gui/UIListView.h @@ -22,226 +22,156 @@ THE SOFTWARE. ****************************************************************************/ + #ifndef __UILISTVIEW_H__ #define __UILISTVIEW_H__ -/* gui mark */ -#include "gui/Layout.h" -/**/ +#include "gui/UIScrollView.h" -namespace gui { - -/** - * list view direction - */ -typedef enum LISTVIEW_DIR -{ - LISTVIEW_DIR_NONE, - LISTVIEW_DIR_VERTICAL, - LISTVIEW_DIR_HORIZONTAL -}ListViewDirection; - -/** - * list view scroll direction - */ -typedef enum LISTVIEW_MOVE_DIR -{ - LISTVIEW_MOVE_DIR_NONE, - LISTVIEW_MOVE_DIR_UP, - LISTVIEW_MOVE_DIR_DOWN, - LISTVIEW_MOVE_DIR_LEFT, - LISTVIEW_MOVE_DIR_RIGHT, -}ListViewMoveDirection; +namespace gui{ typedef enum { - LISTVIEW_EVENT_INIT_CHILD, - LISTVIEW_EVENT_UPDATE_CHILD, -}ListViewEventType; + LISTVIEW_GRAVITY_LEFT, + LISTVIEW_GRAVITY_RIGHT, + LISTVIEW_GRAVITY_CENTER_HORIZONTAL, + + LISTVIEW_GRAVITY_TOP, + LISTVIEW_GRAVITY_BOTTOM, + LISTVIEW_GRAVITY_CENTER_VERTICAL, +}ListViewGravity; -/** - * list view event - */ -typedef void (cocos2d::Object::*SEL_ListViewEvent)(cocos2d::Object*, ListViewEventType); -#define listvieweventselector(_SELECTOR)(SEL_ListViewEvent)(&_SELECTOR) - -class UIListView : public Layout +class UIListView : public UIScrollView { + public: + + /** + * Default constructor + */ UIListView(); + + /** + * Default destructor + */ virtual ~UIListView(); + + /** + * Allocates and initializes. + */ static UIListView* create(); /** - * add widget child override + * Sets a item model for listview + * + * A model will be cloned for adding default item. + * + * @param model item model for listview */ - virtual bool addChild(UIWidget* widget); - /** - * remove all widget children override - */ - virtual void removeAllChildren(); - /** - * remove widget child override - */ - virtual bool removeChild(UIWidget* child); - - virtual bool onTouchBegan(const cocos2d::Point &touchPoint); - virtual void onTouchMoved(const cocos2d::Point &touchPoint); - virtual void onTouchEnded(const cocos2d::Point &touchPoint); - virtual void onTouchCancelled(const cocos2d::Point &touchPoint); - virtual void onTouchLongClicked(const cocos2d::Point &touchPoint); + void setItemModel(UIWidget* model); /** - * set and get direction + * Push back a default item(create by a cloned model) into listview. */ - void setDirection(ListViewDirection dir); - ListViewDirection getDirection(); + void pushBackDefaultItem(); /** - * initialze data length - * and create children with parameter length + * Insert a default item(create by a cloned model) into listview. */ - void initChildWithDataLength(int length); - /** - * get data length - */ - int getDataLength(); + void insertDefaultItem(int index); /** - * update child function whetn trigger update child event + * Push back custom item into listview. */ - /** - * get update widget child - */ - UIWidget* getUpdateChild(); - /** - * get update data index - */ - int getUpdateDataIndex(); - /** - * get and set update success or not - */ - bool getUpdateSuccess(); - void setUpdateSuccess(bool sucess); + void pushBackCustomItem(UIWidget* item); /** - * add event call-back function + * Insert custom item into listview. */ - /** - * add event - */ - void addEventListenter(cocos2d::Object* target, SEL_ListViewEvent selector); - - /* gui mark */ - /** - * get and set degree range for checking move or not with scrolling - */ - /**/ - virtual void update(float dt); - - virtual void doLayout(){}; + void insertCustomItem(UIWidget* item, int index); /** - * Returns the "class name" of widget. + * Removes the last item of listview. */ + void removeLastItem(); + + /** + * Removes a item whose index is same as the parameter. + * + * @param index of item. + */ + void removeItem(int index); + + /** + * Returns a item whose index is same as the parameter. + * + * @param index of item. + * + * @return the item widget. + */ + UIWidget* getItem(unsigned int index); + + /** + * Returns the item container. + */ + cocos2d::Array* getItems(); + + /** + * Returns the index of item. + * + * @param item the item which need to be checked. + * + * @return the index of item. + */ + unsigned int getIndex(UIWidget* item) const; + + /** + * Changes the gravity of listview. + * @see ListViewGravity + */ + void setGravity(ListViewGravity gravity); + + /** + * Changes the margin between each item. + * + * @param margin + */ + void setItemsMargin(float margin); + + /** + * Refresh the view of list. + * + * If you change the data, you need to call this mathod. + */ + void refreshView(); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + virtual void setDirection(SCROLLVIEW_DIR dir); + virtual const char* getDescription() const; + protected: virtual bool init(); - + void updateInnerContainerSize(); + void remedyLayoutParameter(UIWidget* item); virtual void onSizeChanged(); - - void setMoveDirection(ListViewMoveDirection dir); - ListViewMoveDirection getMoveDirection(); - - virtual void resetProperty(); - - virtual void handlePressLogic(const cocos2d::Point &touchPoint); - virtual void handleMoveLogic(const cocos2d::Point &touchPoint); - virtual void handleReleaseLogic(const cocos2d::Point &touchPoint); - virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - /* gui mark */ -// virtual bool isInScrollDegreeRange(UIWidget* widget); - /**/ - virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); - - void moveChildren(float offset); - virtual bool scrollChildren(float touchOffset); - void autoScrollChildren(float dt); - float getCurAutoScrollDistance(float time); - void startAutoScrollChildren(float v); - void stopAutoScrollChildren(); - void recordSlidTime(float dt); - void startRecordSlidAction(); - virtual void endRecordSlidAction(); - - UIWidget* getCheckPositionChild(); - UIWidget* getChildFromUpdatePool(); - void pushChildToPool(); - void getAndCallback(); - - void setUpdateChild(UIWidget* child); - void setUpdateDataIndex(int index); - void clearCollectOverArray(); - void collectOverTopChild(); - void collectOverBottomChild(); - void collectOverLeftChild(); - void collectOverRightChild(); - void setLoopPosition(); - void updateChild(); - - void initChildEvent(); - void updateChildEvent(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: - ListViewDirection _direction; - ListViewMoveDirection _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test - float _leftBoundary; - float _rightBoundary; - - bool _autoScroll; - - float _autoScrollOriginalSpeed; - float _autoScrollAcceleration; - - bool _bePressed; - float _slidTime; - cocos2d::Point _moveChildPoint; - float _childFocusCancelOffset; - - cocos2d::Object* _eventListener; - SEL_ListViewEvent _eventSelector; - - cocos2d::Array* _childPool; - cocos2d::Array* _updatePool; - - int _dataLength; - int _begin; - int _end; - UIWidget* _updateChild; - int _updateDataIndex; - bool _updateSuccess; - - cocos2d::Array* _overTopArray; - cocos2d::Array* _overBottomArray; - cocos2d::Array* _overLeftArray; - cocos2d::Array* _overRightArray; - - float _disBoundaryToChild_0; - float _disBetweenChild; - - /* gui mark */ - float _scrollDegreeRange; - /**/ + UIWidget* _model; + cocos2d::Array* _items; + ListViewGravity _gravity; + float _itemsMargin; }; } - -#endif /* defined(__Test__UIListView__) */ +#endif /* defined(__UIListView__) */ diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index 6d74be86c4..09b78c7b25 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -25,11 +25,9 @@ #include "gui/UILoadingBar.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" - using namespace cocos2d; - using namespace cocos2d::extension; - namespace gui { + #define DYNAMIC_CAST_CCSPRITE dynamic_cast(_barRenderer) UILoadingBar::UILoadingBar(): @@ -38,10 +36,10 @@ _percent(100), _totalLength(0), _barRenderer(NULL), _renderBarTexType(UI_TEX_TYPE_LOCAL), -_barRendererTextureSize(Size::ZERO), +_barRendererTextureSize(cocos2d::Size::ZERO), _scale9Enabled(false), _prevIgnoreSize(true), -_capInsets(Rect::ZERO), +_capInsets(cocos2d::Rect::ZERO), _textureFile("") { } @@ -66,9 +64,9 @@ UILoadingBar* UILoadingBar::create() void UILoadingBar::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); _renderer->addChild(_barRenderer); - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0,0.5)); } void UILoadingBar::setDirection(LoadingBarType dir) @@ -82,19 +80,19 @@ void UILoadingBar::setDirection(LoadingBarType dir) switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); - _barRenderer->setPosition(Point(-_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); - _barRenderer->setPosition(Point(_totalLength*0.5f,0.0f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength*0.5f,0.0f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -118,21 +116,23 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->initWithFile(texture); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->setCapInsets(_capInsets); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); } break; default: @@ -140,31 +140,31 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } - _barRendererTextureSize.width = _barRenderer->getContentSize().width; - _barRendererTextureSize.height = _barRenderer->getContentSize().height; + _barRendererTextureSize = _barRenderer->getContentSize(); switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setAnchorPoint(Point(0.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(0.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(false); + dynamic_cast(_barRenderer)->setFlippedX(false); } break; case LoadingBarTypeRight: - _barRenderer->setAnchorPoint(Point(1.0f,0.5f)); + _barRenderer->setAnchorPoint(cocos2d::Point(1.0f,0.5f)); if (!_scale9Enabled) { - dynamic_cast(_barRenderer)->setFlippedX(true); + dynamic_cast(_barRenderer)->setFlippedX(true); } break; } @@ -182,11 +182,11 @@ void UILoadingBar::setScale9Enabled(bool enabled) _barRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); } loadTexture(_textureFile.c_str(),_renderBarTexType); _renderer->addChild(_barRenderer); @@ -203,14 +203,14 @@ void UILoadingBar::setScale9Enabled(bool enabled) setCapInsets(_capInsets); } -void UILoadingBar::setCapInsets(const Rect &capInsets) +void UILoadingBar::setCapInsets(const cocos2d::Rect &capInsets) { _capInsets = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } void UILoadingBar::setPercent(int percent) @@ -231,10 +231,10 @@ void UILoadingBar::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = DYNAMIC_CAST_CCSPRITE; + cocos2d::Sprite* barNode = DYNAMIC_CAST_CCSPRITE; if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -249,7 +249,7 @@ void UILoadingBar::setPercent(int percent) } else { - dynamic_cast(_barRenderer)->setTextureRect(Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setTextureRect(cocos2d::Rect(x, y, _barRendererTextureSize.width * res, _barRendererTextureSize.height)); } } @@ -272,12 +272,12 @@ void UILoadingBar::ignoreContentAdaptWithSize(bool ignore) } } -const Size& UILoadingBar::getContentSize() const +const cocos2d::Size& UILoadingBar::getContentSize() const { return _barRendererTextureSize; } -Node* UILoadingBar::getVirtualRenderer() +cocos2d::Node* UILoadingBar::getVirtualRenderer() { return _barRenderer; } @@ -303,7 +303,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() else { - Size textureSize = _barRenderer->getContentSize(); + cocos2d::Size textureSize = _barRendererTextureSize; if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -318,10 +318,10 @@ void UILoadingBar::barRendererScaleChangedWithSize() switch (_barType) { case LoadingBarTypeLeft: - _barRenderer->setPosition(Point(-_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(-_totalLength * 0.5f, 0.0f)); break; case LoadingBarTypeRight: - _barRenderer->setPosition(Point(_totalLength * 0.5f, 0.0f)); + _barRenderer->setPosition(cocos2d::Point(_totalLength * 0.5f, 0.0f)); break; default: break; @@ -331,7 +331,7 @@ void UILoadingBar::barRendererScaleChangedWithSize() void UILoadingBar::setScale9Scale() { float width = (float)(_percent) / 100 * _totalLength; - dynamic_cast(_barRenderer)->setPreferredSize(Size(width, _barRendererTextureSize.height)); + dynamic_cast(_barRenderer)->setPreferredSize(cocos2d::Size(width, _size.height)); } const char* UILoadingBar::getDescription() const @@ -339,4 +339,22 @@ const char* UILoadingBar::getDescription() const return "LoadingBar"; } +UIWidget* UILoadingBar::createCloneInstance() +{ + return UILoadingBar::create(); +} + +void UILoadingBar::copySpecialProperties(UIWidget *widget) +{ + UILoadingBar* loadingBar = dynamic_cast(widget); + if (loadingBar) + { + _prevIgnoreSize = loadingBar->_prevIgnoreSize; + setScale9Enabled(loadingBar->_scale9Enabled); + loadTexture(loadingBar->_textureFile.c_str(), loadingBar->_renderBarTexType); + setCapInsets(loadingBar->_capInsets); + setPercent(loadingBar->_percent); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UILoadingBar.h b/cocos/gui/UILoadingBar.h index b67e7314f5..81c5722b4b 100644 --- a/cocos/gui/UILoadingBar.h +++ b/cocos/gui/UILoadingBar.h @@ -34,7 +34,10 @@ typedef enum LoadingBarTypeLeft, LoadingBarTypeRight }LoadingBarType; - +/** +* @js NA +* @lua NA +*/ class UILoadingBar : public UIWidget { public: @@ -126,6 +129,8 @@ protected: virtual void onSizeChanged(); void setScale9Scale(); void barRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: LoadingBarType _barType; int _percent; diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 0fc6558975..8498e79d88 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -24,8 +24,6 @@ #include "gui/UIPageView.h" - using namespace cocos2d; - namespace gui { UIPageView::UIPageView(): @@ -33,9 +31,8 @@ _curPageIdx(0), _pages(NULL), _touchMoveDir(PAGEVIEW_TOUCHLEFT), _touchStartLocation(0.0f), -_touchEndLocation(0.0f), _touchMoveStartLocation(0.0f), -_movePagePoint(Point::ZERO), +_movePagePoint(cocos2d::Point::ZERO), _leftChild(NULL), _rightChild(NULL), _leftBoundary(0.0f), @@ -52,7 +49,8 @@ _eventSelector(NULL) UIPageView::~UIPageView() { - _pages->release(); + _pages->removeAllObjects(); + CC_SAFE_RELEASE(_pages); } UIPageView* UIPageView::create() @@ -69,12 +67,13 @@ UIPageView* UIPageView::create() bool UIPageView::init() { - if (Layout::init()) + if (UILayout::init()) { - _pages = CCArray::create(); + _pages = cocos2d::Array::create(); _pages->retain(); setClippingEnabled(true); setUpdateEnabled(true); + setTouchEnabled(true); return true; } return false; @@ -86,6 +85,10 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { return; } + if (pageIdx < 0) + { + return; + } int pageCount = _pages->count(); if (pageIdx < 0 || pageIdx >= pageCount) { @@ -95,30 +98,29 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate { CCLOG("pageIdx is %d, it will be added as page id [%d]",pageIdx,pageCount); } - Layout* newPage = createPage(); + UILayout* newPage = createPage(); newPage->addChild(widget); addPage(newPage); } } else { - Layout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); + UILayout * page = dynamic_cast(_pages->getObjectAtIndex(pageIdx)); if (page) { page->addChild(widget); } } - } -Layout* UIPageView::createPage() +UILayout* UIPageView::createPage() { - Layout* newPage = Layout::create(); + UILayout* newPage = UILayout::create(); newPage->setSize(getSize()); return newPage; } -void UIPageView::addPage(Layout* page) +void UIPageView::addPage(UILayout* page) { if (!page) { @@ -132,20 +134,20 @@ void UIPageView::addPage(Layout* page) { return; } - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - page->setPosition(Point(getPositionXByIndex(_pages->count()), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(_pages->count()), 0)); _pages->addObject(page); addChild(page); updateBoundaryPages(); } -void UIPageView::insertPage(Layout* page, int idx) +void UIPageView::insertPage(UILayout* page, int idx) { if (idx < 0) { @@ -172,27 +174,27 @@ void UIPageView::insertPage(Layout* page, int idx) else { _pages->insertObject(page, idx); - page->setPosition(Point(getPositionXByIndex(idx), 0)); + page->setPosition(cocos2d::Point(getPositionXByIndex(idx), 0)); addChild(page); - Size pSize = page->getSize(); - Size pvSize = getSize(); + cocos2d::Size pSize = page->getSize(); + cocos2d::Size pvSize = getSize(); if (!pSize.equals(pvSize)) { CCLOG("page size does not match pageview size, it will be force sized!"); page->setSize(pvSize); } - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i=(idx+1); i(arrayPages->arr[i]); - Point formerPos = behindPage->getPosition(); - behindPage->setPosition(Point(formerPos.x+getSize().width, 0)); + cocos2d::Point formerPos = behindPage->getPosition(); + behindPage->setPosition(cocos2d::Point(formerPos.x+getSize().width, 0)); } updateBoundaryPages(); } } -void UIPageView::removePage(Layout* page) +void UIPageView::removePage(UILayout* page) { if (!page) { @@ -209,7 +211,7 @@ void UIPageView::removePageAtIndex(int index) { return; } - Layout* page = dynamic_cast(_pages->getObjectAtIndex(index)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(index)); if (page) { removePage(page); @@ -222,6 +224,7 @@ void UIPageView::updateBoundaryPages() { _leftChild = NULL; _rightChild = NULL; + return; } _leftChild = dynamic_cast(_pages->getObjectAtIndex(0)); _rightChild = dynamic_cast(_pages->getLastObject()); @@ -234,7 +237,7 @@ float UIPageView::getPositionXByIndex(int idx) bool UIPageView::addChild(UIWidget* widget) { - return Layout::addChild(widget); + return UILayout::addChild(widget); } bool UIPageView::removeChild(UIWidget* widget) @@ -242,14 +245,14 @@ bool UIPageView::removeChild(UIWidget* widget) if (_pages->containsObject(widget)) { _pages->removeObject(widget); - return Layout::removeChild(widget); + return UILayout::removeChild(widget); } return false; } void UIPageView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _rightBoundary = getSize().width; updateChildrenSize(); updateChildrenPosition(); @@ -262,10 +265,10 @@ void UIPageView::updateChildrenSize() return; } - Size selfSize = getSize(); - for (int i = 0; i < _pages->count(); i++) + cocos2d::Size selfSize = getSize(); + for (unsigned int i=0; i<_pages->count(); i++) { - Layout* page = dynamic_cast(_pages->getObjectAtIndex(i)); + UILayout* page = dynamic_cast(_pages->getObjectAtIndex(i)); page->setSize(selfSize); } } @@ -288,18 +291,18 @@ void UIPageView::updateChildrenPosition() _curPageIdx = pageCount-1; } float pageWidth = getSize().width; - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; for (int i=0; i(arrayPages->arr[i]); - page->setPosition(Point((i-_curPageIdx)*pageWidth, 0)); + UILayout* page = dynamic_cast(arrayPages->arr[i]); + page->setPosition(cocos2d::Point((i-_curPageIdx)*pageWidth, 0)); } } void UIPageView::removeAllChildren() { _pages->removeAllObjects(); - Layout::removeAllChildren(); + UILayout::removeAllChildren(); } void UIPageView::scrollToPage(int idx) @@ -330,13 +333,16 @@ void UIPageView::update(float dt) step = -_autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance += step; } scrollPages(-step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } break; @@ -348,13 +354,16 @@ void UIPageView::update(float dt) step = _autoScrollDistance; _autoScrollDistance = 0.0f; _isAutoScrolling = false; - pageTurningEvent(); } else { _autoScrollDistance -= step; } scrollPages(step); + if (!_isAutoScrolling) + { + pageTurningEvent(); + } break; } default: @@ -363,14 +372,14 @@ void UIPageView::update(float dt) } } -bool UIPageView::onTouchBegan(const Point &touchPoint) +bool UIPageView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIPageView::onTouchMoved(const Point &touchPoint) +void UIPageView::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -387,15 +396,15 @@ void UIPageView::onTouchMoved(const Point &touchPoint) } } -void UIPageView::onTouchEnded(const Point &touchPoint) +void UIPageView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } void UIPageView::movePages(float offset) { - ccArray* arrayPages = _pages->data; + cocos2d::ccArray* arrayPages = _pages->data; int length = arrayPages->num; for (int i = 0; i < length; i++) { @@ -447,21 +456,21 @@ bool UIPageView::scrollPages(float touchOffset) return true; } -void UIPageView::onTouchCancelled(const Point &touchPoint) +void UIPageView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); } -void UIPageView::handlePressLogic(const Point &touchPoint) +void UIPageView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); _touchMoveStartLocation = nsp.x; _touchStartLocation = nsp.x; } -void UIPageView::handleMoveLogic(const Point &touchPoint) +void UIPageView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); float offset = 0.0; float moveX = nsp.x; offset = moveX - _touchMoveStartLocation; @@ -477,12 +486,16 @@ void UIPageView::handleMoveLogic(const Point &touchPoint) scrollPages(offset); } -void UIPageView::handleReleaseLogic(const Point &touchPoint) +void UIPageView::handleReleaseLogic(const cocos2d::Point &touchPoint) { + if (_pages->count() <= 0) + { + return; + } UIWidget* curPage = dynamic_cast(_pages->getObjectAtIndex(_curPageIdx)); if (curPage) { - Point curPagePos = curPage->getPosition(); + cocos2d::Point curPagePos = curPage->getPosition(); int pageCount = _pages->count(); float curPageLocation = curPagePos.x; float pageWidth = getSize().width; @@ -516,12 +529,12 @@ void UIPageView::handleReleaseLogic(const Point &touchPoint) } } -void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const Point &touchPoint) +void UIPageView::checkChildInfo(int handleState,UIWidget* sender, const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } -void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -556,7 +569,7 @@ void UIPageView::pageTurningEvent() } } -void UIPageView::addEventListener(Object *target, SEL_PageViewEvent selector) +void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -567,9 +580,39 @@ int UIPageView::getCurPageIndex() const return _curPageIdx; } +cocos2d::Array* UIPageView::getPages() +{ + return _pages; +} + const char* UIPageView::getDescription() const { return "PageView"; } +UIWidget* UIPageView::createCloneInstance() +{ + return UIPageView::create(); +} + +void UIPageView::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayPages = dynamic_cast(model)->getPages()->data; + int length = arrayPages->num; + for (int i=0; iarr[i]); + addPage(dynamic_cast(page->clone())); + } +} + +void UIPageView::copySpecialProperties(UIWidget *widget) +{ + UIPageView* pageView = dynamic_cast(widget); + if (pageView) + { + UILayout::copySpecialProperties(widget); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIPageView.h b/cocos/gui/UIPageView.h index e8d3d5192d..ec78df8bbd 100644 --- a/cocos/gui/UIPageView.h +++ b/cocos/gui/UIPageView.h @@ -25,7 +25,7 @@ #ifndef __UIPAGEVIEW_H__ #define __UIPAGEVIEW_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -43,7 +43,7 @@ typedef enum { PAGEVIEW_TOUCHRIGHT }PVTouchDir; -class UIPageView : public Layout , public UIScrollInterface +class UIPageView : public UILayout , public UIScrollInterface { public: @@ -78,21 +78,21 @@ public: * * @param page page to be added to pageview. */ - void addPage(Layout* page); + void addPage(UILayout* page); /** * Inert a page to pageview. * * @param page page to be added to pageview. */ - void insertPage(Layout* page, int idx); + void insertPage(UILayout* page, int idx); /** * Remove a page of pageview. * * @param page page which will be removed. */ - void removePage(Layout* page); + void removePage(UILayout* page); /** * Remove a page at index of pageview. @@ -115,8 +115,11 @@ public: */ int getCurPageIndex() const; + cocos2d::Array* getPages(); + // event void addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector); + //override "removeChild" method of widget. virtual bool removeChild(UIWidget* widget); @@ -140,15 +143,16 @@ public: virtual void update(float dt); virtual void doLayout(){}; - + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual bool addChild(UIWidget* widget); virtual bool init(); - Layout* createPage(); + UILayout* createPage(); float getPositionXByIndex(int idx); void updateBoundaryPages(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -162,14 +166,15 @@ protected: void updateChildrenSize(); void updateChildrenPosition(); virtual void onSizeChanged(); - - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: int _curPageIdx; cocos2d::Array* _pages; PVTouchDir _touchMoveDir; float _touchStartLocation; - float _touchEndLocation; float _touchMoveStartLocation; cocos2d::Point _movePagePoint; UIWidget* _leftChild; @@ -183,6 +188,7 @@ protected: float _childFocusCancelOffset; cocos2d::Object* _eventListener; SEL_PageViewEvent _eventSelector; + }; } diff --git a/cocos/gui/UIRootWidget.cpp b/cocos/gui/UIRootWidget.cpp index f6bf7359f0..0b7581287f 100644 --- a/cocos/gui/UIRootWidget.cpp +++ b/cocos/gui/UIRootWidget.cpp @@ -24,8 +24,6 @@ #include "gui/UIRootWidget.h" - using namespace cocos2d; - namespace gui { UIRootWidget::UIRootWidget() @@ -50,9 +48,9 @@ UIRootWidget* UIRootWidget::create() bool UIRootWidget::init() { - if (Layout::init()) + if (UILayout::init()) { - setSize(Director::getInstance()->getWinSize()); + setSize(cocos2d::Director::getInstance()->getWinSize()); return true; } return false; diff --git a/cocos/gui/UIRootWidget.h b/cocos/gui/UIRootWidget.h index f4bff4955f..dc93ac4645 100644 --- a/cocos/gui/UIRootWidget.h +++ b/cocos/gui/UIRootWidget.h @@ -25,11 +25,15 @@ #ifndef __UIROOTWIDGET_H__ #define __UIROOTWIDGET_H__ -#include "gui/Layout.h" +#include "gui/UILayout.h" namespace gui { - -class UIRootWidget : public Layout + +/** +* @js NA +* @lua NA +*/ +class UIRootWidget : public UILayout { public: /** diff --git a/cocos/gui/UIScrollInterface.h b/cocos/gui/UIScrollInterface.h index 2e835982fd..dfff4cd66c 100644 --- a/cocos/gui/UIScrollInterface.h +++ b/cocos/gui/UIScrollInterface.h @@ -36,7 +36,6 @@ protected: virtual void handleMoveLogic(const cocos2d::Point &touchPoint) = 0; virtual void handleReleaseLogic(const cocos2d::Point &touchPoint) = 0; virtual void interceptTouchEvent(int handleState, UIWidget* sender, const cocos2d::Point &touchPoint) = 0; -// virtual bool isInScrollDegreeRange(UIWidget* widget) = 0; }; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index bdb3d45a21..1270c78682 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -23,34 +23,52 @@ ****************************************************************************/ #include "gui/UIScrollView.h" -#include "gui/UILayer.h" - - using namespace cocos2d; namespace gui { +#define AUTOSCROLLMAXSPEED 1000.0f + +const cocos2d::Point SCROLLDIR_UP = cocos2d::Point(0.0f, 1.0f); +const cocos2d::Point SCROLLDIR_DOWN = cocos2d::Point(0.0f, -1.0f); +const cocos2d::Point SCROLLDIR_LEFT = cocos2d::Point(-1.0f, 0.0f); +const cocos2d::Point SCROLLDIR_RIGHT = cocos2d::Point(1.0f, 0.0f); + UIScrollView::UIScrollView(): _innerContainer(NULL), _direction(SCROLLVIEW_DIR_VERTICAL), -_moveDirection(SCROLLVIEW_MOVE_DIR_NONE), -_touchStartLocation(0.0f), -_touchEndLocation(0.0f), -_touchMoveStartLocation(0.0f), +_touchBeganPoint(cocos2d::Point::ZERO), +_touchMovedPoint(cocos2d::Point::ZERO), +_touchEndedPoint(cocos2d::Point::ZERO), +_touchMovingPoint(cocos2d::Point::ZERO), +_autoScrollDir(cocos2d::Point::ZERO), _topBoundary(0.0f), _bottomBoundary(0.0f), _leftBoundary(0.0f), _rightBoundary(0.0f), -_topEnd(false), -_bottomEnd(false), -_leftEnd(false), -_rightEnd(false), +_bounceTopBoundary(0.0f), +_bounceBottomBoundary(0.0f), +_bounceLeftBoundary(0.0f), +_bounceRightBoundary(0.0f), _autoScroll(false), +_autoScrollAddUpTime(0.0f), _autoScrollOriginalSpeed(0.0f), -_autoScrollAcceleration(600.0f), +_autoScrollAcceleration(-1000.0f), +_isAutoScrollSpeedAttenuated(false), +_needCheckAutoScrollDestination(false), +_autoScrollDestination(cocos2d::Point::ZERO), _bePressed(false), _slidTime(0.0f), -_moveChildPoint(Point::ZERO), +_moveChildPoint(cocos2d::Point::ZERO), _childFocusCancelOffset(5.0f), +_leftBounceNeeded(false), +_topBounceNeeded(false), +_rightBounceNeeded(false), +_bottomBounceNeeded(false), +_bounceEnabled(false), +_bouncing(false), +_bounceDir(cocos2d::Point::ZERO), +_bounceOriginalSpeed(0.0f), +_inertiaScrollEnabled(true), _eventListener(NULL), _eventSelector(NULL) { @@ -73,22 +91,9 @@ UIScrollView* UIScrollView::create() return NULL; } -void UIScrollView::releaseResoures() -{ - setUpdateEnabled(false); - removeAllChildren(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); - - Layout::removeChild(_innerContainer); - - _children->release(); -} - bool UIScrollView::init() { - if (Layout::init()) + if (UILayout::init()) { setUpdateEnabled(true); setTouchEnabled(true); @@ -101,29 +106,36 @@ bool UIScrollView::init() void UIScrollView::initRenderer() { - Layout::initRenderer(); - _innerContainer = Layout::create(); - Layout::addChild(_innerContainer); + UILayout::initRenderer(); + _innerContainer = UILayout::create(); + UILayout::addChild(_innerContainer); } void UIScrollView::onSizeChanged() { - Layout::onSizeChanged(); + UILayout::onSizeChanged(); _topBoundary = _size.height; _rightBoundary = _size.width; - Size innerSize = _innerContainer->getSize(); + float bounceBoundaryParameterX = _size.width / 3.0f; + float bounceBoundaryParameterY = _size.height / 3.0f; + _bounceTopBoundary = _size.height - bounceBoundaryParameterY; + _bounceBottomBoundary = bounceBoundaryParameterY; + _bounceLeftBoundary = bounceBoundaryParameterX; + _bounceRightBoundary = _size.width - bounceBoundaryParameterX; + cocos2d::Size innerSize = _innerContainer->getSize(); float orginInnerSizeWidth = innerSize.width; float orginInnerSizeHeight = innerSize.height; float innerSizeWidth = MAX(orginInnerSizeWidth, _size.width); float innerSizeHeight = MAX(orginInnerSizeHeight, _size.height); - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + _innerContainer->setPosition(cocos2d::Point(0, _size.height - _innerContainer->getSize().height)); } -void UIScrollView::setInnerContainerSize(const Size &size) +void UIScrollView::setInnerContainerSize(const cocos2d::Size &size) { float innerSizeWidth = _size.width; float innerSizeHeight = _size.height; + cocos2d::Size originalInnerSize = _innerContainer->getSize(); if (size.width < _size.width) { CCLOG("Inner width <= scrollview width, it will be force sized!"); @@ -140,11 +152,45 @@ void UIScrollView::setInnerContainerSize(const Size &size) { innerSizeHeight = size.height; } - _innerContainer->setSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Point(0, _size.height - _innerContainer->getSize().height)); + _innerContainer->setSize(cocos2d::Size(innerSizeWidth, innerSizeHeight)); + + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.height - newInnerSize.height; + scrollChildren(0.0f, offset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: + { + if (_innerContainer->getRightInParent() <= _size.width) + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offset = originalInnerSize.width - newInnerSize.width; + scrollChildren(offset, 0.0f); + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Size newInnerSize = _innerContainer->getSize(); + float offsetY = originalInnerSize.height - newInnerSize.height; + float offsetX = 0.0f; + if (_innerContainer->getRightInParent() <= _size.width) + { + offsetX = originalInnerSize.width - newInnerSize.width; + } + scrollChildren(offsetX, offsetY); + break; + } + default: + break; + } } -const Size& UIScrollView::getInnerContainerSize() const +const cocos2d::Size& UIScrollView::getInnerContainerSize() const { return _innerContainer->getSize(); } @@ -164,378 +210,1192 @@ bool UIScrollView::removeChild(UIWidget* child) return _innerContainer->removeChild(child); } -Array* UIScrollView::getChildren() +cocos2d::Array* UIScrollView::getChildren() { return _innerContainer->getChildren(); } -void UIScrollView::moveChildren(float offset) +void UIScrollView::moveChildren(float offsetX, float offsetY) { - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - { - _moveChildPoint.x = _innerContainer->getPosition().x; - _moveChildPoint.y = _innerContainer->getPosition().y + offset; - _innerContainer->setPosition(_moveChildPoint); - break; - } - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - _moveChildPoint.x = _innerContainer->getPosition().x + offset; - _moveChildPoint.y = _innerContainer->getPosition().y; - _innerContainer->setPosition(_moveChildPoint); - break; - } - default: - break; - } + _moveChildPoint = _innerContainer->getPosition() + cocos2d::Point(offsetX, offsetY); + _innerContainer->setPosition(_moveChildPoint); } void UIScrollView::autoScrollChildren(float dt) { - switch (_direction) + float lastTime = _autoScrollAddUpTime; + _autoScrollAddUpTime += dt; + if (_isAutoScrollSpeedAttenuated) { - case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - default: - break; - } - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + float nowSpeed = _autoScrollOriginalSpeed + _autoScrollAcceleration * _autoScrollAddUpTime; + if (nowSpeed <= 0.0f) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + else + { + float timeParam = lastTime * 2 + dt; + float offset = (_autoScrollOriginalSpeed + _autoScrollAcceleration * timeParam * 0.5f) * dt; + float offsetX = offset * _autoScrollDir.x; + float offsetY = offset * _autoScrollDir.y; + if (!scrollChildren(offsetX, offsetY)) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(-curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float curDis = getCurAutoScrollDistance(dt); - if (curDis <= 0) - { - curDis = 0; - stopAutoScrollChildren(); - } - if (!scrollChildren(curDis)) - { - stopAutoScrollChildren(); - } - } - break; - - default: - break; + stopAutoScrollChildren(); + checkNeedBounce(); } - break; - - default: - break; + } + } + else + { + if (_needCheckAutoScrollDestination) + { + float xOffset = _autoScrollDir.x * dt * _autoScrollOriginalSpeed; + float yOffset = _autoScrollDir.y * dt * _autoScrollOriginalSpeed; + bool notDone = checkCustomScrollDestination(&xOffset, &yOffset); + bool scrollCheck = scrollChildren(xOffset, yOffset); + if (!notDone || !scrollCheck) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } + else + { + if (!scrollChildren(_autoScrollDir.x * dt * _autoScrollOriginalSpeed, _autoScrollDir.y * dt * _autoScrollOriginalSpeed)) + { + stopAutoScrollChildren(); + checkNeedBounce(); + } + } } } -void UIScrollView::startAutoScrollChildren(float v) +void UIScrollView::bounceChildren(float dt) { + if (_bounceOriginalSpeed <= 0.0f) + { + stopBounceChildren(); + } + if (!bounceScrollChildren(_bounceDir.x * dt * _bounceOriginalSpeed, _bounceDir.y * dt * _bounceOriginalSpeed)) + { + stopBounceChildren(); + } +} + +bool UIScrollView::checkNeedBounce() +{ + if (!_bounceEnabled) + { + return false; + } + checkBounceBoundary(); + if (_topBounceNeeded || _bottomBounceNeeded || _leftBounceNeeded || _rightBounceNeeded) + { + if (_topBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, _size.height) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded && _rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_topBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(0.0f, _size.height) - cocos2d::Point(0.0f, _innerContainer->getTopInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_bottomBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(0.0f, _innerContainer->getBottomInParent()); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_leftBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point::ZERO - cocos2d::Point(_innerContainer->getLeftInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + else if (_rightBounceNeeded) + { + cocos2d::Point scrollVector = cocos2d::Point(_size.width, 0.0f) - cocos2d::Point(_innerContainer->getRightInParent(), 0.0f); + float orSpeed = scrollVector.getLength()/(0.2f); + _bounceDir = scrollVector.normalize(); + startBounceChildren(orSpeed); + } + return true; + } + return false; +} + +void UIScrollView::checkBounceBoundary() +{ + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos > _bottomBoundary) + { + scrollToBottomEvent(); + _bottomBounceNeeded = true; + } + else + { + _bottomBounceNeeded = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos < _topBoundary) + { + scrollToTopEvent(); + _topBounceNeeded = true; + } + else + { + _topBounceNeeded = false; + } + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos < _rightBoundary) + { + scrollToRightEvent(); + _rightBounceNeeded = true; + } + else + { + _rightBounceNeeded = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos > _leftBoundary) + { + scrollToLeftEvent(); + _leftBounceNeeded = true; + } + else + { + _leftBounceNeeded = false; + } +} + +void UIScrollView::startBounceChildren(float v) +{ + _bounceOriginalSpeed = v; + _bouncing = true; +} + +void UIScrollView::stopBounceChildren() +{ + _bouncing = false; + _bounceOriginalSpeed = 0.0f; + _leftBounceNeeded = false; + _rightBounceNeeded = false; + _topBounceNeeded = false; + _bottomBounceNeeded = false; +} + +void UIScrollView::startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration) +{ + stopAutoScrollChildren(); + _autoScrollDir = dir; + _isAutoScrollSpeedAttenuated = attenuated; _autoScrollOriginalSpeed = v; _autoScroll = true; + _autoScrollAcceleration = acceleration; +} + +void UIScrollView::startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated) +{ + _needCheckAutoScrollDestination = false; + _autoScrollDestination = des; + cocos2d::Point dis = des - _innerContainer->getPosition(); + cocos2d::Point dir = dis.normalize(); + float orSpeed = 0.0f; + float acceleration = -1000.0f; + if (attenuated) + { + acceleration = (-(2 * dis.getLength())) / (time * time); + orSpeed = 2 * dis.getLength() / time; + } + else + { + _needCheckAutoScrollDestination = true; + orSpeed = dis.getLength() / time; + } + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, attenuated, acceleration); +} + +void UIScrollView::jumpToDestination(const cocos2d::Point &des) +{ + float finalOffsetX = des.x; + float finalOffsetY = des.y; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + case SCROLLVIEW_DIR_BOTH: + if (des.y <= 0) + { + finalOffsetY = MAX(des.y, _size.height - _innerContainer->getSize().height); + } + if (des.x <= 0) + { + finalOffsetX = MAX(des.x, _size.width - _innerContainer->getSize().width); + } + break; + default: + break; + } + _innerContainer->setPosition(cocos2d::Point(finalOffsetX, finalOffsetY)); } void UIScrollView::stopAutoScrollChildren() { _autoScroll = false; _autoScrollOriginalSpeed = 0.0f; + _autoScrollAddUpTime = 0.0f; } -float UIScrollView::getCurAutoScrollDistance(float time) +bool UIScrollView::bounceScrollChildren(float touchOffsetX, float touchOffsetY) { - float dt = time; - _autoScrollOriginalSpeed -= _autoScrollAcceleration*dt; - return _autoScrollOriginalSpeed*dt; + bool scrollenabled = true; + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) //first quadrant //bounce to top-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if(touchOffsetX < 0.0f && touchOffsetY > 0.0f) //second quadrant //bounce to top-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) //third quadrant //bounce to bottom-left + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icLefrPos = _innerContainer->getLeftInParent(); + if (icLefrPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLefrPos; + bounceLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) //forth quadrant //bounce to bottom-right + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // bounce to top + { + float realOffsetY = touchOffsetY; + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY >= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + bounceTopEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) //bounce to bottom + { + float realOffsetY = touchOffsetY; + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY <= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + bounceBottomEvent(); + scrollenabled = false; + } + moveChildren(0.0f, realOffsetY); + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) //bounce to right + { + float realOffsetX = touchOffsetX; + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + realOffsetX >= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + bounceRightEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) //bounce to left + { + float realOffsetX = touchOffsetX; + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + realOffsetX <= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + bounceLeftEvent(); + scrollenabled = false; + } + moveChildren(realOffsetX, 0.0f); + } + return scrollenabled; } -bool UIScrollView::scrollChildren(float touchOffset) -{ - float realOffset = touchOffset; - +bool UIScrollView::checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY) +{ + bool scrollenabled = true; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - switch (_moveDirection) - { - case SCROLLVIEW_MOVE_DIR_UP: // up - { - float icBottomPos = _innerContainer->getBottomInParent(); - if (icBottomPos + touchOffset >= _bottomBoundary) - { - realOffset = _bottomBoundary - icBottomPos; - moveChildren(realOffset); - _bottomEnd = true; - scrollToBottomEvent(); - return false; - } - break; - } - case SCROLLVIEW_MOVE_DIR_DOWN: // down - { - float icTopPos = _innerContainer->getTopInParent(); - if (icTopPos + touchOffset <= _topBoundary) - { - realOffset = _topBoundary - icTopPos; - moveChildren(realOffset); - _topEnd = true; - scrollToTopEvent(); - return false; - } - break; - } - default: - break; - } - moveChildren(realOffset); - _topEnd = false; - _bottomEnd = false; - return true; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - switch (_moveDirection) + { + if (_autoScrollDir.y > 0) { - case SCROLLVIEW_MOVE_DIR_LEFT: // left + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) { - float icRightPos = _innerContainer->getRightInParent(); - if (icRightPos + touchOffset <= _rightBoundary) - { - realOffset = _rightBoundary - icRightPos; - moveChildren(realOffset); - _rightEnd = true; - scrollToRightEvent(); - return false; - } - break; + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; } - case SCROLLVIEW_MOVE_DIR_RIGHT: // right - { - float icLeftPos = _innerContainer->getLeftInParent(); - if (icLeftPos + touchOffset >= _leftBoundary) - { - realOffset = _leftBoundary - icLeftPos; - moveChildren(realOffset); - _leftEnd = true; - scrollToLeftEvent(); - return false; - } - break; - } - default: - break; } - moveChildren(realOffset); - _leftEnd = false; - _rightEnd = false; - return true; break; - + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + if (_autoScrollDir.x > 0) + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + else + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } + case SCROLLVIEW_DIR_BOTH: + { + if (*touchOffsetX > 0.0f && *touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + *touchOffsetY >= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icBottomPos; + scrollenabled = false; + } + } + else if (*touchOffsetX < 0.0f && *touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + *touchOffsetX <= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icRightPos; + scrollenabled = false; + } + } + else if (*touchOffsetX == 0.0f && *touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + *touchOffsetY <= _autoScrollDestination.y) + { + *touchOffsetY = _autoScrollDestination.y - icTopPos; + scrollenabled = false; + } + } + else if (*touchOffsetX > 0.0f && *touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + *touchOffsetX >= _autoScrollDestination.x) + { + *touchOffsetX = _autoScrollDestination.x - icLeftPos; + scrollenabled = false; + } + } + break; + } default: break; } - - return false; + return scrollenabled; } -void UIScrollView::scrollToBottom() +bool UIScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - scrollChildren(_innerContainer->getSize().height); + bool scrollenabled = true; + scrollingEvent(); + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: // vertical + { + float realOffset = touchOffsetY; + if (_bounceEnabled) + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffset = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffset = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffset = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffset = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + moveChildren(0.0f, realOffset); + break; + } + case SCROLLVIEW_DIR_HORIZONTAL: // horizontal + { + float realOffset = touchOffsetX; + if (_bounceEnabled) + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffset = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffset = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + else + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffset = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffset = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + moveChildren(realOffset, 0.0f); + break; + } + case SCROLLVIEW_DIR_BOTH: + { + float realOffsetX = touchOffsetX; + float realOffsetY = touchOffsetY; + if (_bounceEnabled) + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bounceBottomBoundary) + { + realOffsetY = _bounceBottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _bounceRightBoundary) + { + realOffsetX = _bounceRightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _bounceTopBoundary) + { + realOffsetY = _bounceTopBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _bounceLeftBoundary) + { + realOffsetX = _bounceLeftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + else + { + if (touchOffsetX > 0.0f && touchOffsetY > 0.0f) // up right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY > 0.0f) // up left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY < 0.0f) // down left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY < 0.0f) // down right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY > 0.0f) // up + { + float icBottomPos = _innerContainer->getBottomInParent(); + if (icBottomPos + touchOffsetY >= _bottomBoundary) + { + realOffsetY = _bottomBoundary - icBottomPos; + scrollToBottomEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX < 0.0f && touchOffsetY == 0.0f) // left + { + float icRightPos = _innerContainer->getRightInParent(); + if (icRightPos + touchOffsetX <= _rightBoundary) + { + realOffsetX = _rightBoundary - icRightPos; + scrollToRightEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX == 0.0f && touchOffsetY < 0.0f) // down + { + float icTopPos = _innerContainer->getTopInParent(); + if (icTopPos + touchOffsetY <= _topBoundary) + { + realOffsetY = _topBoundary - icTopPos; + scrollToTopEvent(); + scrollenabled = false; + } + } + else if (touchOffsetX > 0.0f && touchOffsetY == 0.0f) // right + { + float icLeftPos = _innerContainer->getLeftInParent(); + if (icLeftPos + touchOffsetX >= _leftBoundary) + { + realOffsetX = _leftBoundary - icLeftPos; + scrollToLeftEvent(); + scrollenabled = false; + } + } + } + moveChildren(realOffsetX, realOffsetY); + break; + } + default: + break; + } + return scrollenabled; } -void UIScrollView::scrollToTop() +void UIScrollView::scrollToBottom(float time, bool attenuated) { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - scrollChildren(-_innerContainer->getSize().height); + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToTop(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToLeft(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToRight(float time, bool attenuated) +{ + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToTopLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToTopRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height), time, attenuated); +} + +void UIScrollView::scrollToBottomLeft(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point::ZERO, time, attenuated); +} + +void UIScrollView::scrollToBottomRight(float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + startAutoScrollChildrenWithDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentVertical(float percent, float time, bool attenuated) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + startAutoScrollChildrenWithDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f), time, attenuated); +} + +void UIScrollView::scrollToPercentHorizontal(float percent, float time, bool attenuated) +{ + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y), time, attenuated); +} + +void UIScrollView::scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + startAutoScrollChildrenWithDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f), time, attenuated); +} + +void UIScrollView::jumpToBottom() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, 0.0f)); +} + +void UIScrollView::jumpToTop() +{ + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToLeft() +{ + jumpToDestination(cocos2d::Point(0.0f, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToRight() +{ + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToTopLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(0.0f, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToTopRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, _size.height - _innerContainer->getSize().height)); +} + +void UIScrollView::jumpToBottomLeft() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point::ZERO); +} + +void UIScrollView::jumpToBottomRight() +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + CCLOG("Scroll diretion is not both!"); + return; + } + jumpToDestination(cocos2d::Point(_size.width - _innerContainer->getSize().width, 0.0f)); +} + +void UIScrollView::jumpToPercentVertical(float percent) +{ + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + jumpToDestination(cocos2d::Point(_innerContainer->getPosition().x, minY + percent * h / 100.0f)); +} + +void UIScrollView::jumpToPercentHorizontal(float percent) +{ + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent * w / 100.0f), _innerContainer->getPosition().y)); +} + +void UIScrollView::jumpToPercentBothDirection(const cocos2d::Point& percent) +{ + if (_direction != SCROLLVIEW_DIR_BOTH) + { + return; + } + float minY = _size.height - _innerContainer->getSize().height; + float h = - minY; + float w = _innerContainer->getSize().width - _size.width; + jumpToDestination(cocos2d::Point(-(percent.x * w / 100.0f), minY + percent.y * h / 100.0f)); } void UIScrollView::startRecordSlidAction() { - if (_children->count() <= 0) + if (_autoScroll) { - return; - } - if (_autoScroll){ stopAutoScrollChildren(); } - _bePressed = true; - _slidTime = 0.0; + if (_bouncing) + { + stopBounceChildren(); + } + _slidTime = 0.0f; } void UIScrollView::endRecordSlidAction() { - if (_children->count() <= 0) + if (!checkNeedBounce() && _inertiaScrollEnabled) { - return; + if (_slidTime <= 0.016f) + { + return; + } + float totalDis = 0.0f; + cocos2d::Point dir; + switch (_direction) + { + case SCROLLVIEW_DIR_VERTICAL: + totalDis = _touchEndedPoint.y - _touchBeganPoint.y; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_DOWN; + } + else + { + dir = SCROLLDIR_UP; + } + break; + case SCROLLVIEW_DIR_HORIZONTAL: + totalDis = _touchEndedPoint.x - _touchBeganPoint.x; + if (totalDis < 0.0f) + { + dir = SCROLLDIR_LEFT; + } + else + { + dir = SCROLLDIR_RIGHT; + } + break; + case SCROLLVIEW_DIR_BOTH: + { + cocos2d::Point subVector = _touchEndedPoint - _touchBeganPoint; + totalDis = subVector.getLength(); + dir = subVector.normalize(); + break; + } + default: + break; + } + float orSpeed = MIN(fabs(totalDis)/(_slidTime), AUTOSCROLLMAXSPEED); + startAutoScrollChildrenWithOriginalSpeed(dir, orSpeed, true, -1000); + _slidTime = 0.0f; } - if (_slidTime <= 0.016f) - { - return; - } - float totalDis = 0; - totalDis = _touchEndLocation-_touchStartLocation; - float orSpeed = fabs(totalDis)/(_slidTime); - startAutoScrollChildren(orSpeed); - - _bePressed = false; - _slidTime = 0.0; } -void UIScrollView::handlePressLogic(const Point &touchPoint) +void UIScrollView::handlePressLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchMoveStartLocation = nsp.y; - _touchStartLocation = nsp.y; - break; - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchMoveStartLocation = nsp.x; - _touchStartLocation = nsp.x; - break; - default: - break; - } + _touchBeganPoint = _renderer->convertToNodeSpace(touchPoint); + _touchMovingPoint = _touchBeganPoint; startRecordSlidAction(); + _bePressed = true; } -void UIScrollView::handleMoveLogic(const Point &touchPoint) +void UIScrollView::handleMoveLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - float offset = 0.0f; - + _touchMovedPoint = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point delta = _touchMovedPoint - _touchMovingPoint; + _touchMovingPoint = _touchMovedPoint; switch (_direction) { case SCROLLVIEW_DIR_VERTICAL: // vertical - { - float moveY = nsp.y; - offset = moveY - _touchMoveStartLocation; - _touchMoveStartLocation = moveY; - - if (offset < 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_DOWN; // down - } - else if (offset > 0.0f) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_UP; // up - } - } + { + scrollChildren(0.0f, delta.y); break; - + } case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - { - float moveX = nsp.x; - offset = moveX - _touchMoveStartLocation; - _touchMoveStartLocation = moveX; - - if (offset < 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_LEFT; // left - } - else if (offset > 0) - { - _moveDirection = SCROLLVIEW_MOVE_DIR_RIGHT; // right - } - } + { + scrollChildren(delta.x, 0.0f); break; - + } + case SCROLLVIEW_DIR_BOTH: // both + { + scrollChildren(delta.x, delta.y); + break; + } default: break; } - scrollChildren(offset); } -void UIScrollView::handleReleaseLogic(const Point &touchPoint) +void UIScrollView::handleReleaseLogic(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - _touchEndLocation = nsp.y; - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - _touchEndLocation = nsp.x; - break; - - default: - break; - } + _touchEndedPoint = _renderer->convertToNodeSpace(touchPoint); endRecordSlidAction(); + _bePressed = false; } -bool UIScrollView::onTouchBegan(const Point &touchPoint) +bool UIScrollView::onTouchBegan(const cocos2d::Point &touchPoint) { - bool pass = Layout::onTouchBegan(touchPoint); + bool pass = UILayout::onTouchBegan(touchPoint); handlePressLogic(touchPoint); return pass; } -void UIScrollView::onTouchMoved(const Point &touchPoint) +void UIScrollView::onTouchMoved(const cocos2d::Point &touchPoint) { - Layout::onTouchMoved(touchPoint); + UILayout::onTouchMoved(touchPoint); handleMoveLogic(touchPoint); } -void UIScrollView::onTouchEnded(const Point &touchPoint) +void UIScrollView::onTouchEnded(const cocos2d::Point &touchPoint) { - Layout::onTouchEnded(touchPoint); + UILayout::onTouchEnded(touchPoint); handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchCancelled(const Point &touchPoint) +void UIScrollView::onTouchCancelled(const cocos2d::Point &touchPoint) { - Layout::onTouchCancelled(touchPoint); + UILayout::onTouchCancelled(touchPoint); + handleReleaseLogic(touchPoint); } -void UIScrollView::onTouchLongClicked(const Point &touchPoint) +void UIScrollView::onTouchLongClicked(const cocos2d::Point &touchPoint) { } @@ -546,6 +1406,10 @@ void UIScrollView::update(float dt) { autoScrollChildren(dt); } + if (_bouncing) + { + bounceChildren(dt); + } recordSlidTime(dt); } @@ -557,7 +1421,7 @@ void UIScrollView::recordSlidTime(float dt) } } -void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const Point &touchPoint) +void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { switch (handleState) { @@ -567,20 +1431,7 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const case 1: { - float offset = 0; - switch (_direction) - { - case SCROLLVIEW_DIR_VERTICAL: // vertical - offset = fabs(sender->getTouchStartPos().y - touchPoint.y); - break; - - case SCROLLVIEW_DIR_HORIZONTAL: // horizontal - offset = fabs(sender->getTouchStartPos().x - touchPoint.x); - break; - - default: - break; - } + float offset = (sender->getTouchStartPos() - touchPoint).getLength(); if (offset > _childFocusCancelOffset) { sender->setFocused(false); @@ -594,11 +1445,12 @@ void UIScrollView::interceptTouchEvent(int handleState, UIWidget *sender, const break; case 3: + handleReleaseLogic(touchPoint); break; } } -void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const Point &touchPoint) +void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint) { interceptTouchEvent(handleState, sender, touchPoint); } @@ -635,7 +1487,47 @@ void UIScrollView::scrollToRightEvent() } } -void UIScrollView::addEventListener(Object *target, SEL_ScrollViewEvent selector) +void UIScrollView::scrollingEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); + } +} + +void UIScrollView::bounceTopEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); + } +} + +void UIScrollView::bounceBottomEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); + } +} + +void UIScrollView::bounceLeftEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); + } +} + +void UIScrollView::bounceRightEvent() +{ + if (_eventListener && _eventSelector) + { + (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); + } +} + +void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { _eventListener = target; _eventSelector = selector; @@ -651,17 +1543,27 @@ SCROLLVIEW_DIR UIScrollView::getDirection() return _direction; } -void UIScrollView::setMoveDirection(SCROLLVIEW_MOVE_DIR dir) +void UIScrollView::setBounceEnabled(bool enabled) { - _moveDirection = dir; + _bounceEnabled = enabled; } -SCROLLVIEW_MOVE_DIR UIScrollView::getMoveDirection() +bool UIScrollView::isBounceEnabled() const { - return _moveDirection; + return _bounceEnabled; } -Layout* UIScrollView::getInnerContainer() +void UIScrollView::setInertiaScrollEnabled(bool enabled) +{ + _inertiaScrollEnabled = enabled; +} + +bool UIScrollView::isInertiaScrollEnabled() const +{ + return _inertiaScrollEnabled; +} + +UILayout* UIScrollView::getInnerContainer() { return _innerContainer; } @@ -686,4 +1588,27 @@ const char* UIScrollView::getDescription() const return "ScrollView"; } +UIWidget* UIScrollView::createCloneInstance() +{ + return UIScrollView::create(); +} + +void UIScrollView::copyClonedWidgetChildren(UIWidget* model) +{ + UILayout::copyClonedWidgetChildren(model); +} + +void UIScrollView::copySpecialProperties(UIWidget *widget) +{ + UIScrollView* scrollView = dynamic_cast(widget); + if (scrollView) + { + UILayout::copySpecialProperties(widget); + setInnerContainerSize(scrollView->getInnerContainerSize()); + setDirection(scrollView->_direction); + setBounceEnabled(scrollView->_bounceEnabled); + setInertiaScrollEnabled(scrollView->_inertiaScrollEnabled); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 1a6cf31f99..4d762930f8 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -25,7 +25,7 @@ #ifndef __UISCROLLVIEW_H__ #define __UISCROLLVIEW_H__ -#include "gui//Layout.h" +#include "gui/UILayout.h" #include "gui/UIScrollInterface.h" namespace gui { @@ -34,16 +34,8 @@ enum SCROLLVIEW_DIR { SCROLLVIEW_DIR_NONE, SCROLLVIEW_DIR_VERTICAL, - SCROLLVIEW_DIR_HORIZONTAL -}; - -enum SCROLLVIEW_MOVE_DIR -{ - SCROLLVIEW_MOVE_DIR_NONE, - SCROLLVIEW_MOVE_DIR_UP, - SCROLLVIEW_MOVE_DIR_DOWN, - SCROLLVIEW_MOVE_DIR_LEFT, - SCROLLVIEW_MOVE_DIR_RIGHT, + SCROLLVIEW_DIR_HORIZONTAL, + SCROLLVIEW_DIR_BOTH }; typedef enum @@ -52,13 +44,18 @@ typedef enum SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM, SCROLLVIEW_EVENT_SCROLL_TO_LEFT, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, + SCROLLVIEW_EVENT_SCROLLING, + SCROLLVIEW_EVENT_BOUNCE_TOP, + SCROLLVIEW_EVENT_BOUNCE_BOTTOM, + SCROLLVIEW_EVENT_BOUNCE_LEFT, + SCROLLVIEW_EVENT_BOUNCE_RIGHT }ScrollviewEventType; -typedef void (cocos2d::Object::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); +typedef void (cocos2d::CCObject::*SEL_ScrollViewEvent)(cocos2d::Object*, ScrollviewEventType); #define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) -class UIScrollView : public Layout , public UIScrollInterface +class UIScrollView : public UILayout , public UIScrollInterface { public: /** @@ -83,7 +80,7 @@ public: * * @param SCROLLVIEW_DIR */ - void setDirection(SCROLLVIEW_DIR dir); + virtual void setDirection(SCROLLVIEW_DIR dir); /** * Gets scroll direction of scrollview. @@ -101,17 +98,117 @@ public: * * @return inner container. */ - Layout* getInnerContainer(); + UILayout* getInnerContainer(); /** * Scroll inner container to bottom boundary of scrollview. */ - void scrollToBottom(); + void scrollToBottom(float time, bool attenuated); /** * Scroll inner container to top boundary of scrollview. */ - void scrollToTop(); + void scrollToTop(float time, bool attenuated); + + /** + * Scroll inner container to left boundary of scrollview. + */ + void scrollToLeft(float time, bool attenuated); + + /** + * Scroll inner container to right boundary of scrollview. + */ + void scrollToRight(float time, bool attenuated); + + /** + * Scroll inner container to top and left boundary of scrollview. + */ + void scrollToTopLeft(float time, bool attenuated); + + /** + * Scroll inner container to top and right boundary of scrollview. + */ + void scrollToTopRight(float time, bool attenuated); + + /** + * Scroll inner container to bottom and left boundary of scrollview. + */ + void scrollToBottomLeft(float time, bool attenuated); + + /** + * Scroll inner container to bottom and right boundary of scrollview. + */ + void scrollToBottomRight(float time, bool attenuated); + + /** + * Scroll inner container to vertical percent position of scrollview. + */ + void scrollToPercentVertical(float percent, float time, bool attenuated); + + /** + * Scroll inner container to horizontal percent position of scrollview. + */ + void scrollToPercentHorizontal(float percent, float time, bool attenuated); + + /** + * Scroll inner container to both direction percent position of scrollview. + */ + void scrollToPercentBothDirection(const cocos2d::Point& percent, float time, bool attenuated); + + /** + * Move inner container to bottom boundary of scrollview. + */ + void jumpToBottom(); + + /** + * Move inner container to top boundary of scrollview. + */ + void jumpToTop(); + + /** + * Move inner container to left boundary of scrollview. + */ + void jumpToLeft(); + + /** + * Move inner container to right boundary of scrollview. + */ + void jumpToRight(); + + /** + * Move inner container to top and left boundary of scrollview. + */ + void jumpToTopLeft(); + + /** + * Move inner container to top and right boundary of scrollview. + */ + void jumpToTopRight(); + + /** + * Move inner container to bottom and left boundary of scrollview. + */ + void jumpToBottomLeft(); + + /** + * Move inner container to bottom and right boundary of scrollview. + */ + void jumpToBottomRight(); + + /** + * Move inner container to vertical percent position of scrollview. + */ + void jumpToPercentVertical(float percent); + + /** + * Move inner container to horizontal percent position of scrollview. + */ + void jumpToPercentHorizontal(float percent); + + /** + * Move inner container to both direction percent position of scrollview. + */ + void jumpToPercentBothDirection(const cocos2d::Point& percent); /** * Changes inner container size of scrollview. @@ -134,7 +231,7 @@ public: /** * Add call back function called scrollview event triggered */ - void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); + void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); //override "addChild" method of widget. virtual bool addChild(UIWidget* widget); @@ -165,6 +262,14 @@ public: virtual void update(float dt); + void setBounceEnabled(bool enabled); + + bool isBounceEnabled() const; + + void setInertiaScrollEnabled(bool enabled); + + bool isInertiaScrollEnabled() const; + /** * Sets LayoutType. * @@ -192,12 +297,20 @@ public: protected: virtual bool init(); virtual void initRenderer(); - void moveChildren(float offset); + void moveChildren(float offsetX, float offsetY); void autoScrollChildren(float dt); - void startAutoScrollChildren(float v); + void bounceChildren(float dt); + void checkBounceBoundary(); + bool checkNeedBounce(); + void startAutoScrollChildrenWithOriginalSpeed(const cocos2d::Point& dir, float v, bool attenuated, float acceleration); + void startAutoScrollChildrenWithDestination(const cocos2d::Point& des, float time, bool attenuated); + void jumpToDestination(const cocos2d::Point& des); void stopAutoScrollChildren(); - float getCurAutoScrollDistance(float time); - virtual bool scrollChildren(float touchOffset); + void startBounceChildren(float v); + void stopBounceChildren(); + bool checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY); + virtual bool scrollChildren(float touchOffsetX, float touchOffsetY); + bool bounceScrollChildren(float touchOffsetX, float touchOffsetY); void startRecordSlidAction(); virtual void endRecordSlidAction(); virtual void handlePressLogic(const cocos2d::Point &touchPoint); @@ -206,48 +319,71 @@ protected: virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); virtual void checkChildInfo(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); void recordSlidTime(float dt); - //override "releaseResoures" method of widget. - virtual void releaseResoures(); - void scrollToTopEvent(); void scrollToBottomEvent(); void scrollToLeftEvent(); void scrollToRightEvent(); - void setMoveDirection(SCROLLVIEW_MOVE_DIR dir); - SCROLLVIEW_MOVE_DIR getMoveDirection(); + void scrollingEvent(); + void bounceTopEvent(); + void bounceBottomEvent(); + void bounceLeftEvent(); + void bounceRightEvent(); virtual void onSizeChanged(); - virtual void setClippingEnabled(bool able){Layout::setClippingEnabled(able);}; + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); + virtual void setClippingEnabled(bool able){UILayout::setClippingEnabled(able);}; protected: - Layout* _innerContainer; + UILayout* _innerContainer; SCROLLVIEW_DIR _direction; - SCROLLVIEW_MOVE_DIR _moveDirection; - float _touchStartLocation; - float _touchEndLocation; - float _touchMoveStartLocation; - float _topBoundary;//test - float _bottomBoundary;//test + + cocos2d::Point _touchBeganPoint; + cocos2d::Point _touchMovedPoint; + cocos2d::Point _touchEndedPoint; + cocos2d::Point _touchMovingPoint; + cocos2d::Point _autoScrollDir; + + float _topBoundary; + float _bottomBoundary; float _leftBoundary; float _rightBoundary; - bool _topEnd; - bool _bottomEnd; - bool _leftEnd; - bool _rightEnd; + float _bounceTopBoundary; + float _bounceBottomBoundary; + float _bounceLeftBoundary; + float _bounceRightBoundary; + bool _autoScroll; + float _autoScrollAddUpTime; float _autoScrollOriginalSpeed; float _autoScrollAcceleration; + bool _isAutoScrollSpeedAttenuated; + bool _needCheckAutoScrollDestination; + cocos2d::Point _autoScrollDestination; bool _bePressed; float _slidTime; cocos2d::Point _moveChildPoint; float _childFocusCancelOffset; + bool _leftBounceNeeded; + bool _topBounceNeeded; + bool _rightBounceNeeded; + bool _bottomBounceNeeded; + + bool _bounceEnabled; + bool _bouncing; + cocos2d::Point _bounceDir; + float _bounceOriginalSpeed; + bool _inertiaScrollEnabled; + + + cocos2d::Object* _eventListener; SEL_ScrollViewEvent _eventSelector; - }; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index 425fc581e0..f3c0a90b97 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -25,15 +25,12 @@ #include "gui/UISlider.h" #include "extensions/GUI/CCControlExtension/CCScale9Sprite.h" -using namespace cocos2d; -using namespace cocos2d::extension; - namespace gui { UISlider::UISlider(): _barRenderer(NULL), _progressBarRenderer(NULL), -_progressBarTextureSize(Size::ZERO), +_progressBarTextureSize(cocos2d::Size::ZERO), _slidBallNormalRenderer(NULL), _slidBallPressedRenderer(NULL), _slidBallDisabledRenderer(NULL), @@ -47,8 +44,8 @@ _progressBarTextureFile(""), _slidBallNormalTextureFile(""), _slidBallPressedTextureFile(""), _slidBallDisabledTextureFile(""), -_capInsetsBarRenderer(Rect::ZERO), -_capInsetsProgressBarRenderer(Rect::ZERO), +_capInsetsBarRenderer(cocos2d::Rect::ZERO), +_capInsetsProgressBarRenderer(cocos2d::Rect::ZERO), _slidPercentListener(NULL), _slidPercentSelector(NULL), _barTexType(UI_TEX_TYPE_LOCAL), @@ -79,17 +76,17 @@ UISlider* UISlider::create() void UISlider::initRenderer() { UIWidget::initRenderer(); - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _renderer->addChild(_barRenderer, -1); _renderer->addChild(_progressBarRenderer, -1); - _slidBallNormalRenderer = CCSprite::create(); - _slidBallPressedRenderer = CCSprite::create(); + _slidBallNormalRenderer = cocos2d::Sprite::create(); + _slidBallPressedRenderer = cocos2d::Sprite::create(); _slidBallPressedRenderer->setVisible(false); - _slidBallDisabledRenderer = CCSprite::create(); + _slidBallDisabledRenderer = cocos2d::Sprite::create(); _slidBallDisabledRenderer->setVisible(false); - _slidBallRenderer = CCNode::create(); + _slidBallRenderer = cocos2d::Node::create(); _slidBallRenderer->addChild(_slidBallNormalRenderer); _slidBallRenderer->addChild(_slidBallPressedRenderer); _slidBallRenderer->addChild(_slidBallDisabledRenderer); @@ -109,21 +106,21 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } else { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -131,13 +128,13 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) } if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_barRenderer)->setColor(getColor()); - dynamic_cast(_barRenderer)->setOpacity(getOpacity()); + dynamic_cast(_barRenderer)->setColor(getColor()); + dynamic_cast(_barRenderer)->setOpacity(getOpacity()); } barRendererScaleChangedWithSize(); } @@ -155,21 +152,21 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy case UI_TEX_TYPE_LOCAL: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->initWithFile(fileName); } break; case UI_TEX_TYPE_PLIST: if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } else { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); } break; default: @@ -177,15 +174,15 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy } if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } else { - dynamic_cast(_progressBarRenderer)->setColor(getColor()); - dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); + dynamic_cast(_progressBarRenderer)->setColor(getColor()); + dynamic_cast(_progressBarRenderer)->setOpacity(getOpacity()); } - _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); + _progressBarRenderer->setAnchorPoint(cocos2d::Point(0.0f, 0.5f)); _progressBarTextureSize = _progressBarRenderer->getContentSize(); progressBarRendererScaleChangedWithSize(); } @@ -204,13 +201,13 @@ void UISlider::setScale9Enabled(bool able) _progressBarRenderer = NULL; if (_scale9Enabled) { - _barRenderer = Scale9Sprite::create(); - _progressBarRenderer = Scale9Sprite::create(); + _barRenderer = cocos2d::extension::Scale9Sprite::create(); + _progressBarRenderer = cocos2d::extension::Scale9Sprite::create(); } else { - _barRenderer = CCSprite::create(); - _progressBarRenderer = CCSprite::create(); + _barRenderer = cocos2d::Sprite::create(); + _progressBarRenderer = cocos2d::Sprite::create(); } loadBarTexture(_textureFile.c_str(), _barTexType); loadProgressBarTexture(_progressBarTextureFile.c_str(), _progressBarTexType); @@ -239,30 +236,30 @@ void UISlider::ignoreContentAdaptWithSize(bool ignore) } } -void UISlider::setCapInsets(const Rect &capInsets) +void UISlider::setCapInsets(const cocos2d::Rect &capInsets) { setCapInsetsBarRenderer(capInsets); setCapInsetProgressBarRebderer(capInsets); } -void UISlider::setCapInsetsBarRenderer(const Rect &capInsets) +void UISlider::setCapInsetsBarRenderer(const cocos2d::Rect &capInsets) { _capInsetsBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_barRenderer)->setCapInsets(capInsets); + dynamic_cast(_barRenderer)->setCapInsets(capInsets); } -void UISlider::setCapInsetProgressBarRebderer(const Rect &capInsets) +void UISlider::setCapInsetProgressBarRebderer(const cocos2d::Rect &capInsets) { _capInsetsProgressBarRenderer = capInsets; if (!_scale9Enabled) { return; } - dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); + dynamic_cast(_progressBarRenderer)->setCapInsets(capInsets); } void UISlider::loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType) @@ -353,10 +350,10 @@ void UISlider::setPercent(int percent) } _percent = percent; float dis = _barLength*(percent/100.0f); - _slidBallRenderer->setPosition(Point(-_barLength/2.0f + dis, 0.0f)); + _slidBallRenderer->setPosition(cocos2d::Point(-_barLength/2.0f + dis, 0.0f)); if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(Size(dis,_progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setPreferredSize(cocos2d::Size(dis,_progressBarTextureSize.height)); } else { @@ -365,10 +362,10 @@ void UISlider::setPercent(int percent) { case UI_TEX_TYPE_PLIST: { - Sprite* barNode = dynamic_cast(_progressBarRenderer); + cocos2d::Sprite* barNode = dynamic_cast(_progressBarRenderer); if (barNode) { - Point to = barNode->getTextureRect().origin; + cocos2d::Point to = barNode->getTextureRect().origin; x = to.x; y = to.y; } @@ -377,33 +374,33 @@ void UISlider::setPercent(int percent) default: break; } - dynamic_cast(_progressBarRenderer)->setTextureRect(Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); + dynamic_cast(_progressBarRenderer)->setTextureRect(cocos2d::Rect(x, y, _progressBarTextureSize.width * (percent/100.0f), _progressBarTextureSize.height)); } } -bool UISlider::onTouchBegan(const Point &touchPoint) +bool UISlider::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); - Point nsp = _renderer->convertToNodeSpace(touchPoint); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); return pass; } -void UISlider::onTouchMoved(const Point &touchPoint) +void UISlider::onTouchMoved(const cocos2d::Point &touchPoint) { - Point nsp = _renderer->convertToNodeSpace(touchPoint); - _slidBallRenderer->setPosition(Point(nsp.x,0)); + cocos2d::Point nsp = _renderer->convertToNodeSpace(touchPoint); + _slidBallRenderer->setPosition(cocos2d::Point(nsp.x,0)); setPercent(getPercentWithBallPos(nsp.x)); percentChangedEvent(); } -void UISlider::onTouchEnded(const Point &touchPoint) +void UISlider::onTouchEnded(const cocos2d::Point &touchPoint) { UIWidget::onTouchEnded(touchPoint); } -void UISlider::onTouchCancelled(const Point &touchPoint) +void UISlider::onTouchCancelled(const cocos2d::Point &touchPoint) { UIWidget::onTouchCancelled(touchPoint); } @@ -413,7 +410,7 @@ float UISlider::getPercentWithBallPos(float px) return (((px-(-_barLength/2.0f))/_barLength)*100.0f); } -void UISlider::addEventListener(Object *target, SEL_SlidPercentChangedEvent selector) +void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { _slidPercentListener = target; _slidPercentSelector = selector; @@ -438,12 +435,12 @@ void UISlider::onSizeChanged() progressBarRendererScaleChangedWithSize(); } -const Size& UISlider::getContentSize() const +const cocos2d::Size& UISlider::getContentSize() const { return _barRenderer->getContentSize(); } -Node* UISlider::getVirtualRenderer() +cocos2d::Node* UISlider::getVirtualRenderer() { return _barRenderer; } @@ -462,11 +459,11 @@ void UISlider::barRendererScaleChangedWithSize() _barLength = _size.width; if (_scale9Enabled) { - dynamic_cast(_barRenderer)->setPreferredSize(_size); + dynamic_cast(_barRenderer)->setPreferredSize(_size); } else { - Size btextureSize = _barRenderer->getContentSize(); + cocos2d::Size btextureSize = _barRenderer->getContentSize(); if (btextureSize.width <= 0.0f || btextureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); @@ -487,7 +484,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (!_scale9Enabled) { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; float pscaleX = _size.width / ptextureSize.width; float pscaleY = _size.height / ptextureSize.height; _progressBarRenderer->setScaleX(pscaleX); @@ -498,11 +495,11 @@ void UISlider::progressBarRendererScaleChangedWithSize() { if (_scale9Enabled) { - dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); + dynamic_cast(_progressBarRenderer)->setPreferredSize(_size); } else { - Size ptextureSize = _progressBarTextureSize; + cocos2d::Size ptextureSize = _progressBarTextureSize; if (ptextureSize.width <= 0.0f || ptextureSize.height <= 0.0f) { _progressBarRenderer->setScale(1.0f); @@ -514,7 +511,7 @@ void UISlider::progressBarRendererScaleChangedWithSize() _progressBarRenderer->setScaleY(pscaleY); } } - _progressBarRenderer->setPosition(Point(-_barLength * 0.5f, 0.0f)); + _progressBarRenderer->setPosition(cocos2d::Point(-_barLength * 0.5f, 0.0f)); setPercent(_percent); } @@ -544,4 +541,25 @@ const char* UISlider::getDescription() const return "Slider"; } +UIWidget* UISlider::createCloneInstance() +{ + return UISlider::create(); +} + +void UISlider::copySpecialProperties(UIWidget *widget) +{ + UISlider* slider = dynamic_cast(widget); + if (slider) + { + _prevIgnoreSize = slider->_prevIgnoreSize; + setScale9Enabled(slider->_scale9Enabled); + loadBarTexture(slider->_textureFile.c_str(), slider->_barTexType); + loadProgressBarTexture(slider->_progressBarTextureFile.c_str(), slider->_progressBarTexType); + loadSlidBallTextureNormal(slider->_slidBallNormalTextureFile.c_str(), slider->_ballNTexType); + loadSlidBallTexturePressed(slider->_slidBallPressedTextureFile.c_str(), slider->_ballPTexType); + loadSlidBallTextureDisabled(slider->_slidBallDisabledTextureFile.c_str(), slider->_ballDTexType); + setPercent(slider->getPercent()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UISlider.h b/cocos/gui/UISlider.h index 0654336600..186af44d45 100644 --- a/cocos/gui/UISlider.h +++ b/cocos/gui/UISlider.h @@ -34,9 +34,13 @@ typedef enum SLIDER_PERCENTCHANGED }SliderEventType; -typedef void (cocos2d::CCObject::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); +typedef void (cocos2d::Object::*SEL_SlidPercentChangedEvent)(cocos2d::Object*,SliderEventType); #define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ class UISlider : public UIWidget { public: @@ -185,6 +189,7 @@ public: * Returns the "class name" of widget. */ virtual const char* getDescription() const; + protected: virtual void initRenderer(); float getPercentWithBallPos(float location); @@ -195,6 +200,8 @@ protected: virtual void onSizeChanged(); void barRendererScaleChangedWithSize(); void progressBarRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: cocos2d::Node* _barRenderer; cocos2d::Node* _progressBarRenderer; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 4e1365592d..2eabd208b2 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -24,19 +24,17 @@ #include "gui/UITextField.h" - using namespace cocos2d; - namespace gui { UICCTextField::UICCTextField() -: m_bMaxLengthEnabled(false) -, m_nMaxLength(0) -, m_bPasswordEnabled(false) -, m_strPasswordStyleText("*") -, m_bAttachWithIME(false) -, m_bDetachWithIME(false) -, m_bInsertText(false) -, m_bDeleteBackward(false) +: _maxLengthEnabled(false) +, _maxLength(0) +, _passwordEnabled(false) +, _passwordStyleText("*") +, _attachWithIME(false) +, _detachWithIME(false) +, _insertText(false) +, _deleteBackward(false) { } @@ -64,26 +62,26 @@ UICCTextField * UICCTextField::create(const char *placeholder, const char *fontN void UICCTextField::onEnter() { - CCTextFieldTTF::setDelegate(this); + cocos2d::TextFieldTTF::setDelegate(this); } -bool UICCTextField::onTextFieldAttachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldAttachWithIME(cocos2d::TextFieldTTF *pSender) { setAttachWithIME(true); return false; } -bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *text, int nLen) +bool UICCTextField::onTextFieldInsertText(cocos2d::TextFieldTTF *pSender, const char *text, int nLen) { if (nLen == 1 && strcmp(text, "\n") == 0) { return false; } setInsertText(true); - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { - if (CCTextFieldTTF::getCharCount() >= m_nMaxLength) + if (cocos2d::TextFieldTTF::getCharCount() >= _maxLength) { return true; } @@ -92,13 +90,13 @@ bool UICCTextField::onTextFieldInsertText(TextFieldTTF *pSender, const char *tex return false; } -bool UICCTextField::onTextFieldDeleteBackward(TextFieldTTF *pSender, const char *delText, int nLen) +bool UICCTextField::onTextFieldDeleteBackward(cocos2d::TextFieldTTF *pSender, const char *delText, int nLen) { setDeleteBackward(true); return false; } -bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) +bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) { setDetachWithIME(true); return false; @@ -107,11 +105,11 @@ bool UICCTextField::onTextFieldDetachWithIME(TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = strlen(CCTextFieldTTF::getString()); + int str_len = strlen(cocos2d::TextFieldTTF::getString()); if (strcmp(text, "\n") != 0) { - if (m_bMaxLengthEnabled) + if (_maxLengthEnabled) { int multiple = 1; char value = text[0]; @@ -120,26 +118,26 @@ void UICCTextField::insertText(const char * text, int len) multiple = 3; } - if (str_len + len > m_nMaxLength * multiple) + if (str_len + len > _maxLength * multiple) { - str_text = str_text.substr(0, m_nMaxLength * multiple); - len = m_nMaxLength * multiple; + str_text = str_text.substr(0, _maxLength * multiple); + len = _maxLength * multiple; /* int mod = str_len % 3; int offset = (mod == 0) ? 0 : (3 - mod); int amount = str_len + offset; - str_text = str_text.substr(0, m_nMaxLength - amount); + str_text = str_text.substr(0, _maxLength - amount); // CCLOG("str_test = %s", str_text.c_str()); */ } } } - CCTextFieldTTF::insertText(str_text.c_str(), len); + cocos2d::TextFieldTTF::insertText(str_text.c_str(), len); // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { setPasswordText(_inputText->c_str()); } @@ -148,12 +146,12 @@ void UICCTextField::insertText(const char * text, int len) void UICCTextField::deleteBackward() { - CCTextFieldTTF::deleteBackward(); + cocos2d::TextFieldTTF::deleteBackward(); - if (CCTextFieldTTF::getCharCount() > 0) + if (cocos2d::TextFieldTTF::getCharCount() > 0) { // password - if (m_bPasswordEnabled) + if (_passwordEnabled) { setPasswordText(_inputText->c_str()); } @@ -162,47 +160,47 @@ void UICCTextField::deleteBackward() void UICCTextField::openIME() { - CCTextFieldTTF::attachWithIME(); + cocos2d::TextFieldTTF::attachWithIME(); } void UICCTextField::closeIME() { - CCTextFieldTTF::detachWithIME(); + cocos2d::TextFieldTTF::detachWithIME(); } void UICCTextField::setMaxLengthEnabled(bool enable) { - m_bMaxLengthEnabled = enable; + _maxLengthEnabled = enable; } bool UICCTextField::isMaxLengthEnabled() { - return m_bMaxLengthEnabled; + return _maxLengthEnabled; } void UICCTextField::setMaxLength(int length) { - m_nMaxLength = length; + _maxLength = length; } int UICCTextField::getMaxLength() { - return m_nMaxLength; + return _maxLength; } int UICCTextField::getCharCount() { - return CCTextFieldTTF::getCharCount(); + return cocos2d::TextFieldTTF::getCharCount(); } void UICCTextField::setPasswordEnabled(bool enable) { - m_bPasswordEnabled = enable; + _passwordEnabled = enable; } bool UICCTextField::isPasswordEnabled() { - return m_bPasswordEnabled; + return _passwordEnabled; } void UICCTextField::setPasswordStyleText(const char* styleText) @@ -216,7 +214,7 @@ void UICCTextField::setPasswordStyleText(const char* styleText) { return; } - m_strPasswordStyleText = styleText; + _passwordStyleText = styleText; } void UICCTextField::setPasswordText(const char *text) @@ -224,49 +222,49 @@ void UICCTextField::setPasswordText(const char *text) std::string tempStr; for (size_t i = 0; i < strlen(text); ++i) { - tempStr.append(m_strPasswordStyleText); + tempStr.append(_passwordStyleText); } - CCLabelTTF::setString(tempStr.c_str()); + cocos2d::LabelTTF::setString(tempStr.c_str()); } void UICCTextField::setAttachWithIME(bool attach) { - m_bAttachWithIME = attach; + _attachWithIME = attach; } bool UICCTextField::getAttachWithIME() { - return m_bAttachWithIME; + return _attachWithIME; } void UICCTextField::setDetachWithIME(bool detach) { - m_bDetachWithIME = detach; + _detachWithIME = detach; } bool UICCTextField::getDetachWithIME() { - return m_bDetachWithIME; + return _detachWithIME; } void UICCTextField::setInsertText(bool insert) { - m_bInsertText = insert; + _insertText = insert; } bool UICCTextField::getInsertText() { - return m_bInsertText; + return _insertText; } void UICCTextField::setDeleteBackward(bool deleteBackward) { - m_bDeleteBackward = deleteBackward; + _deleteBackward = deleteBackward; } bool UICCTextField::getDeleteBackward() { - return m_bDeleteBackward; + return _deleteBackward; } @@ -278,7 +276,8 @@ _touchWidth(0.0f), _touchHeight(0.0f), _useTouchArea(false), _eventListener(NULL), -_eventSelector(NULL) +_eventSelector(NULL), +_passwordStyleText("") { } @@ -315,7 +314,7 @@ void UITextField::initRenderer() _renderer->addChild(_textFieldRenderer); } -void UITextField::setTouchSize(const Size &size) +void UITextField::setTouchSize(const cocos2d::Size &size) { _useTouchArea = true; _touchWidth = size.width; @@ -361,7 +360,7 @@ const char* UITextField::getStringValue() return _textFieldRenderer->getString(); } -bool UITextField::onTouchBegan(const Point &touchPoint) +bool UITextField::onTouchBegan(const cocos2d::Point &touchPoint) { bool pass = UIWidget::onTouchBegan(touchPoint); _textFieldRenderer->attachWithIME(); @@ -401,6 +400,8 @@ bool UITextField::isPasswordEnabled() void UITextField::setPasswordStyleText(const char *styleText) { _textFieldRenderer->setPasswordStyleText(styleText); + + _passwordStyleText = styleText; } void UITextField::update(float dt) @@ -489,7 +490,7 @@ void UITextField::insertTextEvent() { if (_eventListener && _eventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INDERT_TEXT); + (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); } } @@ -501,19 +502,19 @@ void UITextField::deleteBackwardEvent() } } -void UITextField::addEventListener(Object *target, SEL_TextFieldEvent selecor) +void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { _eventListener = target; _eventSelector = selecor; } -void UITextField::setAnchorPoint(const Point &pt) +void UITextField::setAnchorPoint(const cocos2d::Point &pt) { UIWidget::setAnchorPoint(pt); _textFieldRenderer->setAnchorPoint(pt); } -void UITextField::setColor(const Color3B &color) +void UITextField::setColor(const cocos2d::Color3B &color) { UIWidget::setColor(color); _textFieldRenderer->setColor(color); @@ -539,7 +540,7 @@ void UITextField::textfieldRendererScaleChangedWithSize() } else { - Size textureSize = getContentSize(); + cocos2d::Size textureSize = getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { _textFieldRenderer->setScale(1.0f); @@ -552,12 +553,12 @@ void UITextField::textfieldRendererScaleChangedWithSize() } } -const Size& UITextField::getContentSize() const +const cocos2d::Size& UITextField::getContentSize() const { return _textFieldRenderer->getContentSize(); } -Node* UITextField::getVirtualRenderer() +cocos2d::Node* UITextField::getVirtualRenderer() { return _textFieldRenderer; } @@ -567,4 +568,34 @@ const char* UITextField::getDescription() const return "TextField"; } +void UITextField::attachWithIME() +{ + _textFieldRenderer->attachWithIME(); +} + +UIWidget* UITextField::createCloneInstance() +{ + return UITextField::create(); +} + +void UITextField::copySpecialProperties(UIWidget *widget) +{ + UITextField* textField = dynamic_cast(widget); + if (textField) + { + setText(textField->_textFieldRenderer->getString()); + setPlaceHolder(textField->getStringValue()); + setFontSize(textField->_textFieldRenderer->getFontSize()); + setFontName(textField->_textFieldRenderer->getFontName()); + setMaxLengthEnabled(textField->isMaxLengthEnabled()); + setMaxLength(textField->getMaxLength()); + setPasswordEnabled(textField->isPasswordEnabled()); + setPasswordStyleText(textField->_passwordStyleText.c_str()); + setAttachWithIME(textField->getAttachWithIME()); + setDetachWithIME(textField->getDetachWithIME()); + setInsertText(textField->getInsertText()); + setDeleteBackward(textField->getDeleteBackward()); + } +} + } \ No newline at end of file diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index 31b7052443..ac5641114f 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -30,6 +30,10 @@ namespace gui { +/** + * @js NA + * @lua NA + */ class UICCTextField: public cocos2d::TextFieldTTF, public cocos2d::TextFieldDelegate { public: @@ -70,32 +74,32 @@ public: bool getInsertText(); void setDeleteBackward(bool deleteBackward); bool getDeleteBackward(); - - protected: - bool m_bMaxLengthEnabled; - int m_nMaxLength; - bool m_bPasswordEnabled; - std::string m_strPasswordStyleText; - bool m_bAttachWithIME; - bool m_bDetachWithIME; - bool m_bInsertText; - bool m_bDeleteBackward; + bool _maxLengthEnabled; + int _maxLength; + bool _passwordEnabled; + std::string _passwordStyleText; + bool _attachWithIME; + bool _detachWithIME; + bool _insertText; + bool _deleteBackward; }; - typedef enum { TEXTFIELD_EVENT_ATTACH_WITH_IME, TEXTFIELD_EVENT_DETACH_WITH_IME, - TEXTFIELD_EVENT_INDERT_TEXT, + TEXTFIELD_EVENT_INSERT_TEXT, TEXTFIELD_EVENT_DELETE_BACKWARD, }TextFiledEventType; typedef void (cocos2d::Object::*SEL_TextFieldEvent)(cocos2d::Object*, TextFiledEventType); #define textfieldeventselector(_SELECTOR) (SEL_TextFieldEvent)(&_SELECTOR) -//class UITextField : public UIWidget +/** class UITextField : public UIWidget +* @js NA +* @lua NA +*/ class UITextField : public UIWidget { public: @@ -129,22 +133,19 @@ public: bool getDeleteBackward(); void setDeleteBackward(bool deleteBackward); void addEventListener(cocos2d::Object* target, SEL_TextFieldEvent selecor); + virtual void setAnchorPoint(const cocos2d::Point &pt); virtual void setColor(const cocos2d::Color3B &color); virtual void setOpacity(int opacity); + /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; - /*compatibel*/ - /** - * These methods will be removed - */ - void setMaxLengthEnable(bool is){setMaxLengthEnabled(is);}; - void setPasswordEnable(bool is){setPasswordEnabled(is);}; - /************/ + virtual const cocos2d::Size& getContentSize() const; virtual cocos2d::Node* getVirtualRenderer(); + void attachWithIME(); protected: // event void attachWithIMEEvent(); @@ -153,9 +154,11 @@ protected: void deleteBackwardEvent(); virtual void onSizeChanged(); void textfieldRendererScaleChangedWithSize(); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); protected: UICCTextField* _textFieldRenderer; - + float _touchWidth; float _touchHeight; bool _useTouchArea; @@ -163,6 +166,7 @@ protected: cocos2d::Object* _eventListener; SEL_TextFieldEvent _eventSelector; + std::string _passwordStyleText; }; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index ea9651582b..00ee50680c 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -24,11 +24,9 @@ #include "gui/UIWidget.h" #include "gui/UILayer.h" -#include "gui/Layout.h" +#include "gui/UILayout.h" #include "gui/UIHelper.h" - using namespace cocos2d; - namespace gui { #define DYNAMIC_CAST_CCBLENDPROTOCOL dynamic_cast(_renderer) @@ -45,31 +43,31 @@ _touchEnabled(false), _touchPassedEnabled(false), _focus(false), _widgetZOrder(0), -_anchorPoint(Point(0.5f, 0.5f)), +_anchorPoint(cocos2d::Point(0.5f, 0.5f)), _widgetParent(NULL), _brightStyle(BRIGHT_NONE), _updateEnabled(false), _renderer(NULL), -_touchStartPos(Point::ZERO), -_touchMovePos(Point::ZERO), -_touchEndPos(Point::ZERO), +_touchStartPos(cocos2d::Point::ZERO), +_touchMovePos(cocos2d::Point::ZERO), +_touchEndPos(cocos2d::Point::ZERO), _touchEventListener(NULL), _touchEventSelector(NULL), _widgetTag(-1), _name("default"), _widgetType(WidgetTypeWidget), _actionTag(0), -_size(Size::ZERO), -_customSize(Size::ZERO), -_layoutParameter(NULL), +_size(cocos2d::Size::ZERO), +_customSize(cocos2d::Size::ZERO), +_layoutParameterDictionary(NULL), _ignoreSize(false), _children(NULL), _affectByClipping(false), _scheduler(NULL), _sizeType(SIZE_ABSOLUTE), -_sizePercent(Point::ZERO), +_sizePercent(cocos2d::Point::ZERO), _positionType(POSITION_ABSOLUTE), -_positionPercent(Point::ZERO), +_positionPercent(cocos2d::Point::ZERO), _isRunning(false) { @@ -79,7 +77,8 @@ UIWidget::~UIWidget() { releaseResoures(); setParent(NULL); - CC_SAFE_RELEASE_NULL(_layoutParameter); + _layoutParameterDictionary->removeAllObjects(); + CC_SAFE_RELEASE(_layoutParameterDictionary); CC_SAFE_RELEASE(_scheduler); } @@ -97,12 +96,14 @@ UIWidget* UIWidget::create() bool UIWidget::init() { - _children = Array::create(); + _children = cocos2d::Array::create(); _children->retain(); + _layoutParameterDictionary = cocos2d::Dictionary::create(); + CC_SAFE_RETAIN(_layoutParameterDictionary); initRenderer(); _renderer->retain(); _renderer->setZOrder(_widgetZOrder); - RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* renderRGBA = DYNAMIC_CAST_CCRGBAPROTOCOL; if (renderRGBA) { renderRGBA->setCascadeColorEnabled(true); @@ -110,14 +111,13 @@ bool UIWidget::init() } setBright(true); ignoreContentAdaptWithSize(true); - _scheduler = Director::getInstance()->getScheduler(); + _scheduler = cocos2d::Director::getInstance()->getScheduler(); CC_SAFE_RETAIN(_scheduler); return true; } void UIWidget::releaseResoures() { - setUpdateEnabled(false); removeAllChildren(); _children->release(); _renderer->removeAllChildrenWithCleanup(true); @@ -157,7 +157,7 @@ bool UIWidget::addChild(UIWidget *child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -203,7 +203,7 @@ bool UIWidget::removeChild(UIWidget *child) { child->onExit(); } - child->disableUpdate(); + child->setUpdateEnabled(false); child->setParent(NULL); _renderer->removeChild(child->getRenderer()); _children->removeObject(child); @@ -246,7 +246,7 @@ void UIWidget::reorderChild(UIWidget* child) else { bool seekSucceed = false; - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; for (int i=childrenCount-1; i>=0; --i) { UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); @@ -274,21 +274,6 @@ void UIWidget::reorderChild(UIWidget* child) CC_SAFE_RELEASE(child); } -void UIWidget::disableUpdate() -{ - if (_scheduler) - { - _scheduler->unscheduleUpdateForTarget(this); - } - int childrenCount = _children->data->num; - ccArray* arrayChildren = _children->data; - for (int i=0; iarr[i]); - child->disableUpdate(); - } -} - void UIWidget::setEnabled(bool enabled) { _enabled = enabled; @@ -299,9 +284,9 @@ void UIWidget::setEnabled(bool enabled) } else { - dynamic_cast(_renderer)->setEnabled(enabled); + dynamic_cast(_renderer)->setEnabled(enabled); } - ccArray* arrayChildren = _children->data; + cocos2d::ccArray* arrayChildren = _children->data; int childrenCount = arrayChildren->num; for (int i = 0; i < childrenCount; i++) { @@ -312,15 +297,15 @@ void UIWidget::setEnabled(bool enabled) UIWidget* UIWidget::getChildByName(const char *name) { - return CCUIHELPER->seekWidgetByName(this, name); + return UIHelper::seekWidgetByName(this, name); } UIWidget* UIWidget::getChildByTag(int tag) { - return CCUIHELPER->seekWidgetByTag(this, tag); + return UIHelper::seekWidgetByTag(this, tag); } -Array* UIWidget::getChildren() +cocos2d::Array* UIWidget::getChildren() { return _children; } @@ -330,7 +315,7 @@ void UIWidget::initRenderer() _renderer = GUIRenderer::create(); } -void UIWidget::setSize(const Size &size) +void UIWidget::setSize(const cocos2d::Size &size) { _customSize = size; if (_ignoreSize) @@ -343,19 +328,19 @@ void UIWidget::setSize(const Size &size) } if (_isRunning) { - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); } onSizeChanged(); } -void UIWidget::setSizePercent(const Point &percent) +void UIWidget::setSizePercent(const cocos2d::Point &percent) { _sizePercent = percent; if (!_isRunning) { return; } - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * percent.x , _widgetParent->getSize().height * percent.y); if (_ignoreSize) { _size = getContentSize(); @@ -381,11 +366,11 @@ void UIWidget::updateSizeAndPosition() { _size = _customSize; } - _sizePercent = (_widgetParent == NULL) ? Point::ZERO : Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); + _sizePercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(_customSize.width / _widgetParent->getSize().width, _customSize.height / _widgetParent->getSize().height); break; case SIZE_PERCENT: { - Size cSize = (_widgetParent == NULL) ? Size::ZERO : Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); + cocos2d::Size cSize = (_widgetParent == NULL) ? cocos2d::Size::ZERO : cocos2d::Size(_widgetParent->getSize().width * _sizePercent.x , _widgetParent->getSize().height * _sizePercent.y); if (_ignoreSize) { _size = getContentSize(); @@ -401,16 +386,16 @@ void UIWidget::updateSizeAndPosition() break; } onSizeChanged(); - Point absPos = getPosition(); + cocos2d::Point absPos = getPosition(); switch (_positionType) { case POSITION_ABSOLUTE: - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(absPos.x / _widgetParent->getSize().width, absPos.y / _widgetParent->getSize().height); break; case POSITION_PERCENT: { - Size parentSize = _widgetParent->getSize(); - absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); } break; default: @@ -434,7 +419,7 @@ void UIWidget::ignoreContentAdaptWithSize(bool ignore) _ignoreSize = ignore; if (_ignoreSize) { - Size s = getContentSize(); + cocos2d::Size s = getContentSize(); _size = s; } else @@ -449,27 +434,27 @@ bool UIWidget::isIgnoreContentAdaptWithSize() const return _ignoreSize; } -const Size& UIWidget::getSize() const +const cocos2d::Size& UIWidget::getSize() const { return _size; } -const Point& UIWidget::getSizePercent() const +const cocos2d::Point& UIWidget::getSizePercent() const { return _sizePercent; } -Point UIWidget::getWorldPosition() +cocos2d::Point UIWidget::getWorldPosition() { - return _renderer->convertToWorldSpace(Point::ZERO); + return _renderer->convertToWorldSpace(cocos2d::Point::ZERO); } -Point UIWidget::convertToWorldSpace(const Point& pt) +cocos2d::Point UIWidget::convertToWorldSpace(const cocos2d::Point& pt) { return _renderer->convertToWorldSpace(pt); } -Node* UIWidget::getVirtualRenderer() +cocos2d::Node* UIWidget::getVirtualRenderer() { return _renderer; } @@ -479,7 +464,7 @@ void UIWidget::onSizeChanged() } -const Size& UIWidget::getContentSize() const +const cocos2d::Size& UIWidget::getContentSize() const { return _size; } @@ -511,6 +496,10 @@ bool UIWidget::isTouchEnabled() const void UIWidget::setUpdateEnabled(bool enable) { + if (enable == _updateEnabled) + { + return; + } _updateEnabled = enable; if (enable) { @@ -616,7 +605,7 @@ void UIWidget::didNotSelectSelf() } -bool UIWidget::onTouchBegan(const Point &touchPoint) +bool UIWidget::onTouchBegan(const cocos2d::Point &touchPoint) { setFocused(true); _touchStartPos.x = touchPoint.x; @@ -629,7 +618,7 @@ bool UIWidget::onTouchBegan(const Point &touchPoint) return _touchPassedEnabled; } -void UIWidget::onTouchMoved(const Point &touchPoint) +void UIWidget::onTouchMoved(const cocos2d::Point &touchPoint) { _touchMovePos.x = touchPoint.x; _touchMovePos.y = touchPoint.y; @@ -641,7 +630,7 @@ void UIWidget::onTouchMoved(const Point &touchPoint) moveEvent(); } -void UIWidget::onTouchEnded(const Point &touchPoint) +void UIWidget::onTouchEnded(const cocos2d::Point &touchPoint) { _touchEndPos.x = touchPoint.x; _touchEndPos.y = touchPoint.y; @@ -661,13 +650,13 @@ void UIWidget::onTouchEnded(const Point &touchPoint) } } -void UIWidget::onTouchCancelled(const Point &touchPoint) +void UIWidget::onTouchCancelled(const cocos2d::Point &touchPoint) { setFocused(false); cancelUpEvent(); } -void UIWidget::onTouchLongClicked(const Point &touchPoint) +void UIWidget::onTouchLongClicked(const cocos2d::Point &touchPoint) { longClickEvent(); } @@ -709,31 +698,31 @@ void UIWidget::longClickEvent() } -void UIWidget::addTouchEventListener(Object *target, SEL_TouchEvent selector) +void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { _touchEventListener = target; _touchEventSelector = selector; } -Node* UIWidget::getRenderer() +cocos2d::Node* UIWidget::getRenderer() { return _renderer; } -void UIWidget::addRenderer(Node* renderer, int zOrder) +void UIWidget::addRenderer(cocos2d::Node* renderer, int zOrder) { _renderer->addChild(renderer, zOrder); } -void UIWidget::removeRenderer(Node* renderer, bool cleanup) +void UIWidget::removeRenderer(cocos2d::Node* renderer, bool cleanup) { _renderer->removeChild(renderer,cleanup); } -bool UIWidget::hitTest(const Point &pt) +bool UIWidget::hitTest(const cocos2d::Point &pt) { - Point nsp = _renderer->convertToNodeSpace(pt); - Rect bb = Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); + cocos2d::Point nsp = _renderer->convertToNodeSpace(pt); + cocos2d::Rect bb = cocos2d::Rect(-_size.width * _anchorPoint.x, -_size.height * _anchorPoint.y, _size.width, _size.height); if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) { return true; @@ -741,14 +730,14 @@ bool UIWidget::hitTest(const Point &pt) return false; } -bool UIWidget::clippingParentAreaContainPoint(const Point &pt) +bool UIWidget::clippingParentAreaContainPoint(const cocos2d::Point &pt) { _affectByClipping = false; UIWidget* parent = getParent(); UIWidget* clippingParent = NULL; while (parent) { - Layout* layoutParent = dynamic_cast(parent); + UILayout* layoutParent = dynamic_cast(parent); if (layoutParent) { if (layoutParent->isClippingEnabled()) @@ -783,7 +772,7 @@ bool UIWidget::clippingParentAreaContainPoint(const Point &pt) return true; } -void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &touchPoint) +void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const cocos2d::Point &touchPoint) { if (_widgetParent) { @@ -791,27 +780,27 @@ void UIWidget::checkChildInfo(int handleState, UIWidget *sender, const Point &to } } -void UIWidget::setPosition(const Point &pos) +void UIWidget::setPosition(const cocos2d::Point &pos) { if (_isRunning) { - _positionPercent = (_widgetParent == NULL) ? Point::ZERO : Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); + _positionPercent = (_widgetParent == NULL) ? cocos2d::Point::ZERO : cocos2d::Point(pos.x / _widgetParent->getSize().width, pos.y / _widgetParent->getSize().height); } _renderer->setPosition(pos); } -void UIWidget::setPositionPercent(const Point &percent) +void UIWidget::setPositionPercent(const cocos2d::Point &percent) { _positionPercent = percent; if (_isRunning) { - Size parentSize = _widgetParent->getSize(); - Point absPos = Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); + cocos2d::Size parentSize = _widgetParent->getSize(); + cocos2d::Point absPos = cocos2d::Point(parentSize.width * _positionPercent.x, parentSize.height * _positionPercent.y); _renderer->setPosition(absPos); } } -void UIWidget::setAnchorPoint(const Point &pt) +void UIWidget::setAnchorPoint(const cocos2d::Point &pt) { _anchorPoint = pt; _renderer->setAnchorPoint(pt); @@ -822,12 +811,12 @@ void UIWidget::updateAnchorPoint() setAnchorPoint(_anchorPoint); } -const Point& UIWidget::getPosition() +const cocos2d::Point& UIWidget::getPosition() { return _renderer->getPosition(); } -const Point& UIWidget::getPositionPercent() +const cocos2d::Point& UIWidget::getPositionPercent() { return _positionPercent; } @@ -842,7 +831,7 @@ PositionType UIWidget::getPositionType() const return _positionType; } -const Point& UIWidget::getAnchorPoint() +const cocos2d::Point& UIWidget::getAnchorPoint() { return _anchorPoint; } @@ -930,36 +919,12 @@ bool UIWidget::isEnabled() const float UIWidget::getLeftInParent() { - float leftPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - leftPos = getPosition().x - getAnchorPoint().x * _size.width; - break; - case WidgetTypeContainer: - leftPos = getPosition().x; - break; - default: - break; - } - return leftPos; + return getPosition().x - getAnchorPoint().x * _size.width;; } float UIWidget::getBottomInParent() { - float bottomPos = 0.0f; - switch (_widgetType) - { - case WidgetTypeWidget: - bottomPos = getPosition().y - getAnchorPoint().y * _size.height; - break; - case WidgetTypeContainer: - bottomPos = getPosition().y; - break; - default: - break; - } - return bottomPos; + return getPosition().y - getAnchorPoint().y * _size.height;; } float UIWidget::getRightInParent() @@ -982,17 +947,17 @@ void UIWidget::setParent(UIWidget* parent) _widgetParent = parent; } -Action* UIWidget::runAction(Action *action) +cocos2d::Action* UIWidget::runAction(cocos2d::Action *action) { return _renderer->runAction(action); } -void UIWidget::setActionManager(ActionManager *actionManager) +void UIWidget::setActionManager(cocos2d::ActionManager *actionManager) { _renderer->setActionManager(actionManager); } -ActionManager* UIWidget::getActionManager() +cocos2d::ActionManager* UIWidget::getActionManager() { return _renderer->getActionManager(); } @@ -1002,7 +967,7 @@ void UIWidget::stopAllActions() _renderer->stopAllActions(); } -void UIWidget::stopAction(Action *action) +void UIWidget::stopAction(cocos2d::Action *action) { _renderer->stopAction(action); } @@ -1012,33 +977,33 @@ void UIWidget::stopActionByTag(int tag) _renderer->stopActionByTag(tag); } -Action* UIWidget::getActionByTag(int tag) +cocos2d::Action* UIWidget::getActionByTag(int tag) { return _renderer->getActionByTag(tag); } -void UIWidget::setColor(const Color3B &color) +void UIWidget::setColor(const cocos2d::Color3B &color) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setColor(color); } } -const Color3B& UIWidget::getColor() +const cocos2d::Color3B& UIWidget::getColor() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getColor(); } - return Color3B::WHITE; + return cocos2d::Color3B::WHITE; } void UIWidget::setOpacity(int opacity) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setOpacity(opacity); @@ -1047,7 +1012,7 @@ void UIWidget::setOpacity(int opacity) int UIWidget::getOpacity() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->getOpacity(); @@ -1057,7 +1022,7 @@ int UIWidget::getOpacity() bool UIWidget::isCascadeOpacityEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeOpacityEnabled(); @@ -1067,7 +1032,7 @@ bool UIWidget::isCascadeOpacityEnabled() void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeOpacityEnabled(cascadeOpacityEnabled); @@ -1076,7 +1041,7 @@ void UIWidget::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) bool UIWidget::isCascadeColorEnabled() { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { return rgbap->isCascadeColorEnabled(); @@ -1086,33 +1051,33 @@ bool UIWidget::isCascadeColorEnabled() void UIWidget::setCascadeColorEnabled(bool cascadeColorEnabled) { - RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; + cocos2d::RGBAProtocol* rgbap = DYNAMIC_CAST_CCRGBAPROTOCOL; if (rgbap) { rgbap->setCascadeColorEnabled(cascadeColorEnabled); } } -void UIWidget::setBlendFunc(BlendFunc blendFunc) +void UIWidget::setBlendFunc(cocos2d::BlendFunc blendFunc) { - BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; + cocos2d::BlendProtocol * blendNode = DYNAMIC_CAST_CCBLENDPROTOCOL; if (blendNode) { blendNode->setBlendFunc(blendFunc); } } -const Point& UIWidget::getTouchStartPos() +const cocos2d::Point& UIWidget::getTouchStartPos() { return _touchStartPos; } -const Point& UIWidget::getTouchMovePos() +const cocos2d::Point& UIWidget::getTouchMovePos() { return _touchMovePos; } -const Point& UIWidget::getTouchEndPos() +const cocos2d::Point& UIWidget::getTouchEndPos() { return _touchEndPos; } @@ -1142,19 +1107,14 @@ WidgetType UIWidget::getWidgetType() const return _widgetType; } -void UIWidget::setLayoutParameter(LayoutParameter *parameter) +void UIWidget::setLayoutParameter(UILayoutParameter *parameter) { - if (_layoutParameter) - { - CC_SAFE_RELEASE_NULL(_layoutParameter); - } - _layoutParameter = parameter; - CC_SAFE_RETAIN(_layoutParameter); + _layoutParameterDictionary->setObject(parameter, parameter->getLayoutType()); } -LayoutParameter* UIWidget::getLayoutParameter() +UILayoutParameter* UIWidget::getLayoutParameter(LayoutParameterType type) { - return _layoutParameter; + return dynamic_cast(_layoutParameterDictionary->objectForKey(type)); } const char* UIWidget::getDescription() const @@ -1162,6 +1122,71 @@ const char* UIWidget::getDescription() const return "Widget"; } +UIWidget* UIWidget::clone() +{ + UIWidget* clonedWidget = createCloneInstance(); + clonedWidget->copyProperties(this); + clonedWidget->copyClonedWidgetChildren(this); + return clonedWidget; +} + +UIWidget* UIWidget::createCloneInstance() +{ + return UIWidget::create(); +} + +void UIWidget::copyClonedWidgetChildren(UIWidget* model) +{ + cocos2d::ccArray* arrayWidgetChildren = model->getChildren()->data; + int length = arrayWidgetChildren->num; + for (int i=0; iarr[i]); + addChild(child->clone()); + } +} + +void UIWidget::copySpecialProperties(UIWidget* model) +{ + +} + +void UIWidget::copyProperties(UIWidget *widget) +{ + setEnabled(widget->isEnabled()); + setVisible(widget->isVisible()); + setBright(widget->isBright()); + setTouchEnabled(widget->isTouchEnabled()); + _touchPassedEnabled = false; + setZOrder(widget->getZOrder()); + setUpdateEnabled(widget->isUpdateEnabled()); + setTag(widget->getTag()); + setName(widget->getName()); + setActionTag(widget->getActionTag()); + _ignoreSize = widget->_ignoreSize; + _size = widget->_size; + _customSize = widget->_customSize; + copySpecialProperties(widget); + _sizeType = widget->getSizeType(); + _sizePercent = widget->_sizePercent; + _positionType = widget->_positionType; + _positionPercent = widget->_positionPercent; + setPosition(widget->getPosition()); + setAnchorPoint(widget->getAnchorPoint()); + setScaleX(widget->getScaleX()); + setScaleY(widget->getScaleY()); + setRotation(widget->getRotation()); + setRotationX(widget->getRotationX()); + setRotationY(widget->getRotationY()); + setFlipX(widget->isFlipX()); + setFlipY(widget->isFlipY()); + setColor(widget->getColor()); + setOpacity(widget->getOpacity()); + setCascadeOpacityEnabled(widget->isCascadeOpacityEnabled()); + setCascadeColorEnabled(widget->isCascadeColorEnabled()); + onSizeChanged(); +} + /*temp action*/ void UIWidget::setActionTag(int tag) { @@ -1214,7 +1239,7 @@ void GUIRenderer::visit() { return; } - NodeRGBA::visit(); + cocos2d::NodeRGBA::visit(); } - + } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index ebc7e8a665..d8f35578f4 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -27,9 +27,9 @@ #include "cocos2d.h" #include "gui/UILayoutDefine.h" -#include "gui/LayoutParameter.h" -namespace gui { +#include "gui/UILayoutParameter.h" +namespace gui { typedef enum { @@ -72,11 +72,10 @@ typedef enum typedef void (cocos2d::Object::*SEL_TouchEvent)(cocos2d::Object*,TouchEventType); #define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) - -//class UILayer; -/*temp action*/ -class UIActionNode; - +/** +* @js NA +* @lua NA +*/ class UIWidget : public cocos2d::Object { public: @@ -260,12 +259,7 @@ public: * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. */ virtual void removeAllChildren(); - - /** - * Unschedules the "update" method. - */ - void disableUpdate(); - + /** * Reorders a child according to a new z value. * @@ -304,27 +298,27 @@ public: /** * Gets the renderer of widget * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * - * @return a CCNode object + * @return a Node object */ cocos2d::Node* getRenderer(); /** - * Add a CCNode for rendering. + * Add a Node for rendering. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node * - * @param zOrder Z order for drawing priority. Please refer to CCNode::setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to Node::setZOrder(int) */ void addRenderer(cocos2d::Node* renderer, int zOrder); /** - * Remove a CCNode from widget. + * Remove a Node from widget. * - * renderer is a CCNode, it's for drawing + * renderer is a Node, it's for drawing * * @param renderer A render node which needs to be removed * @@ -359,7 +353,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param position The position (x,y) of the widget in OpenGL coordinates @@ -369,7 +363,7 @@ public: /** * Changes the position (x,y) of the widget in OpenGL coordinates * - * Usually we use ccp(x,y) to compose Point object. + * Usually we use p(x,y) to compose Point object. * The original point (0,0) is at the left-bottom corner of screen. * * @param percent The percent (x,y) of the widget in OpenGL coordinates @@ -809,15 +803,21 @@ public: * @see LayoutParameter * * @param LayoutParameter pointer + * + * @param type Relative or Linear */ - void setLayoutParameter(LayoutParameter* parameter); + void setLayoutParameter(UILayoutParameter* parameter); /** * Gets LayoutParameter of widget. * * @see LayoutParameter + * + * @param type Relative or Linear + * + * @return LayoutParameter */ - LayoutParameter* getLayoutParameter(); + UILayoutParameter* getLayoutParameter(LayoutParameterType type); /** * Ignore the widget size @@ -850,7 +850,7 @@ public: * * For example, a button's Virtual Renderer is it's texture renderer. * - * @return CCNode pointer. + * @return Node pointer. */ virtual cocos2d::Node* getVirtualRenderer(); @@ -871,14 +871,15 @@ public: */ virtual const cocos2d::Size& getContentSize() const; - virtual void onEnter(); - virtual void onExit(); - /** * Returns the "class name" of widget. */ virtual const char* getDescription() const; + UIWidget* clone(); + + virtual void onEnter(); + virtual void onExit(); /*temp action*/ void setActionTag(int tag); int getActionTag(); @@ -913,6 +914,10 @@ protected: */ virtual void releaseResoures(); void updateSizeAndPosition(); + void copyProperties(UIWidget* model); + virtual UIWidget* createCloneInstance(); + virtual void copySpecialProperties(UIWidget* model); + virtual void copyClonedWidgetChildren(UIWidget* model); protected: bool _enabled; ///< Highest control of widget bool _visible; ///< is this widget visible @@ -930,7 +935,7 @@ protected: cocos2d::Point _touchMovePos; ///< touch moved point cocos2d::Point _touchEndPos; ///< touch ended point - cocos2d::Object* _touchEventListener; + Object* _touchEventListener; SEL_TouchEvent _touchEventSelector; @@ -941,7 +946,7 @@ protected: int _actionTag; cocos2d::Size _size; cocos2d::Size _customSize; - LayoutParameter* _layoutParameter; + cocos2d::Dictionary* _layoutParameterDictionary; bool _ignoreSize; cocos2d::Array* _children; bool _affectByClipping; @@ -954,7 +959,10 @@ protected: cocos2d::Point _positionPercent; bool _isRunning; }; - +/** +* @js NA +* @lua NA +*/ class GUIRenderer : public cocos2d::NodeRGBA { public: @@ -969,5 +977,4 @@ protected: }; } - #endif /* defined(__UIWidget__) */ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 1ba28914df..750b562a67 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -19,7 +19,6 @@ CocosGUITestScene::~CocosGUITestScene() { cocostudio::SceneReader::getInstance()->purgeSceneReader(); cocostudio::ActionManagerEx::purgeActionManager(); - gui::UIHelper::purgeUIHelper(); } void CocosGUITestScene::runThisTest() diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp index e80ff2fd01..dacec9ba84 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.cpp @@ -44,78 +44,25 @@ bool UIDragPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/scrollviewbg.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BERTH_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LFETTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BERTH_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Berth To Bottom")->getCString()); - break; - - default: - break; - } -} - // UIDragPanelTest_Bounce UIDragPanelTest_Bounce::UIDragPanelTest_Bounce() : m_pDisplayValueLabel(NULL) @@ -151,76 +98,23 @@ bool UIDragPanelTest_Bounce::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - - // Create the dragpanel - UIDragPanel* dragPanel = UIDragPanel::create(); - dragPanel->setTouchEnabled(true); - dragPanel->setBounceEnable(true); - dragPanel->setBackGroundImageScale9Enabled(true); - dragPanel->setBackGroundImage("cocosgui/green_edit.png"); - dragPanel->setSize(Size(210, 122.5)); - Size backgroundSize = background->getContentSize(); - dragPanel->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - dragPanel->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - dragPanel->getSize().height) / 2)); - dragPanel->addEventListener(this, dragpaneleventselector(UIDragPanelTest_Bounce::dragPanelEvent)); - - UIImageView* imageView = UIImageView::create(); - imageView->setTouchEnabled(true); - imageView->loadTexture("cocosgui/b11.png"); - dragPanel->addChild(imageView); - - dragPanel->setInnerContainerSize(imageView->getContentSize()); - Size innerSize = dragPanel->getInnerContainerSize(); - imageView->setPosition(Point(innerSize.width / 2, innerSize.height / 2)); - - m_pUiLayer->addWidget(dragPanel); - + UIScrollView* sc = UIScrollView::create(); + sc->setBackGroundColor(Color3B::GREEN); + sc->setBackGroundColorType(LAYOUT_COLOR_SOLID); + sc->setBounceEnabled(true); + sc->setDirection(SCROLLVIEW_DIR_BOTH); + sc->setInnerContainerSize(Size(480, 320)); + sc->setSize(Size(100,100)); + sc->setPosition(Point(100,100)); + sc->scrollToPercentBothDirection(Point(50, 50), 1, true); + UIImageView* iv = UIImageView::create(); + iv->loadTexture("cocosgui/Hello.png"); + iv->setPosition(Point(240, 160)); + sc->addChild(iv); + m_pUiLayer->addWidget(sc); return true; } return false; } -void UIDragPanelTest_Bounce::dragPanelEvent(Object *pSender, DragPanelEventType type) -{ - switch (type) - { - case DRAGPANEL_EVENT_BOUNCE_LEFTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTBOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Bottom")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHTTOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_LEFT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Left")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_TOP: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Top")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_RIGHT: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Right")->getCString()); - break; - - case DRAGPANEL_EVENT_BOUNCE_BOTTOM: - m_pDisplayValueLabel->setText(CCString::createWithFormat("Bounce To Bottom")->getCString()); - break; - - default: - break; - } -} diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h index 76f8469154..b8967247f3 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIDragPanelTest/UIDragPanelTest.h @@ -33,7 +33,6 @@ public: UIDragPanelTest(); ~UIDragPanelTest(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest) @@ -46,7 +45,6 @@ public: UIDragPanelTest_Bounce(); ~UIDragPanelTest_Bounce(); bool init(); - void dragPanelEvent(Object* pSender, DragPanelEventType type); protected: UI_SCENE_CREATE_FUNC(UIDragPanelTest_Bounce) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp index 6681c744ee..c2163e8059 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp @@ -45,54 +45,23 @@ bool UIListViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + UIListView* lv = UIListView::create(); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); + + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listWidth = listView->getSize().width; - float listHeight = listView->getSize().height; - - for (int i = 0; i < 5; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size panel_size = layout->getSize(); - layout->setPosition(Point((listWidth - panel_size.width) / 2, - (listHeight - (panel_size.height + panel_size.height * 0.25)) - i * (panel_size.height + panel_size.height * 0.25))); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Vertical::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } @@ -100,46 +69,6 @@ bool UIListViewTest_Vertical::init() return false; } -void UIListViewTest_Vertical::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} - // UIListViewTest_Horizontal UIListViewTest_Horizontal::UIListViewTest_Horizontal() @@ -176,97 +105,26 @@ bool UIListViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + + UIListView* lv = UIListView::create(); + lv->setDirection(SCROLLVIEW_DIR_HORIZONTAL); + UIButton* model = UIButton::create(); + model->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); + lv->setItemModel(model); - // Create the list view - m_nCount = 0; - m_array = CCArray::create(); - m_array->retain(); - for (int i = 0; i < 20; ++i) + for (int i=0; i<20; i++) { - String* ccstr = String::createWithFormat("object_%d", i); - m_array->addObject(ccstr); + lv->pushBackDefaultItem(); } - - UIListView *listView = UIListView::create(); - listView->setDirection(LISTVIEW_DIR_HORIZONTAL); - listView->setTouchEnabled(true); - listView->setBackGroundImageScale9Enabled(true); - listView->setBackGroundImage("cocosgui/green_edit.png"); - listView->setSize(Size(240, 130)); - Size backgroundSize = background->getContentSize(); - listView->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + - (backgroundSize.width - listView->getSize().width) / 2, - (widgetSize.height - backgroundSize.height) / 2 + - (backgroundSize.height - listView->getSize().height) / 2)); - - float listHeight = listView->getSize().height; - - for (int i = 0; i < 3; ++i) - { - UIButton* textButton = UIButton::create(); - textButton->setName("TextButton"); - textButton->setTouchEnabled(true); - textButton->loadTextures("cocosgui/backtotoppressed.png", "cocosgui/backtotopnormal.png", ""); - - Layout *layout = Layout::create(); - layout->setName(String::createWithFormat("panel_%i", i)->getCString()); - layout->setSize(Size(textButton->getSize().width, textButton->getSize().height)); - textButton->setPosition(Point(layout->getSize().width / 2, layout->getSize().height / 2)); - layout->addChild(textButton); - - Size layout_size = layout->getSize(); - layout->setPosition(Point(0 + (layout_size.width * 0.2) + i * (layout_size.width + layout_size.width * 0.2), - (listHeight - layout_size.height) / 2)); - - listView->addChild(layout); - } - listView->addEventListenter(this, listvieweventselector(UIListViewTest_Horizontal::listViewEvent)); - listView->initChildWithDataLength(m_array->count()); - m_pUiLayer->addWidget(listView); - + lv->setItemsMargin(10); + lv->setGravity(LISTVIEW_GRAVITY_CENTER_VERTICAL); + lv->setSize(Size(100, 100)); + lv->setBackGroundColorType(LAYOUT_COLOR_SOLID); + lv->setBackGroundColor(Color3B::GREEN); + lv->setPosition(Point(100, 100)); + m_pUiLayer->addWidget(lv); return true; } return false; -} - -void UIListViewTest_Horizontal::listViewEvent(Object *pSender, ListViewEventType type) -{ - switch (type) - { - case LISTVIEW_EVENT_INIT_CHILD: - { - String* ccstr = static_cast(m_array->getObjectAtIndex(m_nCount)); - UIListView* list = dynamic_cast(pSender); - - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - - m_nCount++; - } - break; - - case LISTVIEW_EVENT_UPDATE_CHILD: - { - UIListView* list = dynamic_cast(pSender); - int index = list->getUpdateDataIndex(); - - if (index < 0 || index >= list->getDataLength()) - { - list->setUpdateSuccess(false); - } - - String* ccstr = static_cast(m_array->getObjectAtIndex(index)); - Layout* layout = dynamic_cast(list->getUpdateChild()); - UIButton* textButton = dynamic_cast(layout->getChildByName("TextButton")); - textButton->setTitleText(ccstr->getCString()); - list->setUpdateSuccess(true); - } - break; - - default: - break; - } -} +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h index b2725e33ee..4dee33553c 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h @@ -33,7 +33,6 @@ public: UIListViewTest_Vertical(); ~UIListViewTest_Vertical(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Vertical) @@ -49,7 +48,6 @@ public: UIListViewTest_Horizontal(); ~UIListViewTest_Horizontal(); bool init(); - void listViewEvent(Object* pSender, ListViewEventType type); protected: UI_SCENE_CREATE_FUNC(UIListViewTest_Horizontal) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp index 22b97ef9e6..ce5028ae35 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp @@ -44,7 +44,7 @@ bool UIPageViewTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the page view UIPageView* pageView = UIPageView::create(); @@ -58,7 +58,7 @@ bool UIPageViewTest::init() for (int i = 0; i < 3; ++i) { - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(240, 130)); UIImageView* imageView = UIImageView::create(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp index 49674298bc..94dbb02819 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPanelTest/UIPanelTest.cpp @@ -34,10 +34,10 @@ bool UIPanelTest::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); layout->setPosition(Point((widgetSize.width - backgroundSize.width) / 2 + @@ -98,10 +98,10 @@ bool UIPanelTest_Color::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with color render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); layout->setBackGroundColor(Color3B(128, 128, 128)); layout->setSize(Size(280, 150)); @@ -163,10 +163,10 @@ bool UIPanelTest_Gradient::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with gradient render - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundColorType(LAYOUT_COLOR_GRADIENT); layout->setBackGroundColor(Color3B(64, 64, 64), Color3B(192, 192, 192)); layout->setSize(Size(280, 150)); @@ -228,10 +228,10 @@ bool UIPanelTest_BackGroundImage::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setClippingEnabled(true); layout->setBackGroundImage("cocosgui/Hello.png"); layout->setSize(Size(280, 150)); @@ -293,10 +293,10 @@ bool UIPanelTest_BackGroundImage_Scale9::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout with background image - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setBackGroundImageScale9Enabled(true); layout->setBackGroundImage("cocosgui/green_edit.png"); layout->setSize(Size(280, 150)); @@ -358,10 +358,10 @@ bool UIPanelTest_Layout_Linear_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_VERTICAL); layout->setSize(Size(280, 150)); Size backgroundSize = background->getSize(); @@ -377,7 +377,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp1->setMargin(UIMargin(0, 5, 0, 10)); @@ -389,7 +389,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -402,7 +402,7 @@ bool UIPanelTest_Layout_Linear_Vertical::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_HORIZONTAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -441,10 +441,10 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_LINEAR_HORIZONTAL); layout->setClippingEnabled(true); layout->setSize(Size(280, 150)); @@ -460,7 +460,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - LinearLayoutParameter* lp1 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp1 = UILinearLayoutParameter::create(); button->setLayoutParameter(lp1); lp1->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -472,7 +472,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - LinearLayoutParameter* lp2 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp2 = UILinearLayoutParameter::create(); textButton->setLayoutParameter(lp2); lp2->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp2->setMargin(UIMargin(0, 10, 0, 10)); @@ -485,7 +485,7 @@ bool UIPanelTest_Layout_Linear_Horizontal::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - LinearLayoutParameter* lp3 = LinearLayoutParameter::create(); + UILinearLayoutParameter* lp3 = UILinearLayoutParameter::create(); button_scale9->setLayoutParameter(lp3); lp3->setGravity(LINEAR_GRAVITY_CENTER_VERTICAL); lp3->setMargin(UIMargin(0, 10, 0, 10)); @@ -524,10 +524,10 @@ bool UIPanelTest_Layout_Relative::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the layout - Layout* layout = Layout::create(); + UILayout* layout = UILayout::create(); layout->setLayoutType(LAYOUT_RELATIVE); layout->setSize(Size(280, 150)); layout->setBackGroundColorType(LAYOUT_COLOR_SOLID); @@ -544,9 +544,9 @@ bool UIPanelTest_Layout_Relative::init() button->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", ""); layout->addChild(button); - RelativeLayoutParameter* rp1 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp1 = UIRelativeLayoutParameter::create(); button->setLayoutParameter(rp1); - rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM); + rp1->setAlign(RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL); // rp1->setMargin(UIMargin(0, 10, 0, 10)); @@ -556,9 +556,9 @@ bool UIPanelTest_Layout_Relative::init() textButton->setTitleText("Text Button"); layout->addChild(textButton); - RelativeLayoutParameter* rp2 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp2 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp2); - rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT); + rp2->setAlign(RELATIVE_ALIGN_PARENT_LEFT_BOTTOM); UIButton* button_scale9 = UIButton::create(); @@ -568,9 +568,9 @@ bool UIPanelTest_Layout_Relative::init() button_scale9->setSize(Size(100, button_scale9->getContentSize().height)); layout->addChild(button_scale9); - RelativeLayoutParameter* rp3 = RelativeLayoutParameter::create(); + UIRelativeLayoutParameter* rp3 = UIRelativeLayoutParameter::create(); textButton->setLayoutParameter(rp3); - rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT); + rp3->setAlign(RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM); layout->doLayout(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index a57787dfb1..38344c9490 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -3,6 +3,7 @@ #include "UIScene.h" #include "UISceneManager.h" #include "../ExtensionsTest.h" +#include "editor-support/cocostudio/CCSGUIReader.h" using namespace gui; @@ -25,7 +26,7 @@ bool UIScene::init() m_pUiLayer = UILayer::create(); addChild(m_pUiLayer); - m_pWidget = dynamic_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UITest/UITest.json")); + m_pWidget = dynamic_cast(cocostudio::CCSGUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json")); m_pUiLayer->addWidget(m_pWidget); m_pSceneTitle = dynamic_cast(m_pUiLayer->getWidgetByName("UItest")); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h index bf10ffa76b..720fdd4224 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h @@ -95,7 +95,7 @@ protected: protected: UILayer *m_pUiLayer; - Layout *m_pWidget; + UILayout *m_pWidget; }; #endif /* defined(__TestCpp__UIScene__) */ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp index c7a13fd225..01b3b83278 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp @@ -44,7 +44,7 @@ bool UIScrollViewTest_Vertical::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by vertical UIScrollView* scrollView = UIScrollView::create(); @@ -129,10 +129,11 @@ bool UIScrollViewTest_Horizontal::init() alert->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 2.925)); m_pUiLayer->addWidget(alert); - Layout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); + UILayout *background = dynamic_cast(m_pUiLayer->getWidgetByName("background_Panel")); // Create the scrollview by horizontal - UIScrollView* scrollView = UIScrollView::create(); + UIScrollView* scrollView = UIScrollView::create(); + scrollView->setBounceEnabled(true); scrollView->setDirection(SCROLLVIEW_DIR_HORIZONTAL); scrollView->setTouchEnabled(true); scrollView->setSize(Size(280, 150)); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index bba53b0444..c486c5be3a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -82,7 +82,7 @@ void UITextFieldTest::textFieldEvent(Object *pSender, TextFiledEventType type) } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words")->getCString()); break; @@ -132,7 +132,7 @@ bool UITextFieldTest_MaxLength::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setMaxLengthEnable(true); + textField->setMaxLengthEnabled(true); textField->setMaxLength(3); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -170,7 +170,7 @@ void UITextFieldTest_MaxLength::textFieldEvent(Object *pSender, TextFiledEventTy } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: { UITextField* textField = dynamic_cast(pSender); m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words max length %d", textField->getMaxLength())->getCString()); @@ -226,7 +226,7 @@ bool UITextFieldTest_Password::init() // Create the textfield UITextField* textField = UITextField::create(); - textField->setPasswordEnable(true); + textField->setPasswordEnabled(true); textField->setPasswordStyleText("*"); textField->setTouchEnabled(true); textField->setFontName(font_UITextFieldTest); @@ -264,7 +264,7 @@ void UITextFieldTest_Password::textFieldEvent(Object *pSender, TextFiledEventTyp } break; - case TEXTFIELD_EVENT_INDERT_TEXT: + case TEXTFIELD_EVENT_INSERT_TEXT: m_pDisplayValueLabel->setText(CCString::createWithFormat("insert words password")->getCString()); break; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index 0ce946c5a6..f7ddf0c777 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -14,7 +14,6 @@ SceneEditorTestLayer::~SceneEditorTestLayer() ArmatureDataManager::getInstance()->destoryInstance(); SceneReader::getInstance()->purgeSceneReader(); ActionManagerEx::shareManager()->purgeActionManager(); - UIHelper::instance()->purgeUIHelper(); } SceneEditorTestLayer::SceneEditorTestLayer() From 12570b5e8fe3a103bd0f6a801dff17538369eb29 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 16:20:01 +0800 Subject: [PATCH 432/557] temp commit --- cocos/editor-support/cocostudio/CCSGUIReader.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 0f5c597306..d5b10e62b3 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -162,8 +162,8 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) } else if (classname && strcmp(classname, "ListView") == 0) { -// widget = UIListView::create(); -// setPropsForListViewFromJsonDictionary(widget, uiOptions); + widget = UIListView::create(); + setPropsForListViewFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "PageView") == 0) { @@ -232,13 +232,14 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) const char* file = DICTOOL->getStringValueFromArray_json(jsonDict, "textures", i); std::string tp = m_strFilePath; tp.append(file); -// CCUIHELPER->addSpriteFrame(tp.c_str()); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); +// UIHelper:: // CCUIHELPER->setFileDesignWidth(winSize.width); // CCUIHELPER->setFileDesignHeight(winSize.height); } From 3ea0d2f12d4881413f99f0939ac053b7c91e237a Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Wed, 6 Nov 2013 16:37:30 +0800 Subject: [PATCH 433/557] change override function --- cocos/editor-support/cocostudio/CCSkin.cpp | 16 ++++++++-------- cocos/editor-support/cocostudio/CCSkin.h | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 62710e561d..394dfb48ec 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -83,11 +83,11 @@ Skin::Skin() _skinTransform = AffineTransformIdentity; } -bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) +bool Skin::initWithSpriteFrameName(const std::string& spriteFrameName) { - CCAssert(pszSpriteFrameName != nullptr, ""); + CCAssert(spriteFrameName != "", ""); - SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pszSpriteFrameName); + SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); bool ret = true; if (pFrame != nullptr) @@ -96,20 +96,20 @@ bool Skin::initWithSpriteFrameName(const char *pszSpriteFrameName) } else { - CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", pszSpriteFrameName); + CCLOG("Cann't find CCSpriteFrame with %s. Please check your .plist file", spriteFrameName.c_str()); ret = false; } - _displayName = pszSpriteFrameName; + _displayName = spriteFrameName; return ret; } -bool Skin::initWithFile(const char *pszFilename) +bool Skin::initWithFile(const std::string& filename) { - bool ret = Sprite::initWithFile(pszFilename); + bool ret = Sprite::initWithFile(filename); - _displayName = pszFilename; + _displayName = filename; return ret; } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index 3d937a76bb..e740d1eb01 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -39,8 +39,8 @@ public: public: Skin(); - virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName) override; - virtual bool initWithFile(const char *pszFilename) override; + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName) override; + virtual bool initWithFile(const std::string& filename) override; void updateArmatureTransform(); void updateTransform() override; From 94896b5b74bfa9e923468a0b3f8f542d1265c5b3 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 17:20:14 +0800 Subject: [PATCH 434/557] Modify mk files --- cocos/gui/Android.mk | 5 ++--- cocos/gui/CMakeLists.txt | 5 ++--- cocos/gui/Makefile | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/cocos/gui/Android.mk b/cocos/gui/Android.mk index 33171c7c1d..17f15efe44 100644 --- a/cocos/gui/Android.mk +++ b/cocos/gui/Android.mk @@ -7,14 +7,13 @@ LOCAL_MODULE_FILENAME := libgui LOCAL_SRC_FILES := UIRootWidget.cpp \ UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ +UILayout.cpp \ +UILayoutParameter.cpp \ UILayoutDefine.cpp \ CocosGUI.cpp \ UIHelper.cpp \ UIInputManager.cpp \ UILayer.cpp \ -UIDragPanel.cpp \ UIListView.cpp \ UIPageView.cpp \ UIScrollView.cpp \ diff --git a/cocos/gui/CMakeLists.txt b/cocos/gui/CMakeLists.txt index 916e5cf0f2..d4b428f890 100644 --- a/cocos/gui/CMakeLists.txt +++ b/cocos/gui/CMakeLists.txt @@ -1,14 +1,13 @@ set(GUI_SRC UIRootWidget.cpp UIWidget.cpp - Layout.cpp - LayoutParameter.cpp + UILayout.cpp + UILayoutParameter.cpp UILayoutDefine.cpp CocosGUI.cpp UIHelper.cpp UIInputManager.cpp UILayer.cpp - UIDragPanel.cpp UIListView.cpp UIPageView.cpp UIScrollView.cpp diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile index 0e8501cc63..8dcb0cb404 100644 --- a/cocos/gui/Makefile +++ b/cocos/gui/Makefile @@ -6,14 +6,13 @@ INCLUDES = -I../ \ SOURCES = UIRootWidget.cpp \ UIWidget.cpp \ -Layout.cpp \ -LayoutParameter.cpp \ +UILayout.cpp \ +UILayoutParameter.cpp \ UILayoutDefine.cpp \ CocosGUI.cpp \ UIHelper.cpp \ UIInputManager.cpp \ UILayer.cpp \ -UIDragPanel.cpp \ UIListView.cpp \ UIPageView.cpp \ UIScrollView.cpp \ From 8a836dc4771f2ccb1037a769f71768a0382fa12d Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 6 Nov 2013 09:38:34 +0000 Subject: [PATCH 435/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 9b0b068f92..f55eab57aa 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 9b0b068f923249440b8a8c758b1c06d29f6cbdfe +Subproject commit f55eab57aa6b3ff20fd33bea986e4569ebd68c8e From 3deb3b4231eff1868d24961b8c65c39452e27237 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 17:52:03 +0800 Subject: [PATCH 436/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index e206d5cea7..93e703edb1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] EventListeners can't be removed sometimes. [FIX] When parsing XML using TinyXML, the data size has to be specified. [FIX] Parameter type: const char* -> const string& + [FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. [Android] From 8c0ab2d4895a392593bad1904eb4a111855abf08 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 18:05:02 +0800 Subject: [PATCH 437/557] [ci skip] --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 217779827f..6d84c08926 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ How to start a new game Example: - $ cd cocos2d-x/tools/project-creator - $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp + $ cd cocos2d-x/tools/project-creator + $ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp $ cd ../../projects/mygame @@ -97,8 +97,9 @@ $ open samples.xcodeproj * For Linux ``` -$ cd cocos2d-x/build -$ ./make-all-linux-projects.sh +$ cd cocos2d-x +$ cmake CMakeLists.txt +$ make ``` * For Windows From b30494cc4fa906a6995f1ba06b579d592aadc776 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 6 Nov 2013 18:07:03 +0800 Subject: [PATCH 438/557] [ci skip] --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d84c08926..1cfd3a014d 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Build Requirements ------------------ * Mac OS X 10.7+, Xcode 4.6+ -* or Ubuntu 13.04+ +* or Ubuntu 12.10+, CMake 2.6+ * or Windows 7+, VS 2012+ From e765eb1e7a5a9f5cc6b20b12aa3904849ee9c767 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 6 Nov 2013 18:30:09 +0800 Subject: [PATCH 439/557] Test commit --- cocos/editor-support/cocostudio/CCSGUIReader.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index d5b10e62b3..de644e6ec6 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -239,7 +239,6 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); -// UIHelper:: // CCUIHELPER->setFileDesignWidth(winSize.width); // CCUIHELPER->setFileDesignHeight(winSize.height); } From d6d041f561b2677dc600cdb41407c784ba7b2c88 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 6 Nov 2013 19:15:20 +0800 Subject: [PATCH 440/557] issue #3113: [Linux] Adding options for modules. --- CMakeLists.txt | 73 ++++++++++++++++++++++++++++--- cocos/scripting/CMakeLists.txt | 6 +++ external/Box2D/CMakeLists.txt | 6 +++ external/lua/lua/CMakeLists.txt | 8 +++- external/lua/tolua/CMakeLists.txt | 5 +++ samples/CMakeLists.txt | 12 ++++- 6 files changed, 101 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e07f618e27..f75d56a708 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 2.6) -project (Cocos2dxSamples) +project (Cocos2dx) # The version number set(Cocos2dxSamples_VERSION_MAJOR 3) @@ -7,14 +7,45 @@ set(Cocos2dxSamples_VERSION_MINOR 0) include(build/BuildHelpers.CMakeLists.txt) -set(CMAKE_BUILE_TYPE DEBUG) +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) +option(BUILD_LIBS_LUA "Build lua libraries" ON) +option(BUILD_GUI "Build GUI library" ON) +option(BUILD_NETWORK "Build network library" ON) +option(BUILD_EXTENSIONS "Build extension library" ON) +option(BUILD_EDITOR_SPINE "Build editor support for spine" ON) +option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) +option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) + + +option(BUILD_HelloCpp "Only build HelloCpp sample" ON) +option(BUILD_TestCpp "Only build TestCpp sample" ON) +option(BUILD_HelloLua "Only build HelloLua sample" ON) +option(BUILD_TestLua "Only build TestLua sample" ON) + + +if(DEBUG_MODE) + set(CMAKE_BUILE_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILE_TYPE RELEASE) +endif(DEBUG_MODE) + set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") -add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) # architecture if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) @@ -58,6 +89,7 @@ link_directories( ${CMAKE_SOURCE_DIR}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) + # kazmath add_subdirectory(cocos/math/kazmath) @@ -73,8 +105,6 @@ add_subdirectory(external/unzip) # tinyxml2 library add_subdirectory(external/tinyxml2) -add_subdirectory(external/json) - # audio add_subdirectory(cocos/audio) @@ -84,22 +114,51 @@ add_subdirectory(cocos/base) # cocos 2d library add_subdirectory(cocos/2d) +if(BUILD_GUI) +# gui add_subdirectory(cocos/gui) +endif(BUILD_GUI) +if(BUILD_NETWORK) +# network add_subdirectory(cocos/network) +endif(BUILD_NETWORK) +if(BUILD_EXTENSIONS) +# extensions add_subdirectory(extensions) +endif(BUILD_EXTENSIONS) +## Editor Support + +if(BUILD_EDITOR_SPINE) +# spine add_subdirectory(cocos/editor-support/spine) +endif(BUILD_EDITOR_SPINE) + +if(BUILD_EDITOR_COCOSBUILDER) +# cocosbuilder add_subdirectory(cocos/editor-support/cocosbuilder) +endif(BUILD_EDITOR_COCOSBUILDER) + +if(BUILD_EDITOR_COCOSTUDIO) +# cocostudio add_subdirectory(cocos/editor-support/cocostudio) +# jsoncpp library, cocostuido depends on jsoncpp +add_subdirectory(external/json) +endif(BUILD_EDITOR_COCOSTUDIO) - +if(BUILD_LIBS_LUA) +## Scripting +# lua add_subdirectory(external/lua/lua) + +# tolua add_subdirectory(external/lua/tolua) +# luabinding add_subdirectory(cocos/scripting) +endif(BUILD_LIBS_LUA) # build samples add_subdirectory(samples) - diff --git a/cocos/scripting/CMakeLists.txt b/cocos/scripting/CMakeLists.txt index 478ae9a039..612d728162 100644 --- a/cocos/scripting/CMakeLists.txt +++ b/cocos/scripting/CMakeLists.txt @@ -36,3 +36,9 @@ target_link_libraries(luabinding tolua lua ) + +set_target_properties(luabinding + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt index 94a1fffb50..fd1f63dc64 100644 --- a/external/Box2D/CMakeLists.txt +++ b/external/Box2D/CMakeLists.txt @@ -53,3 +53,9 @@ include_directories( add_library(box2d STATIC ${BOX2D_SRC} ) + +set_target_properties(box2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/lua/lua/CMakeLists.txt b/external/lua/lua/CMakeLists.txt index faba14e849..c63d80a7b2 100644 --- a/external/lua/lua/CMakeLists.txt +++ b/external/lua/lua/CMakeLists.txt @@ -33,4 +33,10 @@ set(LUA_SRC add_library(lua STATIC ${LUA_SRC} -) \ No newline at end of file +) + +set_target_properties(lua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/external/lua/tolua/CMakeLists.txt b/external/lua/tolua/CMakeLists.txt index 481bdd1247..b12e144e75 100644 --- a/external/lua/tolua/CMakeLists.txt +++ b/external/lua/tolua/CMakeLists.txt @@ -15,3 +15,8 @@ add_library(tolua STATIC ${TOLUA_SRC} ) +set_target_properties(tolua + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index d73334ce7e..198764a991 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,5 +1,15 @@ - +if(BUILD_HelloCpp) add_subdirectory(Cpp/HelloCpp) +endif(BUILD_HelloCpp) + +if(BUILD_TestCpp) add_subdirectory(Cpp/TestCpp) +endif(BUILD_TestCpp) + +if(BUILD_HelloLua) add_subdirectory(Lua/HelloLua) +endif(BUILD_HelloLua) + +if(BUILD_TestLua) add_subdirectory(Lua/TestLua) +endif(BUILD_TestLua) \ No newline at end of file From b7173cd60d086217a930dd5e51c78769f7ce1a75 Mon Sep 17 00:00:00 2001 From: Michael Contento Date: Wed, 6 Nov 2013 14:42:31 +0100 Subject: [PATCH 441/557] add Sprite::setScale(float, float) --- cocos/2d/CCSprite.cpp | 6 ++++++ cocos/2d/CCSprite.h | 1 + 2 files changed, 7 insertions(+) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fa6f4878b0..63aa9fb5bb 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -840,6 +840,12 @@ void Sprite::setScale(float fScale) SET_DIRTY_RECURSIVELY(); } +void Sprite::setScale(float scaleX, float scaleY) +{ + Node::setScale(scaleX, scaleY); + SET_DIRTY_RECURSIVELY(); +} + void Sprite::setVertexZ(float fVertexZ) { Node::setVertexZ(fVertexZ); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 7ebf7ff616..0c0b652972 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -494,6 +494,7 @@ public: /// @name Functions inherited from Node virtual void setScaleX(float scaleX) override; virtual void setScaleY(float scaleY) override; + virtual void setScale(float scaleX, float scaleY) override; /** * @js NA * @lua NA From 6be59456a5c03d9bac50d0f7359a16e9a1ed0aa3 Mon Sep 17 00:00:00 2001 From: Oleg Loginov Date: Thu, 7 Nov 2013 01:24:33 +0400 Subject: [PATCH 442/557] correct type in root CMakeLists.txt --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f75d56a708..c03a1e9d87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,9 +26,9 @@ option(BUILD_TestLua "Only build TestLua sample" ON) if(DEBUG_MODE) - set(CMAKE_BUILE_TYPE DEBUG) + set(CMAKE_BUILD_TYPE DEBUG) else(DEBUG_MODE) - set(CMAKE_BUILE_TYPE RELEASE) + set(CMAKE_BUILD_TYPE RELEASE) endif(DEBUG_MODE) set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") From 998b7986465d1288ad683d0e8263965b379778ae Mon Sep 17 00:00:00 2001 From: Oleg Loginov Date: Thu, 7 Nov 2013 01:43:26 +0400 Subject: [PATCH 443/557] ignore output files from script make-all-linux-project.sh --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 8acdd3504c..d16b0398e7 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,8 @@ tools/jenkins_scripts/mac/android/userconf.ini # CTags tags + +# ignore files, created with make-all-linux-project script +/lib +/build/linux-build + From ddb0111392f921c826cfb6ec0f211960b7d8ff0d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 6 Nov 2013 17:05:13 -0800 Subject: [PATCH 444/557] continue replacing `const char*` with `const std::string&` This patch includes: * Continue replacing `const char*` with `const std::string&` where it makes sense. * It also removes some Hungarian notation from the code. * It fixes some indentation issues in part of the code * It replaces `int` or `unsigned int` with `long` where it makes sense. --- cocos/2d/CCAtlasNode.cpp | 10 +- cocos/2d/CCAtlasNode.h | 17 +- cocos/2d/CCDrawNode.cpp | 10 +- cocos/2d/CCDrawNode.h | 6 +- cocos/2d/CCFont.cpp | 4 +- cocos/2d/CCFont.h | 23 +- cocos/2d/CCFontAtlas.cpp | 30 +- cocos/2d/CCFontAtlas.h | 50 ++-- cocos/2d/CCFontAtlasCache.cpp | 2 +- cocos/2d/CCFontAtlasCache.h | 6 +- cocos/2d/CCFontAtlasFactory.cpp | 30 +- cocos/2d/CCFontDefinition.cpp | 8 +- cocos/2d/CCFontDefinition.h | 12 +- cocos/2d/CCFontFNT.cpp | 32 ++- cocos/2d/CCFontFNT.h | 7 +- cocos/2d/CCGrabber.h | 2 +- cocos/2d/CCGrid.cpp | 2 +- cocos/2d/CCGrid.h | 12 +- cocos/2d/CCLabelAtlas.cpp | 43 ++- cocos/2d/CCLabelAtlas.h | 12 +- cocos/2d/CCLabelBMFont.cpp | 28 +- cocos/2d/CCLabelBMFont.h | 6 +- cocos/2d/CCLabelTTF.cpp | 145 +++++----- cocos/2d/CCLabelTTF.h | 28 +- cocos/2d/CCMenuItem.cpp | 272 +++++++++--------- cocos/2d/CCMenuItem.h | 50 ++-- cocos/2d/CCScene.h | 14 +- cocos/2d/CCTMXTiledMap.cpp | 49 ++-- cocos/2d/CCTMXTiledMap.h | 14 +- cocos/2d/CCTMXXMLParser.cpp | 30 +- cocos/2d/CCTMXXMLParser.h | 24 +- cocos/gui/UIButton.cpp | 2 +- .../CCControlExtension/CCControlButton.cpp | 2 +- 33 files changed, 508 insertions(+), 474 deletions(-) diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 7d5a64dba7..6922a8f7ca 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -61,8 +61,7 @@ AtlasNode::~AtlasNode() CC_SAFE_RELEASE(_textureAtlas); } -AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { AtlasNode * pRet = new AtlasNode(); if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) @@ -74,15 +73,14 @@ AtlasNode * AtlasNode::create(const char *tile, unsigned int tileWidth, unsigned return NULL; } -bool AtlasNode::initWithTileFile(const char *tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender) +bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { - CCASSERT(tile != NULL, "title should not be null"); + CCASSERT(tile.size() > 0, "file size should not be empty"); Texture2D *texture = TextureCache::getInstance()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } -bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender) +bool AtlasNode::initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender) { _itemWidth = tileWidth; _itemHeight = tileHeight; diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 74dcc9f970..9f06456589 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -52,8 +52,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol { public: /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - static AtlasNode * create(const char* tile,unsigned int tileWidth, unsigned int tileHeight, - unsigned int itemsToRender); + static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender); /** * @js ctor */ @@ -65,10 +64,10 @@ public: virtual ~AtlasNode(); /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - bool initWithTileFile(const char* tile, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); + bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender); /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ - bool initWithTexture(Texture2D* texture, unsigned int tileWidth, unsigned int tileHeight, unsigned int itemsToRender); + bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender); /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses @@ -115,14 +114,14 @@ private : protected: //! chars per row - unsigned int _itemsPerRow; + long _itemsPerRow; //! chars per column - unsigned int _itemsPerColumn; + long _itemsPerColumn; //! width of each char - unsigned int _itemWidth; + long _itemWidth; //! height of each char - unsigned int _itemHeight; + long _itemHeight; Color3B _colorUnmodified; @@ -132,7 +131,7 @@ protected: BlendFunc _blendFunc; // quads to draw - unsigned int _quadsToDraw; + long _quadsToDraw; // color uniform GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 3623266864..d373709686 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -140,7 +140,7 @@ DrawNode* DrawNode::create() return pRet; } -void DrawNode::ensureCapacity(int count) +void DrawNode::ensureCapacity(long count) { CCASSERT(count>=0, "capacity must be >= 0"); @@ -331,8 +331,10 @@ void DrawNode::drawSegment(const Point &from, const Point &to, float radius, con _dirty = true; } -void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) +void DrawNode::drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor) { + CCASSERT(count >= 0, "invalid count value"); + struct ExtrudeVerts {Vertex2F offset, n;}; struct ExtrudeVerts* extrude = (struct ExtrudeVerts*)malloc(sizeof(struct ExtrudeVerts)*count); memset(extrude, 0, sizeof(struct ExtrudeVerts)*count); @@ -376,9 +378,9 @@ void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fill *cursor++ = tmp; } - for(unsigned int i = 0; i < count; i++) + for(long i = 0; i < count; i++) { - int j = (i+1)%count; + long j = (i+1)%count; Vertex2F v0 = __v2f(verts[i]); Vertex2F v1 = __v2f(verts[j]); diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 3e128d26ea..fe7312ade8 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -71,7 +71,7 @@ public: * In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor) * @endcode */ - void drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); + void drawPolygon(Point *verts, long count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); /** Clear the geometry in the node's buffer. */ void clear(); @@ -99,13 +99,13 @@ public: virtual void draw() override; protected: - void ensureCapacity(int count); + void ensureCapacity(long count); void render(); GLuint _vao; GLuint _vbo; - int _bufferCapacity; + long _bufferCapacity; GLsizei _bufferCount; V2F_C4B_T2F *_buffer; diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 3dc8271499..c48acdc0b5 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -99,12 +99,12 @@ const char * Font::getCurrentGlyphCollection() const } } -Font* Font::createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) +Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); } -Font* Font::createWithFNT(const char* fntFilePath) +Font* Font::createWithFNT(const std::string& fntFilePath) { return FontFNT::create(fntFilePath); } diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index e4bcb141ce..cf3084011d 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -42,21 +42,21 @@ class CC_DLL Font : public Object public: // create the font - static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const char* fntFilePath); + static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); + static Font* createWithFNT(const std::string& fntFilePath); virtual FontAtlas *createFontAtlas() = 0; - virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; - virtual const char * getCurrentGlyphCollection() const; + virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; + virtual const char* getCurrentGlyphCollection() const; - virtual int getLetterPadding() const { return 0; } - virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } - virtual int getFontMaxHeight() const { return 0; } - virtual Rect getRectForChar(unsigned short theChar) const; + virtual int getLetterPadding() const { return 0; } + virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } + virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } + virtual Rect getRectForChar(unsigned short theChar) const; - virtual int getUTF16TextLenght(unsigned short int *text) const; + virtual int getUTF16TextLenght(unsigned short int *text) const; virtual unsigned short int * getUTF16Text(const char *text, int &outNumLetters) const; virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; @@ -71,8 +71,7 @@ protected: void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0); const char * getGlyphCollection(GlyphCollection glyphs) const; -private: - + GlyphCollection _usedGlyphs; char * _customGlyphs; static const char * _glyphASCII; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 24b56bd448..72f29e13d8 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlas.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/18/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "cocos2d.h" #include "CCFontAtlas.h" diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index a388a5b987..317a06561d 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -24,7 +24,7 @@ #ifndef _CCFontAtlas_h_ #define _CCFontAtlas_h_ -#include +#include NS_CC_BEGIN @@ -34,17 +34,17 @@ class Font; struct FontLetterDefinition { unsigned short letteCharUTF16; - float U; - float V; - float width; - float height; - float offsetX; - float offsetY; - int textureID; - float commonLineHeight; - float anchorX; - float anchorY; - bool validDefinition; + float U; + float V; + float width; + float height; + float offsetX; + float offsetY; + int textureID; + float commonLineHeight; + float anchorX; + float anchorY; + bool validDefinition; }; class CC_DLL FontAtlas : public Object @@ -69,26 +69,26 @@ public: float getCommonLineHeight() const; void setCommonLineHeight(float newHeight); - Texture2D & getTexture(int slot); - const Font * getFont() const; + Texture2D& getTexture(int slot); + const Font* getFont() const; private: bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); void relaseTextures(); - std::map _atlasTextures; - std::map _fontLetterDefinitions; - float _commonLineHeight; - Font * _font; + std::unordered_map _atlasTextures; + std::unordered_map _fontLetterDefinitions; + float _commonLineHeight; + Font * _font; // Dynamic GlyphCollection related stuff - int _currentPage; - unsigned char *_currentPageData; - int _currentPageDataSize; - float _currentPageOrigX; - float _currentPageOrigY; - float _currentPageLineHeight; - float _letterPadding; + int _currentPage; + unsigned char *_currentPageData; + int _currentPageDataSize; + float _currentPageOrigX; + float _currentPageOrigY; + float _currentPageLineHeight; + float _letterPadding; }; diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 762a506ae4..00fc1e2a1f 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -28,7 +28,7 @@ NS_CC_BEGIN -std::map FontAtlasCache::_atlasMap; +std::unordered_map FontAtlasCache::_atlasMap; FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) { diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index c63c832d48..f5f8ca7df4 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -26,7 +26,7 @@ #define _CCFontAtlasCache_h_ #include -#include +#include #include "cocos2d.h" #include "CCFontAtlas.h" @@ -41,12 +41,12 @@ public: static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * getFontAtlasFNT(const char *fontFileName); - static bool releaseFontAtlas(FontAtlas *atlas); + static bool releaseFontAtlas(FontAtlas *atlas); private: static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); - static std::map _atlasMap; + static std::unordered_map _atlasMap; }; NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index f5e4f60802..b1cd69172f 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -1,10 +1,26 @@ -// -// CCFontAtlasFactory.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/23/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCFontAtlasFactory.h" #include "CCFontFNT.h" diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index 938204f3b0..d8414dc64d 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -27,7 +27,7 @@ NS_CC_BEGIN -const int FontDefinitionTTF::DEFAUL_ATALS_TEXTURE_SIZE = 1024; +const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024; FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) { @@ -36,7 +36,7 @@ FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) { if (textureSize == 0) - textureSize = DEFAUL_ATALS_TEXTURE_SIZE; + textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; FontDefinitionTTF *ret = new FontDefinitionTTF; @@ -82,8 +82,8 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) // loops all the lines in this page for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); + float posXUV = 0.0; + float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); int charsCounter = 0; diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h index f5e6da10b6..1f9504920c 100644 --- a/cocos/2d/CCFontDefinition.h +++ b/cocos/2d/CCFontDefinition.h @@ -25,6 +25,8 @@ #ifndef _FontDefinition_h_ #define _FontDefinition_h_ +#include + #include "CCTextImage.h" #include "CCFont.h" #include "CCFontAtlas.h" @@ -55,11 +57,11 @@ private: bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); void addLetterDefinition(const FontLetterDefinition &defToAdd); - TextImage * _textImages; - std::map _fontLettersDefinitionUTF16; - float _commonLineHeight; - static const int DEFAUL_ATALS_TEXTURE_SIZE; - + TextImage * _textImages; + std::unordered_map _fontLettersDefinitionUTF16; + float _commonLineHeight; + + static const int DEFAUL_ATLAS_TEXTURE_SIZE; }; NS_CC_END diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index e655236a1b..1992b4f828 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -1,17 +1,33 @@ -// -// CCFontFNT.cpp -// cocos2d_libs -// -// Created by Carlo Morgantini on 7/24/13. -// -// +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCFontFNT.h" #include "CCFontAtlas.h" NS_CC_BEGIN -FontFNT * FontFNT::create(const char* fntFilePath) +FontFNT * FontFNT::create(const std::string& fntFilePath) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); if (!newConf) diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 3994e14463..e9c4327672 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -35,7 +35,7 @@ class FontFNT : public Font public: - static FontFNT * create(const char* fntFilePath); + static FontFNT * create(const std::string& fntFilePath); virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual Rect getRectForChar(unsigned short theChar) const override; @@ -43,7 +43,8 @@ public: protected: - FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {} + FontFNT(CCBMFontConfiguration *theContfig) : + _configuration(theContfig) {} /** * @js NA * @lua NA @@ -56,7 +57,7 @@ private: int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; Rect getRectForCharInternal(unsigned short theChar) const; - CCBMFontConfiguration * _configuration; + CCBMFontConfiguration * _configuration; }; diff --git a/cocos/2d/CCGrabber.h b/cocos/2d/CCGrabber.h index 9fef542459..022e68ed0d 100644 --- a/cocos/2d/CCGrabber.h +++ b/cocos/2d/CCGrabber.h @@ -59,7 +59,7 @@ public: protected: GLuint _FBO; GLint _oldFBO; - GLfloat _oldClearColor[4]; + GLfloat _oldClearColor[4]; }; // end of effects group diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index fc2152ab13..717277eff8 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -119,7 +119,7 @@ bool GridBase::initWithSize(const Size& gridSize) // we only use rgba8888 Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888; - int dataLen = (int)(POTWide * POTHigh * 4); + long dataLen = POTWide * POTHigh * 4; void *data = calloc(dataLen, 1); if (! data) { diff --git a/cocos/2d/CCGrid.h b/cocos/2d/CCGrid.h index 97904cdf3e..61a8cbbe34 100644 --- a/cocos/2d/CCGrid.h +++ b/cocos/2d/CCGrid.h @@ -66,23 +66,23 @@ public: bool initWithSize(const Size& gridSize); /** whether or not the grid is active */ - inline bool isActive(void) { return _active; } + inline bool isActive(void) const { return _active; } void setActive(bool bActive); /** number of times that the grid will be reused */ - inline int getReuseGrid(void) { return _reuseGrid; } + inline int getReuseGrid(void) const { return _reuseGrid; } inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; } /** size of the grid */ - inline const Size& getGridSize(void) { return _gridSize; } + inline const Size& getGridSize(void) const { return _gridSize; } inline void setGridSize(const Size& gridSize) { _gridSize = gridSize; } /** pixels between the grids */ - inline const Point& getStep(void) { return _step; } + inline const Point& getStep(void) const { return _step; } inline void setStep(const Point& step) { _step = step; } /** is texture flipped */ - inline bool isTextureFlipped(void) { return _isTextureFlipped; } + inline bool isTextureFlipped(void) const { return _isTextureFlipped; } void setTextureFlipped(bool bFlipped); void beforeDraw(void); @@ -95,7 +95,7 @@ public: protected: bool _active; - int _reuseGrid; + long _reuseGrid; Size _gridSize; Texture2D *_texture; Point _step; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index f1a9126b54..56a6ff723b 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN //CCLabelAtlas - Creation & Init -LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsigned int itemWidth, int unsigned itemHeight, unsigned int startCharMap) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { LabelAtlas *pRet = new LabelAtlas(); if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) @@ -54,16 +54,15 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *charMapFile, unsi return NULL; } -bool LabelAtlas::initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile); return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } -bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +bool LabelAtlas::initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap) { - CCASSERT(string != NULL, ""); - if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, strlen(string))) + if (AtlasNode::initWithTexture(texture, itemWidth, itemHeight, string.size())) { _mapStartChar = startCharMap; this->setString(string); @@ -72,7 +71,7 @@ bool LabelAtlas::initWithString(const char *string, Texture2D* texture, unsigned return false; } -LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) +LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& fntFile) { LabelAtlas *ret = new LabelAtlas(); if (ret) @@ -90,24 +89,24 @@ LabelAtlas* LabelAtlas::create(const char *string, const char *fntFile) return ret; } -bool LabelAtlas::initWithString(const char *theString, const char *fntFile) +bool LabelAtlas::initWithString(const std::string& theString, const std::string& fntFile) { - std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); - std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; - Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); - - CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version"); - - std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString(); - String *textureFilename = String::create(texturePathStr); - unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR(); - unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR(); - unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue(); - + std::string pathStr = FileUtils::getInstance()->fullPathForFilename(fntFile); + std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; + Dictionary *dict = Dictionary::createWithContentsOfFile(pathStr.c_str()); - this->initWithString(theString, textureFilename->getCString(), width, height, startChar); - - return true; + CCASSERT(((String*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version"); + + std::string texturePathStr = relPathStr + ((String*)dict->objectForKey("textureFilename"))->getCString(); + String *textureFilename = String::create(texturePathStr); + unsigned int width = ((String*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR(); + unsigned int height = ((String*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR(); + unsigned int startChar = ((String*)dict->objectForKey("firstChar"))->intValue(); + + + this->initWithString(theString, textureFilename->getCString(), width, height, startChar); + + return true; } //CCLabelAtlas - Atlas generation diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index b8df38f62d..eb8d06f4be 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -67,23 +67,23 @@ public: } /** creates the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - static LabelAtlas * create(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + static LabelAtlas * create(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); /** creates the LabelAtlas with a string and a configuration file @since v2.0 */ - static LabelAtlas* create(const char *string, const char *fntFile); + static LabelAtlas* create(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - bool initWithString(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + bool initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap); /** initializes the LabelAtlas with a string and a configuration file @since v2.0 */ - bool initWithString(const char *string, const char *fntFile); + bool initWithString(const std::string& string, const std::string& fntFile); /** initializes the LabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */ - bool initWithString(const char* string, Texture2D* texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + bool initWithString(const std::string& string, Texture2D* texture, long itemWidth, long itemHeight, long startCharMap); // super methods virtual void updateAtlasValues(); @@ -98,7 +98,7 @@ protected: // string to render std::string _string; // the first char in the charmap - unsigned int _mapStartChar; + long _mapStartChar; }; // end of GUI group diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 1000889c62..e28d4d0afc 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -64,7 +64,7 @@ static Dictionary* s_pConfigurations = NULL; CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) { - CCBMFontConfiguration* pRet = NULL; + CCBMFontConfiguration* ret = NULL; if( s_pConfigurations == NULL ) { @@ -72,17 +72,17 @@ CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) s_pConfigurations->init(); } - pRet = static_cast( s_pConfigurations->objectForKey(fntFile) ); - if( pRet == NULL ) + ret = static_cast( s_pConfigurations->objectForKey(fntFile) ); + if( ret == NULL ) { - pRet = CCBMFontConfiguration::create(fntFile.c_str()); - if (pRet) + ret = CCBMFontConfiguration::create(fntFile.c_str()); + if (ret) { - s_pConfigurations->setObject(pRet, fntFile); + s_pConfigurations->setObject(ret, fntFile); } } - return pRet; + return ret; } void FNTConfigRemoveCache( void ) @@ -98,19 +98,19 @@ void FNTConfigRemoveCache( void ) //BitmapFontConfiguration // -CCBMFontConfiguration * CCBMFontConfiguration::create(const char *FNTfile) +CCBMFontConfiguration * CCBMFontConfiguration::create(const std::string& FNTfile) { - CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); - if (pRet->initWithFNTfile(FNTfile)) + CCBMFontConfiguration * ret = new CCBMFontConfiguration(); + if (ret->initWithFNTfile(FNTfile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) +bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile) { _kerningDictionary = NULL; _fontDefDictionary = NULL; diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index 0da1584387..cc49dd0806 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -140,10 +140,10 @@ public: const char * description() const; /** allocates a CCBMFontConfiguration with a FNT file */ - static CCBMFontConfiguration * create(const char *FNTfile); + static CCBMFontConfiguration * create(const std::string& FNTfile); /** initializes a BitmapFontConfiguration with a FNT file */ - bool initWithFNTfile(const char *FNTfile); + bool initWithFNTfile(const std::string& FNTfile); inline const std::string& getAtlasName(){ return _atlasName; } inline void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; } @@ -303,7 +303,7 @@ protected: bool _cascadeColorEnabled; bool _cascadeOpacityEnabled; /** conforms to RGBAProtocol protocol */ - bool _isOpacityModifyRGB; + bool _isOpacityModifyRGB; }; diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 051b07d9b7..3eec437d09 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -42,7 +42,7 @@ NS_CC_BEGIN LabelTTF::LabelTTF() : _alignment(TextHAlignment::CENTER) , _vAlignment(TextVAlignment::TOP) -, _fontName(NULL) +, _fontName("") , _fontSize(0.0) , _string("") , _shadowEnabled(false) @@ -53,58 +53,57 @@ LabelTTF::LabelTTF() LabelTTF::~LabelTTF() { - CC_SAFE_DELETE(_fontName); } LabelTTF * LabelTTF::create() { - LabelTTF * pRet = new LabelTTF(); - if (pRet && pRet->init()) + LabelTTF * ret = new LabelTTF(); + if (ret && ret->init()) { - pRet->autorelease(); + ret->autorelease(); } else { - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); } - return pRet; + return ret; } -LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize) +LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize) { return LabelTTF::create(string, fontName, fontSize, Size::ZERO, TextHAlignment::CENTER, TextVAlignment::TOP); } -LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize, +LabelTTF * LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment) { return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, TextVAlignment::TOP); } -LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize, +LabelTTF* LabelTTF::create(const std::string& string, const std::string& fontName, float fontSize, const Size &dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -LabelTTF * LabelTTF::createWithFontDefinition(const char *string, FontDefinition &textDefinition) +LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition) { - LabelTTF *pRet = new LabelTTF(); - if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition)) + LabelTTF *ret = new LabelTTF(); + if(ret && ret->initWithStringAndTextDefinition(string, textDefinition)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -113,19 +112,19 @@ bool LabelTTF::init() return this->initWithString("", "Helvetica", 12); } -bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize, +bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment alignment) { return this->initWithString(label, fontName, fontSize, dimensions, alignment, TextVAlignment::TOP); } -bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize) +bool LabelTTF::initWithString(const std::string& label, const std::string& fontName, float fontSize) { return this->initWithString(label, fontName, fontSize, Size::ZERO, TextHAlignment::LEFT, TextVAlignment::TOP); } -bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize, +bool LabelTTF::initWithString(const std::string& string, const std::string& fontName, float fontSize, const cocos2d::Size &dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment) { @@ -135,10 +134,10 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM)); _dimensions = Size(dimensions.width, dimensions.height); - _alignment = hAlignment; - _vAlignment = vAlignment; - _fontName = new std::string(fontName); - _fontSize = fontSize; + _alignment = hAlignment; + _vAlignment = vAlignment; + _fontName = fontName; + _fontSize = fontSize; this->setString(string); @@ -148,7 +147,7 @@ bool LabelTTF::initWithString(const char *string, const char *fontName, float fo return false; } -bool LabelTTF::initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition) +bool LabelTTF::initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition) { if (Sprite::init()) { @@ -188,7 +187,7 @@ const char* LabelTTF::getString(void) const const char* LabelTTF::description() const { - return String::createWithFormat("", _fontName->c_str(), _fontSize)->getCString(); + return String::createWithFormat("", _fontName.c_str(), _fontSize)->getCString(); } TextHAlignment LabelTTF::getHorizontalAlignment() const @@ -236,6 +235,7 @@ const Size& LabelTTF::getDimensions() const void LabelTTF::setDimensions(const Size &dim) { + // XXX: float comparison... very unreliable if (dim.width != _dimensions.width || dim.height != _dimensions.height) { _dimensions = dim; @@ -255,6 +255,7 @@ float LabelTTF::getFontSize() const void LabelTTF::setFontSize(float fontSize) { + // XXX: float comparison... very unreliable if (_fontSize != fontSize) { _fontSize = fontSize; @@ -267,17 +268,16 @@ void LabelTTF::setFontSize(float fontSize) } } -const char* LabelTTF::getFontName() const +const std::string& LabelTTF::getFontName() const { - return _fontName->c_str(); + return _fontName; } -void LabelTTF::setFontName(const char *fontName) +void LabelTTF::setFontName(const std::string& fontName) { - if (_fontName->compare(fontName)) + if (_fontName.compare(fontName)) { - delete _fontName; - _fontName = new std::string(fontName); + _fontName = fontName; // Force update if (_string.size() > 0) @@ -296,21 +296,21 @@ bool LabelTTF::updateTexture() if (!tex) return false; - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) FontDefinition texDef = _prepareTextDefinition(true); tex->initWithString( _string.c_str(), texDef ); - #else +#else tex->initWithString( _string.c_str(), - _fontName->c_str(), + _fontName.c_str(), _fontSize * CC_CONTENT_SCALE_FACTOR(), CC_SIZE_POINTS_TO_PIXELS(_dimensions), _alignment, _vAlignment); - #endif +#endif // set the texture this->setTexture(tex); @@ -340,7 +340,7 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float if ( (_shadowOffset.width != shadowOffset.width) || (_shadowOffset.height!=shadowOffset.height) ) { - _shadowOffset.width = shadowOffset.width; + _shadowOffset.width = shadowOffset.width; _shadowOffset.height = shadowOffset.height; valueChanged = true; @@ -352,27 +352,26 @@ void LabelTTF::enableShadow(const Size &shadowOffset, float shadowOpacity, float valueChanged = true; } - if (_shadowBlur != shadowBlur) + if (_shadowBlur != shadowBlur) { _shadowBlur = shadowBlur; valueChanged = true; } - if ( valueChanged && updateTexture ) { this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::disableShadow(bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_shadowEnabled) { @@ -380,17 +379,16 @@ void LabelTTF::disableShadow(bool updateTexture) if (updateTexture) this->updateTexture(); - } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) bool valueChanged = false; @@ -417,15 +415,15 @@ void LabelTTF::enableStroke(const Color3B &strokeColor, float strokeSize, bool u this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::disableStroke(bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_strokeEnabled) { @@ -435,15 +433,15 @@ void LabelTTF::disableStroke(bool updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) { - #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) if (_textFillColor.r != tintColor.r || _textFillColor.g != tintColor.g || _textFillColor.b != tintColor.b) { _textFillColor = tintColor; @@ -451,9 +449,9 @@ void LabelTTF::setFontFillColor(const Color3B &tintColor, bool updateTexture) if (updateTexture) this->updateTexture(); } - #else +#else CCLOGERROR("Currently only supported on iOS and Android!"); - #endif +#endif } void LabelTTF::setTextDefinition(const FontDefinition& theDefinition) @@ -469,11 +467,11 @@ FontDefinition LabelTTF::getTextDefinition() void LabelTTF::_updateWithTextDefinition(const FontDefinition& textDefinition, bool mustUpdateTexture) { _dimensions = Size(textDefinition._dimensions.width, textDefinition._dimensions.height); - _alignment = textDefinition._alignment; - _vAlignment = textDefinition._vertAlignment; + _alignment = textDefinition._alignment; + _vAlignment = textDefinition._vertAlignment; - _fontName = new std::string(textDefinition._fontName); - _fontSize = textDefinition._fontSize; + _fontName = textDefinition._fontName; + _fontSize = textDefinition._fontSize; // shadow @@ -500,19 +498,19 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) FontDefinition texDef; if (adjustForResolution) - texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); + texDef._fontSize = _fontSize * CC_CONTENT_SCALE_FACTOR(); else - texDef._fontSize = _fontSize; + texDef._fontSize = _fontSize; - texDef._fontName = *_fontName; - texDef._alignment = _alignment; - texDef._vertAlignment = _vAlignment; + texDef._fontName = _fontName; + texDef._alignment = _alignment; + texDef._vertAlignment = _vAlignment; if (adjustForResolution) - texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); + texDef._dimensions = CC_SIZE_POINTS_TO_PIXELS(_dimensions); else - texDef._dimensions = _dimensions; + texDef._dimensions = _dimensions; // stroke @@ -525,21 +523,18 @@ FontDefinition LabelTTF::_prepareTextDefinition(bool adjustForResolution) texDef._stroke._strokeSize = _strokeSize * CC_CONTENT_SCALE_FACTOR(); else texDef._stroke._strokeSize = _strokeSize; - - } else { texDef._stroke._strokeEnabled = false; } - // shadow if ( _shadowEnabled ) { - texDef._shadow._shadowEnabled = true; - texDef._shadow._shadowBlur = _shadowBlur; - texDef._shadow._shadowOpacity = _shadowOpacity; + texDef._shadow._shadowEnabled = true; + texDef._shadow._shadowBlur = _shadowBlur; + texDef._shadow._shadowOpacity = _shadowOpacity; if (adjustForResolution) texDef._shadow._shadowOffset = CC_SIZE_POINTS_TO_PIXELS(_shadowOffset); diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 1f785028c4..029a125def 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -75,39 +75,39 @@ public: /** creates a LabelTTF with a font name and font size in points @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize); /** creates a LabelTTF from a fontname, horizontal alignment, dimension in points, and font size in points. @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment); /** creates a Label from a fontname, alignment, dimension in points and font size in points @since v2.0.1 */ - static LabelTTF * create(const char *string, const char *fontName, float fontSize, - const Size& dimensions, TextHAlignment hAlignment, - TextVAlignment vAlignment); + static LabelTTF * create(const std::string& string, const std::string& fontName, float fontSize, + const Size& dimensions, TextHAlignment hAlignment, + TextVAlignment vAlignment); /** Create a lable with string and a font definition*/ - static LabelTTF * createWithFontDefinition(const char *string, FontDefinition &textDefinition); + static LabelTTF * createWithFontDefinition(const std::string& string, FontDefinition &textDefinition); /** initializes the LabelTTF with a font name and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize); + bool initWithString(const std::string& string, const std::string& fontName, float fontSize); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize, + bool initWithString(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithString(const char *string, const char *fontName, float fontSize, + bool initWithString(const std::string& string, const std::string& fontName, float fontSize, const Size& dimensions, TextHAlignment hAlignment, TextVAlignment vAlignment); /** initializes the LabelTTF with a font name, alignment, dimension and font size */ - bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition); + bool initWithStringAndTextDefinition(const std::string& string, FontDefinition &textDefinition); /** set the text definition used by this label */ void setTextDefinition(const FontDefinition& theDefinition); @@ -159,8 +159,8 @@ public: float getFontSize() const; void setFontSize(float fontSize); - const char* getFontName() const; - void setFontName(const char *fontName); + const std::string& getFontName() const; + void setFontName(const std::string& fontName); private: bool updateTexture(); @@ -177,7 +177,7 @@ protected: /** The vertical alignment of the label */ TextVAlignment _vAlignment; /** Font name used in the label */ - std::string * _fontName; + std::string _fontName; /** Font size of the label */ float _fontSize; /** label's string */ diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 24ec16a3a7..89aa7eaba6 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -42,7 +42,7 @@ THE SOFTWARE. NS_CC_BEGIN -static unsigned int _globalFontSize = kItemSize; +static long _globalFontSize = kItemSize; static std::string _globalFontName = "Marker Felt"; static bool _globalFontNameRelease = false; @@ -64,18 +64,18 @@ MenuItem* MenuItem::create() // XXX deprecated MenuItem* MenuItem::create(Object *target, SEL_MenuHandler selector) { - MenuItem *pRet = new MenuItem(); - pRet->initWithTarget(target, selector); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithTarget(target, selector); + ret->autorelease(); + return ret; } MenuItem* MenuItem::create( const ccMenuCallback& callback) { - MenuItem *pRet = new MenuItem(); - pRet->initWithCallback(callback); - pRet->autorelease(); - return pRet; + MenuItem *ret = new MenuItem(); + ret->initWithCallback(callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -188,26 +188,26 @@ void MenuItemLabel::setLabel(Node* var) // XXX: deprecated MenuItemLabel * MenuItemLabel::create(Node*label, Object* target, SEL_MenuHandler selector) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, target, selector); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, target, selector); + ret->autorelease(); + return ret; } MenuItemLabel * MenuItemLabel::create(Node*label, const ccMenuCallback& callback) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, callback); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, callback); + ret->autorelease(); + return ret; } MenuItemLabel* MenuItemLabel::create(Node *label) { - MenuItemLabel *pRet = new MenuItemLabel(); - pRet->initWithLabel(label, (const ccMenuCallback&) nullptr); - pRet->autorelease(); - return pRet; + MenuItemLabel *ret = new MenuItemLabel(); + ret->initWithLabel(label, (const ccMenuCallback&) nullptr); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -237,7 +237,7 @@ MenuItemLabel::~MenuItemLabel() { } -void MenuItemLabel::setString(const char * label) +void MenuItemLabel::setString(const std::string& label) { dynamic_cast(_label)->setString(label); this->setContentSize(_label->getContentSize()); @@ -310,41 +310,39 @@ void MenuItemLabel::setEnabled(bool enabled) //CCMenuItemAtlasFont // -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap) { return MenuItemAtlasFont::create(value, charMapFile, itemWidth, itemHeight, startCharMap, (const ccMenuCallback&)nullptr); } // XXX: deprecated -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { - MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); + ret->autorelease(); + return ret; } -MenuItemAtlasFont * MenuItemAtlasFont::create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) +MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) { - MenuItemAtlasFont *pRet = new MenuItemAtlasFont(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); - pRet->autorelease(); - return pRet; + MenuItemAtlasFont *ret = new MenuItemAtlasFont(); + ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback); + ret->autorelease(); + return ret; } // XXX: deprecated -bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) +bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) { - CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0"); - _target = target; CC_SAFE_RETAIN(_target); return initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) +bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback) { - CCASSERT( value != NULL && strlen(value) != 0, "value length must be greater than 0"); + CCASSERT( value.size() != 0, "value length must be greater than 0"); LabelAtlas *label = new LabelAtlas(); label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); label->autorelease(); @@ -359,17 +357,17 @@ bool MenuItemAtlasFont::initWithString(const char *value, const char *charMapFil //CCMenuItemFont // -void MenuItemFont::setFontSize(unsigned int s) +void MenuItemFont::setFontSize(long s) { _globalFontSize = s; } -unsigned int MenuItemFont::getFontSize() +long MenuItemFont::getFontSize() { return _globalFontSize; } -void MenuItemFont::setFontName(const char *name) +void MenuItemFont::setFontName(const std::string& name) { if (_globalFontNameRelease) { @@ -379,35 +377,35 @@ void MenuItemFont::setFontName(const char *name) _globalFontNameRelease = true; } -const char * MenuItemFont::getFontName() +const std::string& MenuItemFont::getFontName() { - return _globalFontName.c_str(); + return _globalFontName; } // XXX: deprecated MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, target, selector); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, target, selector); + ret->autorelease(); + return ret; } -MenuItemFont * MenuItemFont::create(const char *value, const ccMenuCallback& callback) +MenuItemFont * MenuItemFont::create(const std::string& value, const ccMenuCallback& callback) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, callback); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, callback); + ret->autorelease(); + return ret; } -MenuItemFont * MenuItemFont::create(const char *value) +MenuItemFont * MenuItemFont::create(const std::string& value) { - MenuItemFont *pRet = new MenuItemFont(); - pRet->initWithString(value, (const ccMenuCallback&)nullptr); - pRet->autorelease(); - return pRet; + MenuItemFont *ret = new MenuItemFont(); + ret->initWithString(value, (const ccMenuCallback&)nullptr); + ret->autorelease(); + return ret; } MenuItemFont::MenuItemFont() @@ -429,14 +427,14 @@ bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHan return initWithString(value, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemFont::initWithString(const char *value, const ccMenuCallback& callback) +bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) { - CCASSERT( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); + CCASSERT( value.size() >= 0, "Value length must be greater than 0"); _fontName = _globalFontName; _fontSize = _globalFontSize; - LabelTTF *label = LabelTTF::create(value, _fontName.c_str(), (float)_fontSize); + LabelTTF *label = LabelTTF::create(value, _fontName, (float)_fontSize); if (MenuItemLabel::initWithLabel(label, callback)) { // do something ? @@ -451,26 +449,26 @@ void MenuItemFont::recreateLabel() this->setLabel(label); } -void MenuItemFont::setFontSizeObj(unsigned int s) +void MenuItemFont::setFontSizeObj(long s) { _fontSize = s; recreateLabel(); } -unsigned int MenuItemFont::getFontSizeObj() const +long MenuItemFont::getFontSizeObj() const { return _fontSize; } -void MenuItemFont::setFontNameObj(const char* name) +void MenuItemFont::setFontNameObj(const std::string& name) { _fontName = name; recreateLabel(); } -const char* MenuItemFont::getFontNameObj() const +const std::string& MenuItemFont::getFontNameObj() const { - return _fontName.c_str(); + return _fontName; } // @@ -561,18 +559,18 @@ MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite // XXX deprecated MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, Object *target, SEL_MenuHandler selector) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); + ret->autorelease(); + return ret; } MenuItemSprite * MenuItemSprite::create(Node *normalSprite, Node *selectedSprite, Node *disabledSprite, const ccMenuCallback& callback) { - MenuItemSprite *pRet = new MenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); - pRet->autorelease(); - return pRet; + MenuItemSprite *ret = new MenuItemSprite(); + ret->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback); + ret->autorelease(); + return ret; } // XXX deprecated @@ -687,71 +685,71 @@ void MenuItemSprite::updateImagesVisibility() MenuItemImage* MenuItemImage::create() { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->init()) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->init()) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } bool MenuItemImage::init(void) { - return initWithNormalImage(NULL, NULL, NULL, (const ccMenuCallback&)nullptr); + return initWithNormalImage("", "", "", (const ccMenuCallback&)nullptr); } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage) { - return MenuItemImage::create(normalImage, selectedImage, NULL, (const ccMenuCallback&)nullptr); + return MenuItemImage::create(normalImage, selectedImage, "", (const ccMenuCallback&)nullptr); } // XXX deprecated MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector) { - return MenuItemImage::create(normalImage, selectedImage, NULL, target, selector); + return MenuItemImage::create(normalImage, selectedImage, "", target, selector); } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const ccMenuCallback& callback) { - return MenuItemImage::create(normalImage, selectedImage, NULL, callback); + return MenuItemImage::create(normalImage, selectedImage, "", callback); } // XXX deprecated MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, callback)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage) +MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage) { - MenuItemImage *pRet = new MenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) + MenuItemImage *ret = new MenuItemImage(); + if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, (const ccMenuCallback&)nullptr)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -762,23 +760,23 @@ bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *sel CC_SAFE_RETAIN(_target); return initWithNormalImage(normalImage, selectedImage, disabledImage, std::bind(selector,target, std::placeholders::_1) ); } -bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback) +bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) { Node *normalSprite = NULL; Node *selectedSprite = NULL; Node *disabledSprite = NULL; - if (normalImage) + if (normalImage.size() >0) { normalSprite = Sprite::create(normalImage); } - if (selectedImage) + if (selectedImage.size() >0) { selectedSprite = Sprite::create(selectedImage); } - if(disabledImage) + if(disabledImage.size() >0) { disabledSprite = Sprite::create(disabledImage); } @@ -810,38 +808,38 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame) // XXX: deprecated MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithTarget(target, selector); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithTarget(target, selector); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->MenuItem::initWithCallback(callback); - pRet->_subItems = Array::create(); - pRet->_subItems->retain(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->MenuItem::initWithCallback(callback); + ret->_subItems = Array::create(); + ret->_subItems->retain(); for (int z=0; z < menuItems->count(); z++) { MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - pRet->_subItems->addObject(menuItem); + ret->_subItems->addObject(menuItem); } - pRet->_selectedIndex = UINT_MAX; - pRet->setSelectedIndex(0); - return pRet; + ret->_selectedIndex = UINT_MAX; + ret->setSelectedIndex(0); + return ret; } // XXX: deprecated @@ -849,30 +847,30 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithTarget(target, selector, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithTarget(target, selector, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, MenuItem* item, ...) { va_list args; va_start(args, item); - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithCallback(callback, item, args); - pRet->autorelease(); + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithCallback(callback, item, args); + ret->autorelease(); va_end(args); - return pRet; + return ret; } MenuItemToggle * MenuItemToggle::create() { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(NULL); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(NULL); + ret->autorelease(); + return ret; } // XXX: deprecated @@ -903,10 +901,10 @@ bool MenuItemToggle::initWithCallback(const ccMenuCallback &callback, MenuItem * MenuItemToggle* MenuItemToggle::create(MenuItem *item) { - MenuItemToggle *pRet = new MenuItemToggle(); - pRet->initWithItem(item); - pRet->autorelease(); - return pRet; + MenuItemToggle *ret = new MenuItemToggle(); + ret->initWithItem(item); + ret->autorelease(); + return ret; } bool MenuItemToggle::initWithItem(MenuItem *item) diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index 78b8d333ef..d0fcda9a50 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -166,7 +166,7 @@ public: CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); /** sets a new string to the inner label */ - void setString(const char * label); + void setString(const std::string& label); /** Gets the color that will be used to disable the item */ inline const Color3B& getDisabledColor() const { return _disabledColor; }; @@ -204,11 +204,11 @@ class CC_DLL MenuItemAtlasFont : public MenuItemLabel { public: /** creates a menu item from a string and atlas with a target/selector */ - static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ - static MenuItemAtlasFont* create(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); + static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); /** * @js ctor */ @@ -220,9 +220,9 @@ public: virtual ~MenuItemAtlasFont(){} /** initializes a menu item from a string and atlas with a target/selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); + CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string and atlas with a target/selector */ - bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); }; @@ -233,11 +233,11 @@ class CC_DLL MenuItemFont : public MenuItemLabel { public: /** creates a menu item from a string without target/selector. To be used with MenuItemToggle */ - static MenuItemFont * create(const char *value); + static MenuItemFont * create(const std::string& value); /** creates a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string with a target/selector */ - static MenuItemFont * create(const char *value, const ccMenuCallback& callback); + static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); /** * @js ctor */ @@ -251,30 +251,30 @@ public: /** initializes a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string with a target/selector */ - bool initWithString(const char *value, const ccMenuCallback& callback); + bool initWithString(const std::string& value, const ccMenuCallback& callback); /** set default font size */ - static void setFontSize(unsigned int s); + static void setFontSize(long size); /** get default font size */ - static unsigned int getFontSize(); + static long getFontSize(); CC_DEPRECATED_ATTRIBUTE static unsigned int fontSize() { return MenuItemFont::getFontSize(); }; /** set the default font name */ - static void setFontName(const char *name); + static void setFontName(const std::string& name); /** get the default font name */ - static const char *getFontName(); - CC_DEPRECATED_ATTRIBUTE static const char *fontName() { return MenuItemFont::getFontName(); }; + static const std::string& getFontName(); + CC_DEPRECATED_ATTRIBUTE static const std::string& fontName() { return MenuItemFont::getFontName(); }; /** set font size * c++ can not overload static and non-static member functions with the same parameter types * so change the name to setFontSizeObj * @js setFontSize */ - void setFontSizeObj(unsigned int s); + void setFontSizeObj(long size); /** get font size * @js getFontSize */ - unsigned int getFontSizeObj() const; + long getFontSizeObj() const; CC_DEPRECATED_ATTRIBUTE unsigned int fontSizeObj() const { return getFontSizeObj(); }; /** set the font name @@ -282,20 +282,20 @@ public: * so change the name to setFontNameObj * @js setFontName */ - void setFontNameObj(const char* name); + void setFontNameObj(const std::string& name); /** returns the name of the Font * @js getFontNameObj */ - const char* getFontNameObj() const; + const std::string& getFontNameObj() const; /** deprecated Use getFontNameObj() instead */ - CC_DEPRECATED_ATTRIBUTE const char* fontNameObj() const { return getFontNameObj(); } + CC_DEPRECATED_ATTRIBUTE const std::string& fontNameObj() const { return getFontNameObj(); } protected: void recreateLabel(); - unsigned int _fontSize; + long _fontSize; std::string _fontName; }; @@ -384,18 +384,18 @@ public: /** Creates an MenuItemImage. */ static MenuItemImage* create(); /** creates a menu item with a normal and selected image*/ - static MenuItemImage* create(const char *normalImage, const char *selectedImage); + static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage); /** creates a menu item with a normal,selected and disabled image*/ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage); + static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage); /** creates a menu item with a normal and selected image with target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector); /** creates a menu item with a normal and selected image with a callable object */ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const ccMenuCallback& callback); + static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const ccMenuCallback& callback); /** creates a menu item with a normal,selected and disabled image with target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); /** creates a menu item with a normal,selected and disabled image with a callable object */ - static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); + static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback); /** * @js ctor */ @@ -410,7 +410,7 @@ public: /** initializes a menu item with a normal, selected and disabled image with target/selector */ CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); /** initializes a menu item with a normal, selected and disabled image with a callable object */ - bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, const ccMenuCallback& callback); + bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback); /** sets the sprite frame for the normal image */ void setNormalSpriteFrame(SpriteFrame* frame); diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index e0f69edd82..19f5c5f1cc 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -68,18 +68,14 @@ public: #ifdef CC_USE_PHYSICS public: bool initWithPhysics(); - + + inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } + virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder, int tag) override; - - /* - * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" - */ - virtual void update(float delta) override; - - inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } - + virtual void update(float delta) override; + protected: virtual void addChildToPhysicsWorld(Node* child); diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index c6c47b3abd..4205adb1fe 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -32,33 +32,33 @@ NS_CC_BEGIN // implementation TMXTiledMap -TMXTiledMap * TMXTiledMap::create(const char *tmxFile) +TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile) { - TMXTiledMap *pRet = new TMXTiledMap(); - if (pRet->initWithTMXFile(tmxFile)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithTMXFile(tmxFile)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -TMXTiledMap* TMXTiledMap::createWithXML(const char* tmxString, const char* resourcePath) +TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath) { - TMXTiledMap *pRet = new TMXTiledMap(); - if (pRet->initWithXML(tmxString, resourcePath)) + TMXTiledMap *ret = new TMXTiledMap(); + if (ret->initWithXML(tmxString, resourcePath)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -bool TMXTiledMap::initWithTMXFile(const char *tmxFile) +bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile) { - CCASSERT(tmxFile != NULL && strlen(tmxFile)>0, "TMXTiledMap: tmx file should not bi NULL"); + CCASSERT(tmxFile.size()>0, "TMXTiledMap: tmx file should not be empty"); setContentSize(Size::ZERO); @@ -74,7 +74,7 @@ bool TMXTiledMap::initWithTMXFile(const char *tmxFile) return true; } -bool TMXTiledMap::initWithXML(const char* tmxString, const char* resourcePath) +bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath) { setContentSize(Size::ZERO); @@ -195,8 +195,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) // update content size with the max size const Size& childSize = child->getContentSize(); Size currentSize = this->getContentSize(); - currentSize.width = MAX( currentSize.width, childSize.width ); - currentSize.height = MAX( currentSize.height, childSize.height ); + currentSize.width = std::max( currentSize.width, childSize.width ); + currentSize.height = std::max( currentSize.height, childSize.height ); this->setContentSize(currentSize); idx++; @@ -206,16 +206,16 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) } // public -TMXLayer * TMXTiledMap::getLayer(const char *layerName) const +TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const { - CCASSERT(layerName != NULL && strlen(layerName) > 0, "Invalid layer name!"); + CCASSERT(layerName.size() > 0, "Invalid layer name!"); Object* pObj = NULL; CCARRAY_FOREACH(_children, pObj) { TMXLayer* layer = dynamic_cast(pObj); if(layer) { - if(0 == strcmp(layer->getLayerName(), layerName)) + if(layerName.compare( layer->getLayerName()) == 0) { return layer; } @@ -226,11 +226,10 @@ TMXLayer * TMXTiledMap::getLayer(const char *layerName) const return NULL; } -TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const +TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const { - CCASSERT(groupName != NULL && strlen(groupName) > 0, "Invalid group name!"); + CCASSERT(groupName.size() > 0, "Invalid group name!"); - std::string sGroupName = groupName; if (_objectGroups && _objectGroups->count()>0) { TMXObjectGroup* objectGroup = NULL; @@ -238,7 +237,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const CCARRAY_FOREACH(_objectGroups, pObj) { objectGroup = static_cast(pObj); - if (objectGroup && objectGroup->getGroupName() == sGroupName) + if (objectGroup && objectGroup->getGroupName() == groupName) { return objectGroup; } @@ -249,7 +248,7 @@ TMXObjectGroup * TMXTiledMap::getObjectGroup(const char *groupName) const return NULL; } -String* TMXTiledMap::getProperty(const char *propertyName) const +String* TMXTiledMap::getProperty(const std::string& propertyName) const { return static_cast(_properties->objectForKey(propertyName)); } diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index 82ea45bd13..f870938174 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -120,19 +120,19 @@ public: virtual ~TMXTiledMap(); /** creates a TMX Tiled Map with a TMX file.*/ - static TMXTiledMap* create(const char *tmxFile); + static TMXTiledMap* create(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - static TMXTiledMap* createWithXML(const char* tmxString, const char* resourcePath); + static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const char *tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const char* tmxString, const char* resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); /** return the TMXLayer for the specific layer */ - TMXLayer* getLayer(const char *layerName) const; + TMXLayer* getLayer(const std::string& layerName) const; /** * @js NA * @lua NA @@ -140,7 +140,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const char *layerName) const { return getLayer(layerName); }; /** return the TMXObjectGroup for the specific group */ - TMXObjectGroup* getObjectGroup(const char *groupName) const; + TMXObjectGroup* getObjectGroup(const std::string& groupName) const; /** * @js NA * @lua NA @@ -148,7 +148,7 @@ public: CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const char *groupName) const { return getObjectGroup(groupName); }; /** return the value for the specific property name */ - String *getProperty(const char *propertyName) const; + String *getProperty(const std::string& propertyName) const; /** * @js NA * @lua NA diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 8497638cf7..d981cca6b4 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -112,7 +112,7 @@ Rect TMXTilesetInfo::rectForGID(unsigned int gid) // implementation TMXMapInfo -TMXMapInfo * TMXMapInfo::create(const char *tmxFile) +TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile) { TMXMapInfo *pRet = new TMXMapInfo(); if(pRet->initWithTMXFile(tmxFile)) @@ -124,7 +124,7 @@ TMXMapInfo * TMXMapInfo::create(const char *tmxFile) return NULL; } -TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resourcePath) +TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath) { TMXMapInfo *pRet = new TMXMapInfo(); if(pRet->initWithXML(tmxString, resourcePath)) @@ -136,7 +136,7 @@ TMXMapInfo * TMXMapInfo::createWithXML(const char* tmxString, const char* resour return NULL; } -void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) +void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath) { _tilesets = Array::create(); _tilesets->retain(); @@ -144,12 +144,12 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _layers = Array::create(); _layers->retain(); - if (tmxFileName != NULL) + if (tmxFileName.size() > 0) { _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName); } - if (resourcePath != NULL) + if (resourcePath.size() > 0) { _resources = resourcePath; } @@ -169,15 +169,15 @@ void TMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) _parentElement = TMXPropertyNone; _currentFirstGID = 0; } -bool TMXMapInfo::initWithXML(const char* tmxString, const char* resourcePath) +bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath) { - internalInit(NULL, resourcePath); + internalInit("", resourcePath); return parseXMLString(tmxString); } -bool TMXMapInfo::initWithTMXFile(const char *tmxFile) +bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile) { - internalInit(tmxFile, NULL); + internalInit(tmxFile, ""); return parseXMLFile(_TMXFileName.c_str()); } @@ -205,13 +205,11 @@ TMXMapInfo::~TMXMapInfo() CC_SAFE_RELEASE(_objectGroups); } -bool TMXMapInfo::parseXMLString(const char *xmlString) +bool TMXMapInfo::parseXMLString(const std::string& xmlString) { - int len = strlen(xmlString); - if (xmlString == NULL || len <= 0) - { + int len = xmlString.size(); + if (len <= 0) return false; - } SAXParser parser; @@ -222,10 +220,10 @@ bool TMXMapInfo::parseXMLString(const char *xmlString) parser.setDelegator(this); - return parser.parse(xmlString, len); + return parser.parse(xmlString.c_str(), len); } -bool TMXMapInfo::parseXMLFile(const char *xmlFilename) +bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename) { SAXParser parser; diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 7b4851386c..80afafd1aa 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -166,9 +166,9 @@ class CC_DLL TMXMapInfo : public Object, public SAXDelegator { public: /** creates a TMX Format with a tmx file */ - static TMXMapInfo * create(const char *tmxFile); + static TMXMapInfo * create(const std::string& tmxFile); /** creates a TMX Format with an XML string and a TMX resource path */ - static TMXMapInfo * createWithXML(const char* tmxString, const char* resourcePath); + static TMXMapInfo * createWithXML(const std::string& tmxString, const std::string& resourcePath); /** creates a TMX Format with a tmx file */ CC_DEPRECATED_ATTRIBUTE static TMXMapInfo * formatWithTMXFile(const char *tmxFile) { return TMXMapInfo::create(tmxFile); }; @@ -185,13 +185,13 @@ public: virtual ~TMXMapInfo(); /** initializes a TMX format with a tmx file */ - bool initWithTMXFile(const char *tmxFile); + bool initWithTMXFile(const std::string& tmxFile); /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(const char* tmxString, const char* resourcePath); + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); /** initializes parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(const char *xmlFilename); + bool parseXMLFile(const std::string& xmlFilename); /* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(const char *xmlString); + bool parseXMLString(const std::string& xmlString); Dictionary* getTileProperties() { return _tileProperties; }; void setTileProperties(Dictionary* tileProperties) { @@ -278,13 +278,13 @@ public: */ void textHandler(void *ctx, const char *ch, int len); - inline const char* getCurrentString(){ return _currentString.c_str(); } - inline void setCurrentString(const char *currentString){ _currentString = currentString; } - inline const char* getTMXFileName(){ return _TMXFileName.c_str(); } - inline void setTMXFileName(const char *fileName){ _TMXFileName = fileName; } -private: - void internalInit(const char* tmxFileName, const char* resourcePath); + inline const std::string& getCurrentString() const { return _currentString; } + inline void setCurrentString(const std::string& currentString){ _currentString = currentString; } + inline const std::string& getTMXFileName() const { return _TMXFileName; } + inline void setTMXFileName(const std::string& fileName){ _TMXFileName = fileName; } + protected: + void internalInit(const std::string& tmxFileName, const std::string& resourcePath); /// map orientation int _orientation; diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 12cc3cc932..1190e8ae8d 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -603,7 +603,7 @@ void UIButton::setTitleFontName(const char* fontName) const char* UIButton::getTitleFontName() const { - return _titleRenderer->getFontName(); + return _titleRenderer->getFontName().c_str(); } void UIButton::setColor(const Color3B &color) diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index 5e4e102aba..e747dfe24c 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -404,7 +404,7 @@ const char * ControlButton::getTitleTTFForState(State state) LabelTTF* labelTTF = dynamic_cast(label); if(labelTTF != 0) { - return labelTTF->getFontName(); + return labelTTF->getFontName().c_str(); } else { From fa0011346e21345a03e688e7a85181cc67aa03d0 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 09:58:24 +0800 Subject: [PATCH 445/557] fixed linux build error --- cocos/gui/UILabelBMFont.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gui/UILabelBMFont.cpp b/cocos/gui/UILabelBMFont.cpp index d8560fd4a8..ee3ad66ddf 100644 --- a/cocos/gui/UILabelBMFont.cpp +++ b/cocos/gui/UILabelBMFont.cpp @@ -60,7 +60,7 @@ void UILabelBMFont::initRenderer() void UILabelBMFont::setFntFile(const char *fileName) { - if (!fileName || std::strcmp(fileName, "") == 0) + if (!fileName || strcmp(fileName, "") == 0) { return; } From f05b79d14082f1fb09aeca7e8247960f7d60a79f Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 7 Nov 2013 11:29:23 +0800 Subject: [PATCH 446/557] remove unneeded files --- samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id | 1 - 1 file changed, 1 deletion(-) delete mode 100644 samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 06123eec12..0000000000 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3275ac270645139eb273b2a47c215f39bcb0e0d5 \ No newline at end of file From af5ab02bc7a123292a85d78b27f2397e7cd13d04 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 14:00:51 +0800 Subject: [PATCH 447/557] temp commit --- .../cocostudio/CCSGUIReader.cpp | 9 ++++---- cocos/gui/UIHelper.cpp | 23 +++++++++++++++++++ cocos/gui/UIHelper.h | 5 +++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index de644e6ec6..f799c26752 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -236,16 +236,15 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) } float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) + { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); -// CCUIHELPER->setFileDesignWidth(winSize.width); -// CCUIHELPER->setFileDesignHeight(winSize.height); + UIHelper::setFileDesignSize(fileName, winSize); } else { -// CCUIHELPER->setFileDesignWidth(fileDesignWidth); -// CCUIHELPER->setFileDesignHeight(fileDesignHeight); + UIHelper::setFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index d896a6372c..8b43c8f890 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -25,6 +25,8 @@ #include "CocosGUI.h" namespace gui { + +static cocos2d::Dictionary* fileDesignSizes = NULL; UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -118,5 +120,26 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) } return NULL; } + +void UIHelper::setFileDesignSize(const char *fileName, const cocos2d::Size &size) +{ + if (!fileDesignSizes) + { + fileDesignSizes = cocos2d::Dictionary::create(); + fileDesignSizes->retain(); + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + fileDesignSizes->setObject(strSize, fileName); +} + +const cocos2d::Size UIHelper::getFileDesignSize(const char* fileName) +{ + if (!fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} } \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index 75ccba81eb..68893ceff0 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -71,8 +71,11 @@ public: /*temp action*/ static UIWidget* seekActionWidgetByActionTag(UIWidget* root, int tag); + + static void setFileDesignSize(const char* fileName, const cocos2d::Size &size); + + static const cocos2d::Size getFileDesignSize(const char* fileName); }; - } #endif /* defined(__CocoGUI__UISystem__) */ From f2cd5ca63003e7d4c1425309ea76a68d677e2aff Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 14:17:57 +0800 Subject: [PATCH 448/557] issue #2771: fix body and joint memory bugs. add removeFormWorld and destroy to PhysicsJoint, and add a destroy param to PhysicsWorld->removeJoint() --- cocos/physics/CCPhysicsBody.cpp | 35 +++++---- cocos/physics/CCPhysicsBody.h | 2 + cocos/physics/CCPhysicsJoint.cpp | 50 +++++++++++-- cocos/physics/CCPhysicsJoint.h | 10 ++- cocos/physics/CCPhysicsShape.cpp | 4 +- cocos/physics/CCPhysicsWorld.cpp | 125 ++++++++++++++++++++++--------- cocos/physics/CCPhysicsWorld.h | 13 ++-- 7 files changed, 176 insertions(+), 63 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 131bfdc3c5..031104157a 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -86,22 +86,15 @@ PhysicsBody::PhysicsBody() PhysicsBody::~PhysicsBody() { - if (_world) - { - removeFromWorld(); - } - - removeAllShapes(); - for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; + PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); - - other->_joints.erase(std::find(other->_joints.begin(), other->_joints.end(), joint)); - + other->removeJoint(joint); delete joint; } + CC_SAFE_DELETE(_info); } @@ -282,6 +275,16 @@ bool PhysicsBody::init() return false; } +void PhysicsBody::removeJoint(PhysicsJoint* joint) +{ + auto it = std::find(_joints.begin(), _joints.end(), joint); + + if (it != _joints.end()) + { + _joints.erase(it); + } +} + void PhysicsBody::setDynamic(bool dynamic) { if (dynamic != _dynamic) @@ -616,7 +619,7 @@ void PhysicsBody::removeShape(int tag) void PhysicsBody::removeShape(PhysicsShape* shape) { - if (_shapes->getIndexOfObject(shape) == UINT_MAX) + if (_shapes->getIndexOfObject(shape) != UINT_MAX) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -629,6 +632,9 @@ void PhysicsBody::removeShape(PhysicsShape* shape) { _world->removeShape(shape); } + + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; shape->setBody(nullptr); _shapes->removeObject(shape); } @@ -650,6 +656,9 @@ void PhysicsBody::removeAllShapes() { _world->removeShape(shape); } + + // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. + shape->_body = nullptr; shape->setBody(nullptr); } @@ -674,10 +683,10 @@ void PhysicsBody::setEnable(bool enable) { if (enable) { - _world->addBody(this); + _world->delayTestAddBody(this); }else { - _world->removeBody(this); + _world->delayTestRemoveBody(this); } } } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 6ae92e4b33..7f465d561c 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -263,6 +263,8 @@ protected: virtual void update(float delta) override; + void removeJoint(PhysicsJoint* joint); + protected: PhysicsBody(); virtual ~PhysicsBody(); diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 791266f8ba..38eb106fce 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -32,6 +32,7 @@ #endif #include "CCPhysicsBody.h" +#include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsJointInfo_chipmunk.h" #include "box2d/CCPhysicsJointInfo_box2d.h" @@ -48,9 +49,11 @@ NS_CC_BEGIN PhysicsJoint::PhysicsJoint() : _bodyA(nullptr) , _bodyB(nullptr) +, _world(nullptr) , _info(nullptr) , _enable(false) , _collisionEnable(true) +, _destoryMark(false) , _tag(0) { @@ -94,12 +97,15 @@ void PhysicsJoint::setEnable(bool enable) { _enable = enable; - if (enable) + if (_world != nullptr) { - - }else - { - + if (enable) + { + _world->delayTestAddJoint(this); + }else + { + _world->delayTestRemoveJoint(this); + } } } } @@ -174,6 +180,40 @@ void PhysicsJoint::setCollisionEnable(bool enable) } } +void PhysicsJoint::removeFormWorld() +{ + if (_world) + { + _world->removeJoint(this, false); + } +} + +void PhysicsJoint::destroy(PhysicsJoint* joint) +{ + if (joint!= nullptr) + { + // remove the joint and delete it. + if (joint->_world != nullptr) + { + joint->_world->removeJoint(joint, true); + } + else + { + if (joint->_bodyA != nullptr) + { + joint->_bodyA->removeJoint(joint); + } + + if (joint->_bodyB != nullptr) + { + joint->_bodyB->removeJoint(joint); + } + + delete joint; + } + } +} + PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointFixed* joint = new PhysicsJointFixed(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index fea8ba4707..55befaf328 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -34,6 +34,7 @@ NS_CC_BEGIN class PhysicsBody; +class PhysicsWorld; class PhysicsJointInfo; class PhysicsBodyInfo; @@ -47,14 +48,17 @@ protected: virtual ~PhysicsJoint() = 0; public: - PhysicsBody* getBodyA() const { return _bodyA; } - PhysicsBody* getBodyB() const { return _bodyB; } + inline PhysicsBody* getBodyA() const { return _bodyA; } + inline PhysicsBody* getBodyB() const { return _bodyB; } + inline PhysicsWorld* getWorld() const { return _world; } inline int getTag() const { return _tag; } inline void setTag(int tag) { _tag = tag; } inline bool isEnabled() const { return _enable; } void setEnable(bool enable); inline bool isCollisionEnabled() const { return _collisionEnable; } void setCollisionEnable(bool enable); + void removeFormWorld(); + static void destroy(PhysicsJoint* joint); protected: bool init(PhysicsBody* a, PhysicsBody* b); @@ -68,9 +72,11 @@ protected: protected: PhysicsBody* _bodyA; PhysicsBody* _bodyB; + PhysicsWorld* _world; PhysicsJointInfo* _info; bool _enable; bool _collisionEnable; + bool _destoryMark; int _tag; friend class PhysicsBody; diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index 7cc64483cd..05264e6a70 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -265,7 +265,7 @@ Point PhysicsShape::getPolyonCenter(const Point* points, int count) void PhysicsShape::setBody(PhysicsBody *body) { // already added - if (_body == body) + if (body != nullptr && _body == body) { return; } @@ -278,12 +278,10 @@ void PhysicsShape::setBody(PhysicsBody *body) if (body == nullptr) { _info->setBody(nullptr); - //_info->setGroup(CP_NO_GROUP); _body = nullptr; }else { _info->setBody(body->_info->getBody()); - //_info->setGroup(body->_info->group); _body = body; } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 3c5956b85c..104b916530 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -307,32 +307,82 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::addJoint(PhysicsJoint* joint) { - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it == _joints.end()) - { - delayTestAddJoint(joint); - _joints.push_back(joint); - } - + delayTestAddJoint(joint); + _joints.push_back(joint); + joint->_world = this; } -void PhysicsWorld::removeJoint(PhysicsJoint* joint) +void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) { - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it != _joints.end()) + if (joint->getWorld() != this) { - delayTestRemoveJoint(*it); - _joints.remove(joint); + if (destroy) + { + CCLOG("physics warnning: the joint is not in this world, it won't be destoried utill the body it conntect is destoried"); + } + return; + } + + delayTestRemoveJoint(joint); + + _joints.remove(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } } } -void PhysicsWorld::removeAllJoints() +void PhysicsWorld::removeAllJoints(bool destroy) { for (auto joint : _joints) { delayTestRemoveJoint(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } } _joints.clear(); @@ -365,8 +415,6 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) if (body->isEnabled()) { - body->_world = this; - //is gravity enable if (!body->isGravityEnabled()) { @@ -393,14 +441,28 @@ PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) delayTestAddBody(body); _bodies->addObject(body); + body->_world = this; return body; } void PhysicsWorld::removeBody(PhysicsBody* body) { + + if (body->getWorld() != this) + { + return; + } + + // destory the body's joints + for (auto joint : body->_joints) + { + removeJoint(joint, true); + } + delayTestRemoveBody(body); _bodies->removeObject(body); + body->_world = nullptr; } void PhysicsWorld::removeBody(int tag) @@ -420,23 +482,12 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); - if (body->getWorld() != this) - { - return; - } - // reset the gravity if (!body->isGravityEnabled()) { body->applyForce(-_gravity); } - // remove joints - for (auto joint : body->_joints) - { - removeJoint(joint); - } - // remove shaps for (auto shape : *body->getShapes()) { @@ -445,8 +496,6 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) // remove body _info->removeBody(body->_info->getBody()); - - body->_world = nullptr; } void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) @@ -461,7 +510,9 @@ void PhysicsWorld::removeAllBodies() { for (Object* obj : *_bodies) { - delayTestRemoveBody(dynamic_cast(obj)); + PhysicsBody* child = dynamic_cast(obj); + delayTestRemoveBody(child); + child->_world = nullptr; } _bodies->removeAllObjects(); @@ -515,6 +566,11 @@ void PhysicsWorld::updateJoints() for (auto joint : _delayRemoveJoints) { realRemoveJoint(joint); + + if (joint->_destoryMark) + { + delete joint; + } } _delayAddJoints.clear(); @@ -525,8 +581,9 @@ void PhysicsWorld::update(float delta) { if (_delayDirty) { - updateBodies(); + // the updateJoints must run before the updateBodies. updateJoints(); + updateBodies(); _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } @@ -795,7 +852,7 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) _scene->getEventDispatcher()->dispatchEvent(&event); } -void PhysicsWorld::setGravity(Point gravity) +void PhysicsWorld::setGravity(const Vect& gravity) { if (_bodies != nullptr) { @@ -932,8 +989,8 @@ PhysicsWorld::PhysicsWorld() PhysicsWorld::~PhysicsWorld() { + removeAllJoints(true); removeAllBodies(); - removeAllJoints(); CC_SAFE_RELEASE(_delayRemoveBodies); CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 2e70749f57..65ffd19927 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -57,7 +57,7 @@ public: Point start; Point end; Point contact; - Point normal; + Vect normal; float fraction; void* data; }Info; @@ -101,9 +101,9 @@ public: /** Adds a joint to the physics world.*/ virtual void addJoint(PhysicsJoint* joint); /** Removes a joint from the physics world.*/ - virtual void removeJoint(PhysicsJoint* joint); + virtual void removeJoint(PhysicsJoint* joint, bool destroy); /** Remove all joints from the physics world.*/ - virtual void removeAllJoints(); + virtual void removeAllJoints(bool destroy); virtual void removeBody(PhysicsBody* body); virtual void removeBody(int tag); @@ -123,9 +123,9 @@ public: inline Scene& getScene() const { return *_scene; } /** get the gravity value */ - inline Point getGravity() const { return _gravity; } + inline Vect getGravity() const { return _gravity; } /** set the gravity value */ - void setGravity(Point gravity); + void setGravity(const Vect& gravity); /** test the debug draw is enabled */ inline bool isDebugDraw() const { return _debugDraw; } @@ -162,7 +162,7 @@ protected: virtual void updateJoints(); protected: - Point _gravity; + Vect _gravity; float _speed; PhysicsWorldInfo* _info; @@ -187,6 +187,7 @@ protected: friend class Scene; friend class PhysicsBody; friend class PhysicsShape; + friend class PhysicsJoint; friend class PhysicsWorldCallback; }; From a02fd7c6dadf2bac0d7a88dfaf0513ab4bb97045 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 14:40:09 +0800 Subject: [PATCH 449/557] issue #2771: fix PhysicsWorld some bugs --- cocos/physics/CCPhysicsWorld.cpp | 29 +++++++++++++++++++---------- cocos/physics/CCPhysicsWorld.h | 4 ++-- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 104b916530..eeabdbce13 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -307,6 +307,11 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::addJoint(PhysicsJoint* joint) { + if (joint->getWorld() != nullptr && joint->getWorld() != this) + { + joint->removeFormWorld(); + } + delayTestAddJoint(joint); _joints.push_back(joint); joint->_world = this; @@ -388,14 +393,14 @@ void PhysicsWorld::removeAllJoints(bool destroy) _joints.clear(); } -PhysicsShape* PhysicsWorld::addShape(PhysicsShape* shape) +void PhysicsWorld::addShape(PhysicsShape* shape) { for (auto cps : shape->_info->getShapes()) { _info->addShape(cps); } - return shape; + return; } void PhysicsWorld::realAddJoint(PhysicsJoint *joint) @@ -408,11 +413,6 @@ void PhysicsWorld::realAddJoint(PhysicsJoint *joint) void PhysicsWorld::realAddBody(PhysicsBody* body) { - if (body->getWorld() != this && body->getWorld() != nullptr) - { - body->removeFromWorld(); - } - if (body->isEnabled()) { //is gravity enable @@ -435,15 +435,23 @@ void PhysicsWorld::realAddBody(PhysicsBody* body) } } -PhysicsBody* PhysicsWorld::addBody(PhysicsBody* body) +void PhysicsWorld::addBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); + if (body->getWorld() == this) + { + return; + } + + if (body->getWorld() != nullptr) + { + body->removeFromWorld(); + } + delayTestAddBody(body); _bodies->addObject(body); body->_world = this; - - return body; } void PhysicsWorld::removeBody(PhysicsBody* body) @@ -451,6 +459,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) if (body->getWorld() != this) { + CCLOG("Physics Warnning: this body doesn't belong to this world"); return; } diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 65ffd19927..1b7775f546 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -136,8 +136,8 @@ protected: static PhysicsWorld* create(Scene& scene); bool init(Scene& scene); - virtual PhysicsBody* addBody(PhysicsBody* body); - virtual PhysicsShape* addShape(PhysicsShape* shape); + virtual void addBody(PhysicsBody* body); + virtual void addShape(PhysicsShape* shape); virtual void removeShape(PhysicsShape* shape); virtual void update(float delta); From eb508e47289fbccdce28e9cd5fadfa51fb66798c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 15:12:13 +0800 Subject: [PATCH 450/557] issue #2771: fix PhysicsWorld functions name readadd/removexxx -> doadd/removexxx delayTestAdd/Removexxx -> add/removexxxOrDelay --- cocos/physics/CCPhysicsBody.cpp | 4 +-- cocos/physics/CCPhysicsJoint.cpp | 4 +-- cocos/physics/CCPhysicsWorld.cpp | 44 ++++++++++++++++---------------- cocos/physics/CCPhysicsWorld.h | 16 ++++++------ 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 031104157a..9304e3652b 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -683,10 +683,10 @@ void PhysicsBody::setEnable(bool enable) { if (enable) { - _world->delayTestAddBody(this); + _world->addBodyOrDelay(this); }else { - _world->delayTestRemoveBody(this); + _world->removeBodyOrDelay(this); } } } diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 38eb106fce..2e037cf2f5 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -101,10 +101,10 @@ void PhysicsJoint::setEnable(bool enable) { if (enable) { - _world->delayTestAddJoint(this); + _world->addJointOrDelay(this); }else { - _world->delayTestRemoveJoint(this); + _world->removeJointOrDelay(this); } } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index eeabdbce13..976fb29e04 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -219,7 +219,7 @@ bool PhysicsWorld::init(Scene& scene) return false; } -void PhysicsWorld::delayTestAddBody(PhysicsBody* body) +void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) { if (_delayRemoveBodies->getIndexOfObject(body) != UINT_MAX) { @@ -236,11 +236,11 @@ void PhysicsWorld::delayTestAddBody(PhysicsBody* body) } }else { - realAddBody(body); + doAddBody(body); } } -void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) +void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) { if (_delayAddBodies->getIndexOfObject(body) != UINT_MAX) { @@ -257,11 +257,11 @@ void PhysicsWorld::delayTestRemoveBody(PhysicsBody* body) } }else { - realRemoveBody(body); + doRemoveBody(body); } } -void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) +void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) { auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); if (it != _delayRemoveJoints.end()) @@ -279,11 +279,11 @@ void PhysicsWorld::delayTestAddJoint(PhysicsJoint* joint) } }else { - realAddJoint(joint); + doAddJoint(joint); } } -void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) +void PhysicsWorld::removeJointOrDelay(PhysicsJoint* joint) { auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); if (it != _delayAddJoints.end()) @@ -301,7 +301,7 @@ void PhysicsWorld::delayTestRemoveJoint(PhysicsJoint* joint) } }else { - realRemoveJoint(joint); + doRemoveJoint(joint); } } @@ -312,7 +312,7 @@ void PhysicsWorld::addJoint(PhysicsJoint* joint) joint->removeFormWorld(); } - delayTestAddJoint(joint); + addJointOrDelay(joint); _joints.push_back(joint); joint->_world = this; } @@ -328,7 +328,7 @@ void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) return; } - delayTestRemoveJoint(joint); + removeJointOrDelay(joint); _joints.remove(joint); joint->_world = nullptr; @@ -362,7 +362,7 @@ void PhysicsWorld::removeAllJoints(bool destroy) { for (auto joint : _joints) { - delayTestRemoveJoint(joint); + removeJointOrDelay(joint); joint->_world = nullptr; // clean the connection to this joint @@ -403,7 +403,7 @@ void PhysicsWorld::addShape(PhysicsShape* shape) return; } -void PhysicsWorld::realAddJoint(PhysicsJoint *joint) +void PhysicsWorld::doAddJoint(PhysicsJoint *joint) { for (auto subjoint : joint->_info->getJoints()) { @@ -411,7 +411,7 @@ void PhysicsWorld::realAddJoint(PhysicsJoint *joint) } } -void PhysicsWorld::realAddBody(PhysicsBody* body) +void PhysicsWorld::doAddBody(PhysicsBody* body) { if (body->isEnabled()) { @@ -449,7 +449,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) body->removeFromWorld(); } - delayTestAddBody(body); + addBodyOrDelay(body); _bodies->addObject(body); body->_world = this; } @@ -469,7 +469,7 @@ void PhysicsWorld::removeBody(PhysicsBody* body) removeJoint(joint, true); } - delayTestRemoveBody(body); + removeBodyOrDelay(body); _bodies->removeObject(body); body->_world = nullptr; } @@ -487,7 +487,7 @@ void PhysicsWorld::removeBody(int tag) } } -void PhysicsWorld::realRemoveBody(PhysicsBody* body) +void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -507,7 +507,7 @@ void PhysicsWorld::realRemoveBody(PhysicsBody* body) _info->removeBody(body->_info->getBody()); } -void PhysicsWorld::realRemoveJoint(PhysicsJoint* joint) +void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) { for (auto subjoint : joint->_info->getJoints()) { @@ -520,7 +520,7 @@ void PhysicsWorld::removeAllBodies() for (Object* obj : *_bodies) { PhysicsBody* child = dynamic_cast(obj); - delayTestRemoveBody(child); + removeBodyOrDelay(child); child->_world = nullptr; } @@ -548,12 +548,12 @@ void PhysicsWorld::updateBodies() for (auto body : *_delayAddBodies) { - realAddBody(dynamic_cast(body)); + doAddBody(dynamic_cast(body)); } for (auto body : *_delayRemoveBodies) { - realRemoveBody(dynamic_cast(body)); + doRemoveBody(dynamic_cast(body)); } _delayAddBodies->removeAllObjects(); @@ -569,12 +569,12 @@ void PhysicsWorld::updateJoints() for (auto joint : _delayAddJoints) { - realAddJoint(joint); + doAddJoint(joint); } for (auto joint : _delayRemoveJoints) { - realRemoveJoint(joint); + doRemoveJoint(joint); if (joint->_destoryMark) { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 1b7775f546..aee0dfefbd 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -150,14 +150,14 @@ protected: virtual void collisionPostSolveCallback(PhysicsContact& contact); virtual void collisionSeparateCallback(PhysicsContact& contact); - virtual void realAddBody(PhysicsBody* body); - virtual void realRemoveBody(PhysicsBody* body); - virtual void realAddJoint(PhysicsJoint* joint); - virtual void realRemoveJoint(PhysicsJoint* joint); - virtual void delayTestAddBody(PhysicsBody* body); - virtual void delayTestRemoveBody(PhysicsBody* body); - virtual void delayTestAddJoint(PhysicsJoint* joint); - virtual void delayTestRemoveJoint(PhysicsJoint* joint); + virtual void doAddBody(PhysicsBody* body); + virtual void doRemoveBody(PhysicsBody* body); + virtual void doAddJoint(PhysicsJoint* joint); + virtual void doRemoveJoint(PhysicsJoint* joint); + virtual void addBodyOrDelay(PhysicsBody* body); + virtual void removeBodyOrDelay(PhysicsBody* body); + virtual void addJointOrDelay(PhysicsJoint* joint); + virtual void removeJointOrDelay(PhysicsJoint* joint); virtual void updateBodies(); virtual void updateJoints(); From 8c025a2cee14a732cac0ba5b614e29de79519a8e Mon Sep 17 00:00:00 2001 From: samuele3 Date: Thu, 7 Nov 2013 15:12:19 +0800 Subject: [PATCH 451/557] Reslove the linux compiled error --- cocos/2d/CCProfiling.cpp | 2 +- cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 3cd9878375..1db8ba0678 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -125,7 +125,7 @@ const char* ProfilingTimer::description() const { static char s_desciption[512] = {0}; - sprintf(s_desciption, "%s ::\tavg1: %dµ,\tavg2: %dµ,\tmin: %dµ,\tmax: %dµ,\ttotal: %.2fs,\tnr calls: %d", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls); + sprintf(s_desciption, "%s ::\tavg1: %ldµ,\tavg2: %ldµ,\tmin: %ldµ,\tmax: %ldµ,\ttotal: %.2fs,\tnr calls: %ld", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls); return s_desciption; } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp index 7e5a38abb1..39083ae1e3 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp @@ -51,8 +51,8 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) ok = true; break; } - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; @@ -70,9 +70,9 @@ static int tolua_cocos2d_MenuItemImage_create(lua_State* tolua_S) break; } #endif - const char* normalImage = ((const char*) tolua_tostring(tolua_S,2,0)); - const char* selectedImage = ((const char*) tolua_tostring(tolua_S,3,0)); - const char* disabledImage = ((const char*) tolua_tostring(tolua_S,4,0)); + const std::string normalImage = ((const std::string) tolua_tocppstring(tolua_S,2,0)); + const std::string selectedImage = ((const std::string) tolua_tocppstring(tolua_S,3,0)); + const std::string disabledImage = ((const std::string) tolua_tocppstring(tolua_S,4,0)); MenuItemImage* tolua_ret = (MenuItemImage*) MenuItemImage::create(normalImage,selectedImage,disabledImage); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; @@ -155,7 +155,7 @@ static int tolua_cocos2d_MenuItemFont_create(lua_State* tolua_S) goto tolua_lerror; } #endif - const char* value = ((const char*) tolua_tostring(tolua_S,2,0)); + const std::string value = ((const std::string) tolua_tocppstring(tolua_S,2,0)); MenuItemFont* tolua_ret = (MenuItemFont*) MenuItemFont::create(value); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; From ef5440f738cdfb45469708a0c7ca13d03af5fc3e Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 16:23:50 +0800 Subject: [PATCH 452/557] issue #2771: change rayCast and rectQuery callback class to std::function --- cocos/physics/CCPhysicsWorld.cpp | 28 +++-- cocos/physics/CCPhysicsWorld.h | 68 +++++------- .../Classes/PhysicsTest/PhysicsTest.cpp | 101 ++++++------------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 4 +- 4 files changed, 74 insertions(+), 127 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 976fb29e04..5b223bb798 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -73,7 +73,7 @@ namespace typedef struct RayCastCallbackInfo { PhysicsWorld* world; - PhysicsRayCastCallback* callback; + PhysicsRayCastCallbackFunc func; Point p1; Point p2; void* data; @@ -82,7 +82,7 @@ namespace typedef struct RectQueryCallbackInfo { PhysicsWorld* world; - PhysicsRectQueryCallback* callback; + PhysicsRectQueryCallbackFunc func; void* data; }RectQueryCallbackInfo; } @@ -148,7 +148,7 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect auto it = PhysicsShapeInfo::getMap().find(shape); CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - PhysicsRayCastCallback::Info callbackInfo = + PhysicsRayCastInfo callbackInfo = { it->second->getShape(), info->p1, @@ -158,7 +158,7 @@ void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect (float)t, }; - PhysicsWorldCallback::continues = info->callback->report(*info->world, callbackInfo, info->data); + PhysicsWorldCallback::continues = info->func(*info->world, callbackInfo, info->data); } void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info) @@ -172,9 +172,7 @@ void PhysicsWorldCallback::rectQueryCallbackFunc(cpShape *shape, RectQueryCallba return; } - PhysicsWorldCallback::continues = info->callback->report(*info->world, - *it->second->getShape(), - info->data); + PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } void PhysicsWorldCallback::nearestPointQueryFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) @@ -883,13 +881,13 @@ void PhysicsWorld::setGravity(const Vect& gravity) } -void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data) +void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data) { - CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); - if (callback.report != nullptr) + if (func != nullptr) { - RayCastCallbackInfo info = { this, &callback, point1, point2, data }; + RayCastCallbackInfo info = { this, func, point1, point2, data }; PhysicsWorldCallback::continues = true; cpSpaceSegmentQuery(this->_info->getSpace(), @@ -903,13 +901,13 @@ void PhysicsWorld::rayCast(PhysicsRayCastCallback& callback, const Point& point1 } -void PhysicsWorld::rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data) +void PhysicsWorld::rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data) { - CCASSERT(callback.report != nullptr, "callback.report shouldn't be nullptr"); + CCASSERT(func != nullptr, "callback.report shouldn't be nullptr"); - if (callback.report != nullptr) + if (func != nullptr) { - RectQueryCallbackInfo info = {this, &callback, data}; + RectQueryCallbackInfo info = {this, func, data}; PhysicsWorldCallback::continues = true; cpSpaceBBQuery(this->_info->getSpace(), diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index aee0dfefbd..240e3fa660 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -48,49 +48,31 @@ class Scene; class DrawNode; class PhysicsWorld; -class PhysicsRayCastCallback -{ -public: - typedef struct Info - { - PhysicsShape* shape; - Point start; - Point end; - Point contact; - Vect normal; - float fraction; - void* data; - }Info; - -public: - PhysicsRayCastCallback() - : report(nullptr) - {} - virtual ~PhysicsRayCastCallback(){} - /** - * @brief Called for each fixture found in the query. You control how the ray cast - * proceeds by returning a float: - * return true: continue - * return false: terminate the ray cast - * @param fixture the fixture hit by the ray - * @param point the point of initial intersection - * @param normal the normal vector at the point of intersection - * @return true to continue, false to terminate - */ - std::function report; -}; -class PhysicsRectQueryCallback + +typedef struct PhysicsRayCastInfo { -public: - PhysicsRectQueryCallback() - : report(nullptr) - {} - virtual ~PhysicsRectQueryCallback(){} - -public: - std::function report; -}; + PhysicsShape* shape; + Point start; + Point end; + Point contact; + Vect normal; + float fraction; + void* data; +}PhysicsRayCastInfo; + +/** + * @brief Called for each fixture found in the query. You control how the ray cast + * proceeds by returning a float: + * return true: continue + * return false: terminate the ray cast + * @param fixture the fixture hit by the ray + * @param point the point of initial intersection + * @param normal the normal vector at the point of intersection + * @return true to continue, false to terminate + */ +typedef std::function PhysicsRayCastCallbackFunc; +typedef std::function PhysicsRectQueryCallbackFunc; /** * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. @@ -109,8 +91,8 @@ public: virtual void removeBody(int tag); virtual void removeAllBodies(); - void rayCast(PhysicsRayCastCallback& callback, const Point& point1, const Point& point2, void* data); - void rectQuery(PhysicsRectQueryCallback& callback, const Rect& rect, void* data); + void rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data); + void rectQuery(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data); Array* getShapes(const Point& point) const; PhysicsShape* getShape(const Point& point) const; Array* getAllBodies() const; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 0885218d9a..af27626949 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -602,65 +602,12 @@ void PhysicsDemoRayCast::changeModeCallback(Object* sender) } } -bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data) +bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data) { *((Point*)data) = info.contact; return false; } -class PhysicsDemoNearestRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoNearestRayCastCallback(); - -private: - float _friction; -}; - -PhysicsDemoNearestRayCastCallback::PhysicsDemoNearestRayCastCallback() -: _friction(1.0f) -{ - report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool - { - if (_friction > info.fraction) - { - *((Point*)data) = info.contact; - _friction = info.fraction; - } - - return true; - }; -} - -namespace -{ - static const int MAX_MULTI_RAYCAST_NUM = 5; -} - -class PhysicsDemoMultiRayCastCallback : public PhysicsRayCastCallback -{ -public: - PhysicsDemoMultiRayCastCallback(); - -public: - Point points[MAX_MULTI_RAYCAST_NUM]; - int num; -}; - -PhysicsDemoMultiRayCastCallback::PhysicsDemoMultiRayCastCallback() -: num(0) -{ - report = [this](PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data)->bool - { - if (num < MAX_MULTI_RAYCAST_NUM) - { - points[num++] = info.contact; - } - - return true; - }; -} - void PhysicsDemoRayCast::update(float delta) { float L = 150.0f; @@ -674,11 +621,10 @@ void PhysicsDemoRayCast::update(float delta) { case 0: { - PhysicsRayCastCallback callback; Point point3 = point2; - callback.report = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); + auto func = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -691,10 +637,20 @@ void PhysicsDemoRayCast::update(float delta) } case 1: { - PhysicsDemoNearestRayCastCallback callback; Point point3 = point2; + float friction = 1.0f; + PhysicsRayCastCallbackFunc func = [&point3, &friction](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (friction > info.fraction) + { + point3 = info.contact; + friction = info.fraction; + } + + return true; + }; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, &point3); + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) @@ -707,15 +663,27 @@ void PhysicsDemoRayCast::update(float delta) } case 2: { - PhysicsDemoMultiRayCastCallback callback; +#define MAX_MULTI_RAYCAST_NUM 5 + Point points[MAX_MULTI_RAYCAST_NUM]; + int num = 0; - _scene->getPhysicsWorld()->rayCast(callback, point1, point2, nullptr); + PhysicsRayCastCallbackFunc func = [&points, &num](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool + { + if (num < MAX_MULTI_RAYCAST_NUM) + { + points[num++] = info.contact; + } + + return true; + }; + + _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point2, 1, STATIC_COLOR); - for (int i = 0; i < callback.num; ++i) + for (int i = 0; i < num; ++i) { - _node->drawDot(callback.points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + _node->drawDot(points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); @@ -1089,7 +1057,7 @@ void PhysicsDemoSlice::onEnter() addChild(box); } -bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastCallback::Info &info, void *data) +bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastInfo& info, void *data) { if (info.shape->getBody()->getTag() != _sliceTag) { @@ -1156,9 +1124,8 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) { - PhysicsRayCastCallback callback; - callback.report = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); - _scene->getPhysicsWorld()->rayCast(callback, touch->getStartLocation(), touch->getLocation(), nullptr); + auto func = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); + _scene->getPhysicsWorld()->rayCast(func, touch->getStartLocation(), touch->getLocation(), nullptr); } std::string PhysicsDemoSlice::title() diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 7355045cad..5235f92e34 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -96,7 +96,7 @@ public: void changeModeCallback(Object* sender); - bool anyRay(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); + bool anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); private: float _angle; @@ -150,7 +150,7 @@ public: std::string title() override; std::string subtitle() override; - bool slice(PhysicsWorld& world, const PhysicsRayCastCallback::Info& info, void* data); + bool slice(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data); void clipPoly(PhysicsShapePolygon* shape, Point normal, float distance); bool onTouchBegan(Touch *touch, Event *event); From c9f814c0160023bb90f44025ca733dd889c66c75 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 7 Nov 2013 16:39:41 +0800 Subject: [PATCH 453/557] fix Accelerometer Test with missing: Device::setAccelerometerEnabled(true); --- .../Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp | 1 + samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 2 ++ samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 1 + samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 1 + 4 files changed, 5 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index db535fe321..8ca2430219 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,6 +32,7 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index e0c4ba23ed..0d52bdde86 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,6 +20,7 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -60,6 +61,7 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 50d5dc7252..fbc07ca9c3 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -26,6 +26,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index db51829b3f..3184565698 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -210,6 +210,7 @@ void PhysicsDemoClickAdd::onEnter() touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); From 9f5095b9c35171bdd962a9bb37c8239534358abd Mon Sep 17 00:00:00 2001 From: samuele3 Date: Thu, 7 Nov 2013 16:43:04 +0800 Subject: [PATCH 454/557] Reslove the compiled error --- cocos/gui/UITextField.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 2eabd208b2..7eb30518cd 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -586,7 +586,7 @@ void UITextField::copySpecialProperties(UIWidget *widget) setText(textField->_textFieldRenderer->getString()); setPlaceHolder(textField->getStringValue()); setFontSize(textField->_textFieldRenderer->getFontSize()); - setFontName(textField->_textFieldRenderer->getFontName()); + setFontName(textField->_textFieldRenderer->getFontName().c_str()); setMaxLengthEnabled(textField->isMaxLengthEnabled()); setMaxLength(textField->getMaxLength()); setPasswordEnabled(textField->isPasswordEnabled()); From 9f2297a5a6502f26ab6df1a70db293e9e3ee989f Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 16:46:41 +0800 Subject: [PATCH 455/557] add "retain" to listeners --- cocos/gui/UICheckBox.cpp | 6 +++++- cocos/gui/UIPageView.cpp | 5 +++++ cocos/gui/UIScrollView.cpp | 6 +++++- cocos/gui/UISlider.cpp | 6 +++++- cocos/gui/UITextField.cpp | 5 +++++ cocos/gui/UIWidget.cpp | 21 ++++++++++--------- cocos/gui/UIWidget.h | 6 ------ .../CocoStudioGUITest/UIScene.cpp | 3 +++ 8 files changed, 39 insertions(+), 19 deletions(-) diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index a826fa40ef..c577a86fe6 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -51,7 +51,9 @@ _frontCrossDisabledFileName("") UICheckBox::~UICheckBox() { - + CC_SAFE_RELEASE(_selectedStateEventListener); + _selectedStateEventListener = NULL; + _selectedStateEventSelector = NULL; } UICheckBox* UICheckBox::create() @@ -300,7 +302,9 @@ void UICheckBox::unSelectedEvent() void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { + CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = target; + CC_SAFE_RETAIN(_selectedStateEventListener); _selectedStateEventSelector = selector; } diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 8498e79d88..bb88e6cb80 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -51,6 +51,9 @@ UIPageView::~UIPageView() { _pages->removeAllObjects(); CC_SAFE_RELEASE(_pages); + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UIPageView* UIPageView::create() @@ -571,7 +574,9 @@ void UIPageView::pageTurningEvent() void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 1270c78682..2654eeda53 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -76,7 +76,9 @@ _eventSelector(NULL) UIScrollView::~UIScrollView() { - + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UIScrollView* UIScrollView::create() @@ -1529,7 +1531,9 @@ void UIScrollView::bounceRightEvent() void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index f3c0a90b97..d5e0eac9ae 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -58,7 +58,9 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - + CC_SAFE_RELEASE(_slidPercentListener); + _slidPercentListener = NULL; + _slidPercentSelector = NULL; } UISlider* UISlider::create() @@ -412,7 +414,9 @@ float UISlider::getPercentWithBallPos(float px) void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { + CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = target; + CC_SAFE_RETAIN(_slidPercentListener); _slidPercentSelector = selector; } diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 2eabd208b2..68f4c1c75b 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -283,6 +283,9 @@ _passwordStyleText("") UITextField::~UITextField() { + CC_SAFE_RELEASE(_eventListener); + _eventListener = NULL; + _eventSelector = NULL; } UITextField* UITextField::create() @@ -504,7 +507,9 @@ void UITextField::deleteBackwardEvent() void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { + CC_SAFE_RELEASE(_eventListener); _eventListener = target; + CC_SAFE_RETAIN(_eventListener); _eventSelector = selecor; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 00ee50680c..3f93746594 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -75,7 +75,15 @@ _isRunning(false) UIWidget::~UIWidget() { - releaseResoures(); + CCLOG("widget aa"); + CC_SAFE_RELEASE(_touchEventListener); + _touchEventListener = NULL; + _touchEventSelector = NULL; + removeAllChildren(); + _children->release(); + _renderer->removeAllChildrenWithCleanup(true); + _renderer->removeFromParentAndCleanup(true); + _renderer->release(); setParent(NULL); _layoutParameterDictionary->removeAllObjects(); CC_SAFE_RELEASE(_layoutParameterDictionary); @@ -116,15 +124,6 @@ bool UIWidget::init() return true; } -void UIWidget::releaseResoures() -{ - removeAllChildren(); - _children->release(); - _renderer->removeAllChildrenWithCleanup(true); - _renderer->removeFromParentAndCleanup(true); - _renderer->release(); -} - void UIWidget::onEnter() { arrayMakeObjectsPerformSelector(_children, onEnter, UIWidget*); @@ -700,7 +699,9 @@ void UIWidget::longClickEvent() void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { + CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = target; + CC_SAFE_RETAIN(_touchEventListener); _touchEventSelector = selector; } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index d8f35578f4..f4f48f2a94 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -907,12 +907,6 @@ protected: void cancelUpEvent(); void longClickEvent(); void updateAnchorPoint(); - /** - * Release texture resoures of widget. - * Release renderer. - * If you override releaseResoures, you shall call its parent's one, e.g. UIWidget::releaseResoures(). - */ - virtual void releaseResoures(); void updateSizeAndPosition(); void copyProperties(UIWidget* model); virtual UIWidget* createCloneInstance(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index 38344c9490..cc95546ca1 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -74,6 +74,7 @@ void UIScene::previousCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->previousUIScene()); } } @@ -82,6 +83,7 @@ void UIScene::restartCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->currentUIScene()); } } @@ -90,6 +92,7 @@ void UIScene::nextCallback(Object* sender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); CCDirector::getInstance()->replaceScene(UISceneManager::sharedUISceneManager()->nextUIScene()); } } From b5f83c30b66b696c02725ddaa1237ad064ace846 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 7 Nov 2013 17:08:16 +0800 Subject: [PATCH 456/557] fix indention --- .../TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp | 2 +- samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 4 ++-- samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 2 +- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index 8ca2430219..5bc3d6a7ed 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -32,7 +32,7 @@ void AccelerometerTest::onEnter() { Layer::onEnter(); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index 0d52bdde86..b7a60bb7a8 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -20,7 +20,7 @@ bool Bug624Layer::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); @@ -61,7 +61,7 @@ bool Bug624Layer2::init() label->setPosition(Point(size.width/2, size.height/2)); addChild(label); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index fbc07ca9c3..4a4cd5e027 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -26,7 +26,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 3184565698..2ef3f4fc4a 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -210,7 +210,7 @@ void PhysicsDemoClickAdd::onEnter() touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - Device::setAccelerometerEnabled(true); + Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); _eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); From a116e7ec79b786bcddfba4c8ffb2761f8a420622 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 7 Nov 2013 09:11:22 +0000 Subject: [PATCH 457/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f55eab57aa..52e968dfe0 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f55eab57aa6b3ff20fd33bea986e4569ebd68c8e +Subproject commit 52e968dfe02f077f56d4df6cc04e38c8b76e22b9 From e2249c8c3f4bebd788e06699f2b7584f51cecfd2 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 17:15:52 +0800 Subject: [PATCH 458/557] Fixed crash --- cocos/gui/UIInputManager.cpp | 8 ++++---- cocos/gui/UIWidget.cpp | 1 - .../CocoStudioGUITest/CocosGUIScene.cpp | 13 +------------ .../ExtensionsTest/CocoStudioGUITest/UIScene.cpp | 1 + 4 files changed, 6 insertions(+), 17 deletions(-) diff --git a/cocos/gui/UIInputManager.cpp b/cocos/gui/UIInputManager.cpp index bb36043855..a1c6659557 100644 --- a/cocos/gui/UIInputManager.cpp +++ b/cocos/gui/UIInputManager.cpp @@ -176,10 +176,10 @@ void UIInputManager::onTouchEnd(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchEnded(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::onTouchCancelled(Touch* touch) @@ -191,10 +191,10 @@ void UIInputManager::onTouchCancelled(Touch* touch) int length = selectedWidgetArray->num; for (int i=0; iarr[i]); + UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); + _selectedWidgets->removeObject(hitWidget); hitWidget->onTouchCancelled(_touchEndedPoint); } - _selectedWidgets->removeAllObjects(); } void UIInputManager::setRootWidget(UIWidget *root) diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 3f93746594..7f2adc545a 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -75,7 +75,6 @@ _isRunning(false) UIWidget::~UIWidget() { - CCLOG("widget aa"); CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = NULL; _touchEventSelector = NULL; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp index 750b562a67..43a15715c8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp @@ -25,17 +25,7 @@ void CocosGUITestScene::runThisTest() { Director::getInstance()->replaceScene(this); - - ul = UILayer::create(); - ul->scheduleUpdate(); - this->addChild(ul); - - /* - Layout* layout = static_cast(CCUIHELPER->createWidgetFromJsonFile("cocosgui/UI/UI01.json")); - ul->addWidget(layout); - */ - -// /* + Size s = CCDirector::getInstance()->getWinSize(); _itemMenu = CCMenu::create(); @@ -56,7 +46,6 @@ void CocosGUITestScene::runThisTest() } void CocosGUITestScene::MainMenuCallback(Object* pSender) { - ul->removeFromParent(); ExtensionsTestScene *pScene = new ExtensionsTestScene(); pScene->runThisTest(); pScene->release(); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index cc95546ca1..a2a3ddcf42 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -64,6 +64,7 @@ void UIScene::menuCloseCallback(Object* pSender, TouchEventType type) { if (type == TOUCH_EVENT_ENDED) { + m_pUiLayer->removeFromParent(); auto scene = new ExtensionsTestScene(); scene->runThisTest(); scene->release(); From b9b14571ac3e21f252b1483a101065ccea810d0b Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 7 Nov 2013 17:16:31 +0800 Subject: [PATCH 459/557] fix compiling erros on Android --- cocos/2d/CCUserDefaultAndroid.cpp | 4 +- .../platform/android/CCFileUtilsAndroid.cpp | 40 +++++++++---------- .../2d/platform/android/CCFileUtilsAndroid.h | 6 +-- cocos/gui/UILayoutDefine.h | 1 - 4 files changed, 25 insertions(+), 26 deletions(-) diff --git a/cocos/2d/CCUserDefaultAndroid.cpp b/cocos/2d/CCUserDefaultAndroid.cpp index 38c09c2a90..db18dd2951 100644 --- a/cocos/2d/CCUserDefaultAndroid.cpp +++ b/cocos/2d/CCUserDefaultAndroid.cpp @@ -74,8 +74,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc { tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument(); *doc = xmlDoc; - unsigned long nSize; - const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize); + long size; + const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size); //const char* pXmlBuffer = (const char*)data.getBuffer(); if(NULL == pXmlBuffer) { diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp index d15e4f874a..c447b5db32 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp @@ -130,21 +130,21 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const } -unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, long * size) { - return doGetFileData(filename, pszMode, pSize, false); + return doGetFileData(filename, mode, size, false); } -unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize) +unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, long * pSize) { return doGetFileData(filename, pszMode, pSize, true); } -unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync) +unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, long * size, bool forAsync) { - unsigned char * pData = 0; + unsigned char * data = 0; - if ((! filename) || (! pszMode) || 0 == strlen(filename)) + if ((! filename) || (! mode) || 0 == strlen(filename)) { return 0; } @@ -189,14 +189,14 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* return NULL; } - off_t size = AAsset_getLength(asset); + off_t fileSize = AAsset_getLength(asset); - pData = new unsigned char[size]; + data = new unsigned char[fileSize]; - int bytesread = AAsset_read(asset, (void*)pData, size); - if (pSize) + int bytesread = AAsset_read(asset, (void*)data, fileSize); + if (size) { - *pSize = bytesread; + *size = bytesread; } AAsset_close(asset); @@ -207,32 +207,32 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* { // read rrom other path than user set it //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); - FILE *fp = fopen(fullPath.c_str(), pszMode); + FILE *fp = fopen(fullPath.c_str(), mode); CC_BREAK_IF(!fp); - unsigned long size; + long fileSize; fseek(fp,0,SEEK_END); - size = ftell(fp); + fileSize = ftell(fp); fseek(fp,0,SEEK_SET); - pData = new unsigned char[size]; - size = fread(pData,sizeof(unsigned char), size,fp); + data = new unsigned char[fileSize]; + fileSize = fread(data,sizeof(unsigned char), fileSize,fp); fclose(fp); - if (pSize) + if (size) { - *pSize = size; + *size = fileSize; } } while (0); } - if (! pData) + if (! data) { std::string msg = "Get data from file("; msg.append(filename).append(") failed!"); CCLOG("%s", msg.c_str()); } - return pData; + return data; } string FileUtilsAndroid::getWritablePath() const diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index 87a2445f48..3bee6d2e39 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -55,7 +55,7 @@ public: /* override funtions */ bool init(); - virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize); + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size); virtual std::string getWritablePath() const; virtual bool isFileExist(const std::string& strFilePath) const; @@ -64,10 +64,10 @@ public: /** This function is android specific. It is used for TextureCache::addImageAsync(). Don't use it in your codes. */ - unsigned char* getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize); + unsigned char* getFileDataForAsync(const char* filename, const char* mode, long * size); private: - unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync); + unsigned char* doGetFileData(const char* filename, const char* mode, long * size, bool forAsync); static AAssetManager* assetmanager; }; diff --git a/cocos/gui/UILayoutDefine.h b/cocos/gui/UILayoutDefine.h index 0b772837ca..70ab70251f 100644 --- a/cocos/gui/UILayoutDefine.h +++ b/cocos/gui/UILayoutDefine.h @@ -26,7 +26,6 @@ #define __UILAYOUTDEFINE_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" namespace gui { /** From e278ad66c80ec24f047a6b007893dbaa90a89e70 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 17:46:05 +0800 Subject: [PATCH 460/557] issue #2771: change PhysicsJoint::create() to PhysicsJoint::construct() --- cocos/physics/CCPhysicsJoint.cpp | 10 +++++----- cocos/physics/CCPhysicsJoint.h | 12 ++++++------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 16 ++++++++-------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index 2e037cf2f5..578b8fefc7 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -214,7 +214,7 @@ void PhysicsJoint::destroy(PhysicsJoint* joint) } } -PhysicsJointFixed* PhysicsJointFixed::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointFixed* PhysicsJointFixed::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointFixed* joint = new PhysicsJointFixed(); @@ -255,7 +255,7 @@ bool PhysicsJointFixed::init(PhysicsBody* a, PhysicsBody* b, const Point& anchr) return false; } -PhysicsJointPin* PhysicsJointPin::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr) +PhysicsJointPin* PhysicsJointPin::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr) { PhysicsJointPin* joint = new PhysicsJointPin(); @@ -296,7 +296,7 @@ float PhysicsJointPin::getMaxForce() const return PhysicsHelper::cpfloat2float(_info->getJoints().front()->maxForce); } -PhysicsJointSliding* PhysicsJointSliding::create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) +PhysicsJointSliding* PhysicsJointSliding::construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr) { PhysicsJointSliding* joint = new PhysicsJointSliding(); @@ -331,7 +331,7 @@ bool PhysicsJointSliding::init(PhysicsBody* a, PhysicsBody* b, const Point& groo } -PhysicsJointLimit* PhysicsJointLimit::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointLimit* PhysicsJointLimit::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointLimit* joint = new PhysicsJointLimit(); @@ -386,7 +386,7 @@ void PhysicsJointLimit::setMax(float max) cpSlideJointSetMax(_info->getJoints().front(), PhysicsHelper::float2cpfloat(max)); } -PhysicsJointDistance* PhysicsJointDistance::create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) +PhysicsJointDistance* PhysicsJointDistance::construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2) { PhysicsJointDistance* joint = new PhysicsJointDistance(); diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 55befaf328..789d64a5b2 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -89,7 +89,7 @@ protected: class PhysicsJointFixed : public PhysicsJoint { public: - static PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointFixed* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); @@ -105,7 +105,7 @@ protected: class PhysicsJointSliding : public PhysicsJoint { public: - static PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); + static PhysicsJointSliding* construct(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); @@ -121,7 +121,7 @@ protected: class PhysicsJointSpring : public PhysicsJoint { public: - PhysicsJointSpring* create(); + PhysicsJointSpring* construct(); protected: bool init(); @@ -137,7 +137,7 @@ protected: class PhysicsJointLimit : public PhysicsJoint { public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + PhysicsJointLimit* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); float getMin() const; void setMin(float min); @@ -158,7 +158,7 @@ protected: class PhysicsJointPin : public PhysicsJoint { public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); + static PhysicsJointPin* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr); void setMaxForce(float force); float getMaxForce() const; @@ -175,7 +175,7 @@ class PhysicsJointDistance : public PhysicsJoint { public: - static PhysicsJointDistance* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); + static PhysicsJointDistance* construct(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); protected: bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index af27626949..f635e4541f 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -403,7 +403,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); - PhysicsJointPin* joint = PhysicsJointPin::create(mouse->getPhysicsBody(), shape->getBody(), location); + PhysicsJointPin* joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), shape->getBody(), location); joint->setMaxForce(5000.0f * shape->getBody()->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); @@ -765,7 +765,7 @@ void PhysicsDemoJoints::onEnter() auto sp2 = makeBall(offset + Point(30, 0), 10); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - PhysicsJointPin* joint = PhysicsJointPin::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + PhysicsJointPin* joint = PhysicsJointPin::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -780,7 +780,7 @@ void PhysicsDemoJoints::onEnter() auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - PhysicsJointFixed* joint = PhysicsJointFixed::create(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); + PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -895,7 +895,7 @@ void PhysicsDemoPump::onEnter() sgearB->setCategoryBitmask(0x04); sgearB->setCollisionBitmask(0x04); sgearB->setTag(1); - _world->addJoint(PhysicsJointPin::create(body, sgearB, sgearB->getPosition())); + _world->addJoint(PhysicsJointPin::construct(body, sgearB, sgearB->getPosition())); // big gear @@ -905,7 +905,7 @@ void PhysicsDemoPump::onEnter() bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); this->addChild(bgear); bgearB->setCategoryBitmask(0x04); - _world->addJoint(PhysicsJointPin::create(body, bgearB, bgearB->getPosition())); + _world->addJoint(PhysicsJointPin::construct(body, bgearB, bgearB->getPosition())); // pump @@ -917,7 +917,7 @@ void PhysicsDemoPump::onEnter() this->addChild(pump); pumpB->setCategoryBitmask(0x02); pumpB->setGravityEnable(false); - _world->addJoint(PhysicsJointDistance::create(pumpB, sgearB, Point(0, 0), Point(0, -44))); + _world->addJoint(PhysicsJointDistance::construct(pumpB, sgearB, Point(0, 0), Point(0, -44))); // plugger Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; @@ -934,8 +934,8 @@ void PhysicsDemoPump::onEnter() this->addChild(plugger); pluggerB->setCategoryBitmask(0x02); sgearB->setCollisionBitmask(0x04 | 0x01); - _world->addJoint(PhysicsJointPin::create(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); - _world->addJoint(PhysicsJointDistance::create(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); + _world->addJoint(PhysicsJointPin::construct(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); + _world->addJoint(PhysicsJointDistance::construct(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); } void PhysicsDemoPump::update(float delta) From 3e8871f2c962d554685b52e3a742a963f175f21a Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 17:53:30 +0800 Subject: [PATCH 461/557] issue #2771: delete some unfinished PhysicsTest and change subtitle --- .../Classes/PhysicsTest/PhysicsTest.cpp | 54 +++---------------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 17 +----- 2 files changed, 8 insertions(+), 63 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index f635e4541f..c97b377709 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -6,7 +6,6 @@ namespace { static std::function createFunctions[] = { CL(PhysicsDemoLogoSmash), - CL(PhysicsDemoPyramidStack), CL(PhysicsDemoPlink), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), @@ -481,42 +480,6 @@ std::string PhysicsDemoLogoSmash::title() return "Logo Smash"; } -void PhysicsDemoPyramidStack::onEnter() -{ - PhysicsDemo::onEnter(); - - auto touchListener = EventListenerTouchOneByOne::create(); - touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchBegan, this); - touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchMoved, this); - touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchEnded, this); - _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); - - auto node = Node::create(); - node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); - this->addChild(node); - - auto ball = Sprite::create("Images/ball.png"); - ball->setScale(1); - ball->setPhysicsBody(PhysicsBody::createCircle(10)); - ball->setPosition(VisibleRect::bottom() + Point(0, 60)); - this->addChild(ball); - - for(int i=0; i<14; i++) - { - for(int j=0; j<=i; j++) - { - auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); - - sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); - } - } -} -std::string PhysicsDemoPyramidStack::title() -{ - return "Pyramid Stack"; -} - - void PhysicsDemoPlink::onEnter() { PhysicsDemo::onEnter(); @@ -995,6 +958,11 @@ std::string PhysicsDemoPump::title() return "Pump"; } +std::string PhysicsDemoPump::subtitle() +{ + return "open debug to see it"; +} + void PhysicsDemoOneWayPlatform::onEnter() { PhysicsDemo::onEnter(); @@ -1135,15 +1103,5 @@ std::string PhysicsDemoSlice::title() std::string PhysicsDemoSlice::subtitle() { - return "click and drag to slice up the block"; -} - -void PhysicsDemoWater::onEnter() -{ - PhysicsDemo::onEnter(); -} - -std::string PhysicsDemoWater::title() -{ - return "Water"; + return "click and drag to slice up the block, open debug to see it"; } \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 5235f92e34..4ca37bd77b 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -70,13 +70,6 @@ public: std::string title() override; }; -class PhysicsDemoPyramidStack : public PhysicsDemo -{ -public: - void onEnter() override; - std::string title() override; -}; - class PhysicsDemoPlink : public PhysicsDemo { public: @@ -122,8 +115,9 @@ class PhysicsDemoPump : public PhysicsDemo { public: void onEnter() override; - std::string title() override; void update(float delta) override; + std::string title() override; + std::string subtitle() override; bool onTouchBegan(Touch* touch, Event* event); void onTouchMoved(Touch* touch, Event* event); @@ -161,11 +155,4 @@ private: int _sliceTag; }; -class PhysicsDemoWater : public PhysicsDemo -{ -public: - void onEnter() override; - std::string title() override; -}; - #endif From 99546cef4686babdfbd208bea5fd6c441f604368 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 18:52:36 +0800 Subject: [PATCH 462/557] issue #3025: add getTextureCache() in CCdirector() --- cocos/2d/CCDirector.cpp | 28 +++++++++++++++++++++++++++- cocos/2d/CCDirector.h | 10 ++++++++++ cocos/2d/CCTextureCache.cpp | 27 +++++++++------------------ cocos/2d/CCTextureCache.h | 4 ++++ 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 130d170d30..b55bec2446 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -145,6 +145,8 @@ bool Director::init(void) _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); + //init TextureCache + initTextureCache(); // create autorelease pool PoolManager::sharedPoolManager()->push(); @@ -359,6 +361,29 @@ void Director::setOpenGLView(EGLView *pobOpenGLView) } } +TextureCache* Director::getTextureCache() const +{ + return _textureCache; +} + +void Director::initTextureCache() +{ +#ifdef EMSCRIPTEN + _textureCache = new TextureCacheEmscripten(); +#else + _textureCache = new TextureCache(); +#endif // EMSCRIPTEN +} + +void Director::destroyTextureCache() +{ + if (_textureCache) + { + _textureCache->waitForQuit(); + CC_SAFE_RELEASE_NULL(_textureCache); + } +} + void Director::setViewport() { if (_openGLView) @@ -693,7 +718,6 @@ void Director::purgeDirector() DrawPrimitives::free(); AnimationCache::destroyInstance(); SpriteFrameCache::destroyInstance(); - TextureCache::destroyInstance(); ShaderCache::destroyInstance(); FileUtils::destroyInstance(); Configuration::destroyInstance(); @@ -704,6 +728,8 @@ void Director::purgeDirector() GL::invalidateStateCache(); + destroyTextureCache(); + CHECK_GL_ERROR_DEBUG(); // OpenGL view diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index b01b0fe954..0eb4b5d390 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -54,6 +54,7 @@ class Node; class Scheduler; class ActionManager; class EventDispatcher; +class TextureCache; /** @brief Class that creates and handles the main Window and manages how @@ -137,6 +138,8 @@ public: inline EGLView* getOpenGLView() { return _openGLView; } void setOpenGLView(EGLView *pobOpenGLView); + TextureCache* getTextureCache() const; + inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; } void setNextDeltaTimeZero(bool nextDeltaTimeZero); @@ -381,6 +384,10 @@ protected: /** calculates delta time since last time it was called */ void calculateDeltaTime(); + //textureCache creation or release + void initTextureCache(); + void destroyTextureCache(); + protected: /** Scheduler associated with this director @since v2.0 @@ -403,6 +410,9 @@ protected: /* The EGLView, where everything is rendered */ EGLView *_openGLView; + //texture cache belongs to this director + TextureCache *_textureCache; + double _animationInterval; double _oldAnimationInterval; diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 8f3fc6fe3a..cf1e8887f9 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -55,15 +55,7 @@ TextureCache* TextureCache::_sharedTextureCache = nullptr; TextureCache * TextureCache::getInstance() { - if (!_sharedTextureCache) - { -#ifdef EMSCRIPTEN - _sharedTextureCache = new TextureCacheEmscripten(); -#else - _sharedTextureCache = new TextureCache(); -#endif // EMSCRIPTEN - } - return _sharedTextureCache; + return Director::getInstance()->getTextureCache(); } TextureCache::TextureCache() @@ -89,15 +81,6 @@ TextureCache::~TextureCache() void TextureCache::destroyInstance() { - if (_sharedTextureCache) - { - // notify sub thread to quick - _sharedTextureCache->_needQuit = true; - _sharedTextureCache->_sleepCondition.notify_one(); - if (_sharedTextureCache->_loadingThread) _sharedTextureCache->_loadingThread->join(); - - CC_SAFE_RELEASE_NULL(_sharedTextureCache); - } } const char* TextureCache::description() const @@ -443,6 +426,14 @@ void TextureCache::reloadAllTextures() #endif } +void TextureCache::waitForQuit() +{ + // notify sub thread to quick + _needQuit = true; + _sleepCondition.notify_one(); + if (_loadingThread) _loadingThread->join(); +} + void TextureCache::dumpCachedTextureInfo() const { unsigned int count = 0; diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index ec87d891d8..1dcc96eb3e 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -158,6 +158,10 @@ public: */ void dumpCachedTextureInfo() const; + //wait for texture cahe to quit befor destroy instance + //called by director, please do not called outside + void waitForQuit(); + private: void addImageAsyncCallBack(float dt); void loadImage(); From c8fe6077aad9811ea19d1154ad94a15636bd49cf Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 19:10:14 +0800 Subject: [PATCH 463/557] issue #3025: Deprecate TextureCache::getInstance() destroyInstance() --- cocos/2d/CCTextureCache.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 1dcc96eb3e..7916696513 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -59,7 +59,7 @@ class CC_DLL TextureCache : public Object { public: /** Returns the shared instance of the cache */ - static TextureCache * getInstance(); + CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance(); /** @deprecated Use getInstance() instead */ CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); } @@ -67,7 +67,7 @@ public: /** purges the cache. It releases the retained instance. @since v0.99.0 */ - static void destroyInstance(); + CC_DEPRECATED_ATTRIBUTE static void destroyInstance(); /** @deprecated Use destroyInstance() instead */ CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } From 99bcca0532df738b3ac1a9e33c45a42a3d9c580b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 19:11:09 +0800 Subject: [PATCH 464/557] issue #3025: replace TextureCache::getInstance() by Director::getInstance()->getTextureCache() in cocos folder --- cocos/2d/CCAnimation.cpp | 3 ++- cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCDirector.cpp | 4 ++-- cocos/2d/CCFontFNT.cpp | 4 ++-- cocos/2d/CCLabelAtlas.cpp | 2 +- cocos/2d/CCLabelBMFont.cpp | 4 ++-- cocos/2d/CCMotionStreak.cpp | 4 ++-- cocos/2d/CCParticleBatchNode.cpp | 2 +- cocos/2d/CCParticleExamples.cpp | 4 ++-- cocos/2d/CCParticleSystem.cpp | 6 +++--- cocos/2d/CCSprite.cpp | 10 +++++----- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCSpriteFrame.cpp | 2 +- cocos/2d/CCSpriteFrameCache.cpp | 5 +++-- cocos/2d/CCTMXLayer.cpp | 2 +- cocos/2d/CCTextureAtlas.cpp | 3 ++- cocos/editor-support/cocosbuilder/CCBReader.cpp | 2 +- cocos/editor-support/cocosbuilder/CCNodeLoader.cpp | 4 ++-- cocos/editor-support/spine/spine-cocos2dx.cpp | 2 +- 19 files changed, 35 insertions(+), 32 deletions(-) diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index 5fa37cd85c..ca1c949882 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "CCTexture2D.h" #include "ccMacros.h" #include "CCSpriteFrame.h" +#include "CCDirector.h" NS_CC_BEGIN @@ -176,7 +177,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame) void Animation::addSpriteFrameWithFile(const char *filename) { - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; rect.size = texture->getContentSize(); SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 6922a8f7ca..7ced2ffc9d 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -76,7 +76,7 @@ AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tile bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender) { CCASSERT(tile.size() > 0, "file size should not be empty"); - Texture2D *texture = TextureCache::getInstance()->addImage(tile); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile); return initWithTexture(texture, tileWidth, tileHeight, itemsToRender); } diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index b55bec2446..5a10d83d1e 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -462,7 +462,7 @@ void Director::purgeCachedData(void) if (s_SharedDirector->getOpenGLView()) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); - TextureCache::getInstance()->removeUnusedTextures(); + _textureCache->removeUnusedTextures(); } FileUtils::getInstance()->purgeCachedEntries(); } @@ -867,7 +867,7 @@ void Director::getFPSImageData(unsigned char** datapointer, long* length) void Director::createStatsLabel() { Texture2D *texture = nullptr; - TextureCache *textureCache = TextureCache::getInstance(); + TextureCache *textureCache = _textureCache; if (_FPSLabel && _SPFLabel) { diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 1992b4f828..25709c714e 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -34,7 +34,7 @@ FontFNT * FontFNT::create(const std::string& fntFilePath) return nullptr; // add the texture - Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName()); + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName()); if (!tempTexture) { delete newConf; @@ -198,7 +198,7 @@ FontAtlas * FontFNT::createFontAtlas() // add the texture (only one texture for now) - Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()); if (!tempTexture) return 0; diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 56a6ff723b..119492b062 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -56,7 +56,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap) { - Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile); return initWithString(string, texture, itemWidth, itemHeight, startCharMap); } diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index e28d4d0afc..6e1a9aefda 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -486,7 +486,7 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string _fntFile = fntFile; - texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + texture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()); } else { @@ -1213,7 +1213,7 @@ void LabelBMFont::setFntFile(const char* fntFile) CC_SAFE_RELEASE(_configuration); _configuration = newConf; - this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName())); + this->setTexture(Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName())); this->createFontChars(); } } diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 47cb43a207..14920662ce 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCGLProgram.h" #include "CCShaderCache.h" #include "ccMacros.h" - +#include "CCDirector.h" #include "CCVertex.h" NS_CC_BEGIN @@ -93,7 +93,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co { CCASSERT(path != NULL, "Invalid filename"); - Texture2D *texture = TextureCache::getInstance()->addImage(path); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path); return initWithFade(fade, minSeg, stroke, color, texture); } diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 788fdd221c..cd473bf097 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -111,7 +111,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity) */ bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity) { - Texture2D *tex = TextureCache::getInstance()->addImage(fileImage); + Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); } diff --git a/cocos/2d/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp index c7e2946172..7120c4b821 100644 --- a/cocos/2d/CCParticleExamples.cpp +++ b/cocos/2d/CCParticleExamples.cpp @@ -42,7 +42,7 @@ static Texture2D* getDefaultTexture() { bool bRet = false; const char* key = "/__firePngData"; - texture = TextureCache::getInstance()->getTextureForKey(key); + texture = Director::getInstance()->getTextureCache()->getTextureForKey(key); CC_BREAK_IF(texture != NULL); pImage = new Image(); @@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture() bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData)); CC_BREAK_IF(!bRet); - texture = TextureCache::getInstance()->addImage(pImage, key); + texture = Director::getInstance()->getTextureCache()->addImage(pImage, key); } while (0); CC_SAFE_RELEASE(pImage); diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 21c473f2f2..cb2c4326f3 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -374,7 +374,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin // set not pop-up message box when load image failed bool bNotify = FileUtils::getInstance()->isPopupNotify(); FileUtils::getInstance()->setPopupNotify(false); - tex = TextureCache::getInstance()->addImage(textureName.c_str()); + tex = Director::getInstance()->getTextureCache()->addImage(textureName.c_str()); // reset the value of UIImage notify FileUtils::getInstance()->setPopupNotify(bNotify); } @@ -400,13 +400,13 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData"); CC_BREAK_IF(!deflated); - // For android, we should retain it in VolatileTexture::addImage which invoked in TextureCache::getInstance()->addUIImage() + // For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage() image = new Image(); bool isOK = image->initWithImageData(deflated, deflatedLen); CCASSERT(isOK, "CCParticleSystem: error init image with Data"); CC_BREAK_IF(!isOK); - setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str())); + setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str())); image->release(); } diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fa6f4878b0..98680b0ea3 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -219,7 +219,7 @@ bool Sprite::initWithFile(const std::string& filename) { CCASSERT(filename.size()>0, "Invalid filename for sprite"); - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { Rect rect = Rect::ZERO; @@ -237,7 +237,7 @@ bool Sprite::initWithFile(const std::string &filename, const Rect& rect) { CCASSERT(filename.size()>0, "Invalid filename"); - Texture2D *texture = TextureCache::getInstance()->addImage(filename); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); if (texture) { return initWithTexture(texture, rect); @@ -284,7 +284,7 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) CCASSERT(pImage != NULL); // XXX: possible bug. See issue #349. New API should be added - Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey); + Texture2D *texture = Director::getInstance()->getTextureCache()->addCGImage(pImage, pszKey); const Size& size = texture->getContentSize(); Rect rect = Rect(0 ,0, size.width, size.height); @@ -1107,7 +1107,7 @@ void Sprite::setTexture(Texture2D *texture) if (NULL == texture) { // Gets the texture by key firstly. - texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); + texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (NULL == texture) @@ -1116,7 +1116,7 @@ void Sprite::setTexture(Texture2D *texture) bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); - texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); + texture = Director::getInstance()->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE(image); } } diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 820a999401..f13a306aa2 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -114,7 +114,7 @@ bool SpriteBatchNode::init() */ bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity) { - Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage); + Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(texture2D, capacity); } diff --git a/cocos/2d/CCSpriteFrame.cpp b/cocos/2d/CCSpriteFrame.cpp index d2fd2c2495..06ca1b80c5 100644 --- a/cocos/2d/CCSpriteFrame.cpp +++ b/cocos/2d/CCSpriteFrame.cpp @@ -180,7 +180,7 @@ Texture2D* SpriteFrame::getTexture(void) } if( _textureFilename.length() > 0 ) { - return TextureCache::getInstance()->addImage(_textureFilename.c_str()); + return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str()); } // no texture or texture filename return NULL; diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index 7ab33b85fe..f5afd18f76 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -37,6 +37,7 @@ THE SOFTWARE. #include "CCString.h" #include "CCArray.h" #include "CCDictionary.h" +#include "CCDirector.h" #include using namespace std; @@ -215,7 +216,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Text void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) { CCASSERT(textureFileName.size()>0, "texture name should not be null"); - Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(textureFileName); if (texture) { @@ -265,7 +266,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist) CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str()); } - Texture2D *texture = TextureCache::getInstance()->addImage(texturePath.c_str()); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str()); if (texture) { diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 4b801ea83e..aa48b8b2b4 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -58,7 +58,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la Texture2D *texture = NULL; if( tilesetInfo ) { - texture = TextureCache::getInstance()->addImage(tilesetInfo->_sourceImage.c_str()); + texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage.c_str()); } if (SpriteBatchNode::initWithTexture(texture, (unsigned int)capacity)) diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 3ef2a365c4..f19a2f5f87 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -32,6 +32,7 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCNotificationCenter.h" #include "CCEventType.h" +#include "CCDirector.h" #include "CCGL.h" // support #include "CCTexture2D.h" @@ -134,7 +135,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity bool TextureAtlas::initWithFile(const char * file, long capacity) { // retained in property - Texture2D *texture = TextureCache::getInstance()->addImage(file); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file); if (texture) { diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 154d2b0b36..5dd2a20624 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -833,7 +833,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) { spriteFile = _CCBRootPath + spriteFile; - Texture2D *texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index e82764ce86..7eba8e9340 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -577,7 +577,7 @@ SpriteFrame * NodeLoader::parsePropTypeSpriteFrame(Node * pNode, Node * pParent, if (spriteSheet.length() == 0) { spriteFile = ccbReader->getCCBRootPath() + spriteFile; - Texture2D * texture = TextureCache::getInstance()->addImage(spriteFile.c_str()); + Texture2D * texture = Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); if(texture != NULL) { Rect bounds = Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height); spriteFrame = SpriteFrame::createWithTexture(texture, bounds); @@ -635,7 +635,7 @@ Texture2D * NodeLoader::parsePropTypeTexture(Node * pNode, Node * pParent, CCBRe if (spriteFile.length() > 0) { - return TextureCache::getInstance()->addImage(spriteFile.c_str()); + return Director::getInstance()->getTextureCache()->addImage(spriteFile.c_str()); } else { diff --git a/cocos/editor-support/spine/spine-cocos2dx.cpp b/cocos/editor-support/spine/spine-cocos2dx.cpp index dbc389db51..298031aaab 100644 --- a/cocos/editor-support/spine/spine-cocos2dx.cpp +++ b/cocos/editor-support/spine/spine-cocos2dx.cpp @@ -31,7 +31,7 @@ USING_NS_CC; namespace spine { void _AtlasPage_createTexture (AtlasPage* self, const char* path) { - Texture2D* texture = TextureCache::getInstance()->addImage(path); + Texture2D* texture = Director::getInstance()->getTextureCache()->addImage(path); TextureAtlas* textureAtlas = TextureAtlas::createWithTexture(texture, 4); textureAtlas->retain(); self->rendererObject = textureAtlas; From cee966e28428dbfab97d3e44a66de4c1e3182100 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 7 Nov 2013 19:24:15 +0800 Subject: [PATCH 465/557] issue #2771: fix build error --- samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index c97b377709..e1c52d2705 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1,4 +1,5 @@ #include "PhysicsTest.h" +#include #include "../testResource.h" USING_NS_CC; @@ -1071,7 +1072,7 @@ void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float if (aDist*bDist < 0.0f) { - float t = abs(aDist)/(abs(aDist) + abs(bDist)); + float t = std::fabs(aDist)/(std::fabs(aDist) + std::fabs(bDist)); points[pointsCount] = a.lerp(b, t); ++pointsCount; } From cbb9c655d962577f5ed586bfed56b7d1d93a7edf Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 21:10:48 +0800 Subject: [PATCH 466/557] fixed bugs --- .../UILoadingBarTest/UILoadingBarTest.cpp | 83 ++++++++++++++----- 1 file changed, 61 insertions(+), 22 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp index 18b150ef6d..f031bc87e8 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp @@ -67,20 +67,29 @@ void UILoadingBarTest_Left::update(float delta) void UILoadingBarTest_Left::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right @@ -142,20 +151,29 @@ void UILoadingBarTest_Right::update(float delta) void UILoadingBarTest_Right::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Left_Scale9 @@ -219,20 +237,29 @@ void UILoadingBarTest_Left_Scale9::update(float delta) void UILoadingBarTest_Left_Scale9::previousCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::restartCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Left_Scale9::nextCallback(Object* sender, TouchEventType type) { - unscheduleUpdate(); - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } // UILoadingBarTest_Right_Scale9 @@ -290,22 +317,34 @@ void UILoadingBarTest_Right_Scale9::update(float delta) { m_nCount = 0; } - + CCLOG("wocao"); UILoadingBar* loadingBar = dynamic_cast(m_pUiLayer->getWidgetByName("LoadingBar")); loadingBar->setPercent(m_nCount); } void UILoadingBarTest_Right_Scale9::previousCallback(Object* sender, TouchEventType type) { - UIScene::previousCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::previousCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::restartCallback(Object* sender, TouchEventType type) { - UIScene::restartCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::restartCallback(sender, type); + } } void UILoadingBarTest_Right_Scale9::nextCallback(Object* sender, TouchEventType type) { - UIScene::nextCallback(sender, type); + if (type == TOUCH_EVENT_ENDED) + { + unscheduleUpdate(); + UIScene::nextCallback(sender, type); + } } \ No newline at end of file From c69163559b2a0f2a829163be2fb580a47e8aca1d Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 7 Nov 2013 21:26:56 +0800 Subject: [PATCH 467/557] Move some method from helper to reader --- .../cocostudio/CCSGUIReader.cpp | 28 ++++++++++++++++--- .../editor-support/cocostudio/CCSGUIReader.h | 4 +++ cocos/gui/UIHelper.cpp | 23 --------------- cocos/gui/UIHelper.h | 4 --- 4 files changed, 28 insertions(+), 31 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index f799c26752..3ad788b563 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -40,12 +40,13 @@ CCSGUIReader::CCSGUIReader(): m_strFilePath(""), m_bOlderVersion(false) { - + _fileDesignSizes = Dictionary::create(); + CC_SAFE_RETAIN(_fileDesignSizes); } CCSGUIReader::~CCSGUIReader() { - + CC_SAFE_RELEASE(_fileDesignSizes); } CCSGUIReader* CCSGUIReader::shareReader() @@ -197,7 +198,26 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) return widget; } +void CCSGUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size) +{ + if (!_fileDesignSizes) + { + _fileDesignSizes = cocos2d::Dictionary::create(); + _fileDesignSizes->retain(); + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + _fileDesignSizes->setObject(strSize, fileName); +} +const cocos2d::Size CCSGUIReader::getFileDesignSize(const char* fileName) const +{ + if (!_fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)_fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) { @@ -240,11 +260,11 @@ UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) { printf("Read design size error!\n"); Size winSize = Director::getInstance()->getWinSize(); - UIHelper::setFileDesignSize(fileName, winSize); + storeFileDesignSize(fileName, winSize); } else { - UIHelper::setFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); + storeFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); } JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); UIWidget* widget = widgetFromJsonDictionary(widgetTree); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h index d39c349ee0..415b7b9e81 100755 --- a/cocos/editor-support/cocostudio/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/CCSGUIReader.h @@ -65,9 +65,13 @@ public: void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); void setPropsForDragPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + void storeFileDesignSize(const char* fileName, const cocos2d::Size &size); + + const cocos2d::Size getFileDesignSize(const char* fileName) const; protected: std::string m_strFilePath; bool m_bOlderVersion; + cocos2d::Dictionary* _fileDesignSizes; }; } diff --git a/cocos/gui/UIHelper.cpp b/cocos/gui/UIHelper.cpp index 8b43c8f890..d896a6372c 100644 --- a/cocos/gui/UIHelper.cpp +++ b/cocos/gui/UIHelper.cpp @@ -25,8 +25,6 @@ #include "CocosGUI.h" namespace gui { - -static cocos2d::Dictionary* fileDesignSizes = NULL; UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag) { @@ -120,26 +118,5 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag) } return NULL; } - -void UIHelper::setFileDesignSize(const char *fileName, const cocos2d::Size &size) -{ - if (!fileDesignSizes) - { - fileDesignSizes = cocos2d::Dictionary::create(); - fileDesignSizes->retain(); - } - cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); - fileDesignSizes->setObject(strSize, fileName); -} - -const cocos2d::Size UIHelper::getFileDesignSize(const char* fileName) -{ - if (!fileDesignSizes) - { - return cocos2d::Size::ZERO; - } - cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)fileDesignSizes->objectForKey(fileName))->_string.c_str()); - return designSize; -} } \ No newline at end of file diff --git a/cocos/gui/UIHelper.h b/cocos/gui/UIHelper.h index 68893ceff0..838875adf4 100644 --- a/cocos/gui/UIHelper.h +++ b/cocos/gui/UIHelper.h @@ -71,10 +71,6 @@ public: /*temp action*/ static UIWidget* seekActionWidgetByActionTag(UIWidget* root, int tag); - - static void setFileDesignSize(const char* fileName, const cocos2d::Size &size); - - static const cocos2d::Size getFileDesignSize(const char* fileName); }; } From bd7d62aee04cb4dcebb04398a9bec4ba8abddfdf Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 7 Nov 2013 21:48:39 +0800 Subject: [PATCH 468/557] issue #3025: replace TextureCache::getInstance() by Director::getInstance()->getTextureCache() in samples folder --- .../TestCpp/Classes/Box2DTest/Box2dTest.cpp | 2 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 2 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 2 +- .../DataVisitorTest/DataVisitorTest.cpp | 2 +- .../Classes/IntervalTest/IntervalTest.cpp | 2 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 4 +- .../Classes/ParticleTest/ParticleTest.cpp | 46 +++--- .../PerformanceParticleTest.cpp | 20 +-- .../PerformanceTest/PerformanceSpriteTest.cpp | 2 +- .../PerformanceTextureTest.cpp | 4 +- .../RenderTextureTest/RenderTextureTest.cpp | 4 +- .../Classes/SchedulerTest/SchedulerTest.cpp | 2 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 146 +++++++++--------- .../TextureCacheTest/TextureCacheTest.cpp | 40 ++--- .../Classes/TouchesTest/TouchesTest.cpp | 4 +- 16 files changed, 142 insertions(+), 142 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index ca75a9efe3..ba9d1982fe 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -29,7 +29,7 @@ Box2DTestLayer::Box2DTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/blocks.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/blocks.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 50d5dc7252..aad89f259d 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -46,7 +46,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() _spriteTexture = parent->getTexture(); #else // doesn't use batch node. Slower - _spriteTexture = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + _spriteTexture = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); auto parent = Node::create(); #endif addChild(parent, 0, kTagParentNode); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 93e26514a2..f69ba49240 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -107,7 +107,7 @@ bool BaseClippingNodeTest::init() BaseClippingNodeTest::~BaseClippingNodeTest() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } std::string BaseClippingNodeTest::title() diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp index 4f8a1fb932..aeed903837 100644 --- a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -71,7 +71,7 @@ void PrettyPrinterDemo::onEnter() vistor.clear(); addSprite(); -// dict = TextureCache::getInstance()->snapshotTextures(); +// dict = Director::getInstance()->getTextureCache()->snapshotTextures(); // dict->acceptVisitor(vistor); // log("%s", vistor.getResult().c_str()); } diff --git a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp index da9fefdca9..3771b1e2aa 100644 --- a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp +++ b/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp @@ -16,7 +16,7 @@ IntervalLayer::IntervalLayer() auto s = Director::getInstance()->getWinSize(); // sun auto sun = ParticleSun::create(); - sun->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + sun->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); sun->setPosition( Point(VisibleRect::rightTop().x-32,VisibleRect::rightTop().y-32) ); sun->setTotalParticles(130); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 82a8a6ebcb..1b2655680f 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -359,7 +359,7 @@ void StressTest1::shouldNotCrash(float dt) // if the node has timers, it crashes auto explosion = ParticleSun::create(); - explosion->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + explosion->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // if it doesn't, it works Ok. // auto explosion = [Sprite create:@"grossinis_sister2.png"); @@ -409,7 +409,7 @@ StressTest2::StressTest2() sublayer->addChild(sp1, 1); auto fire = ParticleFire::create(); - fire->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + fire->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); fire->setPosition( Point(80, s.height/2-50) ); auto copy_seq3 = seq3->clone(); diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index d238482244..c4e3b15bad 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -22,7 +22,7 @@ void DemoFirework::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -46,7 +46,7 @@ void DemoFire::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) );//.pvr"); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) );//.pvr"); auto p = _emitter->getPosition(); _emitter->setPosition( Point(p.x, 100) ); @@ -71,7 +71,7 @@ void DemoSun::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -94,7 +94,7 @@ void DemoGalaxy::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -116,7 +116,7 @@ void DemoFlower::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); setEmitterPosition(); } @@ -141,7 +141,7 @@ void DemoBigFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : use this line or remove this line and use autorelease() - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setDuration(-1); @@ -225,7 +225,7 @@ void DemoRotFlower::onEnter() _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : Remove this line - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars2) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars2) ); // duration _emitter->setDuration(-1); @@ -308,7 +308,7 @@ void DemoMeteor::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -331,7 +331,7 @@ void DemoSpiral::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -354,7 +354,7 @@ void DemoExplosion::onEnter() _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setAutoRemoveOnFinish(true); @@ -378,7 +378,7 @@ void DemoSmoke::onEnter() _emitter = ParticleSmoke::create(); _emitter->retain(); _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto p = _emitter->getPosition(); _emitter->setPosition( Point( p.x, 100) ); @@ -429,7 +429,7 @@ void DemoSnow::onEnter() _emitter->setEmissionRate(_emitter->getTotalParticles()/_emitter->getLife()); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_snow) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_snow) ); setEmitterPosition(); } @@ -456,7 +456,7 @@ void DemoRain::onEnter() _emitter->setPosition( Point( p.x, p.y-100) ); _emitter->setLife(4); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); setEmitterPosition(); } @@ -540,7 +540,7 @@ void DemoModernArt::onEnter() _emitter->setEndSizeVar(8.0f); // texture - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); // additive _emitter->setBlendAdditive(false); @@ -567,7 +567,7 @@ void DemoRing::onEnter() _background->addChild(_emitter, 10); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); _emitter->setLifeVar(0); _emitter->setLife(10); _emitter->setSpeed(100); @@ -605,14 +605,14 @@ void ParallaxParticle::onEnter() _emitter = ParticleFlower::create(); _emitter->retain(); - _emitter->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + _emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); p1->addChild(_emitter, 10); _emitter->setPosition( Point(250,200) ); auto par = ParticleSun::create(); p2->addChild(par, 10); - par->setTexture( TextureCache::getInstance()->addImage(s_fire) ); + par->setTexture( Director::getInstance()->getTextureCache()->addImage(s_fire) ); auto move = MoveBy::create(4, Point(300,0)); auto move_back = move->reverse(); @@ -641,7 +641,7 @@ void RadiusMode1::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -725,7 +725,7 @@ void RadiusMode2::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(200); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/stars-grayscale.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -809,7 +809,7 @@ void Issue704::onEnter() _emitter = new ParticleSystemQuad(); _emitter->initWithTotalParticles(100); addChild(_emitter, 10); - _emitter->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // duration _emitter->setDuration(ParticleSystem::DURATION_INFINITY); @@ -900,7 +900,7 @@ void Issue870::onEnter() auto system = new ParticleSystemQuad(); system->initWithFile("Particles/SpinningPeas.plist"); - system->setTextureWithRect(TextureCache::getInstance()->addImage("Images/particles.png"), Rect(0,0,32,32)); + system->setTextureWithRect(Director::getInstance()->getTextureCache()->addImage("Images/particles.png"), Rect(0,0,32,32)); addChild(system, 10); _emitter = system; @@ -1452,7 +1452,7 @@ bool RainbowEffect::initWithTotalParticles(unsigned int numberOfParticles) _endColorVar.b = 0.0f; _endColorVar.a = 0.0f; - setTexture(TextureCache::getInstance()->addImage("Images/particles.png")); + setTexture(Director::getInstance()->getTextureCache()->addImage("Images/particles.png")); return true; } @@ -1504,7 +1504,7 @@ void MultipleParticleSystems::onEnter() removeChild(_background, true); _background = NULL; - TextureCache::getInstance()->addImage("Images/particles.png"); + Director::getInstance()->getTextureCache()->addImage("Images/particles.png"); for (int i = 0; i<5; i++) { auto particleSystem = ParticleSystemQuad::create("Particles/SpinningPeas.plist"); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp index b72ad00da5..b6878a5b22 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp @@ -187,8 +187,8 @@ void ParticleMainScene::createParticleSystem() removeChildByTag(kTagParticleSystem, true); // remove the "fire.png" from the TextureCache cache. - auto texture = TextureCache::getInstance()->addImage("Images/fire.png"); - TextureCache::getInstance()->removeTexture(texture); + auto texture = Director::getInstance()->getTextureCache()->addImage("Images/fire.png"); + Director::getInstance()->getTextureCache()->removeTexture(texture); //TODO: if (subtestNumber <= 3) // { @@ -204,42 +204,42 @@ void ParticleMainScene::createParticleSystem() case 1: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 3: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 4: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 5: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; case 6: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); particleSystem->initWithTotalParticles(quantityParticles); - particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); + particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); break; // case 8: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[TextureCache sharedTextureCache] addImage:@"fire.pvr"]; -// particleSystem->setTexture(TextureCache::getInstance()->addImage("Images/fire.png")); +// particleSystem->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); // break; default: particleSystem = NULL; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 7e290e5e5b..ccf4ca602d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -52,7 +52,7 @@ void SubTest::initWithSubTest(int nSubTest, Node* p) */ // purge textures - auto mgr = TextureCache::getInstance(); + auto mgr = Director::getInstance()->getTextureCache(); // [mgr removeAllTextures]; mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png")); mgr->removeTexture(mgr->addImage("Images/grossini_dance_atlas.png")); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp index bcbae20aa1..0da9efd0ec 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp @@ -84,7 +84,7 @@ void TextureTest::performTestsPNG(const char* filename) { struct timeval now; Texture2D *texture; - auto cache = TextureCache::getInstance(); + auto cache = Director::getInstance()->getTextureCache(); log("RGBA 8888"); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); @@ -131,7 +131,7 @@ void TextureTest::performTests() { // Texture2D *texture; // struct timeval now; -// auto cache = TextureCache::getInstance(); +// auto cache = Director::getInstance()->getTextureCache(); log("--------"); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index baf174ac9b..987d8b8f05 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -156,7 +156,7 @@ void RenderTextureSave::saveImage(cocos2d::Object *sender) auto image = _target->newImage(); - auto tex = TextureCache::getInstance()->addImage(image, png); + auto tex = Director::getInstance()->getTextureCache()->addImage(image, png); CC_SAFE_DELETE(image); @@ -176,7 +176,7 @@ RenderTextureSave::~RenderTextureSave() { _brush->release(); _target->release(); - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } void RenderTextureSave::onTouchesMoved(const std::vector& touches, Event* event) diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 96ee66292b..d225e1c8f8 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -924,7 +924,7 @@ void SchedulerTimeScale::onEnter() kathia->runAction(Speed::create(action3, 1.0f)); auto emitter = ParticleFireworks::create(); - emitter->setTexture( TextureCache::getInstance()->addImage(s_stars1) ); + emitter->setTexture( Director::getInstance()->getTextureCache()->addImage(s_stars1) ); addChild(emitter); _sliderCtl = sliderCtl(); diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 499b1b8dfe..09b2f61d9d 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file +ddd085a82dc104bac66268a7ddcdf9b0c32cb4ee \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 8184bc1467..6245237ca8 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -129,18 +129,18 @@ void TextureDemo::onEnter() { BaseTest::onEnter(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); auto col = LayerColor::create(Color4B(128,128,128,255)); addChild(col, -10); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } TextureDemo::~TextureDemo() { - TextureCache::getInstance()->removeUnusedTextures(); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } void TextureDemo::restartCallback(Object* sender) @@ -191,7 +191,7 @@ void TextureTIFF::onEnter() auto img = Sprite::create("Images/test_image.tiff"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); this->addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureTIFF::title() @@ -213,7 +213,7 @@ void TexturePNG::onEnter() auto img = Sprite::create("Images/test_image.png"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePNG::title() @@ -234,7 +234,7 @@ void TextureJPEG::onEnter() auto img = Sprite::create("Images/test_image.jpeg"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureJPEG::title() @@ -255,7 +255,7 @@ void TextureWEBP::onEnter() auto img = Sprite::create("Images/test_image.webp"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureWEBP::title() @@ -273,12 +273,12 @@ void TextureMipMap::onEnter() TextureDemo::onEnter(); auto s = Director::getInstance()->getWinSize(); - auto texture0 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas.png"); + auto texture0 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas.png"); texture0->generateMipmap(); Texture2D::TexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; texture0->setTexParameters(texParams); - auto texture1 = TextureCache::getInstance()->addImage("Images/grossini_dance_atlas_nomipmap.png"); + auto texture1 = Director::getInstance()->getTextureCache()->addImage("Images/grossini_dance_atlas_nomipmap.png"); auto img0 = Sprite::createWithTexture(texture0); img0->setTextureRect(Rect(85, 121, 85, 121)); @@ -299,7 +299,7 @@ void TextureMipMap::onEnter() img0->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img1->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureMipMap::title() @@ -350,7 +350,7 @@ void TexturePVRMipMap::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap::title() @@ -392,7 +392,7 @@ void TexturePVRMipMap2::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRMipMap2::title() @@ -424,7 +424,7 @@ void TexturePVR2BPP::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR2BPP::title() @@ -455,7 +455,7 @@ void TexturePVRTest::onEnter() { log("This test is not supported."); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -487,7 +487,7 @@ void TexturePVR4BPP::onEnter() { log("This test is not supported in cocos2d-mac"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVR4BPP::title() @@ -510,7 +510,7 @@ void TexturePVRRGBA8888::onEnter() auto img = Sprite::create("Images/test_image_rgba8888.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA8888::title() @@ -540,7 +540,7 @@ void TexturePVRBGRA8888::onEnter() { log("BGRA8888 images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRBGRA8888::title() @@ -563,7 +563,7 @@ void TexturePVRRGBA5551::onEnter() auto img = Sprite::create("Images/test_image_rgba5551.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA5551::title() @@ -586,7 +586,7 @@ void TexturePVRRGBA4444::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444::title() @@ -614,7 +614,7 @@ void TexturePVRRGBA4444GZ::onEnter() #endif img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444GZ::title() @@ -642,7 +642,7 @@ void TexturePVRRGBA4444CCZ::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr.ccz"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGBA4444CCZ::title() @@ -670,7 +670,7 @@ void TexturePVRRGB565::onEnter() auto img = Sprite::create("Images/test_image_rgb565.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB565::title() @@ -693,7 +693,7 @@ void TexturePVRRGB888::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRRGB888::title() @@ -716,7 +716,7 @@ void TexturePVRA8::onEnter() auto img = Sprite::create("Images/test_image_a8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } @@ -740,7 +740,7 @@ void TexturePVRI8::onEnter() auto img = Sprite::create("Images/test_image_i8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRI8::title() @@ -763,7 +763,7 @@ void TexturePVRAI88::onEnter() auto img = Sprite::create("Images/test_image_ai88.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRAI88::title() @@ -785,7 +785,7 @@ void TexturePVR2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR2BPPv3::title() @@ -812,7 +812,7 @@ void TexturePVRII2BPPv3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII2BPPv3::title() @@ -843,7 +843,7 @@ void TexturePVR4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVR4BPPv3::title() @@ -878,7 +878,7 @@ void TexturePVRII4BPPv3::onEnter() log("This test is not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRII4BPPv3::title() @@ -905,7 +905,7 @@ void TexturePVRRGBA8888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA8888v3::title() @@ -936,7 +936,7 @@ void TexturePVRBGRA8888v3::onEnter() log("BGRA images are not supported"); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRBGRA8888v3::title() @@ -963,7 +963,7 @@ void TexturePVRRGBA5551v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA5551v3::title() @@ -990,7 +990,7 @@ void TexturePVRRGBA4444v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGBA4444v3::title() @@ -1017,7 +1017,7 @@ void TexturePVRRGB565v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB565v3::title() @@ -1044,7 +1044,7 @@ void TexturePVRRGB888v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRRGB888v3::title() @@ -1071,7 +1071,7 @@ void TexturePVRA8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRA8v3::title() @@ -1098,7 +1098,7 @@ void TexturePVRI8v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRI8v3::title() @@ -1125,7 +1125,7 @@ void TexturePVRAI88v3::onEnter() addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } string TexturePVRAI88v3::title() @@ -1181,7 +1181,7 @@ void TexturePVRNonSquare::onEnter() auto img = Sprite::create("Images/grossini_128x256_mipmap.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNonSquare::title() @@ -1210,7 +1210,7 @@ void TexturePVRNPOT4444::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT4444::title() @@ -1239,7 +1239,7 @@ void TexturePVRNPOT8888::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePVRNPOT8888::title() @@ -1293,7 +1293,7 @@ void TextureAlias::onEnter() sprite2->runAction(scaleforever); sprite->runAction(scaleToo); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureAlias::title() @@ -1334,7 +1334,7 @@ void TexturePixelFormat::onEnter() addChild(sprite1, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite1->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite1->getTexture()); // RGBA 4444 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); @@ -1343,7 +1343,7 @@ void TexturePixelFormat::onEnter() addChild(sprite2, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite2->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite2->getTexture()); // RGB5A1 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1); @@ -1352,7 +1352,7 @@ void TexturePixelFormat::onEnter() addChild(sprite3, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite3->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite3->getTexture()); // RGB888 image Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB888); @@ -1361,7 +1361,7 @@ void TexturePixelFormat::onEnter() addChild(sprite4, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite4->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite4->getTexture()); // RGB565 image (16-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB565); @@ -1370,7 +1370,7 @@ void TexturePixelFormat::onEnter() addChild(sprite5, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite5->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite5->getTexture()); // A8 image (8-bit) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::A8); @@ -1379,7 +1379,7 @@ void TexturePixelFormat::onEnter() addChild(sprite6, 0); // remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite6->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite6->getTexture()); auto fadeout = FadeOut::create(2); auto fadein = FadeIn::create(2); @@ -1398,7 +1398,7 @@ void TexturePixelFormat::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TexturePixelFormat::title() @@ -1486,7 +1486,7 @@ void TextureAsync::onEnter() TextureAsync::~TextureAsync() { - TextureCache::getInstance()->removeAllTextures(); + Director::getInstance()->getTextureCache()->removeAllTextures(); } void TextureAsync::loadImages(float dt) @@ -1495,15 +1495,15 @@ void TextureAsync::loadImages(float dt) for( int j=0;j < 8; j++) { char szSpriteName[100] = {0}; sprintf(szSpriteName, "Images/sprites_test/sprite-%d-%d.png", i, j); - TextureCache::getInstance()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync(szSpriteName,this, callfuncO_selector(TextureAsync::imageLoaded)); } } - TextureCache::getInstance()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.jpg",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/atlastest.png",this, callfuncO_selector(TextureAsync::imageLoaded)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_atlas.png",this, callfuncO_selector(TextureAsync::imageLoaded)); } @@ -1576,7 +1576,7 @@ std::string TextureGlClamp::title() TextureGlClamp::~TextureGlClamp() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1613,7 +1613,7 @@ std::string TextureGlRepeat::title() TextureGlRepeat::~TextureGlRepeat() { - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); } //------------------------------------------------------------------ @@ -1684,7 +1684,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); sprite = Sprite::create("Images/grossinis_sister1.png"); sprite->setPosition(Point(s.width/5*2, s.height/2)); @@ -1700,7 +1700,7 @@ void TextureCache1::onEnter() sprite->setScale(2); addChild(sprite); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister2.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister2.png"); sprite = Sprite::create("Images/grossinis_sister2.png"); sprite->setPosition(Point(s.width/5*4, s.height/2)); @@ -1724,8 +1724,8 @@ void TextureDrawAtPoint::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1763,8 +1763,8 @@ void TextureDrawAtPoint::draw() void TextureDrawInRect::onEnter() { TextureDemo::onEnter(); - _tex1 = TextureCache::getInstance()->addImage("Images/grossinis_sister1.png"); - _Tex2F = TextureCache::getInstance()->addImage("Images/grossinis_sister2.png"); + _tex1 = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister1.png"); + _Tex2F = Director::getInstance()->getTextureCache()->addImage("Images/grossinis_sister2.png"); _tex1->retain(); _Tex2F->retain(); @@ -1871,7 +1871,7 @@ void TextureMemoryAlloc::updateImage(cocos2d::Object *sender) _background->removeFromParentAndCleanup(true); } - TextureCache::getInstance()->removeUnusedTextures(); + Director::getInstance()->getTextureCache()->removeUnusedTextures(); int tag = ((Node*)sender)->getTag(); string file; @@ -1952,7 +1952,7 @@ TexturePVRv3Premult::TexturePVRv3Premult() // PNG Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - TextureCache::getInstance()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); + Director::getInstance()->getTextureCache()->removeTextureForKey("Images/grossinis_sister1-testalpha.png"); auto png = Sprite::create("Images/grossinis_sister1-testalpha.png"); addChild(png, 0); png->setPosition(Point(size.width/4*3, size.height/2)); @@ -2132,7 +2132,7 @@ static void addImageToDemo(TextureDemo& demo, float x, float y, const char* path demo.addChild(sprite, 0); //remove texture from texture manager - TextureCache::getInstance()->removeTexture(sprite->getTexture()); + Director::getInstance()->getTextureCache()->removeTexture(sprite->getTexture()); } //TextureConvertRGB888 @@ -2157,7 +2157,7 @@ void TextureConvertRGB888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGB888::title() @@ -2191,7 +2191,7 @@ void TextureConvertRGBA8888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertRGBA8888::title() @@ -2225,7 +2225,7 @@ void TextureConvertI8::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertI8::title() @@ -2259,7 +2259,7 @@ void TextureConvertAI88::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - TextureCache::getInstance()->dumpCachedTextureInfo(); + Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); } std::string TextureConvertAI88::title() diff --git a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp index 32d9660ce4..698a2935fd 100644 --- a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp @@ -21,26 +21,26 @@ TextureCacheTest::TextureCacheTest() this->addChild(_labelPercent); // load textrues - TextureCache::getInstance()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); - TextureCache::getInstance()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/HelloWorld.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_01.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_02.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_03.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_04.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_05.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_06.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_07.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_08.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_09.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_10.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_11.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_12.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_13.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/grossini_dance_14.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background1.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background2.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/background3.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); + Director::getInstance()->getTextureCache()->addImageAsync("Images/blocks.png", this, callfuncO_selector(TextureCacheTest::loadingCallBack)); } void TextureCacheTest::loadingCallBack(Object *obj) diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp index 6c57cac1b5..ef695368ff 100644 --- a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp @@ -39,13 +39,13 @@ PongLayer::PongLayer() { _ballStartingVelocity = Point(20.0f, -100.0f); - _ball = Ball::ballWithTexture( TextureCache::getInstance()->addImage(s_Ball) ); + _ball = Ball::ballWithTexture( Director::getInstance()->getTextureCache()->addImage(s_Ball) ); _ball->setPosition( VisibleRect::center() ); _ball->setVelocity( _ballStartingVelocity ); addChild( _ball ); _ball->retain(); - auto paddleTexture = TextureCache::getInstance()->addImage(s_Paddle); + auto paddleTexture = Director::getInstance()->getTextureCache()->addImage(s_Paddle); auto paddlesM = Array::createWithCapacity(4); From 916361af3f6cb0264201ad10834bd1c9d025710b Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 7 Nov 2013 23:40:33 +0800 Subject: [PATCH 469/557] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. --- cocos/base/CCGeometry.cpp | 9 +++++++++ cocos/base/CCGeometry.h | 19 +++++++++++++++++++ .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 1d5c4896c6..b6b59f5b03 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -284,6 +284,15 @@ Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, c } const Point Point::ZERO = Point(0, 0); +const Point Point::ANCHOR_MIDDLE = Point(0.5, 0.5); +const Point Point::ANCHOR_BOTTOM_LEFT = Point(0, 0); +const Point Point::ANCHOR_TOP_LEFT = Point(0, 1); +const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1, 0); +const Point Point::ANCHOR_TOP_RIGHT = Point(1, 1); +const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1, .5); +const Point Point::ANCHOR_MIDDLE_LEFT = Point(0, 0.5); +const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5, 1); +const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5, 0); // implementation of Size diff --git a/cocos/base/CCGeometry.h b/cocos/base/CCGeometry.h index 847557cb35..0b3e30d208 100644 --- a/cocos/base/CCGeometry.h +++ b/cocos/base/CCGeometry.h @@ -423,7 +423,26 @@ public: */ static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); + /** equals to Point(0,0) */ static const Point ZERO; + /** equals to Point(0.5, 0.5) */ + static const Point ANCHOR_MIDDLE; + /** equals to Point(0, 0) */ + static const Point ANCHOR_BOTTOM_LEFT; + /** equals to Point(0, 1) */ + static const Point ANCHOR_TOP_LEFT; + /** equals to Point(1, 0) */ + static const Point ANCHOR_BOTTOM_RIGHT; + /** equals to Point(1, 1) */ + static const Point ANCHOR_TOP_RIGHT; + /** equals to Point(1, 0.5) */ + static const Point ANCHOR_MIDDLE_RIGHT; + /** equals to Point(0, 0.5) */ + static const Point ANCHOR_MIDDLE_LEFT; + /** equals to Point(0.5, 1) */ + static const Point ANCHOR_MIDDLE_TOP; + /** equals to Point(0.5, 0) */ + static const Point ANCHOR_MIDDLE_BOTTOM; private: // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 499b1b8dfe..c01845edff 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -71aa9486e8535b9bd65cae247bb86de59c83f522 \ No newline at end of file +dd564ef17f9cc0281964247923ec24957cad7bd0 \ No newline at end of file From 006d32f883ff2d220823d56c342b5b057b2b319c Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 7 Nov 2013 23:51:01 +0800 Subject: [PATCH 470/557] rename jsb boot file. --- template/multi-platform-js/Classes/AppDelegate.cpp | 2 +- .../multi-platform-js/Resources/{main.js => cocos2d-jsb.js} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename template/multi-platform-js/Resources/{main.js => cocos2d-jsb.js} (100%) diff --git a/template/multi-platform-js/Classes/AppDelegate.cpp b/template/multi-platform-js/Classes/AppDelegate.cpp index 4c2fea3abf..e409b974b5 100644 --- a/template/multi-platform-js/Classes/AppDelegate.cpp +++ b/template/multi-platform-js/Classes/AppDelegate.cpp @@ -47,7 +47,7 @@ bool AppDelegate::applicationDidFinishLaunching() ScriptEngineProtocol *engine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); - ScriptingCore::getInstance()->runScript("main.js"); + ScriptingCore::getInstance()->runScript("cocos2d-jsb.js"); return true; } diff --git a/template/multi-platform-js/Resources/main.js b/template/multi-platform-js/Resources/cocos2d-jsb.js similarity index 100% rename from template/multi-platform-js/Resources/main.js rename to template/multi-platform-js/Resources/cocos2d-jsb.js From e4662b371ae04de9394b4df75d81f99c62e23642 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 11:58:48 -0800 Subject: [PATCH 471/557] TextField uses std::string& in the public API and uses std::string instead of std::string* internally --- cocos/2d/CCTextFieldTTF.cpp | 118 ++++++++++++++++-------------------- cocos/2d/CCTextFieldTTF.h | 28 ++++----- cocos/gui/UITextField.cpp | 4 +- 3 files changed, 68 insertions(+), 82 deletions(-) diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 934b88a091..01179ba523 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -53,8 +53,8 @@ static int _calcCharCount(const char * pszText) TextFieldTTF::TextFieldTTF() : _delegate(0) , _charCount(0) -, _inputText(new std::string) -, _placeHolder(new std::string) // prevent LabelTTF initWithString assertion +, _inputText("") +, _placeHolder("") // prevent LabelTTF initWithString assertion , _secureTextEntry(false) { _colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127; @@ -62,43 +62,41 @@ TextFieldTTF::TextFieldTTF() TextFieldTTF::~TextFieldTTF() { - CC_SAFE_DELETE(_inputText); - CC_SAFE_DELETE(_placeHolder); } ////////////////////////////////////////////////////////////////////////// // static constructor ////////////////////////////////////////////////////////////////////////// -TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) +TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize) { - TextFieldTTF *pRet = new TextFieldTTF(); - if(pRet && pRet->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } -TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) +TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { - TextFieldTTF *pRet = new TextFieldTTF(); - if(pRet && pRet->initWithString("", fontName, fontSize)) + TextFieldTTF *ret = new TextFieldTTF(); + if(ret && ret->initWithString("", fontName, fontSize)) { - pRet->autorelease(); - if (placeholder) + ret->autorelease(); + if (placeholder.size()>0) { - pRet->setPlaceHolder(placeholder); + ret->setPlaceHolder(placeholder); } - return pRet; + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return NULL; } @@ -106,23 +104,15 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, c // initialize ////////////////////////////////////////////////////////////////////////// -bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize) { - if (placeholder) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize, dimensions, alignment); + _placeHolder = placeholder; + return LabelTTF::initWithString(_placeHolder, fontName, fontSize, dimensions, alignment); } -bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize) +bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { - if (placeholder) - { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = new std::string(placeholder); - } - return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize); + _placeHolder = std::string(placeholder); + return LabelTTF::initWithString(_placeHolder, fontName, fontSize); } ////////////////////////////////////////////////////////////////////////// @@ -190,9 +180,9 @@ void TextFieldTTF::insertText(const char * text, int len) } _charCount += _calcCharCount(sInsert.c_str()); - std::string sText(*_inputText); + std::string sText(_inputText); sText.append(sInsert); - setString(sText.c_str()); + setString(sText); } if ((int)sInsert.npos == nPos) { @@ -211,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len) void TextFieldTTF::deleteBackward() { - int nStrLen = _inputText->length(); + int nStrLen = _inputText.length(); if (! nStrLen) { // there is no string @@ -221,12 +211,12 @@ void TextFieldTTF::deleteBackward() // get the delete byte number int nDeleteLen = 1; // default, erase 1 byte - while(0x80 == (0xC0 & _inputText->at(nStrLen - nDeleteLen))) + while(0x80 == (0xC0 & _inputText.at(nStrLen - nDeleteLen))) { ++nDeleteLen; } - if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText->c_str() + nStrLen - nDeleteLen, nDeleteLen)) + if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText.c_str() + nStrLen - nDeleteLen, nDeleteLen)) { // delegate doesn't wan't to delete backwards return; @@ -235,21 +225,20 @@ void TextFieldTTF::deleteBackward() // if all text deleted, show placeholder string if (nStrLen <= nDeleteLen) { - CC_SAFE_DELETE(_inputText); - _inputText = new std::string; + _inputText = ""; _charCount = 0; - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); return; } // set new input text - std::string sText(_inputText->c_str(), nStrLen - nDeleteLen); - setString(sText.c_str()); + std::string sText(_inputText.c_str(), nStrLen - nDeleteLen); + setString(sText); } const char * TextFieldTTF::getContentText() { - return _inputText->c_str(); + return _inputText.c_str(); } void TextFieldTTF::draw() @@ -258,7 +247,7 @@ void TextFieldTTF::draw() { return; } - if (_inputText->length()) + if (_inputText.length()) { LabelTTF::draw(); return; @@ -286,22 +275,20 @@ void TextFieldTTF::setColorSpaceHolder(const Color3B& color) ////////////////////////////////////////////////////////////////////////// // input text property -void TextFieldTTF::setString(const char *text) +void TextFieldTTF::setString(const std::string &text) { static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00}; std::string displayText; int length; - CC_SAFE_DELETE(_inputText); - - if (text) + if (text.length()>0) { - _inputText = new std::string(text); - displayText = *_inputText; + _inputText = text; + displayText = _inputText; if (_secureTextEntry) { displayText = ""; - length = _inputText->length(); + length = _inputText.length(); while (length) { displayText.append(bulletString); @@ -311,40 +298,39 @@ void TextFieldTTF::setString(const char *text) } else { - _inputText = new std::string; + _inputText = ""; } // if there is no input text, display placeholder instead - if (! _inputText->length()) + if (! _inputText.length()) { - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); } else { - LabelTTF::setString(displayText.c_str()); + LabelTTF::setString(displayText); } - _charCount = _calcCharCount(_inputText->c_str()); + _charCount = _calcCharCount(_inputText.c_str()); } const char* TextFieldTTF::getString(void) const { - return _inputText->c_str(); + return _inputText.c_str(); } // place holder text property -void TextFieldTTF::setPlaceHolder(const char * text) +void TextFieldTTF::setPlaceHolder(const std::string& text) { - CC_SAFE_DELETE(_placeHolder); - _placeHolder = (text) ? new std::string(text) : new std::string; - if (! _inputText->length()) + _placeHolder = text; + if (! _inputText.length()) { - LabelTTF::setString(_placeHolder->c_str()); + LabelTTF::setString(_placeHolder); } } -const char * TextFieldTTF::getPlaceHolder(void) +const std::string& TextFieldTTF::getPlaceHolder() const { - return _placeHolder->c_str(); + return _placeHolder; } // secureTextEntry diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 79feb55d7c..28c74a7a9c 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -109,13 +109,13 @@ public: //char * description(); /** creates a TextFieldTTF from a fontname, alignment, dimension and font size */ - static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); + static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); /** creates a LabelTTF from a fontname and font size */ - static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** initializes the TextFieldTTF with a font name, alignment, dimension and font size */ - bool initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize); + bool initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); /** initializes the TextFieldTTF with a font name and font size */ - bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** @brief Open keyboard and receive input text. @@ -147,21 +147,21 @@ public: // input text property public: - virtual void setString(const char *text); + virtual void setString(const std::string& text) override; virtual const char* getString(void) const; protected: TextFieldDelegate * _delegate; int _charCount; - std::string * _inputText; + std::string _inputText; // place holder text property // place holder text displayed when there is no text in the text field. public: - virtual void setPlaceHolder(const char * text); - virtual const char * getPlaceHolder(void); + virtual void setPlaceHolder(const std::string& text); + virtual const std::string& getPlaceHolder(void) const; protected: - std::string * _placeHolder; + std::string _placeHolder; Color3B _colorSpaceHolder; public: virtual void setSecureTextEntry(bool value); @@ -176,11 +176,11 @@ protected: // IMEDelegate interface ////////////////////////////////////////////////////////////////////////// - virtual bool canAttachWithIME(); - virtual bool canDetachWithIME(); - virtual void insertText(const char * text, int len); - virtual void deleteBackward(); - virtual const char * getContentText(); + virtual bool canAttachWithIME() override; + virtual bool canDetachWithIME() override; + virtual void insertText(const char * text, int len) override; + virtual void deleteBackward() override; + virtual const char * getContentText() override; private: class LengthStack; LengthStack * _lens; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 7eb30518cd..da79a1590b 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -139,7 +139,7 @@ void UICCTextField::insertText(const char * text, int len) { if (cocos2d::TextFieldTTF::getCharCount() > 0) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } @@ -153,7 +153,7 @@ void UICCTextField::deleteBackward() // password if (_passwordEnabled) { - setPasswordText(_inputText->c_str()); + setPasswordText(_inputText.c_str()); } } } From ffd434254800645a6d0fe44f0bffa7da90940cb4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 12:42:16 -0800 Subject: [PATCH 472/557] Adds more strings and more `override` and fixes some indetentation issues --- cocos/2d/CCLabel.h | 46 +++++++++++----------- cocos/2d/CCLabelAtlas.cpp | 4 +- cocos/2d/CCLabelAtlas.h | 7 ++-- cocos/2d/CCLabelBMFont.cpp | 4 +- cocos/2d/CCLabelBMFont.h | 4 +- cocos/2d/CCLabelTTF.cpp | 4 +- cocos/2d/CCLabelTTF.h | 4 +- cocos/2d/CCProtocols.h | 2 +- cocos/2d/CCTextFieldTTF.cpp | 4 +- cocos/2d/CCTextFieldTTF.h | 2 +- cocos/gui/UIButton.cpp | 4 +- cocos/gui/UIButton.h | 4 +- cocos/gui/UILabel.cpp | 17 ++++---- cocos/gui/UILabel.h | 6 +-- cocos/gui/UILabelAtlas.cpp | 12 +++--- cocos/gui/UILabelAtlas.h | 10 ++--- cocos/gui/UITextField.cpp | 18 ++++----- cocos/gui/UITextField.h | 8 ++-- samples/Cpp/TestCpp/Classes/controller.cpp | 7 +++- 19 files changed, 84 insertions(+), 83 deletions(-) diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index a4c9a127e2..d781196777 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -83,38 +83,38 @@ public: // CCLabelTextFormat protocol implementation virtual std::vector *getLettersInfo() override { return &_lettersInfo; }; - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; - virtual bool recordPlaceholderInfo(int spriteIndex) override; - virtual float getLetterPosXLeft( int index ) const override; - virtual float getLetterPosXRight( int index ) const override; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; + virtual bool recordPlaceholderInfo(int spriteIndex) override; + virtual float getLetterPosXLeft( int index ) const override; + virtual float getLetterPosXRight( int index ) const override; - virtual Sprite * getLetter(int ID) override; + virtual Sprite * getLetter(int ID) override; // font related stuff - virtual int getCommonLineHeight() const override; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; - virtual int getXOffsetForChar(unsigned short c) const override; - virtual int getYOffsetForChar(unsigned short c) const override; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; - virtual Rect getRectForChar(unsigned short c) const override; + virtual int getCommonLineHeight() const override; + virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; + virtual int getXOffsetForChar(unsigned short c) const override; + virtual int getYOffsetForChar(unsigned short c) const override; + virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; + virtual Rect getRectForChar(unsigned short c) const override; // string related stuff - virtual int getStringNumLines() const override; - virtual int getStringLenght() const override; - virtual unsigned short getCharAtStringPosition(int position) const override; - virtual unsigned short * getUTF8String() const override; - virtual void assignNewUTF8String(unsigned short *newString) override; - virtual TextHAlignment getTextAlignment() const override; + virtual int getStringNumLines() const override; + virtual int getStringLenght() const override; + virtual unsigned short getCharAtStringPosition(int position) const override; + virtual unsigned short * getUTF8String() const override; + virtual void assignNewUTF8String(unsigned short *newString) override; + virtual TextHAlignment getTextAlignment() const override; // label related stuff - virtual float getMaxLineWidth() const override; - virtual bool breakLineWithoutSpace() const override; - virtual Size getLabelContentSize() const override; - virtual void setLabelContentSize(const Size &newSize) override; + virtual float getMaxLineWidth() const override; + virtual bool breakLineWithoutSpace() const override; + virtual Size getLabelContentSize() const override; + virtual void setLabelContentSize(const Size &newSize) override; // carloX - const char * getString() const { return "not implemented"; } - void addChild(Node * child, int zOrder=0, int tag=0); + virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } + void addChild(Node * child, int zOrder=0, int tag=0) override; private: /** diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 56a6ff723b..262c5f2dd9 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -203,9 +203,9 @@ void LabelAtlas::setString(const std::string &label) _quadsToDraw = len; } -const char* LabelAtlas::getString(void) const +const std::string& LabelAtlas::getString(void) const { - return _string.c_str(); + return _string; } //CCLabelAtlas - draw diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index eb8d06f4be..8fd81b9bda 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -87,11 +87,12 @@ public: // super methods virtual void updateAtlasValues(); - virtual void setString(const std::string &label); - virtual const char* getString(void) const; + + virtual void setString(const std::string &label) override; + virtual const std::string& getString(void) const override; #if CC_LABELATLAS_DEBUG_DRAW - virtual void draw(); + virtual void draw() override; #endif protected: diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index e28d4d0afc..fe6026abfe 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -767,9 +767,9 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel) } } -const char* LabelBMFont::getString(void) const +const std::string& LabelBMFont::getString() const { - return _initialStringUTF8.c_str(); + return _initialStringUTF8; } void LabelBMFont::setCString(const char *label) diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index cc49dd0806..a825d28ed6 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -228,10 +228,10 @@ public: /** updates the font chars based on the string to render */ void createFontChars(); // super method - virtual void setString(const std::string& newString); + virtual void setString(const std::string& newString) override; virtual void setString(const std::string& newString, bool needUpdateLabel); - virtual const char* getString() const; + virtual const std::string& getString() const override; virtual void setCString(const char *label); virtual void setAnchorPoint(const Point& var); virtual void updateLabel(); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 3eec437d09..179f079e50 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -180,9 +180,9 @@ void LabelTTF::setString(const std::string &string) } } -const char* LabelTTF::getString(void) const +const std::string& LabelTTF::getString() const { - return _string.c_str(); + return _string; } const char* LabelTTF::description() const diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index 029a125def..8c5689e3d0 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -144,8 +144,8 @@ public: /** changes the string to render * @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas */ - virtual void setString(const std::string &label); - virtual const char* getString(void) const; + virtual void setString(const std::string &label) override; + virtual const std::string& getString(void) const override; TextHAlignment getHorizontalAlignment() const; void setHorizontalAlignment(TextHAlignment alignment); diff --git a/cocos/2d/CCProtocols.h b/cocos/2d/CCProtocols.h index 17249816c0..993d1fa161 100644 --- a/cocos/2d/CCProtocols.h +++ b/cocos/2d/CCProtocols.h @@ -238,7 +238,7 @@ public: * @js NA * @lua NA */ - virtual const char* getString() const = 0; + virtual const std::string& getString() const = 0; }; /** diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 01179ba523..895aab58de 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -313,9 +313,9 @@ void TextFieldTTF::setString(const std::string &text) _charCount = _calcCharCount(_inputText.c_str()); } -const char* TextFieldTTF::getString(void) const +const std::string& TextFieldTTF::getString() const { - return _inputText.c_str(); + return _inputText; } // place holder text property diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 28c74a7a9c..a6ae42dc8e 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -148,7 +148,7 @@ public: // input text property public: virtual void setString(const std::string& text) override; - virtual const char* getString(void) const; + virtual const std::string& getString() const override; protected: TextFieldDelegate * _delegate; int _charCount; diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 43d6b27ecf..d18627be1e 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -565,12 +565,12 @@ void UIButton::setPressedActionEnabled(bool enabled) _pressedActionEnabled = enabled; } -void UIButton::setTitleText(const char* text) +void UIButton::setTitleText(const std::string& text) { _titleRenderer->setString(text); } -const char* UIButton::getTitleText() const +const std::string& UIButton::getTitleText() const { return _titleRenderer->getString(); } diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index bc6958c3e4..b069cbf5e0 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -171,8 +171,8 @@ public: */ virtual const char* getDescription() const; - void setTitleText(const char* text); - const char* getTitleText() const; + void setTitleText(const std::string& text); + const std::string& getTitleText() const; void setTitleColor(const cocos2d::Color3B& color); const cocos2d::Color3B& getTitleColor() const; void setTitleFontSize(float size); diff --git a/cocos/gui/UILabel.cpp b/cocos/gui/UILabel.cpp index 4c8779c9eb..cdf32c49c1 100644 --- a/cocos/gui/UILabel.cpp +++ b/cocos/gui/UILabel.cpp @@ -70,26 +70,23 @@ void UILabel::initRenderer() _renderer->addChild(_labelRenderer); } -void UILabel::setText(const char* text) +void UILabel::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _labelRenderer->setString(strText.c_str()); + + _labelRenderer->setString(text); labelScaleChangedWithSize(); } -const char* UILabel::getStringValue() +const std::string& UILabel::getStringValue() { return _labelRenderer->getString(); } int UILabel::getStringLength() { - const char* str = _labelRenderer->getString(); - return strlen(str); + return _labelRenderer->getString().size(); } void UILabel::setFontSize(int size) @@ -99,7 +96,7 @@ void UILabel::setFontSize(int size) labelScaleChangedWithSize(); } -void UILabel::setFontName(const char* name) +void UILabel::setFontName(const std::string& name) { _fontName = name; _labelRenderer->setFontName(name); diff --git a/cocos/gui/UILabel.h b/cocos/gui/UILabel.h index 5c6a4a105b..c38945bb9a 100644 --- a/cocos/gui/UILabel.h +++ b/cocos/gui/UILabel.h @@ -57,14 +57,14 @@ public: * * @param text string value. */ - void setText(const char* text); + void setText(const std::string& text); /** * Gets the string value of label. * * @return text string value. */ - const char* getStringValue(); + const std::string& getStringValue(); /** * Gets the string length of label. @@ -85,7 +85,7 @@ public: * * @param font name. */ - void setFontName(const char* name); + void setFontName(const std::string& name); /** * Sets the touch scale enabled of label. diff --git a/cocos/gui/UILabelAtlas.cpp b/cocos/gui/UILabelAtlas.cpp index 8e8db6c422..17963f595f 100644 --- a/cocos/gui/UILabelAtlas.cpp +++ b/cocos/gui/UILabelAtlas.cpp @@ -50,12 +50,12 @@ UICCLabelAtlas* UICCLabelAtlas::create() return NULL; } -void UICCLabelAtlas::setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap); } -void UICCLabelAtlas::setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) +void UICCLabelAtlas::setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap) { initWithString(string, texture, itemWidth, itemHeight, startCharMap); } @@ -113,7 +113,7 @@ void UILabelAtlas::initRenderer() _renderer->addChild(_laberAtlasRenderer); } -void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, int itemWidth, int itemHeight, const char *startCharMap) +void UILabelAtlas::setProperty(const std::string& stringValue, const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap) { _stringValue = stringValue; _charMapFileName = charMapFile; @@ -125,14 +125,14 @@ void UILabelAtlas::setProperty(const char *stringValue, const char *charMapFile, labelAtlasScaleChangedWithSize(); } -void UILabelAtlas::setStringValue(const char *value) +void UILabelAtlas::setStringValue(const std::string& value) { _stringValue = value; _laberAtlasRenderer->setString(value); labelAtlasScaleChangedWithSize(); } -const char* UILabelAtlas::getStringValue() +const std::string& UILabelAtlas::getStringValue() const { return _laberAtlasRenderer->getString(); } @@ -195,7 +195,7 @@ void UILabelAtlas::copySpecialProperties(UIWidget *widget) UILabelAtlas* labelAtlas = dynamic_cast(widget); if (labelAtlas) { - setProperty(labelAtlas->_stringValue.c_str(), labelAtlas->_charMapFileName.c_str(), labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap.c_str()); + setProperty(labelAtlas->_stringValue, labelAtlas->_charMapFileName, labelAtlas->_itemWidth, labelAtlas->_itemHeight, labelAtlas->_startCharMap); } } diff --git a/cocos/gui/UILabelAtlas.h b/cocos/gui/UILabelAtlas.h index 73b902633f..a33872ef0c 100644 --- a/cocos/gui/UILabelAtlas.h +++ b/cocos/gui/UILabelAtlas.h @@ -50,8 +50,8 @@ public: * Allocates and initializes. */ static UICCLabelAtlas* create(); - void setProperty(const char *string, const char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); - void setProperty(const char *string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, cocos2d::Texture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); virtual void updateDisplayedOpacity(GLubyte opacity); virtual void draw(void); }; @@ -78,13 +78,13 @@ public: static UILabelAtlas* create(); /** initializes the UILabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ - void setProperty(const char* stringValue,const char* charMapFile, int itemWidth, int itemHeight, const char* startCharMap); + void setProperty(const std::string& stringValue,const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap); //set string value for labelatlas. - void setStringValue(const char* value); + void setStringValue(const std::string& value); //get string value for labelatlas. - const char* getStringValue(); + const std::string& getStringValue() const; //override "setAnchorPoint" method of widget. virtual void setAnchorPoint(const cocos2d::Point &pt); diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index da79a1590b..311c0adfaa 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -105,7 +105,7 @@ bool UICCTextField::onTextFieldDetachWithIME(cocos2d::TextFieldTTF *pSender) void UICCTextField::insertText(const char * text, int len) { std::string str_text = text; - int str_len = strlen(cocos2d::TextFieldTTF::getString()); + int str_len = cocos2d::TextFieldTTF::getString().size(); if (strcmp(text, "\n") != 0) { @@ -321,18 +321,16 @@ void UITextField::setTouchSize(const cocos2d::Size &size) _touchHeight = size.height; } -void UITextField::setText(const char* text) +void UITextField::setText(const std::string& text) { - if (!text) - { + if (text.size()==0) return; - } - std::string strText(text); - _textFieldRenderer->setString(strText.c_str()); + + _textFieldRenderer->setString(text); textfieldRendererScaleChangedWithSize(); } -void UITextField::setPlaceHolder(const char *value) +void UITextField::setPlaceHolder(const std::string& value) { _textFieldRenderer->setPlaceHolder(value); textfieldRendererScaleChangedWithSize(); @@ -344,7 +342,7 @@ void UITextField::setFontSize(int size) textfieldRendererScaleChangedWithSize(); } -void UITextField::setFontName(const char *name) +void UITextField::setFontName(const std::string& name) { _textFieldRenderer->setFontName(name); textfieldRendererScaleChangedWithSize(); @@ -355,7 +353,7 @@ void UITextField::didNotSelectSelf() _textFieldRenderer->detachWithIME(); } -const char* UITextField::getStringValue() +const std::string& UITextField::getStringValue() { return _textFieldRenderer->getString(); } diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index ac5641114f..fc90ea9466 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -109,12 +109,12 @@ public: virtual bool init(); virtual void initRenderer(); void setTouchSize(const cocos2d::Size &size); - void setText(const char* text); - void setPlaceHolder(const char* value); + void setText(const std::string& text); + void setPlaceHolder(const std::string& value); void setFontSize(int size); - void setFontName(const char* name); + void setFontName(const std::string& name); virtual void didNotSelectSelf(); - const char* getStringValue(); + const std::string& getStringValue(); virtual bool onTouchBegan(const cocos2d::Point &touchPoint); void setMaxLengthEnabled(bool enable); bool isMaxLengthEnabled(); diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index fa87e4c9e5..1f18b31118 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -14,6 +14,11 @@ struct { const char *test_name; std::function callback; } g_aTestNames[] = { + + // + // TESTS MUST BE ORDERED ALPHABETICALLY + // violators will be prosecuted + // { "Accelerometer", []() { return new AccelerometerTestScene(); } }, { "ActionManagerTest", [](){return new ActionManagerTestScene(); } }, { "ActionsEaseTest", [](){return new ActionsEaseTestScene();} }, @@ -50,7 +55,6 @@ struct { { "FontTest", []() { return new FontTestScene(); } }, { "IntervalTest", [](){return new IntervalTestScene(); } }, { "KeyboardTest", []() { return new KeyboardTestScene(); } }, - { "MouseTest", []() { return new MouseTestScene(); } }, #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) { "KeypadTest", []() { return new KeypadTestScene(); } }, #endif @@ -59,6 +63,7 @@ struct { { "LayerTest", [](){return new LayerTestScene();} }, { "MenuTest", [](){return new MenuTestScene();} }, { "MotionStreakTest", [](){return new MotionStreakTestScene();} }, + { "MouseTest", []() { return new MouseTestScene(); } }, { "MutiTouchTest", []() { return new MutiTouchTestScene(); } }, { "NodeTest", [](){return new CocosNodeTestScene();} }, { "ParallaxTest", [](){return new ParallaxTestScene(); } }, From 0fb85f88fbd058bd95f2b59a7d61713e6c485972 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 15:08:49 -0800 Subject: [PATCH 473/557] updates coding style. Everything is in MarkDown format. Much easier to read than in redmine --- docs/CODING_STYLE.md | 131 ---------------------------- docs/CODING_STYLE.md.REMOVED.git-id | 1 + 2 files changed, 1 insertion(+), 131 deletions(-) delete mode 100644 docs/CODING_STYLE.md create mode 100644 docs/CODING_STYLE.md.REMOVED.git-id diff --git a/docs/CODING_STYLE.md b/docs/CODING_STYLE.md deleted file mode 100644 index 4b7bf2a7c8..0000000000 --- a/docs/CODING_STYLE.md +++ /dev/null @@ -1,131 +0,0 @@ -# cocos2d-x C++ coding sytle - - -## Detailed information - -Please, refer to this document for a detailed version of the cocos2d-x C++ coding sytle: - -* [cocos2d-x c++ coding style](http://www.cocos2d-x.org/wiki/Cocos2d_c++_coding_style) - - -## Quick Sample - -Use this sample as a quick reference. But DO READ the detailed doc for more info. - -Header file: - -```c++ -/** - * We use Doxygen strings for documentation. - * All public classes, methods, structs should be documented using Doxygen Strings - */ -class CC_DLL Sprite : public NodeRGBA, public TextureProtocol -{ /* class braces start in a new line */ - -/* no indentation here for public, protected or private */ -/* First add all the "public" stuff, then all the "protected" stuff, and finally all the "private" stuff -public: - - /* we don't use tabs, we use spaces, and we use a 4 space identation */ - /* 1st add all static const */ - static const int INDEX_NOT_INITIALIZED = -1; - - /* then add all the creators and other relevant static methods */ - static Sprite* create(); - static Sprite* create(const char *filename); - static Sprite* create(const char *filename, const Rect& rect); - - /* if applicable, then add the consturctors / destructors */ - Sprite(); - virtual ~Sprite(void); - - /* then add all the initialization methods */ - /* notice that they are in the same order as the creators */ - virtual bool init(void); - virtual bool initWithTexture(Texture2D *texture); - virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - - - - /* then add the regular instace methods */ - virtual void updateTransform(void); - virtual SpriteBatchNode* getBatchNode(void); - virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - - - /* then add all the overriden methods */ - /* notice that all overriden methods must use the 'override' keyword */ - /* overriden methods are not forced to have doxygen strings UNLESS they change the behavior in a non obvios way */ - virtual void setPosition(const Point& pos) override; - virtual void setRotation(float rotation) override; - virtual void setRotationX(float rotationX) override; - - - /* once you finish with the 'public' methods, start with the 'protected' ones */ -protected: - - /* protected methods are not forced to have Doxygen strings, but if they have it, better */ - void updateColor(void); - virtual void setTextureCoords(Rect rect); - - /* After adding all the methods, add the ivars */ - /* all ivars must start with _ */ - /* Do not use Hungarian notation */ - TextureAtlas* _textureAtlas; - int _atlasIndex; - SpriteBatchNode* _batchNode; -}; - -``` - -Implementation file: - -```c++ -/* Do not use doxygen comments on the implementation file */ - -/* The methos MUST be in the same order as where declared in the header file */ - -Sprite* Sprite::create(const char *filename) -{ - /* Don't use tabs. Use spaces. Use 4-space indentation */ - Sprite *sprite = new Sprite(); - - /* put curly braces in the same line as in the 'if'*/ - /* leave a space between the 'if' and the '(' */ - /* don't leave spaces between '()' */ - if (sprite && sprite->initWithFile(filename)) { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -/* Initialization list can be indented to 0 spaces, or to 4 spaces. If in doubt, be consistent with the indentation already used in the file */ -/* Only use the Initialization lists for types that can't fail when initialized */ -Sprite::Sprite() -: _shouldBeHidden(false) -, _texture(nullptr) -, _physicsBody(nullptr) -{ -} - -/* use the 'initXXX' methods to initialize types that might fail */ -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - /* it ok not use use curly braces */ - if (something) - do_something(); - else - something_else(); - - /* but if you use curly branches in one branch, all the branches should use curly branches */ - if (something) { - do_something1(); - do_something2(); - } else { - so_something_else(); - } -} - -``` diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id new file mode 100644 index 0000000000..19a3855c35 --- /dev/null +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -0,0 +1 @@ +bf158b68747963e7f0b734954a407e63a30a69c3 \ No newline at end of file From 3300e46d0fa12edeb936c63d93a6016c7d690d00 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 15:37:41 -0800 Subject: [PATCH 474/557] More fixes to the C++ guide --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 19a3855c35..2238cbadfc 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -bf158b68747963e7f0b734954a407e63a30a69c3 \ No newline at end of file +1ab69691a01c1fe6e8d479756b556149e9726e35 \ No newline at end of file From 6d0be761eb7fbe65ec76449655f8df7a5cff3666 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:47:12 +0800 Subject: [PATCH 475/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 93e703edb1..f3dca88228 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -16,6 +16,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. + [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 21f8050a4d271a0b8fa74c6972554aa8e8858e52 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:50:28 +0800 Subject: [PATCH 476/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index f3dca88228..3df3b9aa44 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -38,6 +38,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] sys.localStorage.getItem() does not support non-ascii string. [FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device. [FIX] CCBReader can't play sequence automatically in JSB. + [NEW] main.js -> cocos2d-jsb.js [Lua Binding] [NEW] Added Armature lua binding and added test samples. From 61970934a241b32ca0d45cd68ea3527f23c69dba Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 10:55:49 +0800 Subject: [PATCH 477/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 3df3b9aa44..4582eee2eb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,6 +17,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Arm64 support. [NEW] Added Mouse Support For Desktop Platforms. [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. + [NEW] Sprite: Override setScale(float scaleX, float scaleY) [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From d936622070f4cef6791589014bd8b773c528255a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 7 Nov 2013 19:00:31 -0800 Subject: [PATCH 478/557] Adds TOC to coding style --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 2238cbadfc..51a1dc866d 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -1ab69691a01c1fe6e8d479756b556149e9726e35 \ No newline at end of file +55fe4bd3605531a58a565c46eec20dee0f81ff97 \ No newline at end of file From d4f890a6ee32d57413757eaf431a2e3bc821005b Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 8 Nov 2013 11:01:16 +0800 Subject: [PATCH 479/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 4582eee2eb..743d94f96f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -18,6 +18,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Added Mouse Support For Desktop Platforms. [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [NEW] Sprite: Override setScale(float scaleX, float scaleY) + [NEW] External: added | operator for Control::EventType [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 240fc2ade10226a2a57adaeeda2853a7fc8fc500 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 8 Nov 2013 03:10:36 +0000 Subject: [PATCH 480/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 52e968dfe0..32fcdc004b 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 52e968dfe02f077f56d4df6cc04e38c8b76e22b9 +Subproject commit 32fcdc004b3023c32b1ddc1fce6bcb86bbba9c41 From 935d472979e2900dab5537c040821ef874ad454a Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 8 Nov 2013 11:36:27 +0800 Subject: [PATCH 481/557] issue #3025: remove TextureCache::_sharedTextureCache --- cocos/2d/CCTextureCache.cpp | 4 ---- cocos/2d/CCTextureCache.h | 2 -- 2 files changed, 6 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index cf1e8887f9..840a110a77 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -51,8 +51,6 @@ NS_CC_BEGIN // implementation TextureCache -TextureCache* TextureCache::_sharedTextureCache = nullptr; - TextureCache * TextureCache::getInstance() { return Director::getInstance()->getTextureCache(); @@ -65,7 +63,6 @@ TextureCache::TextureCache() , _needQuit(false) , _asyncRefCount(0) { - CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton."); } TextureCache::~TextureCache() @@ -76,7 +73,6 @@ TextureCache::~TextureCache() (it->second)->release(); CC_SAFE_DELETE(_loadingThread); - _sharedTextureCache = nullptr; } void TextureCache::destroyInstance() diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 7916696513..eaa4567e90 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -200,8 +200,6 @@ protected: int _asyncRefCount; std::unordered_map _textures; - - static TextureCache *_sharedTextureCache; }; #if CC_ENABLE_CACHE_TEXTURE_DATA From fd37d3e9734306fcf076673e80da40d6ada5c35e Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 8 Nov 2013 04:17:15 +0000 Subject: [PATCH 482/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 32fcdc004b..7199547f2f 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 32fcdc004b3023c32b1ddc1fce6bcb86bbba9c41 +Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 From 314f2ac62ed7da993b2571295ce0a3e21591562a Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 8 Nov 2013 14:13:39 +0800 Subject: [PATCH 483/557] use float instead for create point object --- cocos/base/CCGeometry.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 5f681914b0..fe5086cba9 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -293,16 +293,16 @@ Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, c return Point::ZERO; } -const Point Point::ZERO = Point(0, 0); -const Point Point::ANCHOR_MIDDLE = Point(0.5, 0.5); -const Point Point::ANCHOR_BOTTOM_LEFT = Point(0, 0); -const Point Point::ANCHOR_TOP_LEFT = Point(0, 1); -const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1, 0); -const Point Point::ANCHOR_TOP_RIGHT = Point(1, 1); -const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1, .5); -const Point Point::ANCHOR_MIDDLE_LEFT = Point(0, 0.5); -const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5, 1); -const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5, 0); +const Point Point::ZERO = Point(0.0f, 0.0f); +const Point Point::ANCHOR_MIDDLE = Point(0.5f, 0.5f); +const Point Point::ANCHOR_BOTTOM_LEFT = Point(0.0f, 0.0f); +const Point Point::ANCHOR_TOP_LEFT = Point(0.0f, 1.0f); +const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1.0f, 0.0f); +const Point Point::ANCHOR_TOP_RIGHT = Point(1.0f, 1.0f); +const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_LEFT = Point(0.0f, 0.5f); +const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5f, 1.0f); +const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5f, 0.0f); // implementation of Size From da27169d4566ced6972c8561a9be1573bf91744b Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 8 Nov 2013 14:58:20 +0800 Subject: [PATCH 484/557] add "setUserObject" method --- cocos/gui/UICheckBox.cpp | 3 --- cocos/gui/UIPageView.cpp | 3 --- cocos/gui/UIScrollView.cpp | 3 --- cocos/gui/UISlider.cpp | 3 --- cocos/gui/UITextField.cpp | 3 --- cocos/gui/UIWidget.cpp | 14 ++++++++++---- cocos/gui/UIWidget.h | 20 ++++++++++++++++++++ 7 files changed, 30 insertions(+), 19 deletions(-) diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index c577a86fe6..e79be3d5f0 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -51,7 +51,6 @@ _frontCrossDisabledFileName("") UICheckBox::~UICheckBox() { - CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = NULL; _selectedStateEventSelector = NULL; } @@ -302,9 +301,7 @@ void UICheckBox::unSelectedEvent() void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) { - CC_SAFE_RELEASE(_selectedStateEventListener); _selectedStateEventListener = target; - CC_SAFE_RETAIN(_selectedStateEventListener); _selectedStateEventSelector = selector; } diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index bb88e6cb80..54b0713b7a 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -51,7 +51,6 @@ UIPageView::~UIPageView() { _pages->removeAllObjects(); CC_SAFE_RELEASE(_pages); - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -574,9 +573,7 @@ void UIPageView::pageTurningEvent() void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 2654eeda53..ebf32514da 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -76,7 +76,6 @@ _eventSelector(NULL) UIScrollView::~UIScrollView() { - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -1531,9 +1530,7 @@ void UIScrollView::bounceRightEvent() void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selector; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index d5e0eac9ae..b5c90ccfb8 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -58,7 +58,6 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = NULL; _slidPercentSelector = NULL; } @@ -414,9 +413,7 @@ float UISlider::getPercentWithBallPos(float px) void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { - CC_SAFE_RELEASE(_slidPercentListener); _slidPercentListener = target; - CC_SAFE_RETAIN(_slidPercentListener); _slidPercentSelector = selector; } diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 963d807ef1..6a95ac8605 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -283,7 +283,6 @@ _passwordStyleText("") UITextField::~UITextField() { - CC_SAFE_RELEASE(_eventListener); _eventListener = NULL; _eventSelector = NULL; } @@ -505,9 +504,7 @@ void UITextField::deleteBackwardEvent() void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) { - CC_SAFE_RELEASE(_eventListener); _eventListener = target; - CC_SAFE_RETAIN(_eventListener); _eventSelector = selecor; } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 7f2adc545a..ad63b28451 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -68,14 +68,14 @@ _sizeType(SIZE_ABSOLUTE), _sizePercent(cocos2d::Point::ZERO), _positionType(POSITION_ABSOLUTE), _positionPercent(cocos2d::Point::ZERO), -_isRunning(false) +_isRunning(false), +_userObject(NULL) { } UIWidget::~UIWidget() { - CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = NULL; _touchEventSelector = NULL; removeAllChildren(); @@ -87,6 +87,7 @@ UIWidget::~UIWidget() _layoutParameterDictionary->removeAllObjects(); CC_SAFE_RELEASE(_layoutParameterDictionary); CC_SAFE_RELEASE(_scheduler); + CC_SAFE_RELEASE(_userObject); } UIWidget* UIWidget::create() @@ -135,6 +136,13 @@ void UIWidget::onExit() _isRunning = false; arrayMakeObjectsPerformSelector(_children, onExit, UIWidget*); } + +void UIWidget::setUserObject(cocos2d::Object *pUserObject) +{ + CC_SAFE_RETAIN(pUserObject); + CC_SAFE_RELEASE(_userObject); + _userObject = pUserObject; +} bool UIWidget::addChild(UIWidget *child) { @@ -698,9 +706,7 @@ void UIWidget::longClickEvent() void UIWidget::addTouchEventListener(cocos2d::Object *target, SEL_TouchEvent selector) { - CC_SAFE_RELEASE(_touchEventListener); _touchEventListener = target; - CC_SAFE_RETAIN(_touchEventListener); _touchEventSelector = selector; } diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index f4f48f2a94..02db42e731 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -880,6 +880,25 @@ public: virtual void onEnter(); virtual void onExit(); + + virtual Object* getUserObject() { return _userObject; } + /** + * @js NA + * @lua NA + */ + virtual const Object* getUserObject() const { return _userObject; } + + /** + * Returns a user assigned Object + * + * Similar to UserData, but instead of holding a void* it holds an object. + * The UserObject will be retained once in this method, + * and the previous UserObject (if existed) will be relese. + * The UserObject will be released in Node's destructure. + * + * @param userObject A user assigned Object + */ + virtual void setUserObject(Object *userObject); /*temp action*/ void setActionTag(int tag); int getActionTag(); @@ -952,6 +971,7 @@ protected: PositionType _positionType; cocos2d::Point _positionPercent; bool _isRunning; + cocos2d::Object* _userObject; }; /** * @js NA From b726c6fd2c1f07dd7fac51fe8eb43b421c00def8 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 8 Nov 2013 16:47:33 +0800 Subject: [PATCH 485/557] issue #3025: move VolatileTexture static function to VolatileTextureMgr --- cocos/2d/CCRenderTexture.cpp | 4 +-- cocos/2d/CCTexture2D.cpp | 10 ++++---- cocos/2d/CCTextureCache.cpp | 48 ++++++++++++++++++------------------ cocos/2d/CCTextureCache.h | 41 ++++++++++++++++-------------- 4 files changed, 53 insertions(+), 50 deletions(-) diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 17697c9de5..8fa56c282d 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj) if (_UITextureImage) { const Size& s = _texture->getContentSizeInPixels(); - VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); + VolatileTextureMgr::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); if ( _textureCopy ) { - VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); + VolatileTextureMgr::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s); } } else diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 397bdbf68a..2f0665afb4 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -434,7 +434,7 @@ Texture2D::Texture2D() Texture2D::~Texture2D() { #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::removeTexture(this); + VolatileTextureMgr::removeTexture(this); #endif CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name); @@ -1041,7 +1041,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture data - VolatileTexture::addStringTexture(this, text, textDefinition); + VolatileTextureMgr::addStringTexture(this, text, textDefinition); #endif bool bRet = false; @@ -1267,7 +1267,7 @@ void Texture2D::setTexParameters(const TexParams &texParams) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT ); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } @@ -1287,7 +1287,7 @@ void Texture2D::setAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } @@ -1307,7 +1307,7 @@ void Texture2D::setAntiAliasTexParameters() glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, texParams); + VolatileTextureMgr::setTexParameters(this, texParams); #endif } diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 840a110a77..7a5e835653 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -239,7 +239,7 @@ void TextureCache::addImageAsyncCallBack(float dt) #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, filename); + VolatileTextureMgr::addImageTexture(texture, filename); #endif // cache the texture. retain it, since it is added in the map _textures.insert( std::make_pair(filename, texture) ); @@ -299,7 +299,7 @@ Texture2D * TextureCache::addImage(const std::string &path) { #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture file name - VolatileTexture::addImageTexture(texture, fullpath.c_str()); + VolatileTextureMgr::addImageTexture(texture, fullpath.c_str()); #endif // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); @@ -349,7 +349,7 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) } while (0); #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::addImage(texture, image); + VolatileTextureMgr::addImage(texture, image); #endif return texture; @@ -418,7 +418,7 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const void TextureCache::reloadAllTextures() { #if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTexture::reloadAllTextures(); + VolatileTextureMgr::reloadAllTextures(); #endif } @@ -458,8 +458,8 @@ void TextureCache::dumpCachedTextureInfo() const #if CC_ENABLE_CACHE_TEXTURE_DATA -std::list VolatileTexture::_textures; -bool VolatileTexture::_isReloading = false; +std::list VolatileTextureMgr::_textures; +bool VolatileTextureMgr::_isReloading = false; VolatileTexture::VolatileTexture(Texture2D *t) : _texture(t) @@ -474,16 +474,14 @@ VolatileTexture::VolatileTexture(Texture2D *t) _texParams.magFilter = GL_LINEAR; _texParams.wrapS = GL_CLAMP_TO_EDGE; _texParams.wrapT = GL_CLAMP_TO_EDGE; - _textures.push_back(this); } VolatileTexture::~VolatileTexture() { - _textures.remove(this); CC_SAFE_RELEASE(_uiImage); } -void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) +void VolatileTextureMgr::addImageTexture(Texture2D *tt, const char* imageFileName) { if (_isReloading) { @@ -492,20 +490,20 @@ void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName) VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageFile; + vt->_cashedImageType = VolatileTexture::kImageFile; vt->_fileName = imageFileName; vt->_pixelFormat = tt->getPixelFormat(); } -void VolatileTexture::addImage(Texture2D *tt, Image *image) +void VolatileTextureMgr::addImage(Texture2D *tt, Image *image) { VolatileTexture *vt = findVolotileTexture(tt); image->retain(); vt->_uiImage = image; - vt->_cashedImageType = kImage; + vt->_cashedImageType = VolatileTexture::kImage; } -VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) +VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt) { VolatileTexture *vt = 0; auto i = _textures.begin(); @@ -522,12 +520,13 @@ VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt) if (! vt) { vt = new VolatileTexture(tt); + _textures.push_back(vt); } return vt; } -void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize) +void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize) { if (_isReloading) { @@ -536,14 +535,14 @@ void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Tex VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kImageData; + vt->_cashedImageType = VolatileTexture::kImageData; vt->_textureData = data; vt->_dataLen = dataLen; vt->_pixelFormat = pixelFormat; vt->_textureSize = contentSize; } -void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition) +void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition) { if (_isReloading) { @@ -552,12 +551,12 @@ void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const Fo VolatileTexture *vt = findVolotileTexture(tt); - vt->_cashedImageType = kString; + vt->_cashedImageType = VolatileTexture::kString; vt->_text = text; vt->_fontDefinition = fontDefinition; } -void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) +void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) { VolatileTexture *vt = findVolotileTexture(t); @@ -571,7 +570,7 @@ void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams vt->_texParams.wrapT = texParams.wrapT; } -void VolatileTexture::removeTexture(Texture2D *t) +void VolatileTextureMgr::removeTexture(Texture2D *t) { auto i = _textures.begin(); while (i != _textures.end()) @@ -579,13 +578,14 @@ void VolatileTexture::removeTexture(Texture2D *t) VolatileTexture *vt = *i++; if (vt->_texture == t) { + _textures.remove(vt); delete vt; break; } } } -void VolatileTexture::reloadAllTextures() +void VolatileTextureMgr::reloadAllTextures() { _isReloading = true; @@ -598,7 +598,7 @@ void VolatileTexture::reloadAllTextures() switch (vt->_cashedImageType) { - case kImageFile: + case VolatileTexture::kImageFile: { Image* image = new Image(); long size = 0; @@ -616,7 +616,7 @@ void VolatileTexture::reloadAllTextures() CC_SAFE_RELEASE(image); } break; - case kImageData: + case VolatileTexture::kImageData: { vt->_texture->initWithData(vt->_textureData, vt->_dataLen, @@ -626,12 +626,12 @@ void VolatileTexture::reloadAllTextures() vt->_textureSize); } break; - case kString: + case VolatileTexture::kString: { vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); } break; - case kImage: + case VolatileTexture::kImage: { vt->_texture->initWithImage(vt->_uiImage); } diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index eaa4567e90..8c988ff4c3 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -214,7 +214,7 @@ class VolatileTexture kImage, }ccCachedImageType; -public: +private: VolatileTexture(Texture2D *t); /** * @js NA @@ -222,25 +222,8 @@ public: */ ~VolatileTexture(); - static void addImageTexture(Texture2D *tt, const char* imageFileName); - static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition); - static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize); - static void addImage(Texture2D *tt, Image *image); - - static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams); - static void removeTexture(Texture2D *t); - static void reloadAllTextures(); - -public: - static std::list _textures; - static bool _isReloading; - -private: - // find VolatileTexture by Texture2D* - // if not found, create a new one - static VolatileTexture* findVolotileTexture(Texture2D *tt); - protected: + friend class VolatileTextureMgr; Texture2D *_texture; Image *_uiImage; @@ -259,6 +242,26 @@ protected: FontDefinition _fontDefinition; }; +class VolatileTextureMgr +{ +public: + static void addImageTexture(Texture2D *tt, const char* imageFileName); + static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition); + static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize); + static void addImage(Texture2D *tt, Image *image); + + static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams); + static void removeTexture(Texture2D *t); + static void reloadAllTextures(); +public: + static std::list _textures; + static bool _isReloading; +private: + // find VolatileTexture by Texture2D* + // if not found, create a new one + static VolatileTexture* findVolotileTexture(Texture2D *tt); +}; + #endif // end of textures group From eeedab78b2485c9b317fb8beabf8c9b24896a6e2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 8 Nov 2013 18:13:24 +0800 Subject: [PATCH 486/557] [LINUX] Adding template CMake files for linux. --- template/multi-platform-cpp/CMakeLists.txt | 143 ++++++++++++++++++++ template/multi-platform-lua/CMakeLists.txt | 149 +++++++++++++++++++++ tools/travis-scripts/run-script.sh | 7 + 3 files changed, 299 insertions(+) create mode 100644 template/multi-platform-cpp/CMakeLists.txt create mode 100644 template/multi-platform-lua/CMakeLists.txt diff --git a/template/multi-platform-cpp/CMakeLists.txt b/template/multi-platform-cpp/CMakeLists.txt new file mode 100644 index 0000000000..88299d0d83 --- /dev/null +++ b/template/multi-platform-cpp/CMakeLists.txt @@ -0,0 +1,143 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloCpp) +project (${APP_NAME}) + +include(../../build/BuildHelpers.CMakeLists.txt) + +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) + +if(DEBUG_MODE) + set(CMAKE_BUILD_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILD_TYPE RELEASE) +endif(DEBUG_MODE) + +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp + Classes/HelloWorldScene.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/template/multi-platform-lua/CMakeLists.txt b/template/multi-platform-lua/CMakeLists.txt new file mode 100644 index 0000000000..a3cf368403 --- /dev/null +++ b/template/multi-platform-lua/CMakeLists.txt @@ -0,0 +1,149 @@ +cmake_minimum_required(VERSION 2.6) + +set(APP_NAME HelloLua) +project (${APP_NAME}) + +include(../../build/BuildHelpers.CMakeLists.txt) + +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(USE_BOX2D "Use box2d for physics library" OFF) +option(DEBUG_MODE "Debug or release?" ON) + +if(DEBUG_MODE) + set(CMAKE_BUILD_TYPE DEBUG) +else(DEBUG_MODE) + set(CMAKE_BUILD_TYPE RELEASE) +endif(DEBUG_MODE) + +set(CMAKE_C_FLAGS_DEBUG "-g -Wall -DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-std=c99") +set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11") + +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DLINUX -DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-DLINUX -DCC_ENABLE_BOX2D_INTEGRATION=1) +else(USE_CHIPMUNK) + message(FATAL_ERROR "Must choose a physics library.") +endif(USE_CHIPMUNK) + +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + + +set(GAME_SRC + proj.linux/main.cpp + Classes/AppDelegate.cpp +) + +set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/../..) + +include_directories( + Classes + ${COCOS2D_ROOT}/cocos/scripting/lua/bindings + ${COCOS2D_ROOT}/external/lua/lua + ${COCOS2D_ROOT}/external/lua/tolua + ${COCOS2D_ROOT} + ${COCOS2D_ROOT}/cocos + ${COCOS2D_ROOT}/cocos/audio/include + ${COCOS2D_ROOT}/cocos/2d + ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/linux + ${COCOS2D_ROOT}/cocos/base + ${COCOS2D_ROOT}/cocos/physics + ${COCOS2D_ROOT}/cocos/editor-support + ${COCOS2D_ROOT}/cocos/math/kazmath/include + ${COCOS2D_ROOT}/extensions + ${COCOS2D_ROOT}/external + ${COCOS2D_ROOT}/external/jpeg/include/linux + ${COCOS2D_ROOT}/external/tiff/include/linux + ${COCOS2D_ROOT}/external/webp/include/linux + ${COCOS2D_ROOT}/external/glfw3/include/linux + ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tinyxml2 + ${COCOS2D_ROOT}/external/unzip + ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk + ${COCOS2D_ROOT}/external/freetype2/include/linux + ${COCOS2D_ROOT}/external/linux-specific/fmod/include/${ARCH_DIR} +) + +link_directories( + /usr/local/lib + ${COCOS2D_ROOT}/lib + ${COCOS2D_ROOT}/external/jpeg/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} + ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} +) + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(FMOD_LIB "fmodex64") +else() +set(FMOD_LIB "fmodex") +endif() + +target_link_libraries(${APP_NAME} + luabinding + tolua + lua + gui + network + curl + ldap + lber + idn + rtmp + spine + cocostudio + jsoncpp + cocosbuilder + extensions + box2d + audio + ${FMOD_LIB} + cocos2d + cocosbase + chipmunk + tinyxml2 + kazmath + unzip + jpeg + webp + tiff + freetype + fontconfig + png + pthread + glfw + GLEW + GL + X11 + rt + z + ) + +set(APP_BIN_DIR "${CMAKE_SOURCE_DIR}/bin") + +set_target_properties(${APP_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") + +pre_build(${APP_NAME} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources + ) + diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index e8d45a1415..4852ab01f9 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -76,6 +76,13 @@ elif [ "$PLATFORM"x = "linux"x ]; then cd linux-build cmake ../.. make -j10 + cd ../../multi-platform-cpp + cmake . + make -j10 + cd ../multi-platform-lua + cmake . + make -j10 + elif [ "$PLATFORM"x = "emscripten"x ]; then # Generate binding glue codes echo "Generating bindings glue codes ..." From 74497e18ec6ca5f439b1c1ead052e13a8d426341 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 8 Nov 2013 18:25:58 +0800 Subject: [PATCH 487/557] [CMake template] Fix compilation errors. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 4852ab01f9..b609c7cc43 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -76,7 +76,7 @@ elif [ "$PLATFORM"x = "linux"x ]; then cd linux-build cmake ../.. make -j10 - cd ../../multi-platform-cpp + cd ../../template/multi-platform-cpp cmake . make -j10 cd ../multi-platform-lua From 1f389d377960111f967788f5a4aafa126dadcb38 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 8 Nov 2013 18:43:06 +0800 Subject: [PATCH 488/557] Rename event interface --- cocos/gui/UICheckBox.cpp | 22 ++++---- cocos/gui/UICheckBox.h | 6 +-- cocos/gui/UIPageView.cpp | 18 +++---- cocos/gui/UIPageView.h | 6 +-- cocos/gui/UIScrollView.cpp | 50 +++++++++---------- cocos/gui/UIScrollView.h | 6 +-- cocos/gui/UISlider.cpp | 18 +++---- cocos/gui/UISlider.h | 6 +-- cocos/gui/UITextField.cpp | 30 +++++------ cocos/gui/UITextField.h | 6 +-- .../UICheckBoxTest/UICheckBoxTest.cpp | 2 +- .../UIPageViewTest/UIPageViewTest.cpp | 2 +- .../UISliderTest/UISliderTest.cpp | 4 +- .../UITextFieldTest/UITextFieldTest.cpp | 6 +-- 14 files changed, 91 insertions(+), 91 deletions(-) diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index e79be3d5f0..511d03a7ea 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -34,8 +34,8 @@ _frontCrossRenderer(NULL), _backGroundBoxDisabledRenderer(NULL), _frontCrossDisabledRenderer(NULL), _isSelected(true), -_selectedStateEventListener(NULL), -_selectedStateEventSelector(NULL), +_checkBoxEventListener(NULL), +_checkBoxEventSelector(NULL), _backGroundTexType(UI_TEX_TYPE_LOCAL), _backGroundSelectedTexType(UI_TEX_TYPE_LOCAL), _frontCrossTexType(UI_TEX_TYPE_LOCAL), @@ -51,8 +51,8 @@ _frontCrossDisabledFileName("") UICheckBox::~UICheckBox() { - _selectedStateEventListener = NULL; - _selectedStateEventSelector = NULL; + _checkBoxEventListener = NULL; + _checkBoxEventSelector = NULL; } UICheckBox* UICheckBox::create() @@ -285,24 +285,24 @@ bool UICheckBox::getSelectedState() void UICheckBox::selectedEvent() { - if (_selectedStateEventListener && _selectedStateEventSelector) + if (_checkBoxEventListener && _checkBoxEventSelector) { - (_selectedStateEventListener->*_selectedStateEventSelector)(this,CHECKBOX_STATE_EVENT_SELECTED); + (_checkBoxEventListener->*_checkBoxEventSelector)(this,CHECKBOX_STATE_EVENT_SELECTED); } } void UICheckBox::unSelectedEvent() { - if (_selectedStateEventListener && _selectedStateEventSelector) + if (_checkBoxEventListener && _checkBoxEventSelector) { - (_selectedStateEventListener->*_selectedStateEventSelector)(this,CHECKBOX_STATE_EVENT_UNSELECTED); + (_checkBoxEventListener->*_checkBoxEventSelector)(this,CHECKBOX_STATE_EVENT_UNSELECTED); } } -void UICheckBox::addEventListener(cocos2d::Object *target, SEL_SelectedStateEvent selector) +void UICheckBox::addEventListenerCheckBox(cocos2d::Object *target, SEL_SelectedStateEvent selector) { - _selectedStateEventListener = target; - _selectedStateEventSelector = selector; + _checkBoxEventListener = target; + _checkBoxEventSelector = selector; } void UICheckBox::setFlipX(bool flipX) diff --git a/cocos/gui/UICheckBox.h b/cocos/gui/UICheckBox.h index 5e9c836617..26562d2b8f 100644 --- a/cocos/gui/UICheckBox.h +++ b/cocos/gui/UICheckBox.h @@ -138,7 +138,7 @@ public: virtual void setAnchorPoint(const cocos2d::Point &pt); //add a call back function would called when checkbox is selected or unselected. - void addEventListener(cocos2d::Object* target,SEL_SelectedStateEvent selector); + void addEventListenerCheckBox(cocos2d::Object* target,SEL_SelectedStateEvent selector); //override "setFlipX" method of widget. virtual void setFlipX(bool flipX); @@ -190,8 +190,8 @@ protected: cocos2d::Sprite* _frontCrossDisabledRenderer; bool _isSelected; - cocos2d::Object* _selectedStateEventListener; - SEL_SelectedStateEvent _selectedStateEventSelector; + cocos2d::Object* _checkBoxEventListener; + SEL_SelectedStateEvent _checkBoxEventSelector; TextureResType _backGroundTexType; TextureResType _backGroundSelectedTexType; diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 54b0713b7a..2183091b6d 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -42,8 +42,8 @@ _autoScrollDistance(0.0f), _autoScrollSpeed(0.0f), _autoScrollDir(0), _childFocusCancelOffset(5.0f), -_eventListener(NULL), -_eventSelector(NULL) +_pageViewEventListener(NULL), +_pageViewEventSelector(NULL) { } @@ -51,8 +51,8 @@ UIPageView::~UIPageView() { _pages->removeAllObjects(); CC_SAFE_RELEASE(_pages); - _eventListener = NULL; - _eventSelector = NULL; + _pageViewEventListener = NULL; + _pageViewEventSelector = NULL; } UIPageView* UIPageView::create() @@ -565,16 +565,16 @@ void UIPageView::interceptTouchEvent(int handleState, UIWidget *sender, const co void UIPageView::pageTurningEvent() { - if (_eventListener && _eventSelector) + if (_pageViewEventListener && _pageViewEventSelector) { - (_eventListener->*_eventSelector)(this, PAGEVIEW_EVENT_TURNING); + (_pageViewEventListener->*_pageViewEventSelector)(this, PAGEVIEW_EVENT_TURNING); } } -void UIPageView::addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector) +void UIPageView::addEventListenerPageView(cocos2d::Object *target, SEL_PageViewEvent selector) { - _eventListener = target; - _eventSelector = selector; + _pageViewEventListener = target; + _pageViewEventSelector = selector; } int UIPageView::getCurPageIndex() const diff --git a/cocos/gui/UIPageView.h b/cocos/gui/UIPageView.h index ec78df8bbd..ef11056e9b 100644 --- a/cocos/gui/UIPageView.h +++ b/cocos/gui/UIPageView.h @@ -118,7 +118,7 @@ public: cocos2d::Array* getPages(); // event - void addEventListener(cocos2d::Object *target, SEL_PageViewEvent selector); + void addEventListenerPageView(cocos2d::Object *target, SEL_PageViewEvent selector); //override "removeChild" method of widget. @@ -186,8 +186,8 @@ protected: float _autoScrollSpeed; int _autoScrollDir; float _childFocusCancelOffset; - cocos2d::Object* _eventListener; - SEL_PageViewEvent _eventSelector; + cocos2d::Object* _pageViewEventListener; + SEL_PageViewEvent _pageViewEventSelector; }; diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index ebf32514da..e80bd3873c 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -69,15 +69,15 @@ _bouncing(false), _bounceDir(cocos2d::Point::ZERO), _bounceOriginalSpeed(0.0f), _inertiaScrollEnabled(true), -_eventListener(NULL), -_eventSelector(NULL) +_scrollViewEventListener(NULL), +_scrollViewEventSelector(NULL) { } UIScrollView::~UIScrollView() { - _eventListener = NULL; - _eventSelector = NULL; + _scrollViewEventListener = NULL; + _scrollViewEventSelector = NULL; } UIScrollView* UIScrollView::create() @@ -1458,80 +1458,80 @@ void UIScrollView::checkChildInfo(int handleState,UIWidget* sender,const cocos2d void UIScrollView::scrollToTopEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_TOP); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_TOP); } } void UIScrollView::scrollToBottomEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM); } } void UIScrollView::scrollToLeftEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_LEFT); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_LEFT); } } void UIScrollView::scrollToRightEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT); } } void UIScrollView::scrollingEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); } } void UIScrollView::bounceTopEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); } } void UIScrollView::bounceBottomEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); } } void UIScrollView::bounceLeftEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); } } void UIScrollView::bounceRightEvent() { - if (_eventListener && _eventSelector) + if (_scrollViewEventListener && _scrollViewEventSelector) { - (_eventListener->*_eventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); + (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); } } -void UIScrollView::addEventListener(cocos2d::Object *target, SEL_ScrollViewEvent selector) +void UIScrollView::addEventListenerScrollView(cocos2d::Object *target, SEL_ScrollViewEvent selector) { - _eventListener = target; - _eventSelector = selector; + _scrollViewEventListener = target; + _scrollViewEventSelector = selector; } void UIScrollView::setDirection(SCROLLVIEW_DIR dir) diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 4d762930f8..94a6874376 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -231,7 +231,7 @@ public: /** * Add call back function called scrollview event triggered */ - void addEventListener(cocos2d::Object* target, SEL_ScrollViewEvent selector); + void addEventListenerScrollView(cocos2d::Object* target, SEL_ScrollViewEvent selector); //override "addChild" method of widget. virtual bool addChild(UIWidget* widget); @@ -382,8 +382,8 @@ protected: - cocos2d::Object* _eventListener; - SEL_ScrollViewEvent _eventSelector; + cocos2d::Object* _scrollViewEventListener; + SEL_ScrollViewEvent _scrollViewEventSelector; }; } diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index b5c90ccfb8..d8f2f95e86 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -46,8 +46,8 @@ _slidBallPressedTextureFile(""), _slidBallDisabledTextureFile(""), _capInsetsBarRenderer(cocos2d::Rect::ZERO), _capInsetsProgressBarRenderer(cocos2d::Rect::ZERO), -_slidPercentListener(NULL), -_slidPercentSelector(NULL), +_sliderEventListener(NULL), +_sliderEventSelector(NULL), _barTexType(UI_TEX_TYPE_LOCAL), _progressBarTexType(UI_TEX_TYPE_LOCAL), _ballNTexType(UI_TEX_TYPE_LOCAL), @@ -58,8 +58,8 @@ _ballDTexType(UI_TEX_TYPE_LOCAL) UISlider::~UISlider() { - _slidPercentListener = NULL; - _slidPercentSelector = NULL; + _sliderEventListener = NULL; + _sliderEventSelector = NULL; } UISlider* UISlider::create() @@ -411,17 +411,17 @@ float UISlider::getPercentWithBallPos(float px) return (((px-(-_barLength/2.0f))/_barLength)*100.0f); } -void UISlider::addEventListener(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) +void UISlider::addEventListenerSlider(cocos2d::Object *target, SEL_SlidPercentChangedEvent selector) { - _slidPercentListener = target; - _slidPercentSelector = selector; + _sliderEventListener = target; + _sliderEventSelector = selector; } void UISlider::percentChangedEvent() { - if (_slidPercentListener && _slidPercentSelector) + if (_sliderEventListener && _sliderEventSelector) { - (_slidPercentListener->*_slidPercentSelector)(this,SLIDER_PERCENTCHANGED); + (_sliderEventListener->*_sliderEventSelector)(this,SLIDER_PERCENTCHANGED); } } diff --git a/cocos/gui/UISlider.h b/cocos/gui/UISlider.h index 186af44d45..ff08ba1524 100644 --- a/cocos/gui/UISlider.h +++ b/cocos/gui/UISlider.h @@ -162,7 +162,7 @@ public: /** * Add call back function called when slider's percent has changed to slider. */ - void addEventListener(cocos2d::Object* target,SEL_SlidPercentChangedEvent selector); + void addEventListenerSlider(cocos2d::Object* target,SEL_SlidPercentChangedEvent selector); //override "onTouchBegan" method of widget. virtual bool onTouchBegan(const cocos2d::Point &touchPoint); @@ -226,8 +226,8 @@ protected: cocos2d::Rect _capInsetsBarRenderer; cocos2d::Rect _capInsetsProgressBarRenderer; - cocos2d::Object* _slidPercentListener; - SEL_SlidPercentChangedEvent _slidPercentSelector; + cocos2d::Object* _sliderEventListener; + SEL_SlidPercentChangedEvent _sliderEventSelector; TextureResType _barTexType; TextureResType _progressBarTexType; TextureResType _ballNTexType; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 6a95ac8605..75010d0261 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -275,16 +275,16 @@ _textFieldRenderer(NULL), _touchWidth(0.0f), _touchHeight(0.0f), _useTouchArea(false), -_eventListener(NULL), -_eventSelector(NULL), +_textFieldEventListener(NULL), +_textFieldEventSelector(NULL), _passwordStyleText("") { } UITextField::~UITextField() { - _eventListener = NULL; - _eventSelector = NULL; + _textFieldEventListener = NULL; + _textFieldEventSelector = NULL; } UITextField* UITextField::create() @@ -472,40 +472,40 @@ void UITextField::setDeleteBackward(bool deleteBackward) void UITextField::attachWithIMEEvent() { - if (_eventListener && _eventSelector) + if (_textFieldEventListener && _textFieldEventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_ATTACH_WITH_IME); + (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_ATTACH_WITH_IME); } } void UITextField::detachWithIMEEvent() { - if (_eventListener && _eventSelector) + if (_textFieldEventListener && _textFieldEventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_DETACH_WITH_IME); + (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_DETACH_WITH_IME); } } void UITextField::insertTextEvent() { - if (_eventListener && _eventSelector) + if (_textFieldEventListener && _textFieldEventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); + (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); } } void UITextField::deleteBackwardEvent() { - if (_eventListener && _eventSelector) + if (_textFieldEventListener && _textFieldEventSelector) { - (_eventListener->*_eventSelector)(this, TEXTFIELD_EVENT_DELETE_BACKWARD); + (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_DELETE_BACKWARD); } } -void UITextField::addEventListener(cocos2d::Object *target, SEL_TextFieldEvent selecor) +void UITextField::addEventListenerTextField(cocos2d::Object *target, SEL_TextFieldEvent selecor) { - _eventListener = target; - _eventSelector = selecor; + _textFieldEventListener = target; + _textFieldEventSelector = selecor; } void UITextField::setAnchorPoint(const cocos2d::Point &pt) diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index fc90ea9466..6a61faed08 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -132,7 +132,7 @@ public: void setInsertText(bool insertText); bool getDeleteBackward(); void setDeleteBackward(bool deleteBackward); - void addEventListener(cocos2d::Object* target, SEL_TextFieldEvent selecor); + void addEventListenerTextField(cocos2d::Object* target, SEL_TextFieldEvent selecor); virtual void setAnchorPoint(const cocos2d::Point &pt); virtual void setColor(const cocos2d::Color3B &color); @@ -163,8 +163,8 @@ protected: float _touchHeight; bool _useTouchArea; - cocos2d::Object* _eventListener; - SEL_TextFieldEvent _eventSelector; + cocos2d::Object* _textFieldEventListener; + SEL_TextFieldEvent _textFieldEventSelector; std::string _passwordStyleText; }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp index 66b0c64a96..d28264ab46 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp @@ -54,7 +54,7 @@ bool UICheckBoxTest::init() "cocosgui/check_box_active_disable.png"); checkBox->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); - checkBox->addEventListener(this, checkboxselectedeventselector(UICheckBoxTest::selectedEvent)); + checkBox->addEventListenerCheckBox(this, checkboxselectedeventselector(UICheckBoxTest::selectedEvent)); // checkBox->addSelectEvent(this, coco_selectselector(UICheckBoxTest::selectedEvent)); m_pUiLayer->addWidget(checkBox); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp index ce5028ae35..309e9c2264 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp @@ -79,7 +79,7 @@ bool UIPageViewTest::init() pageView->addPage(layout); } - pageView->addEventListener(this, pagevieweventselector(UIPageViewTest::pageViewEvent)); + pageView->addEventListenerPageView(this, pagevieweventselector(UIPageViewTest::pageViewEvent)); m_pUiLayer->addWidget(pageView); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp index 2749e061ab..cae91130ea 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp @@ -52,7 +52,7 @@ bool UISliderTest::init() slider->loadSlidBallTextures("cocosgui/sliderThumb.png", "cocosgui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosgui/sliderProgress.png"); slider->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); - slider->addEventListener(this, sliderpercentchangedselector(UISliderTest::percentChangedEvent)); + slider->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest::percentChangedEvent)); m_pUiLayer->addWidget(slider); return true; @@ -116,7 +116,7 @@ bool UISliderTest_Scale9::init() slider->setCapInsets(Rect(0, 0, 0, 0)); slider->setSize(Size(250, 10)); slider->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); - slider->addEventListener(this, sliderpercentchangedselector(UISliderTest_Scale9::percentChangedEvent)); + slider->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest_Scale9::percentChangedEvent)); m_pUiLayer->addWidget(slider); return true; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index c486c5be3a..34534d008a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -51,7 +51,7 @@ bool UITextFieldTest::init() textField->setFontSize(30); textField->setPlaceHolder("input words here"); textField->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); - textField->addEventListener(this, textfieldeventselector(UITextFieldTest::textFieldEvent)); + textField->addEventListenerTextField(this, textfieldeventselector(UITextFieldTest::textFieldEvent)); m_pUiLayer->addWidget(textField); return true; @@ -139,7 +139,7 @@ bool UITextFieldTest_MaxLength::init() textField->setFontSize(30); textField->setPlaceHolder("input words here"); textField->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 2.0f)); - textField->addEventListener(this, textfieldeventselector(UITextFieldTest_MaxLength::textFieldEvent)); + textField->addEventListenerTextField(this, textfieldeventselector(UITextFieldTest_MaxLength::textFieldEvent)); m_pUiLayer->addWidget(textField); return true; @@ -233,7 +233,7 @@ bool UITextFieldTest_Password::init() textField->setFontSize(30); textField->setPlaceHolder("input password here"); textField->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 2.0f)); - textField->addEventListener(this, textfieldeventselector(UITextFieldTest_Password::textFieldEvent)); + textField->addEventListenerTextField(this, textfieldeventselector(UITextFieldTest_Password::textFieldEvent)); m_pUiLayer->addWidget(textField); return true; From 8a5084effa20f70f5199514e680f7907356cde05 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 8 Nov 2013 20:29:49 +0800 Subject: [PATCH 489/557] add list view event --- cocos/gui/UIListView.cpp | 45 +++++++++++++++++++++++++++++++++++++++- cocos/gui/UIListView.h | 17 +++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 81baaad41d..3017d1e929 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -32,7 +32,10 @@ UIListView::UIListView(): _model(NULL), _items(NULL), _gravity(LISTVIEW_GRAVITY_CENTER_HORIZONTAL), -_itemsMargin(0.0f) +_itemsMargin(0.0f), +_listViewEventListener(NULL), +_listViewEventSelector(NULL), +_curSelectedIndex(0) { } @@ -41,6 +44,8 @@ UIListView::~UIListView() { _items->removeAllObjects(); CC_SAFE_RELEASE(_items); + _listViewEventListener = NULL; + _listViewEventSelector = NULL; } UIListView* UIListView::create() @@ -378,6 +383,44 @@ void UIListView::refreshView() updateInnerContainerSize(); doLayout(); } + +void UIListView::addEventListenerListView(cocos2d::Object *target, SEL_ListViewEvent selector) +{ + _listViewEventListener = target; + _listViewEventSelector = selector; +} + +void UIListView::selectedItemEvent() +{ + if (_listViewEventListener && _listViewEventSelector) + { + (_listViewEventListener->*_listViewEventSelector)(this, LISTVIEW_ONSELECEDTITEM); + } +} + +void UIListView::interceptTouchEvent(int handleState, gui::UIWidget *sender, const cocos2d::Point &touchPoint) +{ + UIScrollView::interceptTouchEvent(handleState, sender, touchPoint); + if (handleState != 1) + { + UIWidget* parent = sender; + while (parent) + { + if (parent && parent->getParent() == _innerContainer) + { + _curSelectedIndex = getIndex(parent); + break; + } + parent = parent->getParent(); + } + selectedItemEvent(); + } +} + +int UIListView::getCurSelectedIndex() const +{ + return _curSelectedIndex; +} void UIListView::onSizeChanged() { diff --git a/cocos/gui/UIListView.h b/cocos/gui/UIListView.h index c78d06ace2..42fd7f15be 100644 --- a/cocos/gui/UIListView.h +++ b/cocos/gui/UIListView.h @@ -40,6 +40,14 @@ typedef enum LISTVIEW_GRAVITY_BOTTOM, LISTVIEW_GRAVITY_CENTER_VERTICAL, }ListViewGravity; + +typedef enum +{ + LISTVIEW_ONSELECEDTITEM +}ListViewEventType; + +typedef void (cocos2d::Object::*SEL_ListViewEvent)(cocos2d::Object*,ListViewEventType); +#define listvieweventselector(_SELECTOR) (SEL_ListViewEvent)(&_SELECTOR) class UIListView : public UIScrollView { @@ -145,6 +153,10 @@ public: */ void refreshView(); + int getCurSelectedIndex() const; + + void addEventListenerListView(cocos2d::Object* target, SEL_ListViewEvent selector); + /** * Changes scroll direction of scrollview. * @@ -164,12 +176,17 @@ protected: virtual UIWidget* createCloneInstance(); virtual void copySpecialProperties(UIWidget* model); virtual void copyClonedWidgetChildren(UIWidget* model); + void selectedItemEvent(); + virtual void interceptTouchEvent(int handleState,UIWidget* sender,const cocos2d::Point &touchPoint); protected: UIWidget* _model; cocos2d::Array* _items; ListViewGravity _gravity; float _itemsMargin; + cocos2d::Object* _listViewEventListener; + SEL_ListViewEvent _listViewEventSelector; + int _curSelectedIndex; }; } From a0f794b7df92d3b17ad0bda3f572afb590882213 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 8 Nov 2013 23:26:44 +0800 Subject: [PATCH 490/557] optimize layout --- cocos/gui/UILayout.cpp | 12 +++++++++++- cocos/gui/UIListView.cpp | 1 - cocos/gui/UIWidget.h | 3 ++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 70b66a0b56..84c65232d7 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -129,7 +129,17 @@ void UILayout::setClippingEnabled(bool able) void UILayout::onSizeChanged() { DYNAMIC_CAST_CLIPPINGLAYER->setClippingSize(_size); - doLayout(); + if (strcmp(getDescription(), "Layout") == 0) + { + cocos2d::ccArray* arrayChildren = _children->data; + int length = arrayChildren->num; + for (int i=0; iarr[i]; + child->updateSizeAndPosition(); + } + doLayout(); + } if (_backGroundImage) { _backGroundImage->setPosition(cocos2d::Point(_size.width/2.0f, _size.height/2.0f)); diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 3017d1e929..c6e076821d 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -381,7 +381,6 @@ void UIListView::refreshView() remedyLayoutParameter(item); } updateInnerContainerSize(); - doLayout(); } void UIListView::addEventListenerListView(cocos2d::Object *target, SEL_ListViewEvent selector) diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index 02db42e731..741d580fee 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -881,6 +881,8 @@ public: virtual void onEnter(); virtual void onExit(); + void updateSizeAndPosition(); + virtual Object* getUserObject() { return _userObject; } /** * @js NA @@ -926,7 +928,6 @@ protected: void cancelUpEvent(); void longClickEvent(); void updateAnchorPoint(); - void updateSizeAndPosition(); void copyProperties(UIWidget* model); virtual UIWidget* createCloneInstance(); virtual void copySpecialProperties(UIWidget* model); From 5faae4a51ea262b911e40320c481feb69c505c0a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 11:30:50 -0800 Subject: [PATCH 492/557] removes exe bit from text files --- .../android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java | 0 .../android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java | 0 .../platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java | 0 cocos/2d/platform/ios/EAGLView.h | 0 cocos/2d/platform/ios/OpenGL_Internal.h | 0 cocos/2d/platform/mac/EAGLView.h | 0 cocos/audio/mac/CDXMacOSXSupport.h | 0 cocos/audio/mac/CDXMacOSXSupport.mm | 0 cocos/audio/proj.linux/.cproject | 0 cocos/audio/proj.linux/.project | 0 cocos/editor-support/cocostudio/CCSGUIReader.cpp | 0 cocos/editor-support/cocostudio/CCSGUIReader.h | 0 cocos/scripting/lua/script/json.lua | 0 13 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java mode change 100755 => 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java mode change 100755 => 100644 cocos/2d/platform/ios/EAGLView.h mode change 100755 => 100644 cocos/2d/platform/ios/OpenGL_Internal.h mode change 100755 => 100644 cocos/2d/platform/mac/EAGLView.h mode change 100755 => 100644 cocos/audio/mac/CDXMacOSXSupport.h mode change 100755 => 100644 cocos/audio/mac/CDXMacOSXSupport.mm mode change 100755 => 100644 cocos/audio/proj.linux/.cproject mode change 100755 => 100644 cocos/audio/proj.linux/.project mode change 100755 => 100644 cocos/editor-support/cocostudio/CCSGUIReader.cpp mode change 100755 => 100644 cocos/editor-support/cocostudio/CCSGUIReader.h mode change 100755 => 100644 cocos/scripting/lua/script/json.lua diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/ios/EAGLView.h b/cocos/2d/platform/ios/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/ios/OpenGL_Internal.h b/cocos/2d/platform/ios/OpenGL_Internal.h old mode 100755 new mode 100644 diff --git a/cocos/2d/platform/mac/EAGLView.h b/cocos/2d/platform/mac/EAGLView.h old mode 100755 new mode 100644 diff --git a/cocos/audio/mac/CDXMacOSXSupport.h b/cocos/audio/mac/CDXMacOSXSupport.h old mode 100755 new mode 100644 diff --git a/cocos/audio/mac/CDXMacOSXSupport.mm b/cocos/audio/mac/CDXMacOSXSupport.mm old mode 100755 new mode 100644 diff --git a/cocos/audio/proj.linux/.cproject b/cocos/audio/proj.linux/.cproject old mode 100755 new mode 100644 diff --git a/cocos/audio/proj.linux/.project b/cocos/audio/proj.linux/.project old mode 100755 new mode 100644 diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp old mode 100755 new mode 100644 diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h old mode 100755 new mode 100644 diff --git a/cocos/scripting/lua/script/json.lua b/cocos/scripting/lua/script/json.lua old mode 100755 new mode 100644 From f7bae6e6cb3f43391db5b54f2b6f3304d80844f6 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:09:21 -0800 Subject: [PATCH 493/557] coding style migrated to version 3.274 --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 51a1dc866d..57c2f6e178 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -55fe4bd3605531a58a565c46eec20dee0f81ff97 \ No newline at end of file +b8582573e1c08366c74eb53e1b9d47abb7b87f31 \ No newline at end of file From 614c6469ff930e68a242791a252c29fe7ab54531 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:10:38 -0800 Subject: [PATCH 494/557] Adds TOC --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 57c2f6e178..65198295ec 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -b8582573e1c08366c74eb53e1b9d47abb7b87f31 \ No newline at end of file +8944142222e4befc64d10add9f9efae2f8172191 \ No newline at end of file From 173b5f634932d94e9f7b300574d3d915985b907a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 19:13:50 -0800 Subject: [PATCH 495/557] fixes markdown --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index 65198295ec..d995f1bb82 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -8944142222e4befc64d10add9f9efae2f8172191 \ No newline at end of file +53b75602e396f08d8700d154b7954d678c2d5894 \ No newline at end of file From 94ad801f3dfd9329423535a778d3a9d57dc993d2 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 20:53:34 -0800 Subject: [PATCH 496/557] Update CODING_STYLE.md --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index d995f1bb82..c8730de5d9 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -53b75602e396f08d8700d154b7954d678c2d5894 \ No newline at end of file +c563be83fa634d5f28d62f647ec099ece413b17a \ No newline at end of file From 9f16bfadd152e14ea60e24695fd7e3655753b46a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 8 Nov 2013 20:59:27 -0800 Subject: [PATCH 497/557] updated TOC --- docs/CODING_STYLE.md.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CODING_STYLE.md.REMOVED.git-id b/docs/CODING_STYLE.md.REMOVED.git-id index c8730de5d9..2a00974e4b 100644 --- a/docs/CODING_STYLE.md.REMOVED.git-id +++ b/docs/CODING_STYLE.md.REMOVED.git-id @@ -1 +1 @@ -c563be83fa634d5f28d62f647ec099ece413b17a \ No newline at end of file +f86eb12e6d4835f93bd6f59d860970bcd2f74128 \ No newline at end of file From f3a5245bfa9a0a36471b0248cc68b4b58ddfb103 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 9 Nov 2013 18:11:57 +0800 Subject: [PATCH 498/557] Triggers an assert only onTouchBegan is nullptr for EventListenerTouchOneByOne. Fixes comments for checkAvailable. --- cocos/2d/CCEventListenerTouch.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCEventListenerTouch.cpp b/cocos/2d/CCEventListenerTouch.cpp index 1367645452..20e620910a 100644 --- a/cocos/2d/CCEventListenerTouch.cpp +++ b/cocos/2d/CCEventListenerTouch.cpp @@ -75,10 +75,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::create() bool EventListenerTouchOneByOne::checkAvailable() { - if (onTouchBegan == nullptr && onTouchMoved == nullptr - && onTouchEnded == nullptr && onTouchCancelled == nullptr) + if (onTouchBegan == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchOneByOne!"); return false; } @@ -150,7 +149,7 @@ bool EventListenerTouchAllAtOnce::checkAvailable() if (onTouchesBegan == nullptr && onTouchesMoved == nullptr && onTouchesEnded == nullptr && onTouchesCancelled == nullptr) { - CCASSERT(false, "Invalid TouchEventListener."); + CCASSERT(false, "Invalid EventListenerTouchAllAtOnce!"); return false; } From 4fba832fb1f9200923777a0f66a3f54e3d58d37b Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 9 Nov 2013 21:05:17 +0800 Subject: [PATCH 499/557] Return non-zero if ndk build fails. --- build/android-build.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index d1a272c2db..c630010ef8 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -95,7 +95,8 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) else: command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) - os.system(command) + if os.system(command) != 0: + raise Exception("Build project [ " + app_android_root + " ] fails!") def copy_files(src, dst): @@ -205,4 +206,8 @@ if __name__ == '__main__': if len(args) == 0: usage() else: - build_samples(args, opts.ndk_build_param) + try: + build_samples(args, opts.ndk_build_param) + except Exception as e: + print e + sys.exit(1) From c4e70387f7395f7161a3f7b3293f4218787b809a Mon Sep 17 00:00:00 2001 From: psi Date: Sat, 9 Nov 2013 23:02:45 +0900 Subject: [PATCH 500/557] Close display --- cocos/2d/platform/linux/CCDevice.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/2d/platform/linux/CCDevice.cpp b/cocos/2d/platform/linux/CCDevice.cpp index 8c4d97ecd2..3b3c962413 100644 --- a/cocos/2d/platform/linux/CCDevice.cpp +++ b/cocos/2d/platform/linux/CCDevice.cpp @@ -24,6 +24,7 @@ int Device::getDPI() ((double) DisplayWidthMM(dpy,scr))); dpi = (int) (xres + 0.5); //printf("dpi = %d\n", dpi); + XCloseDisplay (dpy); } return dpi; } From 5e36021d54ecd0d08aaae6c8d1919246e1db72e6 Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:44:15 +0900 Subject: [PATCH 501/557] [Win32] fix argument type. - argument of interface is a long type. --- cocos/2d/platform/win32/CCFileUtilsWin32.cpp | 2 +- cocos/2d/platform/win32/CCFileUtilsWin32.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp index a5c94dac90..216797bd9e 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp @@ -121,7 +121,7 @@ bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const return false; } -unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, unsigned long* size) +unsigned char* FileUtilsWin32::getFileData(const char* filename, const char* mode, long* size) { unsigned char * pBuffer = NULL; CCASSERT(filename != NULL && size != NULL && mode != NULL, "Invalid parameters."); diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.h b/cocos/2d/platform/win32/CCFileUtilsWin32.h index 4f01adabeb..5c88d97cf9 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.h +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.h @@ -58,7 +58,7 @@ protected: * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const char* filename, const char* mode, unsigned long * size) override; + virtual unsigned char* getFileData(const char* filename, const char* mode, long * size) override; /** * Gets full path for filename, resolution directory and search path. From 3d23ca328ee0629cd95aff366134ede33e62f92f Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:56:24 +0900 Subject: [PATCH 502/557] [Win32] fix compile error. - fix C2552 error in VS2012. --- cocos/gui/UILayout.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 70b66a0b56..a7af98c1b8 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -953,7 +953,7 @@ bool UIRectClippingNode::init() rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); rect[3] = cocos2d::Point(0, _clippingSize.height); - cocos2d::Color4F green = {0, 1, 0, 1}; + cocos2d::Color4F green(0, 1, 0, 1); _innerStencil->drawPolygon(rect, 4, green, 0, green); if (cocos2d::ClippingNode::init(_innerStencil)) { @@ -971,7 +971,7 @@ void UIRectClippingNode::setClippingSize(const cocos2d::Size &size) rect[1] = cocos2d::Point(_clippingSize.width, 0); rect[2] = cocos2d::Point(_clippingSize.width, _clippingSize.height); rect[3] = cocos2d::Point(0, _clippingSize.height); - cocos2d::Color4F green = {0, 1, 0, 1}; + cocos2d::Color4F green(0, 1, 0, 1); _innerStencil->clear(); _innerStencil->drawPolygon(rect, 4, green, 0, green); } From e132142689e84e3caba7122902cdf426f0730e8e Mon Sep 17 00:00:00 2001 From: "Lee, Jae-Hong" Date: Sat, 9 Nov 2013 23:57:18 +0900 Subject: [PATCH 503/557] [Win32] Update libGUI project - Update files list. --- cocos/gui/proj.win32/libGUI.vcxproj | 10 +++---- cocos/gui/proj.win32/libGUI.vcxproj.filters | 30 +++++++++------------ 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/cocos/gui/proj.win32/libGUI.vcxproj b/cocos/gui/proj.win32/libGUI.vcxproj index b225eaa127..2712ae3900 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj +++ b/cocos/gui/proj.win32/libGUI.vcxproj @@ -12,11 +12,8 @@ - - - @@ -24,7 +21,9 @@ + + @@ -37,11 +36,8 @@ - - - @@ -49,7 +45,9 @@ + + diff --git a/cocos/gui/proj.win32/libGUI.vcxproj.filters b/cocos/gui/proj.win32/libGUI.vcxproj.filters index 12f0d385ab..092f28f7e0 100644 --- a/cocos/gui/proj.win32/libGUI.vcxproj.filters +++ b/cocos/gui/proj.win32/libGUI.vcxproj.filters @@ -24,9 +24,6 @@ UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -72,12 +69,6 @@ System - - Layouts - - - Layouts - Layouts @@ -87,14 +78,17 @@ BaseClasses + + Layouts + + + Layouts + UIWidgets\ScrollWidget - - UIWidgets\ScrollWidget - UIWidgets\ScrollWidget @@ -140,12 +134,6 @@ System - - Layouts - - - Layouts - Layouts @@ -155,5 +143,11 @@ BaseClasses + + Layouts + + + Layouts + \ No newline at end of file From d4dbc7a4424992d5bb308ea4ae08691e635a5ad1 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Sun, 10 Nov 2013 09:21:33 +0800 Subject: [PATCH 504/557] Add conversion config for long type --- .../lua/bindings/LuaBasicConversions.cpp | 24 +++++++++++++++++++ .../lua/bindings/LuaBasicConversions.h | 1 + tools/bindings-generator | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index 1914d3a930..4c91daa42b 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -283,6 +283,30 @@ bool luaval_to_point(lua_State* L,int lo,Point* outValue) return ok; } +bool luaval_to_long(lua_State* L,int lo, long* outValue) +{ + if (NULL == L || NULL == outValue) + return false; + + bool ok = true; + + tolua_Error tolua_err; + if (!tolua_isnumber(L,lo,0,&tolua_err)) + { +#if COCOS2D_DEBUG >=1 + luaval_to_native_err(L,"#ferror:",&tolua_err); +#endif + ok = false; + } + + if (ok) + { + *outValue = (long)tolua_tonumber(L, lo, 0); + } + + return ok; +} + bool luaval_to_size(lua_State* L,int lo,Size* outValue) { if (NULL == L || NULL == outValue) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 20167170df..2e2e525993 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -30,6 +30,7 @@ extern bool luaval_to_boolean(lua_State* L,int lo,bool* outValue); extern bool luaval_to_number(lua_State* L,int lo,double* outValue); extern bool luaval_to_long_long(lua_State* L,int lo,long long* outValue); extern bool luaval_to_std_string(lua_State* L, int lo, std::string* outValue); +extern bool luaval_to_long(lua_State* L,int lo, long* outValue); extern bool luaval_to_point(lua_State* L,int lo,Point* outValue); extern bool luaval_to_size(lua_State* L,int lo,Size* outValue); diff --git a/tools/bindings-generator b/tools/bindings-generator index d41959ab0b..bf34fb73c4 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit d41959ab0b15c20aa0802ab5c9ef92be7b742bd4 +Subproject commit bf34fb73c4adece7b0c8194aa8ab57c5ce60fc58 From fa1a5c3735b122b145d08e3563e234257421c741 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Sun, 10 Nov 2013 11:03:27 +0800 Subject: [PATCH 505/557] Add conversion config for long type --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index bf34fb73c4..7ccbabbaa6 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit bf34fb73c4adece7b0c8194aa8ab57c5ce60fc58 +Subproject commit 7ccbabbaa677607048c511b33cb6d83b2081220e From 6e6c63e1112df6a7e2187f8114a0db1a86786f5a Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sun, 10 Nov 2013 03:29:03 +0000 Subject: [PATCH 506/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 7199547f2f..c46cc8ed45 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 +Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 From c75c20de043a30c9383d25384cf75623c7baa1a0 Mon Sep 17 00:00:00 2001 From: dualface Date: Sun, 10 Nov 2013 11:49:52 +0800 Subject: [PATCH 507/557] fix Lua 5.2 compatibility --- cocos/scripting/lua/bindings/tolua_fix.c | 48 ++++++++++++------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/cocos/scripting/lua/bindings/tolua_fix.c b/cocos/scripting/lua/bindings/tolua_fix.c index 259a05242e..f03dd59b5f 100644 --- a/cocos/scripting/lua/bindings/tolua_fix.c +++ b/cocos/scripting/lua/bindings/tolua_fix.c @@ -9,7 +9,7 @@ TOLUA_API void toluafix_open(lua_State* L) lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_newtable(L); lua_rawset(L, LUA_REGISTRYINDEX); @@ -30,29 +30,29 @@ TOLUA_API int toluafix_pushusertype_ccobject(lua_State* L, lua_pushnil(L); return -1; } - + if (*p_refid == 0) { *p_refid = refid; - + lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushlightuserdata(L, ptr); /* stack: refid_ptr refid ptr */ - + lua_rawset(L, -3); /* refid_ptr[refid] = ptr, stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - + lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushstring(L, type); /* stack: refid_type refid type */ lua_rawset(L, -3); /* refid_type[refid] = type, stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + //printf("[LUA] push CCObject OK - refid: %d, ptr: %x, type: %s\n", *p_refid, (int)ptr, type); } - + tolua_pushusertype(L, ptr, type); return 0; } @@ -63,7 +63,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) const char* type = NULL; void** ud = NULL; if (refid == 0) return -1; - + // get ptr from tolua_refid_ptr_mapping lua_pushstring(L, TOLUA_REFID_PTR_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_ptr */ @@ -78,14 +78,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) // printf("[LUA ERROR] remove CCObject with NULL ptr, refid: %d\n", refid); return -2; } - + // remove ptr from tolua_refid_ptr_mapping lua_pushinteger(L, refid); /* stack: refid_ptr refid */ lua_pushnil(L); /* stack: refid_ptr refid nil */ lua_rawset(L, -3); /* delete refid_ptr[refid], stack: refid_ptr */ lua_pop(L, 1); /* stack: - */ - - + + // get type from tolua_refid_type_mapping lua_pushstring(L, TOLUA_REFID_TYPE_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: refid_type */ @@ -97,16 +97,16 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) printf("[LUA ERROR] remove CCObject with NULL type, refid: %d, ptr: %p\n", refid, ptr); return -1; } - + type = lua_tostring(L, -1); lua_pop(L, 1); /* stack: refid_type */ - + // remove type from tolua_refid_type_mapping lua_pushinteger(L, refid); /* stack: refid_type refid */ lua_pushnil(L); /* stack: refid_type refid nil */ lua_rawset(L, -3); /* delete refid_type[refid], stack: refid_type */ lua_pop(L, 1); /* stack: - */ - + // get ubox luaL_getmetatable(L, type); /* stack: mt */ lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ @@ -118,7 +118,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pushstring(L, "tolua_ubox"); /* stack: mt key */ lua_rawget(L, LUA_REGISTRYINDEX); /* stack: mt ubox */ }; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_rawget(L,-2); /* stack: mt ubox ud */ if (lua_isnil(L, -1)) @@ -130,7 +130,7 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) } // cleanup peertable - lua_pushvalue(L, TOLUA_NOPEER); + lua_pushvalue(L, LUA_REGISTRYINDEX); lua_setfenv(L, -2); ud = (void**)lua_touserdata(L, -1); @@ -141,14 +141,14 @@ TOLUA_API int toluafix_remove_ccobject_by_refid(lua_State* L, int refid) lua_pop(L, 2); return -1; } - + // clean userdata *ud = NULL; - + lua_pushlightuserdata(L, ptr); /* stack: mt ubox ptr */ lua_pushnil(L); /* stack: mt ubox ptr nil */ lua_rawset(L, -3); /* ubox[ptr] = nil, stack: mt ubox */ - + lua_pop(L, 2); //printf("[LUA] remove CCObject, refid: %d, ptr: %x, type: %s\n", refid, (int)ptr, type); return 0; @@ -158,19 +158,19 @@ TOLUA_API int toluafix_ref_function(lua_State* L, int lo, int def) { // function at lo if (!lua_isfunction(L, lo)) return 0; - + s_function_ref_id++; - + lua_pushstring(L, TOLUA_REFID_FUNCTION_MAPPING); lua_rawget(L, LUA_REGISTRYINDEX); /* stack: fun ... refid_fun */ lua_pushinteger(L, s_function_ref_id); /* stack: fun ... refid_fun refid */ lua_pushvalue(L, lo); /* stack: fun ... refid_fun refid fun */ - + lua_rawset(L, -3); /* refid_fun[refid] = fun, stack: fun ... refid_ptr */ lua_pop(L, 1); /* stack: fun ... */ - + return s_function_ref_id; - + // lua_pushvalue(L, lo); /* stack: ... func */ // return luaL_ref(L, LUA_REGISTRYINDEX); } From 90df6fc763c3a29f0e90b94a46ffb71394ef6ffa Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Sun, 10 Nov 2013 08:25:01 -0300 Subject: [PATCH 508/557] fixed typos --- tools/project-creator/create_project.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/project-creator/create_project.py b/tools/project-creator/create_project.py index be6e38babc..640fa4e038 100755 --- a/tools/project-creator/create_project.py +++ b/tools/project-creator/create_project.py @@ -30,7 +30,7 @@ def checkParams(): metavar="PROGRAMMING_NAME", type="choice", choices=["cpp", "lua", "javascript"], - help="Major programing language you want to used, should be [cpp | lua | javascript]") + help="Major programming language you want to use, should be [cpp | lua | javascript]") #parse the params (opts, args) = parser.parse_args() From 1f742b66756dabaf8e66f421741cb2a76259a0ad Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 20:56:40 +0800 Subject: [PATCH 509/557] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 37e302de05..71b6680d05 100644 --- a/AUTHORS +++ b/AUTHORS @@ -643,6 +643,9 @@ Developers: Fixed a bug that EventListeners can't be removed sometimes. Fixed a bug that the data size has to be specified when parsing XML using TinyXML. + Luis Parravicini (luisparravicini) + Fixed typos in create_project.py. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From ef92efcd79ec1823f5264ec36486af346cf49c78 Mon Sep 17 00:00:00 2001 From: bopohaa Date: Mon, 11 Nov 2013 02:28:27 +0300 Subject: [PATCH 510/557] Update CCImageCommon_cpp.h webp don't work for me --- cocos/2d/platform/CCImageCommon_cpp.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index f2fc7a9a08..bf1f856e39 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -1737,12 +1737,12 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen) _width = config.input.width; _height = config.input.height; - int bufferSize = _width * _height * 4; - _data = new unsigned char[bufferSize]; + _dataLen = _width * _height * 4; + _data = new unsigned char[_dataLen]; config.output.u.RGBA.rgba = static_cast(_data); config.output.u.RGBA.stride = _width * 4; - config.output.u.RGBA.size = bufferSize; + config.output.u.RGBA.size = _dataLen; config.output.is_external_memory = 1; if (WebPDecode(static_cast(data), dataLen, &config) != VP8_STATUS_OK) From a6c85a3906b22a5ae38436cd08557e30d3a105d3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:23:05 +0800 Subject: [PATCH 511/557] issue #3137: Disabling Accelerometer when layer is destroyed. --- cocos/editor-support/cocostudio/CCInputDelegate.cpp | 3 +++ .../Classes/AccelerometerTest/AccelerometerTest.cpp | 1 + samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp | 10 ++++++++++ samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h | 2 ++ .../Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp | 2 ++ .../Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp | 5 +++++ samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h | 1 + 7 files changed, 24 insertions(+) diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index a134e3cdfe..03ac5030a7 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -47,6 +47,7 @@ InputDelegate::~InputDelegate(void) dispatcher->removeEventListener(_touchListener); dispatcher->removeEventListener(_keyboardListener); dispatcher->removeEventListener(_accelerometerListener); + Device::setAccelerometerEnabled(false); } bool InputDelegate::onTouchBegan(Touch *pTouch, Event *pEvent) @@ -196,6 +197,8 @@ void InputDelegate::setAccelerometerEnabled(bool enabled) dispatcher->removeEventListener(_accelerometerListener); _accelerometerListener = nullptr; + Device::setAccelerometerEnabled(enabled); + if (enabled) { auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(InputDelegate::onAcceleration, this)); diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp index 5bc3d6a7ed..b1a8dcfcf9 100644 --- a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp @@ -21,6 +21,7 @@ AccelerometerTest::AccelerometerTest(void) AccelerometerTest::~AccelerometerTest(void) { _ball->release(); + Device::setAccelerometerEnabled(false); } std::string AccelerometerTest::title() diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp index b7a60bb7a8..7fa35c81d1 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp @@ -10,6 +10,11 @@ // Bug624Layer // //////////////////////////////////////////////////////// +Bug624Layer::~Bug624Layer() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer::init() { if(BugsTestBaseLayer::init()) @@ -51,6 +56,11 @@ void Bug624Layer::onAcceleration(Acceleration* acc, Event* event) // Bug624Layer2 // //////////////////////////////////////////////////////// +Bug624Layer2::~Bug624Layer2() +{ + Device::setAccelerometerEnabled(false); +} + bool Bug624Layer2::init() { if(BugsTestBaseLayer::init()) diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h index b5db348e67..6542ad95ba 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h +++ b/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h @@ -6,6 +6,7 @@ class Bug624Layer : public BugsTestBaseLayer { public: + virtual ~Bug624Layer(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); @@ -16,6 +17,7 @@ public: class Bug624Layer2 : public BugsTestBaseLayer { public: + virtual ~Bug624Layer2(); virtual bool init(); void switchLayer(float dt); virtual void onAcceleration(Acceleration* acc, Event* event); diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 4a4cd5e027..99c01dec70 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -91,6 +91,8 @@ ChipmunkTestLayer::~ChipmunkTestLayer() } cpSpaceFree( _space ); + + Device::setAccelerometerEnabled(false); } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index cdc909b306..29f4b68e6d 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -199,6 +199,11 @@ void PhysicsDemo::toggleDebugCallback(Object* sender) #endif } +PhysicsDemoClickAdd::~PhysicsDemoClickAdd() +{ + Device::setAccelerometerEnabled(false); +} + void PhysicsDemoClickAdd::onEnter() { PhysicsDemo::onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 4ca37bd77b..a3ccc76e57 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -56,6 +56,7 @@ protected: class PhysicsDemoClickAdd : public PhysicsDemo { public: + virtual ~PhysicsDemoClickAdd(); void onEnter() override; std::string subtitle() override; From 0c4b6e7a3700853a1637310b38b87963a7926e78 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:40:51 +0800 Subject: [PATCH 512/557] Removing JSB Version since JSB source codes will be updated with cocos2d-x. Also, remove some unused codes. --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 2 +- .../javascript/bindings/js_bindings_core.cpp | 11 ----------- .../scripting/javascript/bindings/js_bindings_core.h | 5 ----- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 580a3b845e..263e2c0fae 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -246,7 +246,7 @@ JSBool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) } char version[256]; - snprintf(version, sizeof(version)-1, "%s - %s", cocos2dVersion(), JSB_version); + snprintf(version, sizeof(version)-1, "%s", cocos2dVersion()); JSString * js_version = JS_InternString(cx, version); jsval ret = STRING_TO_JSVAL(js_version); diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index fbb6e808fb..645f9fa94b 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -43,17 +43,6 @@ typedef struct _hashJSObject static tHashJSObject *hash = NULL; static tHashJSObject *reverse_hash = NULL; -// Globals -char* JSB_association_proxy_key = NULL; - -const char* JSB_version = "0.3-beta"; - - -static void its_finalize(JSFreeOp *fop, JSObject *obj) -{ - CCLOGINFO("Finalizing global class"); -} - //#pragma mark JSBCore - Helper free functions static void reportError(JSContext *cx, const char *message, JSErrorReport *report) { diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.h b/cocos/scripting/javascript/bindings/js_bindings_core.h index 958b969b2a..33553a9287 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.h +++ b/cocos/scripting/javascript/bindings/js_bindings_core.h @@ -30,10 +30,6 @@ #include "chipmunk.h" #include "SimpleAudioEngine.h" -// Globals -// one shared key for associations -extern char * JSB_association_proxy_key; - #ifdef __cplusplus extern "C" { #endif @@ -77,7 +73,6 @@ extern "C" { // needed for callbacks. It does nothing. JSBool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp); - extern const char* JSB_version; #ifdef __cplusplus } #endif From 27b82f8f67c4a0c82523a2d4f3a113ec10f118e4 Mon Sep 17 00:00:00 2001 From: Marc Lepage Date: Sun, 10 Nov 2013 22:00:50 -0500 Subject: [PATCH 513/557] Fix typos and other trivial cleanup --- cocos/2d/CCSprite.h | 162 ++++++++++++++++++++++---------------------- 1 file changed, 81 insertions(+), 81 deletions(-) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 0c0b652972..317effad84 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __SPITE_NODE_CCSPRITE_H__ -#define __SPITE_NODE_CCSPRITE_H__ +#ifndef __SPRITE_NODE_CCSPRITE_H__ +#define __SPRITE_NODE_CCSPRITE_H__ #include "CCNode.h" #include "CCProtocols.h" @@ -54,7 +54,7 @@ struct transformValues_; * @{ */ -/** +/** * Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) * * Sprite can be created with an image, or with a sub-rectangle of an image. @@ -88,14 +88,14 @@ public: /// @{ /// @name Creators - + /** * Creates an empty sprite without texture. You can call setTexture method subsequently. * * @return An empty sprite object that is marked as autoreleased. */ static Sprite* create(); - + /** * Creates a sprite with an image filename. * @@ -106,7 +106,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* create(const std::string& filename); - + /** * Creates a sprite with an image filename and a rect. * @@ -115,7 +115,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* create(const std::string& filename, const Rect& rect); - + /** * Creates a sprite with an exsiting texture contained in a Texture2D object * After creation, the rect will be the size of the texture, and the offset will be (0,0). @@ -124,7 +124,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithTexture(Texture2D *texture); - + /** * Creates a sprite with a texture and a rect. * @@ -136,7 +136,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithTexture(Texture2D *texture, const Rect& rect); - + /** * Creates a sprite with an sprite frame. * @@ -144,7 +144,7 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * Creates a sprite with an sprite frame name. * @@ -155,31 +155,31 @@ public: * @return A valid sprite object that is marked as autoreleased. */ static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName); - + /// @} end of creators group - - + + /// @{ /// @name Initializers - + /** * Default constructor * @js ctor */ Sprite(void); - + /** * Default destructor * @js NA * @lua NA */ virtual ~Sprite(void); - + /** * Initializes an empty sprite with nothing init. */ virtual bool init(void); - + /** * Initializes a sprite with a texture. * @@ -190,7 +190,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture); - + /** * Initializes a sprite with a texture and a rect. * @@ -202,7 +202,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - + /** * Initializes a sprite with a texture and a rect in points, optionally rotated. * @@ -215,7 +215,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated); - + /** * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite * @@ -223,7 +223,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); - + /** * Initializes a sprite with an sprite frame name. * @@ -234,7 +234,7 @@ public: * @return true if the sprite is initialized properly, false otherwise. */ virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); - + /** * Initializes a sprite with an image filename. * @@ -248,7 +248,7 @@ public: * @lua init */ virtual bool initWithFile(const std::string& filename); - + /** * Initializes a sprite with an image filename, and a rect. * @@ -263,17 +263,17 @@ public: * @lua init */ virtual bool initWithFile(const std::string& filename, const Rect& rect); - + /// @} end of initializers /// @{ /// @name BatchNode methods - + /** - * Updates the quad according the rotation, position, scale values. + * Updates the quad according the rotation, position, scale values. */ virtual void updateTransform(void); - + /** * Returns the batch node object if this sprite is rendered by SpriteBatchNode * @@ -292,26 +292,26 @@ public: * @endcode */ virtual void setBatchNode(SpriteBatchNode *spriteBatchNode); - + /// @} end of BatchNode methods - - - + + + /// @{ /// @name Texture methods - + /** * Updates the texture rect of the Sprite in points. * It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size. */ virtual void setTextureRect(const Rect& rect); - + /** * Sets the texture rect, rectRotated and untrimmed size of the Sprite in points. * It will update the texture coordinates and the vertex rectangle. */ virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize); - + /** * Sets the vertex rect. * It will be called internally by setTextureRect. @@ -319,34 +319,34 @@ public: * Do not call it manually. Use setTextureRect instead. */ virtual void setVertexRect(const Rect& rect); - - /// @} end of texture methods - - + /// @} end of texture methods + + + /// @{ /// @name Frames methods - + /** * Sets a new display frame to the Sprite. */ virtual void setDisplayFrame(SpriteFrame *pNewFrame); - + /** * Returns whether or not a SpriteFrame is being displayed */ virtual bool isFrameDisplayed(SpriteFrame *pFrame) const; - + /** @deprecated Use getDisplayFrame() instead */ CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); }; - + /** * Returns the current displayed frame. */ virtual SpriteFrame* getDisplayFrame(); - + /// @} End of frames methods - + /// @{ /// @name Animation methods @@ -356,23 +356,23 @@ public: */ virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex); /// @} - - + + /// @{ /// @name Sprite Properties' setter/getters - - /** + + /** * Whether or not the Sprite needs to be updated in the Atlas. * * @return true if the sprite needs to be updated in the Atlas, false otherwise. */ virtual bool isDirty(void) const { return _dirty; } - - /** + + /** * Makes the Sprite to be updated in the Atlas. */ virtual void setDirty(bool bDirty) { _dirty = bDirty; } - + /** * Returns the quad (tex coords, vertex coords and color) information. * @js NA @@ -380,24 +380,24 @@ public: */ inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; } - /** + /** * Returns whether or not the texture rectangle is rotated. */ inline bool isTextureRectRotated(void) const { return _rectRotated; } - - /** - * Returns the index used on the TextureAtlas. + + /** + * Returns the index used on the TextureAtlas. */ inline int getAtlasIndex(void) const { return _atlasIndex; } - - /** + + /** * Sets the index used on the TextureAtlas. * @warning Don't modify this value unless you know what you are doing */ inline void setAtlasIndex(int atlasIndex) { _atlasIndex = atlasIndex; } - /** - * Returns the rect of the Sprite in points + /** + * Returns the rect of the Sprite in points */ inline const Rect& getTextureRect(void) { return _rect; } @@ -405,19 +405,19 @@ public: * Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; } - + /** * Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode */ inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; } - /** + /** * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. */ inline const Point& getOffsetPosition(void) const { return _offsetPosition; } - /** + /** * Returns the flag which indicates whether the sprite is flipped horizontally or not. * * It only flips the texture of the sprite, and not the texture of the sprite's children. @@ -425,48 +425,48 @@ public: * If you want to flip the anchorPoint too, and/or to flip the children too use: * sprite->setScaleX(sprite->getScaleX() * -1); * - * @return true if the sprite is flipped horizaontally, false otherwise. + * @return true if the sprite is flipped horizontally, false otherwise. */ bool isFlippedX(void) const; /** * Sets whether the sprite should be flipped horizontally or not. * - * @param bFlipX true if the sprite should be flipped horizaontally, false otherwise. + * @param flippedX true if the sprite should be flipped horizontally, false otherwise. */ void setFlippedX(bool flippedX); - - /** @deprecated Use isFlippedX() instead + + /** @deprecated Use isFlippedX() instead * @js NA * @lua NA */ CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); }; /** @deprecated Use setFlippedX() instead */ - CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); }; - - /** + CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); }; + + /** * Return the flag which indicates whether the sprite is flipped vertically or not. - * + * * It only flips the texture of the sprite, and not the texture of the sprite's children. * Also, flipping the texture doesn't alter the anchorPoint. * If you want to flip the anchorPoint too, and/or to flip the children too use: * sprite->setScaleY(sprite->getScaleY() * -1); - * - * @return true if the sprite is flipped vertically, flase otherwise. + * + * @return true if the sprite is flipped vertically, false otherwise. */ bool isFlippedY(void) const; /** * Sets whether the sprite should be flipped vertically or not. * - * @param bFlipY true if the sprite should be flipped vertically, flase otherwise. + * @param flippedY true if the sprite should be flipped vertically, false otherwise. */ void setFlippedY(bool flippedY); - + /// @} End of Sprite properties getter/setters - + /** @deprecated Use isFlippedY() instead */ CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); }; /** @deprecated Use setFlippedY() instead */ - CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; + CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); }; // // Overrides @@ -543,13 +543,13 @@ protected: TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference) int _atlasIndex; /// Absolute (real) Index on the SpriteSheet SpriteBatchNode* _batchNode; /// Used batch node (weak reference) - + bool _dirty; /// Whether the sprite needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated bool _hasChildren; /// Whether the sprite contains children bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible AffineTransform _transformToBatch; - + // // Data used when the sprite is self-rendered // @@ -575,8 +575,8 @@ protected: bool _opacityModifyRGB; // image is flipped - bool _flippedX; /// Whether the sprite is flipped horizaontally or not. - bool _flippedY; /// Whether the sprite is flipped vertically or not. + bool _flippedX; /// Whether the sprite is flipped horizontally or not + bool _flippedY; /// Whether the sprite is flipped vertically or not }; @@ -585,4 +585,4 @@ protected: NS_CC_END -#endif // __SPITE_NODE_CCSPRITE_H__ +#endif // __SPRITE_NODE_CCSPRITE_H__ From 02da3a29ccf68a99756c082d77644a4cf45e777b Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 11:38:02 +0800 Subject: [PATCH 514/557] issue #3025: deprecate TextureCache::reloadAllTextures, call VolatileTextureMgr::reloadAllTextures instead --- cocos/2d/CCTextureCache.cpp | 7 ++++--- cocos/2d/CCTextureCache.h | 5 +++-- cocos/2d/platform/android/nativeactivity.cpp | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 7a5e835653..780e0330aa 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -417,9 +417,10 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const void TextureCache::reloadAllTextures() { -#if CC_ENABLE_CACHE_TEXTURE_DATA - VolatileTextureMgr::reloadAllTextures(); -#endif +//will do nothing +// #if CC_ENABLE_CACHE_TEXTURE_DATA +// VolatileTextureMgr::reloadAllTextures(); +// #endif } void TextureCache::waitForQuit() diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 8c988ff4c3..c4c14bad53 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -73,9 +73,10 @@ public: CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } /** Reload all textures - It's only useful when the value of CC_ENABLE_CACHE_TEXTURE_DATA is 1 + should not call it, called by frame work + now the function do nothing, use VolatileTextureMgr::reloadAllTextures */ - static void reloadAllTextures(); + CC_DEPRECATED_ATTRIBUTE static void reloadAllTextures(); public: /** diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 12e25d597d..f0e52140ff 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -127,7 +127,7 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) { cocos2d::GL::invalidateStateCache(); cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); - cocos2d::TextureCache::reloadAllTextures(); + cocos2d::VolatileTextureMgr::reloadAllTextures(); cocos2d::NotificationCenter::getInstance()->postNotification(EVNET_COME_TO_FOREGROUND, NULL); cocos2d::Director::getInstance()->setGLDefaultValues(); } From 6c1144ee796608a97733b723fe734fafd650c4ac Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 11 Nov 2013 12:49:38 +0800 Subject: [PATCH 515/557] issue #2770: fix some warning --- cocos/2d/CCLabelBMFont.cpp | 4 +- cocos/2d/CCLabelTextFormatter.cpp | 4 +- cocos/2d/CCProfiling.cpp | 2 +- cocos/2d/CCScene.cpp | 6 +- cocos/2d/CCScheduler.cpp | 64 +++++++++---------- cocos/2d/CCSpriteBatchNode.cpp | 4 +- cocos/base/atitc.cpp | 2 +- cocos/base/s3tc.cpp | 2 +- .../editor-support/cocosbuilder/CCBReader.cpp | 6 +- .../cocostudio/CCDataReaderHelper.cpp | 15 ++--- .../cocostudio/CCSSceneReader.cpp | 4 +- cocos/editor-support/spine/Animation.cpp | 12 ++-- cocos/editor-support/spine/SkeletonJson.cpp | 4 +- extensions/GUI/CCScrollView/CCSorting.cpp | 2 +- extensions/assets-manager/AssetsManager.cpp | 6 +- extensions/assets-manager/AssetsManager.h | 2 +- 16 files changed, 69 insertions(+), 70 deletions(-) diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index fe6026abfe..8eda86469e 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -1073,9 +1073,9 @@ void LabelBMFont::updateLabel() int size = multiline_string.size(); unsigned short* str_new = new unsigned short[size + 1]; - for (int i = 0; i < size; ++i) + for (int j = 0; j < size; ++j) { - str_new[i] = multiline_string[i]; + str_new[j] = multiline_string[j]; } str_new[size] = '\0'; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 87dd3cf7cd..6f85e1495a 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -200,9 +200,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) int size = multiline_string.size(); unsigned short* strNew = new unsigned short[size + 1]; - for (int i = 0; i < size; ++i) + for (int j = 0; j < size; ++j) { - strNew[i] = multiline_string[i]; + strNew[j] = multiline_string[j]; } strNew[size] = 0; diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 1db8ba0678..3c90394d58 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName) CCASSERT(timer, "CCProfilingTimer not found"); - long duration = chrono::duration_cast(now - timer->_startTime).count(); + long duration = static_cast(chrono::duration_cast(now - timer->_startTime).count()); timer->totalTime += duration; timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f; diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index 3f05e43c83..9c636382dd 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -133,12 +133,12 @@ void Scene::addChildToPhysicsWorld(Node* child) if (_physicsWorld) { std::function addToPhysicsWorldFunc = nullptr; - addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void + addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void { - if (dynamic_cast(child) != nullptr) + if (dynamic_cast(obj) != nullptr) { - Node* node = dynamic_cast(child); + Node* node = dynamic_cast(obj); if (node->getPhysicsBody()) { diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 3f9c9da9f8..230e453a7f 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -601,31 +601,31 @@ void Scheduler::unscheduleAllWithMinPriority(int nMinPriority) } // Updates selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; if(nMinPriority < 0) { - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if(pEntry->priority >= nMinPriority) + if(entry->priority >= nMinPriority) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } } if(nMinPriority <= 0) { - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if(pEntry->priority >= nMinPriority) + if(entry->priority >= nMinPriority) { - unscheduleUpdateForTarget(pEntry->target); + unscheduleUpdateForTarget(entry->target); } } @@ -836,32 +836,32 @@ void Scheduler::update(float dt) } // Iterate over all the Updates' selectors - tListEntry *pEntry, *pTmp; + tListEntry *entry, *tmp; // updates with priority < 0 - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } // updates with priority == 0 - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } // updates with priority > 0 - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if ((! pEntry->paused) && (! pEntry->markedForDeletion)) + if ((! entry->paused) && (! entry->markedForDeletion)) { - pEntry->target->update(dt); + entry->target->update(dt); } } @@ -909,43 +909,43 @@ void Scheduler::update(float dt) { for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* pEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); - if (pEntry->isMarkedForDeletion()) + SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + if (eachEntry->isMarkedForDeletion()) { _scriptHandlerEntries->removeObjectAtIndex(i); } - else if (!pEntry->isPaused()) + else if (!eachEntry->isPaused()) { - pEntry->getTimer()->update(dt); + eachEntry->getTimer()->update(dt); } } } // delete all updates that are marked for deletion // updates with priority < 0 - DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesNegList, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } // updates with priority == 0 - DL_FOREACH_SAFE(_updates0List, pEntry, pTmp) + DL_FOREACH_SAFE(_updates0List, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } // updates with priority > 0 - DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp) + DL_FOREACH_SAFE(_updatesPosList, entry, tmp) { - if (pEntry->markedForDeletion) + if (entry->markedForDeletion) { - this->removeUpdateFromHash(pEntry); + this->removeUpdateFromHash(entry); } } diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 820a999401..17198c8cce 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -598,8 +598,8 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) { auto next = std::next(it); - std::for_each(next, _descendants.end(), [](Sprite *sprite) { - sprite->setAtlasIndex( sprite->getAtlasIndex() - 1 ); + std::for_each(next, _descendants.end(), [](Sprite *spr) { + spr->setAtlasIndex( spr->getAtlasIndex() - 1 ); }); _descendants.erase(it); diff --git a/cocos/base/atitc.cpp b/cocos/base/atitc.cpp index 3a60d6d2f7..e93cb801b2 100644 --- a/cocos/base/atitc.cpp +++ b/cocos/base/atitc.cpp @@ -138,7 +138,7 @@ static void atitc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/base/s3tc.cpp b/cocos/base/s3tc.cpp index e7869df631..2995849603 100644 --- a/cocos/base/s3tc.cpp +++ b/cocos/base/s3tc.cpp @@ -126,7 +126,7 @@ static void s3tc_decode_block(uint8_t **blockData, { for (int x = 0; x < 4; ++x) { - initAlpha = (alpha & 0x0f) << 28; + initAlpha = (static_cast(alpha) & 0x0f) << 28; initAlpha += initAlpha >> 4; decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3]; pixelsIndex >>= 2; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 154d2b0b36..d0a70c225b 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -482,12 +482,12 @@ int CCBReader::readInt(bool pSigned) { if(pSigned) { int s = current % 2; if(s) { - num = (int)(current / 2); + num = static_cast(current / 2); } else { - num = (int)(-current / 2); + num = static_cast(-current / 2); } } else { - num = current - 1; + num = static_cast(current - 1); } this->alignBits(); diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index defb268ada..17f10067ed 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -579,8 +579,7 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML ArmatureData *armatureData = new ArmatureData(); armatureData->init(); - const char *name = armatureXML->Attribute(A_NAME); - armatureData->name = name; + armatureData->name = armatureXML->Attribute(A_NAME); tinyxml2::XMLElement *boneXML = armatureXML->FirstChildElement(BONE); @@ -888,21 +887,21 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov //! Change rotation range from (-180 -- 180) to (-infinity -- infinity) FrameData **frames = (FrameData **)movBoneData->frameList.data->arr; - for (int i = movBoneData->frameList.count() - 1; i >= 0; i--) + for (int j = movBoneData->frameList.count() - 1; j >= 0; j--) { - if (i > 0) + if (j > 0) { - float difSkewX = frames[i]->skewX - frames[i - 1]->skewX; - float difSkewY = frames[i]->skewY - frames[i - 1]->skewY; + float difSkewX = frames[j]->skewX - frames[j - 1]->skewX; + float difSkewY = frames[j]->skewY - frames[j - 1]->skewY; if (difSkewX < -M_PI || difSkewX > M_PI) { - frames[i - 1]->skewX = difSkewX < 0 ? frames[i - 1]->skewX - 2 * M_PI : frames[i - 1]->skewX + 2 * M_PI; + frames[j - 1]->skewX = difSkewX < 0 ? frames[j - 1]->skewX - 2 * M_PI : frames[j - 1]->skewX + 2 * M_PI; } if (difSkewY < -M_PI || difSkewY > M_PI) { - frames[i - 1]->skewY = difSkewY < 0 ? frames[i - 1]->skewY - 2 * M_PI : frames[i - 1]->skewY + 2 * M_PI; + frames[j - 1]->skewY = difSkewY < 0 ? frames[j - 1]->skewY - 2 * M_PI : frames[j - 1]->skewY + 2 * M_PI; } } } diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index f26b337d6a..25c84fd773 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -227,9 +227,9 @@ namespace cocostudio { const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); - for (long i = 0; i < childrenCount; ++i) + for (long j = 0; j < childrenCount; ++j) { - const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); + const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", j); std::string plistpath; plistpath += file_path; plistpath.append(plist); diff --git a/cocos/editor-support/spine/Animation.cpp b/cocos/editor-support/spine/Animation.cpp index 655e80be06..0cded9e16a 100644 --- a/cocos/editor-support/spine/Animation.cpp +++ b/cocos/editor-support/spine/Animation.cpp @@ -248,12 +248,12 @@ void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float bone = skeleton->bones[self->boneIndex]; if (time >= self->frames[self->framesLength - 2]) { /* Time is after last frame. */ - 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; + 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; return; } diff --git a/cocos/editor-support/spine/SkeletonJson.cpp b/cocos/editor-support/spine/SkeletonJson.cpp index 98e4be4334..6bfeeb24e7 100644 --- a/cocos/editor-support/spine/SkeletonJson.cpp +++ b/cocos/editor-support/spine/SkeletonJson.cpp @@ -118,7 +118,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S skeletonData->animationCount++; for (i = 0; i < boneCount; ++i) { - int timelineCount; + timelineCount = 0; Json* boneMap = Json_getItemAt(bones, i); const char* boneName = boneMap->name; @@ -175,7 +175,7 @@ static Animation* _SkeletonJson_readAnimation (SkeletonJson* self, Json* root, S } for (i = 0; i < slotCount; ++i) { - int timelineCount; + timelineCount = 0; Json* slotMap = Json_getItemAt(slots, i); const char* slotName = slotMap->name; diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp index fd9d80f32c..412aa157e1 100644 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -33,7 +33,7 @@ class SortedObject : public Object, public SortableObject { public: SortedObject() : objectID(0) {} - virtual void setObjectID(unsigned int objectID) { this->objectID = objectID; } + virtual void setObjectID(unsigned int id) { this->objectID = id; } virtual unsigned int getObjectID() { return objectID; } private: unsigned int objectID; diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 31795c4f39..06e5bd11c6 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -214,7 +214,7 @@ void AssetsManager::downloadAndUncompress() _isDownloading = false; } -void AssetsManager::update() +void AssetsManager::update(float delta) { if (_isDownloading) return; @@ -651,8 +651,8 @@ AssetsManager* AssetsManager::create(const char* packageUrl, const char* version class DelegateProtocolImpl : public AssetsManagerDelegateProtocol { public : - DelegateProtocolImpl(ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback) - : errorCallback(errorCallback), progressCallback(progressCallback), successCallback(successCallback) + DelegateProtocolImpl(ErrorCallback aErrorCallback, ProgressCallback aProgressCallback, SuccessCallback aSuccessCallback) + : errorCallback(aErrorCallback), progressCallback(aProgressCallback), successCallback(aSuccessCallback) {} virtual void onError(AssetsManager::ErrorCode errorCode) { errorCallback(int(errorCode)); } diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index f3e413f4bd..5608084c76 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -98,7 +98,7 @@ public: /* @brief Download new package if there is a new version, and uncompress downloaded zip file. * Ofcourse it will set search path that stores downloaded files. */ - virtual void update(); + virtual void update(float delta) override; /* @brief Gets url of package. */ From 0a72c3c1c2af1f3d5e9d25ff82c682b6d1ded766 Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Mon, 11 Nov 2013 13:33:47 +0800 Subject: [PATCH 516/557] 1.when add a skin to last index, applay it's skindata to the previous skindata 2.Do not retain target when regist frame event and movement event --- .../cocostudio/CCArmatureAnimation.cpp | 17 ++------------ .../cocostudio/CCDisplayManager.cpp | 22 +++++++++++++++++-- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 49aa8e1c6f..f3e5199d6c 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -69,9 +69,6 @@ ArmatureAnimation::~ArmatureAnimation(void) { CC_SAFE_RELEASE_NULL(_tweenList); CC_SAFE_RELEASE_NULL(_animationData); - - CC_SAFE_RELEASE_NULL(_movementEventTarget); - CC_SAFE_RELEASE_NULL(_frameEventTarget); } bool ArmatureAnimation::init(Armature *armature) @@ -423,23 +420,13 @@ std::string ArmatureAnimation::getCurrentMovementID() const void ArmatureAnimation::setMovementEventCallFunc(Object *target, SEL_MovementEventCallFunc callFunc) { - if (target != _movementEventTarget) - { - CC_SAFE_RETAIN(target); - CC_SAFE_RELEASE_NULL(_movementEventTarget); - _movementEventTarget = target; - } + _movementEventTarget = target; _movementEventCallFunc = callFunc; } void ArmatureAnimation::setFrameEventCallFunc(Object *target, SEL_FrameEventCallFunc callFunc) { - if (target != _frameEventTarget) - { - CC_SAFE_RETAIN(target); - CC_SAFE_RELEASE_NULL(_frameEventTarget); - _frameEventTarget = target; - } + _frameEventTarget = target; _frameEventCallFunc = callFunc; } diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index a8c8f5d760..6bcf7eaff3 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -142,8 +142,26 @@ void DisplayManager::addDisplay(Node *display, int index) } else { - BaseData baseData; - skin->setSkinData(baseData); + bool find = false; + + for (int i = _decoDisplayList->count()-2; i>=0; i--) + { + DecorativeDisplay *dd = static_cast(_decoDisplayList->objectAtIndex(i)); + SpriteDisplayData *spriteDisplayData = static_cast(dd->getDisplayData()); + if (spriteDisplayData) + { + find = true; + skin->setSkinData(spriteDisplayData->skinData); + static_cast(displayData)->skinData = spriteDisplayData->skinData; + break; + } + } + + if (!find) + { + BaseData baseData; + skin->setSkinData(baseData); + } } } else if (dynamic_cast(display)) From 058cd9d896db46de077ad5ddd3fb2615fc14628f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 13:51:44 +0800 Subject: [PATCH 517/557] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 71b6680d05..d553c07d24 100644 --- a/AUTHORS +++ b/AUTHORS @@ -646,6 +646,9 @@ Developers: Luis Parravicini (luisparravicini) Fixed typos in create_project.py. + xhcnb + Device::setAccelerometerEnabled needs to be invoked before adding ACC listener. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 55b9462b17eaa740a9cb2f831de025273f2412a5 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 14:21:41 +0800 Subject: [PATCH 518/557] issue #3025: directly use _textureCache in Director --- cocos/2d/CCDirector.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 5a10d83d1e..f948b099bf 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -867,14 +867,13 @@ void Director::getFPSImageData(unsigned char** datapointer, long* length) void Director::createStatsLabel() { Texture2D *texture = nullptr; - TextureCache *textureCache = _textureCache; if (_FPSLabel && _SPFLabel) { CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_drawsLabel); - textureCache->removeTextureForKey("/cc_fps_images"); + _textureCache->removeTextureForKey("/cc_fps_images"); FileUtils::getInstance()->purgeCachedEntries(); } @@ -891,7 +890,7 @@ void Director::createStatsLabel() return; } - texture = textureCache->addImage(image, "/cc_fps_images"); + texture = _textureCache->addImage(image, "/cc_fps_images"); CC_SAFE_RELEASE(image); /* From 9d5813b7d9fe2e449d94a63bd4848ed49cb26668 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 11:23:34 +0800 Subject: [PATCH 519/557] =?UTF-8?q?Some=20fixes:=201)=20Moving=20the=20imp?= =?UTF-8?q?lementation=20of=20JSStringWrapper=20to=20.cpp=20file.=20Removi?= =?UTF-8?q?ng=20override=20operator()=20which=20will=20be=20easy=20to=20ma?= =?UTF-8?q?ke=20errors.=202)=20Deleting=20JSCallFuncWrapper=20since=20it?= =?UTF-8?q?=20isn=E2=80=99t=20needed=20after=20using=20std::function=20for?= =?UTF-8?q?=20MenuItem=E2=80=99s=20Callback.=203)=20Fixing=20ChipmunkTest?= =?UTF-8?q?=20crash=20sometimes=20on=20MAC=20platform(64bit).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../javascript/bindings/ScriptingCore.cpp | 82 +++++++++++++++---- .../javascript/bindings/ScriptingCore.h | 57 +++---------- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../javascript/bindings/cocos2d_specifics.hpp | 13 --- .../javascript/bindings/js_bindings_core.cpp | 12 +-- .../bindings/network/XMLHTTPRequest.cpp | 8 +- 6 files changed, 90 insertions(+), 84 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 263e2c0fae..22de38a70b 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -60,7 +60,7 @@ static std::vector g_queue; static std::mutex g_qMutex; static std::mutex g_rwMutex; static int clientSocket = -1; -static unsigned long s_nestedLoopLevel = 0; +static uint32_t s_nestedLoopLevel = 0; // server entry point for the bg thread static void serverEntryPoint(void); @@ -377,7 +377,7 @@ void ScriptingCore::string_report(jsval val) { LOGD("val : return string is NULL"); } else { JSStringWrapper wrapper(str); - LOGD("val : return string =\n%s\n", (char *)wrapper); + LOGD("val : return string =\n%s\n", wrapper.get()); } } else if (JSVAL_IS_NUMBER(val)) { double number; @@ -631,7 +631,7 @@ JSBool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &string); if (string) { JSStringWrapper wrapper(string); - js_log("%s", (char *)wrapper); + js_log("%s", wrapper.get()); } } return JS_TRUE; @@ -671,14 +671,14 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) // js::RootedObject* rootedGlobal = globals[name]; JSObject* debugObj = ScriptingCore::getInstance()->getDebugGlobal(); if (debugObj) { - res = ScriptingCore::getInstance()->runScript(path, debugObj); + res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { - JS_ReportError(cx, "Invalid global object: %s", (char*)name); + JS_ReportError(cx, "Invalid global object: %s", name.get()); return JS_FALSE; } } else { JSObject* glob = JS::CurrentGlobalOrNull(cx); - res = ScriptingCore::getInstance()->runScript(path, glob); + res = ScriptingCore::getInstance()->runScript(path.get(), glob); } return res; } @@ -764,12 +764,7 @@ void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { - Array * arr = JSCallFuncWrapper::getTargetForNativeNode((Node*)p->ptr); - if (arr) { - arr->removeAllObjects(); - } - - arr = JSScheduleWrapper::getTargetForJSObject(p->obj); + Array* arr = JSScheduleWrapper::getTargetForJSObject(p->obj); if (arr) { Scheduler* pScheduler = Director::getInstance()->getScheduler(); Object* pObj = NULL; @@ -1297,7 +1292,7 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r else if (JSVAL_IS_STRING(*vp)) { JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); - pArray->addObject(String::create(str)); + pArray->addObject(String::create(str.get())); } else { @@ -2373,9 +2368,11 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "fontName", &jsr); JS_ValueToString(cx, jsr); JSStringWrapper wrapper(jsr); - if ( wrapper ) + const char* fontName = wrapper.get(); + + if (fontName && strlen(fontName) > 0) { - out->_fontName = (char*)wrapper; + out->_fontName = fontName; } else { @@ -2539,3 +2536,58 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) // we are done here return JS_TRUE; } + +// JSStringWrapper +JSStringWrapper::JSStringWrapper() +{ + _buffer = NULL; +} + +JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) +{ + set(str, cx); +} + +JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) +{ + set(val, cx); +} + +JSStringWrapper::~JSStringWrapper() +{ + if (_buffer) + { + //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); + delete[] _buffer; + } +} +void JSStringWrapper::set(jsval val, JSContext* cx) +{ + if (val.isString()) + { + this->set(val.toString(), cx); + } + else + { + _buffer = NULL; + } +} + +void JSStringWrapper::set(JSString* str, JSContext* cx) +{ + _string = str; + if (!cx) + { + cx = ScriptingCore::getInstance()->getGlobalContext(); + } + // JS_EncodeString isn't supported in SpiderMonkey ff19.0. + //buffer = JS_EncodeString(cx, string); + unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); + _buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); +} + +const char* JSStringWrapper::get() +{ + return _buffer ? _buffer : ""; +} + diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 992569afc9..6a78f827fe 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -248,54 +248,21 @@ JSObject* NewGlobalObject(JSContext* cx, bool debug = false); // just a simple utility to avoid mem leaking when using JSString class JSStringWrapper { - JSString* string; - const char* buffer; public: - JSStringWrapper() { - buffer = NULL; - } - JSStringWrapper(JSString* str, JSContext* cx = NULL) { - set(str, cx); - } - JSStringWrapper(jsval val, JSContext* cx = NULL) { - set(val, cx); - } - ~JSStringWrapper() { - if (buffer) { - //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); - delete[] buffer; - } - } - void set(jsval val, JSContext* cx) { - if (val.isString()) { - this->set(val.toString(), cx); - } else { - buffer = NULL; - } - } - void set(JSString* str, JSContext* cx) { - string = str; - if (!cx) { - cx = ScriptingCore::getInstance()->getGlobalContext(); - - } - // JS_EncodeString isn't supported in SpiderMonkey ff19.0. - //buffer = JS_EncodeString(cx, string); - unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); - buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); - } - std::string get() { - return buffer; - } + JSStringWrapper(); + JSStringWrapper(JSString* str, JSContext* cx = NULL); + JSStringWrapper(jsval val, JSContext* cx = NULL); + ~JSStringWrapper(); + + void set(jsval val, JSContext* cx); + void set(JSString* str, JSContext* cx); + const char* get(); - operator std::string() { - return std::string(buffer); - } - operator char*() { - return (char*)buffer; - } private: - /* Copy and assignment are not supported. */ + JSString* _string; + const char* _buffer; + + /* Copy and assignment are not supported. */ JSStringWrapper(const JSStringWrapper &another); JSStringWrapper &operator=(const JSStringWrapper &another); }; diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index bc82fe5227..141c335bfe 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -927efea93a520eeb9db9f62c8d8eb7a7b93b08dc \ No newline at end of file +3ba4ef8fa21631bee450ece05841803624c2e636 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index f7e9f2bdb4..3e98123689 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -101,19 +101,6 @@ protected: jsval _extraData; }; -class JSCallFuncWrapper: public JSCallbackWrapper { -public: - JSCallFuncWrapper() {} - virtual ~JSCallFuncWrapper(void) { - return; - } - - static void setTargetForNativeNode(Node *pNode, JSCallFuncWrapper *target); - static Array * getTargetForNativeNode(Node *pNode); - - void callbackFunc(Node *node); -}; - class JSScheduleWrapper: public JSCallbackWrapper { diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index 645f9fa94b..19d63c30e3 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -57,7 +57,7 @@ static void reportError(JSContext *cx, const char *message, JSErrorReport *repor void* jsb_get_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) return element->proxy; @@ -77,13 +77,13 @@ void jsb_set_proxy_for_jsobject(void *proxy, JSObject *obj) element->proxy = proxy; element->jsObject = obj; - HASH_ADD_INT( hash, jsObject, element ); + HASH_ADD_PTR( hash, jsObject, element ); } void jsb_del_proxy_for_jsobject(JSObject *obj) { tHashJSObject *element = NULL; - HASH_FIND_INT(hash, &obj, element); + HASH_FIND_PTR(hash, &obj, element); if( element ) { HASH_DEL(hash, element); free(element); @@ -96,7 +96,7 @@ void jsb_del_proxy_for_jsobject(JSObject *obj) JSObject* jsb_get_jsobject_for_proxy(void *proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) return element->jsObject; @@ -112,13 +112,13 @@ void jsb_set_jsobject_for_proxy(JSObject *jsobj, void* proxy) element->proxy = proxy; element->jsObject = jsobj; - HASH_ADD_INT( reverse_hash, proxy, element ); + HASH_ADD_PTR( reverse_hash, proxy, element ); } void jsb_del_jsobject_for_proxy(void* proxy) { tHashJSObject *element = NULL; - HASH_FIND_INT(reverse_hash, &proxy, element); + HASH_FIND_PTR(reverse_hash, &proxy, element); if( element ) { HASH_DEL(reverse_hash, element); free(element); diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index e3a0ba5b18..cb33e9d413 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -609,8 +609,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) JSStringWrapper w1(jsMethod); JSStringWrapper w2(jsURL); - method = w1; - urlstr = w2; + method = w1.get(); + urlstr = w2.get(); _url = urlstr; _meth = method; @@ -771,8 +771,8 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) JSStringWrapper w1(jsField); JSStringWrapper w2(jsValue); - field = w1; - value = w2; + field = w1.get(); + value = w2.get(); // Populate the request_header map. _setRequestHeader(field, value); From fe88f7c9414ef17fd272bba8ced625384b19c79f Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 10 Nov 2013 13:03:24 +0800 Subject: [PATCH 520/557] Fixing memory leak of JSStringWrapper::set . --- .../javascript/bindings/ScriptingCore.cpp | 17 +++++++++-------- .../javascript/bindings/ScriptingCore.h | 1 - 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 22de38a70b..bca4e18f53 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -2539,28 +2539,27 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) // JSStringWrapper JSStringWrapper::JSStringWrapper() +: _buffer(nullptr) { - _buffer = NULL; } JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) +: JSStringWrapper() { set(str, cx); } JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) +: JSStringWrapper() { set(val, cx); } JSStringWrapper::~JSStringWrapper() { - if (_buffer) - { - //JS_free(ScriptingCore::getInstance()->getGlobalContext(), (void*)buffer); - delete[] _buffer; - } + CC_SAFE_DELETE_ARRAY(_buffer); } + void JSStringWrapper::set(jsval val, JSContext* cx) { if (val.isString()) @@ -2569,13 +2568,14 @@ void JSStringWrapper::set(jsval val, JSContext* cx) } else { - _buffer = NULL; + CC_SAFE_DELETE_ARRAY(_buffer); } } void JSStringWrapper::set(JSString* str, JSContext* cx) { - _string = str; + CC_SAFE_DELETE_ARRAY(_buffer); + if (!cx) { cx = ScriptingCore::getInstance()->getGlobalContext(); @@ -2583,6 +2583,7 @@ void JSStringWrapper::set(JSString* str, JSContext* cx) // JS_EncodeString isn't supported in SpiderMonkey ff19.0. //buffer = JS_EncodeString(cx, string); unsigned short* pStrUTF16 = (unsigned short*)JS_GetStringCharsZ(cx, str); + _buffer = cc_utf16_to_utf8(pStrUTF16, -1, NULL, NULL); } diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 6a78f827fe..7f0e367d92 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -259,7 +259,6 @@ public: const char* get(); private: - JSString* _string; const char* _buffer; /* Copy and assignment are not supported. */ From 5a0df8d2e893cfbb6ee42d494275f1a65a82befa Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 10:29:30 +0800 Subject: [PATCH 521/557] =?UTF-8?q?VS2012=20doesn=E2=80=99t=20support=20in?= =?UTF-8?q?voke=20another=20constructor=20method=20in=20current=20construc?= =?UTF-8?q?tor.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index bca4e18f53..1ce7234d88 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -2544,13 +2544,13 @@ JSStringWrapper::JSStringWrapper() } JSStringWrapper::JSStringWrapper(JSString* str, JSContext* cx/* = NULL*/) -: JSStringWrapper() +: _buffer(nullptr) { set(str, cx); } JSStringWrapper::JSStringWrapper(jsval val, JSContext* cx/* = NULL*/) -: JSStringWrapper() +: _buffer(nullptr) { set(val, cx); } From 55cf30b7c8a494779e475ee7fae7d4ce871cef2f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 12:47:48 +0800 Subject: [PATCH 522/557] =?UTF-8?q?HASH=5FFIND=5FINT=20=E2=80=94>=20HASH?= =?UTF-8?q?=5FFIND=5FPTR=20for=20CCAcitonManager.cpp=20and=20CCScheduler.c?= =?UTF-8?q?pp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCActionManager.cpp | 18 +++++++++--------- cocos/2d/CCScheduler.cpp | 32 ++++++++++++++++---------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 4a01fd7663..0b258f4a6e 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -123,7 +123,7 @@ void ActionManager::removeActionAtIndex(long index, tHashElement *element) void ActionManager::pauseTarget(Object *target) { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { element->paused = true; @@ -133,7 +133,7 @@ void ActionManager::pauseTarget(Object *target) void ActionManager::resumeTarget(Object *target) { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { element->paused = false; @@ -176,14 +176,14 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) tHashElement *element = NULL; // we should convert it to Object*, because we save it as Object* Object *tmp = target; - HASH_FIND_INT(_targets, &tmp, element); + HASH_FIND_PTR(_targets, &tmp, element); if (! element) { element = (tHashElement*)calloc(sizeof(*element), 1); element->paused = paused; target->retain(); element->target = target; - HASH_ADD_INT(_targets, target, element); + HASH_ADD_PTR(_targets, target, element); } actionAllocWithHashElement(element); @@ -215,7 +215,7 @@ void ActionManager::removeAllActionsFromTarget(Object *target) } tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged)) @@ -250,7 +250,7 @@ void ActionManager::removeAction(Action *action) tHashElement *element = NULL; Object *target = action->getOriginalTarget(); - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { long i = ccArrayGetIndexOfObject(element->actions, action); @@ -271,7 +271,7 @@ void ActionManager::removeActionByTag(int tag, Object *target) CCASSERT(target != NULL, ""); tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -298,7 +298,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const CCASSERT(tag != Action::INVALID_TAG, ""); tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { @@ -330,7 +330,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { tHashElement *element = NULL; - HASH_FIND_INT(_targets, &target, element); + HASH_FIND_PTR(_targets, &target, element); if (element) { return element->actions ? element->actions->num : 0; diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 230e453a7f..efc80847d0 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -294,7 +294,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (! element) { @@ -304,7 +304,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in { target->retain(); } - HASH_ADD_INT(_hashForTimers, target, element); + HASH_ADD_PTR(_hashForTimers, target, element); // Is this the 1st element ? Then set the pause level to all the selectors of this target element->paused = paused; @@ -352,7 +352,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target) //CCASSERT(selector); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -448,7 +448,7 @@ void Scheduler::priorityIn(tListEntry **list, Object *target, int priority, bool target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) @@ -467,14 +467,14 @@ void Scheduler::appendIn(_listEntry **list, Object *target, bool paused) target->retain(); pHashElement->list = list; pHashElement->entry = listElement; - HASH_ADD_INT(_hashForUpdates, target, pHashElement); + HASH_ADD_PTR(_hashForUpdates, target, pHashElement); } void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused) { tHashUpdateEntry *pHashElement = NULL; - HASH_FIND_INT(_hashForUpdates, &target, pHashElement); + HASH_FIND_PTR(_hashForUpdates, &target, pHashElement); if (pHashElement) { #if COCOS2D_DEBUG >= 1 @@ -509,7 +509,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target) CCASSERT(target, "Argument target must be non-NULL"); tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (!element) { @@ -541,7 +541,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry) { tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &entry->target, element); + HASH_FIND_PTR(_hashForUpdates, &entry->target, element); if (element) { // list entry @@ -567,7 +567,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target) } tHashUpdateEntry *element = NULL; - HASH_FIND_INT(_hashForUpdates, &target, element); + HASH_FIND_PTR(_hashForUpdates, &target, element); if (element) { if (_updateHashLocked) @@ -645,7 +645,7 @@ void Scheduler::unscheduleAllForTarget(Object *target) // Custom Selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { @@ -702,7 +702,7 @@ void Scheduler::resumeTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = false; @@ -710,7 +710,7 @@ void Scheduler::resumeTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -724,7 +724,7 @@ void Scheduler::pauseTarget(Object *target) // custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if (element) { element->paused = true; @@ -732,7 +732,7 @@ void Scheduler::pauseTarget(Object *target) // update selector tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { CCASSERT(elementUpdate->entry != NULL, ""); @@ -746,7 +746,7 @@ bool Scheduler::isTargetPaused(Object *target) // Custom selectors tHashTimerEntry *element = NULL; - HASH_FIND_INT(_hashForTimers, &target, element); + HASH_FIND_PTR(_hashForTimers, &target, element); if( element ) { return element->paused; @@ -754,7 +754,7 @@ bool Scheduler::isTargetPaused(Object *target) // We should check update selectors if target does not have custom selectors tHashUpdateEntry *elementUpdate = NULL; - HASH_FIND_INT(_hashForUpdates, &target, elementUpdate); + HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if ( elementUpdate ) { return elementUpdate->entry->paused; From ff3bfbe8a27fc23580738a0d0e2aefa3be6cb641 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 12:54:36 +0800 Subject: [PATCH 523/557] Using std::unordered_map instead of UTHASH for js_type_class_t. Since xxx.hash_code() return size_t which is 8bytes on 64bit system, we should not use HASH_ADD_INT and HASH_FIND_INT for js_type_class_t. --- .../javascript/bindings/ScriptingCore.cpp | 14 +- .../chipmunk/js_bindings_chipmunk_manual.cpp | 137 +++++++++++------- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../javascript/bindings/cocos2d_specifics.hpp | 19 ++- .../bindings/js_bindings_opengl.cpp | 28 ++-- .../bindings/spidermonkey_specifics.h | 7 +- 6 files changed, 121 insertions(+), 86 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 1ce7234d88..462debba9d 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -67,7 +67,8 @@ static void serverEntryPoint(void); js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL; -js_type_class_t *_js_global_type_ht = NULL; +std::unordered_map _js_global_type_map; + static char *_js_log_buf = NULL; static std::vector registrationList; @@ -605,14 +606,13 @@ void ScriptingCore::cleanup() _js_log_buf = NULL; } - js_type_class_t* current, *tmp; - HASH_ITER(hh, _js_global_type_ht, current, tmp) + for (auto iter = _js_global_type_map.begin(); iter != _js_global_type_map.end(); ++iter) { - HASH_DEL(_js_global_type_ht, current); - free(current->jsclass); - free(current); + free(iter->second->jsclass); + free(iter->second); } - HASH_CLEAR(hh, _js_global_type_ht); + + _js_global_type_map.clear(); } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index 903b777fde..d7c9f94f57 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -42,9 +42,13 @@ static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { T* cobj = new T(); cobj->autorelease(); js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - assert(p); + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + p = typeMapIter->second; + CCASSERT(p, "The value is null."); + JSObject *_tmp = JS_NewObject(cx, p->jsclass, p->proto, p->parentProto); js_proxy_t *pp = jsb_new_proxy(cobj, _tmp); JS_AddObjectRoot(cx, &pp->obj); @@ -179,10 +183,14 @@ JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_ do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -265,24 +273,27 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSB_CCPhysicsDebugNode_object = JS_InitClass(cx, globalObj, typeClass->proto, JSB_CCPhysicsDebugNode_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSB_CCPhysicsDebugNode_class; p->proto = JSB_CCPhysicsDebugNode_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } @@ -305,10 +316,13 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -331,10 +345,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -370,10 +386,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint do { if (ret) { TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); jsret = OBJECT_TO_JSVAL(obj); js_proxy_t *p = jsb_new_proxy(ret, obj); @@ -393,29 +411,35 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, JSBool ok = JS_TRUE; const char* arg0; std::string arg0_tmp; - if (argc >= 1) { + if (argc == 1) { ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - } - PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); - jsval jsret; - do { - if (ret) { - TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); - JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); - jsret = OBJECT_TO_JSVAL(obj); - js_proxy_t *p = jsb_new_proxy(ret, obj); - JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); - } else { - jsret = JSVAL_NULL; - } - } while (0); - JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + PhysicsSprite* ret = PhysicsSprite::createWithSpriteFrameName(arg0); + + jsval jsret; + do { + if (ret) { + TypeTest t; + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); + jsret = OBJECT_TO_JSVAL(obj); + js_proxy_t *p = jsb_new_proxy(ret, obj); + JS_AddNamedObjectRoot(cx, &p->obj, "CCPhysicsSprite"); + } else { + jsret = JSVAL_NULL; + } + } while (0); + JS_SET_RVAL(cx, vp, jsret); + return JS_TRUE; + } + + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return JS_FALSE; } void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) @@ -450,24 +474,25 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) }; TypeTest t1; - js_type_class_t *typeClass; - uint32_t typeId = t1.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t1.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); JSPROXY_CCPhysicsSprite_object = JS_InitClass(cx, globalObj, typeClass->proto, JSPROXY_CCPhysicsSprite_class, dummy_constructor, 0,properties,funcs,NULL,st_funcs); TypeTest t; js_type_class_t *p; typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = JSPROXY_CCPhysicsSprite_class; p->proto = JSPROXY_CCPhysicsSprite_object; p->parentProto = typeClass->proto; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 141c335bfe..bbc36bbe5b 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -3ba4ef8fa21631bee450ece05841803624c2e636 \ No newline at end of file +36a6cc6177c059364c6ccc3b1151b6475219b396 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index 3e98123689..9c03489007 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -39,14 +39,23 @@ extern callfuncTarget_proxy_t *_callfuncTarget_native_ht; */ template inline js_type_class_t *js_get_type_from_native(T* native_obj) { - js_type_class_t *typeProxy; + bool found = false; long typeId = typeid(*native_obj).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); - if (!typeProxy) { + auto typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter == _js_global_type_map.end()) + { typeId = typeid(T).hash_code(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeProxy); + typeProxyIter = _js_global_type_map.find(typeId); + if (typeProxyIter != _js_global_type_map.end()) + { + found = true; + } } - return typeProxy; + else + { + found = true; + } + return found ? typeProxyIter->second : nullptr; } /** diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index 9fbf145647..3a35eab630 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -32,24 +32,27 @@ JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) if (argc == 0) { GLNode* cobj = new GLNode(); -#ifdef COCOS2D_JAVASCRIPT cocos2d::Object *_ccobj = dynamic_cast(cobj); if (_ccobj) { _ccobj->autorelease(); } -#endif + TypeTest t; - js_type_class_t *typeClass; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, typeClass); - assert(typeClass); + js_type_class_t *typeClass = nullptr; + long typeId = t.s_id(); + auto typeMapIter = _js_global_type_map.find(typeId); + + CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); + typeClass = typeMapIter->second; + CCASSERT(typeClass, "The value is null."); + JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); // link the native object with the javascript object js_proxy_t *p = jsb_new_proxy(cobj, obj); -#ifdef COCOS2D_JAVASCRIPT + JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode"); -#endif + return JS_TRUE; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); @@ -131,14 +134,13 @@ void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) { // add the proto and JSClass to the type->js info hash table TypeTest t; js_type_class_t *p; - uint32_t typeId = t.s_id(); - HASH_FIND_INT(_js_global_type_ht, &typeId, p); - if (!p) { + long typeId = t.s_id(); + if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) + { p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); - p->type = typeId; p->jsclass = js_cocos2dx_GLNode_class; p->proto = js_cocos2dx_GLNode_prototype; p->parentProto = jsb_Node_prototype; - HASH_ADD_INT(_js_global_type_ht, type, p); + _js_global_type_map.insert(std::make_pair(typeId, p)); } } diff --git a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h index be9c709c49..e526ad7e7a 100644 --- a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h +++ b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h @@ -3,6 +3,7 @@ #include "jsapi.h" #include "uthash.h" +#include typedef struct js_proxy { void *ptr; @@ -14,20 +15,18 @@ extern js_proxy_t *_native_js_global_ht; extern js_proxy_t *_js_native_global_ht; typedef struct js_type_class { - uint32_t type; JSClass *jsclass; JSObject *proto; JSObject *parentProto; - UT_hash_handle hh; } js_type_class_t; -extern js_type_class_t *_js_global_type_ht; +extern std::unordered_map _js_global_type_map; template< typename DERIVED > class TypeTest { public: - static int s_id() + static long s_id() { // return id unique for DERIVED // NOT SURE IT WILL BE REALLY UNIQUE FOR EACH CLASS!! From 8f8d0f86d773a8a11b60bacadf2a7b0779e127e3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 13:02:20 +0800 Subject: [PATCH 524/557] Updating Bindings-generator. --- cocos/scripting/auto-generated | 2 +- tools/bindings-generator | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c46cc8ed45..7199547f2f 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 +Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 diff --git a/tools/bindings-generator b/tools/bindings-generator index 7ccbabbaa6..22520b8b34 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 7ccbabbaa677607048c511b33cb6d83b2081220e +Subproject commit 22520b8b34bcc73c2adfdf234798908a7dd563b4 From 9d7a8c44f94ff78c6907d0e75829f544a43bbc78 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 14:40:23 +0800 Subject: [PATCH 525/557] Reverts auto-generated. --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 7199547f2f..c46cc8ed45 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 7199547f2f9ffbac4fdeac20e4bb50328c6d9352 +Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 From 5ba1e4ce105518dea858fe3d1679050e48c6a146 Mon Sep 17 00:00:00 2001 From: yinkaile Date: Mon, 11 Nov 2013 14:50:30 +0800 Subject: [PATCH 526/557] 1.remove compiler wornings 2.change void Bone::removeFromParent(bool recursion); to void Bone::removeFromParent(); --- .../editor-support/cocostudio/CCArmature.cpp | 2 +- .../cocostudio/CCArmatureAnimation.cpp | 2 +- .../cocostudio/CCArmatureAnimation.h | 1 + cocos/editor-support/cocostudio/CCBone.cpp | 19 +++++++--------- cocos/editor-support/cocostudio/CCBone.h | 5 ++--- .../cocostudio/CCDataReaderHelper.cpp | 13 +++++------ cocos/editor-support/cocostudio/CCDatas.h | 22 ++++++------------- .../cocostudio/CCProcessBase.cpp | 2 +- .../editor-support/cocostudio/CCProcessBase.h | 3 +-- cocos/editor-support/cocostudio/CCTween.cpp | 2 +- cocos/editor-support/cocostudio/CCTween.h | 1 + 11 files changed, 30 insertions(+), 42 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index b09922ff70..0e19914954 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -289,7 +289,7 @@ void Armature::removeBone(Bone *bone, bool recursion) CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); bone->setArmature(nullptr); - bone->removeFromParent(recursion); + bone->removeFromParent(); if (_topBoneList->containsObject(bone)) { diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index 49aa8e1c6f..47a475d34a 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -208,7 +208,7 @@ void ArmatureAnimation::play(const char *animationName, int durationTo, int dura loop = (loop < 0) ? _movementData->loop : loop; - ProcessBase::play((void *)animationName, durationTo, durationTween, loop, tweenEasing); + ProcessBase::play(durationTo, durationTween, loop, tweenEasing); if (_rawDuration == 0) diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 8d306398e9..ffc9401dda 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -100,6 +100,7 @@ public: //! The animation update speed virtual void setAnimationInternal(float animationInternal); + using ProcessBase::play; /** * Play animation by animation name. * diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index cbd4544120..17541e2e78 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -322,19 +322,16 @@ void Bone::addChildBone(Bone *child) } } -void Bone::removeChildBone(Bone *bone, bool recursion) +void Bone::removeChildBone(Bone *bone) { if (_children && _children->getIndexOfObject(bone) != UINT_MAX ) { - if(recursion) - { - Array *ccbones = bone->_children; + Array *ccbones = bone->_children; - for(auto object : *ccbones) - { - Bone *ccBone = (Bone *)object; - bone->removeChildBone(ccBone, recursion); - } + for(auto object : *ccbones) + { + Bone *ccBone = (Bone *)object; + bone->removeChildBone(ccBone); } bone->setParentBone(nullptr); @@ -345,11 +342,11 @@ void Bone::removeChildBone(Bone *bone, bool recursion) } } -void Bone::removeFromParent(bool recursion) +void Bone::removeFromParent() { if (nullptr != _parentBone) { - _parentBone->removeChildBone(this, recursion); + _parentBone->removeChildBone(this); } } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 4d67c41e2e..17dc334c34 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -114,15 +114,14 @@ public: /** * Remove itself from its parent. - * @param recursion whether or not to remove childBone's display */ - void removeFromParent(bool recursion); + void removeFromParent(); /** * Removes a child Bone * @param bone the bone you want to remove */ - void removeChildBone(Bone *bone, bool recursion); + void removeChildBone(Bone *bone); void update(float delta) override; diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index defb268ada..45c5d85d41 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -595,10 +595,10 @@ ArmatureData *DataReaderHelper::decodeArmature(tinyxml2::XMLElement *armatureXML if (parentName) { parentXML = armatureXML->FirstChildElement(BONE); - std::string name = parentName; + std::string parentNameStr = parentName; while (parentXML) { - if (name.compare(parentXML->Attribute(A_NAME)) == 0) + if (parentNameStr.compare(parentXML->Attribute(A_NAME)) == 0) { break; } @@ -823,7 +823,7 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov } int length = 0; - int i = 0; + int index = 0; int parentTotalDuration = 0; int currentDuration = 0; @@ -864,13 +864,12 @@ MovementBoneData *DataReaderHelper::decodeMovementBone(tinyxml2::XMLElement *mov /* * in this loop we get the corresponding parent frame xml */ - while(i < length && (parentFrameXML ? (totalDuration < parentTotalDuration || totalDuration >= parentTotalDuration + currentDuration) : true)) + while(index < length && (parentFrameXML ? (totalDuration < parentTotalDuration || totalDuration >= parentTotalDuration + currentDuration) : true)) { - parentFrameXML = parentXmlList[i]; + parentFrameXML = parentXmlList[index]; parentTotalDuration += currentDuration; parentFrameXML->QueryIntAttribute(A_DURATION, ¤tDuration); - i++; - + index++; } } diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 4b9c2feca6..065726472e 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -163,10 +163,8 @@ public: */ virtual ~SpriteDisplayData(); - inline void setParam(const char *displayName) - { - this->displayName = displayName; - } + void setParam(const char *pszDisplayName) { this->displayName = pszDisplayName; } + void copy(SpriteDisplayData *displayData); public: /** @@ -197,10 +195,7 @@ public: */ virtual ~ArmatureDisplayData(); - inline void setParam(const char *displayName) - { - this->displayName = displayName; - } + void setParam(const char *pszDisplayName) { this->displayName = pszDisplayName; } void copy(ArmatureDisplayData *displayData); public: /** @@ -230,10 +225,7 @@ public: */ virtual ~ParticleDisplayData() {}; - void setParam(const char *plist) - { - this->plist = plist; - } + void setParam(const char *pszPlistName) { this->plist = pszPlistName; } void copy(ParticleDisplayData *displayData); public: @@ -478,10 +470,10 @@ public: struct ContourVertex2 : public cocos2d::Object { - ContourVertex2(float x, float y) + ContourVertex2(float xx, float yy) { - this->x = x; - this->y = y; + this->x = xx; + this->y = yy; } float x; diff --git a/cocos/editor-support/cocostudio/CCProcessBase.cpp b/cocos/editor-support/cocostudio/CCProcessBase.cpp index 62bac419b6..f13769e3f7 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.cpp +++ b/cocos/editor-support/cocostudio/CCProcessBase.cpp @@ -77,7 +77,7 @@ void ProcessBase::stop() _currentPercent = 0; } -void ProcessBase::play(void *animation, int durationTo, int durationTween, int loop, int tweenEasing) +void ProcessBase::play(int durationTo, int durationTween, int loop, int tweenEasing) { _isComplete = false; _isPause = false; diff --git a/cocos/editor-support/cocostudio/CCProcessBase.h b/cocos/editor-support/cocostudio/CCProcessBase.h index 2b3ef4ab47..e763616c38 100644 --- a/cocos/editor-support/cocostudio/CCProcessBase.h +++ b/cocos/editor-support/cocostudio/CCProcessBase.h @@ -63,7 +63,6 @@ public: /** * Play animation by animation name. * - * @param animation It will not used in the ProcessBase Class * @param durationTo The frames between two animation changing-over. * It's meaning is changing to this animation need how many frames * @@ -88,7 +87,7 @@ public: * 2 : fade in and out * */ - virtual void play(void *animation, int durationTo, int durationTween, int loop, int tweenEasing); + virtual void play(int durationTo, int durationTween, int loop, int tweenEasing); /** * Pause the Process diff --git a/cocos/editor-support/cocostudio/CCTween.cpp b/cocos/editor-support/cocostudio/CCTween.cpp index dec84bf295..953ea34583 100644 --- a/cocos/editor-support/cocostudio/CCTween.cpp +++ b/cocos/editor-support/cocostudio/CCTween.cpp @@ -98,7 +98,7 @@ bool Tween::init(Bone *bone) void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing) { - ProcessBase::play(nullptr, durationTo, durationTween, loop, tweenEasing); + ProcessBase::play(durationTo, durationTween, loop, tweenEasing); if (loop) { diff --git a/cocos/editor-support/cocostudio/CCTween.h b/cocos/editor-support/cocostudio/CCTween.h index 8b4dcba9d2..ab8bb3f7ff 100644 --- a/cocos/editor-support/cocostudio/CCTween.h +++ b/cocos/editor-support/cocostudio/CCTween.h @@ -59,6 +59,7 @@ public: */ virtual bool init(Bone *bone); + using ProcessBase::play; /** * Start the Process * From 00b477e7563fc4b427069e179d9a346423af7431 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 15:11:28 +0800 Subject: [PATCH 527/557] [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 743d94f96f..e9e1da977c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,6 +19,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc. [NEW] Sprite: Override setScale(float scaleX, float scaleY) [NEW] External: added | operator for Control::EventType + [NEW] Android & iOS screen size change support [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From 677cf0035553e06606ad4799022cda19f92b328c Mon Sep 17 00:00:00 2001 From: yinkaile Date: Mon, 11 Nov 2013 15:29:24 +0800 Subject: [PATCH 528/557] fix compiler warning --- .../editor-support/cocostudio/CCArmature.cpp | 2 +- cocos/editor-support/cocostudio/CCBone.cpp | 19 +++++++++++-------- cocos/editor-support/cocostudio/CCBone.h | 6 ++++-- .../cocostudio/CCDisplayManager.cpp | 10 +++++----- 4 files changed, 21 insertions(+), 16 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index 0e19914954..b09922ff70 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -289,7 +289,7 @@ void Armature::removeBone(Bone *bone, bool recursion) CCASSERT(bone != nullptr, "bone must be added to the bone dictionary!"); bone->setArmature(nullptr); - bone->removeFromParent(); + bone->removeFromParent(recursion); if (_topBoneList->containsObject(bone)) { diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 17541e2e78..cbd4544120 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -322,16 +322,19 @@ void Bone::addChildBone(Bone *child) } } -void Bone::removeChildBone(Bone *bone) +void Bone::removeChildBone(Bone *bone, bool recursion) { if (_children && _children->getIndexOfObject(bone) != UINT_MAX ) { - Array *ccbones = bone->_children; - - for(auto object : *ccbones) + if(recursion) { - Bone *ccBone = (Bone *)object; - bone->removeChildBone(ccBone); + Array *ccbones = bone->_children; + + for(auto object : *ccbones) + { + Bone *ccBone = (Bone *)object; + bone->removeChildBone(ccBone, recursion); + } } bone->setParentBone(nullptr); @@ -342,11 +345,11 @@ void Bone::removeChildBone(Bone *bone) } } -void Bone::removeFromParent() +void Bone::removeFromParent(bool recursion) { if (nullptr != _parentBone) { - _parentBone->removeChildBone(this); + _parentBone->removeChildBone(this, recursion); } } diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index 17dc334c34..8a603c1ad3 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -112,16 +112,18 @@ public: */ Bone *getParentBone(); + using Node::removeFromParent; /** * Remove itself from its parent. + * @param recursion whether or not to remove childBone's display */ - void removeFromParent(); + void removeFromParent(bool recursion); /** * Removes a child Bone * @param bone the bone you want to remove */ - void removeChildBone(Bone *bone); + void removeChildBone(Bone *bone, bool recursion); void update(float delta) override; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 6bcf7eaff3..3c502f2fe7 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -146,13 +146,13 @@ void DisplayManager::addDisplay(Node *display, int index) for (int i = _decoDisplayList->count()-2; i>=0; i--) { - DecorativeDisplay *dd = static_cast(_decoDisplayList->objectAtIndex(i)); - SpriteDisplayData *spriteDisplayData = static_cast(dd->getDisplayData()); - if (spriteDisplayData) + DecorativeDisplay *dd = static_cast(_decoDisplayList->getObjectAtIndex(i)); + SpriteDisplayData *sdd = static_cast(dd->getDisplayData()); + if (sdd) { find = true; - skin->setSkinData(spriteDisplayData->skinData); - static_cast(displayData)->skinData = spriteDisplayData->skinData; + skin->setSkinData(sdd->skinData); + static_cast(displayData)->skinData = sdd->skinData; break; } } From 3fc16256ab2869eeb02e65b4684c629798e026d3 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 15:40:12 +0800 Subject: [PATCH 529/557] issue #3025: move deprecated texture cache implementation to cpp file --- cocos/2d/CCTextureCache.cpp | 10 ++++++++++ cocos/2d/CCTextureCache.h | 8 ++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 780e0330aa..c4276757c6 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -79,6 +79,16 @@ void TextureCache::destroyInstance() { } +TextureCache * TextureCache::sharedTextureCache() +{ + return TextureCache::getInstance(); +} + +void TextureCache::purgeSharedTextureCache() +{ + return TextureCache::destroyInstance(); +} + const char* TextureCache::description() const { return String::createWithFormat("", _textures.size() )->getCString(); diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index c4c14bad53..eb6ca47a22 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -50,6 +50,10 @@ NS_CC_BEGIN * @addtogroup textures * @{ */ +/* +* from version 3.0, TextureCache will never to treated as a singleton, it will be owned by director. +* all call by TextureCache::getInstance() should be replaced by Director::getInstance()->getTextureCache() +*/ /** @brief Singleton that handles the loading of textures * Once the texture is loaded, the next time it will return @@ -62,7 +66,7 @@ public: CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance(); /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); } + CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache(); /** purges the cache. It releases the retained instance. @since v0.99.0 @@ -70,7 +74,7 @@ public: CC_DEPRECATED_ATTRIBUTE static void destroyInstance(); /** @deprecated Use destroyInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); } + CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache(); /** Reload all textures should not call it, called by frame work From 796c75f834570277d7fc78f3cb1bcb16fe217898 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 15:56:15 +0800 Subject: [PATCH 530/557] [ci skip]change the building commands of linux --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1cfd3a014d..2b1a5fa297 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,12 @@ $ open samples.xcodeproj * For Linux ``` -$ cd cocos2d-x -$ cmake CMakeLists.txt -$ make +$ cd cocos2d-x/build +$ ./make-all-linux-project.sh ``` +You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + * For Windows Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln` From 272afaa7d9d4cd11df732d63e3cb9f1ecfd7c273 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:57:15 +0800 Subject: [PATCH 531/557] Updating Bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 22520b8b34..a943736554 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 22520b8b34bcc73c2adfdf234798908a7dd563b4 +Subproject commit a94373655409f756b33d8a58cc798dcb00be257c From dfcae4ed0d6a1dd8d116c251a204d7c59bfcadec Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Mon, 11 Nov 2013 16:04:34 +0800 Subject: [PATCH 532/557] issue #3025: change TextureCache::purgeSharedTextureCache() and TextureCache::sharedTextureCache() to do not call deprecate function anymore --- cocos/2d/CCTextureCache.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index c4276757c6..ab1e0c0eec 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -81,12 +81,11 @@ void TextureCache::destroyInstance() TextureCache * TextureCache::sharedTextureCache() { - return TextureCache::getInstance(); + return Director::getInstance()->getTextureCache(); } void TextureCache::purgeSharedTextureCache() { - return TextureCache::destroyInstance(); } const char* TextureCache::description() const From 2e52dd49050812625d1b9db5972121534276a2c2 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 11 Nov 2013 08:05:15 +0000 Subject: [PATCH 533/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index c46cc8ed45..5788b25003 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit c46cc8ed45556e377715dcca2da91ae037dbc7e4 +Subproject commit 5788b2500339473ecc19acf1c2e43656a2537a6d From 0151ac60ba6cb69f45d8a7d32ac9b7fd58b21c6a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:26:25 +0800 Subject: [PATCH 534/557] =?UTF-8?q?fix=2064bit=20warning.=20unsigned=20int?= =?UTF-8?q?=20(int)=20=E2=80=94>=20long.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCActionInterval.cpp | 6 +++--- cocos/2d/CCActionManager.cpp | 2 +- cocos/2d/CCActionManager.h | 2 +- cocos/2d/CCAtlasNode.cpp | 4 ++-- cocos/2d/CCAtlasNode.h | 4 ++-- cocos/2d/CCTextureAtlas.cpp | 28 ++++++++++++++-------------- cocos/2d/CCTextureAtlas.h | 8 ++++---- cocos/2d/CCTextureCache.cpp | 2 +- 8 files changed, 28 insertions(+), 28 deletions(-) diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index 0fe7e055b9..14c0fec762 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -203,7 +203,7 @@ Sequence* Sequence::create(Array* arrayOfActions) Sequence* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); @@ -576,7 +576,7 @@ Spawn* Spawn::create(Array *arrayOfActions) Spawn* pRet = NULL; do { - unsigned int count = arrayOfActions->count(); + long count = arrayOfActions->count(); CC_BREAK_IF(count == 0); FiniteTimeAction* prev = static_cast(arrayOfActions->getObjectAtIndex(0)); if (count > 1) @@ -2100,7 +2100,7 @@ void Animate::update(float t) } Array* frames = _animation->getFrames(); - int numberOfFrames = frames->count(); + long numberOfFrames = frames->count(); SpriteFrame *frameToDisplay = NULL; for( int i=_nextFrame; i < numberOfFrames; i++ ) { diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 0b258f4a6e..dd2b528bce 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -327,7 +327,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const +long ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 9e21a77125..8a2c077511 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -102,7 +102,7 @@ public: * - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 7 Sequences of 2 actions, it will return 7. */ - unsigned int getNumberOfRunningActionsInTarget(const Object *target) const; + long getNumberOfRunningActionsInTarget(const Object *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 7ced2ffc9d..b756a36193 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -245,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const return _textureAtlas; } -unsigned int AtlasNode::getQuadsToDraw() const +long AtlasNode::getQuadsToDraw() const { return _quadsToDraw; } -void AtlasNode::setQuadsToDraw(unsigned int uQuadsToDraw) +void AtlasNode::setQuadsToDraw(long uQuadsToDraw) { _quadsToDraw = uQuadsToDraw; } diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 9f06456589..8c31496d41 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -77,8 +77,8 @@ public: void setTextureAtlas(TextureAtlas* textureAtlas); TextureAtlas* getTextureAtlas() const; - void setQuadsToDraw(unsigned int quadsToDraw); - unsigned int getQuadsToDraw() const; + void setQuadsToDraw(long quadsToDraw); + long getQuadsToDraw() const; // Overrides diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index f19a2f5f87..efb944db25 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -72,12 +72,12 @@ TextureAtlas::~TextureAtlas() #endif } -int TextureAtlas::getTotalQuads() const +long TextureAtlas::getTotalQuads() const { return _totalQuads; } -int TextureAtlas::getCapacity() const +long TextureAtlas::getCapacity() const { return _capacity; } @@ -216,7 +216,7 @@ void TextureAtlas::listenBackToForeground(Object *obj) const char* TextureAtlas::description() const { - return String::createWithFormat("", _totalQuads)->getCString(); + return String::createWithFormat("", _totalQuads)->getCString(); } @@ -357,7 +357,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads - int remaining = (_totalQuads-1) - index - amount; + long remaining = (_totalQuads-1) - index - amount; // last object doesn't need to be moved if( remaining > 0) @@ -367,9 +367,9 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount) } - int max = index + amount; + long max = index + amount; int j = 0; - for (int i = index; i < max ; i++) + for (long i = index; i < max ; i++) { _quads[index] = quads[j]; index++; @@ -390,9 +390,9 @@ void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex) } // because it is ambiguous in iphone, so we implement abs ourselves // unsigned int howMany = abs( oldIndex - newIndex); - int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); - int dst = oldIndex; - int src = oldIndex + 1; + long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); + long dst = oldIndex; + long src = oldIndex + 1; if( oldIndex > newIndex) { dst = newIndex+1; @@ -412,7 +412,7 @@ void TextureAtlas::removeQuadAtIndex(long index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); - int remaining = (_totalQuads-1) - index; + long remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining ) @@ -431,7 +431,7 @@ void TextureAtlas::removeQuadsAtIndex(long index, long amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); - int remaining = (_totalQuads) - (index + amount); + long remaining = (_totalQuads) - (index + amount); _totalQuads -= amount; @@ -456,7 +456,7 @@ bool TextureAtlas::resizeCapacity(long newCapacity) { return true; } - int oldCapactiy = _capacity; + long oldCapactiy = _capacity; // update capacity and totolQuads _totalQuads = MIN(_totalQuads, newCapacity); _capacity = newCapacity; @@ -575,8 +575,8 @@ void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount) V3F_C4B_T2F_Quad quad; memset(&quad, 0, sizeof(quad)); - int to = index + amount; - for (int i = index ; i < to ; i++) + long to = index + amount; + for (long i = index ; i < to ; i++) { _quads[i] = quad; } diff --git a/cocos/2d/CCTextureAtlas.h b/cocos/2d/CCTextureAtlas.h index 1e5ec742d7..42922ee80b 100644 --- a/cocos/2d/CCTextureAtlas.h +++ b/cocos/2d/CCTextureAtlas.h @@ -197,10 +197,10 @@ public: const char* description() const; /** Gets the quantity of quads that are going to be drawn */ - int getTotalQuads() const; + long getTotalQuads() const; /** Gets the quantity of quads that can be stored with the current texture atlas size */ - int getCapacity() const; + long getCapacity() const; /** Gets the texture of the texture atlas */ Texture2D* getTexture() const; @@ -231,9 +231,9 @@ protected: GLuint _buffersVBO[2]; //0: vertex 1: indices bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated /** quantity of quads that are going to be drawn */ - int _totalQuads; + long _totalQuads; /** quantity of quads that can be stored with the current texture atlas size */ - int _capacity; + long _capacity; /** Texture of the texture atlas */ Texture2D* _texture; /** Quads that are going to be rendered */ diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 780e0330aa..17aa00effb 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -441,7 +441,7 @@ void TextureCache::dumpCachedTextureInfo() const Texture2D* tex = it->second; unsigned int bpp = tex->getBitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. - unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; + long bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", From 20b350a58b00d29f1c91999a28aea819885da2df Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:27:58 +0800 Subject: [PATCH 535/557] Removing cocosjs_manual_conversions.h(.cpp). Put all jsval <-> native value conversion codes to js_manual_conversions.h(.cpp). --- .../project.pbxproj.REMOVED.git-id | 2 +- .../scripting/javascript/bindings/Android.mk | 1 - .../javascript/bindings/ScriptingCore.cpp | 1037 -------------- .../javascript/bindings/ScriptingCore.h | 40 +- ...s_chipmunk_auto_classes.cpp.REMOVED.git-id | 2 +- ...ings_chipmunk_functions.cpp.REMOVED.git-id | 2 +- .../chipmunk/js_bindings_chipmunk_manual.h | 1 - .../bindings/cocosjs_manual_conversions.cpp | 134 -- .../bindings/cocosjs_manual_conversions.h | 24 - .../bindings/js_manual_conversions.cpp | 1227 ++++++++++++++++- .../bindings/js_manual_conversions.h | 69 +- .../bindings/jsb_opengl_functions.cpp | 515 ++++--- .../javascript/bindings/jsb_opengl_manual.cpp | 1 - .../bindings/proj.win32/libJSBinding.vcxproj | 2 - .../proj.win32/libJSBinding.vcxproj.filters | 6 - 15 files changed, 1470 insertions(+), 1593 deletions(-) delete mode 100644 cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp delete mode 100644 cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 1ebbc707a8..5639c9df83 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -30ca6c02884f9bc20405b3e657b444c0153bead7 \ No newline at end of file +a70914e0a87ee8ced4d662bd6038fc955e77f6ca \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/Android.mk b/cocos/scripting/javascript/bindings/Android.mk index 8195fde121..ffb0167ce1 100644 --- a/cocos/scripting/javascript/bindings/Android.mk +++ b/cocos/scripting/javascript/bindings/Android.mk @@ -9,7 +9,6 @@ LOCAL_MODULE_FILENAME := libcocos2dxjsb LOCAL_SRC_FILES := ScriptingCore.cpp \ cocos2d_specifics.cpp \ js_manual_conversions.cpp \ - cocosjs_manual_conversions.cpp \ js_bindings_core.cpp \ js_bindings_opengl.cpp \ jsb_opengl_functions.cpp \ diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 462debba9d..86ddb4bd2e 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -1159,803 +1159,6 @@ int ScriptingCore::sendEvent(ScriptEvent* evt) return 0; } -#pragma mark - Conversion Routines -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (int32_t)dp; - - return ok; -} - -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint32_t)dp; - - return ok; -} - -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ok = JS_TRUE; - double dp; - ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ok &= !isnan(dp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *outval = (uint16_t)dp; - - return ok; -} - -JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - 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]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { - JSString *tmp = JS_ValueToString(cx, v); - JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); - - JSStringWrapper str(tmp); - *ret = str.get(); - return JS_TRUE; -} - -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - double x, y; - 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = (float)x; - ret->y = (float)y; - return JS_TRUE; -} - -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jsz(cx); - JS::RootedValue jstimestamp(cx); - - double x, y, timestamp, z; - 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->x = x; - ret->y = y; - ret->z = z; - ret->timestamp = timestamp; - return JS_TRUE; -} - -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) -{ - JSBool ok = JS_TRUE; - Array* pArray = Array::create(); - for( int i=0; i < argc; i++ ) - { - double num = 0.0; - // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number - if ( JSVAL_IS_NUMBER(*vp)) { - ok &= JS_ValueToNumber(cx, *vp, &num ); - if (!ok) { - break; - } - pArray->addObject(Integer::create((int)num)); - } - else if (JSVAL_IS_STRING(*vp)) - { - JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); - pArray->addObject(String::create(str.get())); - } - else - { - js_proxy_t* p; - JSObject* obj = JSVAL_TO_OBJECT(*vp); - p = jsb_get_js_proxy(obj); - if (p) { - pArray->addObject((Object*)p->ptr); - } - } - // next - vp++; - } - *ret = pArray; - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - return ok; -} - -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { - JSObject *tmp; - JS::RootedValue jsx(cx); - JS::RootedValue jsy(cx); - JS::RootedValue jswidth(cx); - JS::RootedValue jsheight(cx); - - double x, y, width, height; - 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) && - JS_GetProperty(cx, tmp, "height", &jsheight) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jswidth, &width) && - JS_ValueToNumber(cx, jsheight, &height); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->origin.x = x; - ret->origin.y = y; - ret->size.width = width; - ret->size.height = height; - return JS_TRUE; -} - -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { - JSObject *tmp; - JS::RootedValue jsw(cx); - JS::RootedValue jsh(cx); - double w, h; - 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->width = w; - ret->height = h; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - - double r, g, b, a; - 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) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsa(cx); - double r, g, b, a; - 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) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - ret->r = r; - ret->g = g; - ret->b = b; - ret->a = a; - return JS_TRUE; -} - -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { - JSObject *tmp; - JS::RootedValue jsr(cx); - JS::RootedValue jsg(cx); - JS::RootedValue jsb(cx); - double r, g, b; - 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) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - ret->r = r; - ret->g = g; - ret->b = b; - return JS_TRUE; -} - -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { - // Parsing sequence - JSObject *jsobj; - 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); - - Point *array = (Point*)malloc( sizeof(Point) * len); - - for( uint32_t i=0; i< len;i++ ) { - jsval valarg; - JS_GetElement(cx, jsobj, i, &valarg); - - ok = jsval_to_ccpoint(cx, valarg, &array[i]); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - } - - *numPoints = len; - *points = array; - - return JS_TRUE; -} - - -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { - JSObject *jsobj; - 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); - Array* arr = Array::createWithCapacity(len); - for (uint32_t i=0; i < len; i++) { - jsval value; - if (JS_GetElement(cx, jsobj, i, &value)) { - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native js object. - arr->addObject(cobj); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - arr->addObject(dictVal); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - arr->addObject(arrVal); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - arr->addObject(String::create(valueWapper.get())); -// CCLOG("iterate array: value = %s", valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - arr->addObject(Double::create(number)); -// CCLOG("iterate array: value = %lf", number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - arr->addObject(Bool::create(boolVal)); -// CCLOG("iterate object: value = %d", boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - } - *ret = arr; - return JS_TRUE; -} - - -jsval ccarray_to_jsval(JSContext* cx, Array *arr) -{ - JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); - - Object* obj; - int i = 0; - CCARRAY_FOREACH(arr, obj) - { - jsval arrElement; - - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - arrElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - 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); - } else if ((arrVal = dynamic_cast(obj))) { - arrElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - arrElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { - break; - } - ++i; - } - return OBJECT_TO_JSVAL(jsretArr); -} - -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) -{ - JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); - DictElement* pElement = NULL; - CCDICT_FOREACH(dict, pElement) - { - JS::RootedValue dictElement(cx); - Object* obj = pElement->getObject(); - //First, check whether object is associated with js object. - js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); - if (jsproxy) { - dictElement = OBJECT_TO_JSVAL(jsproxy->obj); - } - else { - String* strVal = NULL; - Dictionary* dictVal = NULL; - Array* arrVal = NULL; - Double* doubleVal = NULL; - Bool* boolVal = NULL; - Float* floatVal = NULL; - Integer* intVal = NULL; - - 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); - } else if ((arrVal = dynamic_cast(obj))) { - dictElement = ccarray_to_jsval(cx, arrVal); - } else if ((doubleVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); - } else if ((floatVal = dynamic_cast(obj))) { - dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); - } else if ((intVal = dynamic_cast(obj))) { - dictElement = INT_TO_JSVAL(intVal->getValue()); - } else if ((boolVal = dynamic_cast(obj))) { - dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); - } else { - CCASSERT(false, "the type isn't suppored."); - } - } - const char* key = pElement->getStrKey(); - if (key && strlen(key) > 0) - { - JS_SetProperty(cx, jsRet, key, dictElement); - } - } - return OBJECT_TO_JSVAL(jsRet); -} - -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { - - if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) - { - *ret = NULL; - return JS_TRUE; - } - - JSObject* tmp = JSVAL_TO_OBJECT(v); - if (!tmp) { - LOGD("jsval_to_ccdictionary: the jsval is not an object."); - return JS_FALSE; - } - - JSObject* it = JS_NewPropertyIterator(cx, tmp); - Dictionary* dict = NULL; - - while (true) - { - jsid idp; - jsval key; - if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error - } - - if (key == JSVAL_VOID) { - break; // end of iteration - } - - if (!JSVAL_IS_STRING(key)) { - continue; // ignore integer properties - } - - JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); - if (!dict) { - dict = Dictionary::create(); - } - - JS::RootedValue value(cx); - JS_GetPropertyById(cx, tmp, idp, &value); - if (value.isObject()) - { - js_proxy_t *proxy; - JSObject *tmp = JSVAL_TO_OBJECT(value); - proxy = jsb_get_js_proxy(tmp); - cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - // Don't test it. - //TEST_NATIVE_OBJECT(cx, cobj) - if (cobj) { - // It's a native <-> js glue object. - dict->setObject(cobj, keyWrapper.get()); - } - else if (!JS_IsArrayObject(cx, tmp)){ - // It's a normal js object. - Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); - if (ok) { - dict->setObject(dictVal, keyWrapper.get()); - } - } - else { - // It's a js array object. - Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); - if (ok) { - dict->setObject(arrVal, keyWrapper.get()); - } - } - } - else if (JSVAL_IS_STRING(value)) { - JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); - dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); - } - else if (JSVAL_IS_NUMBER(value)) { - double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); - if (ok) { - dict->setObject(Double::create(number), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); - } - } - else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); - if (ok) { - dict->setObject(Bool::create(boolVal), keyWrapper.get()); -// CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); - } - } - else { - CCASSERT(false, "not supported type"); - } - } - - *ret = dict; - return JS_TRUE; -} - -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) -{ - JSObject *tmp; - JS::RootedValue jsa(cx); - JS::RootedValue jsb(cx); - JS::RootedValue jsc(cx); - JS::RootedValue jsd(cx); - JS::RootedValue jstx(cx); - JS::RootedValue jsty(cx); - double a, b, c, d, tx, ty; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "a", &jsa) && - JS_GetProperty(cx, tmp, "b", &jsb) && - JS_GetProperty(cx, tmp, "c", &jsc) && - JS_GetProperty(cx, tmp, "d", &jsd) && - JS_GetProperty(cx, tmp, "tx", &jstx) && - JS_GetProperty(cx, tmp, "ty", &jsty) && - JS_ValueToNumber(cx, jsa, &a) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsc, &c) && - JS_ValueToNumber(cx, jsd, &d) && - JS_ValueToNumber(cx, jstx, &tx) && - JS_ValueToNumber(cx, jsty, &ty); - - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); - - *ret = AffineTransformMake(a, b, c, d, tx, ty); - return JS_TRUE; -} - -// From native type to jsval -jsval int32_to_jsval( JSContext *cx, int32_t number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint32_to_jsval( JSContext *cx, uint32_t number ) -{ - return UINT_TO_JSVAL(number); -} - -jsval long_long_to_jsval(JSContext* cx, long long v) { - JSObject *tmp = JS_NewUint32Array(cx, 2); - uint32_t *data = (uint32_t *)JS_GetArrayBufferViewData(tmp); - data[0] = ((uint32_t *)(&v))[0]; - data[1] = ((uint32_t *)(&v))[1]; - return OBJECT_TO_JSVAL(tmp); -} - -jsval std_string_to_jsval(JSContext* cx, const std::string& v) -{ - return c_string_to_jsval(cx, v.c_str(), v.size()); -} - -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) -{ - if (v == NULL) - { - return JSVAL_NULL; - } - - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - - if (0 == length) - { - auto emptyStr = JS_NewStringCopyZ(cx, ""); - return STRING_TO_JSVAL(emptyStr); - } - - jsval ret = JSVAL_NULL; - int utf16_size = 0; - jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); - - if (strUTF16 && utf16_size > 0) { - JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); - if (str) { - ret = STRING_TO_JSVAL(str); - } - delete[] strUTF16; - } - return ret; -} - -jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccsize_to_jsval(JSContext* cx, const Size& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && - JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) -{ - JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JSVAL_NULL; - JSBool ok = JS_TRUE; - - ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Shadow - ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - // Stroke - ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - - if (ok) { - return OBJECT_TO_JSVAL(tmp); - } - return JSVAL_NULL; -} - #pragma mark - Debug void SimpleRunLoop::update(float dt) @@ -2297,246 +1500,6 @@ void jsb_remove_proxy(js_proxy_t* nativeProxy, js_proxy_t* jsProxy) JS_REMOVE_PROXY(nativeProxy, jsProxy); } -static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) -{ - JS::RootedValue jsr(cx); - Color3B out; - JS_GetProperty(cx, colorObject, "r", &jsr); - double fontR = 0.0; - JS_ValueToNumber(cx, jsr, &fontR); - - JS_GetProperty(cx, colorObject, "g", &jsr); - double fontG = 0.0; - JS_ValueToNumber(cx, jsr, &fontG); - - JS_GetProperty(cx, colorObject, "b", &jsr); - double fontB = 0.0; - JS_ValueToNumber(cx, jsr, &fontB); - - // the out - out.r = (unsigned char)fontR; - out.g = (unsigned char)fontG; - out.b = (unsigned char)fontB; - - return out; -} - -Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) -{ - JS::RootedValue jsr(cx); - Size out; - JS_GetProperty(cx, sizeObject, "width", &jsr); - double width = 0.0; - JS_ValueToNumber(cx, jsr, &width); - - JS_GetProperty(cx, sizeObject, "height", &jsr); - double height = 0.0; - JS_ValueToNumber(cx, jsr, &height); - - - // the out - out.width = width; - out.height = height; - - return out; -} - -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) -{ - JSObject *jsobj; - - if (!JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - // defaul values - const char * defautlFontName = "Arial"; - const int defaultFontSize = 32; - TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; - TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; - - // by default shadow and stroke are off - out->_shadow._shadowEnabled = false; - out->_stroke._strokeEnabled = false; - - // white text by default - out->_fontFillColor = Color3B::WHITE; - - // font name - JS::RootedValue jsr(cx); - JS_GetProperty(cx, jsobj, "fontName", &jsr); - JS_ValueToString(cx, jsr); - JSStringWrapper wrapper(jsr); - const char* fontName = wrapper.get(); - - if (fontName && strlen(fontName) > 0) - { - out->_fontName = fontName; - } - else - { - out->_fontName = defautlFontName; - } - - // font size - JSBool hasProperty; - JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontSize", &jsr); - double fontSize = 0.0; - JS_ValueToNumber(cx, jsr, &fontSize); - out->_fontSize = fontSize; - } - else - { - out->_fontSize = defaultFontSize; - } - - // font alignment horizontal - JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_alignment = (TextHAlignment)(int)fontAlign; - } - else - { - out->_alignment = defaultTextAlignment; - } - - // font alignment vertical - JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); - double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); - out->_vertAlignment = (TextVAlignment)(int)fontAlign; - } - else - { - out->_vertAlignment = defaultTextVAlignment; - } - - // font fill color - JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); - - JSObject *jsobjColor; - if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) - return JS_FALSE; - - out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); - } - - // font rendering box dimensions - JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); - - JSObject *jsobjSize; - if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) - return JS_FALSE; - - out->_dimensions = getSizeFromJSObject(cx, jsobjSize); - } - - // shadow - JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); - out->_shadow._shadowEnabled = ToBoolean(jsr); - - if ( out->_shadow._shadowEnabled ) - { - // default shadow values - out->_shadow._shadowOffset = Size(5, 5); - out->_shadow._shadowBlur = 1; - out->_shadow._shadowOpacity = 1; - - // shado offset - JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); - - JSObject *jsobjShadowOffset; - if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) - return JS_FALSE; - out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); - } - - // shadow blur - JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); - double shadowBlur = 0.0; - JS_ValueToNumber(cx, jsr, &shadowBlur); - out->_shadow._shadowBlur = shadowBlur; - } - - // shadow intensity - JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); - double shadowOpacity = 0.0; - JS_ValueToNumber(cx, jsr, &shadowOpacity); - out->_shadow._shadowOpacity = shadowOpacity; - } - } - } - - // stroke - JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); - out->_stroke._strokeEnabled = ToBoolean(jsr); - - if ( out->_stroke._strokeEnabled ) - { - // default stroke values - out->_stroke._strokeSize = 1; - out->_stroke._strokeColor = Color3B::BLUE; - - // stroke color - JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeColor", &jsr); - - JSObject *jsobjStrokeColor; - if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) - return JS_FALSE; - out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); - } - - // stroke size - JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); - if ( hasProperty ) - { - JS_GetProperty(cx, jsobj, "strokeSize", &jsr); - double strokeSize = 0.0; - JS_ValueToNumber(cx, jsr, &strokeSize); - out->_stroke._strokeSize = strokeSize; - } - } - } - - // we are done here - return JS_TRUE; -} - // JSStringWrapper JSStringWrapper::JSStringWrapper() : _buffer(nullptr) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index 7f0e367d92..b0c6c45acb 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -17,6 +17,7 @@ #include "jsapi.h" #include "jsfriendapi.h" #include "spidermonkey_specifics.h" +#include "js_manual_conversions.h" void js_log(const char *format, ...); @@ -204,45 +205,6 @@ public: int handleKeypadEvent(void* data); }; -// some utility functions -// to native -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); -JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret); -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret); -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret); -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret); -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret); -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret); -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints); -JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret); -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret); -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret); -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret); -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret); -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition* ret ); - -// from native -jsval int32_to_jsval( JSContext *cx, int32_t l); -jsval uint32_to_jsval( JSContext *cx, uint32_t number ); -jsval long_long_to_jsval(JSContext* cx, long long v); -jsval std_string_to_jsval(JSContext* cx, const std::string& v); -jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); -jsval ccpoint_to_jsval(JSContext* cx, const Point& v); -jsval ccrect_to_jsval(JSContext* cx, const Rect& v); -jsval ccsize_to_jsval(JSContext* cx, const Size& v); -jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v); -jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v); -jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v); -jsval ccdictionary_to_jsval(JSContext* cx, Dictionary *dict); -jsval ccarray_to_jsval(JSContext* cx, Array *arr); -jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v); -jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t); -jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t); - JSObject* NewGlobalObject(JSContext* cx, bool debug = false); // just a simple utility to avoid mem leaking when using JSString diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id index c8c345c32c..0e67c34489 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id @@ -1 +1 @@ -6558be4f421be9227dc4fabf1b682d479825bd18 \ No newline at end of file +2a8f07a22574900290f772ad5a580ef9fc57a9b8 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id index 5cf2a4495d..264696d780 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id @@ -1 +1 @@ -1c5eb9cd58c82de77374cdfa5c9ff647cc8b2f02 \ No newline at end of file +ac3eca550f3b923d03d042ed63edf3b66cc183b7 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h index c6b40ca757..6807bd63e1 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h @@ -27,7 +27,6 @@ #define __js_bindings_chipmunk_manual #include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" #include "js_manual_conversions.h" #include "ScriptingCore.h" #ifdef JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp deleted file mode 100644 index 56bd017069..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include "jsapi.h" -#include "jsfriendapi.h" -#include "ScriptingCore.h" -#include "js_bindings_config.h" -#include "cocosjs_manual_conversions.h" - -#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -using namespace cocos2d; - -JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) -{ -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; - - JSB_PRECONDITION( jsobj, "Not a valid JS object"); - - JS::RootedValue valx(cx); - JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; - ok &= JS_GetProperty(cx, jsobj, "x", &valx); - ok &= JS_GetProperty(cx, jsobj, "y", &valy); - - if( ! ok ) - return JS_FALSE; - - double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); - - if( ! ok ) - return JS_FALSE; - - ret->x = x; - ret->y = y; - - return JS_TRUE; - -#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *tmp_arg; - if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; - - JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); - - JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); - - *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); - - return JS_TRUE; -#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} - - -jsval CGPoint_to_jsval( JSContext *cx, cpVect p) -{ - -#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - - JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - if (!object) - return JSVAL_VOID; - - if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || - !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JSVAL_VOID; - - return OBJECT_TO_JSVAL(object); - -#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - -#ifdef __LP64__ - JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); -#else - JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); -#endif - - cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); - *buffer = p; - return OBJECT_TO_JSVAL(typedArray); -#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -} diff --git a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h b/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h deleted file mode 100644 index 339ac7da9c..0000000000 --- a/cocos/scripting/javascript/bindings/cocosjs_manual_conversions.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __COCOSJS_MANUAL_CONVERSIONS_H__ -#define __COCOSJS_MANUAL_CONVERSIONS_H__ - -#include "chipmunk.h" -#include "cocos2d.h" -#include "js_manual_conversions.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif - -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); -jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); - - -//#ifdef __cplusplus -//} -//#endif - -#define cpVect_to_jsval CGPoint_to_jsval -#define jsval_to_cpVect jsval_to_CGPoint - -#endif /* __COCOSJS_MANUAL_CONVERSIONS_H__ */ - diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 521d1be2aa..0e3e20b617 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -8,6 +8,53 @@ #include "ScriptingCore.h" #include "js_bindings_config.h" #include "js_manual_conversions.h" +#include "cocos2d_specifics.hpp" + +USING_NS_CC; + +static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) +{ + JS::RootedValue jsr(cx); + Color3B out; + JS_GetProperty(cx, colorObject, "r", &jsr); + double fontR = 0.0; + JS_ValueToNumber(cx, jsr, &fontR); + + JS_GetProperty(cx, colorObject, "g", &jsr); + double fontG = 0.0; + JS_ValueToNumber(cx, jsr, &fontG); + + JS_GetProperty(cx, colorObject, "b", &jsr); + double fontB = 0.0; + JS_ValueToNumber(cx, jsr, &fontB); + + // the out + out.r = (unsigned char)fontR; + out.g = (unsigned char)fontG; + out.b = (unsigned char)fontB; + + return out; +} + +static Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) +{ + JS::RootedValue jsr(cx); + Size out; + JS_GetProperty(cx, sizeObject, "width", &jsr); + double width = 0.0; + JS_ValueToNumber(cx, jsr, &width); + + JS_GetProperty(cx, sizeObject, "height", &jsr); + double height = 0.0; + JS_ValueToNumber(cx, jsr, &height); + + + // the out + out.width = width; + out.height = height; + + return out; +} JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **r) { @@ -74,24 +121,6 @@ JSBool jsval_to_long( JSContext *cx, jsval vp, long *r ) return JS_TRUE; } -JSBool jsval_to_longlong( 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"); - - uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); - long long ret = arg_array[0]; - ret = ret << 32; - ret |= arg_array[1]; - - *r = ret; - return JS_TRUE; -} - - jsval opaque_to_jsval( JSContext *cx, void *opaque ) { #ifdef __LP64__ @@ -147,53 +176,6 @@ JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *ret ) return jsval_to_int32(cx, vp, (int32_t*)ret); } - -JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (int32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint32_t)dp; - } - return ret; -} - -JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) -{ - JSBool ret = JS_FALSE; - double dp; - if( (ret=JS_ValueToNumber(cx, vp, &dp)) ) { - if( isnan(dp)) - return JS_FALSE; - *outval = (uint16_t)dp; - } - return ret; -} - -jsval int_to_jsval( JSContext *cx, int number ) -{ - return INT_TO_JSVAL(number); -} - -jsval uint_to_jsval( JSContext *cx, unsigned int number ) -{ - return UINT_TO_JSVAL(number); -} - jsval long_to_jsval( JSContext *cx, long number ) { #ifdef __LP64__ @@ -249,12 +231,9 @@ JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) jsval charptr_to_jsval( JSContext *cx, const char *str) { - JSString *ret_obj = JS_NewStringCopyZ(cx, str); - return STRING_TO_JSVAL(ret_obj); + return c_string_to_jsval(cx, str); } - - JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t) { JSObject *jsobj; @@ -345,4 +324,1114 @@ JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, } +#pragma mark - Conversion Routines +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (int32_t)dp; + + return ok; +} +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint32_t)dp; + + return ok; +} + +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) +{ + JSBool ok = JS_TRUE; + double dp; + ok &= JS_ValueToNumber(cx, vp, &dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= !isnan(dp); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *outval = (uint16_t)dp; + + return ok; +} + +JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { + JSObject *tmp_arg; + JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + 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]; + ret = ret << 32; + ret |= arg_array[1]; + + *r = ret; + return JS_TRUE; +} + +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { + JSString *tmp = JS_ValueToString(cx, v); + JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); + + JSStringWrapper str(tmp); + *ret = str.get(); + return JS_TRUE; +} + +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + double x, y; + 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = (float)x; + ret->y = (float)y; + return JS_TRUE; +} + +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jsz(cx); + JS::RootedValue jstimestamp(cx); + + double x, y, timestamp, z; + 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->x = x; + ret->y = y; + ret->z = z; + ret->timestamp = timestamp; + return JS_TRUE; +} + +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) +{ + JSBool ok = JS_TRUE; + Array* pArray = Array::create(); + for( int i=0; i < argc; i++ ) + { + double num = 0.0; + // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number + if ( JSVAL_IS_NUMBER(*vp)) { + ok &= JS_ValueToNumber(cx, *vp, &num ); + if (!ok) { + break; + } + pArray->addObject(Integer::create((int)num)); + } + else if (JSVAL_IS_STRING(*vp)) + { + JSStringWrapper str(JSVAL_TO_STRING(*vp), cx); + pArray->addObject(String::create(str.get())); + } + else + { + js_proxy_t* p; + JSObject* obj = JSVAL_TO_OBJECT(*vp); + p = jsb_get_js_proxy(obj); + if (p) { + pArray->addObject((Object*)p->ptr); + } + } + // next + vp++; + } + *ret = pArray; + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + return ok; +} + +JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { + JSObject *tmp; + JS::RootedValue jsx(cx); + JS::RootedValue jsy(cx); + JS::RootedValue jswidth(cx); + JS::RootedValue jsheight(cx); + + double x, y, width, height; + 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) && + JS_GetProperty(cx, tmp, "height", &jsheight) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jswidth, &width) && + JS_ValueToNumber(cx, jsheight, &height); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->origin.x = x; + ret->origin.y = y; + ret->size.width = width; + ret->size.height = height; + return JS_TRUE; +} + +JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { + JSObject *tmp; + JS::RootedValue jsw(cx); + JS::RootedValue jsh(cx); + double w, h; + 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_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->width = w; + ret->height = h; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + + double r, g, b, a; + 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) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsa(cx); + double r, g, b, a; + 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) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsa, &a); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + ret->r = r; + ret->g = g; + ret->b = b; + ret->a = a; + return JS_TRUE; +} + +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { + JSObject *tmp; + JS::RootedValue jsr(cx); + JS::RootedValue jsg(cx); + JS::RootedValue jsb(cx); + double r, g, b; + 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) && + JS_ValueToNumber(cx, jsr, &r) && + JS_ValueToNumber(cx, jsg, &g) && + JS_ValueToNumber(cx, jsb, &b); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + ret->r = r; + ret->g = g; + ret->b = b; + return JS_TRUE; +} + +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { + // Parsing sequence + JSObject *jsobj; + 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); + + Point *array = (Point*)malloc( sizeof(Point) * len); + + for( uint32_t i=0; i< len;i++ ) { + jsval valarg; + JS_GetElement(cx, jsobj, i, &valarg); + + ok = jsval_to_ccpoint(cx, valarg, &array[i]); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + } + + *numPoints = len; + *points = array; + + return JS_TRUE; +} + + +JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { + JSObject *jsobj; + 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); + Array* arr = Array::createWithCapacity(len); + for (uint32_t i=0; i < len; i++) { + jsval value; + if (JS_GetElement(cx, jsobj, i, &value)) { + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native js object. + arr->addObject(cobj); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + arr->addObject(dictVal); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + arr->addObject(arrVal); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + arr->addObject(String::create(valueWapper.get())); + // CCLOG("iterate array: value = %s", valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + arr->addObject(Double::create(number)); + // CCLOG("iterate array: value = %lf", number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + arr->addObject(Bool::create(boolVal)); + // CCLOG("iterate object: value = %d", boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + } + *ret = arr; + return JS_TRUE; +} + + +jsval ccarray_to_jsval(JSContext* cx, Array *arr) +{ + JSObject *jsretArr = JS_NewArrayObject(cx, 0, NULL); + + Object* obj; + int i = 0; + CCARRAY_FOREACH(arr, obj) + { + jsval arrElement; + + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + arrElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + 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); + } else if ((arrVal = dynamic_cast(obj))) { + arrElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + arrElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + arrElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { + break; + } + ++i; + } + return OBJECT_TO_JSVAL(jsretArr); +} + +jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) +{ + JSObject* jsRet = JS_NewObject(cx, NULL, NULL, NULL); + DictElement* pElement = NULL; + CCDICT_FOREACH(dict, pElement) + { + JS::RootedValue dictElement(cx); + Object* obj = pElement->getObject(); + //First, check whether object is associated with js object. + js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); + if (jsproxy) { + dictElement = OBJECT_TO_JSVAL(jsproxy->obj); + } + else { + String* strVal = NULL; + Dictionary* dictVal = NULL; + Array* arrVal = NULL; + Double* doubleVal = NULL; + Bool* boolVal = NULL; + Float* floatVal = NULL; + Integer* intVal = NULL; + + 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); + } else if ((arrVal = dynamic_cast(obj))) { + dictElement = ccarray_to_jsval(cx, arrVal); + } else if ((doubleVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(doubleVal->getValue()); + } else if ((floatVal = dynamic_cast(obj))) { + dictElement = DOUBLE_TO_JSVAL(floatVal->getValue()); + } else if ((intVal = dynamic_cast(obj))) { + dictElement = INT_TO_JSVAL(intVal->getValue()); + } else if ((boolVal = dynamic_cast(obj))) { + dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + } else { + CCASSERT(false, "the type isn't suppored."); + } + } + const char* key = pElement->getStrKey(); + if (key && strlen(key) > 0) + { + JS_SetProperty(cx, jsRet, key, dictElement); + } + } + return OBJECT_TO_JSVAL(jsRet); +} + +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) +{ + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + { + *ret = NULL; + return JS_TRUE; + } + + JSObject* tmp = JSVAL_TO_OBJECT(v); + if (!tmp) { + CCLOG("%s", "jsval_to_ccdictionary: the jsval is not an object."); + return JS_FALSE; + } + + JSObject* it = JS_NewPropertyIterator(cx, tmp); + Dictionary* dict = NULL; + + while (true) + { + jsid idp; + jsval key; + if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { + return JS_FALSE; // error + } + + if (key == JSVAL_VOID) { + break; // end of iteration + } + + if (!JSVAL_IS_STRING(key)) { + continue; // ignore integer properties + } + + JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); + if (!dict) { + dict = Dictionary::create(); + } + + JS::RootedValue value(cx); + JS_GetPropertyById(cx, tmp, idp, &value); + if (value.isObject()) + { + js_proxy_t *proxy; + JSObject *tmp = JSVAL_TO_OBJECT(value); + proxy = jsb_get_js_proxy(tmp); + cocos2d::Object* cobj = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + // Don't test it. + //TEST_NATIVE_OBJECT(cx, cobj) + if (cobj) { + // It's a native <-> js glue object. + dict->setObject(cobj, keyWrapper.get()); + } + else if (!JS_IsArrayObject(cx, tmp)){ + // It's a normal js object. + Dictionary* dictVal = NULL; + JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + if (ok) { + dict->setObject(dictVal, keyWrapper.get()); + } + } + else { + // It's a js array object. + Array* arrVal = NULL; + JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + if (ok) { + dict->setObject(arrVal, keyWrapper.get()); + } + } + } + else if (JSVAL_IS_STRING(value)) { + JSStringWrapper valueWapper(JSVAL_TO_STRING(value), cx); + dict->setObject(String::create(valueWapper.get()), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %s", keyWrapper.get().c_str(), valueWapper.get().c_str()); + } + else if (JSVAL_IS_NUMBER(value)) { + double number = 0.0; + JSBool ok = JS_ValueToNumber(cx, value, &number); + if (ok) { + dict->setObject(Double::create(number), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); + } + } + else if (JSVAL_IS_BOOLEAN(value)) { + JSBool boolVal = JS_FALSE; + JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + if (ok) { + dict->setObject(Bool::create(boolVal), keyWrapper.get()); + // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); + } + } + else { + CCASSERT(false, "not supported type"); + } + } + + *ret = dict; + return JS_TRUE; +} + +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) +{ + JSObject *tmp; + JS::RootedValue jsa(cx); + JS::RootedValue jsb(cx); + JS::RootedValue jsc(cx); + JS::RootedValue jsd(cx); + JS::RootedValue jstx(cx); + JS::RootedValue jsty(cx); + double a, b, c, d, tx, ty; + JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "a", &jsa) && + JS_GetProperty(cx, tmp, "b", &jsb) && + JS_GetProperty(cx, tmp, "c", &jsc) && + JS_GetProperty(cx, tmp, "d", &jsd) && + JS_GetProperty(cx, tmp, "tx", &jstx) && + JS_GetProperty(cx, tmp, "ty", &jsty) && + JS_ValueToNumber(cx, jsa, &a) && + JS_ValueToNumber(cx, jsb, &b) && + JS_ValueToNumber(cx, jsc, &c) && + JS_ValueToNumber(cx, jsd, &d) && + JS_ValueToNumber(cx, jstx, &tx) && + JS_ValueToNumber(cx, jsty, &ty); + + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + + *ret = AffineTransformMake(a, b, c, d, tx, ty); + return JS_TRUE; +} + +// From native type to jsval +jsval int32_to_jsval( JSContext *cx, int32_t number ) +{ + return INT_TO_JSVAL(number); +} + +jsval uint32_to_jsval( JSContext *cx, uint32_t number ) +{ + return UINT_TO_JSVAL(number); +} + +jsval std_string_to_jsval(JSContext* cx, const std::string& v) +{ + return c_string_to_jsval(cx, v.c_str(), v.size()); +} + +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) +{ + if (v == NULL) + { + return JSVAL_NULL; + } + + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + + if (0 == length) + { + auto emptyStr = JS_NewStringCopyZ(cx, ""); + return STRING_TO_JSVAL(emptyStr); + } + + jsval ret = JSVAL_NULL; + int utf16_size = 0; + jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); + + if (strUTF16 && utf16_size > 0) { + JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); + if (str) { + ret = STRING_TO_JSVAL(str); + } + delete[] strUTF16; + } + return ret; +} + +jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccsize_to_jsval(JSContext* cx, const Size& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "tx", DOUBLE_TO_JSVAL(t.tx), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + JS_DefineProperty(cx, tmp, "ty", DOUBLE_TO_JSVAL(t.ty), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) +{ + JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); + if (!tmp) return JSVAL_NULL; + JSBool ok = JS_TRUE; + + ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontSize", int32_to_jsval(cx, t._fontSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentH", int32_to_jsval(cx, (int32_t)t._alignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontAlignmentV", int32_to_jsval(cx, (int32_t)t._vertAlignment), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontFillColor", cccolor3b_to_jsval(cx, t._fontFillColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "fontDimensions", ccsize_to_jsval(cx, t._dimensions), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Shadow + ok &= JS_DefineProperty(cx, tmp, "shadowEnabled", BOOLEAN_TO_JSVAL(t._shadow._shadowEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOffset", ccsize_to_jsval(cx, t._shadow._shadowOffset), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowBlur", DOUBLE_TO_JSVAL(t._shadow._shadowBlur), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "shadowOpacity", DOUBLE_TO_JSVAL(t._shadow._shadowOpacity), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + // Stroke + ok &= JS_DefineProperty(cx, tmp, "strokeEnabled", BOOLEAN_TO_JSVAL(t._stroke._strokeEnabled), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeColor", cccolor3b_to_jsval(cx, t._stroke._strokeColor), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + ok &= JS_DefineProperty(cx, tmp, "strokeSize", DOUBLE_TO_JSVAL(t._stroke._strokeSize), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); + + if (ok) { + return OBJECT_TO_JSVAL(tmp); + } + return JSVAL_NULL; +} + +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) +{ + JSObject *jsobj; + + if (!JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + // defaul values + const char * defautlFontName = "Arial"; + const int defaultFontSize = 32; + TextHAlignment defaultTextAlignment = TextHAlignment::LEFT; + TextVAlignment defaultTextVAlignment = TextVAlignment::TOP; + + // by default shadow and stroke are off + out->_shadow._shadowEnabled = false; + out->_stroke._strokeEnabled = false; + + // white text by default + out->_fontFillColor = Color3B::WHITE; + + // font name + JS::RootedValue jsr(cx); + JS_GetProperty(cx, jsobj, "fontName", &jsr); + JS_ValueToString(cx, jsr); + JSStringWrapper wrapper(jsr); + const char* fontName = wrapper.get(); + + if (fontName && strlen(fontName) > 0) + { + out->_fontName = fontName; + } + else + { + out->_fontName = defautlFontName; + } + + // font size + JSBool hasProperty; + JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontSize", &jsr); + double fontSize = 0.0; + JS_ValueToNumber(cx, jsr, &fontSize); + out->_fontSize = fontSize; + } + else + { + out->_fontSize = defaultFontSize; + } + + // font alignment horizontal + JS_HasProperty(cx, jsobj, "fontAlignmentH", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_alignment = (TextHAlignment)(int)fontAlign; + } + else + { + out->_alignment = defaultTextAlignment; + } + + // font alignment vertical + JS_HasProperty(cx, jsobj, "fontAlignmentV", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); + double fontAlign = 0.0; + JS_ValueToNumber(cx, jsr, &fontAlign); + out->_vertAlignment = (TextVAlignment)(int)fontAlign; + } + else + { + out->_vertAlignment = defaultTextVAlignment; + } + + // font fill color + JS_HasProperty(cx, jsobj, "fontFillColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); + + JSObject *jsobjColor; + if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) + return JS_FALSE; + + out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); + } + + // font rendering box dimensions + JS_HasProperty(cx, jsobj, "fontDimensions", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); + + JSObject *jsobjSize; + if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) + return JS_FALSE; + + out->_dimensions = getSizeFromJSObject(cx, jsobjSize); + } + + // shadow + JS_HasProperty(cx, jsobj, "shadowEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); + out->_shadow._shadowEnabled = ToBoolean(jsr); + + if ( out->_shadow._shadowEnabled ) + { + // default shadow values + out->_shadow._shadowOffset = Size(5, 5); + out->_shadow._shadowBlur = 1; + out->_shadow._shadowOpacity = 1; + + // shado offset + JS_HasProperty(cx, jsobj, "shadowOffset", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); + + JSObject *jsobjShadowOffset; + if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) + return JS_FALSE; + out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); + } + + // shadow blur + JS_HasProperty(cx, jsobj, "shadowBlur", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); + double shadowBlur = 0.0; + JS_ValueToNumber(cx, jsr, &shadowBlur); + out->_shadow._shadowBlur = shadowBlur; + } + + // shadow intensity + JS_HasProperty(cx, jsobj, "shadowOpacity", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); + double shadowOpacity = 0.0; + JS_ValueToNumber(cx, jsr, &shadowOpacity); + out->_shadow._shadowOpacity = shadowOpacity; + } + } + } + + // stroke + JS_HasProperty(cx, jsobj, "strokeEnabled", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); + out->_stroke._strokeEnabled = ToBoolean(jsr); + + if ( out->_stroke._strokeEnabled ) + { + // default stroke values + out->_stroke._strokeSize = 1; + out->_stroke._strokeColor = Color3B::BLUE; + + // stroke color + JS_HasProperty(cx, jsobj, "strokeColor", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeColor", &jsr); + + JSObject *jsobjStrokeColor; + if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) + return JS_FALSE; + out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); + } + + // stroke size + JS_HasProperty(cx, jsobj, "strokeSize", &hasProperty); + if ( hasProperty ) + { + JS_GetProperty(cx, jsobj, "strokeSize", &jsr); + double strokeSize = 0.0; + JS_ValueToNumber(cx, jsr, &strokeSize); + out->_stroke._strokeSize = strokeSize; + } + } + } + + // we are done here + return JS_TRUE; +} + +#define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) +{ +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *jsobj; + if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + return JS_FALSE; + + JSB_PRECONDITION( jsobj, "Not a valid JS object"); + + JS::RootedValue valx(cx); + JS::RootedValue valy(cx); + JSBool ok = JS_TRUE; + ok &= JS_GetProperty(cx, jsobj, "x", &valx); + ok &= JS_GetProperty(cx, jsobj, "y", &valy); + + if( ! ok ) + return JS_FALSE; + + double x, y; + ok &= JS_ValueToNumber(cx, valx, &x); + ok &= JS_ValueToNumber(cx, valy, &y); + + if( ! ok ) + return JS_FALSE; + + ret->x = x; + ret->y = y; + + return JS_TRUE; + +#else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *tmp_arg; + if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) + return JS_FALSE; + + JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); + + JSB_PRECONDITION( JS_GetTypedArrayByteLength( tmp_arg, cx ) == sizeof(cpVect), "Invalid length"); + + *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); + + return JS_TRUE; +#endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} + + +jsval CGPoint_to_jsval( JSContext *cx, cpVect p) +{ + +#ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + + JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); + if (!object) + return JSVAL_VOID; + + if (!JS_DefineProperty(cx, object, "x", DOUBLE_TO_JSVAL(p.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || + !JS_DefineProperty(cx, object, "y", DOUBLE_TO_JSVAL(p.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) + return JSVAL_VOID; + + return OBJECT_TO_JSVAL(object); + +#else // JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES + +#ifdef __LP64__ + JSObject *typedArray = JS_NewFloat64Array( cx, 2 ); +#else + JSObject *typedArray = JS_NewFloat32Array( cx, 2 ); +#endif + + cpVect *buffer = (cpVect*)JS_GetArrayBufferViewData(typedArray, cx ); + *buffer = p; + return OBJECT_TO_JSVAL(typedArray); +#endif // ! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES +} diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index 7a4999ae80..b3d15c86e1 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -7,37 +7,70 @@ #include "jsapi.h" #include "js_bindings_core.h" - -//#ifdef __cplusplus -//extern "C" { -//#endif +#include "cocos2d.h" extern JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); extern JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); extern JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); extern JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); -extern JSBool jsval_to_longlong( JSContext *cx, jsval vp, long long *out); -extern jsval opaque_to_jsval( JSContext *cx, void* opaque); -extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); extern JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); -extern jsval int_to_jsval( JSContext *cx, int number ); -extern jsval uint_to_jsval( JSContext *cx, unsigned int number ); -extern jsval long_to_jsval( JSContext *cx, long number ); -extern jsval longlong_to_jsval( JSContext *cx, long long number ); /** converts a jsval (JS string) into a char */ extern JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); + +extern jsval opaque_to_jsval( JSContext *cx, void* opaque); +extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); +extern jsval long_to_jsval( JSContext *cx, long number ); +extern jsval longlong_to_jsval( JSContext *cx, long long number ); + /* Converts a char ptr into a jsval (using JS string) */ extern jsval charptr_to_jsval( JSContext *cx, const char *str); - -extern JSBool JSB_jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ); -extern JSBool JSB_jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval); extern JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); extern JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); -extern JSBool JSB_jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ); -//#ifdef __cplusplus -//} -//#endif +// some utility functions +// to native +JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); +JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); +JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); +JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); +JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); +JSBool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); +JSBool jsval_to_ccrect(JSContext *cx, jsval v, cocos2d::Rect* ret); +JSBool jsval_to_ccsize(JSContext *cx, jsval v, cocos2d::Size* ret); +JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, cocos2d::Color4B* ret); +JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, cocos2d::Color4F* ret); +JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, cocos2d::Color3B* ret); +JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, cocos2d::Point **points, int *numPoints); +JSBool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::Array** ret); +JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::Dictionary** ret); +JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); +JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::Array** ret); +JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); +JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); + +// from native +jsval int32_to_jsval( JSContext *cx, int32_t l); +jsval uint32_to_jsval( JSContext *cx, uint32_t number ); +jsval long_long_to_jsval(JSContext* cx, long long v); +jsval std_string_to_jsval(JSContext* cx, const std::string& v); +jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); +jsval ccpoint_to_jsval(JSContext* cx, const cocos2d::Point& v); +jsval ccrect_to_jsval(JSContext* cx, const cocos2d::Rect& v); +jsval ccsize_to_jsval(JSContext* cx, const cocos2d::Size& v); +jsval cccolor4b_to_jsval(JSContext* cx, const cocos2d::Color4B& v); +jsval cccolor4f_to_jsval(JSContext* cx, const cocos2d::Color4F& v); +jsval cccolor3b_to_jsval(JSContext* cx, const cocos2d::Color3B& v); +jsval ccdictionary_to_jsval(JSContext* cx, cocos2d::Dictionary *dict); +jsval ccarray_to_jsval(JSContext* cx, cocos2d::Array *arr); +jsval ccacceleration_to_jsval(JSContext* cx, const cocos2d::Acceleration& v); +jsval ccaffinetransform_to_jsval(JSContext* cx, const cocos2d::AffineTransform& t); +jsval FontDefinition_to_jsval(JSContext* cx, const cocos2d::FontDefinition& t); + +JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *out ); +jsval CGPoint_to_jsval( JSContext *cx, cpVect p ); + +#define cpVect_to_jsval CGPoint_to_jsval +#define jsval_to_cpVect jsval_to_CGPoint #endif /* __JS_MANUAL_CONVERSIONS_H__ */ diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp index 1d99cff3b3..878191adfd 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp @@ -12,7 +12,6 @@ //#include "jsb_config.h" #include "js_bindings_core.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "jsb_opengl_functions.h" // Arguments: GLenum @@ -23,7 +22,7 @@ JSBool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glActiveTexture((GLenum)arg0 ); @@ -39,8 +38,8 @@ JSBool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glAttachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -56,8 +55,8 @@ JSBool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; const char* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_charptr(cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -74,8 +73,8 @@ JSBool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindBuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -91,8 +90,8 @@ JSBool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindFramebuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -108,8 +107,8 @@ JSBool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindRenderbuffer((GLenum)arg0 , (GLuint)arg1 ); @@ -125,8 +124,8 @@ JSBool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBindTexture((GLenum)arg0 , (GLuint)arg1 ); @@ -142,10 +141,10 @@ JSBool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -161,7 +160,7 @@ JSBool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquation((GLenum)arg0 ); @@ -177,8 +176,8 @@ JSBool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendEquationSeparate((GLenum)arg0 , (GLenum)arg1 ); @@ -194,8 +193,8 @@ JSBool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFunc((GLenum)arg0 , (GLenum)arg1 ); @@ -211,10 +210,10 @@ JSBool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBlendFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -230,10 +229,10 @@ JSBool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg1); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glBufferData((GLenum)arg0 , count, (GLvoid*)arg1 , (GLenum)arg2 ); @@ -249,8 +248,8 @@ JSBool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -268,7 +267,7 @@ JSBool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLenum ret_val; @@ -285,7 +284,7 @@ JSBool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClear((GLbitfield)arg0 ); @@ -301,10 +300,10 @@ JSBool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); @@ -320,7 +319,7 @@ JSBool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearDepthf((GLclampf)arg0 ); @@ -336,7 +335,7 @@ JSBool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glClearStencil((GLint)arg0 ); @@ -352,10 +351,10 @@ JSBool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; uint16_t arg1; uint16_t arg2; uint16_t arg3; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glColorMask((GLboolean)arg0 , (GLboolean)arg1 , (GLboolean)arg2 , (GLboolean)arg3 ); @@ -371,7 +370,7 @@ JSBool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCompileShader((GLuint)arg0 ); @@ -387,13 +386,13 @@ JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; void* arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg7); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -411,14 +410,14 @@ JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; int32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -436,14 +435,14 @@ JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLint)arg3 , (GLint)arg4 , (GLsizei)arg5 , (GLsizei)arg6 , (GLint)arg7 ); @@ -459,14 +458,14 @@ JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg6 ); + ok &= jsval_to_int32( cx, *argvp++, &arg7 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCopyTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLsizei)arg7 ); @@ -493,7 +492,7 @@ JSBool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLuint ret_val; @@ -510,7 +509,7 @@ JSBool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glCullFace((GLenum)arg0 ); @@ -526,7 +525,7 @@ JSBool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteProgram((GLuint)arg0 ); @@ -542,7 +541,7 @@ JSBool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDeleteShader((GLuint)arg0 ); @@ -558,7 +557,7 @@ JSBool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthFunc((GLenum)arg0 ); @@ -574,7 +573,7 @@ JSBool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint16_t arg0; - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthMask((GLboolean)arg0 ); @@ -590,8 +589,8 @@ JSBool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDepthRangef((GLclampf)arg0 , (GLclampf)arg1 ); @@ -607,8 +606,8 @@ JSBool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDetachShader((GLuint)arg0 , (GLuint)arg1 ); @@ -624,7 +623,7 @@ JSBool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisable((GLenum)arg0 ); @@ -640,7 +639,7 @@ JSBool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDisableVertexAttribArray((GLuint)arg0 ); @@ -656,9 +655,9 @@ JSBool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glDrawArrays((GLenum)arg0 , (GLint)arg1 , (GLsizei)arg2 ); @@ -674,9 +673,9 @@ JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; void* arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg3); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -694,7 +693,7 @@ JSBool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnable((GLenum)arg0 ); @@ -710,7 +709,7 @@ JSBool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glEnableVertexAttribArray((GLuint)arg0 ); @@ -746,10 +745,10 @@ JSBool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferRenderbuffer((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 ); @@ -765,11 +764,11 @@ JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFramebufferTexture2D((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 , (GLint)arg4 ); @@ -785,7 +784,7 @@ JSBool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glFrontFace((GLenum)arg0 ); @@ -801,7 +800,7 @@ JSBool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glGenerateMipmap((GLenum)arg0 ); @@ -817,7 +816,7 @@ JSBool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); int ret_val; @@ -846,7 +845,7 @@ JSBool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; const char* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); printf("%s ", arg1); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -865,8 +864,8 @@ JSBool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glHint((GLenum)arg0 , (GLenum)arg1 ); @@ -882,7 +881,7 @@ JSBool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -899,7 +898,7 @@ JSBool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -916,7 +915,7 @@ JSBool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -933,7 +932,7 @@ JSBool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -950,7 +949,7 @@ JSBool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -967,7 +966,7 @@ JSBool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -984,7 +983,7 @@ JSBool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); GLboolean ret_val; @@ -1001,7 +1000,7 @@ JSBool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLineWidth((GLfloat)arg0 ); @@ -1017,7 +1016,7 @@ JSBool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glLinkProgram((GLuint)arg0 ); @@ -1033,8 +1032,8 @@ JSBool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPixelStorei((GLenum)arg0 , (GLint)arg1 ); @@ -1050,8 +1049,8 @@ JSBool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glPolygonOffset((GLfloat)arg0 , (GLfloat)arg1 ); @@ -1067,12 +1066,12 @@ JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; uint32_t arg4; uint32_t arg5; void* arg6; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg5 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg5 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg6); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1100,10 +1099,10 @@ JSBool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glRenderbufferStorage((GLenum)arg0 , (GLenum)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1119,8 +1118,8 @@ JSBool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glSampleCoverage((GLclampf)arg0 , (GLboolean)arg1 ); @@ -1136,10 +1135,10 @@ JSBool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glScissor((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); @@ -1155,9 +1154,9 @@ JSBool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFunc((GLenum)arg0 , (GLint)arg1 , (GLuint)arg2 ); @@ -1173,10 +1172,10 @@ JSBool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 , (GLuint)arg3 ); @@ -1192,7 +1191,7 @@ JSBool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMask((GLuint)arg0 ); @@ -1208,8 +1207,8 @@ JSBool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilMaskSeparate((GLenum)arg0 , (GLuint)arg1 ); @@ -1225,9 +1224,9 @@ JSBool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOp((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 ); @@ -1243,10 +1242,10 @@ JSBool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glStencilOpSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); @@ -1262,14 +1261,14 @@ JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1287,9 +1286,9 @@ JSBool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameterf((GLenum)arg0 , (GLenum)arg1 , (GLfloat)arg2 ); @@ -1305,9 +1304,9 @@ JSBool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; uint32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glTexParameteri((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 ); @@ -1323,14 +1322,14 @@ JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg6 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg7 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg6 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1348,8 +1347,8 @@ JSBool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1f((GLint)arg0 , (GLfloat)arg1 ); @@ -1365,8 +1364,8 @@ JSBool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1384,8 +1383,8 @@ JSBool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform1i((GLint)arg0 , (GLint)arg1 ); @@ -1401,8 +1400,8 @@ JSBool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1420,9 +1419,9 @@ JSBool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1438,8 +1437,8 @@ JSBool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1457,9 +1456,9 @@ JSBool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform2i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 ); @@ -1475,8 +1474,8 @@ JSBool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1494,10 +1493,10 @@ JSBool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1513,8 +1512,8 @@ JSBool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1532,10 +1531,10 @@ JSBool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform3i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 ); @@ -1551,8 +1550,8 @@ JSBool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1570,11 +1569,11 @@ JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1590,8 +1589,8 @@ JSBool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1609,11 +1608,11 @@ JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUniform4i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 ); @@ -1629,8 +1628,8 @@ JSBool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1648,8 +1647,8 @@ JSBool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1667,8 +1666,8 @@ JSBool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1686,8 +1685,8 @@ JSBool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; uint16_t arg1; void* arg2; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1705,7 +1704,7 @@ JSBool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glUseProgram((GLuint)arg0 ); @@ -1721,7 +1720,7 @@ JSBool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glValidateProgram((GLuint)arg0 ); @@ -1737,8 +1736,8 @@ JSBool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib1f((GLuint)arg0 , (GLfloat)arg1 ); @@ -1754,7 +1753,7 @@ JSBool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1772,9 +1771,9 @@ JSBool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib2f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); @@ -1790,7 +1789,7 @@ JSBool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1808,10 +1807,10 @@ JSBool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib3f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); @@ -1827,7 +1826,7 @@ JSBool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1845,11 +1844,11 @@ JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttrib4f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); @@ -1865,7 +1864,7 @@ JSBool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; void* arg1; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); @@ -1883,12 +1882,12 @@ JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; uint32_t arg0; int32_t arg1; uint32_t arg2; uint16_t arg3; int32_t arg4; int32_t arg5; - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_uint32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_uint16( cx, *argvp++, &arg3 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg4 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg5 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); + ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg4 ); + ok &= jsval_to_int32( cx, *argvp++, &arg5 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glVertexAttribPointer((GLuint)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLboolean)arg3 , (GLsizei)arg4 , (GLvoid*)arg5 ); @@ -1904,10 +1903,10 @@ JSBool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp) { JSBool ok = JS_TRUE; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg0 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg1 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg2 ); - ok &= JSB_jsval_to_int32( cx, *argvp++, &arg3 ); + ok &= jsval_to_int32( cx, *argvp++, &arg0 ); + ok &= jsval_to_int32( cx, *argvp++, &arg1 ); + ok &= jsval_to_int32( cx, *argvp++, &arg2 ); + ok &= jsval_to_int32( cx, *argvp++, &arg3 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); glViewport((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp index 38a168b935..fa4e2d31c8 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp @@ -31,7 +31,6 @@ #include "jsb_opengl_manual.h" #include "js_manual_conversions.h" -#include "cocosjs_manual_conversions.h" #include "js_bindings_core.h" #include "jsb_opengl_functions.h" diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj index 11085f336c..a4cbbd4d50 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj @@ -13,7 +13,6 @@ - @@ -25,7 +24,6 @@ - diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters index 1d1e1d400a..85bb2eccd3 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj.filters @@ -17,9 +17,6 @@ manual - - manual - manual @@ -49,9 +46,6 @@ manual - - manual - manual From 49289d7576501e9c943cc14d49ea518f736061c7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:46:00 +0800 Subject: [PATCH 536/557] Adding cc.TextureCache.getInstance() to jsb_deprecated.js. --- cocos/scripting/javascript/script/jsb_deprecated.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos/scripting/javascript/script/jsb_deprecated.js b/cocos/scripting/javascript/script/jsb_deprecated.js index 2c7a7b1ed1..cf2065152f 100644 --- a/cocos/scripting/javascript/script/jsb_deprecated.js +++ b/cocos/scripting/javascript/script/jsb_deprecated.js @@ -14,6 +14,10 @@ var cc = cc || {}; cc.AnimationCache.destroyInstance(); }; + cc.TextureCache.getInstance = function() { + return cc.Director.getInstance().getTextureCache(); + }; + // Deprecated member functions cc.Action.prototype.copy = function() { logW("cc.Action.copy", "cc.Action.clone"); From 22584ca9c2eafd27f344684ecfee68f870924c38 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 15:47:43 +0800 Subject: [PATCH 537/557] Updating submodule of bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index a943736554..9797d44032 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit a94373655409f756b33d8a58cc798dcb00be257c +Subproject commit 9797d4403207848f431d5b6456632cc966d84b0d From 394f4e703b068ebb83e17fe23cd3b939238e499d Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 17:06:32 +0800 Subject: [PATCH 538/557] Reverting AssetsManager::update. --- extensions/assets-manager/AssetsManager.cpp | 2 +- extensions/assets-manager/AssetsManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 06e5bd11c6..4913e5efd0 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -214,7 +214,7 @@ void AssetsManager::downloadAndUncompress() _isDownloading = false; } -void AssetsManager::update(float delta) +void AssetsManager::update() { if (_isDownloading) return; diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 5608084c76..f3e413f4bd 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -98,7 +98,7 @@ public: /* @brief Download new package if there is a new version, and uncompress downloaded zip file. * Ofcourse it will set search path that stores downloaded files. */ - virtual void update(float delta) override; + virtual void update(); /* @brief Gets url of package. */ From 1e15071dc7465020facc3756a97694875d7a75a7 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 17:29:48 +0800 Subject: [PATCH 539/557] remove makefiles --- build/Makefile | 91 ----- build/make-all-linux-project.sh | 24 -- cocos/2d/Makefile | 204 ----------- cocos/audio/CMakeLists.txt | 11 + cocos/audio/proj.linux/.cproject | 378 ------------------- cocos/audio/proj.linux/.project | 100 ----- cocos/audio/proj.linux/CocosDenshion.prf | 20 - cocos/audio/proj.linux/Makefile | 49 --- cocos/editor-support/cocosbuilder/Makefile | 44 --- cocos/editor-support/cocostudio/Makefile | 69 ---- cocos/editor-support/spine/Makefile | 42 --- cocos/gui/Makefile | 43 --- cocos/network/Makefile | 22 -- cocos/scripting/lua/bindings/Makefile | 94 ----- extensions/proj.linux/.cproject | 404 --------------------- extensions/proj.linux/.project | 90 ----- extensions/proj.linux/Makefile | 49 --- external/Box2D/proj.linux/.cproject | 267 -------------- external/Box2D/proj.linux/.project | 110 ------ external/Box2D/proj.linux/Makefile | 72 ---- external/Box2D/proj.linux/box2d.prf | 19 - external/chipmunk/proj.linux/.cproject | 236 ------------ external/chipmunk/proj.linux/.project | 95 ----- external/chipmunk/proj.linux/Makefile | 47 --- external/chipmunk/proj.linux/chipmunk.prf | 19 - 25 files changed, 11 insertions(+), 2588 deletions(-) delete mode 100644 build/Makefile delete mode 100755 build/make-all-linux-project.sh delete mode 100644 cocos/2d/Makefile delete mode 100644 cocos/audio/proj.linux/.cproject delete mode 100644 cocos/audio/proj.linux/.project delete mode 100644 cocos/audio/proj.linux/CocosDenshion.prf delete mode 100644 cocos/audio/proj.linux/Makefile delete mode 100644 cocos/editor-support/cocosbuilder/Makefile delete mode 100644 cocos/editor-support/cocostudio/Makefile delete mode 100644 cocos/editor-support/spine/Makefile delete mode 100644 cocos/gui/Makefile delete mode 100644 cocos/network/Makefile delete mode 100644 cocos/scripting/lua/bindings/Makefile delete mode 100644 extensions/proj.linux/.cproject delete mode 100644 extensions/proj.linux/.project delete mode 100644 extensions/proj.linux/Makefile delete mode 100644 external/Box2D/proj.linux/.cproject delete mode 100644 external/Box2D/proj.linux/.project delete mode 100644 external/Box2D/proj.linux/Makefile delete mode 100644 external/Box2D/proj.linux/box2d.prf delete mode 100644 external/chipmunk/proj.linux/.cproject delete mode 100644 external/chipmunk/proj.linux/.project delete mode 100644 external/chipmunk/proj.linux/Makefile delete mode 100644 external/chipmunk/proj.linux/chipmunk.prf diff --git a/build/Makefile b/build/Makefile deleted file mode 100644 index 761855d264..0000000000 --- a/build/Makefile +++ /dev/null @@ -1,91 +0,0 @@ -PLATFORM ?= linux - -all: - -chipmunk: - $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) -chipmunk-clean: - $(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) clean - -box2d: - $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) -box2d-clean: - $(MAKE) -C ../external/Box2D/proj.$(PLATFORM) clean - -cocos2dx: chipmunk - $(MAKE) -C ../cocos/2d -cocos2dx-clean: - $(MAKE) -C ../cocos/2d clean - -audio: cocos2dx - $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) -audio-clean: - $(MAKE) -C ../cocos/audio/proj.$(PLATFORM) clean - -gui: - $(MAKE) -C ../cocos/gui -gui-clean: - $(MAKE) -C ../cocos/gui clean - -network: cocos2dx - $(MAKE) -C ../cocos/network -network-clean: - $(MAKE) -C ../cocos/network clean - -cocosbuilder: - $(MAKE) -C ../cocos/editor-support/cocosbuilder -cocosbuilder-clean: - $(MAKE) -C ../cocos/editor-support/cocosbuilder clean - -spine: - $(MAKE) -C ../cocos/editor-support/spine -spine-clean: - $(MAKE) -C ../cocos/editor-support/spine clean - -cocostudio: - $(MAKE) -C ../cocos/editor-support/cocostudio -cocostudio-clean: - $(MAKE) -C ../cocos/editor-support/cocostudio clean - -extensions: chipmunk audio box2d - $(MAKE) -C ../extensions/proj.$(PLATFORM) -extensions-clean: - $(MAKE) -C ../extensions/proj.$(PLATFORM) clean - -lua: extensions cocosbuilder cocostudio - $(MAKE) -C ../cocos/scripting/lua/bindings -lua-clean: - $(MAKE) -C ../cocos/scripting/lua/bindings clean - -hellocpp: cocos2dx - $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) -hellocpp-clean: - $(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) clean - -testcpp: cocos2dx audio extensions cocostudio gui cocosbuilder spine network - $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) -testcpp-clean: - $(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) clean - -simplegame: cocos2dx audio - $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) -simplegame-clean: - $(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) clean - -all: chipmunk audio extensions cocos2dx lua hellocpp testcpp simplegame -clean: cocos2dx-clean box2d-clean chipmunk-clean audio-clean extensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean - -hellolua: cocos2dx lua - $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) -hellolua-clean: - $(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) clean - -testlua: cocos2dx lua - $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) -testlua-clean: - $(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) clean - -all: hellolua testlua -clean: hellolua-clean testlua-clean - -.PHONY: all clean diff --git a/build/make-all-linux-project.sh b/build/make-all-linux-project.sh deleted file mode 100755 index 98eaeef714..0000000000 --- a/build/make-all-linux-project.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -# This script will perform a clean linux build of all targets in both -# debug and release configurations. It will also ensure that all the required -# packages are installed. For day-to-day work on the linux port it is -# faster/better to simply use 'make' either at the top level or in the subpject -# you are working on. - -# Exit of first error. -set -e - -# Change directory to the location of this script -cd $(dirname ${BASH_SOURCE[0]}) - -[ -z "$COCOS2DX_USEAPT" ] && COCOS2DX_USEAPT=true - -if $COCOS2DX_USEAPT; then - ./install-deps-linux.sh -fi - -mkdir -p linux-build -cd linux-build -cmake ../.. -make -j10 - diff --git a/cocos/2d/Makefile b/cocos/2d/Makefile deleted file mode 100644 index 3e711d5d20..0000000000 --- a/cocos/2d/Makefile +++ /dev/null @@ -1,204 +0,0 @@ -TARGET = libcocos2d.so - -INCLUDES = - -SOURCES = \ -CCAction.cpp \ -CCActionCamera.cpp \ -CCActionEase.cpp \ -CCActionGrid.cpp \ -CCActionGrid3D.cpp \ -CCActionInstant.cpp \ -CCActionInterval.cpp \ -CCActionManager.cpp \ -CCActionPageTurn3D.cpp \ -CCActionProgressTimer.cpp \ -CCActionTiledGrid.cpp \ -CCActionCatmullRom.cpp \ -CCActionTween.cpp \ -CCAtlasNode.cpp \ -CCNode.cpp \ -../base/CCAffineTransform.cpp \ -../base/CCAutoreleasePool.cpp \ -../base/CCGeometry.cpp \ -../base/CCNS.cpp \ -../base/CCObject.cpp \ -../base/CCSet.cpp \ -../base/CCArray.cpp \ -../base/CCDictionary.cpp \ -../base/CCString.cpp \ -../base/CCDataVisitor.cpp \ -../base/CCData.cpp \ -CCEventAcceleration.cpp \ -CCEventListenerAcceleration.cpp \ -CCEvent.cpp \ -CCEventDispatcher.cpp \ -CCEventListener.cpp \ -CCEventKeyboard.cpp \ -CCEventListenerKeyboard.cpp \ -CCEventMouse.cpp \ -CCEventListenerMouse.cpp \ -CCTouch.cpp \ -CCEventTouch.cpp \ -CCEventListenerTouch.cpp \ -CCEventCustom.cpp \ -CCEventListenerCustom.cpp \ -CCDrawingPrimitives.cpp \ -CCDrawNode.cpp \ -CCGrabber.cpp \ -CCGrid.cpp \ -CCFont.cpp \ -CCFontAtlas.cpp \ -CCFontAtlasCache.cpp \ -CCFontAtlasFactory.cpp \ -CCFontDefinition.cpp \ -CCFontFNT.cpp \ -CCFontFreeType.cpp \ -CCLabel.cpp \ -CCLabelAtlas.cpp \ -CCLabelBMFont.cpp \ -CCLabelTTF.cpp \ -CCLabelTextFormatter.cpp \ -CCTextImage.cpp \ -CCLayer.cpp \ -CCScene.cpp \ -CCTransition.cpp \ -CCTransitionPageTurn.cpp \ -CCTransitionProgress.cpp \ -CCMenu.cpp \ -CCMenuItem.cpp \ -CCMotionStreak.cpp \ -CCProgressTimer.cpp \ -CCClippingNode.cpp \ -CCRenderTexture.cpp \ -CCParticleExamples.cpp \ -CCParticleSystem.cpp \ -CCParticleSystemQuad.cpp \ -CCParticleBatchNode.cpp \ -../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ -../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ -../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ -../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ -../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ -../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ -../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ -../physics/CCPhysicsBody.cpp \ -../physics/CCPhysicsContact.cpp \ -../physics/CCPhysicsShape.cpp \ -../physics/CCPhysicsJoint.cpp \ -../physics/CCPhysicsWorld.cpp \ -../platform/CCSAXParser.cpp \ -../platform/CCThread.cpp \ -../platform/CCEGLViewProtocol.cpp \ -../platform/CCFileUtils.cpp \ -../platform/linux/CCStdC.cpp \ -../platform/linux/CCFileUtilsLinux.cpp \ -../platform/linux/CCCommon.cpp \ -../platform/linux/CCApplication.cpp \ -../platform/linux/CCEGLView.cpp \ -../platform/linux/CCImage.cpp \ -../platform/linux/CCDevice.cpp \ -../base/etc1.cpp \ -../base/s3tc.cpp \ -../base/atitc.cpp \ -CCScriptSupport.cpp \ -CCAnimation.cpp \ -CCAnimationCache.cpp \ -CCSprite.cpp \ -CCSpriteBatchNode.cpp \ -CCSpriteFrame.cpp \ -CCSpriteFrameCache.cpp \ -ccUTF8.cpp \ -CCProfiling.cpp \ -CCUserDefault.cpp \ -TransformUtils.cpp \ -base64.cpp \ -ccUtils.cpp \ -CCVertex.cpp \ -CCNotificationCenter.cpp \ -TGAlib.cpp \ -../../external/tinyxml2/tinyxml2.cpp \ -ZipUtils.cpp \ -../../external/unzip/ioapi.cpp \ -../../external/unzip/unzip.cpp \ -ccCArray.cpp \ -CCComponent.cpp \ -CCComponentContainer.cpp \ -CCIMEDispatcher.cpp \ -CCTextFieldTTF.cpp \ -CCTexture2D.cpp \ -CCTextureAtlas.cpp \ -CCTextureCache.cpp \ -CCParallaxNode.cpp \ -CCTMXLayer.cpp \ -CCTMXObjectGroup.cpp \ -CCTMXTiledMap.cpp \ -CCTMXXMLParser.cpp \ -CCTileMapAtlas.cpp \ -CCGLProgram.cpp \ -ccGLStateCache.cpp \ -CCShaderCache.cpp \ -ccShaders.cpp \ -../math/kazmath/src/aabb.c \ -../math/kazmath/src/plane.c \ -../math/kazmath/src/vec2.c \ -../math/kazmath/src/mat3.c \ -../math/kazmath/src/quaternion.c \ -../math/kazmath/src/vec3.c \ -../math/kazmath/src/mat4.c \ -../math/kazmath/src/ray2.c \ -../math/kazmath/src/vec4.c \ -../math/kazmath/src/neon_matrix_impl.c \ -../math/kazmath/src/utility.c \ -../math/kazmath/src/GL/mat4stack.c \ -../math/kazmath/src/GL/matrix.c \ -CCCamera.cpp \ -CCConfiguration.cpp \ -CCDirector.cpp \ -CCScheduler.cpp \ -ccFPSImages.c \ -ccTypes.cpp \ -cocos2d.cpp \ -CCDeprecated.cpp - -COCOS_ROOT = ../.. - -include cocos2dx.mk - -CXXFLAGS += -Wno-sequence-point -CCFLAGS += -Wno-sequence-point - -STATICLIBS += $(LIB_DIR)/libchipmunk.a - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - - diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 12fde54f25..2f1d642cb2 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -3,6 +3,17 @@ set(AUDIO_SRC linux/FmodAudioPlayer.cpp ) +# architecture +if ( CMAKE_SIZEOF_VOID_P EQUAL 8 ) +set(ARCH_DIR "64-bit") +else() +set(ARCH_DIR "32-bit") +endif() + +include_directories( + ../../external/linux-specific/fmod/include/${ARCH_DIR} +) + add_library(audio STATIC ${AUDIO_SRC} ) diff --git a/cocos/audio/proj.linux/.cproject b/cocos/audio/proj.linux/.cproject deleted file mode 100644 index fc010e1ed7..0000000000 --- a/cocos/audio/proj.linux/.cproject +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cocos/audio/proj.linux/.project b/cocos/audio/proj.linux/.project deleted file mode 100644 index 2860d8d849..0000000000 --- a/cocos/audio/proj.linux/.project +++ /dev/null @@ -1,100 +0,0 @@ - - - libCocosDenshion - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/CocosDenshion/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - linux - 2 - PARENT-1-PROJECT_LOC/linux - - - third_party - 2 - PARENT-1-PROJECT_LOC/third_party - - - diff --git a/cocos/audio/proj.linux/CocosDenshion.prf b/cocos/audio/proj.linux/CocosDenshion.prf deleted file mode 100644 index 4c7ec10f0c..0000000000 --- a/cocos/audio/proj.linux/CocosDenshion.prf +++ /dev/null @@ -1,20 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile extensions on demand using Makefile. - build_CocosDension.name = Build extension static library - build_CocosDension.input = $$PWD/Makefile - build_CocosDension.output = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.target = $$CC_LIBRARY_DIR/libcocosdenshion.so - build_CocosDension.CONFIG = no_link target_predeps - build_CocosDension.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_CocosDension - QMAKE_EXTRA_TARGETS += build_CocosDension - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libcocosdenshion.so - LIBS += -lcocosdenshion -} - diff --git a/cocos/audio/proj.linux/Makefile b/cocos/audio/proj.linux/Makefile deleted file mode 100644 index e8b18e3972..0000000000 --- a/cocos/audio/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libcocosdenshion.so - -INCLUDES = -I.. -I../include - -##Using OpenAL -ifeq ($(OPENAL),1) -SOURCES = ../openal/OpenALDecoder.cpp \ - ../openal/SimpleAudioEngineOpenAL.cpp -SHAREDLIBS += -lopenal -lalut - -ifeq ($(OPENAL_MP3),1) -DEFINES += -DENABLE_MPG123 -SHAREDLIBS += -lmpg123 -endif - -ifneq ($(NOVORBIS),1) -SHAREDLIBS += -logg -lvorbis -lvorbisfile -else -DEFINES += -DDISABLE_VORBIS -endif - -##Using FMOD -else -SOURCES = \ - ../linux/SimpleAudioEngineFMOD.cpp \ - ../linux/FmodAudioPlayer.cpp - -ifeq ($(LBITS),64) -INCLUDES += -I../third-party/fmod/lib64/api/inc -else -INCLUDES += -I../third-party/fmod/api/inc -endif - -endif - -COCOS_ROOT = ../../.. -include $(COCOS_ROOT)/cocos/2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $(TARGET) $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) $(VISIBILITY) -c $< -o $@ diff --git a/cocos/editor-support/cocosbuilder/Makefile b/cocos/editor-support/cocosbuilder/Makefile deleted file mode 100644 index 688c5d49d5..0000000000 --- a/cocos/editor-support/cocosbuilder/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -TARGET = libcocosbuilder.a - -INCLUDES = - -SOURCES = CCBFileLoader.cpp \ -CCMenuItemImageLoader.cpp \ -CCBReader.cpp \ -CCMenuItemLoader.cpp \ -CCControlButtonLoader.cpp \ -CCNodeLoader.cpp \ -CCControlLoader.cpp \ -CCNodeLoaderLibrary.cpp \ -CCLabelBMFontLoader.cpp \ -CCParticleSystemQuadLoader.cpp \ -CCLabelTTFLoader.cpp \ -CCScale9SpriteLoader.cpp \ -CCLayerColorLoader.cpp \ -CCScrollViewLoader.cpp \ -CCLayerGradientLoader.cpp \ -CCSpriteLoader.cpp \ -CCLayerLoader.cpp \ -CCBAnimationManager.cpp \ -CCBKeyframe.cpp \ -CCBSequence.cpp \ -CCBSequenceProperty.cpp \ -CCBValue.cpp \ -CCNode+CCBRelativePositioning.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/editor-support/cocostudio/Makefile b/cocos/editor-support/cocostudio/Makefile deleted file mode 100644 index 810c28372e..0000000000 --- a/cocos/editor-support/cocostudio/Makefile +++ /dev/null @@ -1,69 +0,0 @@ -TARGET = libcocostudio.a - -COCOS_ROOT=../../.. - -INCLUDES = -I../../2d \ --I../../../external \ --I.. \ --I../.. \ - -SOURCES = CCActionFrame.cpp \ -CCActionFrameEasing.cpp \ -CCActionManagerEx.cpp \ -CCActionNode.cpp \ -CCActionObject.cpp \ -CCArmature.cpp \ -CCBone.cpp \ -CCArmatureAnimation.cpp \ -CCProcessBase.cpp \ -CCTween.cpp \ -CCDatas.cpp \ -CCBatchNode.cpp \ -CCDecorativeDisplay.cpp \ -CCDisplayFactory.cpp \ -CCDisplayManager.cpp \ -CCSkin.cpp \ -CCColliderDetector.cpp \ -CCArmatureDataManager.cpp \ -CCArmatureDefine.cpp \ -CCDataReaderHelper.cpp \ -CCSpriteFrameCacheHelper.cpp \ -CCTransformHelp.cpp \ -CCTweenFunction.cpp \ -CCUtilMath.cpp \ -CCComAttribute.cpp \ -CCComAudio.cpp \ -CCComController.cpp \ -CCComRender.cpp \ -CCInputDelegate.cpp \ -CSContentJsonDictionary.cpp \ -DictionaryHelper.cpp \ -CCSGUIReader.cpp \ -CCSSceneReader.cpp \ -../../../external/json/json_reader.cpp \ -../../../external/json/json_value.cpp \ -../../../external/json/json_writer.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/editor-support/spine/Makefile b/cocos/editor-support/spine/Makefile deleted file mode 100644 index 88514a824e..0000000000 --- a/cocos/editor-support/spine/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -TARGET = libspine.a - -INCLUDES = -I.. - -SOURCES = Animation.cpp \ -AnimationState.cpp \ -AnimationStateData.cpp \ -Atlas.cpp \ -AtlasAttachmentLoader.cpp \ -Attachment.cpp \ -AttachmentLoader.cpp \ -Bone.cpp \ -BoneData.cpp \ -Json.cpp \ -RegionAttachment.cpp \ -Skeleton.cpp \ -SkeletonData.cpp \ -SkeletonJson.cpp \ -Skin.cpp \ -Slot.cpp \ -SlotData.cpp \ -extension.cpp \ -spine-cocos2dx.cpp \ -CCSkeleton.cpp \ -CCSkeletonAnimation.cpp - -include ../../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - diff --git a/cocos/gui/Makefile b/cocos/gui/Makefile deleted file mode 100644 index 8dcb0cb404..0000000000 --- a/cocos/gui/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -TARGET = libgui.a - -INCLUDES = -I../ \ --I../editor-support \ --I../../external - -SOURCES = UIRootWidget.cpp \ -UIWidget.cpp \ -UILayout.cpp \ -UILayoutParameter.cpp \ -UILayoutDefine.cpp \ -CocosGUI.cpp \ -UIHelper.cpp \ -UIInputManager.cpp \ -UILayer.cpp \ -UIListView.cpp \ -UIPageView.cpp \ -UIScrollView.cpp \ -UIButton.cpp \ -UICheckBox.cpp \ -UIImageView.cpp \ -UILabel.cpp \ -UILabelAtlas.cpp \ -UILabelBMFont.cpp \ -UILoadingBar.cpp \ -UISlider.cpp \ -UITextField.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/network/Makefile b/cocos/network/Makefile deleted file mode 100644 index 029078722d..0000000000 --- a/cocos/network/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -TARGET = libnetwork.a - -INCLUDES = -I.. - -SOURCES = HttpClient.cpp \ -SocketIO.cpp - -include ../2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/cocos/scripting/lua/bindings/Makefile b/cocos/scripting/lua/bindings/Makefile deleted file mode 100644 index 546ad977b4..0000000000 --- a/cocos/scripting/lua/bindings/Makefile +++ /dev/null @@ -1,94 +0,0 @@ -TARGET = liblua.so - -INCLUDES += -I../../../../external/lua/tolua \ --I../../../../external/lua/lua \ --I../../auto-generated/lua-bindings \ --I../../../../extensions \ --I../../../editor-support \ --I. \ --I../../../editor-support/cocosbuilder \ --I../../../editor-support/cocostudio \ --I../../../../external \ --I../../../ - -SOURCES = ../../../../external/lua/lua/lapi.c \ - ../../../../external/lua/lua/lauxlib.c \ - ../../../../external/lua/lua/lbaselib.c \ - ../../../../external/lua/lua/lcode.c \ - ../../../../external/lua/lua/ldblib.c \ - ../../../../external/lua/lua/ldebug.c \ - ../../../../external/lua/lua/ldo.c \ - ../../../../external/lua/lua/ldump.c \ - ../../../../external/lua/lua/lfunc.c \ - ../../../../external/lua/lua/lgc.c \ - ../../../../external/lua/lua/linit.c \ - ../../../../external/lua/lua/liolib.c \ - ../../../../external/lua/lua/llex.c \ - ../../../../external/lua/lua/lmathlib.c \ - ../../../../external/lua/lua/lmem.c \ - ../../../../external/lua/lua/loadlib.c \ - ../../../../external/lua/lua/lobject.c \ - ../../../../external/lua/lua/lopcodes.c \ - ../../../../external/lua/lua/loslib.c \ - ../../../../external/lua/lua/lparser.c \ - ../../../../external/lua/lua/lstate.c \ - ../../../../external/lua/lua/lstring.c \ - ../../../../external/lua/lua/lstrlib.c \ - ../../../../external/lua/lua/ltable.c \ - ../../../../external/lua/lua/ltablib.c \ - ../../../../external/lua/lua/ltm.c \ - ../../../../external/lua/lua/lundump.c \ - ../../../../external/lua/lua/lvm.c \ - ../../../../external/lua/lua/lzio.c \ - ../../../../external/lua/lua/print.c \ - ../../../../external/lua/tolua/tolua_event.c \ - ../../../../external/lua/tolua/tolua_is.c \ - ../../../../external/lua/tolua/tolua_map.c \ - ../../../../external/lua/tolua/tolua_push.c \ - ../../../../external/lua/tolua/tolua_to.c \ - tolua_fix.c \ - ../../auto-generated/lua-bindings/lua_cocos2dx_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_extension_auto.cpp \ - ../../auto-generated/lua-bindings/lua_cocos2dx_studio_auto.cpp \ - CCLuaBridge.cpp \ - CCLuaEngine.cpp \ - CCLuaStack.cpp \ - CCLuaValue.cpp \ - Cocos2dxLuaLoader.cpp \ - CCBProxy.cpp \ - LuaOpengl.cpp \ - LuaScriptHandlerMgr.cpp \ - LuaBasicConversions.cpp \ - lua_cocos2dx_manual.cpp \ - lua_cocos2dx_extension_manual.cpp \ - lua_cocos2dx_deprecated.cpp \ - lua_xml_http_request.cpp - - -include ../../../2d/cocos2dx.mk - -TARGET := $(LIB_DIR)/$(TARGET) -SHAREDLIBS += -lextension -lcocostudio -lcocosbuilder -STATICLIBS += $(LIB_DIR)/libbox2d.a - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) - -$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../../../../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/extensions/proj.linux/.cproject b/extensions/proj.linux/.cproject deleted file mode 100644 index 696f0898ce..0000000000 --- a/extensions/proj.linux/.cproject +++ /dev/null @@ -1,404 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/extensions/proj.linux/.project b/extensions/proj.linux/.project deleted file mode 100644 index 37e93964dd..0000000000 --- a/extensions/proj.linux/.project +++ /dev/null @@ -1,90 +0,0 @@ - - - libextension - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - CCBReader - 2 - PARENT-1-PROJECT_LOC/CCBReader - - - CCArmature - 2 - PARENT-1-PROJECT_LOC/CCArmature - - - Components - 2 - PARENT-1-PROJECT_LOC/Components - - - spine - 2 - PARENT-1-PROJECT_LOC/spine - - - ExtensionMacros.h - 1 - PARENT-1-PROJECT_LOC/ExtensionMacros.h - - - GUI - 2 - PARENT-1-PROJECT_LOC/GUI - - - LocalStorage - 2 - PARENT-1-PROJECT_LOC/LocalStorage - - - cocos-ext.h - 1 - PARENT-1-PROJECT_LOC/cocos-ext.h - - - network - 2 - PARENT-1-PROJECT_LOC/network - - - physics_nodes - 2 - PARENT-1-PROJECT_LOC/physics_nodes - - - - - 1373359750543 - - 22 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-WebSocket.* - - - - diff --git a/extensions/proj.linux/Makefile b/extensions/proj.linux/Makefile deleted file mode 100644 index fe07e988e5..0000000000 --- a/extensions/proj.linux/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -TARGET = libextension.a - -INCLUDES = -I.. - -SOURCES = \ -assets-manager/AssetsManager.cpp \ -GUI/CCControlExtension/CCControl.cpp \ -GUI/CCControlExtension/CCControlButton.cpp \ -GUI/CCControlExtension/CCControlColourPicker.cpp \ -GUI/CCControlExtension/CCControlHuePicker.cpp \ -GUI/CCControlExtension/CCControlPotentiometer.cpp \ -GUI/CCControlExtension/CCControlSaturationBrightnessPicker.cpp \ -GUI/CCControlExtension/CCControlSlider.cpp \ -GUI/CCControlExtension/CCControlStepper.cpp \ -GUI/CCControlExtension/CCControlSwitch.cpp \ -GUI/CCControlExtension/CCControlUtils.cpp \ -GUI/CCControlExtension/CCInvocation.cpp \ -GUI/CCControlExtension/CCScale9Sprite.cpp \ -GUI/CCEditBox/CCEditBox.cpp \ -GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ -GUI/CCEditBox/CCEditBoxImplNone.cpp \ -GUI/CCEditBox/CCEditBoxImplTizen.cpp \ -GUI/CCEditBox/CCEditBoxImplWin.cpp \ -GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ -GUI/CCScrollView/CCTableView.cpp \ -GUI/CCScrollView/CCTableViewCell.cpp \ -physics-nodes/CCPhysicsDebugNode.cpp \ -physics-nodes/CCPhysicsSprite.cpp - -include ../../cocos/2d/cocos2dx.mk - -CXXFLAGS += -Wno-multichar -Wno-unused-result - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $@ $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ - -$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/.cproject b/external/Box2D/proj.linux/.cproject deleted file mode 100644 index 5aa092cac3..0000000000 --- a/external/Box2D/proj.linux/.cproject +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/Box2D/proj.linux/.project b/external/Box2D/proj.linux/.project deleted file mode 100644 index 164d50f52a..0000000000 --- a/external/Box2D/proj.linux/.project +++ /dev/null @@ -1,110 +0,0 @@ - - - libBox2D - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libBox2D/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Box2D.h - 1 - PARENT-1-PROJECT_LOC/Box2D.h - - - Collision - 2 - PARENT-1-PROJECT_LOC/Collision - - - Common - 2 - PARENT-1-PROJECT_LOC/Common - - - Dynamics - 2 - PARENT-1-PROJECT_LOC/Dynamics - - - Rope - 2 - PARENT-1-PROJECT_LOC/Rope - - - diff --git a/external/Box2D/proj.linux/Makefile b/external/Box2D/proj.linux/Makefile deleted file mode 100644 index b43814ccef..0000000000 --- a/external/Box2D/proj.linux/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -TARGET = libbox2d.a - -SOURCES = ../Collision/Shapes/b2ChainShape.cpp \ -../Collision/Shapes/b2CircleShape.cpp \ -../Collision/Shapes/b2EdgeShape.cpp \ -../Collision/Shapes/b2PolygonShape.cpp \ -../Collision/b2BroadPhase.cpp \ -../Collision/b2CollideCircle.cpp \ -../Collision/b2CollideEdge.cpp \ -../Collision/b2CollidePolygon.cpp \ -../Collision/b2Collision.cpp \ -../Collision/b2Distance.cpp \ -../Collision/b2DynamicTree.cpp \ -../Collision/b2TimeOfImpact.cpp \ -../Common/b2BlockAllocator.cpp \ -../Common/b2Draw.cpp \ -../Common/b2Math.cpp \ -../Common/b2Settings.cpp \ -../Common/b2StackAllocator.cpp \ -../Common/b2Timer.cpp \ -../Dynamics/Contacts/b2ChainAndCircleContact.cpp \ -../Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ -../Dynamics/Contacts/b2CircleContact.cpp \ -../Dynamics/Contacts/b2Contact.cpp \ -../Dynamics/Contacts/b2ContactSolver.cpp \ -../Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ -../Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ -../Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ -../Dynamics/Contacts/b2PolygonContact.cpp \ -../Dynamics/Joints/b2DistanceJoint.cpp \ -../Dynamics/Joints/b2FrictionJoint.cpp \ -../Dynamics/Joints/b2GearJoint.cpp \ -../Dynamics/Joints/b2Joint.cpp \ -../Dynamics/Joints/b2MouseJoint.cpp \ -../Dynamics/Joints/b2PrismaticJoint.cpp \ -../Dynamics/Joints/b2PulleyJoint.cpp \ -../Dynamics/Joints/b2RevoluteJoint.cpp \ -../Dynamics/Joints/b2RopeJoint.cpp \ -../Dynamics/Joints/b2WeldJoint.cpp \ -../Dynamics/Joints/b2WheelJoint.cpp \ -../Dynamics/b2Body.cpp \ -../Dynamics/b2ContactManager.cpp \ -../Dynamics/b2Fixture.cpp \ -../Dynamics/b2Island.cpp \ -../Dynamics/b2World.cpp \ -../Dynamics/b2WorldCallbacks.cpp \ -../Rope/b2Rope.cpp - -include ../../../cocos/2d/cocos2dx.mk - -INCLUDES = -I../.. - -# Cocos2d is not responsible for warnings in external projects -CXXFLAGS += -w - -ifeq ($(DEBUG), 1) -DEFINES = -D_DEBUG -else -DEFINES = -endif - -TARGET := $(LIB_DIR)/$(TARGET) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/Box2D/proj.linux/box2d.prf b/external/Box2D/proj.linux/box2d.prf deleted file mode 100644 index 434ad88406..0000000000 --- a/external/Box2D/proj.linux/box2d.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile box2d on demand using Makefile. - build_box2d.name = Build box2d static library - build_box2d.input = $$PWD/Makefile - build_box2d.output = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.target = $$CC_LIBRARY_DIR/libbox2d.a - build_box2d.CONFIG = no_link target_predeps - build_box2d.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_box2d - QMAKE_EXTRA_TARGETS += build_box2d - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libbox2d.a - LIBS += -Wl,-Bstatic -lbox2d -Wl,-Bdynamic -} diff --git a/external/chipmunk/proj.linux/.cproject b/external/chipmunk/proj.linux/.cproject deleted file mode 100644 index 18467c15ca..0000000000 --- a/external/chipmunk/proj.linux/.cproject +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/external/chipmunk/proj.linux/.project b/external/chipmunk/proj.linux/.project deleted file mode 100644 index 2f42dedf9b..0000000000 --- a/external/chipmunk/proj.linux/.project +++ /dev/null @@ -1,95 +0,0 @@ - - - libChipmunk - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - ?name? - - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/libChipmunk/Debug} - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - include - 2 - PARENT-1-PROJECT_LOC/include - - - src - 2 - PARENT-1-PROJECT_LOC/src - - - diff --git a/external/chipmunk/proj.linux/Makefile b/external/chipmunk/proj.linux/Makefile deleted file mode 100644 index a2cb985b7c..0000000000 --- a/external/chipmunk/proj.linux/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -SOURCES = ../src/chipmunk.c \ - ../src/cpBody.c \ - ../src/cpSpace.c \ - ../src/cpSpatialIndex.c \ - ../src/cpArbiter.c \ - ../src/cpCollision.c \ - ../src/cpSpaceComponent.c \ - ../src/cpSweep1D.c \ - ../src/cpArray.c \ - ../src/cpHashSet.c \ - ../src/cpSpaceHash.c \ - ../src/cpVect.c \ - ../src/cpBB.c \ - ../src/cpPolyShape.c \ - ../src/cpSpaceQuery.c \ - ../src/cpBBTree.c \ - ../src/cpShape.c \ - ../src/cpSpaceStep.c \ - ../src/constraints/cpConstraint.c \ - ../src/constraints/cpPivotJoint.c \ - ../src/constraints/cpDampedRotarySpring.c \ - ../src/constraints/cpRatchetJoint.c \ - ../src/constraints/cpDampedSpring.c \ - ../src/constraints/cpRotaryLimitJoint.c \ - ../src/constraints/cpGearJoint.c \ - ../src/constraints/cpSimpleMotor.c \ - ../src/constraints/cpGrooveJoint.c \ - ../src/constraints/cpSlideJoint.c \ - ../src/constraints/cpPinJoint.c \ - -include ../../../cocos/2d/cocos2dx.mk - -TARGET = $(LIB_DIR)/libchipmunk.a -INCLUDES = -I../include/chipmunk -DEFINES = -DLINUX -CCFLAGS += -std=gnu99 -OBJECTS := $(subst src/,,$(OBJECTS)) - -all: $(TARGET) - -$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_AR)$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS) - -$(OBJ_DIR)/%.o: ../src/%.c $(CORE_MAKEFILE_LIST) - @mkdir -p $(@D) - $(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@ diff --git a/external/chipmunk/proj.linux/chipmunk.prf b/external/chipmunk/proj.linux/chipmunk.prf deleted file mode 100644 index a807b0ab99..0000000000 --- a/external/chipmunk/proj.linux/chipmunk.prf +++ /dev/null @@ -1,19 +0,0 @@ -################################################################################ -# Do not include this file in your project: see cocos2dx.pri. -################################################################################ - -linux { - # We will compile chipmunk on demand using Makefile. - build_chipmunk.name = Build chipmunk static library - build_chipmunk.input = $$PWD/Makefile - build_chipmunk.output = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.target = $$CC_LIBRARY_DIR/libchipmunk.a - build_chipmunk.CONFIG = no_link target_predeps - build_chipmunk.commands = cd $$PWD && make $$CC_MAKE_FLAGS - - QMAKE_EXTRA_COMPILERS += build_chipmunk - QMAKE_EXTRA_TARGETS += build_chipmunk - - PRE_TARGETDEPS += $$CC_LIBRARY_DIR/libchipmunk.a - LIBS += -Wl,-Bstatic -lchipmunk -Wl,-Bdynamic -} From 528c257497d23a84f14858f24fde0a2bd0a4b5ca Mon Sep 17 00:00:00 2001 From: 2youyou2 <501251991@qq.com> Date: Mon, 11 Nov 2013 17:30:37 +0800 Subject: [PATCH 540/557] add setUserObject method to CCArmatureAnimation --- .../cocostudio/CCArmatureAnimation.cpp | 10 ++++++ .../cocostudio/CCArmatureAnimation.h | 31 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp index f3e5199d6c..274a68342f 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.cpp @@ -56,6 +56,7 @@ ArmatureAnimation::ArmatureAnimation() , _toIndex(0) , _tweenList(nullptr) , _ignoreFrameEvent(false) + , _userObject(nullptr) , _movementEventCallFunc(nullptr) , _frameEventCallFunc(nullptr) @@ -69,6 +70,8 @@ ArmatureAnimation::~ArmatureAnimation(void) { CC_SAFE_RELEASE_NULL(_tweenList); CC_SAFE_RELEASE_NULL(_animationData); + + CC_SAFE_RELEASE_NULL(_userObject); } bool ArmatureAnimation::init(Armature *armature) @@ -430,6 +433,13 @@ void ArmatureAnimation::setFrameEventCallFunc(Object *target, SEL_FrameEventCall _frameEventCallFunc = callFunc; } +void ArmatureAnimation::setUserObject(Object *pUserObject) +{ + CC_SAFE_RETAIN(pUserObject); + CC_SAFE_RELEASE(_userObject); + _userObject = pUserObject; +} + void ArmatureAnimation::frameEvent(Bone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) { if (_frameEventTarget && _frameEventCallFunc) diff --git a/cocos/editor-support/cocostudio/CCArmatureAnimation.h b/cocos/editor-support/cocostudio/CCArmatureAnimation.h index 8d306398e9..7b9e9821ab 100644 --- a/cocos/editor-support/cocostudio/CCArmatureAnimation.h +++ b/cocos/editor-support/cocostudio/CCArmatureAnimation.h @@ -202,6 +202,35 @@ public: } } virtual AnimationData *getAnimationData() const { return _animationData; } + + + /** + * Returns a user assigned Object + * + * Similar to userData, but instead of holding a void* it holds an object + * + * @return A user assigned Object + * @js NA + * @lua NA + */ + virtual Object* getUserObject() { return _userObject; } + /** + * @js NA + * @lua NA + */ + virtual const Object* getUserObject() const { return _userObject; } + + /** + * Returns a user assigned Object + * + * Similar to UserData, but instead of holding a void* it holds an object. + * The UserObject will be retained once in this method, + * and the previous UserObject (if existed) will be relese. + * The UserObject will be released in Node's destructure. + * + * @param userObject A user assigned Object + */ + virtual void setUserObject(Object *userObject); protected: /** @@ -242,6 +271,8 @@ protected: bool _ignoreFrameEvent; std::queue _frameEventQueue; + + cocos2d::Object *_userObject; protected: /** * MovementEvent CallFunc. From d1a414194ef5f6f91de2ea31849df9a567a39044 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 11 Nov 2013 17:36:23 +0800 Subject: [PATCH 541/557] [ci skip]update linux build commands --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2b1a5fa297..938f0c39fb 100644 --- a/README.md +++ b/README.md @@ -98,10 +98,13 @@ $ open samples.xcodeproj ``` $ cd cocos2d-x/build -$ ./make-all-linux-project.sh +$ ./install-deps-linux.sh +$ cmake .. +$ make ``` -You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. + `install-deps-linux.sh` only has to be run onece. * For Windows From 4f76141c415cf550f51cece19de1d9fee1af1600 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 11 Nov 2013 18:22:14 +0800 Subject: [PATCH 542/557] optimize guireader --- .../cocostudio/CCSGUIReader.cpp | 2933 +++++++++-------- .../editor-support/cocostudio/CCSGUIReader.h | 103 +- .../CocoStudioGUITest/UIScene.cpp | 2 +- 3 files changed, 1692 insertions(+), 1346 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 3ad788b563..ca1067e504 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -34,36 +34,36 @@ namespace cocostudio { -static CCSGUIReader* sharedReader = NULL; +static GUIReader* sharedReader = NULL; -CCSGUIReader::CCSGUIReader(): -m_strFilePath(""), -m_bOlderVersion(false) +GUIReader::GUIReader(): +m_strFilePath("") { - _fileDesignSizes = Dictionary::create(); + _fileDesignSizes = CCDictionary::create(); CC_SAFE_RETAIN(_fileDesignSizes); } -CCSGUIReader::~CCSGUIReader() +GUIReader::~GUIReader() { + _fileDesignSizes->removeAllObjects(); CC_SAFE_RELEASE(_fileDesignSizes); } -CCSGUIReader* CCSGUIReader::shareReader() +GUIReader* GUIReader::shareReader() { if (!sharedReader) { - sharedReader = new CCSGUIReader(); + sharedReader = new GUIReader(); } return sharedReader; } -void CCSGUIReader::purgeCCSGUIReader() +void GUIReader::purgeGUIReader() { - CC_SAFE_DELETE(sharedReader); + CC_SAFE_DELETE(sharedReader); } -int CCSGUIReader::getVersionInteger(const char *str) +int GUIReader::getVersionInteger(const char *str) { /*********temp***********/ std::string strVersion = str; @@ -98,11 +98,132 @@ int CCSGUIReader::getVersionInteger(const char *str) /************************/ } -UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) +void GUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size) { + if (!_fileDesignSizes) + { + return; + } + cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); + _fileDesignSizes->setObject(strSize, fileName); +} + +const cocos2d::Size GUIReader::getFileDesignSize(const char* fileName) const +{ + if (!_fileDesignSizes) + { + return cocos2d::Size::ZERO; + } + cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)_fileDesignSizes->objectForKey(fileName))->_string.c_str()); + return designSize; +} + + +UIWidget* GUIReader::widgetFromJsonFile(const char *fileName) +{ + DictionaryHelper* dicHelper = DICTOOL; + const char *des = NULL; + std::string jsonpath; + JsonDictionary *jsonDict = NULL; + jsonpath = CCFileUtils::getInstance()->fullPathForFilename(fileName); + int pos = jsonpath.find_last_of('/'); + m_strFilePath = jsonpath.substr(0,pos+1); + long size = 0; + des = (char*)(CCFileUtils::getInstance()->getFileData(jsonpath.c_str(),"r" , &size)); + if(NULL == des || strcmp(des, "") == 0) + { + printf("read json file[%s] error!\n", fileName); + return NULL; + } + std::string strDes(des); + jsonDict = new JsonDictionary(); + jsonDict->initWithDescription(strDes.c_str()); + UIWidget* widget = NULL; - const char* classname = DICTOOL->getStringValue_json(data, "classname"); - JsonDictionary* uiOptions = DICTOOL->getSubDictionary_json(data, "options"); + const char* fileVersion = dicHelper->getStringValue_json(jsonDict, "version"); + WidgetPropertiesReader * pReader = NULL; + if (fileVersion) + { + int versionInteger = getVersionInteger(fileVersion); + if (versionInteger < 250) + { + pReader = new WidgetPropertiesReader0250(); + widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName); + } + else + { + pReader = new WidgetPropertiesReader0300(); + widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName); + } + } + else + { + pReader = new WidgetPropertiesReader0250(); + widget = pReader->createWidget(jsonDict, m_strFilePath.c_str(), fileName); + } + + CC_SAFE_DELETE(pReader); + CC_SAFE_DELETE(jsonDict); + CC_SAFE_DELETE_ARRAY(des); + return widget; +} + + + +UIWidget* WidgetPropertiesReader0250::createWidget(JsonDictionary* data, const char* fullPath, const char* fileName) +{ + m_strFilePath = fullPath; + DictionaryHelper* dicHelper = DICTOOL; + int texturesCount = dicHelper->getArrayCount_json(data, "textures"); + + for (int i=0; igetStringValueFromArray_json(data, "textures", i); + std::string tp = fullPath; + tp.append(file); + CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); + } + float fileDesignWidth = dicHelper->getFloatValue_json(data, "designWidth"); + float fileDesignHeight = dicHelper->getFloatValue_json(data, "designHeight"); + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + printf("Read design size error!\n"); + Size winSize = Director::getInstance()->getWinSize(); + GUIReader::shareReader()->storeFileDesignSize(fileName, winSize); + } + else + { + GUIReader::shareReader()->storeFileDesignSize(fileName, Size(fileDesignWidth, fileDesignHeight)); + } + JsonDictionary* widgetTree = dicHelper->getSubDictionary_json(data, "widgetTree"); + UIWidget* widget = widgetFromJsonDictionary(widgetTree); + + /* *********temp********* */ + if (widget->getContentSize().equals(Size::ZERO)) + { + UILayout* rootWidget = dynamic_cast(widget); + rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); + } + /* ********************** */ + + // widget->setFileDesignSize(Size(fileDesignWidth, fileDesignHeight)); + JsonDictionary* actions = dicHelper->getSubDictionary_json(data, "animation"); + /* *********temp********* */ + // ActionManager::shareManager()->releaseActions(); + /* ********************** */ + CCLOG("file name == [%s]",fileName); + Object* rootWidget = (Object*) widget; + ActionManagerEx::shareManager()->initWithDictionary(fileName,actions,rootWidget); + CC_SAFE_DELETE(widgetTree); + CC_SAFE_DELETE(actions); + return widget; +} + +UIWidget* WidgetPropertiesReader0250::widgetFromJsonDictionary(JsonDictionary *data) +{ + DictionaryHelper* dicHelper = DICTOOL; + UIWidget* widget = NULL; + const char* classname = dicHelper->getStringValue_json(data, "classname"); + JsonDictionary* uiOptions = dicHelper->getSubDictionary_json(data, "options"); if (classname && strcmp(classname, "Button") == 0) { widget = UIButton::create(); @@ -134,12 +255,12 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) else if (classname && strcmp(classname, "TextArea") == 0) { widget = UILabel::create(); - setPropsForTextAreaFromJsonDictionary(widget, uiOptions); + setPropsForLabelFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "TextButton") == 0) { widget = UIButton::create(); - setPropsForTextButtonFromJsonDictionary(widget, uiOptions); + setPropsForButtonFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "TextField") == 0) { @@ -154,13 +275,742 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) else if (classname && strcmp(classname, "Panel") == 0) { widget = UILayout::create(); - setPropsForPanelFromJsonDictionary(widget, uiOptions); + setPropsForLayoutFromJsonDictionary(widget, uiOptions); } else if (classname && strcmp(classname, "Slider") == 0) { widget = UISlider::create(); setPropsForSliderFromJsonDictionary(widget, uiOptions); } + else if (classname && strcmp(classname, "LabelBMFont") == 0) + { + widget = UILabelBMFont::create(); + setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "DragPanel") == 0) + { + widget = UIScrollView::create(); + setPropsForScrollViewFromJsonDictionary(widget, uiOptions); + } + + int childrenCount = dicHelper->getArrayCount_json(data, "children"); + for (int i=0;igetDictionaryFromArray_json(data, "children", i); + UIWidget* child = widgetFromJsonDictionary(subData); + if (child) + { + widget->addChild(child); + } + CC_SAFE_DELETE(subData); + } + + CC_SAFE_DELETE(uiOptions); + return widget; +} + +void WidgetPropertiesReader0250::setPropsForWidgetFromJsonDictionary(UIWidget*widget,JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + bool ignoreSizeExsit = dicHelper->checkObjectExist_json(options, "ignoreSize"); + if (ignoreSizeExsit) + { + widget->ignoreContentAdaptWithSize(dicHelper->getBooleanValue_json(options, "ignoreSize")); + } + + float w = dicHelper->getFloatValue_json(options, "width"); + float h = dicHelper->getFloatValue_json(options, "height"); + widget->setSize(Size(w, h)); + + widget->setTag(dicHelper->getIntValue_json(options, "tag")); + widget->setActionTag(dicHelper->getIntValue_json(options, "actiontag")); + widget->setTouchEnabled(dicHelper->getBooleanValue_json(options, "touchAble")); + const char* name = dicHelper->getStringValue_json(options, "name"); + const char* widgetName = name?name:"default"; + widget->setName(widgetName); + float x = dicHelper->getFloatValue_json(options, "x"); + float y = dicHelper->getFloatValue_json(options, "y"); + widget->setPosition(Point(x,y)); + bool sx = dicHelper->checkObjectExist_json(options, "scaleX"); + if (sx) + { + widget->setScaleX(dicHelper->getFloatValue_json(options, "scaleX")); + } + bool sy = dicHelper->checkObjectExist_json(options, "scaleY"); + if (sy) + { + widget->setScaleY(dicHelper->getFloatValue_json(options, "scaleY")); + } + bool rt = dicHelper->checkObjectExist_json(options, "rotation"); + if (rt) + { + widget->setRotation(dicHelper->getFloatValue_json(options, "rotation")); + } + bool vb = dicHelper->checkObjectExist_json(options, "visible"); + if (vb) + { + widget->setVisible(dicHelper->getBooleanValue_json(options, "visible")); + } + int z = dicHelper->getIntValue_json(options, "ZOrder"); + widget->setZOrder(z); +} + +void WidgetPropertiesReader0250::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + bool op = dicHelper->checkObjectExist_json(options, "opacity"); + if (op) + { + widget->setOpacity(dicHelper->getIntValue_json(options, "opacity")); + } + bool cr = dicHelper->checkObjectExist_json(options, "colorR"); + bool cg = dicHelper->checkObjectExist_json(options, "colorG"); + bool cb = dicHelper->checkObjectExist_json(options, "colorB"); + int colorR = cr ? dicHelper->getIntValue_json(options, "colorR") : 255; + int colorG = cg ? dicHelper->getIntValue_json(options, "colorG") : 255; + int colorB = cb ? dicHelper->getIntValue_json(options, "colorB") : 255; + widget->setColor(Color3B(colorR, colorG, colorB)); + bool apx = dicHelper->checkObjectExist_json(options, "anchorPointX"); + float apxf = apx ? dicHelper->getFloatValue_json(options, "anchorPointX") : ((widget->getWidgetType() == WidgetTypeWidget) ? 0.5f : 0.0f); + bool apy = dicHelper->checkObjectExist_json(options, "anchorPointY"); + float apyf = apy ? dicHelper->getFloatValue_json(options, "anchorPointY") : ((widget->getWidgetType() == WidgetTypeWidget) ? 0.5f : 0.0f); + widget->setAnchorPoint(Point(apxf, apyf)); + bool flipX = dicHelper->getBooleanValue_json(options, "flipX"); + bool flipY = dicHelper->getBooleanValue_json(options, "flipY"); + widget->setFlipX(flipX); + widget->setFlipY(flipY); +} + +void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UIButton* button = (UIButton*)widget; + bool scale9Enable = dicHelper->getBooleanValue_json(options, "scale9Enable"); + button->setScale9Enabled(scale9Enable); + + std::string tp_n = m_strFilePath; + std::string tp_p = m_strFilePath; + std::string tp_d = m_strFilePath; + + const char* normalFileName = dicHelper->getStringValue_json(options, "normal"); + const char* pressedFileName = dicHelper->getStringValue_json(options, "pressed"); + const char* disabledFileName = dicHelper->getStringValue_json(options, "disabled"); + + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + if (scale9Enable) + { + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + + if (useMergedTexture) + { + button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); + } + button->setCapInsets(Rect(cx, cy, cw, ch)); + bool sw = dicHelper->checkObjectExist_json(options, "scale9Width"); + bool sh = dicHelper->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = dicHelper->getFloatValue_json(options, "scale9Width"); + float shf = dicHelper->getFloatValue_json(options, "scale9Height"); + button->setSize(Size(swf, shf)); + } + } + else + { + if (useMergedTexture) + { + button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); + } + } + bool tt = dicHelper->checkObjectExist_json(options, "text"); + if (tt) + { + const char* text = dicHelper->getStringValue_json(options, "text"); + if (text) + { + button->setTitleText(text); + } + } + bool cr = dicHelper->checkObjectExist_json(options, "textColorR"); + bool cg = dicHelper->checkObjectExist_json(options, "textColorG"); + bool cb = dicHelper->checkObjectExist_json(options, "textColorB"); + int cri = cr?dicHelper->getIntValue_json(options, "textColorR"):255; + int cgi = cg?dicHelper->getIntValue_json(options, "textColorG"):255; + int cbi = cb?dicHelper->getIntValue_json(options, "textColorB"):255; + button->setTitleColor(Color3B(cri,cgi,cbi)); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); + if (fs) + { + button->setTitleFontSize(dicHelper->getIntValue_json(options, "fontSize")); + } + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); + if (fn) + { + button->setTitleFontName(dicHelper->getStringValue_json(options, "fontName")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UICheckBox* checkBox = (UICheckBox*)widget; + const char* backGroundFileName = dicHelper->getStringValue_json(options, "backGroundBox"); + const char* backGroundSelectedFileName = dicHelper->getStringValue_json(options, "backGroundBoxSelected"); + const char* frontCrossFileName = dicHelper->getStringValue_json(options, "frontCross"); + const char* backGroundDisabledFileName = dicHelper->getStringValue_json(options, "backGroundBoxDisabled"); + const char* frontCrossDisabledFileName = dicHelper->getStringValue_json(options, "frontCrossDisabled"); + + + std::string tp_b = m_strFilePath; + std::string tp_bs = m_strFilePath; + std::string tp_c = m_strFilePath; + std::string tp_bd = m_strFilePath; + std::string tp_cd = m_strFilePath; + + const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; + const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; + const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; + const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; + const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + + if (useMergedTexture) + { + checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + checkBox->loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp,backGroundDisabledFileName_tp,frontCrossDisabledFileName_tp); + } + + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + + UIImageView* imageView = (UIImageView*)widget; + const char* imageFileName = dicHelper->getStringValue_json(options, "fileName"); + bool scale9EnableExist = dicHelper->checkObjectExist_json(options, "scale9Enable"); + bool scale9Enable = false; + if (scale9EnableExist) + { + scale9Enable = dicHelper->getBooleanValue_json(options, "scale9Enable"); + } + imageView->setScale9Enabled(scale9Enable); + + std::string tp_i = m_strFilePath; + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + } + + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + if (scale9Enable) + { + if (useMergedTexture) + { + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + imageView->loadTexture(imageFileName_tp); + } + + bool sw = dicHelper->checkObjectExist_json(options, "scale9Width"); + bool sh = dicHelper->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = dicHelper->getFloatValue_json(options, "scale9Width"); + float shf = dicHelper->getFloatValue_json(options, "scale9Height"); + imageView->setSize(Size(swf, shf)); + } + + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + imageView->setCapInsets(Rect(cx, cy, cw, ch)); + + } + else + { + if (useMergedTexture) + { + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + imageView->loadTexture(imageFileName_tp); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UILabel* label = (UILabel*)widget; + bool touchScaleChangeAble = dicHelper->getBooleanValue_json(options, "touchScaleEnable"); + label->setTouchScaleChangeEnabled(touchScaleChangeAble); + const char* text = dicHelper->getStringValue_json(options, "text"); + label->setText(text); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); + if (fs) + { + label->setFontSize(dicHelper->getIntValue_json(options, "fontSize")); + } + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); + if (fn) + { + label->setFontName(dicHelper->getStringValue_json(options, "fontName")); + } + bool aw = dicHelper->checkObjectExist_json(options, "areaWidth"); + bool ah = dicHelper->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) + { + Size size = Size(dicHelper->getFloatValue_json(options, "areaWidth"),dicHelper->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); + } + bool ha = dicHelper->checkObjectExist_json(options, "hAlignment"); + if (ha) + { + label->setTextHorizontalAlignment((TextHAlignment)dicHelper->getIntValue_json(options, "hAlignment")); + } + bool va = dicHelper->checkObjectExist_json(options, "vAlignment"); + if (va) + { + label->setTextVerticalAlignment((TextVAlignment)dicHelper->getIntValue_json(options, "vAlignment")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; + bool sv = dicHelper->checkObjectExist_json(options, "stringValue"); + bool cmf = dicHelper->checkObjectExist_json(options, "charMapFile"); + bool iw = dicHelper->checkObjectExist_json(options, "itemWidth"); + bool ih = dicHelper->checkObjectExist_json(options, "itemHeight"); + bool scm = dicHelper->checkObjectExist_json(options, "startCharMap"); + if (sv && cmf && iw && ih && scm && (strcmp(dicHelper->getStringValue_json(options, "charMapFile"), "") != 0)) + { + std::string tp_c = m_strFilePath; + const char* cmf_tp = NULL; + const char* cmft = dicHelper->getStringValue_json(options, "charMapFile"); + cmf_tp = tp_c.append(cmft).c_str(); + + labelAtlas->setProperty(dicHelper->getStringValue_json(options, "stringValue"),cmf_tp,dicHelper->getIntValue_json(options, "itemWidth"),dicHelper->getIntValue_json(options,"itemHeight"),dicHelper->getStringValue_json(options, "startCharMap")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + + setPropsForWidgetFromJsonDictionary(widget, options); + UILayout* containerWidget = (UILayout*)widget; + if (!dynamic_cast(containerWidget) + && !dynamic_cast(containerWidget)) + { + containerWidget->setClippingEnabled(dicHelper->getBooleanValue_json(options, "clipAble")); + } + UILayout* panel = (UILayout*)widget; + bool backGroundScale9Enable = dicHelper->getBooleanValue_json(options, "backGroundScale9Enable"); + panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); + int cr = dicHelper->getIntValue_json(options, "bgColorR"); + int cg = dicHelper->getIntValue_json(options, "bgColorG"); + int cb = dicHelper->getIntValue_json(options, "bgColorB"); + + int scr = dicHelper->getIntValue_json(options, "bgStartColorR"); + int scg = dicHelper->getIntValue_json(options, "bgStartColorG"); + int scb = dicHelper->getIntValue_json(options, "bgStartColorB"); + + int ecr = dicHelper->getIntValue_json(options, "bgEndColorR"); + int ecg = dicHelper->getIntValue_json(options, "bgEndColorG"); + int ecb = dicHelper->getIntValue_json(options, "bgEndColorB"); + + float bgcv1 = dicHelper->getFloatValue_json(options, "vectorX"); + float bgcv2 = dicHelper->getFloatValue_json(options, "vectorY"); + panel->setBackGroundColorVector(Point(bgcv1, bgcv2)); + + int co = dicHelper->getIntValue_json(options, "bgColorOpacity"); + + int colorType = dicHelper->getIntValue_json(options, "colorType"); + panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); + panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb)); + panel->setBackGroundColor(Color3B(cr, cg, cb)); + panel->setBackGroundColorOpacity(co); + + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(options, "backGroundImage"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + if (backGroundScale9Enable) + { + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + if (useMergedTexture) + { + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + panel->setBackGroundImage(imageFileName_tp); + } + panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch)); + } + else + { + + if (useMergedTexture) + { + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + panel->setBackGroundImage(imageFileName_tp); + } + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForLayoutFromJsonDictionary(widget, options); + UIScrollView* scrollView = (UIScrollView*)widget; + float innerWidth = dicHelper->getFloatValue_json(options, "innerWidth"); + float innerHeight = dicHelper->getFloatValue_json(options, "innerHeight"); + scrollView->setInnerContainerSize(Size(innerWidth, innerHeight)); + int direction = dicHelper->getFloatValue_json(options, "direction"); + scrollView->setDirection((SCROLLVIEW_DIR)direction); + scrollView->setBounceEnabled(dicHelper->getBooleanValue_json(options, "bounceEnable")); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UISlider* slider = (UISlider*)widget; + + bool barTextureScale9Enable = dicHelper->getBooleanValue_json(options, "barTextureScale9Enable"); + slider->setScale9Enabled(barTextureScale9Enable); + bool bt = dicHelper->checkObjectExist_json(options, "barFileName"); + float barLength = dicHelper->getFloatValue_json(options, "length"); + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + if (bt) + { + if (barTextureScale9Enable) + { + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(options, "barFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadBarTexture(imageFileName_tp); + } + slider->setSize(Size(barLength, slider->getContentSize().height)); + } + else + { + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(options, "barFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadBarTexture(imageFileName_tp); + } + } + } + std::string tp_n = m_strFilePath; + std::string tp_p = m_strFilePath; + std::string tp_d = m_strFilePath; + + const char* normalFileName = dicHelper->getStringValue_json(options, "ballNormal"); + const char* pressedFileName = dicHelper->getStringValue_json(options, "ballPressed"); + const char* disabledFileName = dicHelper->getStringValue_json(options, "ballDisabled"); + + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,UI_TEX_TYPE_PLIST); + } + else + { + slider->loadSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); + } + slider->setPercent(dicHelper->getIntValue_json(options, "percent")); + + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(options, "progressBarFileName"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + slider->loadProgressBarTexture(imageFileName, UI_TEX_TYPE_PLIST); + } + else + { + slider->loadProgressBarTexture(imageFileName_tp); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UITextField* textField = (UITextField*)widget; + bool ph = dicHelper->checkObjectExist_json(options, "placeHolder"); + if (ph) + { + textField->setPlaceHolder(dicHelper->getStringValue_json(options, "placeHolder")); + } + textField->setText(dicHelper->getStringValue_json(options, "text")); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); + if (fs) + { + textField->setFontSize(dicHelper->getIntValue_json(options, "fontSize")); + } + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); + if (fn) + { + textField->setFontName(dicHelper->getStringValue_json(options, "fontName")); + } + bool tsw = dicHelper->checkObjectExist_json(options, "touchSizeWidth"); + bool tsh = dicHelper->checkObjectExist_json(options, "touchSizeHeight"); + if (tsw && tsh) + { + textField->setTouchSize(Size(dicHelper->getFloatValue_json(options, "touchSizeWidth"), dicHelper->getFloatValue_json(options,"touchSizeHeight"))); + } + + float dw = dicHelper->getFloatValue_json(options, "width"); + float dh = dicHelper->getFloatValue_json(options, "height"); + if (dw > 0.0f || dh > 0.0f) + { + //textField->setSize(Size(dw, dh)); + } + bool maxLengthEnable = dicHelper->getBooleanValue_json(options, "maxLengthEnable"); + textField->setMaxLengthEnabled(maxLengthEnable); + + if (maxLengthEnable) + { + int maxLength = dicHelper->getIntValue_json(options, "maxLength"); + textField->setMaxLength(maxLength); + } + bool passwordEnable = dicHelper->getBooleanValue_json(options, "passwordEnable"); + textField->setPasswordEnabled(passwordEnable); + if (passwordEnable) + { + textField->setPasswordStyleText(dicHelper->getStringValue_json(options, "passwordStyleText")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UILoadingBar* loadingBar = (UILoadingBar*)widget; + bool useMergedTexture = dicHelper->getBooleanValue_json(options, "useMergedTexture"); + std::string tp_b = m_strFilePath; + const char*imageFileName = dicHelper->getStringValue_json(options, "texture"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + if (useMergedTexture) + { + loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + } + else + { + loadingBar->loadTexture(imageFileName_tp); + } + loadingBar->setDirection(LoadingBarType(dicHelper->getIntValue_json(options, "direction"))); + loadingBar->setPercent(dicHelper->getIntValue_json(options, "percent")); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0250::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + + setPropsForWidgetFromJsonDictionary(widget, options); + + UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; + + std::string tp_c = m_strFilePath; + const char* cmf_tp = NULL; + const char* cmft = dicHelper->getStringValue_json(options, "fileName"); + cmf_tp = tp_c.append(cmft).c_str(); + + labelBMFont->setFntFile(cmf_tp); + + const char* text = dicHelper->getStringValue_json(options, "text"); + labelBMFont->setText(text); + + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + + +/*0.3.0.0~1.0.0.0*/ +UIWidget* WidgetPropertiesReader0300::createWidget(JsonDictionary* data, const char* fullPath, const char* fileName) +{ + m_strFilePath = fullPath; + DictionaryHelper* dicHelper = DICTOOL; + int texturesCount = dicHelper->getArrayCount_json(data, "textures"); + + for (int i=0; igetStringValueFromArray_json(data, "textures", i); + std::string tp = fullPath; + tp.append(file); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); + } + float fileDesignWidth = dicHelper->getFloatValue_json(data, "designWidth"); + float fileDesignHeight = dicHelper->getFloatValue_json(data, "designHeight"); + if (fileDesignWidth <= 0 || fileDesignHeight <= 0) { + printf("Read design size error!\n"); + Size winSize = Director::getInstance()->getWinSize(); + GUIReader::shareReader()->storeFileDesignSize(fileName, winSize); + } + else + { + GUIReader::shareReader()->storeFileDesignSize(fileName, Size(fileDesignWidth, fileDesignHeight)); + } + JsonDictionary* widgetTree = dicHelper->getSubDictionary_json(data, "widgetTree"); + UIWidget* widget = widgetFromJsonDictionary(widgetTree); + + /* *********temp********* */ + if (widget->getContentSize().equals(Size::ZERO)) + { + UILayout* rootWidget = dynamic_cast(widget); + rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); + } + /* ********************** */ + + // widget->setFileDesignSize(Size(fileDesignWidth, fileDesignHeight)); + JsonDictionary* actions = dicHelper->getSubDictionary_json(data, "animation"); + /* *********temp********* */ + // ActionManager::shareManager()->releaseActions(); + /* ********************** */ + CCLOG("file name == [%s]",fileName); + Object* rootWidget = (Object*) widget; + ActionManagerEx::shareManager()->initWithDictionary(fileName,actions,rootWidget); + CC_SAFE_DELETE(widgetTree); + CC_SAFE_DELETE(actions); + return widget; +} + +UIWidget* WidgetPropertiesReader0300::widgetFromJsonDictionary(JsonDictionary *data) +{ + DictionaryHelper* dicHelper = DICTOOL; + UIWidget* widget = NULL; + const char* classname = dicHelper->getStringValue_json(data, "classname"); + JsonDictionary* uiOptions = dicHelper->getSubDictionary_json(data, "options"); + if (classname && strcmp(classname, "Button") == 0) + { + widget = UIButton::create(); + setPropsForButtonFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "CheckBox") == 0) + { + widget = UICheckBox::create(); + setPropsForCheckBoxFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Label") == 0) + { + widget = UILabel::create(); + setPropsForLabelFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LabelAtlas") == 0) + { + widget = UILabelAtlas::create(); + setPropsForLabelAtlasFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LoadingBar") == 0) + { + widget = UILoadingBar::create(); + setPropsForLoadingBarFromJsonDictionary(widget, uiOptions); + }else if (classname && strcmp(classname, "ScrollView") == 0){ + widget = UIScrollView::create(); + setPropsForScrollViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextArea") == 0) + { + widget = UILabel::create(); + setPropsForLabelFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextButton") == 0) + { + widget = UIButton::create(); + setPropsForButtonFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "TextField") == 0) + { + widget = UITextField::create(); + setPropsForTextFieldFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "ImageView") == 0) + { + widget = UIImageView::create(); + setPropsForImageViewFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Panel") == 0) + { + widget = UILayout::create(); + setPropsForLayoutFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "Slider") == 0) + { + widget = UISlider::create(); + setPropsForSliderFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "LabelBMFont") == 0) + { + widget = UILabelBMFont::create(); + setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions); + } + else if (classname && strcmp(classname, "DragPanel") == 0) + { + widget = UIScrollView::create(); + setPropsForScrollViewFromJsonDictionary(widget, uiOptions); + } else if (classname && strcmp(classname, "ListView") == 0) { widget = UIListView::create(); @@ -171,1389 +1021,466 @@ UIWidget* CCSGUIReader::widgetFromJsonDictionary(JsonDictionary* data) widget = UIPageView::create(); setPropsForPageViewFromJsonDictionary(widget, uiOptions); } - else if (classname && strcmp(classname, "LabelBMFont") == 0) - { - widget = UILabelBMFont::create(); - setPropsForLabelBMFontFromJsonDictionary(widget, uiOptions); - } - else if (classname && strcmp(classname, "DragPanel") == 0) - { - widget = UIScrollView::create(); - setPropsForDragPanelFromJsonDictionary(widget, uiOptions); - } - - int childrenCount = DICTOOL->getArrayCount_json(data, "children"); + + int childrenCount = dicHelper->getArrayCount_json(data, "children"); for (int i=0;igetDictionaryFromArray_json(data, "children", i); + JsonDictionary* subData = dicHelper->getDictionaryFromArray_json(data, "children", i); UIWidget* child = widgetFromJsonDictionary(subData); if (child) { widget->addChild(child); } - CC_SAFE_DELETE(subData); + CC_SAFE_DELETE(subData); } - - CC_SAFE_DELETE(uiOptions); + + CC_SAFE_DELETE(uiOptions); return widget; } -void CCSGUIReader::storeFileDesignSize(const char *fileName, const cocos2d::Size &size) +void WidgetPropertiesReader0300::setPropsForWidgetFromJsonDictionary(UIWidget*widget,JsonDictionary *options) { - if (!_fileDesignSizes) - { - _fileDesignSizes = cocos2d::Dictionary::create(); - _fileDesignSizes->retain(); - } - cocos2d::String* strSize = cocos2d::String::createWithFormat("{%f,%f}", size.width, size.height); - _fileDesignSizes->setObject(strSize, fileName); -} - -const cocos2d::Size CCSGUIReader::getFileDesignSize(const char* fileName) const -{ - if (!_fileDesignSizes) - { - return cocos2d::Size::ZERO; - } - cocos2d::Size designSize = cocos2d::SizeFromString(((cocos2d::String*)_fileDesignSizes->objectForKey(fileName))->_string.c_str()); - return designSize; -} - -UIWidget* CCSGUIReader::widgetFromJsonFile(const char *fileName) -{ - m_bOlderVersion = false; - const char *des = NULL; - std::string jsonpath; - JsonDictionary *jsonDict = NULL; - jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); - - long size = 0; - des = (char*)(FileUtils::getInstance()->getFileData(jsonpath.c_str(),"r" , &size)); - if(NULL == des || strcmp(des, "") == 0) - { - printf("read json file[%s] error!\n", fileName); - return NULL; - } - std::string strDes(des); - jsonDict = new JsonDictionary(); - jsonDict->initWithDescription(strDes.c_str()); - - const char* fileVersion = DICTOOL->getStringValue_json(jsonDict, "version"); - if (!fileVersion || getVersionInteger(fileVersion) < 250) - { - m_bOlderVersion = true; - } - - int texturesCount = DICTOOL->getArrayCount_json(jsonDict, "textures"); - long pos = jsonpath.find_last_of('/'); - m_strFilePath = jsonpath.substr(0,pos+1); - for (int i=0; igetStringValueFromArray_json(jsonDict, "textures", i); - std::string tp = m_strFilePath; - tp.append(file); - SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); - } - float fileDesignWidth = DICTOOL->getFloatValue_json(jsonDict, "designWidth"); - float fileDesignHeight = DICTOOL->getFloatValue_json(jsonDict, "designHeight"); - if (fileDesignWidth <= 0 || fileDesignHeight <= 0) - { - printf("Read design size error!\n"); - Size winSize = Director::getInstance()->getWinSize(); - storeFileDesignSize(fileName, winSize); - } - else - { - storeFileDesignSize(fileName, cocos2d::Size(fileDesignWidth, fileDesignHeight)); - } - JsonDictionary* widgetTree = DICTOOL->getSubDictionary_json(jsonDict, "widgetTree"); - UIWidget* widget = widgetFromJsonDictionary(widgetTree); - - /* *********temp********* */ - if (widget->getContentSize().equals(Size::ZERO)) - { - UILayout* rootWidget = dynamic_cast(widget); - rootWidget->setSize(Size(fileDesignWidth, fileDesignHeight)); - } - /* ********************** */ - -// widget->setFileDesignSize(CCSizeMake(fileDesignWidth, fileDesignHeight)); - JsonDictionary* actions = DICTOOL->getSubDictionary_json(jsonDict, "animation"); - /* *********temp********* */ -// ActionManager::shareManager()->releaseActions(); - /* ********************** */ - CCLOG("file name == [%s]",fileName); - ActionManagerEx::shareManager()->initWithDictionary(fileName,actions,widget); - - CC_SAFE_DELETE(widgetTree); - CC_SAFE_DELETE(actions); - CC_SAFE_DELETE(jsonDict); - CC_SAFE_DELETE_ARRAY(des); - return widget; -} - -void CCSGUIReader::setPropsForWidgetFromJsonDictionary(UIWidget*widget,JsonDictionary *options) -{ - bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, "ignoreSize"); + DictionaryHelper* dicHelper = DICTOOL; + bool ignoreSizeExsit = dicHelper->checkObjectExist_json(options, "ignoreSize"); if (ignoreSizeExsit) { - widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, "ignoreSize")); + widget->ignoreContentAdaptWithSize(dicHelper->getBooleanValue_json(options, "ignoreSize")); } - float w = DICTOOL->getFloatValue_json(options, "width"); - float h = DICTOOL->getFloatValue_json(options, "height"); + float w = dicHelper->getFloatValue_json(options, "width"); + float h = dicHelper->getFloatValue_json(options, "height"); widget->setSize(Size(w, h)); - widget->setTag(DICTOOL->getIntValue_json(options, "tag")); - widget->setActionTag(DICTOOL->getIntValue_json(options, "actiontag")); - widget->setTouchEnabled(DICTOOL->getBooleanValue_json(options, "touchAble")); - const char* name = DICTOOL->getStringValue_json(options, "name"); + widget->setTag(dicHelper->getIntValue_json(options, "tag")); + widget->setActionTag(dicHelper->getIntValue_json(options, "actiontag")); + widget->setTouchEnabled(dicHelper->getBooleanValue_json(options, "touchAble")); + const char* name = dicHelper->getStringValue_json(options, "name"); const char* widgetName = name?name:"default"; widget->setName(widgetName); - float x = DICTOOL->getFloatValue_json(options, "x"); - float y = DICTOOL->getFloatValue_json(options, "y"); + float x = dicHelper->getFloatValue_json(options, "x"); + float y = dicHelper->getFloatValue_json(options, "y"); widget->setPosition(Point(x,y)); - bool sx = DICTOOL->checkObjectExist_json(options, "scaleX"); + bool sx = dicHelper->checkObjectExist_json(options, "scaleX"); if (sx) { - widget->setScaleX(DICTOOL->getFloatValue_json(options, "scaleX")); + widget->setScaleX(dicHelper->getFloatValue_json(options, "scaleX")); } - bool sy = DICTOOL->checkObjectExist_json(options, "scaleY"); + bool sy = dicHelper->checkObjectExist_json(options, "scaleY"); if (sy) { - widget->setScaleY(DICTOOL->getFloatValue_json(options, "scaleY")); + widget->setScaleY(dicHelper->getFloatValue_json(options, "scaleY")); } - bool rt = DICTOOL->checkObjectExist_json(options, "rotation"); + bool rt = dicHelper->checkObjectExist_json(options, "rotation"); if (rt) { - widget->setRotation(DICTOOL->getFloatValue_json(options, "rotation")); + widget->setRotation(dicHelper->getFloatValue_json(options, "rotation")); } - bool vb = DICTOOL->checkObjectExist_json(options, "visible"); + bool vb = dicHelper->checkObjectExist_json(options, "visible"); if (vb) { - widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); + widget->setVisible(dicHelper->getBooleanValue_json(options, "visible")); } -// widget->setUseMergedTexture(DICTOOL->getBooleanValue_json(options, "useMergedTexture")); - int z = DICTOOL->getIntValue_json(options, "ZOrder"); + int z = dicHelper->getIntValue_json(options, "ZOrder"); widget->setZOrder(z); } -void CCSGUIReader::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +void WidgetPropertiesReader0300::setColorPropsForWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) { - bool op = DICTOOL->checkObjectExist_json(options, "opacity"); + DictionaryHelper* dicHelper = DICTOOL; + bool op = dicHelper->checkObjectExist_json(options, "opacity"); if (op) { - widget->setOpacity(DICTOOL->getIntValue_json(options, "opacity")); + widget->setOpacity(dicHelper->getIntValue_json(options, "opacity")); } - bool cr = DICTOOL->checkObjectExist_json(options, "colorR"); - bool cg = DICTOOL->checkObjectExist_json(options, "colorG"); - bool cb = DICTOOL->checkObjectExist_json(options, "colorB"); - int colorR = cr ? DICTOOL->getIntValue_json(options, "colorR") : 255; - int colorG = cg ? DICTOOL->getIntValue_json(options, "colorG") : 255; - int colorB = cb ? DICTOOL->getIntValue_json(options, "colorB") : 255; + bool cr = dicHelper->checkObjectExist_json(options, "colorR"); + bool cg = dicHelper->checkObjectExist_json(options, "colorG"); + bool cb = dicHelper->checkObjectExist_json(options, "colorB"); + int colorR = cr ? dicHelper->getIntValue_json(options, "colorR") : 255; + int colorG = cg ? dicHelper->getIntValue_json(options, "colorG") : 255; + int colorB = cb ? dicHelper->getIntValue_json(options, "colorB") : 255; widget->setColor(Color3B(colorR, colorG, colorB)); - bool apx = DICTOOL->checkObjectExist_json(options, "anchorPointX"); - float apxf = apx ? DICTOOL->getFloatValue_json(options, "anchorPointX") : 0.5f; - bool apy = DICTOOL->checkObjectExist_json(options, "anchorPointY"); - float apyf = apy ? DICTOOL->getFloatValue_json(options, "anchorPointY") : 0.5f; + bool apx = dicHelper->checkObjectExist_json(options, "anchorPointX"); + float apxf = apx ? dicHelper->getFloatValue_json(options, "anchorPointX") : ((widget->getWidgetType() == WidgetTypeWidget) ? 0.5f : 0.0f); + bool apy = dicHelper->checkObjectExist_json(options, "anchorPointY"); + float apyf = apy ? dicHelper->getFloatValue_json(options, "anchorPointY") : ((widget->getWidgetType() == WidgetTypeWidget) ? 0.5f : 0.0f); widget->setAnchorPoint(Point(apxf, apyf)); - bool flipX = DICTOOL->getBooleanValue_json(options, "flipX"); - bool flipY = DICTOOL->getBooleanValue_json(options, "flipY"); + bool flipX = dicHelper->getBooleanValue_json(options, "flipX"); + bool flipY = dicHelper->getBooleanValue_json(options, "flipY"); widget->setFlipX(flipX); widget->setFlipY(flipY); } -void CCSGUIReader::setPropsForButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - UIButton* button = (UIButton*)widget; - bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); - button->setScale9Enabled(scale9Enable); - - std::string tp_n = m_strFilePath; - std::string tp_p = m_strFilePath; - std::string tp_d = m_strFilePath; - - const char* normalFileName = DICTOOL->getStringValue_json(options, "normal"); - const char* pressedFileName = DICTOOL->getStringValue_json(options, "pressed"); - const char* disabledFileName = DICTOOL->getStringValue_json(options, "disabled"); - - const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; - const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; - const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - if (scale9Enable) - { - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - - if (useMergedTexture) - { - button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); - } - else - { - button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); - } - button->setCapInsets(Rect(cx, cy, cw, ch)); - bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); - bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); - if (sw && sh) - { - float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); - float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); - button->setSize(Size(swf, shf)); - } - } - else - { - if (useMergedTexture) - { - button->loadTextures(normalFileName, pressedFileName, disabledFileName,UI_TEX_TYPE_PLIST); - } - else - { - button->loadTextures(normalFileName_tp, pressedFileName_tp, disabledFileName_tp); - } - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - UIButton* button = (UIButton*)widget; - bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); - button->setScale9Enabled(scale9Enable); - - JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "normalData"); - int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); - switch (normalType) - { - case 0: - { - std::string tp_n = m_strFilePath; - const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); - const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; - button->loadTextureNormal(normalFileName_tp); - break; - } - case 1: - { - const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); - button->loadTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(normalDic); - JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "pressedData"); - int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); - switch (pressedType) - { - case 0: - { - std::string tp_p = m_strFilePath; - const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); - const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; - button->loadTexturePressed(pressedFileName_tp); - break; - } - case 1: - { - const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); - button->loadTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(pressedDic); - JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "disabledData"); - int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); - switch (disabledType) - { - case 0: - { - std::string tp_d = m_strFilePath; - const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); - const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; - button->loadTextureDisabled(disabledFileName_tp); - break; - } - case 1: - { - const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); - button->loadTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(disabledDic); - if (scale9Enable) - { - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - - button->setCapInsets(Rect(cx, cy, cw, ch)); - bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); - bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); - if (sw && sh) - { - float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); - float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); - button->setSize(Size(swf, shf)); - } - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - UICheckBox* checkBox = (UICheckBox*)widget; - const char* backGroundFileName = DICTOOL->getStringValue_json(options, "backGroundBox"); - const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(options, "backGroundBoxSelected"); - const char* frontCrossFileName = DICTOOL->getStringValue_json(options, "frontCross"); - const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(options, "backGroundBoxDisabled"); - const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "frontCrossDisabled"); - - - std::string tp_b = m_strFilePath; - std::string tp_bs = m_strFilePath; - std::string tp_c = m_strFilePath; - std::string tp_bd = m_strFilePath; - std::string tp_cd = m_strFilePath; - - const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; - const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; - const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; - const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; - const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - - if (useMergedTexture) - { - checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); - } - else - { - checkBox->loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp,backGroundDisabledFileName_tp,frontCrossDisabledFileName_tp); - } - - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - UICheckBox* checkBox = (UICheckBox*)widget; - - JsonDictionary* backGroundDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxData"); - int backGroundType = DICTOOL->getIntValue_json(backGroundDic, "resourceType"); - switch (backGroundType) - { - case 0: - { - std::string tp_b = m_strFilePath; - const char* backGroundFileName = DICTOOL->getStringValue_json(backGroundDic, "path"); - const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; - checkBox->loadTextureBackGround(backGroundFileName_tp); - break; - } - case 1: - { - const char* backGroundFileName = DICTOOL->getStringValue_json(backGroundDic, "path"); - checkBox->loadTextureBackGround(backGroundFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(backGroundDic); - - JsonDictionary* backGroundSelectedDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxSelectedData"); - int backGroundSelectedType = DICTOOL->getIntValue_json(backGroundSelectedDic, "resourceType"); - switch (backGroundSelectedType) - { - case 0: - { - std::string tp_bs = m_strFilePath; - const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(backGroundSelectedDic, "path"); - const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; - checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName_tp); - break; - } - case 1: - { - const char* backGroundSelectedFileName = DICTOOL->getStringValue_json(backGroundSelectedDic, "path"); - checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(backGroundSelectedDic); - - JsonDictionary* frontCrossDic = DICTOOL->getSubDictionary_json(options, "frontCrossData"); - int frontCrossType = DICTOOL->getIntValue_json(frontCrossDic, "resourceType"); - switch (frontCrossType) - { - case 0: - { - std::string tp_c = m_strFilePath; - const char* frontCrossFileName = DICTOOL->getStringValue_json(frontCrossDic, "path"); - const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; - checkBox->loadTextureFrontCross(frontCrossFileName_tp); - break; - } - case 1: - { - const char* frontCrossFileName = DICTOOL->getStringValue_json(frontCrossDic, "path"); - checkBox->loadTextureFrontCross(frontCrossFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(frontCrossDic); - - JsonDictionary* backGroundDisabledDic = DICTOOL->getSubDictionary_json(options, "backGroundBoxDisabledData"); - int backGroundDisabledType = DICTOOL->getIntValue_json(backGroundDisabledDic, "resourceType"); - switch (backGroundDisabledType) - { - case 0: - { - std::string tp_bd = m_strFilePath; - const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(backGroundDisabledDic, "path"); - const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; - checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName_tp); - break; - } - case 1: - { - const char* backGroundDisabledFileName = DICTOOL->getStringValue_json(backGroundDisabledDic, "path"); - checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(backGroundDisabledDic); - - JsonDictionary* frontCrossDisabledDic = DICTOOL->getSubDictionary_json(options, "frontCrossDisabledData"); - int frontCrossDisabledType = DICTOOL->getIntValue_json(frontCrossDisabledDic, "resourceType"); - switch (frontCrossDisabledType) - { - case 0: - { - std::string tp_cd = m_strFilePath; - const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "path"); - const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; - checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName_tp); - break; - } - case 1: - { - const char* frontCrossDisabledFileName = DICTOOL->getStringValue_json(options, "path"); - checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(frontCrossDisabledDic); - - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForImageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - - UIImageView* imageView = (UIImageView*)widget; - const char* imageFileName = DICTOOL->getStringValue_json(options, "fileName"); - bool scale9EnableExist = DICTOOL->checkObjectExist_json(options, "scale9Enable"); - bool scale9Enable = false; - if (scale9EnableExist) - { - scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); - } - imageView->setScale9Enabled(scale9Enable); - - std::string tp_i = m_strFilePath; - const char* imageFileName_tp = NULL; - if (imageFileName && (strcmp(imageFileName, "") != 0)) - { - imageFileName_tp = tp_i.append(imageFileName).c_str(); - } - - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - if (scale9Enable) - { - if (useMergedTexture) - { - imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - imageView->loadTexture(imageFileName_tp); - } - - bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); - bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); - if (sw && sh) - { - float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); - float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); - imageView->setSize(Size(swf, shf)); - } - - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - imageView->setCapInsets(Rect(cx, cy, cw, ch)); - - } - else - { - if (useMergedTexture) - { - imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - imageView->loadTexture(imageFileName_tp); - } - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - - UIImageView* imageView = (UIImageView*)widget; - - JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); - int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); - switch (imageFileNameType) - { - case 0: - { - std::string tp_i = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - const char* imageFileName_tp = NULL; - if (imageFileName && (strcmp(imageFileName, "") != 0)) - { - imageFileName_tp = tp_i.append(imageFileName).c_str(); - imageView->loadTexture(imageFileName_tp); - } - break; - } - case 1: - { - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(imageFileNameDic); - - bool scale9EnableExist = DICTOOL->checkObjectExist_json(options, "scale9Enable"); - bool scale9Enable = false; - if (scale9EnableExist) - { - scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); - } - imageView->setScale9Enabled(scale9Enable); - - - if (scale9Enable) - { - bool sw = DICTOOL->checkObjectExist_json(options, "scale9Width"); - bool sh = DICTOOL->checkObjectExist_json(options, "scale9Height"); - if (sw && sh) - { - float swf = DICTOOL->getFloatValue_json(options, "scale9Width"); - float shf = DICTOOL->getFloatValue_json(options, "scale9Height"); - imageView->setSize(Size(swf, shf)); - } - - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - - imageView->setCapInsets(Rect(cx, cy, cw, ch)); - - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +void WidgetPropertiesReader0300::setPropsForButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { + DictionaryHelper* dicHelper = DICTOOL; setPropsForWidgetFromJsonDictionary(widget, options); - UILabel* label = (UILabel*)widget; - bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, "touchScaleEnable"); - label->setTouchScaleChangeEnabled(touchScaleChangeAble); - const char* text = DICTOOL->getStringValue_json(options, "text"); - label->setText(text); - bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + UIButton* button = (UIButton*)widget; + bool scale9Enable = dicHelper->getBooleanValue_json(options, "scale9Enable"); + button->setScale9Enabled(scale9Enable); + + JsonDictionary* normalDic = dicHelper->getSubDictionary_json(options, "normalData"); + int normalType = dicHelper->getIntValue_json(normalDic, "resourceType"); + switch (normalType) + { + case 0: + { + std::string tp_n = m_strFilePath; + const char* normalFileName = dicHelper->getStringValue_json(normalDic, "path"); + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + button->loadTextureNormal(normalFileName_tp); + break; + } + case 1: + { + const char* normalFileName = dicHelper->getStringValue_json(normalDic, "path"); + button->loadTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(normalDic); + JsonDictionary* pressedDic = dicHelper->getSubDictionary_json(options, "pressedData"); + int pressedType = dicHelper->getIntValue_json(pressedDic, "resourceType"); + switch (pressedType) + { + case 0: + { + std::string tp_p = m_strFilePath; + const char* pressedFileName = dicHelper->getStringValue_json(pressedDic, "path"); + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + button->loadTexturePressed(pressedFileName_tp); + break; + } + case 1: + { + const char* pressedFileName = dicHelper->getStringValue_json(pressedDic, "path"); + button->loadTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(pressedDic); + JsonDictionary* disabledDic = dicHelper->getSubDictionary_json(options, "disabledData"); + int disabledType = dicHelper->getIntValue_json(disabledDic, "resourceType"); + switch (disabledType) + { + case 0: + { + std::string tp_d = m_strFilePath; + const char* disabledFileName = dicHelper->getStringValue_json(disabledDic, "path"); + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + button->loadTextureDisabled(disabledFileName_tp); + break; + } + case 1: + { + const char* disabledFileName = dicHelper->getStringValue_json(disabledDic, "path"); + button->loadTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(disabledDic); + if (scale9Enable) + { + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + + button->setCapInsets(Rect(cx, cy, cw, ch)); + bool sw = dicHelper->checkObjectExist_json(options, "scale9Width"); + bool sh = dicHelper->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = dicHelper->getFloatValue_json(options, "scale9Width"); + float shf = dicHelper->getFloatValue_json(options, "scale9Height"); + button->setSize(Size(swf, shf)); + } + } + bool tt = dicHelper->checkObjectExist_json(options, "text"); + if (tt) + { + const char* text = dicHelper->getStringValue_json(options, "text"); + if (text) + { + button->setTitleText(text); + } + } + + bool cr = dicHelper->checkObjectExist_json(options, "textColorR"); + bool cg = dicHelper->checkObjectExist_json(options, "textColorG"); + bool cb = dicHelper->checkObjectExist_json(options, "textColorB"); + int cri = cr?dicHelper->getIntValue_json(options, "textColorR"):255; + int cgi = cg?dicHelper->getIntValue_json(options, "textColorG"):255; + int cbi = cb?dicHelper->getIntValue_json(options, "textColorB"):255; + button->setTitleColor(Color3B(cri,cgi,cbi)); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); if (fs) { - label->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + button->setTitleFontSize(dicHelper->getIntValue_json(options, "fontSize")); } - bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); if (fn) { - label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); + button->setTitleFontName(dicHelper->getStringValue_json(options, "fontName")); } - bool cro = DICTOOL->checkObjectExist_json(options, "colorR"); - bool cgo = DICTOOL->checkObjectExist_json(options, "colorG"); - bool cbo = DICTOOL->checkObjectExist_json(options, "colorB"); - int cr = cro?DICTOOL->getIntValue_json(options, "colorR"):255; - int cg = cgo?DICTOOL->getIntValue_json(options, "colorG"):255; - int cb = cbo?DICTOOL->getIntValue_json(options, "colorB"):255; - Color3B tc = Color3B(cr, cg, cb); - label->setColor(tc); setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +void WidgetPropertiesReader0300::setPropsForCheckBoxFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { - if (m_bOlderVersion) + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UICheckBox* checkBox = (UICheckBox*)widget; + + JsonDictionary* backGroundDic = dicHelper->getSubDictionary_json(options, "backGroundBoxData"); + int backGroundType = dicHelper->getIntValue_json(backGroundDic, "resourceType"); + switch (backGroundType) { - setPropsForWidgetFromJsonDictionary(widget, options); - UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; - bool sv = DICTOOL->checkObjectExist_json(options, "stringValue"); - bool cmf = DICTOOL->checkObjectExist_json(options, "charMapFile"); - bool iw = DICTOOL->checkObjectExist_json(options, "itemWidth"); - bool ih = DICTOOL->checkObjectExist_json(options, "itemHeight"); - bool scm = DICTOOL->checkObjectExist_json(options, "startCharMap"); - if (sv && cmf && iw && ih && scm && (strcmp(DICTOOL->getStringValue_json(options, "charMapFile"), "") != 0)) + case 0: + { + std::string tp_b = m_strFilePath; + const char* backGroundFileName = dicHelper->getStringValue_json(backGroundDic, "path"); + const char* backGroundFileName_tp = (backGroundFileName && (strcmp(backGroundFileName, "") != 0))?tp_b.append(backGroundFileName).c_str():NULL; + checkBox->loadTextureBackGround(backGroundFileName_tp); + break; + } + case 1: + { + const char* backGroundFileName = dicHelper->getStringValue_json(backGroundDic, "path"); + checkBox->loadTextureBackGround(backGroundFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundDic); + + JsonDictionary* backGroundSelectedDic = dicHelper->getSubDictionary_json(options, "backGroundBoxSelectedData"); + int backGroundSelectedType = dicHelper->getIntValue_json(backGroundSelectedDic, "resourceType"); + switch (backGroundSelectedType) + { + case 0: + { + std::string tp_bs = m_strFilePath; + const char* backGroundSelectedFileName = dicHelper->getStringValue_json(backGroundSelectedDic, "path"); + const char* backGroundSelectedFileName_tp = (backGroundSelectedFileName && (strcmp(backGroundSelectedFileName, "") != 0))?tp_bs.append(backGroundSelectedFileName).c_str():NULL; + checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName_tp); + break; + } + case 1: + { + const char* backGroundSelectedFileName = dicHelper->getStringValue_json(backGroundSelectedDic, "path"); + checkBox->loadTextureBackGroundSelected(backGroundSelectedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundSelectedDic); + + JsonDictionary* frontCrossDic = dicHelper->getSubDictionary_json(options, "frontCrossData"); + int frontCrossType = dicHelper->getIntValue_json(frontCrossDic, "resourceType"); + switch (frontCrossType) + { + case 0: { std::string tp_c = m_strFilePath; - const char* cmf_tp = NULL; - const char* cmft = DICTOOL->getStringValue_json(options, "charMapFile"); - cmf_tp = tp_c.append(cmft).c_str(); - - labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth"),DICTOOL->getIntValue_json(options,"itemHeight"),DICTOOL->getStringValue_json(options, "startCharMap")); + const char* frontCrossFileName = dicHelper->getStringValue_json(frontCrossDic, "path"); + const char* frontCrossFileName_tp = (frontCrossFileName && (strcmp(frontCrossFileName, "") != 0))?tp_c.append(frontCrossFileName).c_str():NULL; + checkBox->loadTextureFrontCross(frontCrossFileName_tp); + break; } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; - bool sv = DICTOOL->checkObjectExist_json(options, "stringValue"); - bool cmf = DICTOOL->checkObjectExist_json(options, "charMapFile"); - bool iw = DICTOOL->checkObjectExist_json(options, "itemWidth"); - bool ih = DICTOOL->checkObjectExist_json(options, "itemHeight"); - bool scm = DICTOOL->checkObjectExist_json(options, "startCharMap"); - if (sv && cmf && iw && ih && scm) + case 1: { - - JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "charMapFileData"); - int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); - switch (cmfType) - { - case 0: - { - std::string tp_c = m_strFilePath; - const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, "path"); - const char* cmf_tp = tp_c.append(cmfPath).c_str(); - labelAtlas->setProperty(DICTOOL->getStringValue_json(options, "stringValue"),cmf_tp,DICTOOL->getIntValue_json(options, "itemWidth"),DICTOOL->getIntValue_json(options,"itemHeight"),DICTOOL->getStringValue_json(options, "startCharMap")); - break; - } - case 1: - CCLOG("Wrong res type of LabelAtlas!"); - break; - default: - break; - } - CC_SAFE_DELETE(cmftDic); + const char* frontCrossFileName = dicHelper->getStringValue_json(frontCrossDic, "path"); + checkBox->loadTextureFrontCross(frontCrossFileName,UI_TEX_TYPE_PLIST); + break; } - setColorPropsForWidgetFromJsonDictionary(widget,options); + default: + break; } + CC_SAFE_DELETE(frontCrossDic); + + JsonDictionary* backGroundDisabledDic = dicHelper->getSubDictionary_json(options, "backGroundBoxDisabledData"); + int backGroundDisabledType = dicHelper->getIntValue_json(backGroundDisabledDic, "resourceType"); + switch (backGroundDisabledType) + { + case 0: + { + std::string tp_bd = m_strFilePath; + const char* backGroundDisabledFileName = dicHelper->getStringValue_json(backGroundDisabledDic, "path"); + const char* backGroundDisabledFileName_tp = (backGroundDisabledFileName && (strcmp(backGroundDisabledFileName, "") != 0))?tp_bd.append(backGroundDisabledFileName).c_str():NULL; + checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName_tp); + break; + } + case 1: + { + const char* backGroundDisabledFileName = dicHelper->getStringValue_json(backGroundDisabledDic, "path"); + checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(backGroundDisabledDic); + + JsonDictionary* frontCrossDisabledDic = dicHelper->getSubDictionary_json(options, "frontCrossDisabledData"); + int frontCrossDisabledType = dicHelper->getIntValue_json(frontCrossDisabledDic, "resourceType"); + switch (frontCrossDisabledType) + { + case 0: + { + std::string tp_cd = m_strFilePath; + const char* frontCrossDisabledFileName = dicHelper->getStringValue_json(options, "path"); + const char* frontCrossDisabledFileName_tp = (frontCrossDisabledFileName && (strcmp(frontCrossDisabledFileName, "") != 0))?tp_cd.append(frontCrossDisabledFileName).c_str():NULL; + checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName_tp); + break; + } + case 1: + { + const char* frontCrossDisabledFileName = dicHelper->getStringValue_json(options, "path"); + checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(frontCrossDisabledDic); + + setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForContainerWidgetFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +void WidgetPropertiesReader0300::setPropsForImageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { + DictionaryHelper* dicHelper = DICTOOL; setPropsForWidgetFromJsonDictionary(widget, options); - UILayout* containerWidget = (UILayout*)widget; - if (!dynamic_cast(containerWidget) - && !dynamic_cast(containerWidget)) + + UIImageView* imageView = (UIImageView*)widget; + + JsonDictionary* imageFileNameDic = dicHelper->getSubDictionary_json(options, "fileNameData"); + int imageFileNameType = dicHelper->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) { - containerWidget->setClippingEnabled(DICTOOL->getBooleanValue_json(options, "clipAble")); + case 0: + { + std::string tp_i = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + imageView->loadTexture(imageFileName_tp); + } + break; + } + case 1: + { + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + imageView->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + bool scale9EnableExist = dicHelper->checkObjectExist_json(options, "scale9Enable"); + bool scale9Enable = false; + if (scale9EnableExist) + { + scale9Enable = dicHelper->getBooleanValue_json(options, "scale9Enable"); + } + imageView->setScale9Enabled(scale9Enable); + + + if (scale9Enable) + { + bool sw = dicHelper->checkObjectExist_json(options, "scale9Width"); + bool sh = dicHelper->checkObjectExist_json(options, "scale9Height"); + if (sw && sh) + { + float swf = dicHelper->getFloatValue_json(options, "scale9Width"); + float shf = dicHelper->getFloatValue_json(options, "scale9Height"); + imageView->setSize(Size(swf, shf)); + } + + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + + imageView->setCapInsets(Rect(cx, cy, cw, ch)); + } setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForPanelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - if (m_bOlderVersion) - { - setPropsForContainerWidgetFromJsonDictionary(widget, options); - UILayout* panel = (UILayout*)widget; - bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); - panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); - int cr = DICTOOL->getIntValue_json(options, "bgColorR"); - int cg = DICTOOL->getIntValue_json(options, "bgColorG"); - int cb = DICTOOL->getIntValue_json(options, "bgColorB"); - - int scr = DICTOOL->getIntValue_json(options, "bgStartColorR"); - int scg = DICTOOL->getIntValue_json(options, "bgStartColorG"); - int scb = DICTOOL->getIntValue_json(options, "bgStartColorB"); - - int ecr = DICTOOL->getIntValue_json(options, "bgEndColorR"); - int ecg = DICTOOL->getIntValue_json(options, "bgEndColorG"); - int ecb = DICTOOL->getIntValue_json(options, "bgEndColorB"); - - float bgcv1 = DICTOOL->getFloatValue_json(options, "vectorX"); - float bgcv2 = DICTOOL->getFloatValue_json(options, "vectorY"); - panel->setBackGroundColorVector(Point(bgcv1, bgcv2)); - - int co = DICTOOL->getIntValue_json(options, "bgColorOpacity"); - - int colorType = DICTOOL->getIntValue_json(options, "colorType"); - panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); -// float w = DICTOOL->getFloatValue_json(options, "width"); -// float h = DICTOOL->getFloatValue_json(options, "height"); - panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb)); - panel->setBackGroundColor(Color3B(cr, cg, cb)); - panel->setBackGroundColorOpacity(co); -// panel->setSize(CCSizeMake(w, h)); - - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(options, "backGroundImage"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - if (backGroundScale9Enable) - { - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - if (useMergedTexture) - { - panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - panel->setBackGroundImage(imageFileName_tp); - } - panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch)); - } - else - { - - if (useMergedTexture) - { - panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - panel->setBackGroundImage(imageFileName_tp); - } - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForContainerWidgetFromJsonDictionary(widget, options); - UILayout* panel = (UILayout*)widget; - bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, "backGroundScale9Enable"); - panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); - int cr = DICTOOL->getIntValue_json(options, "bgColorR"); - int cg = DICTOOL->getIntValue_json(options, "bgColorG"); - int cb = DICTOOL->getIntValue_json(options, "bgColorB"); - - int scr = DICTOOL->getIntValue_json(options, "bgStartColorR"); - int scg = DICTOOL->getIntValue_json(options, "bgStartColorG"); - int scb = DICTOOL->getIntValue_json(options, "bgStartColorB"); - - int ecr = DICTOOL->getIntValue_json(options, "bgEndColorR"); - int ecg = DICTOOL->getIntValue_json(options, "bgEndColorG"); - int ecb = DICTOOL->getIntValue_json(options, "bgEndColorB"); - - float bgcv1 = DICTOOL->getFloatValue_json(options, "vectorX"); - float bgcv2 = DICTOOL->getFloatValue_json(options, "vectorY"); - panel->setBackGroundColorVector(Point(bgcv1, bgcv2)); - - int co = DICTOOL->getIntValue_json(options, "bgColorOpacity"); - - int colorType = DICTOOL->getIntValue_json(options, "colorType"); - panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); -// float w = DICTOOL->getFloatValue_json(options, "width"); -// float h = DICTOOL->getFloatValue_json(options, "height"); - panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb)); - panel->setBackGroundColor(Color3B(cr, cg, cb)); - panel->setBackGroundColorOpacity(co); -// panel->setSize(CCSizeMake(w, h)); - - - JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "backGroundImageData"); - int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); - switch (imageFileNameType) - { - case 0: - { - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - panel->setBackGroundImage(imageFileName_tp); - break; - } - case 1: - { - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(imageFileNameDic); - - if (backGroundScale9Enable) - { - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch)); - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - setPropsForPanelFromJsonDictionary(widget, options); - UIScrollView* scrollView = (UIScrollView*)widget; - float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); - float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); - scrollView->setInnerContainerSize(Size(innerWidth, innerHeight)); - /* gui mark */ - int direction = DICTOOL->getFloatValue_json(options, "direction"); - scrollView->setDirection((SCROLLVIEW_DIR)direction); - /**/ - setColorPropsForWidgetFromJsonDictionary(widget,options); -} - -void CCSGUIReader::setPropsForSliderFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - UISlider* slider = (UISlider*)widget; - - bool barTextureScale9Enable = DICTOOL->getBooleanValue_json(options, "barTextureScale9Enable"); - slider->setScale9Enabled(barTextureScale9Enable); - bool bt = DICTOOL->checkObjectExist_json(options, "barFileName"); - float barLength = DICTOOL->getFloatValue_json(options, "length"); - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - if (bt) - { - if (barTextureScale9Enable) - { - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - if (useMergedTexture) - { - slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - slider->loadBarTexture(imageFileName_tp); - } - slider->setSize(Size(barLength, slider->getContentSize().height)); - } - else - { - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(options, "barFileName"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - if (useMergedTexture) - { - slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - slider->loadBarTexture(imageFileName_tp); - } - } - } - std::string tp_n = m_strFilePath; - std::string tp_p = m_strFilePath; - std::string tp_d = m_strFilePath; - - const char* normalFileName = DICTOOL->getStringValue_json(options, "ballNormal"); - const char* pressedFileName = DICTOOL->getStringValue_json(options, "ballPressed"); - const char* disabledFileName = DICTOOL->getStringValue_json(options, "ballDisabled"); - - const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; - const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; - const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; - if (useMergedTexture) - { - slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,UI_TEX_TYPE_PLIST); - } - else - { - slider->loadSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); - } - slider->setPercent(DICTOOL->getIntValue_json(options, "percent")); - - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(options, "progressBarFileName"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - if (useMergedTexture) - { - slider->loadProgressBarTexture(imageFileName, UI_TEX_TYPE_PLIST); - } - else - { - slider->loadProgressBarTexture(imageFileName_tp); - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - UISlider* slider = (UISlider*)widget; - - bool barTextureScale9Enable = DICTOOL->getBooleanValue_json(options, "barTextureScale9Enable"); - slider->setScale9Enabled(barTextureScale9Enable); - bool bt = DICTOOL->checkObjectExist_json(options, "barFileName"); - float barLength = DICTOOL->getFloatValue_json(options, "length"); - if (bt) - { - if (barTextureScale9Enable) - { - - JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); - int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); - switch (imageFileType) - { - case 0: - { - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - slider->loadBarTexture(imageFileName_tp); - break; - } - case 1: - { - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - - slider->setSize(Size(barLength, slider->getContentSize().height)); - CC_SAFE_DELETE(imageFileNameDic); - } - else - { - JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "barFileNameData"); - int imageFileType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); - switch (imageFileType) - { - case 0: - { - std::string tp_b = m_strFilePath; - const char*imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - slider->loadBarTexture(imageFileName_tp); - break; - } - case 1: - { - const char*imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(imageFileNameDic); - } - } -// std::string tp_n = m_strFilePath; -// std::string tp_p = m_strFilePath; -// std::string tp_d = m_strFilePath; -// -// const char* normalFileName = DICTOOL->getStringValue_json(options, "ballNormal"); -// const char* pressedFileName = DICTOOL->getStringValue_json(options, "ballPressed"); -// const char* disabledFileName = DICTOOL->getStringValue_json(options, "ballDisabled"); -// -// const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; -// const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; -// const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; -// if (useMergedTexture) -// { -// slider->setSlidBallTextures(normalFileName,pressedFileName,disabledFileName,UI_TEX_TYPE_PLIST); -// } -// else -// { -// slider->setSlidBallTextures(normalFileName_tp,pressedFileName_tp,disabledFileName_tp); -// } - - JsonDictionary* normalDic = DICTOOL->getSubDictionary_json(options, "ballNormalData"); - int normalType = DICTOOL->getIntValue_json(normalDic, "resourceType"); - switch (normalType) - { - case 0: - { - std::string tp_n = m_strFilePath; - const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); - const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; - slider->loadSlidBallTextureNormal(normalFileName_tp); - break; - } - case 1: - { - const char* normalFileName = DICTOOL->getStringValue_json(normalDic, "path"); - slider->loadSlidBallTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(normalDic); - - JsonDictionary* pressedDic = DICTOOL->getSubDictionary_json(options, "ballPressedData"); - int pressedType = DICTOOL->getIntValue_json(pressedDic, "resourceType"); - switch (pressedType) - { - case 0: - { - std::string tp_p = m_strFilePath; - const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); - const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; - slider->loadSlidBallTexturePressed(pressedFileName_tp); - break; - } - case 1: - { - const char* pressedFileName = DICTOOL->getStringValue_json(pressedDic, "path"); - slider->loadSlidBallTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(pressedDic); - - JsonDictionary* disabledDic = DICTOOL->getSubDictionary_json(options, "ballDisabledData"); - int disabledType = DICTOOL->getIntValue_json(disabledDic, "resourceType"); - switch (disabledType) - { - case 0: - { - std::string tp_d = m_strFilePath; - const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); - const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; - slider->loadSlidBallTextureDisabled(disabledFileName_tp); - break; - } - case 1: - { - const char* disabledFileName = DICTOOL->getStringValue_json(disabledDic, "path"); - slider->loadSlidBallTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(disabledDic); - - slider->setPercent(DICTOOL->getIntValue_json(options, "percent")); - - JsonDictionary* progressBarDic = DICTOOL->getSubDictionary_json(options, "progressBarData"); - int progressBarType = DICTOOL->getIntValue_json(progressBarDic, "resourceType"); - switch (progressBarType) - { - case 0: - { - std::string tp_b = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(progressBarDic, "path"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - slider->loadProgressBarTexture(imageFileName_tp); - break; - } - case 1: - { - const char* imageFileName = DICTOOL->getStringValue_json(progressBarDic, "path"); - slider->loadProgressBarTexture(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForTextAreaFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +void WidgetPropertiesReader0300::setPropsForLabelFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { + DictionaryHelper* dicHelper = DICTOOL; setPropsForWidgetFromJsonDictionary(widget, options); - UILabel* textArea = (UILabel*)widget; - textArea->setText(DICTOOL->getStringValue_json(options, "text")); - bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); + UILabel* label = (UILabel*)widget; + bool touchScaleChangeAble = dicHelper->getBooleanValue_json(options, "touchScaleEnable"); + label->setTouchScaleChangeEnabled(touchScaleChangeAble); + const char* text = dicHelper->getStringValue_json(options, "text"); + label->setText(text); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); if (fs) { - textArea->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); + label->setFontSize(dicHelper->getIntValue_json(options, "fontSize")); } - int cr = DICTOOL->getIntValue_json(options, "colorR"); - int cg = DICTOOL->getIntValue_json(options, "colorG"); - int cb = DICTOOL->getIntValue_json(options, "colorB"); - textArea->setColor(Color3B(cr, cg, cb)); - textArea->setFontName(DICTOOL->getStringValue_json(options, "fontName")); - bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); - bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); + if (fn) + { + label->setFontName(dicHelper->getStringValue_json(options, "fontName")); + } + bool aw = dicHelper->checkObjectExist_json(options, "areaWidth"); + bool ah = dicHelper->checkObjectExist_json(options, "areaHeight"); if (aw && ah) { - Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); - textArea->setTextAreaSize(size); + Size size = Size(dicHelper->getFloatValue_json(options, "areaWidth"),dicHelper->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); } - bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); + bool ha = dicHelper->checkObjectExist_json(options, "hAlignment"); if (ha) { - textArea->setTextHorizontalAlignment((TextHAlignment)DICTOOL->getIntValue_json(options, "hAlignment")); + label->setTextHorizontalAlignment((TextHAlignment)dicHelper->getIntValue_json(options, "hAlignment")); } - bool va = DICTOOL->checkObjectExist_json(options, "vAlignment"); + bool va = dicHelper->checkObjectExist_json(options, "vAlignment"); if (va) { - textArea->setTextVerticalAlignment((TextVAlignment)DICTOOL->getIntValue_json(options, "vAlignment")); + label->setTextVerticalAlignment((TextVAlignment)dicHelper->getIntValue_json(options, "vAlignment")); } setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForTextButtonFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - setPropsForButtonFromJsonDictionary(widget, options); - - - UIButton* textButton = (UIButton*)widget; - textButton->setTitleText(DICTOOL->getStringValue_json(options, "text")); - bool cr = DICTOOL->checkObjectExist_json(options, "textColorR"); - bool cg = DICTOOL->checkObjectExist_json(options, "textColorG"); - bool cb = DICTOOL->checkObjectExist_json(options, "textColorB"); - int cri = cr?DICTOOL->getIntValue_json(options, "textColorR"):255; - int cgi = cg?DICTOOL->getIntValue_json(options, "textColorG"):255; - int cbi = cb?DICTOOL->getIntValue_json(options, "textColorB"):255; - textButton->setTitleColor(Color3B(cri,cgi,cbi)); - bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); - if (fs) - { - textButton->setTitleFontSize(DICTOOL->getIntValue_json(options, "fontSize")); - } - bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); - if (fn) - { - textButton->setTitleFontName(DICTOOL->getStringValue_json(options, "fontName")); - } - setColorPropsForWidgetFromJsonDictionary(widget,options); -} - -void CCSGUIReader::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +void WidgetPropertiesReader0300::setPropsForLabelAtlasFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { + DictionaryHelper* dicHelper = DICTOOL; setPropsForWidgetFromJsonDictionary(widget, options); - UITextField* textField = (UITextField*)widget; - bool ph = DICTOOL->checkObjectExist_json(options, "placeHolder"); - if (ph) + UILabelAtlas* labelAtlas = (UILabelAtlas*)widget; + bool sv = dicHelper->checkObjectExist_json(options, "stringValue"); + bool cmf = dicHelper->checkObjectExist_json(options, "charMapFile"); + bool iw = dicHelper->checkObjectExist_json(options, "itemWidth"); + bool ih = dicHelper->checkObjectExist_json(options, "itemHeight"); + bool scm = dicHelper->checkObjectExist_json(options, "startCharMap"); + if (sv && cmf && iw && ih && scm) { - textField->setPlaceHolder(DICTOOL->getStringValue_json(options, "placeHolder")); - } - textField->setText(DICTOOL->getStringValue_json(options, "text")); - bool fs = DICTOOL->checkObjectExist_json(options, "fontSize"); - if (fs) - { - textField->setFontSize(DICTOOL->getIntValue_json(options, "fontSize")); - } - bool fn = DICTOOL->checkObjectExist_json(options, "fontName"); - if (fn) - { - textField->setFontName(DICTOOL->getStringValue_json(options, "fontName")); - } - bool tsw = DICTOOL->checkObjectExist_json(options, "touchSizeWidth"); - bool tsh = DICTOOL->checkObjectExist_json(options, "touchSizeHeight"); - if (tsw && tsh) - { - textField->setTouchSize(Size(DICTOOL->getFloatValue_json(options, "touchSizeWidth"), DICTOOL->getFloatValue_json(options,"touchSizeHeight"))); - } - - float dw = DICTOOL->getFloatValue_json(options, "width"); - float dh = DICTOOL->getFloatValue_json(options, "height"); - if (dw > 0.0f || dh > 0.0f) - { - //textField->setSize(CCSizeMake(dw, dh)); - } - bool maxLengthEnable = DICTOOL->getBooleanValue_json(options, "maxLengthEnable"); - textField->setMaxLengthEnabled(maxLengthEnable); - - if (maxLengthEnable) - { - int maxLength = DICTOOL->getIntValue_json(options, "maxLength"); - textField->setMaxLength(maxLength); - } - bool passwordEnable = DICTOOL->getBooleanValue_json(options, "passwordEnable"); - textField->setPasswordEnabled(passwordEnable); - if (passwordEnable) - { - textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, "passwordStyleText")); - } - setColorPropsForWidgetFromJsonDictionary(widget,options); -} - -void CCSGUIReader::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, JsonDictionary *options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - UILoadingBar* loadingBar = (UILoadingBar*)widget; - bool useMergedTexture = DICTOOL->getBooleanValue_json(options, "useMergedTexture"); - std::string tp_b = m_strFilePath; - const char*imageFileName = DICTOOL->getStringValue_json(options, "texture"); - const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; - if (useMergedTexture) - { - loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); - } - else - { - loadingBar->loadTexture(imageFileName_tp); - } - loadingBar->setDirection(LoadingBarType(DICTOOL->getIntValue_json(options, "direction"))); - loadingBar->setPercent(DICTOOL->getIntValue_json(options, "percent")); - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - UILoadingBar* loadingBar = (UILoadingBar*)widget; - - JsonDictionary* imageFileNameDic = DICTOOL->getSubDictionary_json(options, "textureData"); - int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, "resourceType"); - switch (imageFileNameType) - { - case 0: - { - std::string tp_i = m_strFilePath; - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - const char* imageFileName_tp = NULL; - if (imageFileName && (strcmp(imageFileName, "") != 0)) - { - imageFileName_tp = tp_i.append(imageFileName).c_str(); - loadingBar->loadTexture(imageFileName_tp); - } - break; - } - case 1: - { - const char* imageFileName = DICTOOL->getStringValue_json(imageFileNameDic, "path"); - loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); - break; - } - default: - break; - } - CC_SAFE_DELETE(imageFileNameDic); - - /* gui mark add load bar scale9 parse */ - bool scale9Enable = DICTOOL->getBooleanValue_json(options, "scale9Enable"); - loadingBar->setScale9Enabled(scale9Enable); - - if (scale9Enable) - { - float cx = DICTOOL->getFloatValue_json(options, "capInsetsX"); - float cy = DICTOOL->getFloatValue_json(options, "capInsetsY"); - float cw = DICTOOL->getFloatValue_json(options, "capInsetsWidth"); - float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); - - loadingBar->setCapInsets(Rect(cx, cy, cw, ch)); - - float width = DICTOOL->getFloatValue_json(options, "width"); - float height = DICTOOL->getFloatValue_json(options, "height"); - loadingBar->setSize(Size(width, height)); - } - /**/ - - loadingBar->setDirection(LoadingBarType(DICTOOL->getIntValue_json(options, "direction"))); - loadingBar->setPercent(DICTOOL->getIntValue_json(options, "percent")); - setColorPropsForWidgetFromJsonDictionary(widget,options); - } -} - -void CCSGUIReader::setPropsForListViewFromJsonDictionary(UIWidget *widget, JsonDictionary *options) -{ - setPropsForScrollViewFromJsonDictionary(widget, options); -} - -void CCSGUIReader::setPropsForPageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) -{ - setPropsForPanelFromJsonDictionary(widget, options); - setColorPropsForWidgetFromJsonDictionary(widget,options); -} - -void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, JsonDictionary *options) -{ - if (m_bOlderVersion) - { - setPropsForWidgetFromJsonDictionary(widget, options); - - UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; - - std::string tp_c = m_strFilePath; - const char* cmf_tp = NULL; - const char* cmft = DICTOOL->getStringValue_json(options, "fileName"); - cmf_tp = tp_c.append(cmft).c_str(); - - labelBMFont->setFntFile(cmf_tp); - - const char* text = DICTOOL->getStringValue_json(options, "text"); - labelBMFont->setText(text); - - setColorPropsForWidgetFromJsonDictionary(widget,options); - } - else - { - setPropsForWidgetFromJsonDictionary(widget, options); - - UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; - - JsonDictionary* cmftDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); - int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); + JsonDictionary* cmftDic = dicHelper->getSubDictionary_json(options, "charMapFileData"); + int cmfType = dicHelper->getIntValue_json(cmftDic, "resourceType"); switch (cmfType) { case 0: { std::string tp_c = m_strFilePath; - const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, "path"); + const char* cmfPath = dicHelper->getStringValue_json(cmftDic, "path"); const char* cmf_tp = tp_c.append(cmfPath).c_str(); - labelBMFont->setFntFile(cmf_tp); + labelAtlas->setProperty(dicHelper->getStringValue_json(options, "stringValue"),cmf_tp,dicHelper->getIntValue_json(options, "itemWidth"),dicHelper->getIntValue_json(options,"itemHeight"),dicHelper->getStringValue_json(options, "startCharMap")); break; } case 1: @@ -1563,28 +1490,406 @@ void CCSGUIReader::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, Js break; } CC_SAFE_DELETE(cmftDic); - - const char* text = DICTOOL->getStringValue_json(options, "text"); - labelBMFont->setText(text); - - setColorPropsForWidgetFromJsonDictionary(widget,options); } + setColorPropsForWidgetFromJsonDictionary(widget,options); } -void CCSGUIReader::setPropsForDragPanelFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +void WidgetPropertiesReader0300::setPropsForLayoutFromJsonDictionary(UIWidget*widget,JsonDictionary* options) { - setPropsForPanelFromJsonDictionary(widget, options); + DictionaryHelper* dicHelper = DICTOOL; - UIScrollView* dragPanel = (UIScrollView*)widget; + setPropsForWidgetFromJsonDictionary(widget, options); + UILayout* panel = (UILayout*)widget; + if (!dynamic_cast(widget) + && !dynamic_cast(widget)) + { + panel->setClippingEnabled(dicHelper->getBooleanValue_json(options, "clipAble")); + } + bool backGroundScale9Enable = dicHelper->getBooleanValue_json(options, "backGroundScale9Enable"); + panel->setBackGroundImageScale9Enabled(backGroundScale9Enable); + int cr = dicHelper->getIntValue_json(options, "bgColorR"); + int cg = dicHelper->getIntValue_json(options, "bgColorG"); + int cb = dicHelper->getIntValue_json(options, "bgColorB"); - bool bounceEnable = DICTOOL->getBooleanValue_json(options, "bounceEnable"); - dragPanel->setBounceEnabled(bounceEnable); + int scr = dicHelper->getIntValue_json(options, "bgStartColorR"); + int scg = dicHelper->getIntValue_json(options, "bgStartColorG"); + int scb = dicHelper->getIntValue_json(options, "bgStartColorB"); - float innerWidth = DICTOOL->getFloatValue_json(options, "innerWidth"); - float innerHeight = DICTOOL->getFloatValue_json(options, "innerHeight"); - dragPanel->setInnerContainerSize(Size(innerWidth, innerHeight)); + int ecr = dicHelper->getIntValue_json(options, "bgEndColorR"); + int ecg = dicHelper->getIntValue_json(options, "bgEndColorG"); + int ecb = dicHelper->getIntValue_json(options, "bgEndColorB"); - setColorPropsForWidgetFromJsonDictionary(widget, options); + float bgcv1 = dicHelper->getFloatValue_json(options, "vectorX"); + float bgcv2 = dicHelper->getFloatValue_json(options, "vectorY"); + panel->setBackGroundColorVector(Point(bgcv1, bgcv2)); + + int co = dicHelper->getIntValue_json(options, "bgColorOpacity"); + + int colorType = dicHelper->getIntValue_json(options, "colorType"); + panel->setBackGroundColorType(LayoutBackGroundColorType(colorType)); + panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb)); + panel->setBackGroundColor(Color3B(cr, cg, cb)); + panel->setBackGroundColorOpacity(co); + + + JsonDictionary* imageFileNameDic = dicHelper->getSubDictionary_json(options, "backGroundImageData"); + int imageFileNameType = dicHelper->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + panel->setBackGroundImage(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + panel->setBackGroundImage(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + if (backGroundScale9Enable) + { + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch)); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); } +void WidgetPropertiesReader0300::setPropsForScrollViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForLayoutFromJsonDictionary(widget, options); + UIScrollView* scrollView = (UIScrollView*)widget; + float innerWidth = dicHelper->getFloatValue_json(options, "innerWidth"); + float innerHeight = dicHelper->getFloatValue_json(options, "innerHeight"); + scrollView->setInnerContainerSize(Size(innerWidth, innerHeight)); + int direction = dicHelper->getFloatValue_json(options, "direction"); + scrollView->setDirection((SCROLLVIEW_DIR)direction); + scrollView->setBounceEnabled(dicHelper->getBooleanValue_json(options, "bounceEnable")); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0300::setPropsForSliderFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UISlider* slider = (UISlider*)widget; + + bool barTextureScale9Enable = dicHelper->getBooleanValue_json(options, "barTextureScale9Enable"); + slider->setScale9Enabled(barTextureScale9Enable); + bool bt = dicHelper->checkObjectExist_json(options, "barFileName"); + float barLength = dicHelper->getFloatValue_json(options, "length"); + if (bt) + { + if (barTextureScale9Enable) + { + + JsonDictionary* imageFileNameDic = dicHelper->getSubDictionary_json(options, "barFileNameData"); + int imageFileType = dicHelper->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + + slider->setSize(Size(barLength, slider->getContentSize().height)); + CC_SAFE_DELETE(imageFileNameDic); + } + else + { + JsonDictionary* imageFileNameDic = dicHelper->getSubDictionary_json(options, "barFileNameData"); + int imageFileType = dicHelper->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char*imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char*imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + slider->loadBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + } + } + + JsonDictionary* normalDic = dicHelper->getSubDictionary_json(options, "ballNormalData"); + int normalType = dicHelper->getIntValue_json(normalDic, "resourceType"); + switch (normalType) + { + case 0: + { + std::string tp_n = m_strFilePath; + const char* normalFileName = dicHelper->getStringValue_json(normalDic, "path"); + const char* normalFileName_tp = (normalFileName && (strcmp(normalFileName, "") != 0))?tp_n.append(normalFileName).c_str():NULL; + slider->loadSlidBallTextureNormal(normalFileName_tp); + break; + } + case 1: + { + const char* normalFileName = dicHelper->getStringValue_json(normalDic, "path"); + slider->loadSlidBallTextureNormal(normalFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(normalDic); + + JsonDictionary* pressedDic = dicHelper->getSubDictionary_json(options, "ballPressedData"); + int pressedType = dicHelper->getIntValue_json(pressedDic, "resourceType"); + switch (pressedType) + { + case 0: + { + std::string tp_p = m_strFilePath; + const char* pressedFileName = dicHelper->getStringValue_json(pressedDic, "path"); + const char* pressedFileName_tp = (pressedFileName && (strcmp(pressedFileName, "") != 0))?tp_p.append(pressedFileName).c_str():NULL; + slider->loadSlidBallTexturePressed(pressedFileName_tp); + break; + } + case 1: + { + const char* pressedFileName = dicHelper->getStringValue_json(pressedDic, "path"); + slider->loadSlidBallTexturePressed(pressedFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(pressedDic); + + JsonDictionary* disabledDic = dicHelper->getSubDictionary_json(options, "ballDisabledData"); + int disabledType = dicHelper->getIntValue_json(disabledDic, "resourceType"); + switch (disabledType) + { + case 0: + { + std::string tp_d = m_strFilePath; + const char* disabledFileName = dicHelper->getStringValue_json(disabledDic, "path"); + const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():NULL; + slider->loadSlidBallTextureDisabled(disabledFileName_tp); + break; + } + case 1: + { + const char* disabledFileName = dicHelper->getStringValue_json(disabledDic, "path"); + slider->loadSlidBallTextureDisabled(disabledFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(disabledDic); + + slider->setPercent(dicHelper->getIntValue_json(options, "percent")); + + JsonDictionary* progressBarDic = dicHelper->getSubDictionary_json(options, "progressBarData"); + int progressBarType = dicHelper->getIntValue_json(progressBarDic, "resourceType"); + switch (progressBarType) + { + case 0: + { + std::string tp_b = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(progressBarDic, "path"); + const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():NULL; + slider->loadProgressBarTexture(imageFileName_tp); + break; + } + case 1: + { + const char* imageFileName = dicHelper->getStringValue_json(progressBarDic, "path"); + slider->loadProgressBarTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0300::setPropsForTextFieldFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UITextField* textField = (UITextField*)widget; + bool ph = dicHelper->checkObjectExist_json(options, "placeHolder"); + if (ph) + { + textField->setPlaceHolder(dicHelper->getStringValue_json(options, "placeHolder")); + } + textField->setText(dicHelper->getStringValue_json(options, "text")); + bool fs = dicHelper->checkObjectExist_json(options, "fontSize"); + if (fs) + { + textField->setFontSize(dicHelper->getIntValue_json(options, "fontSize")); + } + bool fn = dicHelper->checkObjectExist_json(options, "fontName"); + if (fn) + { + textField->setFontName(dicHelper->getStringValue_json(options, "fontName")); + } + bool tsw = dicHelper->checkObjectExist_json(options, "touchSizeWidth"); + bool tsh = dicHelper->checkObjectExist_json(options, "touchSizeHeight"); + if (tsw && tsh) + { + textField->setTouchSize(Size(dicHelper->getFloatValue_json(options, "touchSizeWidth"), dicHelper->getFloatValue_json(options,"touchSizeHeight"))); + } + + float dw = dicHelper->getFloatValue_json(options, "width"); + float dh = dicHelper->getFloatValue_json(options, "height"); + if (dw > 0.0f || dh > 0.0f) + { + //textField->setSize(Size(dw, dh)); + } + bool maxLengthEnable = dicHelper->getBooleanValue_json(options, "maxLengthEnable"); + textField->setMaxLengthEnabled(maxLengthEnable); + + if (maxLengthEnable) + { + int maxLength = dicHelper->getIntValue_json(options, "maxLength"); + textField->setMaxLength(maxLength); + } + bool passwordEnable = dicHelper->getBooleanValue_json(options, "passwordEnable"); + textField->setPasswordEnabled(passwordEnable); + if (passwordEnable) + { + textField->setPasswordStyleText(dicHelper->getStringValue_json(options, "passwordStyleText")); + } + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0300::setPropsForLoadingBarFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + UILoadingBar* loadingBar = (UILoadingBar*)widget; + + JsonDictionary* imageFileNameDic = dicHelper->getSubDictionary_json(options, "textureData"); + int imageFileNameType = dicHelper->getIntValue_json(imageFileNameDic, "resourceType"); + switch (imageFileNameType) + { + case 0: + { + std::string tp_i = m_strFilePath; + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + const char* imageFileName_tp = NULL; + if (imageFileName && (strcmp(imageFileName, "") != 0)) + { + imageFileName_tp = tp_i.append(imageFileName).c_str(); + loadingBar->loadTexture(imageFileName_tp); + } + break; + } + case 1: + { + const char* imageFileName = dicHelper->getStringValue_json(imageFileNameDic, "path"); + loadingBar->loadTexture(imageFileName,UI_TEX_TYPE_PLIST); + break; + } + default: + break; + } + CC_SAFE_DELETE(imageFileNameDic); + + /* gui mark add load bar scale9 parse */ + bool scale9Enable = dicHelper->getBooleanValue_json(options, "scale9Enable"); + loadingBar->setScale9Enabled(scale9Enable); + + if (scale9Enable) + { + float cx = dicHelper->getFloatValue_json(options, "capInsetsX"); + float cy = dicHelper->getFloatValue_json(options, "capInsetsY"); + float cw = dicHelper->getFloatValue_json(options, "capInsetsWidth"); + float ch = dicHelper->getFloatValue_json(options, "capInsetsHeight"); + + loadingBar->setCapInsets(Rect(cx, cy, cw, ch)); + + float width = dicHelper->getFloatValue_json(options, "width"); + float height = dicHelper->getFloatValue_json(options, "height"); + loadingBar->setSize(Size(width, height)); + } + /**/ + + loadingBar->setDirection(LoadingBarType(dicHelper->getIntValue_json(options, "direction"))); + loadingBar->setPercent(dicHelper->getIntValue_json(options, "percent")); + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0300::setPropsForLabelBMFontFromJsonDictionary(UIWidget *widget, JsonDictionary *options) +{ + DictionaryHelper* dicHelper = DICTOOL; + setPropsForWidgetFromJsonDictionary(widget, options); + + UILabelBMFont* labelBMFont = (UILabelBMFont*)widget; + + JsonDictionary* cmftDic = dicHelper->getSubDictionary_json(options, "fileNameData"); + int cmfType = dicHelper->getIntValue_json(cmftDic, "resourceType"); + switch (cmfType) + { + case 0: + { + std::string tp_c = m_strFilePath; + const char* cmfPath = dicHelper->getStringValue_json(cmftDic, "path"); + const char* cmf_tp = tp_c.append(cmfPath).c_str(); + labelBMFont->setFntFile(cmf_tp); + break; + } + case 1: + CCLOG("Wrong res type of LabelAtlas!"); + break; + default: + break; + } + CC_SAFE_DELETE(cmftDic); + + const char* text = dicHelper->getStringValue_json(options, "text"); + labelBMFont->setText(text); + + setColorPropsForWidgetFromJsonDictionary(widget,options); +} + +void WidgetPropertiesReader0300::setPropsForPageViewFromJsonDictionary(UIWidget*widget,JsonDictionary* options) +{ + +} + +void WidgetPropertiesReader0300::setPropsForListViewFromJsonDictionary(UIWidget* widget, JsonDictionary* options) +{ + +} } \ No newline at end of file diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.h b/cocos/editor-support/cocostudio/CCSGUIReader.h index 415b7b9e81..19a37292fd 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.h +++ b/cocos/editor-support/cocostudio/CCSGUIReader.h @@ -31,49 +31,90 @@ namespace cocostudio { #define kCCSVersion 1.0 -class CCSGUIReader : cocos2d::Object +class GUIReader : public cocos2d::Object { public: - CCSGUIReader(); - ~CCSGUIReader(); - static CCSGUIReader* shareReader(); - static void purgeCCSGUIReader(); + GUIReader(); + ~GUIReader(); + static GUIReader* shareReader(); + static void purgeGUIReader(); gui::UIWidget* widgetFromJsonFile(const char* fileName); - gui::UIWidget* widgetFromJsonDictionary(JsonDictionary* data); - int getVersionInteger(const char* str); - - void setPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setColorPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForCheckBoxFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForImageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForLabelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForLabelAtlasFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForContainerWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForScrollViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForSliderFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForTextAreaFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForTextButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForTextFieldFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForLoadingBarFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForImageButtonFromJsonDictionary(gui::UIWidget* widget, JsonDictionary* options); - void setPropsForListViewFromJsonDictionary(gui::UIWidget* widget, JsonDictionary* options); - void setPropsForPageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void setPropsForDragPanelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); - void storeFileDesignSize(const char* fileName, const cocos2d::Size &size); - const cocos2d::Size getFileDesignSize(const char* fileName) const; protected: std::string m_strFilePath; - bool m_bOlderVersion; cocos2d::Dictionary* _fileDesignSizes; }; +class WidgetPropertiesReader : public cocos2d::Object +{ +public: + virtual gui::UIWidget* createWidget(JsonDictionary* dic, const char* fullPath, const char* fileName)=0; + virtual gui::UIWidget* widgetFromJsonDictionary(JsonDictionary* dic) = 0; +protected: + std::string m_strFilePath; +}; + + +class WidgetPropertiesReader0250 : public WidgetPropertiesReader +{ + + +public: + WidgetPropertiesReader0250(){}; + virtual ~WidgetPropertiesReader0250(){}; + + virtual gui::UIWidget* createWidget(JsonDictionary* dic, const char* fullPath, const char* fileName); + virtual gui::UIWidget* widgetFromJsonDictionary(JsonDictionary* dic); + virtual void setPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + + virtual void setColorPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForCheckBoxFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForImageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelAtlasFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLoadingBarFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForSliderFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForTextFieldFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + + virtual void setPropsForLayoutFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForScrollViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); +}; + +class WidgetPropertiesReader0300 : public WidgetPropertiesReader +{ + + +public: + WidgetPropertiesReader0300(){}; + virtual ~WidgetPropertiesReader0300(){}; + + virtual gui::UIWidget* createWidget(JsonDictionary* dic, const char* fullPath, const char* fileName); + virtual gui::UIWidget* widgetFromJsonDictionary(JsonDictionary* dic); + virtual void setPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + + virtual void setColorPropsForWidgetFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForButtonFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForCheckBoxFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForImageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelAtlasFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLabelBMFontFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForLoadingBarFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForSliderFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForTextFieldFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + + virtual void setPropsForLayoutFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForPageViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForScrollViewFromJsonDictionary(gui::UIWidget*widget,JsonDictionary* options); + virtual void setPropsForListViewFromJsonDictionary(gui::UIWidget* widget, JsonDictionary* options); +}; + + } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp index a2a3ddcf42..10b482311a 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp @@ -26,7 +26,7 @@ bool UIScene::init() m_pUiLayer = UILayer::create(); addChild(m_pUiLayer); - m_pWidget = dynamic_cast(cocostudio::CCSGUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json")); + m_pWidget = dynamic_cast(cocostudio::GUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json")); m_pUiLayer->addWidget(m_pWidget); m_pSceneTitle = dynamic_cast(m_pUiLayer->getWidgetByName("UItest")); From df214acb6f062a5f5aa0e06605de89c6b71d157b Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 11 Nov 2013 18:42:39 +0800 Subject: [PATCH 543/557] [develop] Updating bindings-generator, fixing forward declare that generates binding glue codes which is an empty class. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 9797d44032..cad9d9ec4a 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 9797d4403207848f431d5b6456632cc966d84b0d +Subproject commit cad9d9ec4a24bdad1de383c941afa9418501161e From 3472d7ad50be0f61135949f06714f5bc4de9afde Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 11 Nov 2013 10:57:57 +0000 Subject: [PATCH 544/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 5788b25003..ce2f223cd3 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 5788b2500339473ecc19acf1c2e43656a2537a6d +Subproject commit ce2f223cd3b4bffbd564df37c738fc5b18f8d853 From d6446e9b14951fb49764a6fed7d31cb1213f74df Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 11 Nov 2013 16:07:46 -0800 Subject: [PATCH 545/557] calls `delete[]` instead of `delete` calls `delete[]` instead of `delete` --- cocos/2d/platform/ios/CCDevice.mm | 6 ++++-- cocos/physics/CCPhysicsShape.cpp | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index 4555b14df2..e8610db653 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -37,8 +37,10 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; - (id) init { - _acceleration = new cocos2d::Acceleration(); - _motionManager = [[CMMotionManager alloc] init]; + if( (self = [super init]) ) { + _acceleration = new cocos2d::Acceleration(); + _motionManager = [[CMMotionManager alloc] init]; + } return self; } diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index bb043b027a..91df06d1ea 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -539,7 +539,7 @@ bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMate cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset)); - CC_SAFE_DELETE(vecs); + CC_SAFE_DELETE_ARRAY(vecs); CC_BREAK_IF(shape == nullptr); @@ -563,7 +563,7 @@ float PhysicsShapePolygon::calculateArea(const Point* points, int count) cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); float area = PhysicsHelper::cpfloat2float(cpAreaForPoly(count, vecs)); - CC_SAFE_DELETE(vecs); + CC_SAFE_DELETE_ARRAY(vecs); return area; } @@ -574,7 +574,7 @@ float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int PhysicsHelper::points2cpvs(points, vecs, count); float moment = mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(mass, count, vecs, PhysicsHelper::point2cpv(offset))); - CC_SAFE_DELETE(vecs); + CC_SAFE_DELETE_ARRAY(vecs); return moment; } From a5eeff4f4fdaec575914470519174e6f89a6e382 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 11 Nov 2013 16:09:32 -0800 Subject: [PATCH 546/557] fixes for android create improves the message. fixes some grammar errors --- build/android-build.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index c630010ef8..4a65c9e6e2 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -15,11 +15,12 @@ ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES def usage(): - print "%prog [-n ndk-build-parameter] target\n\ - valid target are [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon\ -|crystalcraze|moonwarriors|testjavascript|watermelonwithme], of course you can use 'cpp'\ -to build all cpp samples, 'lua' to build all lua samples, 'jsb' to build all javascript samples,\ - and 'all' for all samples" + print """%s [-n ndk-build-parameter] 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.""" % sys.argv[0] def check_environment_variables(): ''' Checking the environment NDK_ROOT, which will be used for building From d7a0787336adbdade7f2bb1cd9b42e6eb84dead5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 12 Nov 2013 09:44:07 +0800 Subject: [PATCH 547/557] Up --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index d553c07d24..f8e3957968 100644 --- a/AUTHORS +++ b/AUTHORS @@ -642,6 +642,7 @@ Developers: ledyba Fixed a bug that EventListeners can't be removed sometimes. Fixed a bug that the data size has to be specified when parsing XML using TinyXML. + Closed X display after getting DPI on Linux. Luis Parravicini (luisparravicini) Fixed typos in create_project.py. From 412712c5e4737394b8f7a13452c7eec60d695f4b Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 12 Nov 2013 09:45:07 +0800 Subject: [PATCH 548/557] Update CHANGELOG[ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index e9e1da977c..e7632e9061 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -34,6 +34,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox. [Linux] [NEW] Used CMake to build linux projects. + [FIX] Closed X display after getting DPI on Linux. [Desktop] [FIX] Trigger onKeyReleased only after the key has been released. [Javascript binding] From 8c42e62a3fdd6fb53f8bf3a85331b8458b2cb528 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 12 Nov 2013 10:32:22 +0800 Subject: [PATCH 549/557] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index f8e3957968..e857757e3c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -650,6 +650,9 @@ Developers: xhcnb Device::setAccelerometerEnabled needs to be invoked before adding ACC listener. + bopohaa + Fixed a bug that Webp test crashes. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 0358eae8f03b9f5cf9b0dc0af9cbc0ce0b8e2b47 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 12 Nov 2013 10:33:18 +0800 Subject: [PATCH 550/557] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index e7632e9061..e06e8d0e37 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -20,6 +20,7 @@ cocos2d-x-3.0alpha1 @??? 2013 [NEW] Sprite: Override setScale(float scaleX, float scaleY) [NEW] External: added | operator for Control::EventType [NEW] Android & iOS screen size change support + [FIX] Webp Test Crashes. [Android] [FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes [FIX] Fixed application will crash when pause and resume. From db07c781abdbb672b93f79b2f29e3e92906d99c7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 12 Nov 2013 10:35:50 +0800 Subject: [PATCH 551/557] #include for std::max, std::min on VS2013. --- cocos/2d/CCTMXTiledMap.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 4205adb1fe..7ab6da363b 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -27,6 +27,7 @@ THE SOFTWARE. #include "CCTMXXMLParser.h" #include "CCTMXLayer.h" #include "CCSprite.h" +#include NS_CC_BEGIN From e2224d53160a7006136dcc66e014322a3d2019e9 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 12 Nov 2013 11:24:59 +0800 Subject: [PATCH 552/557] [ci skip] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 938f0c39fb..c5d464e62f 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,8 @@ $ cmake .. $ make ``` - You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, you should make it to direct to a correct one. - `install-deps-linux.sh` only has to be run onece. + You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target, + you should make it to direct to a correct one. `install-deps-linux.sh` only has to be run onece. * For Windows From e182328d5101b934ac2c227c7ac55b1c514b4ff2 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 12 Nov 2013 16:25:39 +0800 Subject: [PATCH 553/557] fix incomplete copy resource --- build/android-build.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index 4a65c9e6e2..7670e03dd2 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -109,6 +109,7 @@ def copy_files(src, dst): if os.path.isdir(path): new_dst = os.path.join(dst, item) os.mkdir(new_dst) + print new_dst copy_files(path, new_dst) def copy_resources(target, app_android_root): @@ -133,13 +134,26 @@ def copy_resources(target, app_android_root): resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android") if target == "crystalcraze": resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android") - if target == "moonwarriors": - resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res") if target == "testjavascript": resources_dir = os.path.join(app_android_root, "../../Shared/tests/") if target == "watermelonwithme": resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe") - copy_files(resources_dir, assets_dir) + if target != "moonwarriors": + copy_files(resources_dir, assets_dir) + else: + resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res") + dst_dir = os.path.join(assets_dir, "res") + os.mkdir(dst_dir) + copy_files(resources_dir, dst_dir) + resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/src") + dst_dir = os.path.join(assets_dir, "src") + os.mkdir(dst_dir) + copy_files(resources_dir, dst_dir) + resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors") + for item in os.listdir(resources_dir): + path = os.path.join(resources_dir, item) + if item.endswith('.js') and os.path.isfile(path): + shutil.copy(path, assets_dir) # AssetsManager test should also copy javascript files if target == "assetsmanager": From 18bc96096c389df1946db7652d0b86c8a47ecd09 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 12 Nov 2013 17:18:51 +0800 Subject: [PATCH 554/557] Resolve some warning and modify uint32_t to long --- cocos/scripting/lua/bindings/LuaBasicConversions.cpp | 2 +- cocos/scripting/lua/bindings/LuaBasicConversions.h | 2 +- tools/bindings-generator | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index 4c91daa42b..6fe9afcd00 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -32,7 +32,7 @@ extern "C" { } #endif -std::map g_luaType; +std::map g_luaType; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 2e2e525993..6861d1a056 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -10,7 +10,7 @@ extern "C" { using namespace cocos2d; -extern std::map g_luaType; +extern std::map g_luaType; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err); diff --git a/tools/bindings-generator b/tools/bindings-generator index 7ccbabbaa6..5f62d1fbcf 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 7ccbabbaa677607048c511b33cb6d83b2081220e +Subproject commit 5f62d1fbcf526dce6135e3829682b421bf794823 From cb51df7d65df708ccc63e9aec11b35a4bce8f4bb Mon Sep 17 00:00:00 2001 From: samuele3 Date: Tue, 12 Nov 2013 17:31:24 +0800 Subject: [PATCH 555/557] Update bindings-generator --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 5f62d1fbcf..2f3c19e01d 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 5f62d1fbcf526dce6135e3829682b421bf794823 +Subproject commit 2f3c19e01d5043485d0887ad69a3f02e312ad690 From 0acaa1f76e4c44477fcf88d52f18189ff9a75581 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 12 Nov 2013 09:50:13 +0000 Subject: [PATCH 556/557] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index ce2f223cd3..3fa10c3f8f 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit ce2f223cd3b4bffbd564df37c738fc5b18f8d853 +Subproject commit 3fa10c3f8f9fe083ef05cb401924d31740da9719 From d43bc3f75d92026f66c871bb47192daec9491676 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 12 Nov 2013 17:53:23 +0800 Subject: [PATCH 557/557] remove unnecessary print --- build/android-build.py | 1 - 1 file changed, 1 deletion(-) diff --git a/build/android-build.py b/build/android-build.py index 7670e03dd2..34ac6010d9 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -109,7 +109,6 @@ def copy_files(src, dst): if os.path.isdir(path): new_dst = os.path.join(dst, item) os.mkdir(new_dst) - print new_dst copy_files(path, new_dst) def copy_resources(target, app_android_root):